Programs & Examples On #Gigaspaces

How can I compile and run c# program without using visual studio?

If you have a project ready and just want to change some code and then build. Check out MSBuild which is located in the Microsoft.Net under windows directory.

C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild "C:\Projects\MyProject.csproj" /p:Configuration=Debug;DeployOnBuild=True;PackageAsSingleFile=False;outdir=C:\Projects\MyProjects\Publish\

(Please do not edit, leave as a single line)

... The line above broken up for readability

C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild "C:\Projects\MyProject.csproj"
/p:Configuration=Debug;DeployOnBuild=True;PackageAsSingleFile=False;
outdir=C:\Projects\MyProjects\Publish\

How to listen state changes in react.js?

I haven't used Angular, but reading the link above, it seems that you're trying to code for something that you don't need to handle. You make changes to state in your React component hierarchy (via this.setState()) and React will cause your component to be re-rendered (effectively 'listening' for changes). If you want to 'listen' from another component in your hierarchy then you have two options:

  1. Pass handlers down (via props) from a common parent and have them update the parent's state, causing the hierarchy below the parent to be re-rendered.
  2. Alternatively, to avoid an explosion of handlers cascading down the hierarchy, you should look at the flux pattern, which moves your state into data stores and allows components to watch them for changes. The Fluxxor plugin is very useful for managing this.

Oracle SQL - DATE greater than statement

you have to use the To_Date() function to convert the string to date ! http://www.techonthenet.com/oracle/functions/to_date.php

Exporting data In SQL Server as INSERT INTO

If you are running SQL Server 2008 R2 the built in options on to do this in SSMS as marc_s described above changed a bit. Instead of selecting Script data = true as shown in his diagram, there is now a new option called "Types of data to script" just above the "Table/View Options" grouping. Here you can select to script data only, schema and data or schema only. Works like a charm.

Removing unwanted table cell borders with CSS

add some css:

td, th {
   border:none;
}

Close popup window

An old tip...

var daddy = window.self;
daddy.opener = window.self;
daddy.close();

Microsoft.ACE.OLEDB.12.0 is not registered

I installed the "Microsoft Access Database Engine 2010 Redistributable" as mentioned above and got side-tracked troubleshooting bitness issues when it seemed to be a version issue.

Installing "2007 Office System Driver: Data Connectivity Components" sorted it for me.

https://www.microsoft.com/en-us/download/details.aspx?id=23734

MD5 hashing in Android

this is working perfectly for me, I used this to get MD5 on LIST Array(then convert it to JSON object), but if you only need to apply it on your data. type format, replace JsonObject with yours.

Especially if you have a mismatch with python MD5 implementation use this!

private static String md5(List<AccelerationSensor> sensor) {

    Gson gson= new Gson();
    byte[] JsonObject = new byte[0];
    try {
        JsonObject = gson.toJson(sensor).getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    MessageDigest m = null;

    try {
        m = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    byte[] thedigest = m.digest(JsonObject);
    String hash = String.format("%032x", new BigInteger(1, thedigest));
    return hash;


}

Why does javascript map function return undefined?

Since ES6 filter supports pointy arrow notation (like LINQ):

So it can be boiled down to following one-liner.

['a','b',1].filter(item => typeof item ==='string');

jQuery get the id/value of <li> element after click function

If you change your html code a bit - remove the ids

<ul id='myid'>  
<li>First</li>
<li>Second</li>
<li>Third</li>
<li>Fourth</li>
<li>Fifth</li>
</ul>

Then the jquery code you want is...

$("#myid li").click(function() {
    alert($(this).prevAll().length+1);
});?

You don't need to place any ids, just keep on adding li items.

Take a look at demo

Useful links

Parsing Query String in node.js

node -v v9.10.1

If you try to console log query object directly you will get error TypeError: Cannot convert object to primitive value

So I would suggest use JSON.stringify

const http = require('http');
const url = require('url');

const server = http.createServer((req, res) => {
    const parsedUrl = url.parse(req.url, true);

    const path = parsedUrl.pathname, query = parsedUrl.query;
    const method = req.method;

    res.end("hello world\n");

    console.log(`Request received on: ${path} + method: ${method} + query: 
    ${JSON.stringify(query)}`);
    console.log('query: ', query);
  });


  server.listen(3000, () => console.log("Server running at port 3000"));

So doing curl http://localhost:3000/foo\?fizz\=buzz will return Request received on: /foo + method: GET + query: {"fizz":"buzz"}

How to close TCP and UDP ports via windows command line

Use TCPView: http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx
or CurrPorts: https://www.nirsoft.net/utils/cports.html

Alternatively, if you don't want to use EXTERNAL SOFTWARE (these tools don't require an installation by the way), you can simply FIRST run the netstat command (preferably netstat -b ) & then setup Local Security Policy to block the IP address of the user's machine in question, that's what I have been doing with unwanted or even unknown connections - that allows you doing everything WITHOUT ANY EXTERNAL SOFTWARE (everything comes with Windows)...

How do I run two commands in one line in Windows CMD?

cmd /c ipconfig /all & Output.txt

This command execute command and open Output.txt file in a single command

What is sys.maxint in Python 3?

Python 3.0 doesn't have sys.maxint any more since Python 3's ints are of arbitrary length. Instead of sys.maxint it has sys.maxsize; the maximum size of a positive sized size_t aka Py_ssize_t.

How to print from Flask @app.route to python console

I tried running @Viraj Wadate's code, but couldn't get the output from app.logger.info on the console.

To get INFO, WARNING, and ERROR messages in the console, the dictConfig object can be used to create logging configuration for all logs (source):

from logging.config import dictConfig
from flask import Flask


dictConfig({
    'version': 1,
    'formatters': {'default': {
        'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
    }},
    'handlers': {'wsgi': {
        'class': 'logging.StreamHandler',
        'stream': 'ext://flask.logging.wsgi_errors_stream',
        'formatter': 'default'
    }},
    'root': {
        'level': 'INFO',
        'handlers': ['wsgi']
    }
})


app = Flask(__name__)

@app.route('/')
def index():
    return "Hello from Flask's test environment"

@app.route('/print')
def printMsg():
    app.logger.warning('testing warning log')
    app.logger.error('testing error log')
    app.logger.info('testing info log')
    return "Check your console"

if __name__ == '__main__':
    app.run(debug=True)

How can I open a Shell inside a Vim Window?

You may want to open a "screen" program, split screen, open shell on one and vim on another. Works for me.

MVC 5 Access Claims Identity User Data

You can also do this:

//Get the current claims principal
var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
var claims = identity.Claims;

Update

To provide further explanation as per comments.

If you are creating users within your system as follows:

UserManager<applicationuser> userManager = new UserManager<applicationuser>(new UserStore<applicationuser>(new SecurityContext()));
ClaimsIdentity identity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

You should automatically have some Claims populated relating to you Identity.

To add customized claims after a user authenticates you can do this as follows:

var user = userManager.Find(userName, password);
identity.AddClaim(new Claim(ClaimTypes.Email, user.Email));

The claims can be read back out as Darin has answered above or as I have.

The claims are persisted when you call below passing the identity in:

AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = persistCookie }, identity);

MySQL Delete all rows from table and reset ID to zero

An interesting fact.

I was sure TRUNCATE will always perform better, but in my case, for a database with approximately 30 tables with foreign keys, populated with only a few rows, it took about 12 seconds to TRUNCATE all tables, as opposed to only a few hundred milliseconds to DELETE the rows. Setting the auto increment adds about a second in total, but it's still a lot better.

So I would suggest try both, see which works faster for your case.

"continue" in cursor.forEach()

Making use of JavaScripts short-circuit evaluation. If el.shouldBeProcessed returns true, doSomeLengthyOperation

elementsCollection.forEach( el => 
  el.shouldBeProcessed && doSomeLengthyOperation()
);

How to change the current URL in javascript?

What you're doing is appending a "1" (the string) to your URL. If you want page 1.html link to page 2.html you need to take the 1 out of the string, add one to it, then reassemble the string.

Why not do something like this:

var url = 'http://mywebsite.com/1.html';
var pageNum = parseInt( url.split("/").pop(),10 );
var nextPage = 'http://mywebsite.com/'+(pageNum+1)+'.html';

nextPage will contain the url http://mywebsite.com/2.html in this case. Should be easy to put in a function if needed.

Simplest way to download and unzip files in Node.js cross-platform?

Another working example:

var zlib = require('zlib');
var tar = require('tar');
var ftp = require('ftp');

var files = [];

var conn = new ftp();
conn.on('connect', function(e) 
{
    conn.auth(function(e) 
    {
        if (e)
        {
            throw e;
        }
        conn.get('/tz/tzdata-latest.tar.gz', function(e, stream) 
        {
            stream.on('success', function() 
            {
                conn.end();

                console.log("Processing files ...");

                for (var name in files)
                {
                    var file = files[name];

                    console.log("filename: " + name);
                    console.log(file);
                }
                console.log("OK")
            });
            stream.on('error', function(e) 
            {
                console.log('ERROR during get(): ' + e);
                conn.end();
            });

            console.log("Reading ...");

            stream
            .pipe(zlib.createGunzip())
            .pipe(tar.Parse())
            .on("entry", function (e) 
            {    
                var filename = e.props["path"];
                console.log("filename:" + filename);
                if( files[filename] == null )
                {
                    files[filename] = "";
                }
                e.on("data", function (c) 
                {
                    files[filename] += c.toString();
                })    
            });
        });
    });
})
.connect(21, "ftp.iana.org");

How do I make a text input non-editable?

You can use readonly attribute, if you want your input only to be read. And you can use disabled attribute, if you want input to be shown, but totally disabled (even processing languages like PHP wont be able to read those).

Generating UML from C++ code?

I have used Rational Rose and Rational Rhapsody for reverse engineering large projects. I would prefer Rational Rhapsody for getting the UML class files for C++ !

How to check if a String contains any of some strings

Well, there's always this:

public static bool ContainsAny(this string haystack, params string[] needles)
{
    foreach (string needle in needles)
    {
        if (haystack.Contains(needle))
            return true;
    }

    return false;
}

Usage:

bool anyLuck = s.ContainsAny("a", "b", "c");

Nothing's going to match the performance of your chain of || comparisons, however.

Accessing private member variables from prototype-defined functions

There is a very simple way to do this

function SharedPrivate(){
  var private = "secret";
  this.constructor.prototype.getP = function(){return private}
  this.constructor.prototype.setP = function(v){ private = v;}
}

var o1 = new SharedPrivate();
var o2 = new SharedPrivate();

console.log(o1.getP()); // secret
console.log(o2.getP()); // secret
o1.setP("Pentax Full Frame K1 is on sale..!");
console.log(o1.getP()); // Pentax Full Frame K1 is on sale..!
console.log(o2.getP()); // Pentax Full Frame K1 is on sale..!
o2.setP("And it's only for $1,795._");
console.log(o1.getP()); // And it's only for $1,795._

JavaScript prototypes are golden.

How do I create and access the global variables in Groovy?

Like all OO languages, Groovy has no concept of "global" by itself (unlike, say, BASIC, Python or Perl).

If you have several methods that need to share the same variable, use a field:

class Foo {
    def a;

    def foo() {
        a = 1;
    }
    def bar() {
        print a;
    }
}

Where to find Java JDK Source Code?

Chances that you already got the source code with the JDK, it is matter of finding where it is. In case, JDK folder doesn't contain the source code:

sudo apt-get install openjdk-7-source

OSX Folks, search in homebrew formulas.

In ubuntu, the command above would put your souce file under: /usr/lib/jvm/openjdk-7/

Good news is that Eclipse will take you there already (How to bind Eclipse to the Java source code):

Follow the orange buttons

enter image description here enter image description here enter image description here

Remove ALL styling/formatting from hyperlinks

As Chris said before me, just an a should override. For example:

a { color:red; }
a:hover { color:blue; }
.nav a { color:green; }

In this instance the .nav a would ALWAYS be green, the :hover wouldn't apply to it.

If there's some other rule affecting it, you COULD use !important, but you shouldn't. It's a bad habit to fall into.

.nav a { color:green !important; } /*I'm a bad person and shouldn't use !important */

Then it'll always be green, irrelevant of any other rule.

Illegal pattern character 'T' when parsing a date string to java.util.Date

Update for Java 8 and higher

You can now simply do Instant.parse("2015-04-28T14:23:38.521Z") and get the correct thing now, especially since you should be using Instant instead of the broken java.util.Date with the most recent versions of Java.

You should be using DateTimeFormatter instead of SimpleDateFormatter as well.

Original Answer:

The explanation below is still valid as as what the format represents. But it was written before Java 8 was ubiquitous so it uses the old classes that you should not be using if you are using Java 8 or higher.

This works with the input with the trailing Z as demonstrated:

In the pattern the T is escaped with ' on either side.

The pattern for the Z at the end is actually XXX as documented in the JavaDoc for SimpleDateFormat, it is just not very clear on actually how to use it since Z is the marker for the old TimeZone information as well.

Q2597083.java

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class Q2597083
{
    /**
     * All Dates are normalized to UTC, it is up the client code to convert to the appropriate TimeZone.
     */
    public static final TimeZone UTC;

    /**
     * @see <a href="http://en.wikipedia.org/wiki/ISO_8601#Combined_date_and_time_representations">Combined Date and Time Representations</a>
     */
    public static final String ISO_8601_24H_FULL_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";

    /**
     * 0001-01-01T00:00:00.000Z
     */
    public static final Date BEGINNING_OF_TIME;

    /**
     * 292278994-08-17T07:12:55.807Z
     */
    public static final Date END_OF_TIME;

    static
    {
        UTC = TimeZone.getTimeZone("UTC");
        TimeZone.setDefault(UTC);
        final Calendar c = new GregorianCalendar(UTC);
        c.set(1, 0, 1, 0, 0, 0);
        c.set(Calendar.MILLISECOND, 0);
        BEGINNING_OF_TIME = c.getTime();
        c.setTime(new Date(Long.MAX_VALUE));
        END_OF_TIME = c.getTime();
    }

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

        final SimpleDateFormat sdf = new SimpleDateFormat(ISO_8601_24H_FULL_FORMAT);
        sdf.setTimeZone(UTC);
        System.out.println("sdf.format(BEGINNING_OF_TIME) = " + sdf.format(BEGINNING_OF_TIME));
        System.out.println("sdf.format(END_OF_TIME) = " + sdf.format(END_OF_TIME));
        System.out.println("sdf.format(new Date()) = " + sdf.format(new Date()));
        System.out.println("sdf.parse(\"2015-04-28T14:23:38.521Z\") = " + sdf.parse("2015-04-28T14:23:38.521Z"));
        System.out.println("sdf.parse(\"0001-01-01T00:00:00.000Z\") = " + sdf.parse("0001-01-01T00:00:00.000Z"));
        System.out.println("sdf.parse(\"292278994-08-17T07:12:55.807Z\") = " + sdf.parse("292278994-08-17T07:12:55.807Z"));
    }
}

