Programs & Examples On #Highlighter.net

How do I dynamically change the content in an iframe using jquery?

If you just want to change where the iframe points to and not the actual content inside the iframe, you would just need to change the src attribute.

 $("#myiframe").attr("src", "newwebpage.html");

Flatten an irregular list of lists

Here's the compiler.ast.flatten implementation in 2.7.5:

def flatten(seq):
    l = []
    for elt in seq:
        t = type(elt)
        if t is tuple or t is list:
            for elt2 in flatten(elt):
                l.append(elt2)
        else:
            l.append(elt)
    return l

There are better, faster methods (If you've reached here, you have seen them already)

Also note:

Deprecated since version 2.6: The compiler package has been removed in Python 3.

Embed an External Page Without an Iframe?

HTML Imports, part of the Web Components cast, is also a way to include HTML documents in other HTML documents. See http://www.html5rocks.com/en/tutorials/webcomponents/imports/

How to get attribute of element from Selenium?

As the recent developed Web Applications are using JavaScript, jQuery, AngularJS, ReactJS etc there is a possibility that to retrieve an attribute of an element through Selenium you have to induce WebDriverWait to synchronize the WebDriver instance with the lagging Web Client i.e. the Web Browser before trying to retrieve any of the attributes.

Some examples:

  • Python:

    • To retrieve any attribute form a visible element (e.g. <h1> tag) you need to use the expected_conditions as visibility_of_element_located(locator) as follows:

      attribute_value = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.ID, "org"))).get_attribute("attribute_name")
      
    • To retrieve any attribute form an interactive element (e.g. <input> tag) you need to use the expected_conditions as element_to_be_clickable(locator) as follows:

      attribute_value = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "org"))).get_attribute("attribute_name")
      

HTML Attributes

Below is a list of some attributes often used in HTML

HTML Attributes

Note: A complete list of all attributes for each HTML element, is listed in: HTML Attribute Reference

Direct download from Google Drive using Google Drive API

If you face the "This file cannot be checked for viruses" intermezzo page, the download is not that easy.

You essentially need to first download the normal download link, which however redirects you to the "Download anyway" page. You need to store cookies from this first request, find out the link pointed to by the "Download anyway" button, and then use this link to download the file, but reusing the cookies you got from the first request.

Here's a bash variant of the download process using CURL:

curl -c /tmp/cookies "https://drive.google.com/uc?export=download&id=DOCUMENT_ID" > /tmp/intermezzo.html
curl -L -b /tmp/cookies "https://drive.google.com$(cat /tmp/intermezzo.html | grep -Po 'uc-download-link" [^>]* href="\K[^"]*' | sed 's/\&amp;/\&/g')" > FINAL_DOWNLOADED_FILENAME

Notes:

  • this procedure will probably stop working after some Google changes
  • the grep command uses Perl syntax (-P) and the \K "operator" which essentially means "do not include anything preceding \K to the matched result. I don't know which version of grep introduced these options, but ancient or non-Ubuntu versions probably don't have it
  • a Java solution would be more or less the same, just take a HTTPS library which can handle cookies, and some nice text-parsing library

Java: How to check if object is null?

DIY

private boolean isNull(Object obj) {
    return obj == null;
}

Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath());
if (isNull(drawable)) {
    drawable = getRandomDrawable();
}

What is the purpose of the vshost.exe file?

The vshost.exe file is the executable run by Visual Studio (Visual Studio host executable). This is the executable that links to Visual Studio and improves debugging.

When you're distributing your application to others, you do not use the vshost.exe or .pdb (debug database) files.

How Long Does it Take to Learn Java for a Complete Newbie?

10 weeks? Apparently you can do it in 24 hours!

http://www.amazon.com/Sams-Teach-Yourself-Programming-Hours/dp/0672328445

EDIT:

Okay, so only 1 person found my answer amusing, but not amusing enough to upvote. The real question is how good do you need to be in 10 weeks?

If you get yourself a good book (the one linked above has some good reviews on Amazon), then in 10 weeks you might be proficient enough to do something useful in Java, but it takes years to become expert. Any time spent between 10 weeks and several years will move you from beginner towards expert.

Oh and read Teach Yourself Programming in Ten Years.

Checking if a key exists in a JavaScript object?

Checking for undefined-ness is not an accurate way of testing whether a key exists. What if the key exists but the value is actually undefined?

var obj = { key: undefined };
obj["key"] !== undefined // false, but the key exists!

You should instead use the in operator:

"key" in obj // true, regardless of the actual value

If you want to check if a key doesn't exist, remember to use parenthesis:

!("key" in obj) // true if "key" doesn't exist in object
!"key" in obj   // Do not do this! It is equivalent to "false in obj"

Or, if you want to particularly test for properties of the object instance (and not inherited properties), use hasOwnProperty:

obj.hasOwnProperty("key") // true

For performance comparison between the methods that are in, hasOwnProperty and key is undefined, see this benchmark

How to convert date to timestamp in PHP?

Using strtotime() function you can easily convert date to timestamp

<?php
// set default timezone
date_default_timezone_set('America/Los_Angeles');

//define date and time
$date = date("d M Y H:i:s");

// output
echo strtotime($date);
?> 

More info: http://php.net/manual/en/function.strtotime.php

Online conversion tool: http://freeonlinetools24.com/

Hex colors: Numeric representation for "transparent"?

I was also trying for transparency - maybe you could try leaving blank the value of background e.g. something like

bgcolor=" "

How to make a parent div auto size to the width of its children divs

Your interior <div> elements should likely both be float:left. Divs size to 100% the size of their container width automatically. Try using display:inline-block instead of width:auto on the container div. Or possibly float:left the container and also apply overflow:auto. Depends on what you're after exactly.

How can I format DateTime to web UTC format?

Try this:

DateTime date = DateTime.ParseExact(
    "Tue, 1 Jan 2008 00:00:00 UTC", 
    "ddd, d MMM yyyy HH:mm:ss UTC", 
    CultureInfo.InvariantCulture);

Previously asked question

java.math.BigInteger cannot be cast to java.lang.Integer

As we see from the javaDoc, BigInteger is not a subclass of Integer:

java.lang.Object                      java.lang.Object
   java.lang.Number                       java.lang.Number
      java.math.BigInteger                    java.lang.Integer

And that's the reason why casting from BigInteger to Integer is impossible.

Casting of java primitives will do some conversion (like casting from double to int) while casting of types will never transform classes.

How to write log to file

To help others, I create a basic log function to handle the logging in both cases, if you want the output to stdout, then turn debug on, its straight forward to do a switch flag so you can choose your output.

func myLog(msg ...interface{}) {
    defer func() { r := recover(); if r != nil { fmt.Print("Error detected logging:", r) } }()
    if conf.DEBUG {
        fmt.Println(msg)
    } else {
        logfile, err := os.OpenFile(conf.LOGDIR+"/"+conf.AppName+".log", os.O_RDWR | os.O_CREATE | os.O_APPEND,0666)
        if !checkErr(err) {
            log.SetOutput(logfile)
            log.Println(msg)
        }
        defer logfile.Close()
    }
}




How to impose maxlength on textArea in HTML using JavaScript

Try to use this code example:

$("#TextAreaID1").bind('input propertychange', function () {
    var maxLength = 4000;
    if ($(this).val().length > maxLength) {
        $(this).val($(this).val().substring(0, maxLength));
    }
});

logger configuration to log to file and print to stdout

Just get a handle to the root logger and add the StreamHandler. The StreamHandler writes to stderr. Not sure if you really need stdout over stderr, but this is what I use when I setup the Python logger and I also add the FileHandler as well. Then all my logs go to both places (which is what it sounds like you want).

import logging
logging.getLogger().addHandler(logging.StreamHandler())

If you want to output to stdout instead of stderr, you just need to specify it to the StreamHandler constructor.

import sys
# ...
logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))

You could also add a Formatter to it so all your log lines have a common header.

ie:

import logging
logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s]  %(message)s")
rootLogger = logging.getLogger()

fileHandler = logging.FileHandler("{0}/{1}.log".format(logPath, fileName))
fileHandler.setFormatter(logFormatter)
rootLogger.addHandler(fileHandler)

consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(logFormatter)
rootLogger.addHandler(consoleHandler)

Prints to the format of:

2012-12-05 16:58:26,618 [MainThread  ] [INFO ]  my message

How do I get the Back Button to work with an AngularJS ui-router state machine?

app.run(['$window', '$rootScope', 
function ($window ,  $rootScope) {
  $rootScope.goBack = function(){
    $window.history.back();
  }
}]);

<a href="#" ng-click="goBack()">Back</a>

How to format string to money

//Extra currency symbol and currency formatting: "€3,311.50":
String result = (Decimal.Parse("000000331150") / 100).ToString("C");

//No currency symbol and no currency formatting: "3311.50"
String result = (Decimal.Parse("000000331150") / 100).ToString("f2");

Python Checking a string's first and last character

When you say [:-1] you are stripping the last element. Instead of slicing the string, you can apply startswith and endswith on the string object itself like this

if str1.startswith('"') and str1.endswith('"'):

So the whole program becomes like this

>>> str1 = '"xxx"'
>>> if str1.startswith('"') and str1.endswith('"'):
...     print "hi"
>>> else:
...     print "condition fails"
...
hi

Even simpler, with a conditional expression, like this

>>> print("hi" if str1.startswith('"') and str1.endswith('"') else "fails")
hi

List of ANSI color escape sequences

For these who don't get proper results other than mentioned languages, if you're using C# to print a text into console(terminal) window you should replace "\033" with "\x1b". In Visual Basic it would be Chrw(27).

How can I schedule a daily backup with SQL Server Express?

Eduardo Molteni had a great answer:

Using Windows Scheduled Tasks:

In the batch file

"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLCMD.EXE" -S 
(local)\SQLExpress -i D:\dbbackups\SQLExpressBackups.sql

In SQLExpressBackups.sql

BACKUP DATABASE MyDataBase1 TO  DISK = N'D:\DBbackups\MyDataBase1.bak' 
WITH NOFORMAT, INIT,  NAME = N'MyDataBase1 Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10

BACKUP DATABASE MyDataBase2 TO  DISK = N'D:\DBbackups\MyDataBase2.bak' 
WITH NOFORMAT, INIT,  NAME = N'MyDataBase2 Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10

GO

Run AVD Emulator without Android Studio

The path for emulator is

/Users/<Username>/AppData/Local/Android/sdk/tools

Table-level backup

This is similar to qntmfred's solution, but using a direct table dump. This option is slightly faster (see BCP docs):

to export:

bcp "[MyDatabase].dbo.Customer " out "Customer.bcp" -N -S localhost -T -E

to import:

bcp [MyDatabase].dbo.Customer in "Customer.bcp" -N -S localhost -T -E -b 10000

Xcode 6 Storyboard the wrong size?

In Storyboard, select your ViewController and go to Atribute Inspector. At the very top, under Simulated Metrics you have Size and Orientation properties which are set to Inferred. Change them to desired values.

In order for an application to display properly on another screen size, you also have to setup constraints, as described by Can Poyrazoglu in the first post.

ORDER BY date and time BEFORE GROUP BY name in mysql

Use a subselect:

select name, date, time
from mytable main
where date + time = (select min(date + time) from mytable where name = main.mytable)
order by date + time;

Photoshop text tool adds punctuation to the beginning of text

You can try : go to edit>preferencec>type.. select type > choose text engine options select east asian. Restart photoshop. Create new peroject. Try text tool again.

(if you want to use your project created with other text engine type) copy /paste all layers to new project.

How to call Stored Procedures with EntityFramework?

Basically you just have to map the procedure to the entity using Stored Procedure Mapping.

Once mapped, you use the regular method for adding an item in EF, and it will use your stored procedure instead.

Please see: This Link for a walkthrough. The result will be adding an entity like so (which will actually use your stored procedure)

using (var ctx = new SchoolDBEntities())
        {
            Student stud = new Student();
            stud.StudentName = "New sp student";
            stud.StandardId = 262;

            ctx.Students.Add(stud);
            ctx.SaveChanges();
        }

Login failed for user 'IIS APPPOOL\ASP.NET v4.0'

You can change the ApplicationPoolIdentity from IIS7 -> Application Pools -> Advanced Settings. AdvancedSettings

Under ApplicationPoolIdentity you will find local system. This will make your application run under NT AUTHORITY\SYSTEM, which is an existing login for the database by default.

Edit: Before applying this suggestion you should note and understand the security implications.

git: How to diff changed files versus previous versions after a pull?

If you do a straight git pull then you will either be 'fast-forwarded' or merge an unknown number of commits from the remote repository. This happens as one action though, so the last commit that you were at immediately before the pull will be the last entry in the reflog and can be accessed as HEAD@{1}. This means that you can do:

git diff HEAD@{1}

However, I would strongly recommend that if this is something you find yourself doing a lot then you should consider just doing a git fetch and examining the fetched branch before manually merging or rebasing onto it. E.g. if you're on master and were going to pull in origin/master:

git fetch

git log HEAD..origin/master

 # looks good, lets merge

git merge origin/master

What is the App_Data folder used for in Visual Studio?

We use it as a temporary storage area for uploaded csv files. Once uploaded, an ajax method processes and deletes the file.

What is the use of System.in.read()?

System is a final class in java.lang package

code sample from the source code of api

public final class System {

   /**
     * The "standard" input stream. This stream is already
     * open and ready to supply input data. Typically this stream
     * corresponds to keyboard input or another input source specified by
     * the host environment or user.
     */
    public final static InputStream in = nullInputStream();

}

read() is an abstract method of abstract class InputStream

 /**
     * Reads the next byte of data from the input stream. The value byte is
     * returned as an <code>int</code> in the range <code>0</code> to
     * <code>255</code>. If no byte is available because the end of the stream
     * has been reached, the value <code>-1</code> is returned. This method
     * blocks until input data is available, the end of the stream is detected,
     * or an exception is thrown.
     *
     * <p> A subclass must provide an implementation of this method.
     *
     * @return     the next byte of data, or <code>-1</code> if the end of the
     *             stream is reached.
     * @exception  IOException  if an I/O error occurs.
     */
    public abstract int read() throws IOException;

In short from the api:

Reads some number of bytes from the input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer. This method blocks until input data is available, end of file is detected, or an exception is thrown.

from InputStream.html#read()

Include of non-modular header inside framework module

try @import FrameworkName instead of #import "FrameworkName.h"

How do you run a single query through mysql from the command line?

here's how you can do it with a cool shell trick:

mysql -uroot -p -hslavedb.mydomain.com mydb_production <<< 'select * from users'

'<<<' instructs the shell to take whatever follows it as stdin, similar to piping from echo.

use the -t flag to enable table-format output

Postgres could not connect to server

Just two steps to run the database after the Installation (Before that ensure your logged as postgres user)

Installed-Dirs/bin/postmaster -D Installed-Dirs/pgsql/data

For an example:

[postgres@localhost bin]$ /usr/local/pgsql/bin/postmaster -D /usr/local/pgsql/data

