Programs & Examples On #Lockdown

How to decrypt an encrypted Apple iTunes iPhone backup?

Sorry, but it might even be more complicated, involving pbkdf2, or even a variation of it. Listen to the WWDC 2010 session #209, which mainly talks about the security measures in iOS 4, but also mentions briefly the separate encryption of backups and how they're related.

You can be pretty sure that without knowing the password, there's no way you can decrypt it, even by brute force.

Let's just assume you want to try to enable people who KNOW the password to get to the data of their backups.

I fear there's no way around looking at the actual code in iTunes in order to figure out which algos are employed.

Back in the Newton days, I had to decrypt data from a program and was able to call its decryption function directly (knowing the password, of course) without the need to even undersand its algorithm. It's not that easy anymore, unfortunately.

I'm sure there are skilled people around who could reverse engineer that iTunes code - you just have to get them interested.

In theory, Apple's algos should be designed in a way that makes the data still safe (i.e. practically unbreakable by brute force methods) to any attacker knowing the exact encryption method. And in WWDC session 209 they went pretty deep into details about what they do to accomplish this. Maybe you can actually get answers directly from Apple's security team if you tell them your good intentions. After all, even they should know that security by obfuscation is not really efficient. Try their security mailing list. Even if they do not repond, maybe someone else silently on the list will respond with some help.

Good luck!

Temporarily disable all foreign key constraints

Disable all table constraints

ALTER TABLE TableName NOCHECK CONSTRAINT ConstraintName

-- Enable all table constraints

ALTER TABLE TableName CHECK CONSTRAINT ConstraintName

int to hex string

Try C# string interpolation introduced in C# 6:

var id = 100;
var hexid = $"0x{id:X}";

hexid value:

"0x64"

check if file exists in php

file_exists checks whether a file exist in the specified path or not.

Syntax:

file_exists ( string $filename )

Returns TRUE if the file or directory specified by filename exists; FALSE otherwise.

$filename = BASE_DIR."images/a/test.jpg";
if (file_exists($filename)){
    echo "File exist.";
}else{
    echo "File does not exist.";
}

Another alternative method you can use getimagesize(), it will return 0(zero) if file/directory is not available in the specified path.

if (@getimagesize($filename)) {...}

What is pipe() function in Angular

The Pipes you are talking about in the starting description are different from the pipe you showed in the example.

In Angular(2|4|5) Pipes are used to format view as you said. I think you have a basic understanding of pipes in Angular, you can learn more about that from this link - Angular Pipe Doc

The pipe() you have shown in the example is the pipe() method of RxJS 5.5 (RxJS is the default for all Angular apps). In Angular5 all the RxJS operators can be imported using single import and they are now combined using the pipe method.

tap() - RxJS tap operator will look at the Observable value and do something with that value. In other words, after a successful API request, the tap() operator will do any function you want it to perform with the response. In the example, it will just log that string.

catchError() - catchError does exactly the same thing but with error response. If you want to throw an error or want to call some function if you get an error, you can do it here. In the example, it will call handleError() and inside that, it will just log that string.

How to import local packages without gopath

I have a similar problem and the solution I am currently using uses Go 1.11 modules. I have the following structure

- projects
  - go.mod
  - go.sum
  - project1
    - main.go
  - project2
    - main.go
  - package1
    - lib.go
  - package2
    - lib.go

And I am able to import package1 and package2 from project1 and project2 by using

import (
    "projects/package1"
    "projects/package2"
)