Produces the following output:

sdf.format(BEGINNING_OF_TIME) = 0001-01-01T00:00:00.000Z
sdf.format(END_OF_TIME) = 292278994-08-17T07:12:55.807Z
sdf.format(new Date()) = 2015-04-28T14:38:25.956Z
sdf.parse("2015-04-28T14:23:38.521Z") = Tue Apr 28 14:23:38 UTC 2015
sdf.parse("0001-01-01T00:00:00.000Z") = Sat Jan 01 00:00:00 UTC 1
sdf.parse("292278994-08-17T07:12:55.807Z") = Sun Aug 17 07:12:55 UTC 292278994

Can I bind an array to an IN() condition?

I extended PDO to do something similar to what stefs suggests, and it was easier for me in the long run:

class Array_Capable_PDO extends PDO {
    /**
     * Both prepare a statement and bind array values to it
     * @param string $statement mysql query with colon-prefixed tokens
     * @param array $arrays associatve array with string tokens as keys and integer-indexed data arrays as values 
     * @param array $driver_options see php documention
     * @return PDOStatement with given array values already bound 
     */
    public function prepare_with_arrays($statement, array $arrays, $driver_options = array()) {

        $replace_strings = array();
        $x = 0;
        foreach($arrays as $token => $data) {
            // just for testing...
            //// tokens should be legit
            //assert('is_string($token)');
            //assert('$token !== ""');
            //// a given token shouldn't appear more than once in the query
            //assert('substr_count($statement, $token) === 1');
            //// there should be an array of values for each token
            //assert('is_array($data)');
            //// empty data arrays aren't okay, they're a SQL syntax error
            //assert('count($data) > 0');

            // replace array tokens with a list of value tokens
            $replace_string_pieces = array();
            foreach($data as $y => $value) {
                //// the data arrays have to be integer-indexed
                //assert('is_int($y)');
                $replace_string_pieces[] = ":{$x}_{$y}";
            }
            $replace_strings[] = '('.implode(', ', $replace_string_pieces).')';
            $x++;
        }
        $statement = str_replace(array_keys($arrays), $replace_strings, $statement);
        $prepared_statement = $this->prepare($statement, $driver_options);

        // bind values to the value tokens
        $x = 0;
        foreach($arrays as $token => $data) {
            foreach($data as $y => $value) {
                $prepared_statement->bindValue(":{$x}_{$y}", $value);
            }
            $x++;
        }

        return $prepared_statement;
    }
}

You can use it like this:

$db_link = new Array_Capable_PDO($dsn, $username, $password);

$query = '
    SELECT     *
    FROM       test
    WHERE      field1 IN :array1
     OR        field2 IN :array2
     OR        field3 = :value
';

$pdo_query = $db_link->prepare_with_arrays(
    $query,
    array(
        ':array1' => array(1,2,3),
        ':array2' => array(7,8,9)
    )
);

$pdo_query->bindValue(':value', '10');

$pdo_query->execute();

How to change ViewPager's page?

Without checking your code, I think what you are describing is that your pages are out of sync and you have stale data.

You say you are changing the number of pages, then crashing because you are accessing the old set of pages. This sounds to me like you are not calling pageAdapter.notifyDataSetChanged() after changing your data.

When your viewPager is showing page 3 of a set of 10 pages, and you change to a set with only 5, then call notifyDataSetChanged(), what you'll find is you are now viewing page 3 of the new set. If you were previously viewing page 8 of the old set, after putting in the new set and calling notifyDataSetChanged() you will find you are now viewing the last page of the new set without crashing.

If you simply change your current page, you may just be masking the problem.

Scala list concatenation, ::: vs ++

Always use :::. There are two reasons: efficiency and type safety.

Efficiency

x ::: y ::: z is faster than x ++ y ++ z, because ::: is right associative. x ::: y ::: z is parsed as x ::: (y ::: z), which is algorithmically faster than (x ::: y) ::: z (the latter requires O(|x|) more steps).

Type safety

With ::: you can only concatenate two Lists. With ++ you can append any collection to List, which is terrible:

scala> List(1, 2, 3) ++ "ab"
res0: List[AnyVal] = List(1, 2, 3, a, b)

++ is also easy to mix up with +:

scala> List(1, 2, 3) + "ab"
res1: String = List(1, 2, 3)ab

REST API 404: Bad URI, or Missing Resource?

So in essence, it sounds like the answer could depend on how the request is formed.

If the requested resource forms part of the URI as per a request to http://mywebsite/restapi/user/13 and user 13 does not exist, then a 404 is probably appropriate and intuitive because the URI is representative of a non-existent user/entity/document/etc. The same would hold for the more secure technique using a GUID http://mywebsite/api/user/3dd5b770-79ea-11e1-b0c4-0800200c9a66 and the api/restapi argument above.

However, if the requested resource ID was included in the request header [include your own example], or indeed, in the URI as a parameter, eg http://mywebsite/restapi/user/?UID=13 then the URI would still be correct (because the concept of a USER does exits at http://mywebsite/restapi/user/); and therefore the response could reasonable be expected to be a 200 (with an appropriately verbose message) because the specific user known as 13 does not exist but the URI does. This way we are saying the URI is good, but the request for data has no content.

Personally a 200 still doesn't feel right (though I have previously argued it does). A 200 response code (without a verbose response) could cause an issue not to be investigated when an incorrect ID is sent for example.

A better approach would be to send a 204 - No Contentresponse. This is compliant with w3c's description *The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation.*1 The confusion, in my opinion is caused by the Wikipedia entry stating 204 No Content - The server successfully processed the request, but is not returning any content. Usually used as a response to a successful delete request. The last sentence is highly debateable. Consider the situation without that sentence and the solution is easy - just send a 204 if the entity does not exist. There is even an argument for returning a 204 instead of a 404, the request has been processed and no content has been returned! Please be aware though, 204's do not allow content in the response body

Sources

http://en.wikipedia.org/wiki/List_of_HTTP_status_codes 1. http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

How to iterate over a std::map full of strings in C++

Your main problem is that you are calling a method called first() in the iterator. What you are meant to do is use the property called first:

...append(iter->first) rather than ...append(iter->first())

As a matter of style, you shouldn't be using new to create that string.

std::string something::toString() 
{
        std::map<std::string, std::string>::iterator iter;
        std::string strToReturn; //This is no longer on the heap

        for (iter = table.begin(); iter != table.end(); ++iter) {
           strToReturn.append(iter->first); //Not a method call
           strToReturn.append("=");
           strToReturn.append(iter->second);
           //....
           // Make sure you don't modify table here or the iterators will not work as you expect
        }
        //...
        return strToReturn;
}

edit: facildelembrar pointed out (in the comments) that in modern C++ you can now rewrite the loop

for (auto& item: table) {
    ...
}

node.js Error: connect ECONNREFUSED; response from server

I got this error because my AdonisJS server was not running before I ran the test. Running the server first fixed it.

Focus Next Element In Tab Index

There is the tabindex property that can be set on component. It specifies in which order the input components should be iterated when selecting one and pressing tab. Values above 0 are reserved for custom navigation, 0 is "in natural order" (so would behave differently if set for the first element), -1 means not keyboard focusable:

<!-- navigate with tab key: -->
<input tabindex="1" type="text"/>
<input tabindex="2" type="text"/>

It can also be set for something else than the text input fields but it is not very obvious what it would do there, if anything at all. Even if the navigation works, maybe better to use "natural order" for anything else than the very obvious user input elements.

No, you do not need JQuery or any scripting at all to support this custom path of navigation. You can implement it on the server side without any JavaScript support. From the other side, the property also works fine in React framework but does not require it.

Can I get JSON to load into an OrderedDict?

Yes, you can. By specifying the object_pairs_hook argument to JSONDecoder. In fact, this is the exact example given in the documentation.

>>> json.JSONDecoder(object_pairs_hook=collections.OrderedDict).decode('{"foo":1, "bar": 2}')
OrderedDict([('foo', 1), ('bar', 2)])
>>> 

You can pass this parameter to json.loads (if you don't need a Decoder instance for other purposes) like so:

>>> import json
>>> from collections import OrderedDict
>>> data = json.loads('{"foo":1, "bar": 2}', object_pairs_hook=OrderedDict)
>>> print json.dumps(data, indent=4)
{
    "foo": 1,
    "bar": 2
}
>>> 

Using json.load is done in the same way:

>>> data = json.load(open('config.json'), object_pairs_hook=OrderedDict)

How to get english language word database?

You may check *spell en-GB dictionary used by Mozilla, OpenOffice, plenty of other software.

Write to CSV file and export it?

How to write to a file (easy search in Google) ... 1st Search Result

As far as creation of the file each time a user accesses the page ... each access will act on it's own behalf. You business case will dictate the behavior.

Case 1 - same file but does not change (this type of case can have multiple ways of being defined)

  • You would have logic that created the file when needed and only access the file if generation is not needed.

Case 2 - each user needs to generate their own file

  • You would decide how you identify each user, create a file for each user and access the file they are supposed to see ... this can easily merge with Case 1. Then you delete the file after serving the content or not if it requires persistence.

Case 3 - same file but generation required for each access

  • Use Case 2, this will cause a generation each time but clean up once accessed.

SQL comment header examples

Here is my preferred variant:

/* =====================================================================
DESC:   Some notes about what this does
           tabbed in if you need additional lines
NOTES:  Additional notes
           tabbed in if you need additional lines
======================================================================== */

How do I clone a single branch in Git?

A little late but I wanted to add the solution I used to solve this problem. I found the solution here.

Anyway, the question seems to be asking 'how to start a new project from a branch of another repo?'

To this, the solution I used would be to first create a new repo in github or where ever. This will serve as the repo to your new project.

On your local machine, navigate to the project that has the branch you want to use as the template for your new project.

Run the command:

git push https://github.com/accountname/new-repo.git +old_branch:master

What this will do is push the old_branch to new-repo and make it the master branch of the new repo.

You then just have to clone the new repo down to your new project's local directory and you have a new project started at the old branch.

ORA-00918: column ambiguously defined in SELECT *

You have multiple columns named the same thing in your inner query, so the error is raised in the outer query. If you get rid of the outer query, it should run, although still be confusing:

SELECT DISTINCT
    coaches.id,
    people.*,
    users.*,
    coaches.*
FROM "COACHES"
    INNER JOIN people ON people.id = coaches.person_id
    INNER JOIN users ON coaches.person_id = users.person_id
    LEFT OUTER JOIN organizations_users ON organizations_users.user_id = users.id
WHERE
    rownum <= 25

It would be much better (for readability and performance both) to specify exactly what fields you need from each of the tables instead of selecting them all anyways. Then if you really need two fields called the same thing from different tables, use column aliases to differentiate between them.

Java RegEx meta character (.) and ordinary dot?

Solutions proposed by the other members don't work for me.

But I found this :

to escape a dot in java regexp write [.]

google map API zoom range

Available Zoom Levels

Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.

Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.

As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:

  • Road maps - seem to go up to zoom level 22 everywhere
  • Hybrid and satellite maps - the max available zoom levels depend on location. Here are some examples:
  • Remote regions of Antarctica: 13
  • Gobi Desert: 17
  • Much of the U.S. and Europe: 21
  • "Deep zoom" locations: 22-23 (see bkaid's link)

Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.

Map Scale at Various Zoom Levels

Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:

meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)

Formula is from Chris Broadfoot's comment.


Google Maps basics

Zoom Level - zoom

0 - 19

0 lowest zoom (whole world)

19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()


What you're looking for are the scales for each zoom level. Use these:

20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9  : 2311162.307000
8  : 4622324.614000
7  : 9244649.227000
6  : 18489298.450000
5  : 36978596.910000
4  : 73957193.820000
3  : 147914387.600000
2  : 295828775.300000
1  : 591657550.500000

Could not find any resources appropriate for the specified culture or the neutral culture

I resolved this by going to the project where my resources file was saved, scrolling down to its ItemGroup and adding a logical name that corresponded to the path the compiler expected.

My EmbeddedResource looked like this:

   <ItemGroup>
    <EmbeddedResource Update="Properties\TextResources.resx">
      <Generator>PublicResXFileCodeGenerator</Generator>
      <LastGenOutput>TextResources.Designer.cs</LastGenOutput>
    </EmbeddedResource>
  </ItemGroup>

Now it looks like this

  <ItemGroup>
    <EmbeddedResource Update="Properties\TextResources.resx">
      <Generator>PublicResXFileCodeGenerator</Generator>
      <LastGenOutput>TextResources.Designer.cs</LastGenOutput>
      <LogicalName>MyProject.Properties.Resources.resources</LogicalName>
    </EmbeddedResource>
  </ItemGroup>

Boto3 Error: botocore.exceptions.NoCredentialsError: Unable to locate credentials

try specifying keys manually

    s3 = boto3.resource('s3',
         aws_access_key_id=ACCESS_ID,
         aws_secret_access_key= ACCESS_KEY)

Make sure you don't include your ACCESS_ID and ACCESS_KEY in the code directly for security concerns. Consider using environment configs and injecting them in the code as suggested by @Tiger_Mike.

For Prod environments consider using rotating access keys: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html#Using_RotateAccessKey

Java decimal formatting using String.format?

You want java.text.DecimalFormat.

DecimalFormat df = new DecimalFormat("0.00##");
String result = df.format(34.4959);

How to change Java version used by TOMCAT?

On Linux, Tomcat7 has a configuration file located at:

/etc/sysconfig/tomcat7

... which is where server specific configurations should be made. You can set the JAVA_HOME env variable here w/o needing to create a profile.d/ script.

This worked for me.

Angular 6 Material mat-select change method removed

The changed it from change to selectionChange.

<mat-select (change)="doSomething($event)">

is now

<mat-select (selectionChange)="doSomething($event)">

https://material.angular.io/components/select/api

How to 'restart' an android application programmatically

Checkout intent properties like no history , clear back stack etc ... Intent.setFlags

Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);