Step-2 : Run psql from the Installed path (To check where you installed '#which postgres' will use to find out the installed location)

[postgres@localhost bin]$ psql 

What is the correct way to free memory in C#

  1. Yes
  2. What do you mean by the same? It will be re-executed every time the method is run.
  3. Yes, the .Net garbage collector uses an algorithm that starts with any global/in-scope variables, traverses them while following any reference it finds recursively, and deletes any object in memory deemed to be unreachable. see here for more detail on Garbage Collection
  4. Yes, the memory from all variables declared in a method is released when the method exits as they are all unreachable. In addition, any variables that are declared but never used will be optimized out by the compiler, so in reality your Foo variable will never ever take up memory.
  5. the using statement simply calls dispose on an IDisposable object when it exits, so this is equivalent to your second bullet point. Both will indicate that you are done with the object and tell the GC that you are ready to let go of it. Overwriting the only reference to the object will have a similar effect.

#pragma pack effect

I have seen people use it to make sure that a structure takes a whole cache line to prevent false sharing in a multithreaded context. If you are going to have a large number of objects that are going to be loosely packed by default it could save memory and improve cache performance to pack them tighter, though unaligned memory access will usually slow things down so there might be a downside.

How to secure MongoDB with username and password

This is what i did for ubuntu 20.04 and mongodb enterprise 4.4.2:

  1. start mongo shell by typing mongo in terminal.

  2. use admin database:

use admin
  1. create a new user and assign your intended role:
use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: passwordPrompt(), // or cleartext password
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
  }
)
  1. exit mongo and add the following line to etc/mongod.conf:
security:
    authorization: enabled
  1. restart mongodb server

(optional) 6.If you want your user to have root access you can either specify it when creating your user like:

db.createUser(
  {
    user: "myUserAdmin",
    pwd: passwordPrompt(), // or cleartext password
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
  }
)

or you can change user role using:

db.grantRolesToUser('admin', [{ role: 'root', db: 'admin' }])

Android ADB stop application command like "force-stop" for non rooted device

If you have a rooted device you can use kill command

Connect to your device with adb:

adb shell

Once the session is established, you have to escalade privileges:

su

Then

ps

will list running processes. Note down the PID of the process you want to terminate. Then get rid of it

kill PID

How to query GROUP BY Month in a Year

For MS SQL you can do this.

    select  CAST(DATEPART(MONTH, DateTyme) as VARCHAR) +'/'+ 
CAST(DATEPART(YEAR, DateTyme) as VARCHAR) as 'Date' from #temp
    group by Name, CAST(DATEPART(MONTH, DateTyme) as VARCHAR) +'/'+
 CAST(DATEPART(YEAR, DateTyme) as VARCHAR) 

How to import a .cer certificate into a java keystore?

  • If you want to authenticate you need the private key - there is no other option.
  • A certificate is a public key with extra properties (like company name, country,...) that is signed by some Certificate authority that guarantees that the attached properties are true.
  • .CER files are certificates and don't have the private key. The private key is provided with a .PFX keystore file normally. If you really authenticate is because you already had imported the private key.
  • You normally can import .CER certificates without any problems with

    keytool -importcert -file certificate.cer -keystore keystore.jks -alias "Alias" 
    

Including a .js file within a .js file

The best solution for your browser load time would be to use a server side script to join them all together into one big .js file. Make sure to gzip/minify the final version. Single request - nice and compact.

Alternatively, you can use DOM to create a <script> tag and set the src property on it then append it to the <head>. If you need to wait for that functionality to load, you can make the rest of your javascript file be called from the load event on that script tag.

This function is based on the functionality of jQuery $.getScript()

function loadScript(src, f) {
  var head = document.getElementsByTagName("head")[0];
  var script = document.createElement("script");
  script.src = src;
  var done = false;
  script.onload = script.onreadystatechange = function() { 
    // attach to both events for cross browser finish detection:
    if ( !done && (!this.readyState ||
      this.readyState == "loaded" || this.readyState == "complete") ) {
      done = true;
      if (typeof f == 'function') f();
      // cleans up a little memory:
      script.onload = script.onreadystatechange = null;
      head.removeChild(script);
    }
  };
  head.appendChild(script);
}

// example:
loadScript('/some-other-script.js', function() { 
   alert('finished loading');
   finishSetup();
 });

What's HTML character code 8203?

If you're seeing these in a source be aware that it may be someone attempting to fingerprint text documents to reveal who is leaking information. It also may be an attempt to bypass a spam filter by making the same looking information different on a byte-by-byte level.

See my article on mitigating fingerprinting if you're interested in learning more.

How do I change JPanel inside a JFrame on the fly?

class Frame1 extends javax.swing.JFrame {

    remove(previouspanel); //or getContentPane().removeAll();

    add(newpanel); //or setContentPane(newpanel);

    invalidate(); validate(); // or ((JComponent) getContentPane()).revalidate();

    repaint(); //DO NOT FORGET REPAINT

}

Sometimes you can do the work without using the revalidation and sometimes without using the repaint.My advise use both.

Unable to login to SQL Server + SQL Server Authentication + Error: 18456

By default login failed error message is nothing but a client user connection has been refused by the server due to mismatch of login credentials. First task you might check is to see whether that user has relevant privileges on that SQL Server instance and relevant database too, thats good. Obviously if the necessary prvileges are not been set then you need to fix that issue by granting relevant privileges for that user login.

Althought if that user has relevant grants on database & server if the Server encounters any credential issues for that login then it will prevent in granting the authentication back to SQL Server, the client will get the following error message:

Msg 18456, Level 14, State 1, Server <ServerName>, Line 1
Login failed for user '<Name>'

Ok now what, by looking at the error message you feel like this is non-descriptive to understand the Level & state. By default the Operating System error will show 'State' as 1 regardless of nature of the issues in authenticating the login. So to investigate further you need to look at relevant SQL Server instance error log too for more information on Severity & state of this error. You might look into a corresponding entry in log as:

2007-05-17 00:12:00.34 Logon     Error: 18456, Severity: 14, State: 8.
or

2007-05-17 00:12:00.34 Logon     Login failed for user '<user name>'.

As defined above the Severity & State columns on the error are key to find the accurate reflection for the source of the problem. On the above error number 8 for state indicates authentication failure due to password mismatch. Books online refers: By default, user-defined messages of severity lower than 19 are not sent to the Microsoft Windows application log when they occur. User-defined messages of severity lower than 19 therefore do not trigger SQL Server Agent alerts.

Sung Lee, Program Manager in SQL Server Protocols (Dev.team) has outlined further information on Error state description:The common error states and their descriptions are provided in the following table:

ERROR STATE       ERROR DESCRIPTION
------------------------------------------------------------------------------
2 and 5           Invalid userid
6                 Attempt to use a Windows login name with SQL Authentication
7                 Login disabled and password mismatch
8                 Password mismatch
9                 Invalid password
11 and 12         Valid login but server access failure
13                SQL Server service paused
18                Change password required


Well I'm not finished yet, what would you do in case of error:

2007-05-17 00:12:00.34 Logon     Login failed for user '<user name>'.

You can see there is no severity or state level defined from that SQL Server instance's error log. So the next troubleshooting option is to look at the Event Viewer's security log [edit because screen shot is missing but you get the

idea, look in the event log for interesting events].

Undefined symbols for architecture armv7

I had this warning, when wrote two classes in .h file of another class, but FORGOT to write the implementation for this classes in .m file.

Cannot implicitly convert type 'int?' to 'int'.

The first problem encountered with your code is the message

Local variable OrdersPerHour might not be initialized before accessing.

It happens because in the case where your database query would throw an exception, the value might not be set to something (you have an empty catch clause).

To fix this, set the value to what you'd want to have if the query fails, which is probably 0 :

int? OrdersPerHour = 0;

Once this is fixed, now there's the error you're posting about. This happens because your method signature declares you are returning an int, but you are in fact returning a nullable int, int?, variable.

So to get the int part of your int?, you can use the .Value property:

return OrdersPerHour.Value;

However, if you declared your OrdersPerHour to be null at start instead of 0, the value can be null so a proper validation before returning is probably needed (Throw a more specific exception, for example).

To do so, you can use the HasValue property to be sure you're having a value before returning it:

if (OrdersPerHour.HasValue){
    return OrdersPerHour.Value;
}
else{
    // Handle the case here
}

As a side note, since you're coding in C# it would be better if you followed C#'s conventions. Your parameter and variables should be in camelCase, not PascalCase. So User and OrdersPerHour would be user and ordersPerHour.

Is there a way to rollback my last push to Git?

Since you are the only user:

git reset --hard HEAD@{1}
git push -f
git reset --hard HEAD@{1}

( basically, go back one commit, force push to the repo, then go back again - remove the last step if you don't care about the commit )

Without doing any changes to your local repo, you can also do something like:

git push -f origin <sha_of_previous_commit>:master

Generally, in published repos, it is safer to do git revert and then git push

How to embed fonts in CSS?

Go through http://www.w3.org/TR/css3-fonts/

Try this:

  @font-face {
        font-family: 'EntezareZohoor2';
        src: url('EntezareZohoor2.eot');
        src: local('EntezareZohoor2'), local('EntezareZohoor2'), url('EntezareZohoor2.ttf') format('svg');
       font-weight: normal;
       font-style: normal;
    }

How to deal with persistent storage (e.g. databases) in Docker

There are several levels of managing persistent data, depending on your needs:

  • Store it on your host
    • Use the flag -v host-path:container-path to persist container directory data to a host directory.
    • Backups/restores happen by running a backup/restore container (such as tutumcloud/dockup) mounted to the same directory.
  • Create a data container and mount its volumes to your application container
    • Create a container that exports a data volume, use --volumes-from to mount that data into your application container.
    • Backup/restore the same as the above solution.
  • Use a Docker volume plugin that backs an external/third-party service
    • Docker volume plugins allow your datasource to come from anywhere - NFS, AWS (S3, EFS, and EBS)
    • Depending on the plugin/service, you can attach single or multiple containers to a single volume.
    • Depending on the service, backups/restores may be automated for you.
    • While this can be cumbersome to do manually, some orchestration solutions - such as Rancher - have it baked in and simple to use.
    • Convoy is the easiest solution for doing this manually.

IE11 prevents ActiveX from running

Does IE11 displays any message relative to the blocked execution of your ActiveX ?

You should read this and this.

Use the following JS function to detect support of ActiveX :

function IsActiveXSupported() {
    var isSupported = false;

    if(window.ActiveXObject) {
        return true;
    }

    if("ActiveXObject" in window) {
        return true;
    }

    try {
        var xmlDom = new ActiveXObject("Microsoft.XMLDOM");
        isSupported = true;
    } catch (e) {
        if (e.name === "TypeError" || e.name === "Error") {
            isSupported = true;
        }
    }

    return isSupported;
}

Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time

The System.out.println(cal_Two.getTime()) invocation returns a Date from getTime(). It is the Date which is getting converted to a string for println, and that conversion will use the default IST timezone in your case.

You'll need to explicitly use DateFormat.setTimeZone() to print the Date in the desired timezone.

EDIT: Courtesy of @Laurynas, consider this:

TimeZone timeZone = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(timeZone);
SimpleDateFormat simpleDateFormat = 
       new SimpleDateFormat("EE MMM dd HH:mm:ss zzz yyyy", Locale.US);
simpleDateFormat.setTimeZone(timeZone);

System.out.println("Time zone: " + timeZone.getID());
System.out.println("default time zone: " + TimeZone.getDefault().getID());
System.out.println();

System.out.println("UTC:     " + simpleDateFormat.format(calendar.getTime()));
System.out.println("Default: " + calendar.getTime());

How do you align left / right a div without using float?

You could just use a margin-left with a percentage.

HTML

<div class="goleft">Left Div</div>
<div class="goright">Right Div</div>

CSS

.goright{
    margin-left:20%;
}
.goleft{
    margin-right:20%;
}

(goleft would be the same as default, but can reverse if needed)

text-align doesn't always work as intended for layout options, it's mainly just for text. (But is often used for form elements too).

The end result of doing this will have a similar effect to a div with float:right; and width:80% set. Except, it won't clump together like a float will. (Saving the default display properties for the elements that come after).

Regex Last occurrence?

If you don't want to include the backslash, but only the text after it, try this: ([^\\]+)$ or for unix: ([^\/]+)$

Modifying location.hash without page scrolling

Erm I have a somewhat crude but definitely working method.
Just store the current scroll position in a temp variable and then reset it after changing the hash. :)

So for the original example:

$("#buttons li a").click(function(){
        $("#buttons li a").removeClass('selected');
        $(this).addClass('selected');

        var scrollPos = $(document).scrollTop();
        document.location.hash=$(this).attr("id")
        $(document).scrollTop(scrollPos);
});

Fastest method to replace all instances of a character in a string

Also you can try:

string.split('foo').join('bar');

Evaluate list.contains string in JSTL

<c:if test="${fn:contains(task.subscribers, customer)}">

This works fine for me.

Xcode doesn't see my iOS device but iTunes does

I just barely tried every solution suggested above. The only thing that worked and resolved my issue was to go into xcode's "Organizer", right click on my iPhone, click on "Remove from organizer" and then wait about 10 seconds while xcode automatically re-added the device.

I previously plugged in my phone and itunes recognized it fine and synced with it, etc, but all xcode said in the organizer was "Device is not currently connected", which it was most definitely connected if itunes was syncing with it and not syncing over wi-fi.

Why xcode needed me to delete and re-add the phone is beyond me, but it works great now that I did this.

Checking for #N/A in Excel cell from VBA code

First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.

If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
  If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
    'do something
  End If
End If

Laravel - Eloquent or Fluent random row

Use Laravel function

ModelName::inRandomOrder()->first();

manage.py runserver

in flask using flask.ext.script, you can do it like this:

python manage.py runserver -h 127.0.0.1 -p 8000

Understanding lambda in python and using it to pass multiple arguments

Why do you need to state both 'x' and 'y' before the ':'?

Because a lambda is (conceptually) the same as a function, just written inline. Your example is equivalent to

def f(x, y) : return x + y

just without binding it to a name like f.

Also how do you make it return multiple arguments?

The same way like with a function. Preferably, you return a tuple:

lambda x, y: (x+y, x-y)

Or a list, or a class, or whatever.

The thing with self.entry_1.bind should be answered by Demosthenex.

Generating CSV file for Excel, how to have a newline inside a value

You could use keyboard shortcut ALT+Enter.

  1. Select the cell you wish to edit
  2. enter edit mode either by double clicking it or pressing F2 3.Press Alt+enter. This will create a new line in cell

How to use DbContext.Database.SqlQuery<TElement>(sql, params) with stored procedure? EF Code First CTP5

Most answers are brittle because they rely on the order of the SP's parameters. Better to name the Stored Proc's params and give parameterized values to those.

In order to use Named params when calling your SP, without worrying about the order of parameters

Using SQL Server named parameters with ExecuteStoreQuery and ExecuteStoreCommand

Describes the best approach. Better than Dan Mork's answer here.

  • Doesn't rely on concatenating strings, and doesn't rely on the order of parameters defined in the SP.