After running go mod init projects. I can use go build from project1 and project2 directories or I can do go build -o project1/exe project1/*.go from the projects directory.

The downside of this method is that all your projects end up sharing the same dependency list in go.mod. I am still looking for a solution to this problem, but it looks like it might be fundamental.

How to watch and reload ts-node when TypeScript files change

you could use ts-node-dev

It restarts target node process when any of required files changes (as standard node-dev) but shares Typescript compilation process between restarts.

Install

yarn add ts-node-dev --dev

and your package.json could be like this

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "tsc": "tsc",
  "dev": "ts-node-dev --respawn --transpileOnly ./src/index.ts",
  "prod": "tsc && node ./build/index.js"
}

Get current date/time in seconds

I use this:

Math.round(Date.now() / 1000)

No need for new object creation (see doc Date.now())

Creating a URL in the controller .NET MVC

Another way to create an absolute URL to an action:

var relativeUrl = Url.Action("MyAction");  //..or one of the other .Action() overloads
var currentUrl = Request.Url;

var absoluteUrl = new System.Uri(currentUrl, relativeUrl);

read string from .resx file in C#

Once you add a resource (Name: ResourceName and Value: ResourceValue) to the solution/assembly, you could simply use "Properties.Resources.ResourceName" to get the required resource.

Is it possible to force Excel recognize UTF-8 CSV files automatically?

If you want to make it fully automatic, one click, or to load automatically into Excel from say a web page, but can't generate proper Excel files, then I would suggest looking at SYLK format as an alternative. OK it is not as simple as CSV but it is text based and very easy to implement and it supports UTF-8 with no issues.

I wrote a PHP class that receives the data and outputs a SYLK file which will open directly in Excel by just clicking the file (or will auto-launch Excel if you write the file to a web page with the correct mime type. You can even add formatting (like bold, format numbers in particular ways etc) and change column sizes, or auto size columns to the text in the columns and all in all the code is probably not more than about 100 lines.

It is dead easy to reverse engineer SYLK by creating a simple spreadsheet and saving as SYLK and then reading it with a text editor. The first block are headers and standard number formats that you will recognise (which you just regurgitate in every file you create), then the data is simply an X/Y coordinate and a value.

Not able to pip install pickle in python 3.6

import pickle

intArray = [i for i in range(1,100)]
output = open('data.pkl', 'wb')
pickle.dump(intArray, output)
output.close()

Test your pickle quickly. pickle is a part of standard python library and available by default.

Wavy shape with css

My implementation uses the svg element in html and I also made a generator for making the wave you want:

https://smooth.ie/blogs/news/svg-wavey-transitions-between-sections

<div style="height: 150px; overflow: hidden;">
  <svg viewBox="0 0 500 150" preserveAspectRatio="none" style="height: 100%; width: 100%;">
    <path d="M0.00,92.27 C216.83,192.92 304.30,8.39 500.00,109.03 L500.00,0.00 L0.00,0.00 Z" style="stroke: none;fill: #e1efe3;"></path>
  </svg>
</div>

https://jsfiddle.net/1b8L7nax/5/

How do I tell if a regular file does not exist in Bash?

You should be careful about running test for an unquoted variable, because it might produce unexpected results:

$ [ -f ]
$ echo $?
0
$ [ -f "" ]
$ echo $?
1

The recommendation is usually to have the tested variable surrounded by double quotation marks:

#!/bin/sh
FILE=$1

if [ ! -f "$FILE" ]
then
   echo "File $FILE does not exist."
fi

How to make a div center align in HTML

I think that the the align="center" aligns the content, so if you wanted to use that method, you would need to use it in a 'wraper' div - a div that just wraps the rest.

text-align is doing a similar sort of thing.

left:50% is ignored unless you set the div's position to be something like relative or absolute.

The generally accepted methods is to use the following properties

width:500px; // this can be what ever unit you want, you just have to define it
margin-left:auto;
margin-right:auto;

the margins being auto means they grow/shrink to match the browser window (or parent div)

UPDATE

Thanks to Meo for poiting this out, if you wanted to you could save time and use the short hand propery for the margin.

margin:0 auto;

this defines the top and bottom as 0 (as it is zero it does not matter about lack of units) and the left and right get defined as 'auto' You can then, if you wan't override say the top margin as you would with any other CSS rules.

ActionBarActivity: cannot be resolved to a type

UPDATE:

Since the version 22.1.0, the class ActionBarActivity is deprecated, so instead use AppCompatActivity. For more details see here

Using ActionBarActivity:

In Eclipse:

1 - Make sure library project(appcompat_v7) is open & is proper referenced (added as library) in your application project.

2 - Delete android-support-v4.jar from your project's libs folder(if jar is present).

3 - Appcompat_v7 must have android-support-v4.jar & android-support-v7-appcompat.jar inside it's libs folder. (If jars are not present copy them from /sdk/extras/android/support/v7/appcompat/libs folder of your installed android sdk location)

4- Check whether ActionBarActivity is properly imported.

import android.support.v7.app.ActionBarActivity;

In Android Studio

Just add compile dependencies to app's build.gradle

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.1.1'
}

Exit a Script On Error

exit 1 is all you need. The 1 is a return code, so you can change it if you want, say, 1 to mean a successful run and -1 to mean a failure or something like that.

How to identify whether a grammar is LL(1), LR(0) or SLR(1)?

Simple answer:A grammar is said to be an LL(1),if the associated LL(1) parsing table has atmost one production in each table entry.

Take the simple grammar A -->Aa|b.[A is non-terminal & a,b are terminals]
   then find the First and follow sets A.
    First{A}={b}.
    Follow{A}={$,a}.

    Parsing table for Our grammar.Terminals as columns and Nonterminal S as a row element.

        a            b                   $
    --------------------------------------------
 S  |               A-->a                      |
    |               A-->Aa.                    |
    -------------------------------------------- 

As [S,b] contains two Productions there is a confusion as to which rule to choose.So it is not LL(1).

Some simple checks to see whether a grammar is LL(1) or not. Check 1: The Grammar should not be left Recursive. Example: E --> E+T. is not LL(1) because it is Left recursive. Check 2: The Grammar should be Left Factored.

Left factoring is required when two or more grammar rule choices share a common prefix string. Example: S-->A+int|A.

Check 3:The Grammar should not be ambiguous.

These are some simple checks.

There is an error in XML document (1, 41)

First check the variables declared using proper Datatypes. I had a same problem then I have checked, by mistake I declared SAPUser as int datatype so that the error occurred. One more thing XML file stores its data using concept like array but its first index starts having +1. e.g. if error is in(7,2) then check for 6th line always.....

What is the difference between i++ & ++i in a for loop?

The way for loop is processed is as follows

1 First, initialization is performed (i=0)

2 the check is performed (i < n)

3 the code in the loop is executed.

4 the value is incremented

5 Repeat steps 2 - 4

This is the reason why, there is no difference between i++ and ++i in the for loop which has been used.

Add onClick event to document.createElement("th")

var newTH = document.createElement('th');
newTH.setAttribute("onclick", "removeColumn(#)");
newTH.setAttribute("id", "#");

function removeColumn(#){
// remove column #
}

Does swift have a trim method on String?

extension String {
    /// EZSE: Trims white space and new line characters
    public mutating func trim() {
         self = self.trimmed()
    }

    /// EZSE: Trims white space and new line characters, returns a new string
    public func trimmed() -> String {
        return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    }
}

Taken from this repo of mine: https://github.com/goktugyil/EZSwiftExtensions/commit/609fce34a41f98733f97dfd7b4c23b5d16416206

Regular expression to match a dot

"In the default mode, Dot (.) matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline." (python Doc)

So, if you want to evaluate dot literaly, I think you should put it in square brackets:

>>> p = re.compile(r'\b(\w+[.]\w+)')
>>> resp = p.search("blah blah blah [email protected] blah blah")
>>> resp.group()
'test.this'

How to add to the PYTHONPATH in Windows, so it finds my modules/packages?

This PYTHONPATH variable needs to be set for ArcPY when ArcGIS Desktop is installed.

PYTHONPATH=C:\arcgis\bin (your ArcGIS home bin)

For some reason it never was set when I used the installer on a Windows 7 32-bit system.

How to connect from windows command prompt to mysql command line

Please perform the following steps

  1. First, open your command prompt with Administrator.
  2. Go to MySQL installed directory and copy path and past on command prompt like:- C:\Program Files\MySQL\MySQL Server 5.7\bin>

  3. C:\Program Files\MySQL\MySQL Server 5.7\bin>mysql -uroot -p [-u for username -p for password]

  4. C:\Program Files\MySQL\MySQL Server 5.7\bin>mysql -uroot -p Enter password: **** [enter your password here]

1 first image

Mysql service is missing

I came across the same problem. I properly installed the MYSQL Workbench 6.x, but faced the connection as below:

enter image description here

I did a bit R&D on this and found that MySQL service in service.msc is not present. To achieve this I created a new connection in MySQL Workbench then manually configured the MySQL Database Server in "System Profile" (see the below picture).

You also need to install MySQL Database Server and set a configuration file path for my.ini. Now at last test the connection (make sure MySQL service is running in services.msc).

enter image description here

round a single column in pandas

If you are doing machine learning and use tensorflow, many float are of 'float32', not 'float64', and none of the methods mentioned in this thread likely to work. You will have to first convert to float64 first.

x.astype('float')

before round(...).

Change a Nullable column to NOT NULL with Default Value

You may have to first update all the records that are null to the default value then use the alter table statement.

Update dbo.TableName
Set
Created="01/01/2000"
where Created is NULL

How to check type of files without extensions in python?

In the case of images, you can use the imghdr module.

>>> import imghdr
>>> imghdr.what('8e5d7e9d873e2a9db0e31f9dfc11cf47')  # You can pass a file name or a file object as first param. See doc for optional 2nd param.
'png'

Python 2 imghdr doc
Python 3 imghdr doc

Regular expression for a hexadecimal number?

In case you need this within an input where the user can type 0 and 0x too but not a hex number without the 0x prefix:

^0?[xX]?[0-9a-fA-F]*$

cmake and libpthread

@Manuel was part way there. You can add the compiler option as well, like this:

If you have CMake 3.1.0+, this becomes even easier:

set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
target_link_libraries(my_app PRIVATE Threads::Threads)

If you are using CMake 2.8.12+, you can simplify this to:

find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
  target_compile_options(my_app PUBLIC "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
  target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
endif()

Older CMake versions may require:

find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
  set_property(TARGET my_app PROPERTY COMPILE_OPTIONS "-pthread")
  set_property(TARGET my_app PROPERTY INTERFACE_COMPILE_OPTIONS "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
  target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
endif()

If you want to use one of the first two methods with CMake 3.1+, you will need set(THREADS_PREFER_PTHREAD_FLAG ON) there too.

Set inputType for an EditText Programmatically?

For Kotlin:

    val password = EditText(this)
    password.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
    password.hint = "Password"

What is the maximum number of characters that nvarchar(MAX) will hold?

From char and varchar (Transact-SQL)

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.

How to run sql script using SQL Server Management Studio?

Open SQL Server Management Studio > File > Open > File > Choose your .sql file (the one that contains your script) > Press Open > the file will be opened within SQL Server Management Studio, Now all what you need to do is to press Execute button.

Maven build debug in Eclipse

The Run/Debug configuration you're using is meant to let you run Maven on your workspace as if from the command line without leaving Eclipse.

Assuming your tests are JUnit based you should be able to debug them by choosing a source folder containing tests with the right button and choose Debug as... -> JUnit tests.

RecyclerView: Inconsistency detected. Invalid item position

I had a same issue previously. Finally found a workaround for that

What i do is to notify adapter that item has removed and then notify adapter data set range changed

 public void setData(List<Data> dataList) {
      if (this.dataList.size() > 0) {
          notifyItemRangeRemoved(0, dataList.size());
          this.dataList.clear();
      }
      this.dataList.addAll(dataList)
      notifyItemRangeChanged(0, dataList.size());

 }

Reading NFC Tags with iPhone 6 / iOS 8

At the moment, Apple has not opened any access to the embedded NFC chip to developers as suggested by many articles such as these ones :

The list goes on. The main reason seems (like lots the other hardware features added to the iPhone in the past) that Apple wants to ensure the security of such technology before releasing any API for developers to let them do whatever they want. So at first, they will use it internally for their needs only (such as Apple Pay at launch time).

"At the moment, there isn't any open access to the NFC controller," said RapidNFC, a provider of NFC tags. "There are currently no NFC APIs in the iOS 8 GM SDK".

But eventually, I think we can all agree that they will develop such API, it's only a matter of time.

What is the best Java library to use for HTTP POST, GET etc.?

I want to mention the Ning Async Http Client Library. I've never used it but my colleague raves about it as compared to the Apache Http Client, which I've always used in the past. I was particularly interested to learn it is based on Netty, the high-performance asynchronous i/o framework, with which I am more familiar and hold in high esteem.

Is it possible to output a SELECT statement from a PL/SQL block?

From an anonymous block? I'd like to now more about the situation where you think that to be required, because with subquery factoring clauses and inline views it's pretty rare that you need to resort to PL/SQL for anything other than the most complex situations.

If you can use a named procedure then use pipelined functions. Here's an example pulled from the documentation:

CREATE PACKAGE pkg1 AS
  TYPE numset_t IS TABLE OF NUMBER;
  FUNCTION f1(x NUMBER) RETURN numset_t PIPELINED;
END pkg1;
/

CREATE PACKAGE BODY pkg1 AS
-- FUNCTION f1 returns a collection of elements (1,2,3,... x)
FUNCTION f1(x NUMBER) RETURN numset_t PIPELINED IS
  BEGIN
    FOR i IN 1..x LOOP
      PIPE ROW(i);
    END LOOP;
    RETURN;
  END;
END pkg1;
/

-- pipelined function is used in FROM clause of SELECT statement
SELECT * FROM TABLE(pkg1.f1(5));

Detecting iOS orientation change instantly

Try making your changes in:

- (void) viewWillLayoutSubviews {}

The code will run at every orientation change as the subviews get laid out again.

ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings

If you are using the local server, run Django shell using python manage.py shell. It will take you to the Django python environment and you are good to go.

SQL Server procedure declare a list

That is not possible with a normal query since the in clause needs separate values and not a single value containing a comma separated list. One solution would be a dynamic query

declare @myList varchar(100)
set @myList = '(1,2,5,7,10)'
exec('select * from DBTable where id IN ' + @myList)

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

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

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

How do I skip an iteration of a `foreach` loop?

Another approach using linq is:

foreach ( int number in numbers.Skip(1))
{   
    // process number  
}

If you want to skip the first in a number of items.

Or use .SkipWhere if you want to specify a condition for skipping.

Compiling dynamic HTML strings from database

In angular 1.2.10 the line scope.$watch(attrs.dynamic, function(html) { was returning an invalid character error because it was trying to watch the value of attrs.dynamic which was html text.

I fixed that by fetching the attribute from the scope property

 scope: { dynamic: '=dynamic'}, 

My example

angular.module('app')
  .directive('dynamic', function ($compile) {
    return {
      restrict: 'A',
      replace: true,
      scope: { dynamic: '=dynamic'},
      link: function postLink(scope, element, attrs) {
        scope.$watch( 'dynamic' , function(html){
          element.html(html);
          $compile(element.contents())(scope);
        });
      }
    };
  });

How can I convert a PFX certificate file for use with Apache on a linux server?

To get it to work with Apache, we needed one extra step.

openssl pkcs12 -in domain.pfx -clcerts -nokeys -out domain.cer
openssl pkcs12 -in domain.pfx -nocerts -nodes  -out domain_encrypted.key
openssl rsa -in domain_encrypted.key -out domain.key

The final command decrypts the key for use with Apache. The domain.key file should look like this:

-----BEGIN RSA PRIVATE KEY-----
MjQxODIwNTFaMIG0MRQwEgYDVQQKEwtFbnRydXN0Lm5ldDFAMD4GA1UECxQ3d3d3
LmVudHJ1c3QubmV0L0NQU18yMDQ4IGluY29ycC4gYnkgcmVmLiAobGltaXRzIGxp
YWIuKTElMCMGA1UECxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEG
A1UEAxMqRW50cnVzdC5uZXQgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgKDIwNDgp
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArU1LqRKGsuqjIAcVFmQq
-----END RSA PRIVATE KEY-----

Conditionally formatting cells if their value equals any value of another column

No formulas required. This works on as many columns as you need, but will only compare columns in the same worksheet:

NOTE: remove any duplicates from the individual columns first!

  1. Select the columns to compare
  2. click Conditional Formatting
  3. click Highlight Cells Rules
  4. click Duplicate Values (the defaults should be OK)
  5. Duplicates are now highlighted in red

    • Bonus tip, you can filter each row by colour to either leave the unique values in the column, or leave just the duplicates.

enter image description here enter image description here

How do I create a pause/wait function using Qt?

If you want a cross-platform method of doing this, the general pattern is to derive from QThread and create a function (static, if you'd like) in your derived class that will call one of the sleep functions in QThread.

How to produce a range with step n in bash? (generate a sequence of numbers with increments)

Bash 4's brace expansion has a step feature:

for {0..10..2}; do
  ..
done

No matter if Bash 2/3 (C-style for loop, see answers above) or Bash 4, I would prefer anything over the 'seq' command.

How to use youtube-dl from a python program?

If youtube-dl is a terminal program, you can use the subprocess module to access the data you want.

Check out this link for more details: Calling an external command in Python

How to detect escape key press with pure JS or jQuery?

Note: keyCode is becoming deprecated, use key instead.

function keyPress (e) {
    if(e.key === "Escape") {
        // write your logic here.
    }
}

Code Snippet:

_x000D_
_x000D_
var msg = document.getElementById('state-msg');

document.body.addEventListener('keypress', function(e) {
  if (e.key == "Escape") {
    msg.textContent += 'Escape pressed:'
  }
});
_x000D_
Press ESC key <span id="state-msg"></span>
_x000D_
_x000D_
_x000D_


keyCode is becoming deprecated

It seems keydown and keyup work, even though keypress may not


$(document).keyup(function(e) {
     if (e.key === "Escape") { // escape key maps to keycode `27`
        // <DO YOUR WORK HERE>
    }
});

Which keycode for escape key with jQuery

How can I show the table structure in SQL Server query?

I was trying 'DESC table_name' but then this worked for me in psql:

select * 
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='table_name'; 

Is HTML considered a programming language?

List it under technologies or something. I'd just leave it off if I were you as it's pretty much expected that you know HTML and XML at this point.

How to disable and then enable onclick event on <div> with javascript

First of all this is JavaScript and not C#

Then you cannot disable a div because it normally has no functionality. To disable a click event, you simply have to remove the event from the dom object. (bind and unbind)...

How to rotate portrait/landscape Android emulator?

See the Android documentation on controlling the emulator; it's Ctrl + F11 / Ctrl + F12.

On ThinkPad running Ubuntu, you may try CTRL + Left Arrow Key or Right Arrow Key

Mongodb service won't start

I tried deleting the lock file, but the real reason that this happened to me was because I was using ~/data/db as the data directory. Mongo needs an absolute path to the database. Once I changed it to /home//data/db, I was in business.

Storyboard - refer to ViewController in AppDelegate

For iOS 13+

in SceneDelegate:

var window: UIWindow?

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options 
connectionOptions: UIScene.ConnectionOptions) {
    guard let windowScene = (scene as? UIWindowScene) else { return }
    window = UIWindow(windowScene: windowScene)
    let storyboard = UIStoryboard(name: "Main", bundle: nil) // Where "Main" is the storyboard file name
    let vc = storyboard.instantiateViewController(withIdentifier: "ViewController") // Where "ViewController" is the ID of your viewController
    window?.rootViewController = vc
    window?.makeKeyAndVisible()
}

Google Chrome Full Black Screen

You can turn off GPU usage by Chrome without Windows restart in safe mode. Options:

1) by inserting section in Chrome config file "%USERPROFILE%\AppData\Local\Google\Chrome\User Data\Local State":

"hardware_acceleration_mode": { "enabled": false },

2) chrome.exe --disable-gpu

jQuery Validate Plugin - How to create a simple custom rule?

$(document).ready(function(){
    var response;
    $.validator.addMethod(
        "uniqueUserName", 
        function(value, element) {
            $.ajax({
                type: "POST",
                url: "http://"+location.host+"/checkUser.php",
                data: "checkUsername="+value,
                dataType:"html",
                success: function(msg)
                {
                    //If username exists, set response to true
                    response = ( msg == 'true' ) ? true : false;
                }
             });
            return response;
        },
        "Username is Already Taken"
    );

    $("#regFormPart1").validate({
        username: {
            required: true,
            minlength: 8,
            uniqueUserName: true
        },
        messages: {
            username: {
                required: "Username is required",
                minlength: "Username must be at least 8 characters",
                uniqueUserName: "This Username is taken already"
            }
        }
    });
});

Java: getMinutes and getHours

public static LocalTime time() {
    LocalTime ldt = java.time.LocalTime.now();

    ldt = ldt.truncatedTo(ChronoUnit.MINUTES);
    System.out.println(ldt);
    return ldt;
}

This works for me

Why am I getting an OPTIONS request instead of a GET request?

Just change the "application/json" to "text/plain" and do not forget the JSON.stringify(request):

var request = {Company: sapws.dbName, UserName: username, Password: userpass};
    console.log(request);
    $.ajax({
        type: "POST",
        url: this.wsUrl + "/Login",
        contentType: "text/plain",
        data: JSON.stringify(request),

        crossDomain: true,
    });

Not class selector in jQuery

You need the :not() selector:

$('div[class^="first-"]:not(.first-bar)')

or, alternatively, the .not() method:

$('div[class^="first-"]').not('.first-bar');

Skip to next iteration in loop vba

I use Goto

  For x= 1 to 20

       If something then goto continue

       skip this code

  Continue:

  Next x

How to download a file using a Java REST service and a data stream

Refer this:

@RequestMapping(value="download", method=RequestMethod.GET)
public void getDownload(HttpServletResponse response) {

// Get your file stream from wherever.
InputStream myStream = someClass.returnFile();

// Set the content type and attachment header.
response.addHeader("Content-disposition", "attachment;filename=myfilename.txt");
response.setContentType("txt/plain");

// Copy the stream to the response's output stream.
IOUtils.copy(myStream, response.getOutputStream());
response.flushBuffer();
}

Details at: https://twilblog.github.io/java/spring/rest/file/stream/2015/08/14/return-a-file-stream-from-spring-rest.html

Exception Error c0000005 in VC++

Exception code c0000005 is the code for an access violation. That means that your program is accessing (either reading or writing) a memory address to which it does not have rights. Most commonly this is caused by:

  • Accessing a stale pointer. That is accessing memory that has already been deallocated. Note that such stale pointer accesses do not always result in access violations. Only if the memory manager has returned the memory to the system do you get an access violation.
  • Reading off the end of an array. This is when you have an array of length N and you access elements with index >=N.

To solve the problem you'll need to do some debugging. If you are not in a position to get the fault to occur under your debugger on your development machine you should get a crash dump file and load it into your debugger. This will allow you to see where in the code the problem occurred and hopefully lead you to the solution. You'll need to have the debugging symbols associated with the executable in order to see meaningful stack traces.

What does "all" stand for in a makefile?

A build, as Makefile understands it, consists of a lot of targets. For example, to build a project you might need

  1. Build file1.o out of file1.c
  2. Build file2.o out of file2.c
  3. Build file3.o out of file3.c
  4. Build executable1 out of file1.o and file3.o
  5. Build executable2 out of file2.o

If you implemented this workflow with makefile, you could make each of the targets separately. For example, if you wrote

make file1.o

it would only build that file, if necessary.

The name of all is not fixed. It's just a conventional name; all target denotes that if you invoke it, make will build all what's needed to make a complete build. This is usually a dummy target, which doesn't create any files, but merely depends on the other files. For the example above, building all necessary is building executables, the other files being pulled in as dependencies. So in the makefile it looks like this:

all: executable1 executable2

all target is usually the first in the makefile, since if you just write make in command line, without specifying the target, it will build the first target. And you expect it to be all.

all is usually also a .PHONY target. Learn more here.

Install tkinter for Python

If you're using Python 3 then you must install as follows:

sudo apt-get update
sudo apt-get install python3-tk

Tkinter for Python 2 (python-tk) is different from Python 3's (python3-tk).

SQL Server, division returns zero

Either declare set1 and set2 as floats instead of integers or cast them to floats as part of the calculation:

SET @weight= CAST(@set1 AS float) / CAST(@set2 AS float);

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

Lombok supports var but it's still classified as experimental:

import lombok.experimental.var;

var number = 1; // Inferred type: int
number = 2; // Legal reassign since var is not final
number = "Hi"; // Compilation error since a string cannot be assigned to an int variable
System.out.println(number);

Here is a pitfall to avoid when trying to use it in IntelliJ IDEA. It appears to work as expected though including auto completion and everything. Until there is a "non-hacky" solution (e.g. due to JEP 286: Local-Variable Type Inference), this might be your best bet right now.

Note that val is support by Lombok as well without modifying or creating a lombok.config.

ImportError: No module named 'pygame'

  1. Install and download pygame .whl file.
  2. Move .whl file to your python35/Scripts
  3. Go to cmd
  4. Change directory to python scripts
  5. Type:

    pip install pygame
    

Here is an example:

C:\Users\user\AppData\Local\Programs\Python\Python36-32\Scripts>pip install pygame

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

The simple answer:

  • doing a MOV RBX, 3 and MUL RBX is expensive; just ADD RBX, RBX twice

  • ADD 1 is probably faster than INC here

  • MOV 2 and DIV is very expensive; just shift right

  • 64-bit code is usually noticeably slower than 32-bit code and the alignment issues are more complicated; with small programs like this you have to pack them so you are doing parallel computation to have any chance of being faster than 32-bit code

If you generate the assembly listing for your C++ program, you can see how it differs from your assembly.

Using Pairs or 2-tuples in Java

Here's this exact same question elsewhere, that includes a more robust equals, hash that maerics alludes to:

http://groups.google.com/group/comp.lang.java.help/browse_thread/thread/f8b63fc645c1b487/1d94be050cfc249b

That discussion goes on to mirror the maerics vs ColinD approaches of "should I re-use a class Tuple with an unspecific name, or make a new class with specific names each time I encounter this situation". Years ago I was in the latter camp; I've evolved into supporting the former.

How to override Bootstrap's Panel heading background color?

I tried using custom panel class but it didn't work. So for those who are struggling just like me, you can use inline CSS and it works fine for me.

Here is what my code looks like :

<div class="panel-heading" style="background-image:none;background: #a4c6ff;">

Clicking a checkbox with ng-click does not update the model

Replacing ng-model with ng-checked works for me.

Get only the Date part of DateTime in mssql

This may not be as slick as a one-liner, but I use it to perform date manipulation mainly for reports:

DECLARE @Date datetime
SET @Date = GETDATE()

-- Set all time components to zero
SET @Date = DATEADD(ms, -DATEPART(ms, @Date), @Date) -- milliseconds = 0
SET @Date = DATEADD(ss, -DATEPART(ss, @Date), @Date) -- seconds = 0
SET @Date = DATEADD(mi, -DATEPART(mi, @Date), @Date) -- minutes = 0
SET @Date = DATEADD(hh, -DATEPART(hh, @Date), @Date) -- hours = 0

-- Extra manipulation for month and year
SET @Date = DATEADD(dd, -DATEPART(dd, @Date) + 1, @Date) -- day = 1
SET @Date = DATEADD(mm, -DATEPART(mm, @Date) + 1, @Date) -- month = 1

I use this to get hourly, daily, monthly, and yearly dates used for reporting and performance indicators, etc.

How to do logging in React Native?

There are two options to debug or get output of your react native application when using

Emulator or Real Device

For First Using Emulator: use

react-native log-android or react-native log-ios

to get the log output

on real device.shake your device

so the menu will come from where you select remote debug and it will open this screen in your browser. so you can see your log output in console tab.enter image description here

Could not load the Tomcat server configuration

I've just solved this exact problem on my Ubuntu 14.04 with Eclipse Mars 2.

This could happen when Eclipse is not finding Tomcat's configuration files where they are expected to be. This place is in

$eclipse_workspace_folder/$version_of_your_tomcat_server_at_localhost/

(by default if you didn't changed server's name). So you have to copy all the files under your $tomcat_installation_folder/conf/* to the workspace server's folder.

But it was easier to just remove the server from your server list and add it again. Eclipse will automatically recreate all these files again into the proper folders. Like in the picture below:

enter image description here

In my case I've downloaded tomcat-8.0.35 from the website, so the configuration files needed are in /opt/apache-tomcat-8.0.35/conf/ filesystem.

Just delete the desired server from the Servers view (Window -> Show View -> Servers) and then go to Window -> Preferences -> Server -> Runtime Environment -> Add and add the server again.

How to tell if a <script> tag failed to load

This doesn't need jquery, doesn't need to load the script async, needs no timer nor to have the loaded script set a value. I've tested it in FF, Chrome, and Safari.

<script>
        function loadScript(src) {
          return new Promise(function(resolve, reject) {

            let s = window.document.createElement("SCRIPT");

            s.onload = () => resolve(s);
            s.onerror = () => reject(new Error(src));
            s.src = src;
            // don't bounce to global handler on 404.
            s.addEventListener('error', function() {});
            window.document.head.append(s);
          }); 
        }   
                        
        let successCallback = (result) => {
          console.log(scriptUrl + " loaded.");
        }   
                        
        let failureCallback = (error) => {
          console.log("load failed: " + error.message);
        }   
                        
        loadScript(scriptUrl).then(successCallback, failureCallback);
</script>

How to upgrade Python version to 3.7?

Try this if you are on ubuntu:

sudo apt-get update
sudo apt-get install build-essential libpq-dev libssl-dev openssl libffi-dev zlib1g-dev
sudo apt-get install python3-pip python3.7-dev
sudo apt-get install python3.7

In case you don't have the repository and so it fires a not-found package you first have to install this:

sudo apt-get install -y software-properties-common
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update

more info here: http://devopspy.com/python/install-python-3-6-ubuntu-lts/

Debug assertion failed. C++ vector subscript out of range

this type of error usually occur when you try to access data through the index in which data data has not been assign. for example

//assign of data in to array
for(int i=0; i<10; i++){
   arr[i]=i;
}
//accessing of data through array index
for(int i=10; i>=0; i--){
cout << arr[i];
}

the code will give error (vector subscript out of range) because you are accessing the arr[10] which has not been assign yet.

What are all the possible values for HTTP "Content-Type" header?

If you are using jaxrs or any other, then there will be a class called mediatype.User interceptor before sending the request and compare it against this.

How to get size in bytes of a CLOB column in Oracle?

Try this one for CLOB sizes bigger than VARCHAR2:

We have to split the CLOB in parts of "VARCHAR2 compatible" sizes, run lengthb through every part of the CLOB data, and summarize all results.

declare
   my_sum int;
begin
   for x in ( select COLUMN, ceil(DBMS_LOB.getlength(COLUMN) / 2000) steps from TABLE ) 
   loop
       my_sum := 0;
       for y in 1 .. x.steps
       loop
          my_sum := my_sum + lengthb(dbms_lob.substr( x.COLUMN, 2000, (y-1)*2000+1 ));
          -- some additional output
          dbms_output.put_line('step:' || y );
          dbms_output.put_line('char length:' || DBMS_LOB.getlength(dbms_lob.substr( x.COLUMN, 2000 , (y-1)*2000+1 )));
          dbms_output.put_line('byte length:' || lengthb(dbms_lob.substr( x.COLUMN, 2000, (y-1)*2000+1 )));
          continue;
        end loop;
        dbms_output.put_line('char summary:' || DBMS_LOB.getlength(x.COLUMN));
        dbms_output.put_line('byte summary:' || my_sum);
        continue;
    end loop;
end;
/

maxlength ignored for input type="number" in Chrome

try use tel :

 maxlength="5" type="tel"

Can't include C++ headers like vector in Android NDK

Let me add a little to Sebastian Roth's answer.

Your project can be compiled by using ndk-build in the command line after adding the code Sebastian had posted. But as for me, there were syntax errors in Eclipse, and I didn't have code completion.

Note that your project must be converted to a C/C++ project.

How to convert a C/C++ project

To fix this issue right-click on your project, click Properties

Choose C/C++ General -> Paths and Symbols and include the ${ANDROID_NDK}/sources/cxx-stl/stlport/stlport to Include directories

Click Yes when a dialog shows up.

Dialog

Before

Before

After

After

Update #1

GNU C. Add directories, rebuild. There won't be any errors in C source files
GNU C++. Add directories, rebuild. There won't be any errors in CPP source files.

How can I round a number in JavaScript? .toFixed() returns a string?

You should use it like below.

var someNumber: number = 0.000000;
someNumber = Number(someNumber.toFixed(2))

javascript date to string

A little bit simpler using regex and toJSON().

var now = new Date();
var timeRegex = /^.*T(\d{2}):(\d{2}):(\d{2}).*$/
var dateRegex = /^(\d{4})-(\d{2})-(\d{2})T.*$/
var dateData = dateRegex.exec(now.toJSON());
var timeData = timeRegex.exec(now.toJSON());
var myFormat = dateData[1]+dateData[2]+dateData[3]+timeData[1]+timeData[2]+timeData[3]

Which at the time of writing gives you "20151111180924".

The good thing of using toJSON() is that everything comes already padded.

Difference between "\n" and Environment.NewLine

Depends on the platform. On Windows it is actually "\r\n".

From MSDN:

A string containing "\r\n" for non-Unix platforms, or a string containing "\n" for Unix platforms.

Options for embedding Chromium instead of IE WebBrowser control with WPF/C#

Here is another one:

http://www.essentialobjects.com/Products/WebBrowser/Default.aspx

This one is also based on the latest Chrome engine but it's much easier to use than CEF. It's a single .NET dll that you can simply reference and use.

Two dimensional array list

for (Project project : listOfLists) {
    String nama_project = project.getNama_project();
    if (project.getModelproject().size() > 1) {
        for (int i = 1; i < project.getModelproject().size(); i++) {
            DataModel model = project.getModelproject().get(i);
            int id_laporan = model.getId();
            String detail_pekerjaan = model.getAlamat();
        }
    }
}

How to add a reference programmatically

Ommit

There are two ways to add references via VBA to your projects

1) Using GUID

2) Directly referencing the dll.

Let me cover both.

But first these are 3 things you need to take care of

a) Macros should be enabled

b) In Security settings, ensure that "Trust Access To Visual Basic Project" is checked

enter image description here

c) You have manually set a reference to `Microsoft Visual Basic for Applications Extensibility" object

enter image description here

Way 1 (Using GUID)

I usually avoid this way as I have to search for the GUID in the registry... which I hate LOL. More on GUID here.

Topic: Add a VBA Reference Library via code

Link: http://www.vbaexpress.com/kb/getarticle.php?kb_id=267

'Credits: Ken Puls
Sub AddReference()
     'Macro purpose:  To add a reference to the project using the GUID for the
     'reference library

    Dim strGUID As String, theRef As Variant, i As Long

     'Update the GUID you need below.
    strGUID = "{00020905-0000-0000-C000-000000000046}"

     'Set to continue in case of error
    On Error Resume Next

     'Remove any missing references
    For i = ThisWorkbook.VBProject.References.Count To 1 Step -1
        Set theRef = ThisWorkbook.VBProject.References.Item(i)
        If theRef.isbroken = True Then
            ThisWorkbook.VBProject.References.Remove theRef
        End If
    Next i

     'Clear any errors so that error trapping for GUID additions can be evaluated
    Err.Clear

     'Add the reference
    ThisWorkbook.VBProject.References.AddFromGuid _
    GUID:=strGUID, Major:=1, Minor:=0

     'If an error was encountered, inform the user
    Select Case Err.Number
    Case Is = 32813
         'Reference already in use.  No action necessary
    Case Is = vbNullString
         'Reference added without issue
    Case Else
         'An unknown error was encountered, so alert the user
        MsgBox "A problem was encountered trying to" & vbNewLine _
        & "add or remove a reference in this file" & vbNewLine & "Please check the " _
        & "references in your VBA project!", vbCritical + vbOKOnly, "Error!"
    End Select
    On Error GoTo 0
End Sub

Way 2 (Directly referencing the dll)

This code adds a reference to Microsoft VBScript Regular Expressions 5.5

Option Explicit

Sub AddReference()
    Dim VBAEditor As VBIDE.VBE
    Dim vbProj As VBIDE.VBProject
    Dim chkRef As VBIDE.Reference
    Dim BoolExists As Boolean

    Set VBAEditor = Application.VBE
    Set vbProj = ActiveWorkbook.VBProject

    '~~> Check if "Microsoft VBScript Regular Expressions 5.5" is already added
    For Each chkRef In vbProj.References
        If chkRef.Name = "VBScript_RegExp_55" Then
            BoolExists = True
            GoTo CleanUp
        End If
    Next

    vbProj.References.AddFromFile "C:\WINDOWS\system32\vbscript.dll\3"

CleanUp:
    If BoolExists = True Then
        MsgBox "Reference already exists"
    Else
        MsgBox "Reference Added Successfully"
    End If

    Set vbProj = Nothing
    Set VBAEditor = Nothing
End Sub

Note: I have not added Error Handling. It is recommended that in your actual code, do use it :)

EDIT Beaten by mischab1 :)

How to save a pandas DataFrame table as a png

Although I am not sure if this is the result you expect, you can save your DataFrame in png by plotting the DataFrame with Seaborn Heatmap with annotations on, like this:

http://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.heatmap.html#seaborn.heatmap

Example of Seaborn heatmap with annotations on

It works right away with a Pandas Dataframe. You can look at this example: Efficiently ploting a table in csv format using Python

You might want to change the colormap so it displays a white background only.

Hope this helps.

How to disable anchor "jump" when loading a page?

dirty CSS only fix to stay scrolled up every time the anchor is used (not useful if you still want to use anchors for scroll-jumps, very useful for deeplinking):

.elementsWithAnchorIds::before {
   content: "";
   display: block;
   height: 9999px;
   margin-top: -9999px; //higher thin page height
}

How to convert java.util.Date to java.sql.Date?

If you are usgin Mysql a date column can be passed a String representation of this date

so i using the DateFormatter Class to format it and then set it as a String in the sql statement or prepared statement

here is the code illustration:

private String converUtilDateToSqlDate(java.util.Date utilDate) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String sqlDate = sdf.format(utilDate);
    return sqlDate;
}

String date = converUtilDateToSqlDate(otherTransaction.getTransDate());

//then pass this date in you sql statement

.NET Console Application Exit Event

You can use the ProcessExit event of the AppDomain:

class Program
{
    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);           
        // do some work

    }

    static void CurrentDomain_ProcessExit(object sender, EventArgs e)
    {
        Console.WriteLine("exit");
    }
}

Update

Here is a full example program with an empty "message pump" running on a separate thread, that allows the user to input a quit command in the console to close down the application gracefully. After the loop in MessagePump you will probably want to clean up resources used by the thread in a nice manner. It's better to do that there than in ProcessExit for several reasons:

  • Avoid cross-threading problems; if external COM objects were created on the MessagePump thread, it's easier to deal with them there.
  • There is a time limit on ProcessExit (3 seconds by default), so if cleaning up is time consuming, it may fail if pefromed within that event handler.

Here is the code:

class Program
{
    private static bool _quitRequested = false;
    private static object _syncLock = new object();
    private static AutoResetEvent _waitHandle = new AutoResetEvent(false);

    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
        // start the message pumping thread
        Thread msgThread = new Thread(MessagePump);
        msgThread.Start();
        // read input to detect "quit" command
        string command = string.Empty;
        do
        {
            command = Console.ReadLine();
        } while (!command.Equals("quit", StringComparison.InvariantCultureIgnoreCase));
        // signal that we want to quit
        SetQuitRequested();
        // wait until the message pump says it's done
        _waitHandle.WaitOne();
        // perform any additional cleanup, logging or whatever
    }

    private static void SetQuitRequested()
    {
        lock (_syncLock)
        {
            _quitRequested = true;
        }
    }

    private static void MessagePump()
    {
        do
        {
            // act on messages
        } while (!_quitRequested);
        _waitHandle.Set();
    }

    static void CurrentDomain_ProcessExit(object sender, EventArgs e)
    {
        Console.WriteLine("exit");
    }
}

how to rotate a bitmap 90 degrees

By default the rotation point is the Canvas's (0,0) point, and my guess is that you may want to rotate it around the center. I did that:

protected void renderImage(Canvas canvas)
{
    Rect dest,drawRect ;

    drawRect = new Rect(0,0, mImage.getWidth(), mImage.getHeight());
    dest = new Rect((int) (canvas.getWidth() / 2 - mImage.getWidth() * mImageResize / 2), // left
                    (int) (canvas.getHeight()/ 2 - mImage.getHeight()* mImageResize / 2), // top
                    (int) (canvas.getWidth() / 2 + mImage.getWidth() * mImageResize / 2), //right
                    (int) (canvas.getWidth() / 2 + mImage.getHeight()* mImageResize / 2));// bottom

    if(!mRotate) {
        canvas.drawBitmap(mImage, drawRect, dest, null);
    } else {
        canvas.save(Canvas.MATRIX_SAVE_FLAG); //Saving the canvas and later restoring it so only this image will be rotated.
        canvas.rotate(90,canvas.getWidth() / 2, canvas.getHeight()/ 2);
        canvas.drawBitmap(mImage, drawRect, dest, null);
        canvas.restore();
    }
}

Best C/C++ Network Library

Aggregated List of Libraries

How to select different app.config for several build configurations

See if the XDT (web.config) transform engine can help you. Currently it's only natively supported for web projects, but technically there is nothing stopping you from using it in other application types. There are many guides on how to use XDT by manually editing the project files, but I found a plugin that works great: https://visualstudiogallery.msdn.microsoft.com/579d3a78-3bdd-497c-bc21-aa6e6abbc859

The plugin is only helping to setup the configuration, it's not needed to build and the solution can be built on other machines or on a build server without the plugin or any other tools being required.

Formatting ISODate from Mongodb

you can use mongo query like this yearMonthDayhms: { $dateToString: { format: "%Y-%m-%d-%H-%M-%S", date: {$subtract:["$cdt",14400000]}}}

HourMinute: { $dateToString: { format: "%H-%M-%S", date: {$subtract:["$cdt",14400000]}}}

enter image description here

Java collections maintaining insertion order

Why is it necessary to maintain the order of insertion? If you use HashMap, you can get the entry by key. It does not mean it does not provide classes that do what you want.

JSF rendered multiple combined conditions

Assuming that "a" and "b" are bean properties

rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"

You may look at JSF EL operators

Checkout old commit and make it a new commit

This is exactly what I wanted to do. I was not sure of the previous command git cherry-pick C, it sounds nice but it seems you do this to get changes from another branch but not on same branch, has anyone tried it?

So I did something else which also worked : I got the files I wanted back from the old commit file by file

git checkout <commit-hash> <filename>

ex : git checkout 08a6497b76ad098a5f7eda3e4ec89e8032a4da51 file.css

-> this takes the files as they were from the old commit

Then I did my changes. And I committed again.

git status (to check which files were modified)
git diff (to check the changes you made)
git add .
git commit -m "my message"

I checked my history with git log, and I still have my history along with my new changes made from the old files. And I could push too.

Note that to go back to the state you want you need to put the hash of the commit before the unwanted changes. Also make sure you don't have uncommitted changes before you do that.

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

I believe this is the simplest example:

header := w.Header()
header.Add("Access-Control-Allow-Origin", "*")
header.Add("Access-Control-Allow-Methods", "DELETE, POST, GET, OPTIONS")
header.Add("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")

You can also add a header for Access-Control-Max-Age and of course you can allow any headers and methods that you wish.

Finally you want to respond to the initial request:

if r.Method == "OPTIONS" {
    w.WriteHeader(http.StatusOK)
    return
}

Edit (June 2019): We now use gorilla for this. Their stuff is more actively maintained and they have been doing this for a really long time. Leaving the link to the old one, just in case.

Old Middleware Recommendation below: Of course it would probably be easier to just use middleware for this. I don't think I've used it, but this one seems to come highly recommended.

Is there a way to only install the mysql client (Linux)?

When I now just use the command: mysql

I get: Command 'mysql' not found, but can be installed with:

sudo apt install mysql-client-core-8.0 # version 8.0.22-0ubuntu0.20.04.2, or sudo apt install mariadb-client-core-10.3 # version 1:10.3.25-0ubuntu0.20.04.1

Very helpfull.

SQL Group By with an Order By

MySQL prior to version 5 did not allow aggregate functions in ORDER BY clauses.

You can get around this limit with the deprecated syntax:

SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY 1 DESC
LIMIT 20

1, since it's the first column you want to group on.

Set font-weight using Bootstrap classes

You should use bootstarp's variables to control your font-weight if you want a more customized value and/or you're following a scheme that needs to be repeated ; Variables are used throughout the entire project as a way to centralize and share commonly used values like colors, spacing, or font stacks;

you can find all the documentation at http://getbootstrap.com/css.

CSS scrollbar style cross browser

nanoScrollerJS is simply to use. I always use them...

Browser compatibility:
  • IE7+
  • Firefox 3+
  • Chrome
  • Safari 4+
  • Opera 11.60+
Mobile browsers support:
  • iOS 5+ (iPhone, iPad and iPod Touch)
  • iOS 4 (with a polyfill)
  • Android Firefox
  • Android 2.2/2.3 native browser (with a polyfill)
  • Android Opera 11.6 (with a polyfill)

Code example from the Documentation,

  1. Markup - The following type of markup structure is needed to make the plugin work.
<div id="about" class="nano">
    <div class="nano-content"> ... content here ...  </div>
</div>

Get table name by constraint name

ALL_CONSTRAINTS describes constraint definitions on tables accessible to the current user.

DBA_CONSTRAINTS describes all constraint definitions in the database.

USER_CONSTRAINTS describes constraint definitions on tables in the current user's schema

Select CONSTRAINT_NAME,CONSTRAINT_TYPE ,TABLE_NAME ,STATUS from 
USER_CONSTRAINTS;

Why does intellisense and code suggestion stop working when Visual Studio is open?

In my case, I had added an .ascx.cs into the project via right-click => "Include in Project", but the project had it set as "Content" instead of "Compile". Once I set this to "Compile", intellisense began working again.

Does PHP have threading?

pcntl_fork() is what you are searching for, but its process forking not threading. so you will have the problem of data exchange. to solve them you can use phps semaphore functions ( http://www.php.net/manual/de/ref.sem.php ) message queues may be a bit easier for the beginning than shared memory segments.

Anyways, a strategy i am using in a web framework that i am developing which loads resource intensive blocks of a web page (probably with external requests) parallel: i am doing a job queue to know what data i am waiting for and then i fork off the jobs for every process. once done they store their data in the apc cache under a unique key the parent process can access. once every data is there it continues. i am using simple usleep() to wait because inter process communication is not possible in apache (children will loose the connection to their parents and become zombies...). so this brings me to the last thing: its important to self kill every child! there are as well classes that fork processes but keep data, i didn't examine them but zend framework has one, and they usually do slow but reliably code. you can find it here: http://zendframework.com/manual/1.9/en/zendx.console.process.unix.overview.html i think they use shm segments! well last but not least there is an error on this zend website, minor mistake in the example.

while ($process1->isRunning() && $process2->isRunning()) {
    sleep(1);
}
should of course be:
while ($process1->isRunning() || $process2->isRunning()) {
    sleep(1);
}

Calling Oracle stored procedure from C#?

Instead of

cmd = new OracleCommand("ProcName", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";

You can also use this syntax:

cmd = new OracleCommand("BEGIN ProcName(:p0); END;", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";

Note, if you set cmd.BindByName = False (which is the default) then you have to add the parameters in the same order as they are written in your command string, the actual names are not relevant. For cmd.BindByName = True the parameter names have to match, the order does not matter.

In case of a function call the command string would be like this:

cmd = new OracleCommand("BEGIN :ret := ProcName(:ParName); END;", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("ret", OracleDbType.RefCursor, ParameterDirection.ReturnValue);    
cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";
// cmd.ExecuteNonQuery(); is not needed, otherwise the function is executed twice!
var da = new OracleDataAdapter(cmd);
da.Fill(dt);

syntax for creating a dictionary into another dictionary in python

Do you want to insert one dictionary into the other, as one of its elements, or do you want to reference the values of one dictionary from the keys of another?

Previous answers have already covered the first case, where you are creating a dictionary within another dictionary.

To re-reference the values of one dictionary into another, you can use dict.update:

>>> d1 = {1: [1]}
>>> d2 = {2: [2]}
>>> d1.update(d2)
>>> d1
{1: [1], 2: [2]}

A change to a value that's present in both dictionaries will be visible in both:

>>> d1[2].append('appended')
>>> d1
{1: [1], 2: [2, 'appended']}
>>> d2
{2: [2, 'appended']}

This is the same as copying the value over or making a new dictionary with it, i.e.

>>> d3 = {1: d1[1]}
>>> d3[1].append('appended from d3')
>>> d1[1]
[1, 'appended from d3']

What's the difference between utf8_general_ci and utf8_unicode_ci?

According to this post, there is a considerably large performance benefit on MySQL 5.7 when using utf8mb4_general_ci in stead of utf8mb4_unicode_ci: https://www.percona.com/blog/2019/02/27/charset-and-collation-settings-impact-on-mysql-performance/

How can I check whether a radio button is selected with JavaScript?

HTML Code

<input type="radio" name="offline_payment_method" value="Cheque" >
<input type="radio" name="offline_payment_method" value="Wire Transfer" >

Javascript Code:

var off_payment_method = document.getElementsByName('offline_payment_method');
var ischecked_method = false;
for ( var i = 0; i < off_payment_method.length; i++) {
    if(off_payment_method[i].checked) {
        ischecked_method = true;
        break;
    }
}
if(!ischecked_method)   { //payment method button is not checked
    alert("Please choose Offline Payment Method");
}

Print second last column/field in awk

Small addition to Chris Kannon' accepted answer: only print if there actually is a second last column.

(
echo       | awk 'NF && NF-1 { print ( $(NF-1) ) }'
echo 1     | awk 'NF && NF-1 { print ( $(NF-1) ) }'
echo 1 2   | awk 'NF && NF-1 { print ( $(NF-1) ) }'
echo 1 2 3 | awk 'NF && NF-1 { print ( $(NF-1) ) }'
)

How can one develop iPhone apps in Java?

You can't.

Note however that Monotouch allows you to develop in C# instead of Objective-C. http://monotouch.net/

Plot 3D data in R

I use the lattice package for almost everything I plot in R and it has a corresponing plot to persp called wireframe. Let data be the way Sven defined it.

wireframe(z ~ x * y, data=data)

wireframe plot

Or how about this (modification of fig 6.3 in Deepanyan Sarkar's book):

p <- wireframe(z ~ x * y, data=data)
npanel <- c(4, 2)
rotx <- c(-50, -80)
rotz <- seq(30, 300, length = npanel[1]+1)
update(p[rep(1, prod(npanel))], layout = npanel,
    panel = function(..., screen) {
        panel.wireframe(..., screen = list(z = rotz[current.column()],
                                           x = rotx[current.row()]))
    })

Multiple wireframe plots using panel and update

Update: Plotting surfaces with OpenGL

Since this post continues to draw attention I want to add the OpenGL way to make 3-d plots too (as suggested by @tucson below). First we need to reformat the dataset from xyz-tripplets to axis vectors x and y and a matrix z.

x <- 1:5/10
y <- 1:5
z <- x %o% y
z <- z + .2*z*runif(25) - .1*z

library(rgl)
persp3d(x, y, z, col="skyblue")

rgl::persp3d

This image can be freely rotated and scaled using the mouse, or modified with additional commands, and when you are happy with it you save it using rgl.snapshot.

rgl.snapshot("myplot.png")

Export result set on Dbeaver to CSV

Is there a reason you couldn't select your results and right click and choose Advanced Copy -> Advanced Copy? I'm on a Mac and this is how I always copy results to the clipboard for pasting.

how to get files from <input type='file' .../> (Indirect) with javascript

Based on Ray Nicholus's answer :

inputElement.onchange = function(event) {
   var fileList = inputElement.files;
   //TODO do something with fileList.  
}

using this will also work :

inputElement.onchange = function(event) {
   var fileList = event.target.files;
   //TODO do something with fileList.  
}

Coerce multiple columns to factors at once

The more recent tidyverse way is to use the mutate_at function:

library(tidyverse)
library(magrittr)
set.seed(88)

data <- data.frame(matrix(sample(1:40), 4, 10, dimnames = list(1:4, LETTERS[1:10])))
cols <- c("A", "C", "D", "H")

data %<>% mutate_at(cols, funs(factor(.)))
str(data)
 $ A: Factor w/ 4 levels "5","17","18",..: 2 1 4 3   
 $ B: int  36 35 2 26
 $ C: Factor w/ 4 levels "22","31","32",..: 1 2 4 3
 $ D: Factor w/ 4 levels "1","9","16","39": 3 4 1 2
 $ E: int  3 14 30 38
 $ F: int  27 15 28 37
 $ G: int  19 11 6 21
 $ H: Factor w/ 4 levels "7","12","20",..: 1 3 4 2
 $ I: int  23 24 13 8
 $ J: int  10 25 4 33

I ran into a merge conflict. How can I abort the merge?

Sourcetree

Because you not commit your merge, then just double click on another branch (which mean checkout it) and when sourcetree ask you about discarding all changes then agree :)

Update

I see many down-votes but any commet... I will left this answer which is addressed for those who use SourceTree as git client (as I - when I looking for solution for question asked by OP)

Execute a PHP script from another PHP script

I think this is what you are looking for

<?php include ('Scripts/Php/connection.php');
//The connection.php script is executed inside the current file ?>

The script file can also be in a .txt format, it should still work, it does for me

e.g.

<?php include ('Scripts/Php/connection.txt');
//The connection.txt script is executed inside the current file ?>

The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel

If you have a seeder in your database, run php artisan migrate:fresh --seed

How to check if a file exists in the Documents directory in Swift?

You must add a "/" slash before filename, or you get path like ".../DocumentsFilename.jpg"

Most efficient conversion of ResultSet to JSON?

If anyone plan to use this implementation, You might wanna check this out and this

This is my version of that convertion code:

public class ResultSetConverter {
public static JSONArray convert(ResultSet rs) throws SQLException,
        JSONException {
    JSONArray json = new JSONArray();
    ResultSetMetaData rsmd = rs.getMetaData();
    int numColumns = rsmd.getColumnCount();
    while (rs.next()) {

        JSONObject obj = new JSONObject();

        for (int i = 1; i < numColumns + 1; i++) {
            String column_name = rsmd.getColumnName(i);

            if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) {
                obj.put(column_name, rs.getArray(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) {
                obj.put(column_name, rs.getLong(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.REAL) {
                obj.put(column_name, rs.getFloat(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) {
                obj.put(column_name, rs.getBoolean(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BLOB) {
                obj.put(column_name, rs.getBlob(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) {
                obj.put(column_name, rs.getDouble(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) {
                obj.put(column_name, rs.getDouble(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.INTEGER) {
                obj.put(column_name, rs.getInt(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) {
                obj.put(column_name, rs.getNString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.VARCHAR) {
                obj.put(column_name, rs.getString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.CHAR) {
                obj.put(column_name, rs.getString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.NCHAR) {
                obj.put(column_name, rs.getNString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.LONGNVARCHAR) {
                obj.put(column_name, rs.getNString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.LONGVARCHAR) {
                obj.put(column_name, rs.getString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) {
                obj.put(column_name, rs.getByte(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) {
                obj.put(column_name, rs.getShort(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) {
                obj.put(column_name, rs.getDate(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.TIME) {
                obj.put(column_name, rs.getTime(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) {
                obj.put(column_name, rs.getTimestamp(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BINARY) {
                obj.put(column_name, rs.getBytes(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.VARBINARY) {
                obj.put(column_name, rs.getBytes(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.LONGVARBINARY) {
                obj.put(column_name, rs.getBinaryStream(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BIT) {
                obj.put(column_name, rs.getBoolean(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.CLOB) {
                obj.put(column_name, rs.getClob(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.NUMERIC) {
                obj.put(column_name, rs.getBigDecimal(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.DECIMAL) {
                obj.put(column_name, rs.getBigDecimal(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.DATALINK) {
                obj.put(column_name, rs.getURL(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.REF) {
                obj.put(column_name, rs.getRef(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.STRUCT) {
                obj.put(column_name, rs.getObject(column_name)); // must be a custom mapping consists of a class that implements the interface SQLData and an entry in a java.util.Map object.
            } else if (rsmd.getColumnType(i) == java.sql.Types.DISTINCT) {
                obj.put(column_name, rs.getObject(column_name)); // must be a custom mapping consists of a class that implements the interface SQLData and an entry in a java.util.Map object.
            } else if (rsmd.getColumnType(i) == java.sql.Types.JAVA_OBJECT) {
                obj.put(column_name, rs.getObject(column_name));
            } else {
                obj.put(column_name, rs.getString(i));
            }
        }

        json.put(obj);
    }

    return json;
}
}

Using Helvetica Neue in a Website

They are taking a 'shotgun' approach to referencing the font. The browser will attempt to match each font name with any installed fonts on the user's machine (in the order they have been listed).

In your example "HelveticaNeue-Light" will be tried first, if this font variant is unavailable the browser will try "Helvetica Neue Light" and finally "Helvetica Neue".

As far as I'm aware "Helvetica Neue" isn't considered a 'web safe font', which means you won't be able to rely on it being installed for your entire user base. It is quite common to define "serif" or "sans-serif" as a final default position.

In order to use fonts which aren't 'web safe' you'll need to use a technique known as font embedding. Embedded fonts do not need to be installed on a user's computer, instead they are downloaded as part of the page. Be aware this increases the overall payload (just like an image does) and can have an impact on page load times.

A great resource for free fonts with open-source licenses is Google Fonts. (You should still check individual licenses before using them.) Each font has a download link with instructions on how to embed them in your website.

SELECT INTO a table variable in T-SQL

First create a temp table :

Step 1:

create table #tblOm_Temp (

    Name varchar(100),
    Age Int ,
    RollNumber bigint
)

**Step 2: ** Insert Some value in Temp table .

insert into #tblom_temp values('Om Pandey',102,1347)

Step 3: Declare a table Variable to hold temp table data.

declare   @tblOm_Variable table(

    Name Varchar(100),
    Age int,
    RollNumber bigint
)

Step 4: select value from temp table and insert into table variable.

insert into @tblOm_Variable select * from #tblom_temp

Finally value is inserted from a temp table to Table variable

Step 5: Can Check inserted value in table variable.

select * from @tblOm_Variable

Handling of non breaking space: <p>&nbsp;</p> vs. <p> </p>

How about a workaround? In my case I took the value of the textarea in a jQuery variable, and changed all "<p>&nbsp" to <p class="clear"> and clear class to have certain height and margin, as the following example:

jQuery

tinyMCE.triggerSave();
var val = $('textarea').val();
val = val.replace(/<p>&nbsp/g, '<p class="clear">');

the val is then saved to the database with the new val.

CSS

p.clear{height: 2px; margin-bottom: 3px;}

You can adjust the height & margin as you wish. And since 'p' is a display: block element. it should give you the expected output.

Hope that helps!

Select a row from html table and send values onclick of a button

You can access the first element adding the following code to the highlight function

$(this).find(".selected td:first").html()

Working Code:JSFIDDLE

How to add a string to a string[] array? There's no .Add function

string[] MyArray = new string[] { "A", "B" };
MyArray = new List<string>(MyArray) { "C" }.ToArray();
//MyArray = ["A", "B", "C"]

php: catch exception and continue execution, is it possible?

For PHP 8+ we can omit the variable name for a caught exception.

catch

As of PHP 8.0.0, the variable name for a caught exception is optional. If not specified, the catch block will still execute but will not have access to the thrown object.

And thus we can do it like this:

try {
  throw new Exception("An error");
}
catch (Exception) {}

Regular Expression to reformat a US phone number in Javascript

I've extended David Baucum's answer to include support for extensions up to 4 digits in length. It also includes the parentheses requested in the original question. This formatting will work as you type in the field.

phone = phone.replace(/\D/g, '');
const match = phone.match(/^(\d{1,3})(\d{0,3})(\d{0,4})(\d{0,4})$/);
if (match) {
    phone = `(${match[1]}${match[2] ? ') ' : ''}${match[2]}${match[3] ? '-' : ''}${match[3]}${match[4] ? ' x' : ''}${match[4]}`;
}
return phone;

case statement in SQL, how to return multiple variables?

You can return multiple value inside a xml data type in "case" expression, then extract them, also "else" block is available

SELECT 
xmlcol.value('(value1)[1]', 'NVARCHAR(MAX)') AS value1,
xmlcol.value('(value2)[1]', 'NVARCHAR(MAX)') AS value2
FROM
(SELECT CASE
WHEN <condition 1> THEN
CAST((SELECT a1 AS value1, b1 AS value2 FOR XML PATH('')) AS XML)
WHEN <condition 2> THEN
CAST((SELECT a2 AS value1, b2 AS value2 FOR XML PATH('')) AS XML)
ELSE
CAST((SELECT a3 AS value1, b3 AS value2 FOR XML PATH('')) AS XML)
END AS xmlcol
FROM <table>) AS tmp

install / uninstall APKs programmatically (PackageManager vs Intents)

Android P+ requires this permission in AndroidManifest.xml

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

Then:

Intent intent = new Intent(Intent.ACTION_DELETE);
intent.setData(Uri.parse("package:com.example.mypackage"));
startActivity(intent);

to uninstall. Seems easier...

Fastest Way to Find Distance Between Two Lat/Long Points

The full code with details about how to install as MySQL plugin are here: https://github.com/lucasepe/lib_mysqludf_haversine

I posted this last year as comment. Since kindly @TylerCollier suggested me to post as answer, here it is.

Another way is to write a custom UDF function that returns the haversine distance from two points. This function can take in input:

lat1 (real), lng1 (real), lat2 (real), lng2 (real), type (string - optinal - 'km', 'ft', 'mi')

So we can write something like this:

SELECT id, name FROM MY_PLACES WHERE haversine_distance(lat1, lng1, lat2, lng2) < 40;

to fetch all records with a distance less then 40 kilometers. Or:

SELECT id, name FROM MY_PLACES WHERE haversine_distance(lat1, lng1, lat2, lng2, 'ft') < 25;

to fetch all records with a distance less then 25 feet.

The core function is:

double
haversine_distance( UDF_INIT* initid, UDF_ARGS* args, char* is_null, char *error ) {
    double result = *(double*) initid->ptr;
    /*Earth Radius in Kilometers.*/ 
    double R = 6372.797560856;
    double DEG_TO_RAD = M_PI/180.0;
    double RAD_TO_DEG = 180.0/M_PI;
    double lat1 = *(double*) args->args[0];
    double lon1 = *(double*) args->args[1];
    double lat2 = *(double*) args->args[2];
    double lon2 = *(double*) args->args[3];
    double dlon = (lon2 - lon1) * DEG_TO_RAD;
    double dlat = (lat2 - lat1) * DEG_TO_RAD;
    double a = pow(sin(dlat * 0.5),2) + 
        cos(lat1*DEG_TO_RAD) * cos(lat2*DEG_TO_RAD) * pow(sin(dlon * 0.5),2);
    double c = 2.0 * atan2(sqrt(a), sqrt(1-a));
    result = ( R * c );
    /*
     * If we have a 5th distance type argument...
     */
    if (args->arg_count == 5) {
        str_to_lowercase(args->args[4]);
        if (strcmp(args->args[4], "ft") == 0) result *= 3280.8399;
        if (strcmp(args->args[4], "mi") == 0) result *= 0.621371192;
    }

    return result;
}