Download single files from GitHub

You can use curl this way:

curl -OL https://raw.githubusercontent.com/<username>/<repo-name>/<branch-name>/path/to/file

O means that curl downloads the content
L means that curl follows the redirection

How to check whether a string contains a substring in JavaScript?

ECMAScript 6 introduced String.prototype.includes:

_x000D_
_x000D_
const string = "foo";_x000D_
const substring = "oo";_x000D_
_x000D_
console.log(string.includes(substring));
_x000D_
_x000D_
_x000D_

includes doesn’t have Internet Explorer support, though. In ECMAScript 5 or older environments, use String.prototype.indexOf, which returns -1 when a substring cannot be found:

_x000D_
_x000D_
var string = "foo";_x000D_
var substring = "oo";_x000D_
_x000D_
console.log(string.indexOf(substring) !== -1);
_x000D_
_x000D_
_x000D_

What is the { get; set; } syntax in C#?

This is the short way of doing this:

public class Genre
{
    private string _name;

    public string Name
    {
      get => _name;
      set => _name = value;
    }
}

Difference between dates in JavaScript

    // This is for first date
    first = new Date(2010, 03, 08, 15, 30, 10); // Get the first date epoch object
    document.write((first.getTime())/1000); // get the actual epoch values
    second = new Date(2012, 03, 08, 15, 30, 10); // Get the first date epoch object
    document.write((second.getTime())/1000); // get the actual epoch values
    diff= second - first ;
    one_day_epoch = 24*60*60 ;  // calculating one epoch
    if ( diff/ one_day_epoch > 365 ) // check , is it exceei
    {
    alert( 'date is exceeding one year');
    }

How do I clear inner HTML

The h1 tags unfortunately do not receive the onmouseout events.

The simple Javascript snippet below will work for all elements and uses only 1 mouse event.

Note: "The borders in the snippet are applied to provide a visual demarcation of the elements."

_x000D_
_x000D_
document.body.onmousemove = function(){ move("The dog is in its shed"); };_x000D_
_x000D_
document.body.style.border = "2px solid red";_x000D_
document.getElementById("h1Tag").style.border = "2px solid blue";_x000D_
_x000D_
function move(what) {_x000D_
    if(event.target.id == "h1Tag"){ document.getElementById("goy").innerHTML = "what"; } else { document.getElementById("goy").innerHTML = ""; }_x000D_
}
_x000D_
<h1 id="h1Tag">lalala</h1>_x000D_
<div id="goy"></div>
_x000D_
_x000D_
_x000D_

This can also be done in pure CSS by adding the hover selector css property to the h1 tag.

What is the most robust way to force a UIView to redraw?

I had the same problem, and all the solutions from SO or Google didn't work for me. Usually, setNeedsDisplay does work, but when it doesn't...
I've tried calling setNeedsDisplay of the view just every possible way from every possible threads and stuff - still no success. We know, as Rob said, that

"this needs to be drawn in the next draw cycle."

But for some reason it wouldn't draw this time. And the only solution I've found is calling it manually after some time, to let anything that blocks the draw pass away, like this:

dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 
                                        (int64_t)(0.005 * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {
    [viewToRefresh setNeedsDisplay];
});

It's a good solution if you don't need the view to redraw really often. Otherwise, if you're doing some moving (action) stuff, there is usually no problems with just calling setNeedsDisplay.

I hope it will help someone who is lost there, like I was.

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's an old discussion thread where I listed the main differences and the conditions in which you should use each of these methods. I think you may find it useful to go through the discussion.

To explain the differences as relevant to your posted example:

a. When you use RegisterStartupScript, it will render your script after all the elements in the page (right before the form's end tag). This enables the script to call or reference page elements without the possibility of it not finding them in the Page's DOM.

Here is the rendered source of the page when you invoke the RegisterStartupScript method:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
        <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        </div>
        <div> <span id="lblDisplayDate">Label</span>
            <br />
            <input type="submit" name="btnPostback" value="Register Startup Script" id="btnPostback" />
            <br />
            <input type="submit" name="btnPostBack2" value="Register" id="btnPostBack2" />
        </div>
        <div>
            <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="someViewstategibberish" />
        </div>
        <!-- Note this part -->
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            lbl.style.color = 'red';
        </script>
    </form>
    <!-- Note this part -->
</body>
</html>

b. When you use RegisterClientScriptBlock, the script is rendered right after the Viewstate tag, but before any of the page elements. Since this is a direct script (not a function that can be called, it will immediately be executed by the browser. But the browser does not find the label in the Page's DOM at this stage and hence you should receive an "Object not found" error.

Here is the rendered source of the page when you invoke the RegisterClientScriptBlock method:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
        <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        </div>
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            // Error is thrown in the next line because lbl is null.
            lbl.style.color = 'green';

Therefore, to summarize, you should call the latter method if you intend to render a function definition. You can then render the call to that function using the former method (or add a client side attribute).

Edit after comments:


For instance, the following function would work:

protected void btnPostBack2_Click(object sender, EventArgs e) 
{ 
  System.Text.StringBuilder sb = new System.Text.StringBuilder(); 
  sb.Append("<script language='javascript'>function ChangeColor() {"); 
  sb.Append("var lbl = document.getElementById('lblDisplayDate');"); 
  sb.Append("lbl.style.color='green';"); 
  sb.Append("}</script>"); 

  //Render the function definition. 
  if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock")) 
  {
    ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock", sb.ToString()); 
  }

  //Render the function invocation. 
  string funcCall = "<script language='javascript'>ChangeColor();</script>"; 

  if (!ClientScript.IsStartupScriptRegistered("JSScript"))
  { 
    ClientScript.RegisterStartupScript(this.GetType(), "JSScript", funcCall); 
  } 
} 

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

Remove servlet.jar from source web-inf/lib folder as it is available in tomcat lib folder then it works fine

How can I test a change made to Jenkinsfile locally?

Put your SSH key into your Jenkins profile, then use the declarative linter as follows:

ssh jenkins.hostname.here declarative-linter < Jenkinsfile

This will do a static analysis on your Jenkinsfile. In the editor of your choice, define a keyboard shortcut that runs that command automatically. In Visual Studio Code, which is what I use, go to Tasks > Configure Tasks, then use the following JSON to create a Validate Jenkinsfile command:

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "Validate Jenkinsfile",
      "type": "shell",
      "command": "ssh jenkins.hostname declarative-linter < ${file}"
    }
  ]
}

Uncaught ReferenceError: angular is not defined - AngularJS not working

You need to move your angular app code below the inclusion of the angular libraries. At the time your angular code runs, angular does not exist yet. This is an error (see your dev tools console).

In this line:

var app = angular.module(`

you are attempting to access a variable called angular. Consider what causes that variable to exist. That is found in the angular.js script which must then be included first.

  <h1>{{2+3}}</h1>

  <!-- In production use:
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
  -->
  <script src="lib/angular/angular.js"></script>
  <script src="lib/angular/angular-route.js"></script>
  <script src="js/app.js"></script>
  <script src="js/services.js"></script>
  <script src="js/controllers.js"></script>
  <script src="js/filters.js"></script>
  <script src="js/directives.js"></script>

      <script>
        var app = angular.module('myApp',[]);

        app.directive('myDirective',function(){

            return function(scope, element,attrs) {
                element.bind('click',function() {alert('click')});
            };

        });
    </script>

For completeness, it is true that your directive is similar to the already existing directive ng-click, but I believe the point of this exercise is just to practice writing simple directives, so that makes sense.

Checking if an input field is required using jQuery

$('form#register input[required]')

It will only return inputs which have required attribute.

Automatic Preferred Max Layout Width is not available on iOS versions prior to 8.0

Solution it's quite simple

Just enable Builds for iOS 8 and Later

enter image description here

Convert Json string to Json object in Swift 4

Using JSONSerialization always felt unSwifty and unwieldy, but it is even more so with the arrival of Codable in Swift 4. If you wield a [String:Any] in front of a simple struct it will ... hurt. Check out this in a Playground:

import Cocoa

let data = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]".data(using: .utf8)!

struct Form: Codable {
    let id: Int
    let name: String
    let description: String?

    private enum CodingKeys: String, CodingKey {
        case id = "form_id"
        case name = "form_name"
        case description = "form_desc"
    }
}

do {
    let f = try JSONDecoder().decode([Form].self, from: data)
    print(f)
    print(f[0])
} catch {
    print(error)
}

With minimal effort handling this will feel a whole lot more comfortable. And you are given a lot more information if your JSON does not parse properly.

Getting last day of the month in a given string date

I use this one-liner on my JasperServer Reports:

new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyy-MM-dd").parse(new java.util.Date().format('yyyy') + "-" + (new Integer (new SimpleDateFormat("MM").format(new Date()))+1) + "-01")-1)

Doesn't look nice but works for me. Basically it's adding 1 to the current month, get the first day of that month and subtract one day.

Homebrew: Could not symlink, /usr/local/bin is not writable

If you already have a directory in /usr/local for the package you're installing, you can try deleting this directory.

In my case I had previously installed the package I was trying to install without using brew, and had then uninstalled it. There was a directory /usr/local/<my_package>/ left over from that previous install. I deleted this folder (sudo rm -rf /usr/local/<my_package>/) and after that the brew link step was successful.

Divide a number by 3 without using *, /, +, -, % operators

First:

x/3 = (x/4) / (1-1/4)

Then figure out how to solve x/(1 - y):

x/(1-1/y)
  = x * (1+y) / (1-y^2)
  = x * (1+y) * (1+y^2) / (1-y^4)
  = ...
  = x * (1+y) * (1+y^2) * (1+y^4) * ... * (1+y^(2^i)) / (1-y^(2^(i+i))
  = x * (1+y) * (1+y^2) * (1+y^4) * ... * (1+y^(2^i))

with y = 1/4:

int div3(int x) {
    x <<= 6;    // need more precise
    x += x>>2;  // x = x * (1+(1/2)^2)
    x += x>>4;  // x = x * (1+(1/2)^4)
    x += x>>8;  // x = x * (1+(1/2)^8)
    x += x>>16; // x = x * (1+(1/2)^16)
    return (x+1)>>8; // as (1-(1/2)^32) very near 1,
                     // we plus 1 instead of div (1-(1/2)^32)
}

Although it uses +, but somebody already implements add by bitwise op.

How to configure XAMPP to send mail from localhost?

in addition to all answers please note that in sendmail.ini file:

auth_password=this-is-Not-your-Gmail-password

due to new google security concern, you should follow these steps to make an application password for this purpose:

  1. go to https://accounts.google.com/ in security tab
  2. turn two-step-verification on
  3. go back to the security tab and make an App-password (in select-app drop-down menu you can choose 'other')

List of IP addresses/hostnames from local network in Python

One of the answers in this question might help you. There seems to be a platform agnostic version for python, but I haven't tried it yet.

What's the difference between 'git merge' and 'git rebase'?

I really love this excerpt from 10 Things I hate about git (it gives a short explanation for rebase in its second example):

3. Crappy documentation

The man pages are one almighty “f*** you”1. They describe the commands from the perspective of a computer scientist, not a user. Case in point:

git-push – Update remote refs along with associated objects

Here’s a description for humans:

git-push – Upload changes from your local repository into a remote repository

Update, another example: (thanks cgd)

git-rebase – Forward-port local commits to the updated upstream head

Translation:

git-rebase – Sequentially regenerate a series of commits so they can be 
             applied directly to the head node

And then we have

git-merge - Join two or more development histories together

which is a good description.


1. uncensored in the original

CSS3 opacity gradient?

Except using css mask answered by @vals, you can also use transparency gradient background and set background-clip to text.

Create proper gradient:

background: linear-gradient(to bottom, rgba(0, 0, 0, 1) 0%, rgba(0, 0, 0, 0) 100%);

Then clip the backgroud with text:

background-clip: text;
color: transparent;

Demo

https://jsfiddle.net/simonmysun/2h61Ljbn/4/

Tested under Chrome 75 under Windows 10.

Supported platforms:

Declare a variable as Decimal

You can't declare a variable as Decimal - you have to use Variant (you can use CDec to populate it with a Decimal type though).

jquery append external html file into my page

You can use jquery's load function here.

$("#your_element_id").load("file_name.html");

If you need more info, here is the link.

Javascript replace all "%20" with a space

The percentage % sign followed by two hexadecimal numbers (UTF-8 character representation) typically denotes a string which has been encoded to be part of a URI. This ensures that characters that would otherwise have special meaning don't interfere. In your case %20 is immediately recognisable as a whitespace character - while not really having any meaning in a URI it is encoded in order to avoid breaking the string into multiple "parts".

Don't get me wrong, regex is the bomb! However any web technology worth caring about will already have tools available in it's library to handle standards like this for you. Why re-invent the wheel...?

var str = 'xPasswords%20do%20not%20match';
console.log( decodeURI(str) ); // "xPasswords do not match"

Javascript has both decodeURI and decodeURIComponent which differ slightly in respect to their encodeURI and encodeURIComponent counterparts - you should familiarise yourself with the documentation.

Batch - Echo or Variable Not Working

Try the following (note that there should not be a space between the VAR, =, and GREG).

SET VAR=GREG
ECHO %VAR%
PAUSE

Dynamically creating keys in a JavaScript associative array

Somehow all examples, while work well, are overcomplicated:

  • They use new Array(), which is an overkill (and an overhead) for a simple associative array (AKA dictionary).
  • The better ones use new Object(). It works fine, but why all this extra typing?

This question is tagged "beginner", so let's make it simple.

The über-simple way to use a dictionary in JavaScript or "Why doesn't JavaScript have a special dictionary object?":

// Create an empty associative array (in JavaScript it is called ... Object)
var dict = {};   // Huh? {} is a shortcut for "new Object()"

// Add a key named fred with value 42
dict.fred = 42;  // We can do that because "fred" is a constant
                 // and conforms to id rules

// Add a key named 2bob2 with value "twins!"
dict["2bob2"] = "twins!";  // We use the subscript notation because
                           // the key is arbitrary (not id)

// Add an arbitrary dynamic key with a dynamic value
var key = ..., // Insanely complex calculations for the key
    val = ...; // Insanely complex calculations for the value
dict[key] = val;

// Read value of "fred"
val = dict.fred;

// Read value of 2bob2
val = dict["2bob2"];

// Read value of our cool secret key
val = dict[key];

Now let's change values:

// Change the value of fred
dict.fred = "astra";
// The assignment creates and/or replaces key-value pairs

// Change the value of 2bob2
dict["2bob2"] = [1, 2, 3];  // Any legal value can be used

// Change value of our secret key
dict[key] = undefined;
// Contrary to popular beliefs, assigning "undefined" does not remove the key

// Go over all keys and values in our dictionary
for (key in dict) {
  // A for-in loop goes over all properties, including inherited properties
  // Let's use only our own properties
  if (dict.hasOwnProperty(key)) {
    console.log("key = " + key + ", value = " + dict[key]);
  }
}

Deleting values is easy too:

// Let's delete fred
delete dict.fred;
// fred is removed, but the rest is still intact

// Let's delete 2bob2
delete dict["2bob2"];

// Let's delete our secret key
delete dict[key];

// Now dict is empty

// Let's replace it, recreating all original data
dict = {
  fred:    42,
  "2bob2": "twins!"
  // We can't add the original secret key because it was dynamic, but
  // we can only add static keys
  // ...
  // oh well
  temp1:   val
};
// Let's rename temp1 into our secret key:
if (key != "temp1") {
  dict[key] = dict.temp1; // Copy the value
  delete dict.temp1;      // Kill the old key
} else {
  // Do nothing; we are good ;-)
}

Difference between readFile() and readFileSync()

readFileSync() is synchronous and blocks execution until finished. These return their results as return values. readFile() are asynchronous and return immediately while they function in the background. You pass a callback function which gets called when they finish. let's take an example for non-blocking.

following method read a file as a non-blocking way

var fs = require('fs');
fs.readFile(filename, "utf8", function(err, data) {
        if (err) throw err;
        console.log(data);
});

following is read a file as blocking or synchronous way.

var data = fs.readFileSync(filename);

LOL...If you don't want readFileSync() as blocking way then take reference from the following code. (Native)

var fs = require('fs');
function readFileAsSync(){
    new Promise((resolve, reject)=>{
        fs.readFile(filename, "utf8", function(err, data) {
                if (err) throw err;
                resolve(data);
        });
    });
}

async function callRead(){
    let data = await readFileAsSync();
    console.log(data);
}

callRead();

it's mean behind scenes readFileSync() work same as above(promise) base.

Sending and Parsing JSON Objects in Android

you just need to import this

   import org.json.JSONObject;


  constructing the String that you want to send

 JSONObject param=new JSONObject();
 JSONObject post=new JSONObject();

im using two object because you can have an jsonObject within another

post.put("username(here i write the key)","someusername"(here i put the value);
post.put("message","this is a sweet message");
post.put("image","http://localhost/someimage.jpg");
post.put("time":  "present time");

then i put the post json inside another like this

  param.put("post",post);

this is the method that i use to make a request

 makeRequest(param.toString());

public JSONObject makeRequest(String param)
{
    try
    {

setting the connection

        urlConnection = new URL("your url");
        connection = (HttpURLConnection) urlConnection.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-type", "application/json;charset=UTF-8");
        connection.setReadTimeout(60000);
        connection.setConnectTimeout(60000);
        connection.connect();

setting the outputstream

        dataOutputStream = new DataOutputStream(connection.getOutputStream());

i use this to see in the logcat what i am sending

        Log.d("OUTPUT STREAM  " ,param);
        dataOutputStream.writeBytes(param);
        dataOutputStream.flush();
        dataOutputStream.close();

        InputStream in = new BufferedInputStream(connection.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        result = new StringBuilder();
        String line;

here the string is constructed

        while ((line = reader.readLine()) != null)
        {
            result.append(line);
        }

i use this log to see what its comming in the response

         Log.d("INPUTSTREAM: ",result.toString());

instancing a json with the String that contains the server response

        jResponse=new JSONObject(result.toString());

    }
    catch (IOException e) {
        e.printStackTrace();
        return jResponse=null;
    } catch (JSONException e)
    {
        e.printStackTrace();
        return jResponse=null;
    }
    connection.disconnect();
    return jResponse;
}

App can't be opened because it is from an unidentified developer

Control Click the application in the Applications folder, not lauchpad. Choose open and then you get an options to actually open it.

How to make Regular expression into non-greedy?

I believe it would be like this

takedata.match(/(\[.+\])/g);

the g at the end means global, so it doesn't stop at the first match.

Apache: "AuthType not set!" 500 Error

Just remove/comment the following line from your httpd.conf file (etc/httpd/conf)

Require all granted

This is needed till Apache Version 2.2 and is not required from thereon.

How to Extract Year from DATE in POSTGRESQL

Try

select date_part('year', your_column) from your_table;

or

select extract(year from your_column) from your_table;

Android: Expand/collapse animation

Making use of Kotlin Extension Functions this is tested and shortest answer

Just call animateVisibility(expand/collapse) on any View.

fun View.animateVisibility(setVisible: Boolean) {
    if (setVisible) expand(this) else collapse(this)
}

private fun expand(view: View) {
    view.measure(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
    val initialHeight = 0
    val targetHeight = view.measuredHeight

    // Older versions of Android (pre API 21) cancel animations for views with a height of 0.
    //v.getLayoutParams().height = 1;
    view.layoutParams.height = 0
    view.visibility = View.VISIBLE

    animateView(view, initialHeight, targetHeight)
}

private fun collapse(view: View) {
    val initialHeight = view.measuredHeight
    val targetHeight = 0

    animateView(view, initialHeight, targetHeight)
}

private fun animateView(v: View, initialHeight: Int, targetHeight: Int) {
    val valueAnimator = ValueAnimator.ofInt(initialHeight, targetHeight)
    valueAnimator.addUpdateListener { animation ->
        v.layoutParams.height = animation.animatedValue as Int
        v.requestLayout()
    }
    valueAnimator.addListener(object : Animator.AnimatorListener {
        override fun onAnimationEnd(animation: Animator) {
            v.layoutParams.height = targetHeight
        }

        override fun onAnimationStart(animation: Animator) {}
        override fun onAnimationCancel(animation: Animator) {}
        override fun onAnimationRepeat(animation: Animator) {}
    })
    valueAnimator.duration = 300
    valueAnimator.interpolator = DecelerateInterpolator()
    valueAnimator.start()
}

Regular expressions inside SQL Server

Try this

select * from mytable
where p1 not like '%[^0-9]%' and substring(p1,1,1)='5'

Of course, you'll need to adjust the substring value, but the rest should work...

Android SQLite: Update Statement

The SQLiteDatabase object depends on the type of operation on the database.

More information, visit the official website:

https://developer.android.com/training/basics/data-storage/databases.html#UpdateDbRow

It explains how to manipulate consultations on the SQLite database.

INSERT ROW

Gets the data repository in write mode

SQLiteDatabase db = mDbHelper.getWritableDatabase();

Create a new map of values, where column names are the keys

ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_ENTRY_ID, id);
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedEntry.COLUMN_NAME_CONTENT, content);

Insert the new row, returning the primary key value of the new row

long newRowId;
newRowId = db.insert(
     FeedEntry.TABLE_NAME,
     FeedEntry.COLUMN_NAME_NULLABLE,
     values);

UPDATE ROW

Define 'where' part of query.

String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";

Specify arguments in placeholder order.

String[] selectionArgs = { String.valueOf(rowId) };


SQLiteDatabase db = mDbHelper.getReadableDatabase();

New value for one column

ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_TITLE, title);

Which row to update, based on the ID

String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";
String[] selectionArgs = { String.valueOf(rowId) };
    int count = db.update(
    FeedReaderDbHelper.FeedEntry.TABLE_NAME,
    values,
    selection,
    selectionArgs);

How to commit my current changes to a different branch in Git

  1. git checkout my_other_branch
  2. git add my_file my_other_file
  3. git commit -m

And provide your commit message.

git: undo all working dir changes including new files

An alternative solution is to commit the changes, and then get rid of those commits. This does not have an immediate benefit at first, but it opens up the possibility to commit in chunks, and to create a git tag for backup.

You can do it on the current branch, like this:

git add (-A) .
git commit -m"DISCARD: Temporary local changes"
git tag archive/local-changes-2015-08-01  # optional
git revert HEAD
git reset HEAD^^

Or you can do it on detached HEAD. (assuming you start on BRANCHNAME branch):

git checkout --detach HEAD
git add (-A) .
git commit -m"DISCARD: Temporary local changes"
git tag archive/local-changes-2015-08-01  # optional
git checkout BRANCHNAME

However, what I usually do is to commit in chunks, then name some or all commits as "DISCARD: ...". Then use interactive rebase to remove the bad commits and keep the good ones.

git add -p  # Add changes in chunks.
git commit -m"DISCARD: Some temporary changes for debugging"
git add -p  # Add more stuff.
git commit -m"Docblock improvements"
git tag archive/local-changes-2015-08-01
git rebase -i (commit id)  # rebase on the commit id before the changes.
  # Remove the commits that say "DISCARD".

This is more verbose, but it allows to review exactly which changes you want to discard.

The git lol and git lola shortcuts have been very helpful with this workflow.

Use Excel pivot table as data source for another Pivot Table

  • Make your first pivot table.

  • Select the first top left cell.

  • Create a range name using offset:

    OFFSET(Sheet1!$A$3,0,0,COUNTA(Sheet1!$A:$A)-1,COUNTA(Sheet1!$3:$3))

  • Make your second pivot with your range name as source of data using F3.

If you change number of rows or columns from your first pivot, your second pivot will be update after refreshing pivot

GFGDT

Why is synchronized block better than synchronized method?

synchronized should only be used when you want your class to be Thread safe. In fact most of the classes should not use synchronized anyways. synchronized method would only provide a lock on this object and only for the duration of its execution. if you really wanna to make your classes thread safe, you should consider making your variables volatile or synchronize the access.

one of the issues of using synchronized method is that all of the members of the class would use the same lock which will make your program slower. In your case synchronized method and block would execute no different. what I'd would recommend is to use a dedicated lock and use a synchronized block something like this.

public class AClass {
private int x;
private final Object lock = new Object();     //it must be final!

 public void setX() {
    synchronized(lock) {
        x++;
    }
 }
}

Given a starting and ending indices, how can I copy part of a string in C?

Just use memcpy.

If the destination isn't big enough, strncpy won't null terminate. if the destination is huge compared to the source, strncpy just fills the destination with nulls after the string. strncpy is pointless, and unsuitable for copying strings.

strncpy is like memcpy except it fills the destination with nulls once it sees one in the source. It's absolutely useless for string operations. It's for fixed with 0 padded records.

How can I check if a date is the same day as datetime.today()?

If you want to just compare dates,

yourdatetime.date() < datetime.today().date()

Or, obviously,

yourdatetime.date() == datetime.today().date()

If you want to check that they're the same date.

The documentation is usually helpful. It is also usually the first google result for python thing_i_have_a_question_about. Unless your question is about a function/module named "snake".

Basically, the datetime module has three types for storing a point in time:

  • date for year, month, day of month
  • time for hours, minutes, seconds, microseconds, time zone info
  • datetime combines date and time. It has the methods date() and time() to get the corresponding date and time objects, and there's a handy combine function to combine date and time into a datetime.

Is there a list of Pytz Timezones?

In my opinion this is a design flaw of pytz library. It should be more reliable to specify a timezone using the offset, e.g.

pytz.construct("UTC-07:00")

which gives you Canada/Pacific timezone.

How to include layout inside layout?

From Official documents about Re-using Layouts

Although Android offers a variety of widgets to provide small and re-usable interactive elements, you might also need to re-use larger components that require a special layout. To efficiently re-use complete layouts, you can use the tag to embed another layout inside the current layout.

Here is my header.xml file which i can reuse using include tag

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFFFF"
    >


    <TextView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:gravity="center"
        android:text="@string/app_name"
        android:textColor="#000000" />

</RelativeLayout>

No I use the tag in XML to add another layout from another XML file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#f0f0f0" >


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

        <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:background="#ffffff"
        android:orientation="vertical"
        android:padding="5dp" >


    </LinearLayout>

Selenium WebDriver: Wait for complex page with JavaScript to load

Using implicit wait works for me.

driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);

Refer to this answer Selenium c# Webdriver: Wait Until Element is Present

What does appending "?v=1" to CSS and JavaScript URLs in link and script tags do?

During development / testing of new releases, the cache can be a problem because the browser, the server and even sometimes the 3G telco (if you do mobile deployment) will cache the static content (e.g. JS, CSS, HTML, img). You can overcome this by appending version number, random number or timestamp to the URL e.g: JSP: <script src="js/excel.js?time=<%=new java.util.Date()%>"></script>

In case you're running pure HTML (instead of server pages JSP, ASP, PHP) the server won't help you. In browser, links are loaded before the JS runs, therefore you have to remove the links and load them with JS.

// front end cache bust
var cacheBust = ['js/StrUtil.js', 'js/protos.common.js', 'js/conf.js', 'bootstrap_ECP/js/init.js'];   
for (i=0; i < cacheBust.length; i++){
     var el = document.createElement('script');
     el.src = cacheBust[i]+"?v=" + Math.random();
     document.getElementsByTagName('head')[0].appendChild(el);
}

Stacked Tabs in Bootstrap 3

To get left and right tabs (now also with sideways) support for Bootstrap 3, bootstrap-vertical-tabs component can be used.

https://github.com/dbtek/bootstrap-vertical-tabs

What is the easiest way to parse an INI File in C++?

Unless you plan on making the app cross-platform, using the Windows API calls would be the best way to go. Just ignore the note in the API documentation about being provided only for 16-bit app compatibility.

Returning a C string from a function

Your problem is with the return type of the function - it must be:

char *myFunction()

...and then your original formulation will work.

Note that you cannot have C strings without pointers being involved, somewhere along the line.

Also: Turn up your compiler warnings. It should have warned you about that return line converting a char * to char without an explicit cast.

Cannot make file java.io.IOException: No such file or directory

File.isFile() is false if the file / directory does not exist, so you can't use it to test whether you're trying to create a directory. But that's not the first issue here.

The issue is that the intermediate directories don't exist. You want to call f.mkdirs() first.

Convert list to array in Java

Example taken from this page: http://www.java-examples.com/copy-all-elements-java-arraylist-object-array-example

import java.util.ArrayList;

public class CopyElementsOfArrayListToArrayExample {

  public static void main(String[] args) {
    //create an ArrayList object
    ArrayList arrayList = new ArrayList();

    //Add elements to ArrayList
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
    arrayList.add("4");
    arrayList.add("5");

    /*
      To copy all elements of java ArrayList object into array use
      Object[] toArray() method.
    */

    Object[] objArray = arrayList.toArray();

    //display contents of Object array
    System.out.println("ArrayList elements are copied into an Array.
                                                  Now Array Contains..");
    for(int index=0; index < objArray.length ; index++)
      System.out.println(objArray[index]);
  }
}

/*
Output would be
ArrayList elements are copied into an Array. Now Array Contains..
1
2
3
4
5

HTTP POST and GET using cURL in Linux

*nix provides a nice little command which makes our lives a lot easier.

GET:

with JSON:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource

with XML:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource

POST:

For posting data:

curl --data "param1=value1&param2=value2" http://hostname/resource

For file upload:

curl --form "[email protected]" http://hostname/resource

RESTful HTTP Post:

curl -X POST -d @filename http://hostname/resource

For logging into a site (auth):

curl -d "username=admin&password=admin&submit=Login" --dump-header headers http://localhost/Login
curl -L -b headers http://localhost/

Pretty-printing the curl results:

For JSON:

If you use npm and nodejs, you can install json package by running this command:

npm install -g json

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | json

If you use pip and python, you can install pjson package by running this command:

pip install pjson

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | pjson

If you use Python 2.6+, json tool is bundled within.

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | python -m json.tool

If you use gem and ruby, you can install colorful_json package by running this command:

gem install colorful_json

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | cjson

If you use apt-get (aptitude package manager of your Linux distro), you can install yajl-tools package by running this command:

sudo apt-get install yajl-tools

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource |  json_reformat

For XML:

If you use *nix with Debian/Gnome envrionment, install libxml2-utils:

sudo apt-get install libxml2-utils

Usage:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | xmllint --format -

or install tidy:

sudo apt-get install tidy

Usage:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | tidy -xml -i -

Saving the curl response to a file

curl http://hostname/resource >> /path/to/your/file

or

curl http://hostname/resource -o /path/to/your/file

For detailed description of the curl command, hit:

man curl

For details about options/switches of the curl command, hit:

curl -h

Generate signed apk android studio

Use Keytool binary or exe to generate a private keystore. Instructions here. You can then sign your app using this keystore. Keytool gets installed when you install Java.

NOTE: Save/backup this keystore because once you publish an app on play by signing it with this keystore, you will have to use the same keystore for any future updates. So, it's important that you back it up.

HTH.

How to check if an Object is a Collection Type in Java?

Test if the object implements either java.util.Collection or java.util.Map. (Map has to be tested separately because it isn't a sub-interface of Collection.)

Could not install packages due to an EnvironmentError: [Errno 13]

I had the same problem while installing numpy with pip install numpy.

Then I tried

sudo -H pip3 install --upgrade pip

sudo -H pip3 install numpy

It worked well for me.

Explanation : The -H (HOME) option with sudo sets the HOME environment variable to the home directory of the target user (root by default). By default, sudo does not modify HOME.

Show/hide div if checkbox selected

You would need to always consider the state of all checkboxes!

You could increase or decrease a number on checking or unchecking, but imagine the site loads with three of them checked.

So you always need to check all of them:

<script type="text/javascript">
<!--
function showMe (it, box) {
  // consider all checkboxes with same name
  var checked = amountChecked(box.name);

  var vis = (checked >= 3) ? "block" : "none";
  document.getElementById(it).style.display = vis;
}

function amountChecked(name) {
  var all = document.getElementsByName(name);

  // count checked
  var result = 0;
  all.forEach(function(el) {
    if (el.checked) result++;
  });

  return result;
}
//-->
</script>

Printing out a linked list using toString

I do it the following way:

public static void main(String[] args) {

    LinkedList list = new LinkedList();
    list.insertFront(1);
    list.insertFront(2);
    list.insertFront(3);
    System.out.println(list.toString());
}

String toString() {
    StringBuilder result = new StringBuilder();
    for(Object item:this) {
        result.append(item.toString());
        result.append("\n"); //optional
    }
    return result.toString();
}

declaring a priority_queue in c++ with a custom comparator

Answering your question directly:

I'm trying to declare a priority_queue of nodes, using bool Compare(Node a, Node b) as the comparator function

What I currently have is:

priority_queue<Node, vector<Node>, Compare> openSet;

For some reason, I'm getting Error:

"Compare" is not a type name

The compiler is telling you exactly what's wrong: Compare is not a type name, but an instance of a function that takes two Nodes and returns a bool.
What you need is to specify the function pointer type:
std::priority_queue<Node, std::vector<Node>, bool (*)(Node, Node)> openSet(Compare)

Javamail Could not convert socket to TLS GMail

After a full day of search, I disabled Avast for 10 minutes and Windows Firewall (important) and everything started working!

This was my error:

Mail server connection failed; nested exception is javax.mail.MessagingException: Could not convert socket to TLS; nested exception is: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target. Failed messages: javax.mail.MessagingException: Could not convert socket to TLS; nested exception is: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target  

Here is how to fix the issue in Avast 19.8.2393 by adding an exclusion to SMTP port 587 (or whichever port your application uses):

  1. Open Avast

  2. Click on 'Settings'

  3. Click on 'Troubleshooting' and then 'Open old settings'

enter image description here

  1. Click again on 'Troubleshooting', scroll down to 'Redirect settings' and delete the port that your app uses.

enter image description here

In my case, I just removed 587 from SMTP ports.

Now I am able to use Avast and also have my Windows Firewall switched on (no need to add additional exclusion for the Firewall).

Here are my application.properties e-mail properties:

###### I am using a Google App Password which I generated in my Gmail Security settings ######
spring.mail.host = smtp.gmail.com
spring.mail.port = 587
spring.mail.protocol = smtp
spring.mail.username = gmail account
spring.mail.password = password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000

Switch role after connecting to database

If someone still needs it (like I do).

The specified role_name must be a role that the current session user is a member of. https://www.postgresql.org/docs/10/sql-set-role.html

We need to make the current session user a member of the role:

create role myrole;
set role myrole;
grant myrole to myuser;
set role myrole;

produces:

Role ROLE created.


Error starting at line : 4 in command -
set role myrole
Error report -
ERROR: permission denied to set role "myrole"

Grant succeeded.


Role SET succeeded.

C# equivalent of C++ map<string,double>

This code is all you need:

   static void Main(string[] args) {
        String xml = @"
            <transactions>
                <transaction name=""Fred"" amount=""5,20"" />
                <transaction name=""John"" amount=""10,00"" />
                <transaction name=""Fred"" amount=""3,00"" />
            </transactions>";

        XDocument xmlDocument = XDocument.Parse(xml);

        var query = from x in xmlDocument.Descendants("transaction")
                    group x by x.Attribute("name").Value into g
                    select new { Name = g.Key, Amount = g.Sum(t => Decimal.Parse(t.Attribute("amount").Value)) };

        foreach (var item in query) {
            Console.WriteLine("Name: {0}; Amount: {1:C};", item.Name, item.Amount);
        }
    }

And the content is:

Name: Fred; Amount: R$ 8,20;
Name: John; Amount: R$ 10,00;

That is the way of doing this in C# - in a declarative way!

I hope this helps,

Ricardo Lacerda Castelo Branco

Matplotlib/pyplot: How to enforce axis range?

To answer my own question, the trick is to turn auto scaling off...

p.axis([0.0,600.0, 10000.0,20000.0])
ax = p.gca()
ax.set_autoscale_on(False)

Easiest way to convert int to string in C++

I usually use the following method:

#include <sstream>

template <typename T>
  std::string NumberToString ( T Number )
  {
     std::ostringstream ss;
     ss << Number;
     return ss.str();
  }

It is described in details here.

Find provisioning profile in Xcode 5

xCode 6 allows you to right click on the provisioning profile under account -> detail (the screen shot you have there) & shows a popup "show in finder".

Using CMake with GNU Make: How can I see the exact commands?

When you run make, add VERBOSE=1 to see the full command output. For example:

cmake .
make VERBOSE=1

Or you can add -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON to the cmake command for permanent verbose command output from the generated Makefiles.

cmake -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON .
make

To reduce some possibly less-interesting output you might like to use the following options. The option CMAKE_RULE_MESSAGES=OFF removes lines like [ 33%] Building C object..., while --no-print-directory tells make to not print out the current directory filtering out lines like make[1]: Entering directory and make[1]: Leaving directory.

cmake -DCMAKE_RULE_MESSAGES:BOOL=OFF -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON .
make --no-print-directory

Sorting multiple keys with Unix sort

I just want to add some tips, when you using sort , be careful about your locale that effects the order of the key comparison. I usually explicitly use LC_ALL=C to make locale what I want.

Change event on select with knockout binding, how can I know if it is a real change?

I use this custom binding (based on this fiddle by RP Niemeyer, see his answer to this question), which makes sure the numeric value is properly converted from string to number (as suggested by the solution of Michael Best):

Javascript:

ko.bindingHandlers.valueAsNumber = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        var observable = valueAccessor(),
            interceptor = ko.computed({
                read: function () {
                    var val = ko.utils.unwrapObservable(observable);
                    return (observable() ? observable().toString() : observable());
                },
                write: function (newValue) {
                    observable(newValue ? parseInt(newValue, 10) : newValue);
                },
                owner: this
            });
        ko.applyBindingsToNode(element, { value: interceptor });
    }
};

Example HTML:

<select data-bind="valueAsNumber: level, event:{ change: $parent.permissionChanged }">
    <option value="0"></option>
    <option value="1">R</option>
    <option value="2">RW</option>
</select>

What is the difference between `new Object()` and object literal notation?

On my machine using Node.js, I ran the following:

console.log('Testing Array:');
console.time('using[]');
for(var i=0; i<200000000; i++){var arr = []};
console.timeEnd('using[]');

console.time('using new');
for(var i=0; i<200000000; i++){var arr = new Array};
console.timeEnd('using new');

console.log('Testing Object:');

console.time('using{}');
for(var i=0; i<200000000; i++){var obj = {}};
console.timeEnd('using{}');

console.time('using new');
for(var i=0; i<200000000; i++){var obj = new Object};
console.timeEnd('using new');

Note, this is an extension of what is found here: Why is arr = [] faster than arr = new Array?

my output was the following:

Testing Array:
using[]: 1091ms
using new: 2286ms
Testing Object:
using{}: 870ms
using new: 5637ms

so clearly {} and [] are faster than using new for creating empty objects/arrays.

Use table name in MySQL SELECT "AS"

To declare a string literal as an output column, leave the Table off and just use Test. It doesn't need to be associated with a table among your joins, since it will be accessed only by its column alias. When using a metadata function like getColumnMeta(), the table name will be an empty string because it isn't associated with a table.

SELECT
  `field1`, 
  `field2`, 
  'Test' AS `field3` 
FROM `Test`;

Note: I'm using single quotes above. MySQL is usually configured to honor double quotes for strings, but single quotes are more widely portable among RDBMS.

If you must have a table alias name with the literal value, you need to wrap it in a subquery with the same name as the table you want to use:

SELECT
  field1,
  field2,
  field3
FROM 
  /* subquery wraps all fields to put the literal inside a table */
  (SELECT field1, field2, 'Test' AS field3 FROM Test) AS Test

Now field3 will come in the output as Test.field3.

jQuery changing css class to div

$(".first").addClass("second");

If you'd like to add it on an event, you can do so easily as well. An example with the click event:

$(".first").click(function() {
    $(this).addClass("second");
});

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

FormsModule should be added at imports array not declarations array.

  • imports array is for importing modules such as BrowserModule, FormsModule, HttpModule
  • declarations array is for your Components, Pipes, Directives

refer below change:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

How to Reload ReCaptcha using JavaScript?

For AngularJS users:

$window.grecaptcha.reset();

Unicode via CSS :before

The escaped hex reference of &#xf066; is \f066.

content: "\f066";

How can I remove duplicate rows?

For the table structure

MyTable

RowID int not null identity(1,1) primary key,
Col1 varchar(20) not null,
Col2 varchar(2048) not null,
Col3 tinyint not null

The query for removing duplicates:

DELETE t1
FROM MyTable t1
INNER JOIN MyTable t2
WHERE t1.RowID > t2.RowID
  AND t1.Col1 = t2.Col1
  AND t1.Col2=t2.Col2
  AND t1.Col3=t2.Col3;

I am assuming that RowID is kind of auto-increment and rest of the columns have duplicate values.

Specify JDK for Maven to use

I had build problem with maven within Eclipse on Windows 7.

Though I observed mvn build was running just fine from command line.

mvn -T 5 -B -e -X -U -P test clean install -Dmaven.surefire.debug  --settings ..\..\infra-scripts\maven-conf\settings.xml   > output.log

Eclipse was considering as default JVM a JRE installation instead of JDK so it was failing on compilation.

I added to eclipse.ini following line:

-vm
C:\Program Files (x86)\Java\jdk1.8.0_25\bin

Also when starting from eclipse I used in "Goals" section following list:

-T 5 -B -e -X -U -P test clean install -Dmaven.surefire.debug  --settings ..\..\infra-scripts\maven-conf\settings.xml

Compilation error got solved.

Change directory in Node.js command prompt

.help will show you all the options. Do .exit in this case

file_get_contents behind a proxy?

Depending on how the proxy login works stream_context_set_default might help you.

$context  = stream_context_set_default(
  array(
    'http'=>array(
      'header'=>'Authorization: Basic ' . base64_encode('username'.':'.'userpass')
    )
  )
);
$result = file_get_contents('http://..../...');

inner join in linq to entities

You can find a whole bunch of Linq examples in visual studio. Just select Help -> Samples, and then unzip the Linq samples.

Open the linq samples solution and open the LinqSamples.cs of the SampleQueries project.

The answer you are looking for is in method Linq14:

int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };

var pairs =
   from a in numbersA
   from b in numbersB
   where a < b
   select new {a, b};

Using iText to convert HTML to PDF

When I needed HTML to PDF conversion earlier this year, I tried the trial of Winnovative HTML to PDF converter (I think ExpertPDF is the same product, too). It worked great so we bought a license at that company. I don't go into it too in depth after that.

how to convert string into time format and add two hours

Use the SimpleDateFormat class parse() method. This method will return a Date object. You can then create a Calendar object for this Date and add 2 hours to it.

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = formatter.parse(theDateToParse);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, 2);
cal.getTime(); // This will give you the time you want.

Android EditText view Floating Hint in Material Design

@andruboy's suggestion of https://gist.github.com/chrisbanes/11247418 is probably your best bet.

https://github.com/thebnich/FloatingHintEditText kind of works with appcompat-v7 v21.0.0, but since v21.0.0 does not support accent colors with subclasses of EditText, the underline of the FloatingHintEditText will be the default solid black or white. Also the padding is not optimized for the Material style EditText, so you may need to adjust it.

How to Alter Constraint

No. We cannot alter the constraint, only thing we can do is drop and recreate it

ALTER TABLE [TABLENAME] DROP CONSTRAINT [CONSTRAINTNAME]

Foreign Key Constraint

Alter Table Table1 Add Constraint [CONSTRAINTNAME] Foreign Key (Column) References Table2 (Column) On Update Cascade On Delete Cascade

Primary Key constraint

Alter Table Table add constraint [Primary Key] Primary key(Column1,Column2,.....)

Difference between using "chmod a+x" and "chmod 755"

chmod a+x modifies the argument's mode while chmod 755 sets it. Try both variants on something that has full or no permissions and you will notice the difference.

phpmailer: Reply using only "Reply To" address

I have found the answer to this, and it is annoyingly/frustratingly simple! Basically the reply to addresses needed to be added before the from address as such:

$mail->addReplyTo('[email protected]', 'Reply to name');
$mail->SetFrom('[email protected]', 'Mailbox name');

Looking at the phpmailer code in more detail this is the offending line:

public function SetFrom($address, $name = '',$auto=1) {
   $address = trim($address);
   $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
   if (!self::ValidateAddress($address)) {
     $this->SetError($this->Lang('invalid_address').': '. $address);
     if ($this->exceptions) {
       throw new phpmailerException($this->Lang('invalid_address').': '.$address);
     }
     echo $this->Lang('invalid_address').': '.$address;
     return false;
   }
   $this->From = $address;
   $this->FromName = $name;
   if ($auto) {
      if (empty($this->ReplyTo)) {
         $this->AddAnAddress('ReplyTo', $address, $name);
      }
      if (empty($this->Sender)) {
         $this->Sender = $address;
      }
   }
   return true;
}

Specifically this line:

if (empty($this->ReplyTo)) {
   $this->AddAnAddress('ReplyTo', $address, $name);
}

Thanks for your help everyone!

MSBuild doesn't copy references (DLL files) if using project dependencies in solution

Including all referenced DLL files from your projectreferences in the Website project is not always a good idea, especially when you're using dependency injection: your web project just want to add a reference to the interface DLL file/project, not any concrete implementation DLL file.

Because if you add a reference directly to an implementation DLL file/project, you can't prevent your developer from calling a "new" on concrete classes of the implementation DLL file/project instead of via the interface. It's also you've stated a "hardcode" in your website to use the implementation.

Basic HTML - how to set relative path to current folder?

<html>
    <head>
        <title>Page</title>
    </head>
    <body>
       <a href="./">Folder directory</a> 
    </body>
</html>

How to Calculate Execution Time of a Code Snippet in C++

I created a simple utility for measuring performance of blocks of code, using the chrono library's high_resolution_clock: https://github.com/nfergu/codetimer.

Timings can be recorded against different keys, and an aggregated view of the timings for each key can be displayed.

Usage is as follows:

#include <chrono>
#include <iostream>
#include "codetimer.h"

int main () {
    auto start = std::chrono::high_resolution_clock::now();
    // some code here
    CodeTimer::record("mykey", start);
    CodeTimer::printStats();
    return 0;
}

Keep values selected after form submission

To avoid many if-else structures, let JavaScript do the trick automatically:

<select name="name" id="name">
   <option value="a">a</option>
   <option value="b">b</option>
</select>

<script type="text/javascript">
  document.getElementById('name').value = "<?php echo $_GET['name'];?>";
</script>

<select name="location" id="location">
  <option value="x">x</option>
  <option value="y">y</option>
</select>

<script type="text/javascript">
  document.getElementById('location').value = "<?php echo $_GET['location'];?>";
</script>

How can I remove space (margin) above HTML header?

Try margin-top:

<header style="margin-top: -20px;">
    ...

Edit:

Now I found relative position probably a better choice:

<header style="position: relative; top: -20px;">
    ...

How to compile a static library in Linux?

Here a full makefile example:

makefile

TARGET = prog

$(TARGET): main.o lib.a
    gcc $^ -o $@

main.o: main.c
    gcc -c $< -o $@

lib.a: lib1.o lib2.o
    ar rcs $@ $^

lib1.o: lib1.c lib1.h
    gcc -c -o $@ $<

lib2.o: lib2.c lib2.h
    gcc -c -o $@ $<

clean:
    rm -f *.o *.a $(TARGET)

explaining the makefile:

  • target: prerequisites - the rule head
  • $@ - means the target
  • $^ - means all prerequisites
  • $< - means just the first prerequisite
  • ar - a Linux tool to create, modify, and extract from archives see the man pages for further information. The options in this case mean:
    • r - replace files existing inside the archive
    • c - create a archive if not already existent
    • s - create an object-file index into the archive

To conclude: The static library under Linux is nothing more than a archive of object files.

main.c using the lib

#include <stdio.h>

#include "lib.h"

int main ( void )
{
    fun1(10);
    fun2(10);
    return 0;
}

lib.h the libs main header

#ifndef LIB_H_INCLUDED
#define LIB_H_INCLUDED

#include "lib1.h"
#include "lib2.h"

#endif

lib1.c first lib source

#include "lib1.h"

#include <stdio.h>

void fun1 ( int x )
{
    printf("%i\n",x);
}

lib1.h the corresponding header

#ifndef LIB1_H_INCLUDED
#define LIB1_H_INCLUDED

#ifdef __cplusplus
   extern “C” {
#endif

void fun1 ( int x );

#ifdef __cplusplus
   }
#endif

#endif /* LIB1_H_INCLUDED */

lib2.c second lib source

#include "lib2.h"

#include <stdio.h>

void fun2 ( int x )
{
    printf("%i\n",2*x);
}

lib2.h the corresponding header

#ifndef LIB2_H_INCLUDED
#define LIB2_H_INCLUDED

#ifdef __cplusplus
   extern “C” {
#endif

void fun2 ( int x );

#ifdef __cplusplus
   }
#endif

#endif /* LIB2_H_INCLUDED */

How do I convert a number to a letter in Java?

You can try like this:

private String getCharForNumber(int i) {
    CharSequence css = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    if (i > 25) {
        return null;
    }
    return css.charAt(i) + "";
}

How to open my files in data_folder with pandas using relative path?

# script.py
current_file = os.path.abspath(os.path.dirname(__file__)) #older/folder2/scripts_folder

#csv_filename
csv_filename = os.path.join(current_file, '../data_folder/data.csv')

Add column to dataframe with constant value

You can use insert to specify where you want to new column to be. In this case, I use 0 to place the new column at the left.

df.insert(0, 'Name', 'abc')

  Name        Date  Open  High  Low  Close
0  abc  01-01-2015   565   600  400    450

Invoke-WebRequest, POST with parameters

Put your parameters in a hash table and pass them like this:

$postParams = @{username='me';moredata='qwerty'}
Invoke-WebRequest -Uri http://example.com/foobar -Method POST -Body $postParams

How to find out when an Oracle table was updated the last time

How long does the batch process take to write the file? It may be easiest to let it go ahead and then compare the file against a copy of the file from the previous run to see if they are identical.

Detect if value is number in MySQL

use a UDF (user defined function).

CREATE FUNCTION isnumber(inputValue VARCHAR(50))
  RETURNS INT
  BEGIN
    IF (inputValue REGEXP ('^[0-9]+$'))
    THEN
      RETURN 1;
    ELSE
      RETURN 0;
    END IF;
  END;

Then when you query

select isnumber('383XXXX') 

--returns 0

select isnumber('38333434') 

--returns 1

select isnumber(mycol) mycol1, col2, colx from tablex; -- will return 1s and 0s for column mycol1

--you can enhance the function to take decimals, scientific notation , etc...

The advantage of using a UDF is that you can use it on the left or right side of your "where clause" comparison. this greatly simplifies your SQL before being sent to the database:

 SELECT * from tablex where isnumber(columnX) = isnumber('UnkownUserInput');

hope this helps.

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

This is precisely what position: fixed was designed for:

#footer {
    position: fixed;
    bottom: 0;
    width: 100%;
}

Here's the fiddle: http://jsfiddle.net/uw8f9/

Convert a float64 to an int in Go

If its simply from float64 to int, this should work

package main

import (
    "fmt"
)

func main() {
    nf := []float64{-1.9999, -2.0001, -2.0, 0, 1.9999, 2.0001, 2.0}

    //round
    fmt.Printf("Round : ")
    for _, f := range nf {
        fmt.Printf("%d ", round(f))
    }
    fmt.Printf("\n")

    //rounddown ie. math.floor
    fmt.Printf("RoundD: ")
    for _, f := range nf {
        fmt.Printf("%d ", roundD(f))
    }
    fmt.Printf("\n")

    //roundup ie. math.ceil
    fmt.Printf("RoundU: ")
    for _, f := range nf {
        fmt.Printf("%d ", roundU(f)) 
    }
    fmt.Printf("\n")

}

func roundU(val float64) int {
    if val > 0 { return int(val+1.0) }
    return int(val)
}

func roundD(val float64) int {
    if val < 0 { return int(val-1.0) }
    return int(val)
}

func round(val float64) int {
    if val < 0 { return int(val-0.5) }
    return int(val+0.5)
}

Outputs:

Round : -2 -2 -2 0 2 2 2 
RoundD: -2 -3 -3 0 1 2 2 
RoundU: -1 -2 -2 0 2 3 3 

Here's the code in the playground - https://play.golang.org/p/HmFfM6Grqh

PHP Redirect to another page after form submit

If your redirect is in PHP, nothing should be echoed to the user before the redirect instruction.

See header for more info.

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP

Otherwise, you can use Javascript to redirect the user.

Just use

window.location = "http://www.google.com/"

Seeking useful Eclipse Java code templates

Create everything for an event

Since events are kinda a pain to create in Java--all those interfaces, methods, and stuff to write just for 1 event--I made a simple template to create everything needed for 1 event.

${:import(java.util.List, java.util.LinkedList, java.util.EventListener, java.util.EventObject)}

private final List<${eventname}Listener> ${eventname}Listeners = new LinkedList<${eventname}Listener>();

public final void add${eventname}Listener(${eventname}Listener listener)
{
    synchronized(${eventname}Listeners) {
        ${eventname}Listeners.add(listener);
    }
}

public final void remove${eventname}Listener(${eventname}Listener listener)
{
    synchronized(${eventname}Listeners) {
        ${eventname}Listeners.remove(listener);
    }
}

private void raise${eventname}Event(${eventname}Args args)
{
    synchronized(${eventname}Listeners) {
        for(${eventname}Listener listener : ${eventname}Listeners)
            listener.on${eventname}(args);
    }
}

public interface ${eventname}Listener extends EventListener
{
    public void on${eventname}(${eventname}Args args);
}

public class ${eventname}Args extends EventObject
{
    public ${eventname}Args(Object source${cursor})
    {
        super(source);
    }
}

If you have events that share a single EventObject, just delete the customized one inserted by the template and change the appropriate parts of raise___() and on____().

I had written a nice, little, elegant eventing mechanism using a generic interface and generic class, but it wouldn't work due to the way Java handles generics. =(

Edit: 1) I ran into the issue where threads were adding/removing listeners while an event was taking place. The List can't be modified while in use, so I added synchronized blocks where the list of listeners is being accessed or used, locking on the list itself.

Junit - run set up method once

Edit: I just found out while debugging that the class is instantiated before every test too. I guess the @BeforeClass annotation is the best here.

You can set up on the constructor too, the test class is a class after all. I'm not sure if it's a bad practice because almost all other methods are annotated, but it works. You could create a constructor like that:

public UT () {
    // initialize once here
}
@Test
// Some test here...

The ctor will be called before the tests because they are not static.

create table in postgreSQL

Please try this:

CREATE TABLE article (
  article_id bigint(20) NOT NULL serial,
  article_name varchar(20) NOT NULL,
  article_desc text NOT NULL,
  date_added datetime default NULL,
  PRIMARY KEY (article_id)
);

How to get the device's IMEI/ESN programmatically in android?

New Update:

For Android Version 6 And Above, WLAN MAC Address has been deprecated , follow Trevor Johns answer

Update:

For uniquely Identification of devices, You can Use Secure.ANDROID_ID.

Old Answer:

Disadvantages of using IMEI as Unique Device ID:

  • IMEI is dependent on the Simcard slot of the device, so it is not possible to get the IMEI for the devices that do not use Simcard. In Dual sim devices, we get 2 different IMEIs for the same device as it has 2 slots for simcard.

You can Use The WLAN MAC Address string (Not Recommended For Marshmallow and Marshmallow+ as WLAN MAC Address has been deprecated on Marshmallow forward. So you'll get a bogus value)

We can get the Unique ID for android phones using the WLAN MAC address also. The MAC address is unique for all devices and it works for all kinds of devices.

Advantages of using WLAN MAC address as Device ID:

  • It is unique identifier for all type of devices (smart phones and tablets).

  • It remains unique if the application is reinstalled

Disadvantages of using WLAN MAC address as Device ID:

  • Give You a Bogus Value from Marshmallow and above.

  • If device doesn’t have wifi hardware then you get null MAC address, but generally it is seen that most of the Android devices have wifi hardware and there are hardly few devices in the market with no wifi hardware.

SOURCE : technetexperts.com

7-zip commandline

Since 7-zip version 9.25 alpha there is a new -spf switch that can be used to store the full file paths including drive letter to the archive.

7zG.exe a -spf c:\BAckup\backup.zip @c:\temp\tmpFileList.txt

should be working just fine now.

How do I obtain a list of all schemas in a Sql Server database

SELECT s.name + '.' + ao.name
       , s.name
FROM sys.all_objects ao
INNER JOIN sys.schemas s ON s.schema_id = ao.schema_id
WHERE ao.type='u';

error: invalid type argument of ‘unary *’ (have ‘int’)

I have reformatted your code.

The error was situated in this line :

printf("%d", (**c));

To fix it, change to :

printf("%d", (*c));

The * retrieves the value from an address. The ** retrieves the value (an address in this case) of an other value from an address.

In addition, the () was optional.

#include <stdio.h>

int main(void)
{
    int b = 10; 
    int *a = NULL;
    int *c = NULL;

    a = &b;
    c = &a;

    printf("%d", *c);

    return 0;
} 

EDIT :

The line :

c = &a;

must be replaced by :

c = a;

It means that the value of the pointer 'c' equals the value of the pointer 'a'. So, 'c' and 'a' points to the same address ('b'). The output is :

10

EDIT 2:

If you want to use a double * :

#include <stdio.h>

int main(void)
{
    int b = 10; 
    int *a = NULL;
    int **c = NULL;

    a = &b;
    c = &a;

    printf("%d", **c);

    return 0;
} 

Output:

10

How do I use Bash on Windows from the Visual Studio Code integrated terminal?

This answer is similar to the top voted answer, but with an important distinction: a lot of the previous answers on this question focus on running Git Bash while my answer focuses on running WSL Bash.

  1. Enable Windows Subsystem for Linux on your Windows 10 machine.

  2. Open Visual Studio Code and press and hold Ctrl + ` to open the terminal.

  3. Open the command palette using Ctrl + Shift + P.

  4. Type - Select Default Shell.

  5. Select WSL Bash (NOT Git Bash) from the options.

enter image description here

  1. Click on the + icon in the terminal window. The new terminal now will be a WSL Bash terminal!

How to create bitmap from byte array?

You'll need to get those bytes into a MemoryStream:

Bitmap bmp;
using (var ms = new MemoryStream(imageData))
{
    bmp = new Bitmap(ms);
}

That uses the Bitmap(Stream stream) constructor overload.

UPDATE: keep in mind that according to the documentation, and the source code I've been reading through, an ArgumentException will be thrown on these conditions:

stream does not contain image data or is null.
-or-
stream contains a PNG image file with a single dimension greater than 65,535 pixels.

Open PDF in new browser full window

<a href="#" onclick="window.open('MyPDF.pdf', '_blank', 'fullscreen=yes'); return false;">MyPDF</a>

The above link will open the PDF in full screen mode, that's the best you can achieve.

Excel: Use a cell value as a parameter for a SQL query

If you are using microsoft query, you can add "?" to your query...

select name from user where id= ?

that will popup a small window asking for the cell/data/etc when you go back to excel.

In the popup window, you can also select "always use this cell as a parameter" eliminating the need to define that cell every time you refresh your data. This is the easiest option.

Detecting IE11 using CSS Capability/Feature Detection

Detecting IE and its versions actually is extremely easy, at least extremely intuitive:

var uA = navigator.userAgent;
var browser = null;
var ieVersion = null;

if (uA.indexOf('MSIE 6') >= 0) {
    browser = 'IE';
    ieVersion = 6;
}
if (uA.indexOf('MSIE 7') >= 0) {
    browser = 'IE';
    ieVersion = 7;
}
if (document.documentMode) { // as of IE8
    browser = 'IE';
    ieVersion = document.documentMode;
}

.

This way, ou're also catching high IE versions in Compatibility Mode/View. Next, its a matter of assigning conditional classes:

var htmlTag = document.documentElement;
if (browser == 'IE' && ieVersion <= 11)
    htmlTag.className += ' ie11-';

How to check if a table exists in MS Access for vb macros

This is not a new question. I addresed it in comments in one SO post, and posted my alternative implementations in another post. The comments in the first post actually elucidate the performance differences between the different implementations.

Basically, which works fastest depends on what database object you use with it.

Where can I find the Java SDK in Linux after installing it?

on OpenSUSE 13.1/13.2 its: /usr/lib64/jvm/java-1.6.0-openjdk-(version-number)
version-number can be 1.7.x 1.8.x etc. check software manager witch version you have installed...

André

How can I programmatically generate keypress events in C#?

I've not used it, but SendKeys may do what you want.

Use SendKeys to send keystrokes and keystroke combinations to the active application. This class cannot be instantiated. To send a keystroke to a class and immediately continue with the flow of your program, use Send. To wait for any processes started by the keystroke, use SendWait.

System.Windows.Forms.SendKeys.Send("A");
System.Windows.Forms.SendKeys.Send("{ENTER}");

Microsoft has some more usage examples here.

Checking if a website is up via Python

from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
req = Request("http://stackoverflow.com")
try:
    response = urlopen(req)
except HTTPError as e:
    print('The server couldn\'t fulfill the request.')
    print('Error code: ', e.code)
except URLError as e:
    print('We failed to reach a server.')
    print('Reason: ', e.reason)
else:
    print ('Website is working fine')

Works on Python 3

New line character in VB.Net?

If you are using something like this.

Response.Write("Hello \r\n")
Response.Write("World \r\n")

and the output is

Hello\r\nWorld\r\n

Then you are basically looking for something like this

Response.Write("Hello <br/>")
Response.Write("World <br/>")

This will output

Hello 
World

you can also just define "<br />" as constant and reuse it

eg.

Public Const HtmlNewLine as string ="<br />"
Response.Write("Hello " &  HtmlNewLine) 
Response.Write("World " &  HtmlNewLine)

How to get full path of a file?

Usually:

find `pwd` | grep <filename>

Alternatively, just for the current folder:

find `pwd` -maxdepth 1 | grep <filename>

Triggering change detection manually in Angular

I used accepted answer reference and would like to put an example, since Angular 2 documentation is very very hard to read, I hope this is easier:

  1. Import NgZone:

    import { Component, NgZone } from '@angular/core';
    
  2. Add it to your class constructor

    constructor(public zone: NgZone, ...args){}
    
  3. Run code with zone.run:

    this.zone.run(() => this.donations = donations)
    

Custom events in jQuery?

Take a look at this:

(reprinted from the expired blog page http://jamiethompson.co.uk/web/2008/06/17/publish-subscribe-with-jquery/ based on the archived version at http://web.archive.org/web/20130120010146/http://jamiethompson.co.uk/web/2008/06/17/publish-subscribe-with-jquery/)


Publish / Subscribe With jQuery

June 17th, 2008

With a view to writing a jQuery UI integrated with the offline functionality of Google Gears i’ve been toying with some code to poll for network connection status using jQuery.

The Network Detection Object

The basic premise is very simple. We create an instance of a network detection object which will poll a URL at regular intervals. Should these HTTP requests fail we can assume that network connectivity has been lost, or the server is simply unreachable at the current time.

$.networkDetection = function(url,interval){
    var url = url;
    var interval = interval;
    online = false;
    this.StartPolling = function(){
        this.StopPolling();
        this.timer = setInterval(poll, interval);
    };
    this.StopPolling = function(){
        clearInterval(this.timer);
    };
    this.setPollInterval= function(i) {
        interval = i;
    };
    this.getOnlineStatus = function(){
        return online;
    };
    function poll() {
        $.ajax({
            type: "POST",
            url: url,
            dataType: "text",
            error: function(){
                online = false;
                $(document).trigger('status.networkDetection',[false]);
            },
            success: function(){
                online = true;
                $(document).trigger('status.networkDetection',[true]);
            }
        });
    };
};

You can view the demo here. Set your browser to work offline and see what happens…. no, it’s not very exciting.

Trigger and Bind

What is exciting though (or at least what is exciting me) is the method by which the status gets relayed through the application. I’ve stumbled upon a largely un-discussed method of implementing a pub/sub system using jQuery’s trigger and bind methods.

The demo code is more obtuse than it need to be. The network detection object publishes ’status ‘events to the document which actively listens for them and in turn publishes ‘notify’ events to all subscribers (more on those later). The reasoning behind this is that in a real world application there would probably be some more logic controlling when and how the ‘notify’ events are published.

$(document).bind("status.networkDetection", function(e, status){
    // subscribers can be namespaced with multiple classes
    subscribers = $('.subscriber.networkDetection');
    // publish notify.networkDetection even to subscribers
    subscribers.trigger("notify.networkDetection", [status])
    /*
    other logic based on network connectivity could go here
    use google gears offline storage etc
    maybe trigger some other events
    */
});

Because of jQuery’s DOM centric approach events are published to (triggered on) DOM elements. This can be the window or document object for general events or you can generate a jQuery object using a selector. The approach i’ve taken with the demo is to create an almost namespaced approach to defining subscribers.

DOM elements which are to be subscribers are classed simply with “subscriber” and “networkDetection”. We can then publish events only to these elements (of which there is only one in the demo) by triggering a notify event on $(“.subscriber.networkDetection”)

The #notifier div which is part of the .subscriber.networkDetection group of subscribers then has an anonymous function bound to it, effectively acting as a listener.

$('#notifier').bind("notify.networkDetection",function(e, online){
    // the following simply demonstrates
    notifier = $(this);
    if(online){
        if (!notifier.hasClass("online")){
            $(this)
                .addClass("online")
                .removeClass("offline")
                .text("ONLINE");
        }
    }else{
        if (!notifier.hasClass("offline")){
            $(this)
                .addClass("offline")
                .removeClass("online")
                .text("OFFLINE");
        }
    };
});

So, there you go. It’s all pretty verbose and my example isn’t at all exciting. It also doesn’t showcase anything interesting you could do with these methods, but if anyone’s at all interested to dig through the source feel free. All the code is inline in the head of the demo page

DELETE ... FROM ... WHERE ... IN

The canonical T-SQL (SqlServer) answer is to use a DELETE with JOIN as such

DELETE o
FROM Orders o
INNER JOIN Customers c
    ON o.CustomerId = c.CustomerId
WHERE c.FirstName = 'sklivvz'

This will delete all orders which have a customer with first name Sklivvz.

How to check string length and then select substring in Sql Server

To conditionally check the length of the string, use CASE.

SELECT  CASE WHEN LEN(comments) <= 60 
             THEN comments
             ELSE LEFT(comments, 60) + '...'
        END  As Comments
FROM    myView

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

I've modified the version above to run for all tables and support new SQL 2005 data types. It also retains the primary key names. Works only on SQL 2005 (using cross apply).


select  'create table [' + so.name + '] (' + o.list + ')' + CASE WHEN tc.Constraint_Name IS NULL THEN '' ELSE 'ALTER TABLE ' + so.Name + ' ADD CONSTRAINT ' + tc.Constraint_Name  + ' PRIMARY KEY ' + ' (' + LEFT(j.List, Len(j.List)-1) + ')' END
from    sysobjects so
cross apply
    (SELECT 
        '  ['+column_name+'] ' + 
        data_type + case data_type
            when 'sql_variant' then ''
            when 'text' then ''
            when 'ntext' then ''
            when 'xml' then ''
            when 'decimal' then '(' + cast(numeric_precision as varchar) + ', ' + cast(numeric_scale as varchar) + ')'
            else coalesce('('+case when character_maximum_length = -1 then 'MAX' else cast(character_maximum_length as varchar) end +')','') end + ' ' +
        case when exists ( 
        select id from syscolumns
        where object_name(id)=so.name
        and name=column_name
        and columnproperty(id,name,'IsIdentity') = 1 
        ) then
        'IDENTITY(' + 
        cast(ident_seed(so.name) as varchar) + ',' + 
        cast(ident_incr(so.name) as varchar) + ')'
        else ''
        end + ' ' +
         (case when UPPER(IS_NULLABLE) = 'NO' then 'NOT ' else '' end ) + 'NULL ' + 
          case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT ELSE '' END + ', ' 

     from information_schema.columns where table_name = so.name
     order by ordinal_position
    FOR XML PATH('')) o (list)
left join
    information_schema.table_constraints tc
on  tc.Table_name       = so.Name
AND tc.Constraint_Type  = 'PRIMARY KEY'
cross apply
    (select '[' + Column_Name + '], '
     FROM   information_schema.key_column_usage kcu
     WHERE  kcu.Constraint_Name = tc.Constraint_Name
     ORDER BY
        ORDINAL_POSITION
     FOR XML PATH('')) j (list)
where   xtype = 'U'
AND name    NOT IN ('dtproperties')

Update: Added handling of the XML data type

Update 2: Fixed cases when 1) there is multiple tables with the same name but with different schemas, 2) there is multiple tables having PK constraint with the same name