E.g.:

var cmdText = "[DoStuff] @Name = @name_param, @Age = @age_param";
var sqlParams = new[]{
   new SqlParameter("name_param", "Josh"),
   new SqlParameter("age_param", 45)
};

context.Database.SqlQuery<myEntityType>(cmdText, sqlParams)

How to set custom location for local installation of npm package?

If you want this in config, you can set npm config like so:

npm config set prefix "$(pwd)/vendor/node_modules"

or

npm config set prefix "$HOME/vendor/node_modules"

Check your config with

npm config ls -l

Or as @pje says and use the --prefix flag

How to make child element higher z-index than parent?

Try using this code, it worked for me:

z-index: unset;

Undoing accidental git stash pop

If your merge was not too complicated another option would be to:

  1. Move all the changes including the merge changes back to stash using "git stash"
  2. Run the merge again and commit your changes (without the changes from the dropped stash)
  3. Run a "git stash pop" which should ignore all the changes from your previous merge since the files are identical now.

After that you are left with only the changes from the stash you dropped too early.

What is the garbage collector in Java?

Many people think garbage collection collects and discards dead objects.
In reality, Java garbage collection is doing the opposite! Live objects are tracked and everything else designated garbage.

When an object is no longer used, the garbage collector reclaims the underlying memory and reuses it for future object allocation. This means there is no explicit deletion and no memory is given back to the operating system. To determine which objects are no longer in use, the JVM intermittently runs what is very aptly called a mark-and-sweep algorithm.

Check this for more detail information: http://javabook.compuware.com/content/memory/how-garbage-collection-works.aspx

How to hide/show div tags using JavaScript?

Use the following code:

function hide {
document.getElementById('div').style.display = "none";
}
function show {
document.getElementById('div').style.display = "block";
}

How to force keyboard with numbers in mobile website in Android

Some browsers igoners sending leading zero to the server when the input type is "number". So I use a mixing of jquery and html to load a numeric keypad and also make sure that the value is sent as a text not as a number:

_x000D_
_x000D_
$(document).ready(function(){_x000D_
$(".numberonly").focus(function(){$(this).attr("type","number")});_x000D_
$(".numberonly").blur(function(){$(this).attr("type","text")});_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" class="numberonly">
_x000D_
_x000D_
_x000D_

HTML5 - mp4 video does not play in IE9

If it's still not working here's what may certainly be a solution: encode the mp4 with compression format H.264. If you encode it with format mpeg4 or divx or else it will not work on IE9 and may as well crash Google Chrome. To do that, I use Any Video Converter freeware. But it could be done with any good video tool out there.

I've been trying all solutions listed here and tried other workaround for days but the problem lied in the way I created my mp4. IE9 does not decode other format than H.264.

Hope this helps, Jimmy

RSA encryption and decryption in Python

In order to make it work you need to convert key from str to tuple before decryption(ast.literal_eval function). Here is fixed code:

import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random
import ast

random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate pub and priv key

publickey = key.publickey() # pub key export for exchange

encrypted = publickey.encrypt('encrypt this message', 32)
#message to encrypt is in the above line 'encrypt this message'

print 'encrypted message:', encrypted #ciphertext
f = open ('encryption.txt', 'w')
f.write(str(encrypted)) #write ciphertext to file
f.close()

#decrypted code below

f = open('encryption.txt', 'r')
message = f.read()


decrypted = key.decrypt(ast.literal_eval(str(encrypted)))

print 'decrypted', decrypted

f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()

Subtracting two lists in Python

You can use the map construct to do this. It looks quite ok, but beware that the map line itself will return a list of Nones.

a = [1, 2, 3]
b = [2, 3]

map(lambda x:a.remove(x), b)
a

.gitignore file for java eclipse project

You need to add your source files with git add or the GUI equivalent so that Git will begin tracking them.

Use git status to see what Git thinks about the files in any given directory.

MySQL Data - Best way to implement paging?

For 500 records efficiency is probably not an issue, but if you have millions of records then it can be advantageous to use a WHERE clause to select the next page:

SELECT *
FROM yourtable
WHERE id > 234374
ORDER BY id
LIMIT 20

The "234374" here is the id of the last record from the prevous page you viewed.

This will enable an index on id to be used to find the first record. If you use LIMIT offset, 20 you could find that it gets slower and slower as you page towards the end. As I said, it probably won't matter if you have only 200 records, but it can make a difference with larger result sets.

Another advantage of this approach is that if the data changes between the calls you won't miss records or get a repeated record. This is because adding or removing a row means that the offset of all the rows after it changes. In your case it's probably not important - I guess your pool of adverts doesn't change too often and anyway no-one would notice if they get the same ad twice in a row - but if you're looking for the "best way" then this is another thing to keep in mind when choosing which approach to use.

If you do wish to use LIMIT with an offset (and this is necessary if a user navigates directly to page 10000 instead of paging through pages one by one) then you could read this article about late row lookups to improve performance of LIMIT with a large offset.

Load HTML File Contents to Div [without the use of iframes]

Wow, from all the framework-promotional answers you'd think this was something JavaScript made incredibly difficult. It isn't really.

var xhr= new XMLHttpRequest();
xhr.open('GET', 'x.html', true);
xhr.onreadystatechange= function() {
    if (this.readyState!==4) return;
    if (this.status!==200) return; // or whatever error handling you want
    document.getElementById('y').innerHTML= this.responseText;
};
xhr.send();

If you need IE<8 compatibility, do this first to bring those browsers up to speed:

if (!window.XMLHttpRequest && 'ActiveXObject' in window) {
    window.XMLHttpRequest= function() {
        return new ActiveXObject('MSXML2.XMLHttp');
    };
}

Note that loading content into the page with scripts will make that content invisible to clients without JavaScript available, such as search engines. Use with care, and consider server-side includes if all you want is to put data in a common shared file.

Using android.support.v7.widget.CardView in my project (Eclipse)

Simply add the following line in your build.gradle project

dependencies {
    ...
    compile 'com.android.support:cardview-v7:24.0.0'
}

And sync the project with gradle.

Close application and launch home screen on Android

Start the second activity with startActivityForResult and in the second activity return a value, that once in the onActivityResult method of the first activity closes the main application. I think this is the correct way Android does it.

How do I set log4j level on the command line?

In my pretty standard setup I've been seeing the following work well when passed in as VM Option (commandline before class in Java, or VM Option in an IDE):

-Droot.log.level=TRACE

warning: Insecure world writable dir /usr/local/bin in PATH, mode 040777

Am using Mountain Lion. What I did was Look for /usr/local and Get Info. On it there is Sharing and Permissions. Make sure that its only the user and Admin are the only ones who have read and write permissions. Anyone else should have read access only. That sorted my problem.

Its normally helpful is your Run disk utilities and repair permissions too.

What does Maven do, in theory and in practice? When is it worth to use it?

What it does

Maven is a "build management tool", it is for defining how your .java files get compiled to .class, packaged into .jar (or .war or .ear) files, (pre/post)processed with tools, managing your CLASSPATH, and all others sorts of tasks that are required to build your project. It is similar to Apache Ant or Gradle or Makefiles in C/C++, but it attempts to be completely self-contained in it that you shouldn't need any additional tools or scripts by incorporating other common tasks like downloading & installing necessary libraries etc.

It is also designed around the "build portability" theme, so that you don't get issues as having the same code with the same buildscript working on one computer but not on another one (this is a known issue, we have VMs of Windows 98 machines since we couldn't get some of our Delphi applications compiling anywhere else). Because of this, it is also the best way to work on a project between people who use different IDEs since IDE-generated Ant scripts are hard to import into other IDEs, but all IDEs nowadays understand and support Maven (IntelliJ, Eclipse, and NetBeans). Even if you don't end up liking Maven, it ends up being the point of reference for all other modern builds tools.

Why you should use it

There are three things about Maven that are very nice.

  1. Maven will (after you declare which ones you are using) download all the libraries that you use and the libraries that they use for you automatically. This is very nice, and makes dealing with lots of libraries ridiculously easy. This lets you avoid "dependency hell". It is similar to Apache Ant's Ivy.

  2. It uses "Convention over Configuration" so that by default you don't need to define the tasks you want to do. You don't need to write a "compile", "test", "package", or "clean" step like you would have to do in Ant or a Makefile. Just put the files in the places in which Maven expects them and it should work off of the bat.

  3. Maven also has lots of nice plug-ins that you can install that will handle many routine tasks from generating Java classes from an XSD schema using JAXB to measuring test coverage with Cobertura. Just add them to your pom.xml and they will integrate with everything else you want to do.

The initial learning curve is steep, but (nearly) every professional Java developer uses Maven or wishes they did. You should use Maven on every project although don't be surprised if it takes you a while to get used to it and that sometimes you wish you could just do things manually, since learning something new sometimes hurts. However, once you truly get used to Maven you will find that build management takes almost no time at all.

How to Start

The best place to start is "Maven in 5 Minutes". It will get you start with a project ready for you to code in with all the necessary files and folders set-up (yes, I recommend using the quickstart archetype, at least at first).

After you get started you'll want a better understanding over how the tool is intended to be used. For that "Better Builds with Maven" is the most thorough place to understand the guts of how it works, however, "Maven: The Complete Reference" is more up-to-date. Read the first one for understanding, but then use the second one for reference.

Passing parameter to controller action from a Html.ActionLink

Addition to the accepted answer:

if you are going to use

 @Html.ActionLink("LinkName", "ActionName", "ControllerName", new { @id = idValue, @secondParam= = 2 },null)

this will create actionlink where you can't create new custom attribute or style for the link.

However, the 4th parameter in ActionLink extension will solve that problem. Use the 4th parameter for customization in your way.

 @Html.ActionLink("LinkName", "ActionName", "ControllerName", new { @id = idValue, @secondParam= = 2 }, new { @class = "btn btn-info", @target = "_blank" })

How to get current available GPUs in tensorflow?

Use this way and check all parts :

from __future__ import absolute_import, division, print_function, unicode_literals

import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds


version = tf.__version__
executing_eagerly = tf.executing_eagerly()
hub_version = hub.__version__
available = tf.config.experimental.list_physical_devices("GPU")

print("Version: ", version)
print("Eager mode: ", executing_eagerly)
print("Hub Version: ", h_version)
print("GPU is", "available" if avai else "NOT AVAILABLE")

How to download Google Play Services in an Android emulator?

To the latest setup and information if you have installed the Android Studio (i.e. 1.5) and trying to target SDK 4.0 then you may not be able to locate and setup the and AVD Emulator with SDK-vX.XX (with Google API's).

See following steps in order to download the required library and start with that. AVD Emulator setup -setting up Emulator for SDK4.0 with GoogleAPI so Map application can work- In Android Studio

But unfortunately above method did not work well on my side. And was not able to created Emulator with API Level 17 (SDK 4.2). So I followed this post that worked on my side well. The reason seems that the Android Studio Emulator creation window has limited options/features.

Google Play Services in emulator, implementing Google Plus login button etc

How to save as a new file and keep working on the original one in Vim?

After save new file press

Ctrl-6

This is shortcut to alternate file

How to apply box-shadow on all four sides?

The most simple solution and easiest way is to add shadow for all four side. CSS

box-shadow: 0 0 2px 2px #ccc; /* with blur shadow*/
box-shadow: 0 0 0 2px #ccc; /* without blur shadow*/

Inline labels in Matplotlib

Update: User cphyc has kindly created a Github repository for the code in this answer (see here), and bundled the code into a package which may be installed using pip install matplotlib-label-lines.


Pretty Picture:

semi-automatic plot-labeling

In matplotlib it's pretty easy to label contour plots (either automatically or by manually placing labels with mouse clicks). There does not (yet) appear to be any equivalent capability to label data series in this fashion! There may be some semantic reason for not including this feature which I am missing.

Regardless, I have written the following module which takes any allows for semi-automatic plot labelling. It requires only numpy and a couple of functions from the standard math library.

Description

The default behaviour of the labelLines function is to space the labels evenly along the x axis (automatically placing at the correct y-value of course). If you want you can just pass an array of the x co-ordinates of each of the labels. You can even tweak the location of one label (as shown in the bottom right plot) and space the rest evenly if you like.

In addition, the label_lines function does not account for the lines which have not had a label assigned in the plot command (or more accurately if the label contains '_line').

Keyword arguments passed to labelLines or labelLine are passed on to the text function call (some keyword arguments are set if the calling code chooses not to specify).

Issues

  • Annotation bounding boxes sometimes interfere undesirably with other curves. As shown by the 1 and 10 annotations in the top left plot. I'm not even sure this can be avoided.
  • It would be nice to specify a y position instead sometimes.
  • It's still an iterative process to get annotations in the right location
  • It only works when the x-axis values are floats

Gotchas

  • By default, the labelLines function assumes that all data series span the range specified by the axis limits. Take a look at the blue curve in the top left plot of the pretty picture. If there were only data available for the x range 0.5-1 then then we couldn't possibly place a label at the desired location (which is a little less than 0.2). See this question for a particularly nasty example. Right now, the code does not intelligently identify this scenario and re-arrange the labels, however there is a reasonable workaround. The labelLines function takes the xvals argument; a list of x-values specified by the user instead of the default linear distribution across the width. So the user can decide which x-values to use for the label placement of each data series.

Also, I believe this is the first answer to complete the bonus objective of aligning the labels with the curve they're on. :)

label_lines.py:

from math import atan2,degrees
import numpy as np

#Label line with line2D label data
def labelLine(line,x,label=None,align=True,**kwargs):

    ax = line.axes
    xdata = line.get_xdata()
    ydata = line.get_ydata()

    if (x < xdata[0]) or (x > xdata[-1]):
        print('x label location is outside data range!')
        return

    #Find corresponding y co-ordinate and angle of the line
    ip = 1
    for i in range(len(xdata)):
        if x < xdata[i]:
            ip = i
            break

    y = ydata[ip-1] + (ydata[ip]-ydata[ip-1])*(x-xdata[ip-1])/(xdata[ip]-xdata[ip-1])

    if not label:
        label = line.get_label()

    if align:
        #Compute the slope
        dx = xdata[ip] - xdata[ip-1]
        dy = ydata[ip] - ydata[ip-1]
        ang = degrees(atan2(dy,dx))

        #Transform to screen co-ordinates
        pt = np.array([x,y]).reshape((1,2))
        trans_angle = ax.transData.transform_angles(np.array((ang,)),pt)[0]

    else:
        trans_angle = 0

    #Set a bunch of keyword arguments
    if 'color' not in kwargs:
        kwargs['color'] = line.get_color()

    if ('horizontalalignment' not in kwargs) and ('ha' not in kwargs):
        kwargs['ha'] = 'center'

    if ('verticalalignment' not in kwargs) and ('va' not in kwargs):
        kwargs['va'] = 'center'

    if 'backgroundcolor' not in kwargs:
        kwargs['backgroundcolor'] = ax.get_facecolor()

    if 'clip_on' not in kwargs:
        kwargs['clip_on'] = True

    if 'zorder' not in kwargs:
        kwargs['zorder'] = 2.5

    ax.text(x,y,label,rotation=trans_angle,**kwargs)

def labelLines(lines,align=True,xvals=None,**kwargs):

    ax = lines[0].axes
    labLines = []
    labels = []

    #Take only the lines which have labels other than the default ones
    for line in lines:
        label = line.get_label()
        if "_line" not in label:
            labLines.append(line)
            labels.append(label)

    if xvals is None:
        xmin,xmax = ax.get_xlim()
        xvals = np.linspace(xmin,xmax,len(labLines)+2)[1:-1]

    for line,x,label in zip(labLines,xvals,labels):
        labelLine(line,x,label,align,**kwargs)

Test code to generate the pretty picture above:

from matplotlib import pyplot as plt
from scipy.stats import loglaplace,chi2

from labellines import *

X = np.linspace(0,1,500)
A = [1,2,5,10,20]
funcs = [np.arctan,np.sin,loglaplace(4).pdf,chi2(5).pdf]

plt.subplot(221)
for a in A:
    plt.plot(X,np.arctan(a*X),label=str(a))

labelLines(plt.gca().get_lines(),zorder=2.5)

plt.subplot(222)
for a in A:
    plt.plot(X,np.sin(a*X),label=str(a))

labelLines(plt.gca().get_lines(),align=False,fontsize=14)

plt.subplot(223)
for a in A:
    plt.plot(X,loglaplace(4).pdf(a*X),label=str(a))

xvals = [0.8,0.55,0.22,0.104,0.045]
labelLines(plt.gca().get_lines(),align=False,xvals=xvals,color='k')

plt.subplot(224)
for a in A:
    plt.plot(X,chi2(5).pdf(a*X),label=str(a))

lines = plt.gca().get_lines()
l1=lines[-1]
labelLine(l1,0.6,label=r'$Re=${}'.format(l1.get_label()),ha='left',va='bottom',align = False)
labelLines(lines[:-1],align=False)

plt.show()

img onclick call to JavaScript function

Well your onclick function works absolutely fine its your this line
window.external.values(a.value, b.value, c.value, d.value, e.value);

window.external is object and has no method name values

<html>
    <head>
     <script type="text/javascript">
          function exportToForm(a,b,c,d,e) {
             // window.external.values(a.value, b.value, c.value, d.value, e.value);
          //use alert to check its working 
         alert("HELLO");
}
      </script>
    </head>
    <body>
      <img onclick="exportToForm('1.6','55','10','50','1');" src="China-Flag-256.png"/>
      <button onclick="exportToForm('1.6','55','10','50','1');" style="background-color: #00FFFF">Export</button>
    </body>

    </html>

print arraylist element?

Here is an updated solution for Java8, using lambdas and streams:

System.out.println(list.stream()
                       .map(Object::toString)
                       .collect(Collectors.joining("\n")));

Or, without joining the list into one large string:

list.stream().forEach(System.out::println);

How do you migrate an IIS 7 site to another server?

I'd say export your server config in IIS manager:

  1. In IIS manager, click the Server node
  2. Go to Shared Configuration under "Management"
  3. Click “Export Configuration”. (You can use a password if you are sending them across the internet, if you are just gonna move them via a USB key then don't sweat it.)
  4. Move these files to your new server

    administration.config
    applicationHost.config
    configEncKey.key 
    
  5. On the new server, go back to the “Shared Configuration” section and check “Enable shared configuration.” Enter the location in physical path to these files and apply them.

  6. It should prompt for the encryption password(if you set it) and reset IIS.

BAM! Go have a beer!

Difference between volatile and synchronized in Java

volatile is a field modifier, while synchronized modifies code blocks and methods. So we can specify three variations of a simple accessor using those two keywords:

    int i1;
    int geti1() {return i1;}

    volatile int i2;
    int geti2() {return i2;}

    int i3;
    synchronized int geti3() {return i3;}

geti1() accesses the value currently stored in i1 in the current thread. Threads can have local copies of variables, and the data does not have to be the same as the data held in other threads.In particular, another thread may have updated i1 in it's thread, but the value in the current thread could be different from that updated value. In fact Java has the idea of a "main" memory, and this is the memory that holds the current "correct" value for variables. Threads can have their own copy of data for variables, and the thread copy can be different from the "main" memory. So in fact, it is possible for the "main" memory to have a value of 1 for i1, for thread1 to have a value of 2 for i1 and for thread2 to have a value of 3 for i1 if thread1 and thread2 have both updated i1 but those updated value has not yet been propagated to "main" memory or other threads.

On the other hand, geti2() effectively accesses the value of i2 from "main" memory. A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have it's data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Generally volatile variables have a higher access and update overhead than "plain" variables. Generally threads are allowed to have their own copy of data is for better efficiency.

There are two differences between volitile and synchronized.

Firstly synchronized obtains and releases locks on monitors which can force only one thread at a time to execute a code block. That's the fairly well known aspect to synchronized. But synchronized also synchronizes memory. In fact synchronized synchronizes the whole of thread memory with "main" memory. So executing geti3() does the following:

  1. The thread acquires the lock on the monitor for object this .
  2. The thread memory flushes all its variables, i.e. it has all of its variables effectively read from "main" memory .
  3. The code block is executed (in this case setting the return value to the current value of i3, which may have just been reset from "main" memory).
  4. (Any changes to variables would normally now be written out to "main" memory, but for geti3() we have no changes.)
  5. The thread releases the lock on the monitor for object this.

So where volatile only synchronizes the value of one variable between thread memory and "main" memory, synchronized synchronizes the value of all variables between thread memory and "main" memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.

http://javaexp.blogspot.com/2007/12/difference-between-volatile-and.html

Write to custom log file from a Bash script

@chepner make a good point that logger is dedicated to logging messages.

I do need to mention that @Thomas Haratyk simply inquired why I didn't simply use echo.

At the time, I didn't know about echo, as I'm learning shell-scripting, but he was right.

My simple solution is now this:

#!/bin/bash
echo "This logs to where I want, but using echo" > /var/log/mycustomlog

The example above will overwrite the file after the >

So, I can append to that file with this:

#!/bin/bash
echo "I will just append to my custom log file" >> /var/log/customlog

Thanks guys!

  • on a side note, it's simply my personal preference to keep my personal logs in /var/log/, but I'm sure there are other good ideas out there. And since I didn't create a daemon, /var/log/ probably isn't the best place for my custom log file. (just saying)

How to monitor Java memory usage?

If you use the JMX provided history of GC runs you can use the same before/after numbers, you just dont have to force a GC.

You just need to keep in mind that those GC runs (typically one for old and one for new generation) are not on regular intervalls, so you need to extract the starttime as well for plotting (or you plot against a sequence number, for most practical purposes that would be enough for plotting).

For example on Oracle HotSpot VM with ParNewGC, there is a JMX MBean called java.lang:type=GarbageCollector,name=PS Scavenge, it has a attribute LastGCInfo, it returns a CompositeData of the last YG scavenger run. It is recorded with duration, absolute startTime and memoryUsageBefore and memoryUsageAfter.

Just use a timer to read that attribute. Whenever a new startTime shows up you know that it describes a new GC event, you extract the memory information and keep polling for the next update. (Not sure if a AttributeChangeNotification somehow can be used.)

Tip: in your timer you might measure the distance to the last GC run, and if that is too long for the resulution of your plotting, you could invoke System.gc() conditionally. But I would not do that in a OLTP instance.

jquery - Click event not working for dynamically created button

the simple and easy way to do that is use on event:

$('body').on('click','#element',function(){
    //somthing
});

but we can say this is not the best way to do this. I suggest a another way to do this is use clone() method instead of using dynamic html. Write some html in you file for example:

<div id='div1'></div>

Now in the script tag make a clone of this div then all the properties of this div would follow with new element too. For Example:

var dynamicDiv = jQuery('#div1').clone(true);

Now use the element dynamicDiv wherever you want to add it or change its properties as you like. Now all jQuery functions will work with this element

Getting 404 Not Found error while trying to use ErrorDocument

When we apply local url, ErrorDocument directive expect the full path from DocumentRoot. There fore,

 ErrorDocument 404 /yourfoldernames/errors/404.html

How to apply a CSS filter to a background image

You can create a div over the image you want to apply the filter and use backdrop-filter to its CSS class. Check out this link

"An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..."

If you add this to your web.config transformation file, you can also set certain publish options to have debugging enabled or disabled:

<system.web>
    <customErrors mode="Off" defaultRedirect="~/Error.aspx" xdt:Transform="Replace"/>
</system.web>

How to define global variable in Google Apps Script

    var userProperties = PropertiesService.getUserProperties();


function globalSetting(){
  //creating an array
  userProperties.setProperty('gemployeeName',"Rajendra Barge");
  userProperties.setProperty('gemployeeMobile',"9822082320");
  userProperties.setProperty('gemployeeEmail'," [email protected]");
  userProperties.setProperty('gemployeeLastlogin',"03/10/2020");
  
  
  
}


var userProperties = PropertiesService.getUserProperties();
function showUserForm(){

  var templete = HtmlService.createTemplateFromFile("userForm");
  
  var html = templete.evaluate();
  html.setTitle("Customer Data");
  SpreadsheetApp.getUi().showSidebar(html);


}

function appendData(data){
 globalSetting();
 
  var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
  ws.appendRow([data.date,
                data.name,
                data.Kindlyattention,
                data.senderName,
                data.customereMail,
                userProperties.getProperty('gemployeeName'),
                ,
                ,
                data.paymentTerms,
                ,
                userProperties.getProperty('gemployeeMobile'),
                userProperties.getProperty('gemployeeEmail'),
                Utilities.formatDate(new Date(), "GMT+05:30", "dd-MM-yyyy HH:mm:ss")
                
                
  ]);
  
}

function errorMessage(){

Browser.msgBox("! All fields are mandetory");

}

Make an image responsive - the simplest way

I use this all the time

You can customize the img class and the max-width property:

img{
    width: 100%;
    max-width: 800px;
}

max-width is important. Otherwise your image will scale too much for the desktop. There isn't any need to put in the height property, because by default it is auto mode.

Pass variables to Ruby script via command line

tl;dr

I know this is old, but getoptlong wasn't mentioned here and it's probably the best way to parse command line arguments today.


Parsing command line arguments

I strongly recommend getoptlong. It's pretty easy to use and works like a charm. Here is an example extracted from the link above

require 'getoptlong'

opts = GetoptLong.new(
    [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
    [ '--repeat', '-n', GetoptLong::REQUIRED_ARGUMENT ],
    [ '--name', GetoptLong::OPTIONAL_ARGUMENT ]
)

dir = nil
name = nil
repetitions = 1
opts.each do |opt, arg|
    case opt
        when '--help'
            puts <<-EOF
hello [OPTION] ... DIR

-h, --help:
     show help

--repeat x, -n x:
     repeat x times

--name [name]:
     greet user by name, if name not supplied default is John

DIR: The directory in which to issue the greeting.
            EOF
        when '--repeat'
            repetitions = arg.to_i
        when '--name'
            if arg == ''
                name = 'John'
            else
                name = arg
            end
    end
end

if ARGV.length != 1
    puts "Missing dir argument (try --help)"
    exit 0
end

dir = ARGV.shift

Dir.chdir(dir)
for i in (1..repetitions)
    print "Hello"
    if name
        print ", #{name}"
    end
    puts
end

You can call it like this ruby hello.rb -n 6 --name -- /tmp

What OP is trying to do

In this case I think the best option is to use YAML files as suggested in this answer

CSS: fixed to bottom and centered

A jQuery solution

$(function(){
    $(window).resize(function(){
        placeFooter();
    });
    placeFooter();
    // hide it before it's positioned
    $('#footer').css('display','inline');
});

function placeFooter() {    
    var windHeight = $(window).height();
    var footerHeight = $('#footer').height();
    var offset = parseInt(windHeight) - parseInt(footerHeight);
    $('#footer').css('top',offset);
}

<div id='footer' style='position: fixed; display: none;'>I am a footer</div>

Sometimes it's easier to implement JS than to hack old CSS.

http://jsfiddle.net/gLhEZ/

How to publish a Web Service from Visual Studio into IIS?

If using Visual Studio 2010 you can right-click on the project for the service, and select properties. Then select the Web tab. Under the Servers section you can configure the URL. There is also a button to create the virtual directory.

Uses of content-disposition in an HTTP response header

Note that RFC 6266 supersedes the RFCs referenced below. Section 7 outlines some of the related security concerns.

The authority on the content-disposition header is RFC 1806 and RFC 2183. People have also devised content-disposition hacking. It is important to note that the content-disposition header is not part of the HTTP 1.1 standard.

The HTTP 1.1 Standard (RFC 2616) also mentions the possible security side effects of content disposition:

15.5 Content-Disposition Issues

RFC 1806 [35], from which the often implemented Content-Disposition
(see section 19.5.1) header in HTTP is derived, has a number of very
serious security considerations. Content-Disposition is not part of
the HTTP standard, but since it is widely implemented, we are
documenting its use and risks for implementors. See RFC 2183 [49]
(which updates RFC 1806) for details.

Remove icon/logo from action bar on android

This worked for me

getActionBar().setDisplayShowHomeEnabled(false);

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

I got the same error, but when i did as below, it resolved the issue.
Instead of writing like this:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

use the below one:

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

How to add a column in TSQL after a specific column?

You have to rebuild the table. Luckily, the order of the columns doesn't matter at all!

Watch as I magically reorder your columns:

SELECT ID, Newfield, FieldA, FieldB FROM MyTable

Also this has been asked about a bazillion times before.

HTML input fields does not get focus when clicked

I had the same problem. Tore my hair for hours trying all sorts of solutions. Turned out to be an unclosed a tag.Try validate your HTML code, solution could be an unclosed tag causing issues

Shell script to check if file exists

You have to understand how Unix interprets your input.

The standard Unix shell interpolates environment variables, and what are called globs before it passes the parameters to your program. This is a bit different from Windows which makes the program interpret the expansion.

Try this:

 $ echo *

This will echo all the files and directories in your current directory. Before the echo command acts, the shell interpolates the * and expands it, then passes that expanded parameter back to your command. You can see it in action by doing this:

$ set -xv
$ echo *
$ set +xv

The set -xv turns on xtrace and verbose. Verbose echoes the command as entered, and xtrace echos the command that will be executed (that is, after the shell expansion).

Now try this:

$ echo "*"

Note that putting something inside quotes hides the glob expression from the shell, and the shell cannot expand it. Try this:

$ foo="this is the value of foo"
$ echo $foo
$ echo "$foo"
$ echo '$foo'

Note that the shell can still expand environment variables inside double quotes, but not in single quotes.

Now let's look at your statement:

file="home/edward/bank1/fiche/Test*"

The double quotes prevent the shell from expanding the glob expression, so file is equal to the literal home/edward/bank1/finche/Test*. Therefore, you need to do this:

file=/home/edward/bank1/fiche/Test*

The lack of quotes (and the introductory slash which is important!) will now make file equal to all files that match that expression. (There might be more than one!). If there are no files, depending upon the shell, and its settings, the shell may simply set file to that literal string anyway.

You certainly have the right idea:

 file=/home/edward/bank1/fiche/Test*
 if  test -s $file
    then 
        echo "found one"
    else 
       echo "found none"
 fi

However, you still might get found none returned if there is more than one file. Instead, you might get an error in your test command because there are too many parameters.

One way to get around this might be:

if ls /home/edward/bank1/finche/Test* > /dev/null 2>&1
then
    echo "There is at least one match (maybe more)!"
else
    echo "No files found"
fi

In this case, I'm taking advantage of the exit code of the ls command. If ls finds one file it can access, it returns a zero exit code. If it can't find one matching file, it returns a non-zero exit code. The if command merely executes a command, and then if the command returns a zero, it assumes the if statement as true and executes the if clause. If the command returns a non-zero value, the if statement is assumed to be false, and the else clause (if one is available) is executed.

The test command works in a similar fashion. If the test is true, the test command returns a zero. Otherwise, the test command returns a non-zero value. This works great with the if command. In fact, there's an alias to the test command. Try this:

 $ ls -li /bin/test /bin/[

The i prints out the inode. The inode is the real ID of the file. Files with the same ID are the same file. You can see that /bin/test and /bin/[ are the same command. This makes the following two commands the same:

if test -s $file
then
    echo "The file exists"
fi

if [ -s $file ]
then
    echo "The file exists"
fi

Convert HTML5 into standalone Android App

Create an Android app using Eclipse.

Create a layout that has a <WebView> control.

Move your HTML code to /assets folder.

Load webview with your file:///android_asset/ file.

And you have an android app!

Inverse of a matrix using numpy

Inverse of a matrix using python and numpy:

>>> import numpy as np
>>> b = np.array([[2,3],[4,5]])
>>> np.linalg.inv(b)
array([[-2.5,  1.5],
       [ 2. , -1. ]])

Not all matrices can be inverted. For example singular matrices are not Invertable:

>>> import numpy as np
>>> b = np.array([[2,3],[4,6]])
>>> np.linalg.inv(b)

LinAlgError: Singular matrix

Solution to singular matrix problem:

try-catch the Singular Matrix exception and keep going until you find a transform that meets your prior criteria AND is also invertable.

Intuition for why matrix inversion can't always be done; like in singular matrices:

Imagine an old overhead film projector that shines a bright light through film onto a white wall. The pixels in the film are projected to the pixels on the wall.

If I stop the film projection on a single frame, you will see the pixels of the film on the wall and I ask you to regenerate the film based on what you see. That's easy, you say, just take the inverse of the matrix that performed the projection. An Inverse of a matrix is the reversal of the projection.

Now imagine if the projector was corrupted, and I put a distorted lens in front of the film. Now multiple pixels are projected to the same spot on the wall. I asked you again to "undo this operation with the matrix inverse". You say: "I can't because you destroyed information with the lens distortion, I can't get back to where we were, because the matrix is either Singular or Degenerate."

A matrix that can be used to transform some data into other data is invertable only if the process can be reversed with no loss of information. If your matrix can't be inverted, perhaps you are defining your projection using a guess-and-check methodology rather than using a process that guarantees a non-corrupting transform.

If you're using a heuristic or anything less than perfect mathematical precision, then you'll have to define another process to manage and quarantine distortions so that programming by Brownian motion can resume.

Source:

http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.inv.html#numpy.linalg.inv

How to sort a Collection<T>?

Assuming you have a list of object of type Person, using Lambda expression, you can sort the last names of users for instance by doing the following:

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Person {
        private String firstName;
        private String lastName;

        public Person(String firstName, String lastName){
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public String getLastName(){
            return this.lastName;
        }

        public String getFirstName(){
            return this.firstName;
        }

        @Override
        public String toString(){
            return "Person: "+ this.getFirstName() + " " + this.getLastName();
        }
    }

    class TestSort {
        public static void main(String[] args){
            List<Person> people = Arrays.asList(
                                  new Person("John", "Max"), 
                                  new Person("Coolio", "Doe"), 
                                  new Person("Judith", "Dan")
            );

            //Making use of lambda expression to sort the collection
            people.sort((p1, p2)->p1.getLastName().compareTo(p2.getLastName()));

            //Print sorted 
            printPeople(people);
        }

        public static void printPeople(List<Person> people){
            for(Person p : people){
                System.out.println(p);
            }
        }
    }

Remove border radius from Select tag in bootstrap 3

In addition to border-radius: 0, add -webkit-appearance: none;.

ASP.NET MVC Ajax Error handling

In agreement with aleho's response here's a complete example. It works like a charm and is super simple.

Controller code

[HttpGet]
public async Task<ActionResult> ChildItems()
{
    var client = TranslationDataHttpClient.GetClient();
    HttpResponseMessage response = await client.GetAsync("childItems);

    if (response.IsSuccessStatusCode)
        {
            string content = response.Content.ReadAsStringAsync().Result;
            List<WorkflowItem> parameters = JsonConvert.DeserializeObject<List<WorkflowItem>>(content);
            return Json(content, JsonRequestBehavior.AllowGet);
        }
        else
        {
            return new HttpStatusCodeResult(response.StatusCode, response.ReasonPhrase);
        }
    }
}

Javascript code in the view

var url = '@Html.Raw(@Url.Action("ChildItems", "WorkflowItemModal")';

$.ajax({
    type: "GET",
    dataType: "json",
    url: url,
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        // Do something with the returned data
    },
    error: function (xhr, status, error) {
        // Handle the error.
    }
});

Hope this helps someone else!

How to group dataframe rows into list in pandas groupby

Building upon @B.M answer, here is a more general version and updated to work with newer library version: (numpy version 1.19.2, pandas version 1.2.1) And this solution can also deal with multi-indices:

However this is not heavily tested, use with caution.

If performance is important go down to numpy level:

import pandas as pd
import numpy as np

np.random.seed(0)
df = pd.DataFrame({'a': np.random.randint(0, 10, 90), 'b': [1,2,3]*30, 'c':list('abcefghij')*10, 'd': list('hij')*30})


def f_multi(df,col_names):
    if not isinstance(col_names,list):
        col_names = [col_names]
        
    values = df.sort_values(col_names).values.T

    col_idcs = [df.columns.get_loc(cn) for cn in col_names]
    other_col_names = [name for idx, name in enumerate(df.columns) if idx not in col_idcs]
    other_col_idcs = [df.columns.get_loc(cn) for cn in other_col_names]

    # split df into indexing colums(=keys) and data colums(=vals)
    keys = values[col_idcs,:]
    vals = values[other_col_idcs,:]
    
    # list of tuple of key pairs
    multikeys = list(zip(*keys))
    
    # remember unique key pairs and ther indices
    ukeys, index = np.unique(multikeys, return_index=True, axis=0)
    
    # split data columns according to those indices
    arrays = np.split(vals, index[1:], axis=1)

    # resulting list of subarrays has same number of subarrays as unique key pairs
    # each subarray has the following shape:
    #    rows = number of non-grouped data columns
    #    cols = number of data points grouped into that unique key pair
    
    # prepare multi index
    idx = pd.MultiIndex.from_arrays(ukeys.T, names=col_names) 

    list_agg_vals = dict()
    for tup in zip(*arrays, other_col_names):
        col_vals = tup[:-1] # first entries are the subarrays from above 
        col_name = tup[-1]  # last entry is data-column name
        
        list_agg_vals[col_name] = col_vals

    df2 = pd.DataFrame(data=list_agg_vals, index=idx)
    return df2

Tests:

In [227]: %timeit f_multi(df, ['a','d'])

2.54 ms ± 64.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [228]: %timeit df.groupby(['a','d']).agg(list)

4.56 ms ± 61.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)


Results:

for the random seed 0 one would get:

enter image description here

Connection Strings for Entity Framework

What I understand is you want same connection string with different Metadata in it. So you can use a connectionstring as given below and replace "" part. I have used your given connectionString in same sequence.

connectionString="<METADATA>provider=System.Data.SqlClient;provider connection string=&quot;Data Source=SomeServer;Initial Catalog=SomeCatalog;Persist Security Info=True;User ID=Entity;Password=SomePassword;MultipleActiveResultSets=True&quot;"

For first connectionString replace <METADATA> with "metadata=res://*/ModEntity.csdl|res://*/ModEntity.ssdl|res://*/ModEntity.msl;"

For second connectionString replace <METADATA> with "metadata=res://*/Entity.csdl|res://*/Entity.ssdl|res://*/Entity.msl;"

For third connectionString replace <METADATA> with "metadata=res://*/Entity.csdl|res://*/Entity.ssdl|res://*/Entity.msl|res://*/ModEntity.csdl|res://*/ModEntity.ssdl|res://*/ModEntity.msl;"

Happy coding!

How to comment multiple lines in Visual Studio Code?

To comment multiple line on visual code use

shift+alt+a

To comment single line use

ctrl + /

what's the differences between r and rb in fopen

This makes a difference on Windows, at least. See that link for details.

How to cin to a vector

If you know the size of the vector you can do it like this:

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<int> v(n);
    for (auto &it : v) {
        cin >> it;
    }
}

How do I get the first element from an IEnumerable<T> in .net?

Just in case you're using .NET 2.0 and don't have access to LINQ:

 static T First<T>(IEnumerable<T> items)
 {
     using(IEnumerator<T> iter = items.GetEnumerator())
     {
         iter.MoveNext();
         return iter.Current;
     }
 }

This should do what you're looking for...it uses generics so you to get the first item on any type IEnumerable.

Call it like so:

List<string> items = new List<string>() { "A", "B", "C", "D", "E" };
string firstItem = First<string>(items);

Or

int[] items = new int[] { 1, 2, 3, 4, 5 };
int firstItem = First<int>(items);

You could modify it readily enough to mimic .NET 3.5's IEnumerable.ElementAt() extension method:

static T ElementAt<T>(IEnumerable<T> items, int index)
{
    using(IEnumerator<T> iter = items.GetEnumerator())
    {
        for (int i = 0; i <= index; i++, iter.MoveNext()) ;
        return iter.Current;
    }
} 

Calling it like so:

int[] items = { 1, 2, 3, 4, 5 };
int elemIdx = 3;
int item = ElementAt<int>(items, elemIdx);

Of course if you do have access to LINQ, then there are plenty of good answers posted already...

Why can't I shrink a transaction log file, even after backup?

Thank you to everyone for answering.

We finally found the issue. In sys.databases, log_reuse_wait_desc was equal to 'replication'. Apparently this means something to the effect of SQL Server waiting for a replication task to finish before it can reuse the log space.

Replication has never been used on this DB or this server was toyed with once upon a time on this db. We cleared the incorrect state by running sp_removedbreplication. After we ran this, backup log and dbcc shrinkfile worked just fine.

Definitely one for the bag-of-tricks.

Sources:

http://social.technet.microsoft.com/Forums/pt-BR/sqlreplication/thread/34ab68ad-706d-43c4-8def-38c09e3bfc3b

http://www.eggheadcafe.com/conversation.aspx?messageid=34020486&threadid=33890705

gdb: "No symbol table is loaded"

I have the same problem and I followed this Post, it solved my problem.

Follow the following 2 steps:

  1. Make sure the optimization level is -O0
  2. Add -ggdb flag when compiling your program

Good luck!

Mac SQLite editor

I've published instructions for how to run the Firefox SQLite Manager outside of Firefox, since FF hase become so bloated in the last few releases. It's really easy and I've even compiled a DMG for the sqlite gui if anyone wants it.

How to create duplicate table with new name in SQL Server 2008

Right click on the table in SQL Management Studio.

Select Script... Create to... New Query Window.

This will generate a script to recreate the table in a new query window.

Change the name of the table in the script to whatever you want the new table to be named.

Execute the script.

Scroll part of content in fixed position container

What worked for me :

div#scrollable {
    overflow-y: scroll;
    max-height: 100vh;
}

UTC Date/Time String to Timezone

How about:

$timezone = new DateTimeZone('UTC');
$date = new DateTime('2011-04-21 13:14', $timezone);
echo $date->format;

Put buttons at bottom of screen with LinearLayout?

Add android:windowSoftInputMode="adjustPan" to manifest - to the corresponding activity:

  <activity android:name="MyActivity"
    ...
    android:windowSoftInputMode="adjustPan"
    ...
  </activity>

Determining image file size + dimensions via Javascript?

Check the uploaded image size using Javascript

<script type="text/javascript">
    function check(){
      var imgpath=document.getElementById('imgfile');
      if (!imgpath.value==""){
        var img=imgpath.files[0].size;
        var imgsize=img/1024; 
        alert(imgsize);
      }
    }
</script>

Html code

<form method="post" enctype="multipart/form-data" onsubmit="return check();">
<input type="file" name="imgfile" id="imgfile"><br><input type="submit">
</form>

JSON to PHP Array using file_get_contents

Check some typo ','

<?php
 //file_get_content(url);
$jsonD = '{
    "bpath":"http://www.sampledomain.com/",
    "clist":[{
            "cid":"11",
            "display_type":"grid",
            "ctitle":"abc",
            "acount":"71",
            "alist":[{
                    "aid":"6865",
                    "adate":"2 Hours ago",
                    "atitle":"test",
                    "adesc":"test desc",
                    "aimg":"",
                    "aurl":"?nid=6865",
                    "weburl":"news.php?nid=6865",
                    "cmtcount":"0"
                },
                {
                    "aid":"6857",
                    "adate":"20 Hours ago",
                    "atitle":"test1",
                    "adesc":"test desc1",
                    "aimg":"",
                    "aurl":"?nid=6857",
                    "weburl":"news.php?nid=6857",
                    "cmtcount":"0"
                }
            ]
        },
        {
            "cid":"1",
            "display_type":"grid",
            "ctitle":"test1",
            "acount":"2354",
            "alist":[{
                    "aid":"6851",
                    "adate":"1 Days ago",
                    "atitle":"test123",
                    "adesc":"test123 desc",
                    "aimg":"",
                    "aurl":"?nid=6851",
                    "weburl":"news.php?nid=6851",
                    "cmtcount":"7"
                },
                {
                    "aid":"6847",
                    "adate":"2 Days ago",
                    "atitle":"test12345",
                    "adesc":"test12345 desc",
                    "aimg":"",
                    "aurl":"?nid=6847",
                    "weburl":"news.php?nid=6847",
                    "cmtcount":"7"
                }
            ]
        }
    ]
}
';

$parseJ = json_decode($jsonD,true);

print_r($parseJ);
?>

How do you get centered content using Twitter Bootstrap?

You can use any one of the below types

  1. Use the Bootstrap existing class text-center.
  2. Adding a custom style, style = "text-align:center".
  3. Use a column offset:

    Example: <div class="col-md-offset-6 col-md-12"></div>

How can I format the output of a bash command in neat columns

Try

xargs -n2  printf "%-20s%s\n"

or even

xargs printf "%-20s%s\n"

if input is not very large.

Maximum filename length in NTFS (Windows XP and Windows Vista)?

199 on Windows XP NTFS, I just checked.

This is not theory but from just trying on my laptop. There may be mitigating effects, but it physically won't let me make it bigger.

Is there some other setting limiting this, I wonder? Try it for yourself.

Using generic std::function objects with member functions in one class

A non-static member function must be called with an object. That is, it always implicitly passes "this" pointer as its argument.

Because your std::function signature specifies that your function doesn't take any arguments (<void(void)>), you must bind the first (and the only) argument.

std::function<void(void)> f = std::bind(&Foo::doSomething, this);

If you want to bind a function with parameters, you need to specify placeholders:

using namespace std::placeholders;
std::function<void(int,int)> f = std::bind(&Foo::doSomethingArgs, this, std::placeholders::_1, std::placeholders::_2);

Or, if your compiler supports C++11 lambdas:

std::function<void(int,int)> f = [=](int a, int b) {
    this->doSomethingArgs(a, b);
}

(I don't have a C++11 capable compiler at hand right now, so I can't check this one.)

javascript regex : only english letters allowed

_x000D_
_x000D_
let res = /^[a-zA-Z]+$/.test('sfjd');
console.log(res);
_x000D_
_x000D_
_x000D_

Note: If you have any punctuation marks or anything, those are all invalid too. Dashes and underscores are invalid. \w covers a-zA-Z and some other word characters. It all depends on what you need specifically.

How to run a jar file in a linux commandline

copy your file in linux Java directory

cp yourfile.jar /java/bin

open the directory

cd /java/bin

and execute your file

./java -jar yourfile.jar

or all in one try this command:

/java/bin/java -jar jarfilefolder/jarfile.jar

How to add days to the current date?

This will give total number of days including today in the current month.

select day(getDate())

Reloading/refreshing Kendo Grid

What you have to do is just add an event .Events(events => events.Sync("KendoGridRefresh")) in your kendoGrid binding code.No need to write the refresh code in ajax result.

@(Html.Kendo().Grid<Models.DocumentDetail>().Name("document")
    .DataSource(dataSource => dataSource
    .Ajax()
    .PageSize(20)
    .Model(model => model.Id(m => m.Id))        
    .Events(events => events.Sync("KendoGridRefresh"))    
    )
      .Columns(columns =>
      {
          columns.Bound(c => c.Id).Hidden();              
          columns.Bound(c => c.UserName).Title(@Resources.Resource.lblAddedBy);                           
      }).Events(e => e.DataBound("onRowBound"))
          .ToolBar(toolbar => toolbar.Create().Text(@Resources.Resource.lblNewDocument))
          .Sortable()          
          .HtmlAttributes(new { style = "height:260px" })          
  )

And you can add the following Global function in any of your .js file. so, you can call it for all the kendo grids in your project to refresh the kendoGrid.

function KendoGridRefresh() {
    var grid = $('#document').data('kendoGrid');
    grid.dataSource.read();
}

Difference between $(window).load() and $(document).ready() functions

According to DOM Level 2 Events, the load event is supposed to fire on document, not on window. However, load is implemented on window in all browsers for backwards compatibility.

Multiline editing in Visual Studio Code

Box Selecting

Windows: shift + alt + Mouse Left Button

macOS: shift + option + Click

This is contrary to what is mentioned in an answer to Does Visual Studio Code have box select/multi-line edit?.

How can I tell jackson to ignore a property for which I don't have control over the source code?

I had a similar issue, but it was related to Hibernate's bi-directional relationships. I wanted to show one side of the relationship and programmatically ignore the other, depending on what view I was dealing with. If you can't do that, you end up with nasty StackOverflowExceptions. For instance, if I had these objects

public class A{
  Long id;
  String name;
  List<B> children;
}

public class B{
  Long id;
  A parent;
}

I would want to programmatically ignore the parent field in B if I were looking at A, and ignore the children field in A if I were looking at B.

I started off using mixins to do this, but that very quickly becomes horrible; you have so many useless classes laying around that exist solely to format data. I ended up writing my own serializer to handle this in a cleaner way: https://github.com/monitorjbl/json-view.

It allows you programmatically specify what fields to ignore:

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(JsonView.class, new JsonViewSerializer());
mapper.registerModule(module);

List<A> list = getListOfA();
String json = mapper.writeValueAsString(JsonView.with(list)
    .onClass(B.class, match()
        .exclude("parent")));

It also lets you easily specify very simplified views through wildcard matchers:

String json = mapper.writeValueAsString(JsonView.with(list)
    .onClass(A.class, match()
        .exclude("*")
         .include("id", "name")));

In my original case, the need for simple views like this was to show the bare minimum about the parent/child, but it also became useful for our role-based security. Less privileged views of objects needed to return less information about the object.

All of this comes from the serializer, but I was using Spring MVC in my app. To get it to properly handle these cases, I wrote an integration that you can drop in to existing Spring controller classes:

@Controller
public class JsonController {
  private JsonResult json = JsonResult.instance();
  @Autowired
  private TestObjectService service;

  @RequestMapping(method = RequestMethod.GET, value = "/bean")
  @ResponseBody
  public List<TestObject> getTestObject() {
    List<TestObject> list = service.list();

    return json.use(JsonView.with(list)
        .onClass(TestObject.class, Match.match()
            .exclude("int1")
            .include("ignoredDirect")))
        .returnValue();
  }
}

Both are available on Maven Central. I hope it helps someone else out there, this is a particularly ugly problem with Jackson that didn't have a good solution for my case.

How do I include negative decimal numbers in this regular expression?

^[+-]?\d{1,18}(\.\d{1,2})?$

accepts positive or negative decimal values.

What's the best way to break from nested loops in JavaScript?

I thought I'd show a functional-programming approach. You can break out of nested Array.prototype.some() and/or Array.prototype.every() functions, as in my solutions. An added benefit of this approach is that Object.keys() enumerates only an object's own enumerable properties, whereas "a for-in loop enumerates properties in the prototype chain as well".

Close to the OP's solution:

    Args.forEach(function (arg) {
        // This guard is not necessary,
        // since writing an empty string to document would not change it.
        if (!getAnchorTag(arg))
            return;

        document.write(getAnchorTag(arg));
    });

    function getAnchorTag (name) {
        var res = '';

        Object.keys(Navigation.Headings).some(function (Heading) {
            return Object.keys(Navigation.Headings[Heading]).some(function (Item) {
                if (name == Navigation.Headings[Heading][Item].Name) {
                    res = ("<a href=\""
                                 + Navigation.Headings[Heading][Item].URL + "\">"
                                 + Navigation.Headings[Heading][Item].Name + "</a> : ");
                    return true;
                }
            });
        });

        return res;
    }

Solution that reduces iterating over the Headings/Items:

    var remainingArgs = Args.slice(0);

    Object.keys(Navigation.Headings).some(function (Heading) {
        return Object.keys(Navigation.Headings[Heading]).some(function (Item) {
            var i = remainingArgs.indexOf(Navigation.Headings[Heading][Item].Name);

            if (i === -1)
                return;

            document.write("<a href=\""
                                         + Navigation.Headings[Heading][Item].URL + "\">"
                                         + Navigation.Headings[Heading][Item].Name + "</a> : ");
            remainingArgs.splice(i, 1);

            if (remainingArgs.length === 0)
                return true;
            }
        });
    });

How to retrieve data from a SQL Server database in C#?

To retrieve data from database:

private SqlConnection Conn;
 private void CreateConnection()
 {
    string ConnStr =
    ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
    Conn = new SqlConnection(ConnStr);
 }
 public DataTable getData()
 {
 CreateConnection();
    string SqlString = "SELECT * FROM TableName WHERE SomeID = @SomeID;";
    SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);
    DataTable dt = new DataTable();
    try
    {
        Conn.Open();
        sda.Fill(dt);
    }
    catch (SqlException se)
    {
        DBErLog.DbServLog(se, se.ToString());
    }
    finally
    {
        Conn.Close();
    }
    return dt;
}