Call to undefined method mysqli_stmt::get_result

I was getting this same error on my server - PHP 7.0 with the mysqlnd extension already enabled.

Solution was for me (thanks to this page) was to deselect the mysqli extension and select nd_mysqli instead.

NB - You may be able to access the extensions selector in your cPanel. (I access mine via the Select PHP Version option.)

How do I convert from stringstream to string in C++?

std::stringstream::str() is the method you are looking for.

With std::stringstream:

template <class T>
std::string YourClass::NumericToString(const T & NumericValue)
{
    std::stringstream ss;
    ss << NumericValue;
    return ss.str();
}

std::stringstream is a more generic tool. You can use the more specialized class std::ostringstream for this specific job.

template <class T>
std::string YourClass::NumericToString(const T & NumericValue)
{
    std::ostringstream oss;
    oss << NumericValue;
    return oss.str();
}

If you are working with std::wstring type of strings, you must prefer std::wstringstream or std::wostringstream instead.

template <class T>
std::wstring YourClass::NumericToString(const T & NumericValue)
{
    std::wostringstream woss;
    woss << NumericValue;
    return woss.str();
}

if you want the character type of your string could be run-time selectable, you should also make it a template variable.

template <class CharType, class NumType>
std::basic_string<CharType> YourClass::NumericToString(const NumType & NumericValue)
{
    std::basic_ostringstream<CharType> oss;
    oss << NumericValue;
    return oss.str();
}