Oracle - What TNS Names file am I using?

Oracle provides a utility called tnsping:

R:\>tnsping someconnection

TNS Ping Utility for 32-bit Windows: Version 9.0.1.3.1 - Production on 27-AUG-20
08 10:38:07

Copyright (c) 1997 Oracle Corporation.  All rights reserved.

Used parameter files:
C:\Oracle92\network\ADMIN\sqlnet.ora
C:\Oracle92\network\ADMIN\tnsnames.ora

TNS-03505: Failed to resolve name

R:\>


R:\>tnsping entpr01

TNS Ping Utility for 32-bit Windows: Version 9.0.1.3.1 - Production on 27-AUG-20
08 10:39:22

Copyright (c) 1997 Oracle Corporation.  All rights reserved.

Used parameter files:
C:\Oracle92\network\ADMIN\sqlnet.ora
C:\Oracle92\network\ADMIN\tnsnames.ora

Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (COMMUNITY = **)
 (PROTOCOL = TCP) (Host = ****) (Port = 1521))) (CONNECT_DATA = (SID = ENTPR0
1)))
OK (40 msec)

R:\>

This should show what file you're using. The utility sits in the Oracle bin directory.

Delete/Reset all entries in Core Data?

You can delete the SQLite file - but I choose to do it by purging the tables individually with a functions:

- (void) deleteAllObjects: (NSString *) entityDescription  {
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:entityDescription inManagedObjectContext:_managedObjectContext];
    [fetchRequest setEntity:entity];

    NSError *error;
    NSArray *items = [_managedObjectContext executeFetchRequest:fetchRequest error:&error];
    [fetchRequest release];


    for (NSManagedObject *managedObject in items) {
        [_managedObjectContext deleteObject:managedObject];
        DLog(@"%@ object deleted",entityDescription);
    }
    if (![_managedObjectContext save:&error]) {
        DLog(@"Error deleting %@ - error:%@",entityDescription,error);
    }

}

The reason I chose to do it table by table is that it makes me confirm as I am doing the programming that deleting the contents of the table is sensible and there is not data that I would rather keep.

Doing it this will is much slower than just deleting the file and I will change to a file delete if I this method takes too long.

Server http:/localhost:8080 requires a user name and a password. The server says: XDB

I was facing the same problem, I just change the jboss7.1 port from 8080 to 9090. and it worked perfectly for me. To change the jboss7.1 port go to jboss-as-7.1.0.Final\standalone\configuration open standalone.xml look for the line <socket-binding name="http" port="8080"/> change 8080 to 9090. save the file and Restart the server. it should work

Remove Select arrow on IE