How can I convert a cv::Mat to a gray scale in OpenCv?

May be helpful for late comers.

#include "stdafx.h"
#include "cv.h"
#include "highgui.h"

using namespace cv;
using namespace std;

int main(int argc, char *argv[])
{
  if (argc != 2) {
    cout << "Usage: display_Image ImageToLoadandDisplay" << endl;
    return -1;
}else{
    Mat image;
    Mat grayImage;

    image = imread(argv[1], IMREAD_COLOR);
    if (!image.data) {
        cout << "Could not open the image file" << endl;
        return -1;
    }
    else {
        int height = image.rows;
        int width = image.cols;

        cvtColor(image, grayImage, CV_BGR2GRAY);


        namedWindow("Display window", WINDOW_AUTOSIZE);
        imshow("Display window", image);

        namedWindow("Gray Image", WINDOW_AUTOSIZE);
        imshow("Gray Image", grayImage);
        cvWaitKey(0);
        image.release();
        grayImage.release();
        return 0;
    }

  }

}

Finding version of Microsoft C++ compiler from command-line (for makefiles)

Try:

cl /v

Actually, any time I give cl an argument, it prints out the version number on the first line.

You could just feed it a garbage argument and then parse the first line of the output, which contains the verison number.

Access camera from a browser

    <style type="text/css">
        #container {
            margin: 0px auto;
            width: 500px;
            height: 375px;
            border: 10px #333 solid;
        }

        #videoElement {
          width: 500px;
          height: 375px;
          background-color: #777;
        }
    </style>    