For all the methods above, you must include the following two header files.

#include <string>
#include <sstream>

Note that, the argument NumericValue in the examples above can also be passed as std::string or std::wstring to be used with the std::ostringstream and std::wostringstream instances respectively. It is not necessary for the NumericValue to be a numeric value.

C read file line by line

You should use the ANSI functions for reading a line, eg. fgets. After calling you need free() in calling context, eg:

...
const char *entirecontent=readLine(myFile);
puts(entirecontent);
free(entirecontent);
...

const char *readLine(FILE *file)
{
  char *lineBuffer=calloc(1,1), line[128];

  if ( !file || !lineBuffer )
  {
    fprintf(stderr,"an ErrorNo 1: ...");
    exit(1);
  }

  for(; fgets(line,sizeof line,file) ; strcat(lineBuffer,line) )
  {
    if( strchr(line,'\n') ) *strchr(line,'\n')=0;
    lineBuffer=realloc(lineBuffer,strlen(lineBuffer)+strlen(line)+1);
    if( !lineBuffer )
    {
      fprintf(stderr,"an ErrorNo 2: ...");
      exit(2);
    }
  }
  return lineBuffer;
}

How to print a certain line of a file with PowerShell?

Just for fun, here some test:

#Added this for @Graimer's request ;) (not same computer, but one with HD little more #performant...)