In case you want to use the class and pseudo-class:

.simple-control is your css class

:disabled is pseudo class

select.simple-control:disabled{
         /*For FireFox*/
        -webkit-appearance: none;
        /*For Chrome*/
        -moz-appearance: none;
}

/*For IE10+*/
select:disabled.simple-control::-ms-expand {
        display: none;
}

HTML Input Type Date, Open Calendar by default

This is not possible with native HTML input elements. You can use webshim polyfill, which gives you this option by using this markup.

<input type="date" data-date-inline-picker="true" />

Here is a small demo

Java Calendar, getting current month value, clarification needed

as others said Calendar.MONTH returns int and is zero indexed.

to get the current month as a String use SimpleDateFormat.format() method

Calendar cal = Calendar.getInstance();
System.out.println(new SimpleDateFormat("MMM").format(cal.getTime()));

returns NOV

ImportError: No module named mysql.connector using Python2

I was facing the similar issue. My env details - Python 2.7.11 pip 9.0.1 CentOS release 5.11 (Final)

Error on python interpreter -

>>> import mysql.connector
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named mysql.connector
>>>

Use pip to search the available module -

 $ pip search mysql-connector | grep --color mysql-connector-python



mysql-connector-python-rf (2.2.2)        - MySQL driver written in Python
mysql-connector-python (2.0.4)           - MySQL driver written in Python