<div id="container">
            <video autoplay="true" id="videoElement"></video>
        </div>
        <script type="text/javascript">
          var video = document.querySelector("#videoElement");
          navigator.getUserMedia = navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia||navigator.oGetUserMedia;
    
          if(navigator.getUserMedia) {
            navigator.getUserMedia({video:true}, handleVideo, videoError);
          }
    
          function handleVideo(stream) {
            video.srcObject=stream;
            video.play();
          }
    
          function videoError(e) {
    
          }
        </script>

Linq Select Group By

var result = priceLog.GroupBy(s => s.LogDateTime.ToString("MMM yyyy")).Select(grp => new PriceLog() { LogDateTime = Convert.ToDateTime(grp.Key), Price = (int)grp.Average(p => p.Price) }).ToList();

I have converted it to int because my Price field was int and Average method return double .I hope this will help

No newline at end of file

It indicates that you do not have a newline (usually '\n', aka CR or CRLF) at the end of file.

That is, simply speaking, the last byte (or bytes if you're on Windows) in the file is not a newline.

The message is displayed because otherwise there is no way to tell the difference between a file where there is a newline at the end and one where is not. Diff has to output a newline anyway, or the result would be harder to read or process automatically.

Note that it is a good style to always put the newline as a last character if it is allowed by the file format. Furthermore, for example, for C and C++ header files it is required by the language standard.

How do I turn off Unicode in a VC++ project?

Burgos has the right answer. Just to clarify, the Character Set should be changed to "Not Set".

Launch Minecraft from command line - username and password as prefix

To run Minecraft with Forge (change C:\Users\nov11\AppData\Roaming/.minecraft/to your MineCraft path :) [Just for people who are a bit too lazy to search on Google...] Special thanks to ammarx for his TagAPI_3 (Github) which was used to create this command. Arguments are separated line by line to make it easier to find useful ones.

java
-Xms1024M
-Xmx1024M
-XX:HeapDumpPath=MojangTricksIntelDriversForPerformance_javaw.exe_minecraft.exe.heapdump
-Djava.library.path=C:\Users\nov11\AppData\Roaming/.minecraft/versions/1.12.2/natives
-cp
C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/minecraftforge/forge/1.12.2-14.23.5.2775/forge-1.12.2-14.23.5.2775.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/minecraft/launchwrapper/1.12/launchwrapper-1.12.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/ow2/asm/asm-all/5.2/asm-all-5.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/jline/jline/3.5.1/jline-3.5.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/dev/jna/jna/4.4.0/jna-4.4.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/typesafe/akka/akka-actor_2.11/2.3.3/akka-actor_2.11-2.3.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/typesafe/config/1.2.1/config-1.2.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-actors-migration_2.11/1.1.0/scala-actors-migration_2.11-1.1.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-compiler/2.11.1/scala-compiler-2.11.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/plugins/scala-continuations-library_2.11/1.0.2/scala-continuations-library_2.11-1.0.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/plugins/scala-continuations-plugin_2.11.1/1.0.2/scala-continuations-plugin_2.11.1-1.0.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-library/2.11.1/scala-library-2.11.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-parser-combinators_2.11/1.0.1/scala-parser-combinators_2.11-1.0.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-reflect/2.11.1/scala-reflect-2.11.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-swing_2.11/1.0.1/scala-swing_2.11-1.0.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-xml_2.11/1.0.2/scala-xml_2.11-1.0.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/lzma/lzma/0.0.1/lzma-0.0.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/sf/jopt-simple/jopt-simple/5.0.3/jopt-simple-5.0.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/java3d/vecmath/1.5.2/vecmath-1.5.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/sf/trove4j/trove4j/3.0.3/trove4j-3.0.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/maven/maven-artifact/3.5.3/maven-artifact-3.5.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/patchy/1.1/patchy-1.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/oshi-project/oshi-core/1.1/oshi-core-1.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/dev/jna/jna/4.4.0/jna-4.4.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/dev/jna/platform/3.4.0/platform-3.4.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/ibm/icu/icu4j-core-mojang/51.2/icu4j-core-mojang-51.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/sf/jopt-simple/jopt-simple/5.0.3/jopt-simple-5.0.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/codecjorbis/20101023/codecjorbis-20101023.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/codecwav/20101023/codecwav-20101023.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/libraryjavasound/20101123/libraryjavasound-20101123.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/librarylwjglopenal/20100824/librarylwjglopenal-20100824.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/soundsystem/20120107/soundsystem-20120107.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/io/netty/netty-all/4.1.9.Final/netty-all-4.1.9.Final.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/google/guava/guava/21.0/guava-21.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/commons/commons-lang3/3.5/commons-lang3-3.5.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/commons-io/commons-io/2.5/commons-io-2.5.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/commons-codec/commons-codec/1.10/commons-codec-1.10.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/jinput/jinput/2.0.5/jinput-2.0.5.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/jutils/jutils/1.0.0/jutils-1.0.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/google/code/gson/gson/2.8.0/gson-2.8.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/authlib/1.5.25/authlib-1.5.25.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/realms/1.10.22/realms-1.10.22.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/commons/commons-compress/1.8.1/commons-compress-1.8.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/httpcomponents/httpclient/4.3.3/httpclient-4.3.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/commons-logging/commons-logging/1.1.3/commons-logging-1.1.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/httpcomponents/httpcore/4.3.2/httpcore-4.3.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/it/unimi/dsi/fastutil/7.1.0/fastutil-7.1.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/logging/log4j/log4j-api/2.8.1/log4j-api-2.8.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/logging/log4j/log4j-core/2.8.1/log4j-core-2.8.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl/2.9.4-nightly-20150209/lwjgl-2.9.4-nightly-20150209.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl_util/2.9.4-nightly-20150209/lwjgl_util-2.9.4-nightly-20150209.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl-platform/2.9.4-nightly-20150209/lwjgl-platform-2.9.4-nightly-20150209.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl/2.9.2-nightly-20140822/lwjgl-2.9.2-nightly-20140822.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl_util/2.9.2-nightly-20140822/lwjgl_util-2.9.2-nightly-20140822.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/text2speech/1.10.3/text2speech-1.10.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/text2speech/1.10.3/text2speech-1.10.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/ca/weblite/java-objc-bridge/1.0.0/java-objc-bridge-1.0.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/ca/weblite/java-objc-bridge/1.0.0/java-objc-bridge-1.0.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/versions/1.12.2/1.12.2.jar
net.minecraft.launchwrapper.Launch
--width
854
--height
480
--username
Ishikawa
--version
1.12.2-forge1.12.2-14.23.5.2775
--gameDir
C:\Users\nov11\AppData\Roaming/.minecraft
--assetsDir
C:\Users\nov11\AppData\Roaming/.minecraft/assets
--assetIndex
1.12
--uuid
N/A
--accessToken
aeef7bc935f9420eb6314dea7ad7e1e5
--userType
mojang
--tweakClass
net.minecraftforge.fml.common.launcher.FMLTweaker
--versionType
Forge

Just when other solutions don't work. accessToken and uuid can be acquired from Mojang Servers, check other anwsers for details.

Edit (26.11.2018): I've also created Launcher Framework in C# (.NET Framework 3.5), which you can also check to see how launcher should work Available Here

How to find schema name in Oracle ? when you are connected in sql session using read only user

How about the following 3 statements?

-- change to your schema

ALTER SESSION SET CURRENT_SCHEMA=yourSchemaName;

-- check current schema

SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL;

-- generate drop table statements

SELECT 'drop table ', table_name, 'cascade constraints;' FROM ALL_TABLES WHERE OWNER = 'yourSchemaName';

COPY the RESULT and PASTE and RUN.

How to write a foreach in SQL Server?

I came up with a very effective, (I think) readable way to do this.

    1. create a temp table and put the records you want to iterate in there
    2. use WHILE @@ROWCOUNT <> 0 to do the iterating
    3. to get one row at a time do, SELECT TOP 1 <fieldnames>
        b. save the unique ID for that row in a variable
    4. Do Stuff, then delete the row from the temp table based on the ID saved at step 3b.

Here's the code. Sorry, its using my variable names instead of the ones in the question.

            declare @tempPFRunStops TABLE (ProformaRunStopsID int,ProformaRunMasterID int, CompanyLocationID int, StopSequence int );    

        INSERT @tempPFRunStops (ProformaRunStopsID,ProformaRunMasterID, CompanyLocationID, StopSequence) 
        SELECT ProformaRunStopsID, ProformaRunMasterID, CompanyLocationID, StopSequence from ProformaRunStops 
        WHERE ProformaRunMasterID IN ( SELECT ProformaRunMasterID FROM ProformaRunMaster WHERE ProformaId = 15 )

    -- SELECT * FROM @tempPFRunStops

    WHILE @@ROWCOUNT <> 0  -- << I dont know how this works
        BEGIN
            SELECT TOP 1 * FROM @tempPFRunStops
            -- I could have put the unique ID into a variable here
            SELECT 'Ha'  -- Do Stuff
            DELETE @tempPFRunStops WHERE ProformaRunStopsID = (SELECT TOP 1 ProformaRunStopsID FROM @tempPFRunStops)
        END

Display all dataframe columns in a Jupyter Python Notebook

I recommend setting the display options inside a context manager so that it only affects a single output. I usually prefer "pretty" html-output, and define a function force_show_all(df) for displaying the DataFrame df:

from IPython.core.display import display, HTML

def force_show_all(df):
    with pd.option_context('display.max_rows', None, 'display.max_columns', None, 'display.width', None):
        display(HTML(df.to_html()))

# ... now when you're ready to fully display df:
force_show_all(df)

As others have mentioned, please be cautious to only call this on a reasonably-sized dataframe.

What is the difference between Nexus and Maven?

This has a good general description: https://gephi.wordpress.com/tag/maven/

Let me make a few statement that can put the difference in focus:

  1. We migrated our code base from Ant to Maven

  2. All 3rd party librairies have been uploaded to Nexus. Maven is using Nexus as a source for libraries.

  3. Basic functionalities of a repository manager like Sonatype are:

    • Managing project dependencies,
    • Artifacts & Metadata,
    • Proxying external repositories
    • and deployment of packaged binaries and JARs to share those artifacts with other developers and end-users.

Efficient thresholding filter of an array with numpy

b = a[a>threshold] this should do

I tested as follows:

import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()

t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0

t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0

I got

$ python test.py
0:00:00.028000
0:00:02.461000

http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays

How to create a popup window (PopupWindow) in Android

I construct my own class, and then call it from my activity, overriding small methods like showAtLocation. I've found its easier when I have 4 to 5 popups in my activity to do this.

public class ToggleValues implements OnClickListener{

    private View pView;
    private LayoutInflater inflater;
    private PopupWindow pop;
    private Button one, two, three, four, five, six, seven, eight, nine, blank;
    private ImageButton eraser;
    private int selected = 1;
    private Animation appear;

    public ToggleValues(int id, Context c, int screenHeight){
        inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        pop = new PopupWindow(inflater.inflate(id, null, false), 265, (int)(screenHeight * 0.45), true);
        pop.setBackgroundDrawable(c.getResources().getDrawable(R.drawable.alpha_0));
        pView = pop.getContentView();

        appear = AnimationUtils.loadAnimation(c, R.anim.appear);

        one = (Button) pView.findViewById(R.id.one);
        one.setOnClickListener(this);
        two = (Button) pView.findViewById(R.id.two);
        two.setOnClickListener(this);
        three = (Button) pView.findViewById(R.id.three);
        three.setOnClickListener(this);
        four = (Button) pView.findViewById(R.id.four);
        four.setOnClickListener(this);
        five = (Button) pView.findViewById(R.id.five);
        five.setOnClickListener(this);
        six = (Button) pView.findViewById(R.id.six);
        six.setOnClickListener(this);
        seven = (Button) pView.findViewById(R.id.seven);
        seven.setOnClickListener(this);
        eight = (Button) pView.findViewById(R.id.eight);
        eight.setOnClickListener(this);
        nine = (Button) pView.findViewById(R.id.nine);
        nine.setOnClickListener(this);
        blank = (Button) pView.findViewById(R.id.blank_Selection);
        blank.setOnClickListener(this);
        eraser = (ImageButton) pView.findViewById(R.id.eraser);
        eraser.setOnClickListener(this);
    }

    public void showAtLocation(View v) {
        pop.showAtLocation(v, Gravity.BOTTOM | Gravity.LEFT, 40, 40);
        pView.startAnimation(appear);
    }

    public void dismiss(){ 
        pop.dismiss();
    }

    public boolean isShowing() {
        if(pop.isShowing()){
            return true;
        }else{
            return false;
        }
    }

    public int getSelected(){
        return selected;
    }

    public void onClick(View arg0) {
        if(arg0 == one){
            Sudo.setToggleNum(1);
        }else if(arg0 == two){
            Sudo.setToggleNum(2);
        }else if(arg0 == three){
            Sudo.setToggleNum(3);
        }else if(arg0 == four){
            Sudo.setToggleNum(4);
        }else if(arg0 == five){
            Sudo.setToggleNum(5);
        }else if(arg0 == six){
            Sudo.setToggleNum(6);
        }else if(arg0 == seven){
            Sudo.setToggleNum(7);
        }else if(arg0 == eight){
            Sudo.setToggleNum(8);
        }else if(arg0 == nine){
            Sudo.setToggleNum(9);
        }else if(arg0 == blank){
            Sudo.setToggleNum(0);
        }else if(arg0 == eraser){
            Sudo.setToggleNum(-1);
        }
        this.dismiss();
    }

}

Copy directory contents into a directory with python

You can also use glob2 to recursively collect all paths (using ** subfolders wildcard) and then use shutil.copyfile, saving the paths

glob2 link: https://code.activestate.com/pypm/glob2/

PHP Session Destroy on Log Out Button

First give the link of logout.php page in that logout button.In that page make the code which is given below:

Here is the code:

<?php
 session_start();
 session_destroy();
?>

When the session has started, the session for the last/current user has been started, so don't need to declare the username. It will be deleted automatically by the session_destroy method.

GC overhead limit exceeded

From Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning

the following

Excessive GC Time and OutOfMemoryError

The concurrent collector will throw an OutOfMemoryError if too much time is being spent in garbage collection: if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, an OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.

The policy is the same as that in the parallel collector, except that time spent performing concurrent collections is not counted toward the 98% time limit. In other words, only collections performed while the application is stopped count toward excessive GC time. Such collections are typically due to a concurrent mode failure or an explicit collection request (e.g., a call to System.gc()).

in conjunction with a passage further down

One of the most commonly encountered uses of explicit garbage collection occurs with RMIs distributed garbage collection (DGC). Applications using RMI refer to objects in other virtual machines. Garbage cannot be collected in these distributed applications without occasionally collection the local heap, so RMI forces full collections periodically. The frequency of these collections can be controlled with properties. For example,

java -Dsun.rmi.dgc.client.gcInterval=3600000

-Dsun.rmi.dgc.server.gcInterval=3600000 specifies explicit collection once per hour instead of the default rate of once per minute. However, this may also cause some objects to take much longer to be reclaimed. These properties can be set as high as Long.MAX_VALUE to make the time between explicit collections effectively infinite, if there is no desire for an upper bound on the timeliness of DGC activity.

Seems to imply that the evaluation period for determining the 98% is one minute long, but it might be configurable on Sun's JVM with the correct define.

Of course, other interpretations are possible.

How to list the properties of a JavaScript object?

Note that Object.keys and other ECMAScript 5 methods are supported by Firefox 4, Chrome 6, Safari 5, IE 9 and above.

For example:

var o = {"foo": 1, "bar": 2}; 
alert(Object.keys(o));

ECMAScript 5 compatibility table: http://kangax.github.com/es5-compat-table/

Description of new methods: http://markcaudill.com/index.php/2009/04/javascript-new-features-ecma5/

'heroku' does not appear to be a git repository

I've seen all the answers here and the only thing missing is after going through these steps:

$ git add .
$ git commit -m "first heroku commit"

You should run the command below:

$ heroku git:remote -a <YourAppNameOnHeroku>

And lastly, run this:

$ git push -f heroku <NameOfBranch>:master

Notice I used <NameOfBranch> because if you're currently in a different branch to master it would still throw errors, so If you are working in master use master, else put the name of the branch there.

Find which commit is currently checked out in Git

If you want to extract just a simple piece of information, you can get that using git show with the --format=<string> option...and ask it not to give you the diff with --no-patch. This means you can get a printf-style output of whatever you want, which might often be a single field.

For instance, to get just the shortened hash (%h) you could say:

$ git show --format="%h" --no-patch
4b703eb

If you're looking to save that into an environment variable in bash (a likely thing for people to want to do) you can use the $() syntax:

$ GIT_COMMIT="$(git show --format="%h" --no-patch)"

$ echo $GIT_COMMIT
4b703eb

The full list of what you can do is in git show --help. But here's an abbreviated list of properties that might be useful:

  • %H commit hash
  • %h abbreviated commit hash
  • %T tree hash
  • %t abbreviated tree hash
  • %P parent hashes
  • %p abbreviated parent hashes
  • %an author name
  • %ae author email
  • %at author date, UNIX timestamp
  • %aI author date, strict ISO 8601 format
  • %cn committer name
  • %ce committer email
  • %ct committer date, UNIX timestamp
  • %cI committer date, strict ISO 8601 format
  • %s subject
  • %f sanitized subject line, suitable for a filename
  • %gD reflog selector, e.g., refs/stash@{1}
  • %gd shortened reflog selector, e.g., stash@{1}

Flask - Calling python function on button OnClick event

Easiest solution

<button type="button" onclick="window.location.href='{{ url_for( 'move_forward') }}';">Forward</button>

Adding days to a date in Java

Here is some simple code to give output as currentdate + D days = some 'x' date (future date):

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

Calendar c = Calendar.getInstance();    
c.add(Calendar.DATE, 5);
System.out.println(dateFormat.format(c.getTime()));

How to pip or easy_install tkinter on Windows

I came here looking for an answer to this same question and none of the answers above actually answer the question at all!

So after some investigation I found out: there is a package (for python 3.x at least):

pip3 install pytk

The problem is, it is only the python part of the equation and doesn't install the tkinter libraries in your OS, so the answer is that you can't install it completely via pip https://tkdocs.com/tutorial/install.html

Personally I find this very annoying as i'm packaging a python application to be installed via pip that uses tkinter and I was looking for a way to have pip ensure that tkinter is installed and the answer is I can't I have to instruct users to install it if it's not installed already, a very poor experience for end users who should not need to know or care what tkinter is to use my application.

Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; }