measure-command { Get-Content ita\ita.txt -TotalCount 260000 | Select-Object -Last 1 }

Days              : 0
Hours             : 0

Minutes           : 0
Seconds           : 28
Milliseconds      : 893
Ticks             : 288932649
TotalDays         : 0,000334412788194444
TotalHours        : 0,00802590691666667
TotalMinutes      : 0,481554415
TotalSeconds      : 28,8932649
TotalMilliseconds : 28893,2649


> measure-command { (gc "c:\ps\ita\ita.txt")[260000] }


Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 9
Milliseconds      : 257
Ticks             : 92572893
TotalDays         : 0,000107144552083333
TotalHours        : 0,00257146925
TotalMinutes      : 0,154288155
TotalSeconds      : 9,2572893
TotalMilliseconds : 9257,2893


> measure-command { ([System.IO.File]::ReadAllLines("c:\ps\ita\ita.txt"))[260000] }


Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 234
Ticks             : 2348059
TotalDays         : 2,71766087962963E-06
TotalHours        : 6,52238611111111E-05
TotalMinutes      : 0,00391343166666667
TotalSeconds      : 0,2348059
TotalMilliseconds : 234,8059



> measure-command {get-content .\ita\ita.txt | select -index 260000}


Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 36
Milliseconds      : 591
Ticks             : 365912596
TotalDays         : 0,000423509949074074
TotalHours        : 0,0101642387777778
TotalMinutes      : 0,609854326666667
TotalSeconds      : 36,5912596
TotalMilliseconds : 36591,2596