Install the mysql-connector-python-rf -

$ pip install mysql-connector-python-rf

Verify

$ python
Python 2.7.11 (default, Apr 26 2016, 13:18:56)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-54)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mysql.connector
>>>

How do shift operators work in Java?

Right and Left shift work on same way here is How Right Shift works; The Right Shift: The right shift operator, >>, shifts all of the bits in a value to the right a specified number of times. Its general form:

value >> num

Here, num specifies the number of positions to right-shift the value in value. That is, the >> moves all of the bits in the specified value to the right the number of bit positions specified by num. The following code fragment shifts the value 32 to the right by two positions, resulting in a being set to 8:

int a = 32;
a = a >> 2; // a now contains 8

When a value has bits that are “shifted off,” those bits are lost. For example, the next code fragment shifts the value 35 to the right two positions, which causes the two low-order bits to be lost, resulting again in a being set to 8.

int a = 35;
a = a >> 2; // a still contains 8

Looking at the same operation in binary shows more clearly how this happens:

00100011 35 >> 2
00001000 8

Each time you shift a value to the right, it divides that value by two—and discards any remainder. You can take advantage of this for high-performance integer division by 2. Of course, you must be sure that you are not shifting any bits off the right end. When you are shifting right, the top (leftmost) bits exposed by the right shift are filled in with the previous contents of the top bit. This is called sign extension and serves to preserve the sign of negative numbers when you shift them right. For example, –8 >> 1 is –4, which, in binary, is

11111000 –8 >>1
11111100 –4

It is interesting to note that if you shift –1 right, the result always remains –1, since sign extension keeps bringing in more ones in the high-order bits. Sometimes it is not desirable to sign-extend values when you are shifting them to the right. For example, the following program converts a byte value to its hexadecimal string representation. Notice that the shifted value is masked by ANDing it with 0x0f to discard any sign-extended bits so that the value can be used as an index into the array of hexadecimal characters.

// Masking sign extension.
class HexByte {
  static public void main(String args[]) {
    char hex[] = {
      '0', '1', '2', '3', '4', '5', '6', '7',
      '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
    };
  byte b = (byte) 0xf1;
 System.out.println("b = 0x" + hex[(b >> 4) & 0x0f] + hex[b & 0x0f]);
}
}

Here is the output of this program:

b = 0xf1

Format cell if cell contains date less than today

=$W$4<=TODAY()

Returns true for dates up to and including today, false otherwise.

How to turn on WCF tracing?

The following configuration taken from MSDN can be applied to enable tracing on your WCF service.

<configuration>
  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel"
              switchValue="Information, ActivityTracing"
              propagateActivity="true" >
        <listeners>
             <add name="xml"/>
        </listeners>
      </source>
      <source name="System.ServiceModel.MessageLogging">
        <listeners>
            <add name="xml"/>
        </listeners>
      </source>
      <source name="myUserTraceSource"
              switchValue="Information, ActivityTracing">
        <listeners>
            <add name="xml"/>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
        <add name="xml"
             type="System.Diagnostics.XmlWriterTraceListener"
             initializeData="Error.svclog" />
    </sharedListeners>
  </system.diagnostics>
</configuration>

To view the log file, you can use "C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\SvcTraceViewer.exe".

If "SvcTraceViewer.exe" is not on your system, you can download it from the "Microsoft Windows SDK for Windows 7 and .NET Framework 4" package here:

Windows SDK Download

You don't have to install the entire thing, just the ".NET Development / Tools" part.

When/if it bombs out during installation with a non-sensical error, Petopas' answer to Windows 7 SDK Installation Failure solved my issue.

Show compose SMS view in Android

Some of what is explained above is meant only for placing an SMS in a 'ready to launch' state. as Senthil Mg said you can use sms manager to send the sms directly but SMSManager has been moved to android.telephony.SmsManager

I know it's not a lot of more info, but it might help someone some day.

Create listview in fragment android

Instead:

public class PhotosFragment extends Fragment

You can use:

public class PhotosFragment extends ListFragment

It change the methods

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ArrayList<ListviewContactItem> listContact = GetlistContact();
        setAdapter(new ListviewContactAdapter(getActivity(), listContact));
    }

onActivityCreated is void and you didn't need to return a view like in onCreateView

You can see an example here

How can I get the current array index in a foreach loop?

foreach($array as $key=>$value) {
    // do stuff
}

$key is the index of each $array element

How do I properly escape quotes inside HTML attributes?

If you are using Javascript and Lodash, then you can use _.escape(), which escapes ", ', <, >, and &.

See here: https://lodash.com/docs/#escape

What are good ways to prevent SQL injection?

SQL injection should not be prevented by trying to validate your input; instead, that input should be properly escaped before being passed to the database.

How to escape input totally depends on what technology you are using to interface with the database. In most cases and unless you are writing bare SQL (which you should avoid as hard as you can) it will be taken care of automatically by the framework so you get bulletproof protection for free.

You should explore this question further after you have decided exactly what your interfacing technology will be.

What is the proper way to check if a string is empty in Perl?

To check for an empty string you could also do something as follows

if (!defined $val || $val eq '')
{
    # empty
}

Python sum() function with list parameter

Have you used the variable sum anywhere else? That would explain it.

>>> sum = 1
>>> numbers = [1, 2, 3]
>>> numsum = (sum(numbers))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

The name sum doesn't point to the function anymore now, it points to an integer.

Solution: Don't call your variable sum, call it total or something similar.

What is the difference between FragmentPagerAdapter and FragmentStatePagerAdapter?

Something that is not explicitly said in the documentation or in the answers on this page (even though implied by @Naruto), is that FragmentPagerAdapter will not update the Fragments if the data in the Fragment changes because it keeps the Fragment in memory.

So even if you have a limited number of Fragments to display, if you want to be able to refresh your fragments (say for example you re-run the query to update the listView in the Fragment), you need to use FragmentStatePagerAdapter.

My whole point here is that the number of Fragments and whether or not they are similar is not always the key aspect to consider. Whether or not your fragments are dynamic is also key.

Broken references in Virtualenvs

The accepted answer does not work for me: the file $WORKON_HOME/*/bin/python2.7 is no longer a symlink, it is a full-fledged executable:

$ file $WORKON_HOME/*/bin/python2.7
/Users/sds/.virtualenvs/.../bin/python2.7: Mach-O 64-bit executable x86_64
...

The solution is, alas, to completely remove and re-create from scratch all the virtual environments.

For the reference:

deactivate
pip install --user virtualenv virtualenvwrapper
pip install --user --upgrade virtualenv virtualenvwrapper
for ve in $(lsvirtualenv -b); do
  # assume that each VE is associated with a project
  # and the project has the requirements.txt file
  project=$(cat $WORKON_HOME/$ve/.project)
  rmvirtualenv $ve
  mkvirtualenv -a $project -r requirements.txt $ve
done

Visual Studio 2015 doesn't have cl.exe

In Visual Studio 2019 you can find cl.exe inside

32-BIT : C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.20.27508\bin\Hostx86\x86
64-BIT : C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.20.27508\bin\Hostx64\x64

Before trying to compile either run vcvars32 for 32-Bit compilation or vcvars64 for 64-Bit.

32-BIT : "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars32.bat"
64-BIT : "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat"

If you can't find the file or the directory, try going to C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC and see if you can find a folder with a version number. If you can't, then you probably haven't installed C++ through the Visual Studio Installation yet.

Print string to text file

In case you want to pass multiple arguments you can use a tuple

price = 33.3
with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: %s price %f" % (TotalAmount, price))

More: Print multiple arguments in python

Image is not showing in browser?

I had a problem where the images would not show and it wasn't the relative path. I even hard coded the actual path and the image still did not show. I had changed my webserver to run on port 8080 and neither

<img src="c:/public/images/<?php echo $image->filename; ?>" width="100" />
<img src="c:/public/images/mypic.jpg" width="100" />

would not work.

<img src="../../images/<?php echo $photo->filename; ?>" width="100" />

Did not work either. This did work :

<img src="http://localhost:8080/public/images/<?php echo $image->filename; ?>" width="100" />

.htaccess deny from all

You can edit it. The content of the file is literally "Deny from all" which is an Apache directive: http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html#deny

How can I get the current class of a div with jQuery?

var classname=$('#div1').attr('class')

Laravel: Using try...catch with DB::transaction()

If you use PHP7, use Throwable in catch for catching user exceptions and fatal errors.

For example:

DB::beginTransaction();

try {
    DB::insert(...);    
    DB::commit();
} catch (\Throwable $e) {
    DB::rollback();
    throw $e;
}

If your code must be compartable with PHP5, use Exception and Throwable:

DB::beginTransaction();

try {
    DB::insert(...);    
    DB::commit();
} catch (\Exception $e) {
    DB::rollback();
    throw $e;
} catch (\Throwable $e) {
    DB::rollback();
    throw $e;
}

jQuery Refresh/Reload Page if Ajax Success after time

In your ajax success callback do this:

success: function(data){
   if(data.success == true){ // if true (1)
      setTimeout(function(){// wait for 5 secs(2)
           location.reload(); // then reload the page.(3)
      }, 5000); 
   }
}

As you want to reload the page after 5 seconds, then you need to have a timeout as suggested in the answer.

Determining whether an object is a member of a collection in VBA

I created this solution from the above suggestions mixed with microsofts solution of for iterating through a collection.

Public Function InCollection(col As Collection, Optional vItem, Optional vKey) As Boolean
On Error Resume Next

Dim vColItem As Variant

InCollection = False

If Not IsMissing(vKey) Then
    col.item vKey

    '5 if not in collection, it is 91 if no collection exists
    If Err.Number <> 5 And Err.Number <> 91 Then
        InCollection = True
    End If
ElseIf Not IsMissing(vItem) Then
    For Each vColItem In col
        If vColItem = vItem Then
            InCollection = True
            GoTo Exit_Proc
        End If
    Next vColItem
End If

Exit_Proc:
Exit Function
Err_Handle:
Resume Exit_Proc
End Function

SVN remains in conflict?

I guess the proper solution is:

(1) backup your-file/your-directory
(2) svn revert your-file/your-directory
(3) svn update your-file/your-directory
(4) Merge the backup your-file/your-directory to the updated one.
(5) svn ci -m "My work here is done"