You have two options with simple and idiomatic Typescript:

  1. Use index type
DNATranscriber: { [char: string]: string } = {
  G: "C",
  C: "G",
  T: "A",
  A: "U",
};

This is the index signature the error message is talking about. Reference

  1. Type each property:
DNATranscriber: { G: string; C: string; T: string; A: string } = {
  G: "C",
  C: "G",
  T: "A",
  A: "U",
};

jQuery or Javascript - how to disable window scroll without overflow:hidden;

Following Glens idea, here it goes another possibility. It would allow you to scroll inside the div, but would prevent the body to scroll with it, when the div scroll ends. However, it seems to accumulate too many preventDefault if you scroll too much, and then it creates a lag if you want to scroll up. Does anybody have a suggestion to fix that?

    $(".scrollInsideThisDiv").bind("mouseover",function(){
       var bodyTop = document.body.scrollTop;
       $('body').on({
           'mousewheel': function(e) {
           if (document.body.scrollTop == bodyTop) return;
           e.preventDefault();
           e.stopPropagation();
           }
       });
    });
    $(".scrollInsideThisDiv").bind("mouseleave",function(){
          $('body').unbind("mousewheel");
    });

Converting a generic list to a CSV string

Any solution work only if List a list(of string)

If you have a generic list of your own Objects like list(of car) where car has n properties, you must loop the PropertiesInfo of each car object.

Look at: http://www.csharptocsharp.com/generate-csv-from-generic-list

Python - How to convert JSON File to Dataframe

Creating dataframe from dictionary object.

import pandas as pd
data = [{'name': 'vikash', 'age': 27}, {'name': 'Satyam', 'age': 14}]
df = pd.DataFrame.from_dict(data, orient='columns')

df
Out[4]:
   age  name
0   27  vikash
1   14  Satyam

If you have nested columns then you first need to normalize the data:

data = [
  {
    'name': {
      'first': 'vikash',
      'last': 'singh'
    },
    'age': 27
  },
  {
    'name': {
      'first': 'satyam',
      'last': 'singh'
    },
    'age': 14
  }
]