the winner is : ([System.IO.File]::ReadAllLines( path ))[index]

How to format strings using printf() to get equal length in the output

You can specify a width on string fields, e.g.

printf("%-20s", "initialization...");

And then whatever's printed with that field will be blank-padded to the width you indicate.

The - left-justifies your text in that field.

What is the best regular expression to check if a string is a valid URL?

For convenience here's a one-liner regexp for URL's that will also match localhost where you're more likely to have ports than .com or similar.

(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}(\.[a-z]{2,6}|:[0-9]{3,4})\b([-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)

How to use refs in React with Typescript

From React type definition

    type ReactInstance = Component<any, any> | Element;
....
    refs: {
            [key: string]: ReactInstance
    };

So you can access you refs element as follow

stepInput = () => ReactDOM.findDOMNode(this.refs['stepInput']);

without redefinition of refs index.

As @manakor mentioned you can get error like

Property 'stepInput' does not exist on type '{ [key: string]: Component | Element; }

if you redefine refs(depends on IDE and ts version you use)

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

Haskell

foldl (+) 0 [1,2,3,4,5]

Python

reduce(lambda a,b: a+b, [1,2,3,4,5], 0)

Obviously, that is a trivial example to illustrate a point. In Python you would just do sum([1,2,3,4,5]) and even Haskell purists would generally prefer sum [1,2,3,4,5].

For non-trivial scenarios when there is no obvious convenience function, the idiomatic pythonic approach is to explicitly write out the for loop and use mutable variable assignment instead of using reduce or a fold.

That is not at all the functional style, but that is the "pythonic" way. Python is not designed for functional purists. See how Python favors exceptions for flow control to see how non-functional idiomatic python is.

Constants in Kotlin -- what's a recommended way to create them?

Avoid using companion objects. Behind the hood, getter and setter instance methods are created for the fields to be accessible. Calling instance methods is technically more expensive than calling static methods.

public class DbConstants {
    companion object {
        val TABLE_USER_ATTRIBUTE_EMPID = "_id"
        val TABLE_USER_ATTRIBUTE_DATA = "data"
    }

Instead define the constants in object.

Recommended practice :

object DbConstants {
        const val TABLE_USER_ATTRIBUTE_EMPID = "_id"
        const val TABLE_USER_ATTRIBUTE_DATA = "data"
}

and access them globally like this: DbConstants.TABLE_USER_ATTRIBUTE_EMPID

How to create a floating action button (FAB) in android, using AppCompat v21?

I've generally used xml drawables to create shadow/elevation on a pre-lollipop widget. Here, for example, is an xml drawable that can be used on pre-lollipop devices to simulate the floating action button's elevation.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:top="8px">
    <layer-list>
        <item>
            <shape android:shape="oval">
                <solid android:color="#08000000"/>
                <padding
                    android:bottom="3px"
                    android:left="3px"
                    android:right="3px"
                    android:top="3px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#09000000"/>
                <padding
                    android:bottom="2px"
                    android:left="2px"
                    android:right="2px"
                    android:top="2px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#10000000"/>
                <padding
                    android:bottom="2px"
                    android:left="2px"
                    android:right="2px"
                    android:top="2px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#11000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#12000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#13000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#14000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#15000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#16000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#17000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
    </layer-list>
</item>
<item>
    <shape android:shape="oval">
        <solid android:color="?attr/colorPrimary"/>
    </shape>
</item>
</layer-list>

In place of ?attr/colorPrimary you can choose any color. Here's a screenshot of the result:

enter image description here

How can git be installed on CENTOS 5.5?

yum -y install zlib-devel openssl-devel cpio expat-devel gettext-devel gcc
wget http://git-core.googlecode.com/files/git-1.7.11.4.tar.gz
tar zxvf git-1.7.11.4.tar.gz 
cd git-1.7.11.4
./configure 
make
make install

Inconsistent Accessibility: Parameter type is less accessible than method

parameter type 'support.ACTInterface' is less accessible than method    
'support.clients.clients(support.ACTInterface)' 

The error says 'support.ACTInterface' is less accessible because you have made the interface as private, at least make it internal or make it public.

android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

https://stackoverflow.com/a/38858040/395097 this answer is complete.

This answer is for - you already have an app which was targeting below 24, and now you are upgrading to targetSDKVersion >= 24.

In Android N, only the file uri exposed to 3rd party app is changed. (Not the way we were using it before). So change only the places where you are sharing the path with 3rd party app (Camera in my case)

In our app we were sending uri to Camera app, in that location we are expecting the camera app to store the captured image.

  1. For android N, we generate new Content:// uri based url pointing to file.
  2. We generate usual File api based path for the same (using older method).

Now we have 2 different uri for same file. #1 is shared with Camera app. If the camera intent is success, we can access the image from #2.

Hope this helps.

Multiple REPLACE function in Oracle

This is an old post, but I ended up using Peter Lang's thoughts, and did a similar, but yet different approach. Here is what I did:

CREATE OR REPLACE FUNCTION multi_replace(
                        pString IN VARCHAR2
                        ,pReplacePattern IN VARCHAR2
) RETURN VARCHAR2 IS
    iCount  INTEGER;
    vResult VARCHAR2(1000);
    vRule   VARCHAR2(100);
    vOldStr VARCHAR2(50);
    vNewStr VARCHAR2(50);
BEGIN
    iCount := 0;
    vResult := pString;
    LOOP
        iCount := iCount + 1;

        -- Step # 1: Pick out the replacement rules
        vRule := REGEXP_SUBSTR(pReplacePattern, '[^/]+', 1, iCount);

        -- Step # 2: Pick out the old and new string from the rule
        vOldStr := REGEXP_SUBSTR(vRule, '[^=]+', 1, 1);
        vNewStr := REGEXP_SUBSTR(vRule, '[^=]+', 1, 2);

        -- Step # 3: Do the replacement
        vResult := REPLACE(vResult, vOldStr, vNewStr);

        EXIT WHEN vRule IS NULL;
    END LOOP;

    RETURN vResult;
END multi_replace;

Then I can use it like this:

SELECT  multi_replace(
                        'This is a test string with a #, a $ character, and finally a & character'
                        ,'#=%23/$=%24/&=%25'
        )
FROM dual

This makes it so that I can can any character/string with any character/string.

I wrote a post about this on my blog.

How to catch exception output from Python subprocess.check_output()?

This did the trick for me. It captures all the stdout output from the subprocess(For python 3.8):

from subprocess import check_output, STDOUT
cmd = "Your Command goes here"
try:
    cmd_stdout = check_output(cmd, stderr=STDOUT, shell=True).decode()
except Exception as e:
    print(e.output.decode()) # print out the stdout messages up to the exception
    print(e) # To print out the exception message

How to sort an array in Bash

In the 3-hour train trip from Munich to Frankfurt (which I had trouble to reach because Oktoberfest starts tomorrow) I was thinking about my first post. Employing a global array is a much better idea for a general sort function. The following function handles arbitary strings (newlines, blanks etc.):

declare BSORT=()
function bubble_sort()
{   #
    # @param [ARGUMENTS]...
    #
    # Sort all positional arguments and store them in global array BSORT.
    # Without arguments sort this array. Return the number of iterations made.
    #
    # Bubble sorting lets the heaviest element sink to the bottom.
    #
    (($# > 0)) && BSORT=("$@")
    local j=0 ubound=$((${#BSORT[*]} - 1))
    while ((ubound > 0))
    do
        local i=0
        while ((i < ubound))
        do
            if [ "${BSORT[$i]}" \> "${BSORT[$((i + 1))]}" ]
            then
                local t="${BSORT[$i]}"
                BSORT[$i]="${BSORT[$((i + 1))]}"
                BSORT[$((i + 1))]="$t"
            fi
            ((++i))
        done
        ((++j))
        ((--ubound))
    done
    echo $j
}

bubble_sort a c b 'z y' 3 5
echo ${BSORT[@]}

This prints:

3 5 a b c z y

The same output is created from

BSORT=(a c b 'z y' 3 5) 
bubble_sort
echo ${BSORT[@]}

Note that probably Bash internally uses smart-pointers, so the swap-operation could be cheap (although I doubt it). However, bubble_sort demonstrates that more advanced functions like merge_sort are also in the reach of the shell language.

How do I convert an object to an array?

You can quickly convert deeply nested objects to associative arrays by relying on the behavior of the JSON encode/decode functions:

$array = json_decode(json_encode($response->response->docs), true);

Replace first occurrence of string in Python

string replace() function perfectly solves this problem:

string.replace(s, old, new[, maxreplace])

Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

>>> u'longlongTESTstringTEST'.replace('TEST', '?', 1)
u'longlong?stringTEST'

How to stop and restart memcached server?

To shutdown memcache daemon:

sudo service memcached stop

To start memcached daemon:

sudo service memcached start

Restart memcached server:

sudo service memcached restart

You can see if Memcache is currently runing:

sudo ps -e | grep memcached

And you can check the TCP or UDP ports if something (e.g. Memcache) is listening to it:

netstat -ap | grep TheChosenPort#
netstat -ap | grep 11211

For some Linuxes you need to change your commands like:

sudo /etc/init.d/memcached start
sudo /etc/init.d/memcached restart
sudo /etc/init.d/memcached stop

Number of times a particular character appears in a string

function for sql server:

CREATE function NTSGetCinC(@Cadena nvarchar(4000), @UnChar nvarchar(100)) 
Returns int 

 as  

 begin 

 declare @t1 int 

 declare @t2 int 

 declare @t3 int 

 set @t1 = len(@Cadena) 

 set @t2 = len(replace(@Cadena,@UnChar,'')) 

 set @t3 = len(@UnChar) 


 return (@t1 - @t2)  / @t3 

 end 

Code for visual basic and others:

Public Function NTSCuentaChars(Texto As String, CharAContar As String) As Long

NTSCuentaChars = (Len(Texto) - Len(Replace(Texto, CharAContar, ""))) / Len(CharAContar)

End Function

How to serve static files in Flask

You can use this function :

send_static_file(filename)
Function used internally to send static files from the static folder to the browser.

app = Flask(__name__)
@app.route('/<path:path>')
def static_file(path):
    return app.send_static_file(path)

Facebook Callback appends '#_=_' to Return URL

The easiest and clean solution to remove "#_=_" (PHP):

Instead of "header("Location: xxx.php");" to use "echo ("location.href = 'xxx.php';");"

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

From Wikipedia:

UTC does not change with a change of seasons, but local time or civil time may change if a time zone jurisdiction observes daylight saving time (summer time). For example, local time on the east coast of the United States is five hours behind UTC during winter, but four hours behind while daylight saving is observed there.

So this is my code:

TimeSpan span = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0,DateTimeKind.Utc));
double unixTime = span.TotalSeconds;

Run javascript function when user finishes typing instead of on key up?

I like Surreal Dream's answer but I found that my "doneTyping" function would fire for every keypress, i.e. if you type "Hello" really quickly; instead of firing just once when you stop typing, the function would fire 5 times.

The problem was that the javascript setTimeout function doesn't appear to overwrite or kill the any old timeouts that have been set, but if you do it yourself it works! So I just added a clearTimeout call just before the setTimeout if the typingTimer is set. See below:

//setup before functions
var typingTimer;                //timer identifier
var doneTypingInterval = 5000;  //time in ms, 5 second for example

//on keyup, start the countdown
$('#myInput').on("keyup", function(){
    if (typingTimer) clearTimeout(typingTimer);                 // Clear if already set     
    typingTimer = setTimeout(doneTyping, doneTypingInterval);
});

//on keydown, clear the countdown 
$('#myInput').on("keydown", function(){
    clearTimeout(typingTimer);
});

//user is "finished typing," do something
function doneTyping () {
    //do something
}

N.B. I would have liked to have just added this as a comment to Surreal Dream's answer but I'm a new user and don't have enough reputation. Sorry!

Change a Django form field to a hidden field

If you want the field to always be hidden, use the following:

class MyForm(forms.Form):
    hidden_input = forms.CharField(widget=forms.HiddenInput(), initial="value")

If you want the field to be conditionally hidden, you can do the following:

form = MyForm()
if condition:
    form.fields["field_name"].widget = forms.HiddenInput()
    form.fields["field_name"].initial = "value"

Override valueof() and toString() in Java enum

How about a Java 8 implementation? (null can be replaced by your default Enum)

public static RandomEnum getEnum(String value) {
    return Arrays.stream(RandomEnum.values()).filter(m -> m.value.equals(value)).findAny().orElse(null);
}

Or you could use:

...findAny().orElseThrow(NotFoundException::new);

Preventing multiple clicks on button

you can use jQuery's [one][1] :

.one( events [, data ], handler ) Returns: jQuery

Description: Attach a handler to an event for the elements. The handler is executed at most once per element per event type.

see examples:

using jQuery: https://codepen.io/loicjaouen/pen/RwweLVx

// add an even listener that will run only once
$("#click_here_button").one("click", once_callback);

Change div width live with jQuery

You can use, which will be triggered when the window resizes.

$( window ).bind("resize", function(){
    // Change the width of the div
    $("#yourdiv").width( 600 );
});

If you want a DIV width as percentage of the screen, just use CSS width : 80%;.

How to break a while loop from an if condition inside the while loop?

An "if" is not a loop. Just use the break inside the "if" and it will break out of the "while".

If you ever need to use genuine nested loops, Java has the concept of a labeled break. You can put a label before a loop, and then use the name of the label is the argument to break. It will break outside of the labeled loop.

Excel concatenation quotes

easier answer - put the stuff in quotes in different cells and then concatenate them!

B1: rcrCheck.asp
C1: =D1&B1&E1
D1: "code in quotes" and "more code in quotes"  
E1: "

it comes out perfect (can't show you because I get a stupid dialog box about code)

easy peasy!!

Making a DateTime field in a database automatic?

Yes, here's an example:

CREATE TABLE myTable ( col1 int, createdDate datetime DEFAULT(getdate()), updatedDate datetime DEFAULT(getdate()) )

You can INSERT into the table without indicating the createdDate and updatedDate columns:

INSERT INTO myTable (col1) VALUES (1)

Or use the keyword DEFAULT:

INSERT INTO myTable (col1, createdDate, updatedDate) VALUES (1, DEFAULT, DEFAULT)

Then create a trigger for updating the updatedDate column:

CREATE TRIGGER dbo.updateMyTable 
ON dbo.myTable
FOR UPDATE 
AS 
BEGIN 
    IF NOT UPDATE(updatedDate) 
        UPDATE dbo.myTable SET updatedDate=GETDATE() 
        WHERE col1 IN (SELECT col1 FROM inserted) 
END 
GO

What are named pipes?

Compare

echo "test" | wc

to

mkdnod apipe p
wc apipe

wc will block until

echo "test" > apipe

executes

How to create an Excel File with Nodejs?

Use exceljs library for creating and writing into existing excel sheets.

You can check this tutorial for detailed explanation.

link

Installing MySQL-python

  1. find the folder: sudo find / -name "mysql_config" (assume it's "/opt/local/lib/mysql5/bin")

  2. add it into PATH:export PATH:export PATH=/opt/local/lib/mysql5/bin:$PATH

  3. install it again

How to get value by class name in JavaScript or jquery?

Try this:

$(document).ready(function(){
    var yourArray = [];
    $("span.HOEnZb").find("div").each(function(){
        if(($.trim($(this).text()).length>0)){
         yourArray.push($(this).text());
        }
    });
});

DEMO

Get specific line from text file using just shell script

Assuming line is a variable which holds your required line number, if you can use head and tail, then it is quite simple:

head -n $line file | tail -1

If not, this should work:

x=0
want=5
cat lines | while read line; do
  x=$(( x+1 ))
  if [ $x -eq "$want" ]; then
    echo $line
    break
  fi
done

Submit form without page reloading

A further possibility is to make a direct javascript link to your function:

<form action="javascript:your_function();" method="post">

...

Create a unique number with javascript time

Here's what I do when I want something smaller than a bunch of numbers - change base.

var uid = (new Date().getTime()).toString(36)

Tablix: Repeat header rows on each page not working - Report Builder 3.0

I have 2.0 and found the above to help; however, the selecting of a static did not highlight the cell for some reason. I followed these steps:

  1. Under column groups select the advanced and the statics will show up
  2. Click on the static which shows up in the row groups
  3. Set KeepWithGroup to After and RepeatOnNewPage to true

Now your column headers should repeat on each page.

KERNELBASE.dll Exception 0xe0434352 offset 0x000000000000a49d

0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.

There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.

I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException and Application.ThreadException, as appropriate.

"Failed to install the following Android SDK packages as some licences have not been accepted" error

I just done File -> Invalidate caches and restart Then install missing packages. Worked for me.

How to create localhost database using mysql?

removing temp files, and did you restart the computer or stop the MySQL service? That's the error message you get when there isn't a MySQL server running.

Set variable with multiple values and use IN

You need a table variable:

declare @values table
(
    Value varchar(1000)
)

insert into @values values ('A')
insert into @values values ('B')
insert into @values values ('C')

select blah
from foo
where myField in (select value from @values)

Store JSON object in data attribute in HTML jQuery

There's a better way of storing JSON in the HTML:

HTML

<script id="some-data" type="application/json">{"param_1": "Value 1", "param_2": "Value 2"}</script>

JavaScript

JSON.parse(document.getElementById('some-data').textContent);

OAuth: how to test with local URLs?

Or you can use https://tolocalhost.com/ and configure how it should redirect a callback to your local site. You can specify the hostname (if different from localhost, i.e. yourapp.local and the port number). For development purposes only.

Private class declaration

private modifier will make your class inaccessible from outside, so there wouldn't be any advantage of this and I think that is why it is illegal and only public, abstract & final are permitted.

Note : Even you can not make it protected.

What is the difference between "Class.forName()" and "Class.forName().newInstance()"?

Maybe an example demonstrating how both methods are used will help you to understand things better. So, consider the following class:

package test;

public class Demo {

    public Demo() {
        System.out.println("Hi!");
    }

    public static void main(String[] args) throws Exception {
        Class clazz = Class.forName("test.Demo");
        Demo demo = (Demo) clazz.newInstance();
    }
}

As explained in its javadoc, calling Class.forName(String) returns the Class object associated with the class or interface with the given string name i.e. it returns test.Demo.class which is affected to the clazz variable of type Class.

Then, calling clazz.newInstance() creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list. In other words, this is here actually equivalent to a new Demo() and returns a new instance of Demo.

And running this Demo class thus prints the following output:

Hi!

The big difference with the traditional new is that newInstance allows to instantiate a class that you don't know until runtime, making your code more dynamic.

A typical example is the JDBC API which loads, at runtime, the exact driver required to perform the work. EJBs containers, Servlet containers are other good examples: they use dynamic runtime loading to load and create components they don't know anything before the runtime.

Actually, if you want to go further, have a look at Ted Neward paper Understanding Class.forName() that I was paraphrasing in the paragraph just above.

EDIT (answering a question from the OP posted as comment): The case of JDBC drivers is a bit special. As explained in the DriverManager chapter of Getting Started with the JDBC API:

(...) A Driver class is loaded, and therefore automatically registered with the DriverManager, in one of two ways:

  1. by calling the method Class.forName. This explicitly loads the driver class. Since it does not depend on any external setup, this way of loading a driver is the recommended one for using the DriverManager framework. The following code loads the class acme.db.Driver:

    Class.forName("acme.db.Driver");
    

    If acme.db.Driver has been written so that loading it causes an instance to be created and also calls DriverManager.registerDriver with that instance as the parameter (as it should do), then it is in the DriverManager's list of drivers and available for creating a connection.

  2. (...)

In both of these cases, it is the responsibility of the newly-loaded Driver class to register itself by calling DriverManager.registerDriver. As mentioned, this should be done automatically when the class is loaded.

To register themselves during initialization, JDBC driver typically use a static initialization block like this:

package acme.db;

public class Driver {

    static {
        java.sql.DriverManager.registerDriver(new Driver());
    }

    ...
}

Calling Class.forName("acme.db.Driver") causes the initialization of the acme.db.Driver class and thus the execution of the static initialization block. And Class.forName("acme.db.Driver") will indeed "create" an instance but this is just a consequence of how (good) JDBC Driver are implemented.

As a side note, I'd mention that all this is not required anymore with JDBC 4.0(added as a default package since Java 7) and the new auto-loading feature of JDBC 4.0 drivers. See JDBC 4.0 enhancements in Java SE 6.

How to properly reference local resources in HTML?

  • A leading slash tells the browser to start at the root directory.
  • If you don't have the leading slash, you're referencing from the current directory.
  • If you add two dots before the leading slash, it means you're referencing the parent of the current directory.

Take the following folder structure

demo folder structure

notice:

  • the ROOT checkmark is green,
  • the second checkmark is orange,
  • the third checkmark is purple,
  • the forth checkmark is yellow

Now in the index.html.en file you'll want to put the following markup

<p>
    <span>src="check_mark.png"</span>
    <img src="check_mark.png" />
    <span>I'm purple because I'm referenced from this current directory</span>
</p>

<p>
    <span>src="/check_mark.png"</span>
    <img src="/check_mark.png" />
    <span>I'm green because I'm referenced from the ROOT directory</span>
</p>

<p>
    <span>src="subfolder/check_mark.png"</span>
    <img src="subfolder/check_mark.png" />
    <span>I'm yellow because I'm referenced from the child of this current directory</span>
</p>

<p>
    <span>src="/subfolder/check_mark.png"</span>
    <img src="/subfolder/check_mark.png" />
    <span>I'm orange because I'm referenced from the child of the ROOT directory</span>
</p>

<p>
    <span>src="../subfolder/check_mark.png"</span>
    <img src="../subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced from the parent of this current directory</span>
</p>

<p>
    <span>src="subfolder/subfolder/check_mark.png"</span>
    <img src="subfolder/subfolder/check_mark.png" />
    <span>I'm [broken] because there is no subfolder two children down from this current directory</span>
</p>

<p>
    <span>src="/subfolder/subfolder/check_mark.png"</span>
    <img src="/subfolder/subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced two children down from the ROOT directory</span>
</p>

Now if you load up the index.html.en file located in the second subfolder
http://example.com/subfolder/subfolder/

This will be your output

enter image description here

What's the most efficient way to erase duplicates and sort a vector?

As already stated, unique requires a sorted container. Additionally, unique doesn't actually remove elements from the container. Instead, they are copied to the end, unique returns an iterator pointing to the first such duplicate element, and you are expected to call erase to actually remove the elements.

git stash blunder: git stash pop and ended up with merge conflicts

I had a similar thing happen to me. I didn't want to stage the files just yet so I added them with git add and then just did git reset. This basically just added and then unstaged my changes but cleared the unmerged paths.

Radio/checkbox alignment in HTML/CSS

I wouldn't use tables for this at all. CSS can easily do this.

I would do something like this:

   <p class="clearfix">
      <input id="option1" type="radio" name="opt" />
      <label for="option1">Option 1</label>
   </p>

p { margin: 0px 0px 10px 0px; }
input { float: left; width: 50px; }
label { margin: 0px 0px 0px 10px; float: left; }

Note: I have used the clearfix class from : http://www.positioniseverything.net/easyclearing.html

.clearfix:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}

.clearfix {display: inline-block;}

/* Hides from IE-mac \*/
* html .clearfix {height: 1%;}
.clearfix {display: block;}
/* End hide from IE-mac */

Matplotlib - global legend and title aside subplots

In addition to the orbeckst answer one might also want to shift the subplots down. Here's an MWE in OOP style:

import matplotlib.pyplot as plt

fig = plt.figure()
st = fig.suptitle("suptitle", fontsize="x-large")

ax1 = fig.add_subplot(311)
ax1.plot([1,2,3])
ax1.set_title("ax1")

ax2 = fig.add_subplot(312)
ax2.plot([1,2,3])
ax2.set_title("ax2")

ax3 = fig.add_subplot(313)
ax3.plot([1,2,3])
ax3.set_title("ax3")

fig.tight_layout()

# shift subplots down:
st.set_y(0.95)
fig.subplots_adjust(top=0.85)

fig.savefig("test.png")

gives:

enter image description here

CSS: styled a checkbox to look like a button, is there a hover?

Do what Kelly said...

BUT. Instead of having the input positioned absolute and top -20px (just hiding it off the page), make the input box hidden.

example:

<input type="checkbox" hidden> 

Works better and can put it anywhere on the page.

How can I listen to the form submit event in javascript?

This is the simplest way you can have your own javascript function be called when an onSubmit occurs.

HTML

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

JavaScript

window.onload = function() {
    var form = document.querySelector("form");
    form.onsubmit = submitted.bind(form);
}

function submitted(event) {
    event.preventDefault();
}

Mapping many-to-many association table with extra column(s)

Since the SERVICE_USER table is not a pure join table, but has additional functional fields (blocked), you must map it as an entity, and decompose the many to many association between User and Service into two OneToMany associations : One User has many UserServices, and one Service has many UserServices.

You haven't shown us the most important part : the mapping and initialization of the relationships between your entities (i.e. the part you have problems with). So I'll show you how it should look like.

If you make the relationships bidirectional, you should thus have

class User {
    @OneToMany(mappedBy = "user")
    private Set<UserService> userServices = new HashSet<UserService>();
}

class UserService {
    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToOne
    @JoinColumn(name = "service_code")
    private Service service;

    @Column(name = "blocked")
    private boolean blocked;
}

class Service {
    @OneToMany(mappedBy = "service")
    private Set<UserService> userServices = new HashSet<UserService>();
}

If you don't put any cascade on your relationships, then you must persist/save all the entities. Although only the owning side of the relationship (here, the UserService side) must be initialized, it's also a good practice to make sure both sides are in coherence.

User user = new User();
Service service = new Service();
UserService userService = new UserService();

user.addUserService(userService);
userService.setUser(user);

service.addUserService(userService);
userService.setService(service);

session.save(user);
session.save(service);
session.save(userService);

How do I get a plist as a Dictionary in Swift?

Here is a bit shorter version, based on @connor 's answer

guard let path = Bundle.main.path(forResource: "GoogleService-Info", ofType: "plist"),
    let myDict = NSDictionary(contentsOfFile: path) else {
    return nil
}

let value = dict.value(forKey: "CLIENT_ID") as! String?

Slicing a dictionary

the dictionary

d = {1:2, 3:4, 5:6, 7:8}

the subset of keys I'm interested in

l = (1,5)

answer

{key: d[key] for key in l}

How do I set an absolute include path in PHP?

One strategy

I don't know if this is the best way, but it has worked for me.

$root = $_SERVER['DOCUMENT_ROOT'];
include($root."/path/to/file.php");

What is the difference between static func and class func in Swift?

This example will clear every aspect!

import UIKit

class Parent {
    final func finalFunc() -> String { // Final Function, cannot be redeclared.
        return "Parent Final Function."
    }

    static func staticFunc() -> String { // Static Function, can be redeclared.
        return "Parent Static Function."
    }

    func staticFunc() -> String { // Above function redeclared as Normal function.
        return "Parent Static Function, redeclared with same name but as non-static(normal) function."
    }

    class func classFunc() -> String { // Class Function, can be redeclared.
        return "Parent Class Function."
    }

    func classFunc() -> String { // Above function redeclared as Normal function.
        return "Parent Class Function, redeclared with same name but as non-class(normal) function."
    }

    func normalFunc() -> String { // Normal function, obviously cannot be redeclared.
        return "Parent Normal Function."
    }
}

class Child:Parent {

    // Final functions cannot be overridden.

    override func staticFunc() -> String { // This override form is of the redeclared version i.e: "func staticFunc()" so just like any other function of normal type, it can be overridden.
        return "Child Static Function redeclared and overridden, can simply be called Child Normal Function."
    }

    override class func classFunc() -> String { // Class function, can be overidden.
        return "Child Class Function."
    }

    override func classFunc() -> String { // This override form is of the redeclared version i.e: "func classFunc()" so just like any other function of normal type, it can be overridden.
        return "Child Class Function, redeclared and overridden, can simply be called Child Normal Function."
    }

    override func normalFunc() -> String { // Normal function, can be overridden.
        return "Child Normal Function."
    }
}

let parent = Parent()
let child = Child()

// Final
print("1. " + parent.finalFunc())   // 1. Can be called by object.
print("2. " + child.finalFunc())    // 2. Can be called by object, parent(final) function will be called.
// Parent.finalFunc()               // Cannot be called by class name directly.
// Child.finalFunc()                // Cannot be called by class name directly.

// Static
print("3. " + parent.staticFunc())  // 3. Cannot be called by object, this is redeclared version (i.e: a normal function).
print("4. " + child.staticFunc())   // 4. Cannot be called by object, this is override form redeclared version (normal function).
print("5. " + Parent.staticFunc())  // 5. Can be called by class name directly.
print("6. " + Child.staticFunc())   // 6. Can be called by class name direcly, parent(static) function will be called.

// Class
print("7. " + parent.classFunc())   // 7. Cannot be called by object, this is redeclared version (i.e: a normal function).
print("8. " + child.classFunc())    // 8. Cannot be called by object, this is override form redeclared version (normal function).
print("9. " + Parent.classFunc())   // 9. Can be called by class name directly.
print("10. " + Child.classFunc())   // 10. Can be called by class name direcly, child(class) function will be called.

// Normal
print("11. " + parent.normalFunc())  // 11. Can be called by object.
print("12. " + child.normalFunc())   // 12. Can be called by object, child(normal) function will be called.
// Parent.normalFunc()               // Cannot be called by class name directly.
// Child.normalFunc()                // Cannot be called by class name directly.

/*
 Notes:
 ___________________________________________________________________________
 |Types------Redeclare------Override------Call by object------Call by Class|
 |Final----------0--------------0---------------1------------------0-------|
 |Static---------1--------------0---------------0------------------1-------|
 |Class----------1--------------1---------------0------------------1-------|
 |Normal---------0--------------1---------------1------------------0-------|
 ---------------------------------------------------------------------------

 Final vs Normal function: Both are same but normal methods can be overridden.
 Static vs Class function: Both are same but class methods can be overridden.
 */

Output: Output all types of function

Syntax error: Illegal return statement in JavaScript

If you want to return some value then wrap your statement in function

function my_function(){ 

 return my_thing; 
}

Problem is with the statement on the 1st line if you are trying to use PHP

var ask = confirm ('".$message."'); 

IF you are trying to use PHP you should use

 var ask = confirm (<?php echo "'".$message."'" ?>); //now message with be the javascript string!!