df = pd.DataFrame.from_dict(pd.json_normalize(data), orient='columns')

df    
Out[8]:
age name.first  name.last
0   27  vikash  singh
1   14  satyam  singh

Source:

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

I do some quick tests and have the following findings:

1) if using SynchronousQueue:

After the threads reach the maximum size, any new work will be rejected with the exception like below.

Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@3fee733d rejected from java.util.concurrent.ThreadPoolExecutor@5acf9800[Running, pool size = 3, active threads = 3, queued tasks = 0, completed tasks = 0]

at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)

2) if using LinkedBlockingQueue:

The threads never increase from minimum size to maximum size, meaning the thread pool is fixed size as the minimum size.

How can multiple rows be concatenated into one in Oracle without creating a stored procedure?

Easy:

SELECT question_id, wm_concat(element_id) as elements
FROM   questions
GROUP BY question_id;

Pesonally tested on 10g ;-)

From http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php

Which MIME type to use for a binary file that's specific to my program?

I'd recommend application/octet-stream as RFC2046 says "The "octet-stream" subtype is used to indicate that a body contains arbitrary binary data" and "The recommended action for an implementation that receives an "application/octet-stream" entity is to simply offer to put the data in a file[...]".

I think that way you will get better handling from arbitrary programs, that might barf when encountering your unknown mime type.

installing urllib in Python3.6

yu have to install the correct version for your computer 32 or 63 bits thats all

Pros/cons of using redux-saga with ES6 generators vs redux-thunk with ES2017 async/await

Having reviewed a few different large scale React/Redux projects in my experience Sagas provide developers a more structured way of writing code that is much easier to test and harder to get wrong.

Yes it is a little wierd to start with, but most devs get enough of an understanding of it in a day. I always tell people to not worry about what yield does to start with and that once you write a couple of test it will come to you.

I have seen a couple of projects where thunks have been treated as if they are controllers from the MVC patten and this quickly becomes an unmaintable mess.

My advice is to use Sagas where you need A triggers B type stuff relating to a single event. For anything that could cut across a number of actions, I find it is simpler to write customer middleware and use the meta property of an FSA action to trigger it.

How to keep one variable constant with other one changing with row in excel

=(B0+4)/($A$0)

$ means keep same (press a few times F4 after typing A4 to flip through combos quick!)

Converting LastLogon to DateTime format

DateTime.FromFileTime should do the trick:

PS C:\> [datetime]::FromFileTime(129948127853609000)

Monday, October 15, 2012 3:13:05 PM

Then depending on how you want to format it, check out standard and custom datetime format strings.

PS C:\> [datetime]::FromFileTime(129948127853609000).ToString('d MMMM')
15 October
PS C:\> [datetime]::FromFileTime(129948127853609000).ToString('g')
10/15/2012 3:13 PM

If you want to integrate this into your one-liner, change your select statement to this:

... | Select Name, manager, @{N='LastLogon'; E={[DateTime]::FromFileTime($_.LastLogon)}} | ...

How to call a method in another class in Java?

in School,

public void addTeacherName(classroom classroom, String teacherName) {
    classroom.setTeacherName(teacherName);
}

BTW, use Pascal Case for class names. Also, I would suggest a Map<String, classroom> to map a classroom name to a classroom.

Then, if you use my suggestion, this would work

public void addTeacherName(String className, String teacherName) {
    classrooms.get(className).setTeacherName(teacherName);
}

How to detect when facebook's FB.init is complete

The Facebook API watches for the FB._apiKey so you can watch for this before calling your own application of the API with something like:

window.fbAsyncInit = function() {
  FB.init({
    //...your init object
  });
  function myUseOfFB(){
    //...your FB API calls
  };
  function FBreadyState(){
    if(FB._apiKey) return myUseOfFB();
    setTimeout(FBreadyState, 100); // adjust time as-desired
  };
  FBreadyState();
}; 

Not sure this makes a difference but in my case--because I wanted to be sure the UI was ready--I've wrapped the initialization with jQuery's document ready (last bit above):

  $(document).ready(FBreadyState);

Note too that I'm NOT using async = true to load Facebook's all.js, which in my case seems to be helping with signing into the UI and driving features more reliably.

Get the cell value of a GridView row

Expanding on Dennis R answer above ... This will get the value based on the Heading Text (so you don't need to know what column...especially if its dynamic changing).

Example setting a session variable on SelectedIndexChange.

    protected void gvCustomer_SelectedIndexChanged(object sender, EventArgs e)
    {
        int iCustomerID = Convert.ToInt32(Library.gvGetVal(gvCustomer, "CustomerID"));
        Session[SSS.CustomerID] = iCustomerID;
    }

public class Library
{
    public static string gvGetVal(GridView gvGrid, string sHeaderText)
    {
        string sRetVal = string.Empty;
        if (gvGrid.Rows.Count > 0)
        {
            if (gvGrid.SelectedRow != null)
            {
                GridViewRow row = gvGrid.SelectedRow;
                int iCol = gvGetColumn(gvGrid, sHeaderText);
                if (iCol > -1)
                    sRetVal = row.Cells[iCol].Text;
            }
        }
        return sRetVal;
    }

    private static int gvGetColumn(GridView gvGrid, string sHeaderText)
    {
        int iRetVal = -1;
        for (int i = 0; i < gvGrid.Columns.Count; i++)
        {
            if (gvGrid.Columns[i].HeaderText.ToLower().Trim() == sHeaderText.ToLower().Trim())
            {
                iRetVal = i;
            }
        }
        return iRetVal;
    }
}

Get top first record from duplicate records having no unique identity

SELECT TOP 1000 MAX(tel) FROM TableName WHERE Id IN 
(
SELECT Id FROM TableName
GROUP BY Id
HAVING COUNT(*) > 1
) 
GROUP BY Id

Format date and Subtract days using Moment.js

startdate = moment().subtract(1, 'days').format('DD-MM-YYYY');

jQuery UI Alert Dialog as a replacement for alert()

Just throw an empty, hidden div onto your html page and give it an ID. Then you can use that for your jQuery UI dialog. You can populate the text just like you normally would with any jquery call.

How to toggle boolean state of react component?

Depending on your context; this will allow you to update state given the mouseEnter function. Either way, by setting a state value to either true:false you can update that state value given any function by setting it to the opposing value with !this.state.variable

state = {
  hover: false
}

onMouseEnter = () => {
  this.setState({
    hover: !this.state.hover
  });
};

LaTeX source code listing like in professional books

For R code I use

\usepackage{listings}
\lstset{
language=R,
basicstyle=\scriptsize\ttfamily,
commentstyle=\ttfamily\color{gray},
numbers=left,
numberstyle=\ttfamily\color{gray}\footnotesize,
stepnumber=1,
numbersep=5pt,
backgroundcolor=\color{white},
showspaces=false,
showstringspaces=false,
showtabs=false,
frame=single,
tabsize=2,
captionpos=b,
breaklines=true,
breakatwhitespace=false,
title=\lstname,
escapeinside={},
keywordstyle={},
morekeywords={}
}

And it looks exactly like this

enter image description here

How to allow only numbers in textbox in mvc4 razor

This worked for me :

<input type="text" class="numericOnly" placeholder="Search" id="txtSearch">

Javacript:

//Allow users to enter numbers only
$(".numericOnly").bind('keypress', function (e) {
    if (e.keyCode == '9' || e.keyCode == '16') {
        return;
    }
    var code;
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which;
    if (e.which == 46)
        return false;
    if (code == 8 || code == 46)
        return true;
    if (code < 48 || code > 57)
        return false;
});

//Disable paste
$(".numericOnly").bind("paste", function (e) {
    e.preventDefault();
});

$(".numericOnly").bind('mouseenter', function (e) {
    var val = $(this).val();
    if (val != '0') {
        val = val.replace(/[^0-9]+/g, "")
        $(this).val(val);
    }
});

How to loop and render elements in React-native?

If u want a direct/ quick away, without assing to variables:

{
 urArray.map((prop, key) => {
     console.log(emp);
     return <Picker.Item label={emp.Name} value={emp.id} />;
 })
}

How do I convert a numpy array to (and display) an image?

Supplement for doing so with matplotlib. I found it handy doing computer vision tasks. Let's say you got data with dtype = int32

from matplotlib import pyplot as plot
import numpy as np

fig = plot.figure()
ax = fig.add_subplot(1, 1, 1)
# make sure your data is in H W C, otherwise you can change it by
# data = data.transpose((_, _, _))
data = np.zeros((512,512,3), dtype=np.int32)
data[256,256] = [255,0,0]
ax.imshow(data.astype(np.uint8))

Annotations from javax.validation.constraints not working

You should use Validator to check whether you class is valid.

Person person = ....;
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
Set<ConstraintViolation<Person>> violations = validator.validate(person);

Then, iterating violations set, you can find violations.

How many characters in varchar(max)

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

varchar [ ( n | max ) ] Variable-length, non-Unicode character data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of data entered + 2 bytes. The data entered can be 0 characters in length. The ISO synonyms for varchar are char varying or character varying.

1 character = 1 byte. And don't forget 2 bytes for the termination. So, 2^31-3 characters.

Difference between System.DateTime.Now and System.DateTime.Today

The DateTime.Now property returns the current date and time, for example 2011-07-01 10:09.45310.

The DateTime.Today property returns the current date with the time compnents set to zero, for example 2011-07-01 00:00.00000.

The DateTime.Today property actually is implemented to return DateTime.Now.Date:

public static DateTime Today {
  get {
    DateTime now = DateTime.Now;
    return now.Date;
  }
}

How can I convert a Unix timestamp to DateTime and vice versa?

Unix time conversion is new in .NET Framework 4.6.

You can now more easily convert date and time values to or from .NET Framework types and Unix time. This can be necessary, for example, when converting time values between a JavaScript client and .NET server. The following APIs have been added to the DateTimeOffset structure:

static DateTimeOffset FromUnixTimeSeconds(long seconds)
static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds)
long DateTimeOffset.ToUnixTimeSeconds()
long DateTimeOffset.ToUnixTimeMilliseconds()

Access localhost from the internet

Try with your IP Address , I think you can access it by internet.

How to make a local variable (inside a function) global

Simply declare your variable outside any function:

globalValue = 1

def f(x):
    print(globalValue + x)

If you need to assign to the global from within the function, use the global statement:

def f(x):
    global globalValue
    print(globalValue + x)
    globalValue += 1

How to convert vector to array

We can do this using data() method. C++11 provides this method.

Code Snippet

#include<bits/stdc++.h>
using namespace std;


int main()
{
  ios::sync_with_stdio(false);

  vector<int>v = {7, 8, 9, 10, 11};
  int *arr = v.data();

  for(int i=0; i<v.size(); i++)
  {
    cout<<arr[i]<<" ";
  }

  return 0;
}

How to get an absolute file path in Python

import os
os.path.abspath(os.path.expanduser(os.path.expandvars(PathNameString)))

Note that expanduser is necessary (on Unix) in case the given expression for the file (or directory) name and location may contain a leading ~/(the tilde refers to the user's home directory), and expandvars takes care of any other environment variables (like $HOME).

Send POST request using NSURLSession

Motivation

Sometimes I have been getting some errors when you want to pass httpBody serialized to Data from Dictionary, which on most cases is due to the wrong encoding or malformed data due to non NSCoding conforming objects in the Dictionary.

Solution

Depending on your requirements one easy solution would be to create a String instead of Dictionary and convert it to Data. You have the code samples below written on Objective-C and Swift 3.0.

Objective-C

// Create the URLSession on the default configuration
NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];

// Setup the request with URL
NSURL *url = [NSURL URLWithString:@"yourURL"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];

// Convert POST string parameters to data using UTF8 Encoding
NSString *postParams = @"api_key=APIKEY&[email protected]&password=password";
NSData *postData = [postParams dataUsingEncoding:NSUTF8StringEncoding];

// Convert POST string parameters to data using UTF8 Encoding
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:postData];

// Create dataTask
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    // Handle your response here
}];

// Fire the request
[dataTask resume];

Swift

// Create the URLSession on the default configuration
let defaultSessionConfiguration = URLSessionConfiguration.default
let defaultSession = URLSession(configuration: defaultSessionConfiguration)

// Setup the request with URL
let url = URL(string: "yourURL")
var urlRequest = URLRequest(url: url!)  // Note: This is a demo, that's why I use implicitly unwrapped optional

// Convert POST string parameters to data using UTF8 Encoding
let postParams = "api_key=APIKEY&[email protected]&password=password"
let postData = postParams.data(using: .utf8)

// Set the httpMethod and assign httpBody
urlRequest.httpMethod = "POST"
urlRequest.httpBody = postData

// Create dataTask
let dataTask = defaultSession.dataTask(with: urlRequest) { (data, response, error) in
    // Handle your response here
}

// Fire the request
dataTask.resume()

PHP Get Site URL Protocol - http vs https

Some changes:

function siteURL() {
  $protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || 
    $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
  $domainName = $_SERVER['HTTP_HOST'];
  return $protocol.$domainName;
}

Basic communication between two fragments

I recently created a library that uses annotations to generate those type casting boilerplate code for you. https://github.com/zeroarst/callbackfragment

Here is an example. Click a TextView on DialogFragment triggers a callback to MainActivity in onTextClicked then grab the MyFagment instance to interact with.

public class MainActivity extends AppCompatActivity implements MyFragment.FragmentCallback, MyDialogFragment.DialogListener {

private static final String MY_FRAGM = "MY_FRAGMENT";
private static final String MY_DIALOG_FRAGM = "MY_DIALOG_FRAGMENT";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    getSupportFragmentManager().beginTransaction()
        .add(R.id.lo_fragm_container, MyFragmentCallbackable.create(), MY_FRAGM)
        .commit();

    findViewById(R.id.bt).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MyDialogFragmentCallbackable.create().show(getSupportFragmentManager(), MY_DIALOG_FRAGM);
        }
    });
}

Toast mToast;

@Override
public void onClickButton(MyFragment fragment) {
    if (mToast != null)
        mToast.cancel();
    mToast = Toast.makeText(this, "Callback from " + fragment.getTag() + " to " + this.getClass().getSimpleName(), Toast.LENGTH_SHORT);
    mToast.show();
}

@Override
public void onTextClicked(MyDialogFragment fragment) {
    MyFragment myFragm = (MyFragment) getSupportFragmentManager().findFragmentByTag(MY_FRAGM);
    if (myFragm != null) {
        myFragm.updateText("Callback from " + fragment.getTag() + " to " + myFragm.getTag());
    }
}

}

how to access the command line for xampp on windows

In case some one wants to know how to set up Environment variables

  1. Click on the windows button on the bottom left and go to System
  2. Click the Advanced System Settings link in the left column
  3. In the System Properties window, click on the Advanced tab, then click the Environment Variables button near the bottom of that tab.
  4. In the Environment Variables window , highlight the Path variable in the "System variables" section and click the Edit button. Add the path lines with the paths you want the computer to access.

Once you have done that you can run using the command from the start->command line as below

php <path to file location>