Programs & Examples On #Mod auth

Export specific rows from a PostgreSQL table as INSERT SQL script

I tried to write a procedure doing that, based on @PhilHibbs codes, on a different way. Please have a look and test.

 CREATE OR REPLACE FUNCTION dump(IN p_schema text, IN p_table text, IN p_where text)
   RETURNS setof text AS
 $BODY$
 DECLARE
     dumpquery_0 text;
     dumpquery_1 text;
     selquery text;
     selvalue text;
     valrec record;
     colrec record;
 BEGIN

     -- ------ --
     -- GLOBAL --
     --   build base INSERT
     --   build SELECT array[ ... ]
     dumpquery_0 := 'INSERT INTO ' ||  quote_ident(p_schema) || '.' || quote_ident(p_table) || '(';
     selquery    := 'SELECT array[';

     <<label0>>
     FOR colrec IN SELECT table_schema, table_name, column_name, data_type
                   FROM information_schema.columns
                   WHERE table_name = p_table and table_schema = p_schema
                   ORDER BY ordinal_position
     LOOP
         dumpquery_0 := dumpquery_0 || quote_ident(colrec.column_name) || ',';
         selquery    := selquery    || 'CAST(' || quote_ident(colrec.column_name) || ' AS TEXT),';
     END LOOP label0;

     dumpquery_0 := substring(dumpquery_0 ,1,length(dumpquery_0)-1) || ')';
     dumpquery_0 := dumpquery_0 || ' VALUES (';
     selquery    := substring(selquery    ,1,length(selquery)-1)    || '] AS MYARRAY';
     selquery    := selquery    || ' FROM ' ||quote_ident(p_schema)||'.'||quote_ident(p_table);
     selquery    := selquery    || ' WHERE '||p_where;
     -- GLOBAL --
     -- ------ --

     -- ----------- --
     -- SELECT LOOP --
     --   execute SELECT built and loop on each row
     <<label1>>
     FOR valrec IN  EXECUTE  selquery
     LOOP
         dumpquery_1 := '';
         IF not found THEN
             EXIT ;
         END IF;

         -- ----------- --
         -- LOOP ARRAY (EACH FIELDS) --
         <<label2>>
         FOREACH selvalue in ARRAY valrec.MYARRAY
         LOOP
             IF selvalue IS NULL
             THEN selvalue := 'NULL';
             ELSE selvalue := quote_literal(selvalue);
             END IF;
             dumpquery_1 := dumpquery_1 || selvalue || ',';
         END LOOP label2;
         dumpquery_1 := substring(dumpquery_1 ,1,length(dumpquery_1)-1) || ');';
         -- LOOP ARRAY (EACH FIELD) --
         -- ----------- --

         -- debug: RETURN NEXT dumpquery_0 || dumpquery_1 || ' --' || selquery;
         -- debug: RETURN NEXT selquery;
         RETURN NEXT dumpquery_0 || dumpquery_1;

     END LOOP label1 ;
     -- SELECT LOOP --
     -- ----------- --

 RETURN ;
 END
 $BODY$
   LANGUAGE plpgsql VOLATILE;

And then :

-- for a range
SELECT dump('public', 'my_table','my_id between 123456 and 123459'); 
-- for the entire table
SELECT dump('public', 'my_table','true');

tested on my postgres 9.1, with a table with mixed field datatype (text, double, int,timestamp without time zone, etc).

That's why the CAST in TEXT type is needed. My test run correctly for about 9M lines, looks like it fail just before 18 minutes of running.

ps : I found an equivalent for mysql on the WEB.

Converting Symbols, Accent Letters to English Alphabet

The original request has been answered already.

However, I am posting the below answer for those who might be looking for generic transliteration code to transliterate any charset to Latin/English in Java.

Naive meaning of tranliteration: Translated string in it's final form/target charset sounds like the string in it's original form. If we want to transliterate any charset to Latin(English alphabets), then ICU4(ICU4J library in java ) will do the job.

Here is the code snippet in java:

    import com.ibm.icu.text.Transliterator; //ICU4J library import

    public static String TRANSLITERATE_ID = "NFD; Any-Latin; NFC";
    public static String NORMALIZE_ID = "NFD; [:Nonspacing Mark:] Remove; NFC";

    /**
    * Returns the transliterated string to convert any charset to latin.
    */
    public static String transliterate(String input) {
        Transliterator transliterator = Transliterator.getInstance(TRANSLITERATE_ID + "; " + NORMALIZE_ID);
        String result = transliterator.transliterate(input);
        return result;
    }

Track a new remote branch created on GitHub

When the branch is no remote branch you can push your local branch direct to the remote.

git checkout master
git push origin master

or when you have a dev branch

git checkout dev
git push origin dev

or when the remote branch exists

git branch dev -t origin/dev

There are some other posibilites to push a remote branch.

Difference between "char" and "String" in Java

I would recommend you to read through the Java tutorial documentation hosted on Oracle's website whenever you are in doubt about anything related to Java.

You can get a clear understanding of the concepts by going through the following tutorials:

jquery AJAX and json format

You need to parse the string you are sending from javascript object to the JSON object

var json=$.parseJSON(data);

Combining Two Images with OpenCV

The three best way to do it using a single line of code

import cv2
import numpy as np 


img = cv2.imread('Imgs/Saint_Roch_new/data/Point_4_Face.jpg')
dim = (256, 256)
resizedLena = cv2.resize(img, dim, interpolation = cv2.INTER_LINEAR)
X, Y = resizedLena, resizedLena

# Methode 1: Using Numpy (hstack, vstack)
Fusion_Horizontal = np.hstack((resizedLena, Y, X))
Fusion_Vertical   = np.vstack((newIMG, X))

cv2.imshow('Fusion_Vertical using vstack', Fusion_Vertical)
cv2.waitKey(0)

# Methode 2: Using Numpy (contanate)
Fusion_Vertical   = np.concatenate((resizedLena, X, Y), axis=0)
Fusion_Horizontal = np.concatenate((resizedLena, X, Y), axis=1)

cv2.imshow("Fusion_Horizontal usung concatenate", Fusion_Horizontal)
cv2.waitKey(0)


# Methode 3: Using OpenCV (vconcat, hconcat)
Fusion_Vertical   = cv2.vconcat([resizedLena, X, Y])
Fusion_Horizontal = cv2.hconcat([resizedLena, X, Y])

cv2.imshow("Fusion_Horizontal Using hconcat", Fusion_Horizontal)
cv2.waitKey(0)

Using sessions & session variables in a PHP Login Script

You need to begin the session at the top of a page or before you call session code

session_start(); 

How to ignore conflicts in rpm installs

Try Freshen command:

rpm -Fvh *.rpm

How do you make a HTTP request with C++?

Updated answer for April, 2020:

I've had a lot of success, recently, with cpp-httplib (both as a client and a server). It's mature and its approximate, single-threaded RPS is around 6k.

On more of the bleeding edge, there's a really promising framework, cpv-framework, that can get around 180k RPS on two cores (and will scale well with the number of cores because it's based on the seastar framework, which powers the fastest DBs on the planet, scylladb).

However, cpv-framework is still relatively immature; so, for most uses, I highly recommend cpp-httplib.

This recommendation replaces my previous answer (8 years ago).

Why does Maven have such a bad rep?

I think it has a bad reputation with people who have the most simple and the most complicated projects.

If you're building a single WAR from a single codebase it forces you to move your project structure around and manually list the two of three jars into the POM file.

If you're building one EAR from a set of nine EAR file prototypes with some combination of five WAR files, three EJBs and 17 other tools, dependency jars and configurations that require tweaking MANIFEST.MF and XML files in existing resources during final build; then Maven is likely too restricting. Such a project becomes a mess of complicated nested profiles, properties files and misuse of the Maven build goals and Classifier designation.

So if you're in the bottom 10% of the complexity curve, its overkill. At the top 10% of that curve, you're in a straitjacket.

Maven's growth is because it works well for the middle 80%

Compile a DLL in C/C++, then call it from another program

The thing to watch out for when writing C++ dlls is name mangling. If you want interoperability between C and C++, you'd be better off by exporting non-mangled C-style functions from within the dll.

You have two options to use a dll

  • Either use a lib file to link the symbols -- compile time dynamic linking
  • Use LoadLibrary() or some suitable function to load the library, retrieve a function pointer (GetProcAddress) and call it -- runtime dynamic linking

Exporting classes will not work if you follow the second method though.

u'\ufeff' in Python string

This problem arise basically when you save your python code in a UTF-8 or UTF-16 encoding because python add some special character at the beginning of the code automatically (which is not shown by the text editors) to identify the encoding format. But, when you try to execute the code it gives you the syntax error in line 1 i.e, start of code because python compiler understands ASCII encoding. when you view the code of file using read() function you can see at the begin of the returned code '\ufeff' is shown. The one simplest solution to this problem is just by changing the encoding back to ASCII encoding(for this you can copy your code to a notepad and save it Remember! choose the ASCII encoding... Hope this will help.

Bootstrap - Removing padding or margin when screen size is smaller

.container-fluid {
    margin-right: auto;
    margin-left: auto;
    padding-left:0px;
    padding-right:0px;
}

Remove attribute "checked" of checkbox

Sorry, I solved my problem with the code above:

$("#captureImage").live("change", function() {
    if($("#captureImage:checked").val() !== undefined) {
        navigator.device.capture.captureImage(function(mediaFiles) {
            console.log("works");
        }, function(exception) {
            $("#captureImage").removeAttr('checked').checkboxradio('refresh');
            _callback.error(exception);
        }, {});
    }
});

how to add background image to activity?

Nowadays we have to use match_parent :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:background="@drawable/background">
</RelativeLayout>

enter image description here

Mockito: InvalidUseOfMatchersException

For my case, the exception was raised because I tried to mock a package-access method. When I changed the method access level from package to protected the exception went away. E.g. inside below Java class,

public class Foo {
    String getName(String id) {
        return mMap.get(id);
    }
}

the method String getName(String id) has to be AT LEAST protected level so that the mocking mechanism (sub-classing) can work.

is there a function in lodash to replace matched item

As the time passes you should embrace a more functional approach in which you should avoid data mutations and write small, single responsibility functions. With the ECMAScript 6 standard, you can enjoy functional programming paradigm in JavaScript with the provided map, filter and reduce methods. You don't need another lodash, underscore or what else to do most basic things.

Down below I have included some proposed solutions to this problem in order to show how this problem can be solved using different language features:

Using ES6 map:

_x000D_
_x000D_
const replace = predicate => replacement => element =>_x000D_
  predicate(element) ? replacement : element_x000D_
 _x000D_
const arr = [ { id: 1, name: "Person 1" }, { id:2, name:"Person 2" } ];_x000D_
const predicate = element => element.id === 1_x000D_
const replacement = { id: 100, name: 'New object.' }_x000D_
_x000D_
const result = arr.map(replace (predicate) (replacement))_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_


Recursive version - equivalent of mapping:

Requires destructuring and array spread.

_x000D_
_x000D_
const replace = predicate => replacement =>_x000D_
{_x000D_
  const traverse = ([head, ...tail]) =>_x000D_
    head_x000D_
    ? [predicate(head) ? replacement : head, ...tail]_x000D_
    : []_x000D_
  return traverse_x000D_
}_x000D_
 _x000D_
const arr = [ { id: 1, name: "Person 1" }, { id:2, name:"Person 2" } ];_x000D_
const predicate = element => element.id === 1_x000D_
const replacement = { id: 100, name: 'New object.' }_x000D_
_x000D_
const result = replace (predicate) (replacement) (arr)_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_


When the final array's order is not important you can use an object as a HashMap data structure. Very handy if you already have keyed collection as an object - otherwise you have to change your representation first.

Requires object rest spread, computed property names and Object.entries.

_x000D_
_x000D_
const replace = key => ({id, ...values}) => hashMap =>_x000D_
({_x000D_
  ...hashMap,       //original HashMap_x000D_
  [key]: undefined, //delete the replaced value_x000D_
  [id]: values      //assign replacement_x000D_
})_x000D_
_x000D_
// HashMap <-> array conversion_x000D_
const toHashMapById = array =>_x000D_
  array.reduce(_x000D_
    (acc, { id, ...values }) => _x000D_
    ({ ...acc, [id]: values })_x000D_
  , {})_x000D_
  _x000D_
const toArrayById = hashMap =>_x000D_
  Object.entries(hashMap)_x000D_
  .filter( // filter out undefined values_x000D_
    ([_, value]) => value _x000D_
  ) _x000D_
  .map(_x000D_
    ([id, values]) => ({ id, ...values })_x000D_
  )_x000D_
_x000D_
const arr = [ { id: 1, name: "Person 1" }, { id:2, name:"Person 2" } ];_x000D_
const replaceKey = 1_x000D_
const replacement = { id: 100, name: 'New object.' }_x000D_
_x000D_
// Create a HashMap from the array, treating id properties as keys_x000D_
const hashMap = toHashMapById(arr)_x000D_
console.log(hashMap)_x000D_
_x000D_
// Result of replacement - notice an undefined value for replaced key_x000D_
const resultHashMap = replace (replaceKey) (replacement) (hashMap)_x000D_
console.log(resultHashMap)_x000D_
_x000D_
// Final result of conversion from the HashMap to an array_x000D_
const result = toArrayById (resultHashMap)_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

Sending intent to BroadcastReceiver from adb

I had the same problem and found out that you have to escape spaces in the extra:

adb shell am broadcast -a com.whereismywifeserver.intent.TEST --es sms_body "test\ from\ adb"

So instead of "test from adb" it should be "test\ from\ adb"

MySQL error #1054 - Unknown column in 'Field List'

You have an error in your OrderQuantity column. It is named "OrderQuantity" in the INSERT statement and "OrderQantity" in the table definition.

Also, I don't think you can use NOW() as default value in OrderDate. Try to use the following:

 OrderDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP

Example Fiddle

HTML/JavaScript: Simple form validation on submit

You have several errors there.

First, you have to return a value from the function in the HTML markup: <form name="ff1" method="post" onsubmit="return validateForm();">

Second, in the JSFiddle, you place the code inside onLoad which and then the form won't recognize it - and last you have to return true from the function if all validation is a success - I fixed some issues in the update:

https://jsfiddle.net/mj68cq0b/

function validateURL(url) {
    var reurl = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
    return reurl.test(url);
}

function validateForm()
{
    // Validate URL
    var url = $("#frurl").val();
    if (validateURL(url)) { } else {
        alert("Please enter a valid URL, remember including http://");
        return false;
    }

    // Validate Title
    var title = $("#frtitle").val();
    if (title=="" || title==null) {
        alert("Please enter only alphanumeric values for your advertisement title");
        return false;
    }

    // Validate Email
    var email = $("#fremail").val();
    if ((/(.+)@(.+){2,}\.(.+){2,}/.test(email)) || email=="" || email==null) { } else {
        alert("Please enter a valid email");
        return false;
    }
  return true;
}

How do I get row id of a row in sql server

SQL does not do that. The order of the tuples in the table are not ordered by insertion date. A lot of people include a column that stores that date of insertion in order to get around this issue.

Conveniently map between enum and int / String

Really great question :-) I used solution similar to Mr.Ferguson`s sometime ago. Our decompiled enum looks like this:

final class BonusType extends Enum
{

    private BonusType(String s, int i, int id)
    {
        super(s, i);
        this.id = id;
    }

    public static BonusType[] values()
    {
        BonusType abonustype[];
        int i;
        BonusType abonustype1[];
        System.arraycopy(abonustype = ENUM$VALUES, 0, abonustype1 = new BonusType[i = abonustype.length], 0, i);
        return abonustype1;
    }

    public static BonusType valueOf(String s)
    {
        return (BonusType)Enum.valueOf(BonusType, s);
    }

    public static final BonusType MONTHLY;
    public static final BonusType YEARLY;
    public static final BonusType ONE_OFF;
    public final int id;
    private static final BonusType ENUM$VALUES[];

    static 
    {
        MONTHLY = new BonusType("MONTHLY", 0, 1);
        YEARLY = new BonusType("YEARLY", 1, 2);
        ONE_OFF = new BonusType("ONE_OFF", 2, 3);
        ENUM$VALUES = (new BonusType[] {
            MONTHLY, YEARLY, ONE_OFF
        });
    }
}

Seeing this is apparent why ordinal() is unstable. It is the i in super(s, i);. I'm also pessimistic that you can think of a more elegant solution than these you already enumerated. After all enums are classes as any final classes.

How should I remove all the leading spaces from a string? - swift

For anyone looking for an answer to remove only the leading whitespaces out of a string (as the question title clearly ask), Here's an answer:

Assuming:

let string = "   Hello, World!   "

To remove all leading whitespaces, use the following code:

var filtered = ""
var isLeading = true
for character in string {
    if character.isWhitespace && isLeading {
        continue
    } else {
        isLeading = false
        filtered.append(character)
    }
}
print(filtered) // "Hello, World!   "

I'm sure there's better code than this, but it does the job for me.

trying to align html button at the center of the my page

Here is the solution as asked

_x000D_
_x000D_
<button type="button" style="background-color:yellow;margin:auto;display:block">mybuttonname</button>
_x000D_
_x000D_
_x000D_

Connecting to Oracle Database through C#?

First off you need to download and install ODP from this site http://www.oracle.com/technetwork/topics/dotnet/index-085163.html

After installation add a reference of the assembly Oracle.DataAccess.dll.

Your are good to go after this.

using System; 
using Oracle.DataAccess.Client; 

class OraTest
{ 
    OracleConnection con; 
    void Connect() 
    { 
        con = new OracleConnection(); 
        con.ConnectionString = "User Id=<username>;Password=<password>;Data Source=<datasource>"; 
        con.Open(); 
        Console.WriteLine("Connected to Oracle" + con.ServerVersion); 
    }

    void Close() 
    {
        con.Close(); 
        con.Dispose(); 
    } 

    static void Main() 
    { 
        OraTest ot= new OraTest(); 
        ot.Connect(); 
        ot.Close(); 
    } 
}

UTF-8 output from PowerShell

This is a bug in .NET. When PowerShell launches, it caches the output handle (Console.Out). The Encoding property of that text writer does not pick up the value StandardOutputEncoding property.

When you change it from within PowerShell, the Encoding property of the cached output writer returns the cached value, so the output is still encoded with the default encoding.

As a workaround, I would suggest not changing the encoding. It will be returned to you as a Unicode string, at which point you can manage the encoding yourself.

Caching example:

102 [C:\Users\leeholm]
>> $r1 = [Console]::Out

103 [C:\Users\leeholm]
>> $r1

Encoding                                          FormatProvider
--------                                          --------------
System.Text.SBCSCodePageEncoding                  en-US



104 [C:\Users\leeholm]
>> [Console]::OutputEncoding = [System.Text.Encoding]::UTF8

105 [C:\Users\leeholm]
>> $r1

Encoding                                          FormatProvider
--------                                          --------------
System.Text.SBCSCodePageEncoding                  en-US

How to use JavaScript source maps (.map files)?

  • How can a developer use it?

I didn't find answer for this in the comments, here is how can be used:

  1. Don't link your js.map file in your index.html file (no need for that)
  2. Minifiacation tools (good ones) add a comment to your .min.js file:

    //# sourceMappingURL=yourFileName.min.js.map

which will connect your .map file.

When the min.js and js.map files are ready...

  1. Chrome: Open dev-tools, navigate to Sources tab, You will see sources folder, where un-minified applications files are kept.

Difference between dict.clear() and assigning {} in Python

One thing not mentioned is scoping issues. Not a great example, but here's the case where I ran into the problem:

def conf_decorator(dec):
    """Enables behavior like this:
        @threaded
        def f(): ...

        or

        @threaded(thread=KThread)
        def f(): ...

        (assuming threaded is wrapped with this function.)
        Sends any accumulated kwargs to threaded.
        """
    c_kwargs = {}
    @wraps(dec)
    def wrapped(f=None, **kwargs):
        if f:
            r = dec(f, **c_kwargs)
            c_kwargs = {}
            return r
        else:
            c_kwargs.update(kwargs) #<- UnboundLocalError: local variable 'c_kwargs' referenced before assignment
            return wrapped
    return wrapped

The solution is to replace c_kwargs = {} with c_kwargs.clear()

If someone thinks up a more practical example, feel free to edit this post.

Programmatically close aspx page from code behind

You should inject a startup script that will close the page after the postback has finished.

ClientScript.RegisterStartupScript(typeof(Page), "closePage", "<script type='text/JavaScript'>window.close();</script>"); 

String to LocalDate

As you use Joda Time, you should use DateTimeFormatter:

final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MMM-dd");
final LocalDate dt = dtf.parseLocalDate(yourinput);

If using Java 8 or later, then refer to hertzi's answer

change pgsql port

There should be a line in your postgresql.conf file that says:

port = 1486

Change that.

The location of the file can vary depending on your install options. On Debian-based distros it is /etc/postgresql/8.3/main/

On Windows it is C:\Program Files\PostgreSQL\9.3\data

Don't forget to sudo service postgresql restart for changes to take effect.

Send multipart/form-data files with angular using $http

Here's an updated answer for Angular 4 & 5. TransformRequest and angular.identity were dropped. I've also included the ability to combine files with JSON data in one request.

Angular 5 Solution:

import {HttpClient} from '@angular/common/http';

uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
  // Note that setting a content-type header
  // for mutlipart forms breaks some built in
  // request parsers like multer in express.
  const options = {} as any; // Set any options you like
  const formData = new FormData();

  // Append files to the virtual form.
  for (const file of files) {
    formData.append(file.name, file)
  }

  // Optional, append other kev:val rest data to the form.
  Object.keys(restObj).forEach(key => {
    formData.append(key, restObj[key]);
  });

  // Send it.
  return this.httpClient.post(uploadUrl, formData, options)
    .toPromise()
    .catch((e) => {
      // handle me
    });
}

Angular 4 Solution:

// Note that these imports below are deprecated in Angular 5
import {Http, RequestOptions} from '@angular/http';

uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
  // Note that setting a content-type header
  // for mutlipart forms breaks some built in
  // request parsers like multer in express.
  const options = new RequestOptions();
  const formData = new FormData();

  // Append files to the virtual form.
  for (const file of files) {
    formData.append(file.name, file)
  }

  // Optional, append other kev:val rest data to the form.
  Object.keys(restObj).forEach(key => {
    formData.append(key, restObj[key]);
  });

  // Send it.
  return this.http.post(uploadUrl, formData, options)
    .toPromise()
    .catch((e) => {
      // handle me
    });
}

Enterprise app deployment doesn't work on iOS 7.1

Some nice guy handled the issue by using the Class 1 StartSSL certificate and shared Apache config that adds certificate support (will work with any certificate) and code for changing links in existing *.plist files automatically. Too long to copy, so here is the link: http://cases.azoft.com/how-to-fix-certificate-is-not-valid-error-on-ios-7/

Explanation of JSONB introduced by PostgreSQL

Peeyush:

The short answer is:

  • If you are doing a lot of JSON manipulation inside PostgreSQL, such as sorting, slicing, splicing, etc., you should use JSONB for speed reasons.
  • If you need indexed lookups for arbitrary key searches on JSON, then you should use JSONB.
  • If you are doing neither of the above, you should probably use JSON.
  • If you need to preserve key ordering, whitespace, and duplicate keys, you should use JSON.

For a longer answer, you'll need to wait for me to do a full "HowTo" writeup closer to the 9.4 release.

How to add a custom right-click menu to a webpage?

You could try simply blocking the context menu by adding the following to your body tag:

<body oncontextmenu="return false;">

This will block all access to the context menu (not just from the right mouse button but from the keyboard as well).

P.S. you can add this to any tag you want to disable the context menu on

for example:

<div class="mydiv" oncontextmenu="return false;">

Will disable the context menu in that particular div only

How to copy commits from one branch to another?

You could create a patch from the commits that you want to copy and apply the patch to the destination branch.

What is the best way to declare global variable in Vue.js?

For any Single File Component users, here is how I set up global variable(s)

  1. Assuming you are using Vue-Cli's webpack template
  2. Declare your variable(s) in somewhere variable.js

    const shallWeUseVuex = false;
    
  3. Export it in variable.js

    module.exports = { shallWeUseVuex : shallWeUseVuex };
    
  4. Require and assign it in your vue file

    export default {
        data() {
            return {
                shallWeUseVuex: require('../../variable.js')
            };
        }
    }
    

Ref: https://vuejs.org/v2/guide/state-management.html#Simple-State-Management-from-Scratch

How to split a string in Ruby and get all items except the first one?

ex="test1,test2,test3,test4,test5"
all_but_first=ex.split(/,/)[1..-1]

WAITING at sun.misc.Unsafe.park(Native Method)

unsafe.park is pretty much the same as thread.wait, except that it's using architecture specific code (thus the reason it's 'unsafe'). unsafe is not made available publicly, but is used within java internal libraries where architecture specific code would offer significant optimization benefits. It's used a lot for thread pooling.

So, to answer your question, all the thread is doing is waiting for something, it's not really using any CPU. Considering that your original stack trace shows that you're using a lock I would assume a deadlock is going on in your case.

Yes I know you have almost certainly already solved this issue by now. However, you're one of the top results if someone googles sun.misc.unsafe.park. I figure answering the question may help others trying to understand what this method that seems to be using all their CPU is.

$http get parameters does not work

From $http.get docs, the second parameter is a configuration object:

get(url, [config]);

Shortcut method to perform GET request.

You may change your code to:

$http.get('accept.php', {
    params: {
        source: link, 
        category_id: category
    }
});

Or:

$http({
    url: 'accept.php', 
    method: 'GET',
    params: { 
        source: link, 
        category_id: category
    }
});

As a side note, since Angular 1.6: .success should not be used anymore, use .then instead:

$http.get('/url', config).then(successCallback, errorCallback);

How do I get rid of the "cannot empty the clipboard" error?

check this tip. worked for here http://mobeer.blogspot.com/2009/01/excel-2007-cannot-empty-clipboard.html:

This might save somebody some time and headaches if google picks it up. I was getting a 'Cannot empty the Clipboard' error every time I moved cells around in Excel - eventually I mucked around with the settings and made it go away. Here's how; In the excel main menu (glass globe w/logo), click Excel options, then Advanced, then turn off 'Show paste options buttons'

How exciting was this as my first post of the year?

Update: I still haven't found a permanent solution but I found another thing that seems to help. In Excel 2007, from the "home" tab, the first thing on the left is the clipboard tool panel. Expand the panel to view the clipboard and in the clipboard you might find "cannot empty clipboard" as an entry. Empty the clipboard, keep the panel open for a second or two while you do a few cut and pastes/drags etc. and then the bogey seems to go away.

I call this the cable dance because back in the day I had a printer that only worked if you unplugged the cable, shook it out and plugged it back in.

How do I convert a Swift Array to a String?

You can print any object using the print function

or use \(name) to convert any object to a string.

Example:

let array = [1,2,3,4]

print(array) // prints "[1,2,3,4]"

let string = "\(array)" // string == "[1,2,3,4]"
print(string) // prints "[1,2,3,4]"

Difference between const reference and normal parameter

With

 void DoWork(int n);

n is a copy of the value of the actual parameter, and it is legal to change the value of n within the function. With

void DoWork(const int &n);

n is a reference to the actual parameter, and it is not legal to change its value.

How to get a view table query (code) in SQL Server 2008 Management Studio

if i understood you can do the following

Right Click on View Name in SQL Server Management Studio -> Script View As ->CREATE To ->New Query Window

How to export SQL Server 2005 query to CSV

set nocount on

the quotes are there, use -w2000 to keep each row on one line.

OpenCV error: the function is not implemented

Before installing libgtk2.0-dev and pkg-config or libqt4-dev. Make sure that you have uninstalled opencv. You can confirm this by running import cv2 on your python shell. If it fails, then install the needed packages and re-run cmake .

Invalid attempt to read when no data is present

You have to call dr.Read() before attempting to read any data. That method will return false if there is nothing to read.

What is <scope> under <dependency> in pom.xml for?

added good images with explain scopes

enter image description here

enter image description here

Recursively looping through an object to build a property list

UPDATE: JUST USE JSON.stringify to print objects on screen!

All you need is this line:

document.body.innerHTML = '<pre>' + JSON.stringify(ObjectWithSubObjects, null, "\t") + '</pre>';

This is my older version of printing objects recursively on screen:

 var previousStack = '';
    var output = '';
    function objToString(obj, stack) {
        for (var property in obj) {
            var tab = '&nbsp;&nbsp;&nbsp;&nbsp;';
            if (obj.hasOwnProperty(property)) {
                if (typeof obj[property] === 'object' && typeof stack === 'undefined') {
                    config = objToString(obj[property], property);
                } else {
                    if (typeof stack !== 'undefined' && stack !== null && stack === previousStack) {
                        output = output.substring(0, output.length - 1);  // remove last }
                        output += tab + '<span>' + property + ': ' + obj[property] + '</span><br />'; // insert property
                        output += '}';   // add last } again
                    } else {
                        if (typeof stack !== 'undefined') {
                            output += stack + ': {  <br />' + tab;
                        }
                        output += '<span>' + property + ': ' + obj[property] + '</span><br />';
                        if (typeof stack !== 'undefined') {
                            output += '}';
                        }
                    }
                    previousStack = stack;
                }
            }
        }
        return output;
    }

Usage:

document.body.innerHTML = objToString(ObjectWithSubObjects);

Example output:

cache: false
position: fixed
effect: { 
    fade: false
    fall: true
}

Obviously this can be improved by adding comma's when needed and quotes from string values. But this was good enough for my case.

How to open the terminal in Atom?

  1. Open your Atom IDE
  2. press ctrl+shift+P and search for "platformio-ide-terminal" package
  3. press install
  4. once installed press ctrl+~ (tilde above tab key in a standard keyboard)
  5. terminal opens enjoy!!!

Converting byte array to String (Java)

I suggest Arrays.toString(byte_array);

It depends on your purpose. For example, I wanted to save a byte array exactly like the format you can see at time of debug that is something like this : [1, 2, 3] If you want to save exactly same value without converting the bytes to character format, Arrays.toString (byte_array) does this,. But if you want to save characters instead of bytes, you should use String s = new String(byte_array). In this case, s is equal to equivalent of [1, 2, 3] in format of character.

How to add a button programmatically in VBA next to some sheet cell data?

I think this is enough to get you on a nice path:

Sub a()
  Dim btn As Button
  Application.ScreenUpdating = False
  ActiveSheet.Buttons.Delete
  Dim t As Range
  For i = 2 To 6 Step 2
    Set t = ActiveSheet.Range(Cells(i, 3), Cells(i, 3))
    Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
    With btn
      .OnAction = "btnS"
      .Caption = "Btn " & i
      .Name = "Btn" & i
    End With
  Next i
  Application.ScreenUpdating = True
End Sub

Sub btnS()
 MsgBox Application.Caller
End Sub

It creates the buttons and binds them to butnS(). In the btnS() sub, you should show your dialog, etc.

Mathematica graphics

PHP Session timeout

<?php 
session_start();

if (time()<$_SESSION['time']+10){
$_SESSION['time'] = time();
echo "welcome old user";
}

else{
session_destroy();
session_start();
$_SESSION['time'] = time();
echo "welcome new user";
}
?>

how to set start value as "0" in chartjs?

Please add this option:

//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero : true,

(Reference: Chart.js)

N.B: The original solution I posted was for Highcharts, if you are not using Highcharts then please remove the tag to avoid confusion

Add custom header in HttpWebRequest

You can add values to the HttpWebRequest.Headers collection.

According to MSDN, it should be supported in windows phone: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.headers%28v=vs.95%29.aspx

How do I run pip on python for windows?

Maybe you'd like try run pip in Python shell like this:

>>> import pip
>>> pip.main(['install', 'requests'])

This will install requests package using pip.


Because pip is a module in standard library, but it isn't a built-in function(or module), so you need import it.

Other way, you should run pip in system shell(cmd. If pip is in path).

PHP: How to get referrer URL?

If $_SERVER['HTTP_REFERER'] variable doesn't seems to work, then you can either use Google Analytics or AddThis Analytics.

How can I do time/hours arithmetic in Google Spreadsheet?

I used the TO_PURE_NUMBER() function and it worked.

Windows Batch Files: if else

An alternative would be to set a variable, and check whether it is defined:

SET ARG=%1
IF DEFINED ARG (echo "It is defined: %1") ELSE (echo "%%1 is not defined")

Unfortunately, using %1 directly with DEFINED doesn't work.

The import javax.persistence cannot be resolved

I solved the problem by adding the following dependency

<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>2.2</version>
</dependency>

Together with

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>

How to check what version of jQuery is loaded?

You should actually wrap this in a try/catch block for IE:

// Ensure jquery is loaded -- syntaxed for IE compatibility
try
{
    var jqueryIsLoaded=jQuery;
    jQueryIsLoaded=true;
}
catch(err)
{
    var jQueryIsLoaded=false;
}
if(jQueryIsLoaded)
{
    $(function(){
        /** site level jquery code here **/
    });
}
else
{
    // Jquery not loaded
}

Editing specific line in text file in Python

you can use fileinput to do in place editing

import fileinput
for  line in fileinput.FileInput("myfile", inplace=1):
    if line .....:
         print line

Applying a single font to an entire website with CSS

* { font-family: Algerian; }

The universal selector * refers to any element.

Oracle Add 1 hour in SQL

select sysdate + 1/24 from dual;

sysdate is a function without arguments which returns DATE type
+ 1/24 adds 1 hour to a date

select to_char(to_date('2014-10-15 03:30:00 pm', 'YYYY-MM-DD HH:MI:SS pm') + 1/24, 'YYYY-MM-DD HH:MI:SS pm') from dual;

List of encodings that Node.js supports

The encodings are spelled out in the buffer documentation.

Buffers and character encodings:

Character Encodings

  • utf8: Multi-byte encoded Unicode characters. Many web pages and other document formats use UTF-8. This is the default character encoding.
  • utf16le: Multi-byte encoded Unicode characters. Unlike utf8, each character in the string will be encoded using either 2 or 4 bytes.
  • latin1: Latin-1 stands for ISO-8859-1. This character encoding only supports the Unicode characters from U+0000 to U+00FF.

Binary-to-Text Encodings

  • base64: Base64 encoding. When creating a Buffer from a string, this encoding will also correctly accept "URL and Filename Safe Alphabet" as specified in RFC 4648, Section 5.
  • hex: Encode each byte as two hexadecimal characters.

Legacy Character Encodings

  • ascii: For 7-bit ASCII data only. Generally, there should be no reason to use this encoding, as 'utf8' (or, if the data is known to always be ASCII-only, 'latin1') will be a better choice when encoding or decoding ASCII-only text.
  • binary: Alias for 'latin1'.
  • ucs2: Alias of 'utf16le'.

Print string and variable contents on the same line in R

{glue} offers much better string interpolation, see my other answer. Also, as Dainis rightfully mentions, sprintf() is not without problems.

There's also sprintf():

sprintf("Current working dir: %s", wd)

To print to the console output, use cat() or message():

cat(sprintf("Current working dir: %s\n", wd))
message(sprintf("Current working dir: %s\n", wd))

Is there a way of setting culture for a whole application? All current threads and new threads?

For .NET 4.5 and higher, you should use:

var culture = new CultureInfo("en-US");
CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;

jquery .live('click') vs .click()

remember that the use of "live" is for "jQuery 1.3" or higher

in version "jQuery 1.4.3" or higher is used "delegate"

and version "jQuery 1.7 +" or higher is used "on"

$( selector ).live( events, data, handler ); // jQuery 1.3+
$( document ).delegate( selector, events, data, handler ); // jQuery 1.4.3+
$( document ).on( events, selector, data, handler ); // jQuery 1.7+

As of jQuery 1.7, the .live() method is deprecated.

check http://api.jquery.com/live/

Regards, Fernando

How do I convert Long to byte[] and back in java

I will add another answer which is the fastest one possible ?(yes, even more than the accepted answer), BUT it will not work for every single case. HOWEVER, it WILL work for every conceivable scenario:

You can simply use String as intermediate. Note, this WILL give you the correct result even though it seems like using String might yield the wrong results AS LONG AS YOU KNOW YOU'RE WORKING WITH "NORMAL" STRINGS. This is a method to increase effectiveness and make the code simpler which in return must use some assumptions on the data strings it operates on.

Con of using this method: If you're working with some ASCII characters like these symbols in the beginning of the ASCII table, the following lines might fail, but let's face it - you probably will never use them anyway.

Pro of using this method: Remember that most people usually work with some normal strings without any unusual characters and then the method is the simplest and fastest way to go.

from Long to byte[]:

byte[] arr = String.valueOf(longVar).getBytes();

from byte[] to Long:

long longVar = Long.valueOf(new String(byteArr)).longValue();

Function Pointers in Java

The Java idiom for function-pointer-like functionality is an an anonymous class implementing an interface, e.g.

Collections.sort(list, new Comparator<MyClass>(){
    public int compare(MyClass a, MyClass b)
    {
        // compare objects
    }
});

Update: the above is necessary in Java versions prior to Java 8. Now we have much nicer alternatives, namely lambdas:

list.sort((a, b) -> a.isGreaterThan(b));

and method references:

list.sort(MyClass::isGreaterThan);

C++ Fatal Error LNK1120: 1 unresolved externals

In my particular case, this error error was happening because the file which I've added wasn't referenced at .vcproj file.

SQL to Entity Framework Count Group-By

with EF 6.2 it worked for me

  var query = context.People
               .GroupBy(p => new {p.name})
               .Select(g => new { name = g.Key.name, count = g.Count() });

How can I set size of a button?

The following bit of code does what you ask for. Just make sure that you assign enough space so that the text on the button becomes visible

JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(4,4,4,4));

for(int i=0 ; i<16 ; i++){
    JButton btn = new JButton(String.valueOf(i));
    btn.setPreferredSize(new Dimension(40, 40));
    panel.add(btn);
}
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);

The X and Y (two first parameters of the GridLayout constructor) specify the number of rows and columns in the grid (respectively). You may leave one of them as 0 if you want that value to be unbounded.

Edit

I've modified the provided code and I believe it now conforms to what is desired:

JFrame frame = new JFrame("Colored Trails");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

JPanel firstPanel = new JPanel();
firstPanel.setLayout(new GridLayout(4, 4));
firstPanel.setMaximumSize(new Dimension(400, 400));
JButton btn;
for (int i=1; i<=4; i++) {
    for (int j=1; j<=4; j++) {
        btn = new JButton();
        btn.setPreferredSize(new Dimension(100, 100));
        firstPanel.add(btn);
    }
}

JPanel secondPanel = new JPanel();
secondPanel.setLayout(new GridLayout(5, 13));
secondPanel.setMaximumSize(new Dimension(520, 200));
for (int i=1; i<=5; i++) {
    for (int j=1; j<=13; j++) {
        btn = new JButton();
        btn.setPreferredSize(new Dimension(40, 40));
        secondPanel.add(btn);
    }
}

mainPanel.add(firstPanel);
mainPanel.add(secondPanel);
frame.setContentPane(mainPanel);

frame.setSize(520,600);
frame.setMinimumSize(new Dimension(520,600));
frame.setVisible(true);

Basically I now set the preferred size of the panels and a minimum size for the frame.

Angular pass callback function to child component as @Input similar to AngularJS way

The current answer can be simplified to...

@Component({
  ...
  template: '<child [myCallback]="theCallback"></child>',
  directives: [ChildComponent]
})
export class ParentComponent{
  public theCallback(){
    ...
  }
}

@Component({...})
export class ChildComponent{
  //This will be bound to the ParentComponent.theCallback
  @Input()
  public myCallback: Function; 
  ...
}

How to give credentials in a batch script that copies files to a network location?

Try using the net use command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.

net use \\<network-location>\<some-share> password /USER:username

Don't leave a trailing \ at the end of the

What is the most efficient way to create a dictionary of two pandas Dataframe columns?

I found a faster way to solve the problem, at least on realistically large datasets using: df.set_index(KEY).to_dict()[VALUE]

Proof on 50,000 rows:

df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB'))
df['A'] = df['A'].apply(chr)

%timeit dict(zip(df.A,df.B))
%timeit pd.Series(df.A.values,index=df.B).to_dict()
%timeit df.set_index('A').to_dict()['B']

Output:

100 loops, best of 3: 7.04 ms per loop  # WouterOvermeire
100 loops, best of 3: 9.83 ms per loop  # Jeff
100 loops, best of 3: 4.28 ms per loop  # Kikohs (me)

Save PHP array to MySQL?

Uhh, I don't know why everyone suggests serializing the array.

I say, the best way is to actually fit it into your database schema. I have no idea (and you gave no clues) about the actual semantic meaning of the data in your array, but there are generally two ways of storing sequences like that

create table mydata (
  id int not null auto_increment primary key,
  field1 int not null,
  field2 int not null,
  ...
  fieldN int not null
)

This way you are storing your array in a single row.

create table mydata (
    id int not null auto_increment primary key,
    ...
)

create table myotherdata (
    id int not null auto_increment primary key,
    mydata_id int not null,
    sequence int not null,
    data int not null
)

The disadvantage of the first method is, obviously, that if you have many items in your array, working with that table will not be the most elegant thing. It is also impractical (possible, but quite inelegant as well - just make the columns nullable) to work with sequences of variable length.

For the second method, you can have sequences of any length, but of only one type. You can, of course, make that one type varchar or something and serialize the items of your array. Not the best thing to do, but certainly better, than serializing the whole array, right?

Either way, any of this methods gets a clear advantage of being able to access an arbitrary element of the sequence and you don't have to worry about serializing arrays and ugly things like that.

As for getting it back. Well, get the appropriate row/sequence of rows with a query and, well, use a loop.. right?

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

How to disable Google asking permission to regularly check installed apps on my phone?

It is also available in general settings

Settings -> Security -> Verify Apps

Just un-check it.

( I am running 4.2.2 but most probably it should be available in 4.0 and higher. Cant say about previous versions ... )

$_POST not working. "Notice: Undefined index: username..."

undefined index means that somewhere in the $_POST array, there isn't an index (key) for the key username.

You should be setting your posted values into variables for a more clean solution, and it's a good habit to get into.

If I was having a similar error, I'd do something like this:

$username = $_POST['username']; // you should really do some more logic to see if it's set first
echo $username;

If username didn't turn up, that'd mean I was screwing up somewhere. You can also,

var_dump($_POST);

To see what you're posting. var_dump is really useful as far as debugging. Check it out: var_dump

How can I specify working directory for popen

subprocess.Popen takes a cwd argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'), or use r'd:\test\local' so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t part will be translated to a tab.

So, your new line should look like:

subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')

To use your Python script path as cwd, import os and define cwd using this:

os.path.dirname(os.path.realpath(__file__)) 

Node.js/Express routing with get params

Your route isn't ok, it should be like this (with ':')

app.get('/documents/:format/:type', function (req, res) {
   var format = req.params.format,
       type = req.params.type;
});

Also you cannot interchange parameter order unfortunately. For more information on req.params (and req.query) check out the api reference here.

What is the Auto-Alignment Shortcut Key in Eclipse?

Ctrl+Shift+F to invoke the Auto Formatter

Ctrl+I to indent the selected part (or all) of you code.

How to install ADB driver for any android device?

If no other driver package worked for your obscure device go read how to make a truly universal abd and fastboot driver out of Google's USB driver. The trick is to use CompatibleID instead of HardwareID in the driver's INF Models section

HttpClient.GetAsync(...) never returns when using await/async

I was using to many await, so i was not getting response , i converted in to sync call its started working

            using (var client = new HttpClient())
            using (var request = new HttpRequestMessage())
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                request.Method = HttpMethod.Get;
                request.RequestUri = new Uri(URL);
                var response = client.GetAsync(URL).Result;
                response.EnsureSuccessStatusCode();
                string responseBody = response.Content.ReadAsStringAsync().Result;
               

What's the difference between import java.util.*; and import java.util.Date; ?

import java.util.*;

imports everything within java.util including the Date class.

import java.util.Date;

just imports the Date class.

Doing either of these could not make any difference.

Eclipse error "ADB server didn't ACK, failed to start daemon"

I've already up-voted another answer here to this question, but just in case anyone was wondering, you don't need to restart Eclipse to get ADB running again. Just open a shell and run the command:

adb start-server

If you haven't set the path to ADB in your system properties then you must first go to the directory in which ADB exists(in Android\android-sdk\platform-tools....I'm running Windows, I don't know how the mac people do things).

Can I get Unix's pthread.h to compile in Windows?

There are, as i recall, two distributions of the gnu toolchain for windows: mingw and cygwin.

I'd expect cygwin work - a lot of effort has been made to make that a "stadard" posix environment.

The mingw toolchain uses msvcrt.dll for its runtime and thus will probably expose msvcrt's "thread" api: _beginthread which is defined in <process.h>

How can I concatenate a string and a number in Python?

do it like this:

"abc%s" % 9
#or
"abc" + str(9)

How do I check if the mouse is over an element in jQuery?

I couldn't use any of the suggestions above.
Why I prefer my solution?
This method checks if mouse is over an element at any time chosen by You.
Mouseenter and :hover are cool, but mouseenter triggers only if you move the mouse, not when element moves under the mouse.
:hover is pretty sweet but ... IE

So I do this:

No 1. store mouse x, y position every time it's moved when you need to,
No 2. check if mouse is over any of elements that match the query do stuff ... like trigger a mouseenter event

// define mouse x, y variables so they are traced all the time
var mx = 0; //  mouse X position
var my = 0; //  mouse Y position

// update mouse x, y coordinates every time user moves the mouse
$(document).mousemove(function(e){
    mx = e.pageX;
    my = e.pageY;
});

// check is mouse is over an element at any time You need (wrap it in function if You need to)
$("#my_element").each(function(){
    boxX = $(this).offset().left;
    boxY = $(this).offset().top;
    boxW = $(this).innerWidth();
    boxH = $(this).innerHeight();
    if ((boxX <= mx) &&
        (boxX + 1000 >= mx) &&
        (boxY <= my) &&
        (boxY + boxH >= my))
    {
        // mouse is over it so you can for example trigger a mouseenter event
        $(this).trigger("mouseenter");
    }
});

ORA-01036: illegal variable name/number when running query through C#

The Oracle error ORA-01036 means that the query uses an undefined variable somewhere. From the query we can determine which variables are in use, namely all that start with @. However, if you're inputting this into an advanced query, it's important to confirm that all variables have a matching input parameter, including the same case as in the variable name, if your Oracle database is Case Sensitive.

Difference between OpenJDK and Adoptium/AdoptOpenJDK

Update: AdoptOpenJDK has changed its name to Adoptium, as part of its move to the Eclipse Foundation.


OpenJDK ? source code
Adoptium/AdoptOpenJDK ? builds

Difference between OpenJDK and AdoptOpenJDK

The first provides source-code, the other provides builds of that source-code.

Several vendors of Java & OpenJDK

Adoptium of the Eclipse Foundation, formerly known as AdoptOpenJDK, is only one of several vendors distributing implementations of the Java platform. These include:

  • Eclipse Foundation (Adoptium/AdoptOpenJDK)
  • Azul Systems
  • Oracle
  • Red Hat / IBM
  • BellSoft
  • SAP
  • Amazon AWS
  • … and more

See this flowchart of mine to help guide you in picking a vendor for an implementation of the Java platform. Click/tap to zoom.

Flowchart guiding you in choosing a vendor for a Java 11 implementation

Another resource: This comparison matrix by Azul Systems is useful, and seems true and fair to my mind.

Here is a list of considerations and motivations to consider in choosing a vendor and implementation.

Motivations in choosing a vendor for Java

Some vendors offer you a choice of JIT technologies.

Diagram showing history of HotSpot & JRockit merging, and OpenJ9 both available in AdoptOpenJDK

To understand more about this Java ecosystem, read Java Is Still Free

How do I inject a controller into another controller in AngularJS

If your intention is to get hold of already instantiated controller of another component and that if you are following component/directive based approach you can always require a controller (instance of a component) from a another component that follows a certain hierarchy.

For example:

//some container component that provides a wizard and transcludes the page components displayed in a wizard
myModule.component('wizardContainer', {
  ...,
  controller : function WizardController() {
    this.disableNext = function() { 
      //disable next step... some implementation to disable the next button hosted by the wizard
    }
  },
  ...
});

//some child component
myModule.component('onboardingStep', {
 ...,
 controller : function OnboadingStepController(){

    this.$onInit = function() {
      //.... you can access this.container.disableNext() function
    }

    this.onChange = function(val) {
      //..say some value has been changed and it is not valid i do not want wizard to enable next button so i call container's disable method i.e
      if(notIsValid(val)){
        this.container.disableNext();
      }
    }
 },
 ...,
 require : {
    container: '^^wizardContainer' //Require a wizard component's controller which exist in its parent hierarchy.
 },
 ...
});

Now the usage of these above components might be something like this:

<wizard-container ....>
<!--some stuff-->
...
<!-- some where there is this page that displays initial step via child component -->

<on-boarding-step ...>
 <!--- some stuff-->
</on-boarding-step>
...
<!--some stuff-->
</wizard-container>

There are many ways you can set up require.

(no prefix) - Locate the required controller on the current element. Throw an error if not found.

? - Attempt to locate the required controller or pass null to the link fn if not found.

^ - Locate the required controller by searching the element and its parents. Throw an error if not found.

^^ - Locate the required controller by searching the element's parents. Throw an error if not found.

?^ - Attempt to locate the required controller by searching the element and its parents or pass null to the link fn if not found.

?^^ - Attempt to locate the required controller by searching the element's parents, or pass null to the link fn if not found.



Old Answer:

You need to inject $controller service to instantiate a controller inside another controller. But be aware that this might lead to some design issues. You could always create reusable services that follows Single Responsibility and inject them in the controllers as you need.

Example:

app.controller('TestCtrl2', ['$scope', '$controller', function ($scope, $controller) {
   var testCtrl1ViewModel = $scope.$new(); //You need to supply a scope while instantiating.
   //Provide the scope, you can also do $scope.$new(true) in order to create an isolated scope.
   //In this case it is the child scope of this scope.
   $controller('TestCtrl1',{$scope : testCtrl1ViewModel });
   testCtrl1ViewModel.myMethod(); //And call the method on the newScope.
}]);

In any case you cannot call TestCtrl1.myMethod() because you have attached the method on the $scope and not on the controller instance.

If you are sharing the controller, then it would always be better to do:-

.controller('TestCtrl1', ['$log', function ($log) {
    this.myMethod = function () {
        $log.debug("TestCtrl1 - myMethod");
    }
}]);

and while consuming do:

.controller('TestCtrl2', ['$scope', '$controller', function ($scope, $controller) {
     var testCtrl1ViewModel = $controller('TestCtrl1');
     testCtrl1ViewModel.myMethod();
}]);

In the first case really the $scope is your view model, and in the second case it the controller instance itself.

How to change scroll bar position with CSS?

Here is another way, by rotating element with the scrollbar for 180deg, wrapping it's content into another element, and rotating that wrapper for -180deg. Check the snippet below

_x000D_
_x000D_
div {_x000D_
  display: inline-block;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  border: 2px solid black;_x000D_
  margin: 15px;_x000D_
}_x000D_
#vertical {_x000D_
  direction: rtl;_x000D_
  overflow-y: scroll;_x000D_
  overflow-x: hidden;_x000D_
  background: gold;_x000D_
}_x000D_
#vertical p {_x000D_
  direction: ltr;_x000D_
  margin-bottom: 0;_x000D_
}_x000D_
#horizontal {_x000D_
  direction: rtl;_x000D_
  transform: rotate(180deg);_x000D_
  overflow-y: hidden;_x000D_
  overflow-x: scroll;_x000D_
  background: tomato;_x000D_
  padding-top: 30px;_x000D_
}_x000D_
#horizontal span {_x000D_
  direction: ltr;_x000D_
  display: inline-block;_x000D_
  transform: rotate(-180deg);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id=vertical>_x000D_
  <p>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content</p>_x000D_
</div>_x000D_
<div id=horizontal><span> content_content_content_content_content_content_content_content_content_content_content_content_content_content</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

System.drawing namespace not found under console application

You need to add a reference to System.Drawing.dll.

As mentioned in the comments below this can be done as follows: In your Solution Explorer (Where all the files are shown with your project), right click the "References" folder and find System.Drawing on the .NET Tab.

enter image description here

enter image description here

What is the command for cut copy paste a file from one directory to other directory

E:>move "blogger code.txt" d:/"blogger code.txt"

    1 file(s) moved.

"blogger code.txt" is a file name

The file move from E: drive to D: drive

Batch File: ( was unexpected at this time

You are getting that error because when the param1 if statements are evaluated, param is always null due to being scoped variables without delayed expansion.

When parentheses are used, all the commands and variables within those parentheses are expanded. And at that time, param1 has no value making the if statements invalid. When using delayed expansion, the variables are only expanded when the command is actually called.

Also I recommend using if not defined command to determine if a variable is set.

@echo off
setlocal EnableExtensions EnableDelayedExpansion
cls
title ~USB Wizard~
echo What do you want to do?
echo 1.Enable/Disable USB Storage Devices.
echo 2.Enable/Disable Writing Data onto USB Storage.
echo 3.~Yet to come~.

set "a=%globalparam1%"
goto :aCheck
:aPrompt
set /p "a=Enter Choice: "
:aCheck
if not defined a goto :aPrompt
echo %a%

IF "%a%"=="2" (
    title USB WRITE LOCK
    echo What do you want to do?
    echo 1.Apply USB Write Protection
    echo 2.Remove USB Write Protection

    ::param1
    set "param1=%globalparam2%"
    goto :param1Check
    :param1Prompt
    set /p "param1=Enter Choice: "
    :param1Check
    if not defined param1 goto :param1Prompt
    echo !param1!

    if "!param1!"=="1" (
        REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000001 
        echo USB Write is Locked!
    )
    if "!param1!"=="2" (
        REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000000
        echo USB Write is Unlocked! 
    )
)
pause
endlocal

How to get image height and width using java?

Simple way:

BufferedImage readImage = null;

try {
    readImage = ImageIO.read(new File(your path);
    int h = readImage.getHeight();
    int w = readImage.getWidth();
} catch (Exception e) {
    readImage = null;
}

nginx- duplicate default server error

OS Debian 10 + nginx. In my case, i unlinked the "default" page as:

  1. cd/etc/nginx/sites-enabled
  2. unlink default
  3. service nginx restart

How to sort pandas data frame using values from several columns?

The dataframe.sort() method is - so my understanding - deprecated in pandas > 0.18. In order to solve your problem you should use dataframe.sort_values() instead:

f.sort_values(by=["c1","c2"], ascending=[False, True])

The output looks like this:

    c1  c2
    3   10
    2   15
    2   30
    2   100
    1   20

How can I revert multiple Git commits (already pushed) to a published repository?

git revert HEAD -m 1

In the above code line. "Last argument represents"

  • 1 - reverts one commits. 2 - reverts last commits. n - reverts last n commits

or

git reset --hard siriwjdd

How to force Selenium WebDriver to click on element which is not currently visible?

Selenium determines an element is visible or not by the following criteria (use a DOM inspector to determine what css applies to your element, make sure you look at computed style):

  • visibility != hidden
  • display != none (is also checked against every parent element)
  • opacity != 0 (this is not checked for clicking an element)
  • height and width are both > 0
  • for an input, the attribute type != hidden

Your element is matching one of those criteria. If you do not have the ability to change the styling of the element, here is how you can forcefully do it with javascript (going to assume WebDriver since you said Selenium2 API):

((JavascriptExecutor)driver).executeScript("arguments[0].checked = true;", inputElement);

But that won't fire a javascript event, if you depend on the change event for that input you'll have to fire it too (many ways to do that, easiest to use whatever javascript library is loaded on that page).

The source for the visibility check -

https://github.com/SeleniumHQ/selenium/blob/master/javascript/atoms/dom.js#L577

The WebDriver spec that defines this -

https://dvcs.w3.org/hg/webdriver/raw-file/tip/webdriver-spec.html#widl-WebElement-isDisplayed-boolean

HttpClient - A task was cancelled?

In my situation, the controller method was not made as async and the method called inside the controller method was async.

So I guess its important to use async/await all the way to top level to avoid issues like these.

How to append a newline to StringBuilder

Escape should be done with \, not /.

So r.append('\n'); or r.append("\n"); will work (StringBuilder has overloaded methods for char and String type).

Python: Random numbers into a list

Here I use the sample method to generate 10 random numbers between 0 and 100.

Note: I'm using Python 3's range function (not xrange).

import random

print(random.sample(range(0, 100), 10))

The output is placed into a list:

[11, 72, 64, 65, 16, 94, 29, 79, 76, 27]

Java: parse int value from a char

String element = "el5";
int x = element.charAt(2) - 48;

Subtracting ascii value of '0' = 48 from char

Android Pop-up message

If you want a Popup that closes automatically, you should look for Toasts. But if you want a dialog that the user has to close first before proceeding, you should look for a Dialog.

For both approaches it is possible to read a text file with the text you want to display. But you could also hardcode the text or use R.String to set the text.

Regular expression for extracting tag attributes

Token Mantra response: you should not tweak/modify/harvest/or otherwise produce html/xml using regular expression.

there are too may corner case conditionals such as \' and \" which must be accounted for. You are much better off using a proper DOM Parser, XML Parser, or one of the many other dozens of tried and tested tools for this job instead of inventing your own.

I don't really care which one you use, as long as its recognized, tested, and you use one.

my $foo  = Someclass->parse( $xmlstring ); 
my @links = $foo->getChildrenByTagName("a"); 
my @srcs = map { $_->getAttribute("src") } @links; 
# @srcs now contains an array of src attributes extracted from the page. 

How to convert Calendar to java.sql.Date in Java?

stmt.setDate(1, new java.sql.Date(cal.getTime().getTime()));

Fill remaining vertical space - only CSS

Flexbox solution

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  width: 300px;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.first {_x000D_
  height: 50px;_x000D_
}_x000D_
_x000D_
.second {_x000D_
  flex-grow: 1;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="first" style="background:#b2efd8">First</div>_x000D_
  <div class="second" style="background:#80c7cd">Second</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Creating a Facebook share button with customized url, title and image

Unfortunately, it appears that we can't post shares for individual topics or articles within a page. It appears Facebook just wants us to share entire pages (based on url only).

There's also their new share dialog, but even though they claim it can do all of what the old sharer.php could do, that doesn't appear to be true.

And here's Facebooks 'best practices' for sharing.

Redis strings vs Redis hashes to represent JSON: efficiency?

This article can provide a lot of insight here: http://redis.io/topics/memory-optimization

There are many ways to store an array of Objects in Redis (spoiler: I like option 1 for most use cases):

  1. Store the entire object as JSON-encoded string in a single key and keep track of all Objects using a set (or list, if more appropriate). For example:

    INCR id:users
    SET user:{id} '{"name":"Fred","age":25}'
    SADD users {id}
    

    Generally speaking, this is probably the best method in most cases. If there are a lot of fields in the Object, your Objects are not nested with other Objects, and you tend to only access a small subset of fields at a time, it might be better to go with option 2.

    Advantages: considered a "good practice." Each Object is a full-blown Redis key. JSON parsing is fast, especially when you need to access many fields for this Object at once. Disadvantages: slower when you only need to access a single field.

  2. Store each Object's properties in a Redis hash.

    INCR id:users
    HMSET user:{id} name "Fred" age 25
    SADD users {id}
    

    Advantages: considered a "good practice." Each Object is a full-blown Redis key. No need to parse JSON strings. Disadvantages: possibly slower when you need to access all/most of the fields in an Object. Also, nested Objects (Objects within Objects) cannot be easily stored.

  3. Store each Object as a JSON string in a Redis hash.

    INCR id:users
    HMSET users {id} '{"name":"Fred","age":25}'
    

    This allows you to consolidate a bit and only use two keys instead of lots of keys. The obvious disadvantage is that you can't set the TTL (and other stuff) on each user Object, since it is merely a field in the Redis hash and not a full-blown Redis key.

    Advantages: JSON parsing is fast, especially when you need to access many fields for this Object at once. Less "polluting" of the main key namespace. Disadvantages: About same memory usage as #1 when you have a lot of Objects. Slower than #2 when you only need to access a single field. Probably not considered a "good practice."

  4. Store each property of each Object in a dedicated key.

    INCR id:users
    SET user:{id}:name "Fred"
    SET user:{id}:age 25
    SADD users {id}
    

    According to the article above, this option is almost never preferred (unless the property of the Object needs to have specific TTL or something).

    Advantages: Object properties are full-blown Redis keys, which might not be overkill for your app. Disadvantages: slow, uses more memory, and not considered "best practice." Lots of polluting of the main key namespace.

Overall Summary

Option 4 is generally not preferred. Options 1 and 2 are very similar, and they are both pretty common. I prefer option 1 (generally speaking) because it allows you to store more complicated Objects (with multiple layers of nesting, etc.) Option 3 is used when you really care about not polluting the main key namespace (i.e. you don't want there to be a lot of keys in your database and you don't care about things like TTL, key sharding, or whatever).

If I got something wrong here, please consider leaving a comment and allowing me to revise the answer before downvoting. Thanks! :)

Adding Table rows Dynamically in Android

You shouldn't be using an item defined in the Layout XML in order to create more instances of it. You should either create it in a separate XML and inflate it or create the TableRow programmaticaly. If creating them programmaticaly, should be something like this:

    public void init(){
    TableLayout ll = (TableLayout) findViewById(R.id.displayLinear);


    for (int i = 0; i <2; i++) {

        TableRow row= new TableRow(this);
        TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
        row.setLayoutParams(lp);
        checkBox = new CheckBox(this);
        tv = new TextView(this);
        addBtn = new ImageButton(this);
        addBtn.setImageResource(R.drawable.add);
        minusBtn = new ImageButton(this);
        minusBtn.setImageResource(R.drawable.minus);
        qty = new TextView(this);
        checkBox.setText("hello");
        qty.setText("10");
        row.addView(checkBox);
        row.addView(minusBtn);
        row.addView(qty);
        row.addView(addBtn);
        ll.addView(row,i);
    }
}

Redirect on Ajax Jquery Call

For ExpressJs router:

router.post('/login', async(req, res) => {
    return res.send({redirect: '/yoururl'});
})

Client-side:

    success: function (response) {
        if (response.redirect) {
            window.location = response.redirect
        }
    },

The opposite of Intersect()

/// <summary>
/// Given two list, compare and extract differences
/// http://stackoverflow.com/questions/5620266/the-opposite-of-intersect
/// </summary>
public class CompareList
{
    /// <summary>
    /// Returns list of items that are in initial but not in final list.
    /// </summary>
    /// <param name="listA"></param>
    /// <param name="listB"></param>
    /// <returns></returns>
    public static IEnumerable<string> NonIntersect(
        List<string> initial, List<string> final)
    {
        //subtracts the content of initial from final
        //assumes that final.length < initial.length
        return initial.Except(final);
    }

    /// <summary>
    /// Returns the symmetric difference between the two list.
    /// http://en.wikipedia.org/wiki/Symmetric_difference
    /// </summary>
    /// <param name="initial"></param>
    /// <param name="final"></param>
    /// <returns></returns>
    public static IEnumerable<string> SymmetricDifference(
        List<string> initial, List<string> final)
    {
        IEnumerable<string> setA = NonIntersect(final, initial);
        IEnumerable<string> setB = NonIntersect(initial, final);
        // sum and return the two set.
        return setA.Concat(setB);
    }
}

How to prevent Google Colab from disconnecting?

Well this is working for me -

run the following code in the console and it will prevent you from disconnecting. Ctrl+ Shift + i to open inspector view . Then go to console.

function ClickConnect(){
    console.log("Working"); 
    document.querySelector("colab-toolbar-button#connect").click() 
}
setInterval(ClickConnect,60000)

How to prevent google colab from disconnecting

Javascript/DOM: How to remove all events of a DOM object?

angular has a polyfill for this issue, you can check. I did not understand much but maybe it can help.

const REMOVE_ALL_LISTENERS_EVENT_LISTENER = 'removeAllListeners';

    proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER] = function () {
        const target = this || _global;
        const eventName = arguments[0];
        if (!eventName) {
            const keys = Object.keys(target);
            for (let i = 0; i < keys.length; i++) {
                const prop = keys[i];
                const match = EVENT_NAME_SYMBOL_REGX.exec(prop);
                let evtName = match && match[1];
                // in nodejs EventEmitter, removeListener event is
                // used for monitoring the removeListener call,
                // so just keep removeListener eventListener until
                // all other eventListeners are removed
                if (evtName && evtName !== 'removeListener') {
                    this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, evtName);
                }
            }
            // remove removeListener listener finally
            this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, 'removeListener');
        }
        else {
            const symbolEventNames = zoneSymbolEventNames$1[eventName];
            if (symbolEventNames) {
                const symbolEventName = symbolEventNames[FALSE_STR];
                const symbolCaptureEventName = symbolEventNames[TRUE_STR];
                const tasks = target[symbolEventName];
                const captureTasks = target[symbolCaptureEventName];
                if (tasks) {
                    const removeTasks = tasks.slice();
                    for (let i = 0; i < removeTasks.length; i++) {
                        const task = removeTasks[i];
                        let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
                        this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
                    }
                }
                if (captureTasks) {
                    const removeTasks = captureTasks.slice();
                    for (let i = 0; i < removeTasks.length; i++) {
                        const task = removeTasks[i];
                        let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
                        this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
                    }
                }
            }
        }
        if (returnTarget) {
            return this;
        }
    };

....

Android Respond To URL in Intent

You might need to allow different combinations of data in your intent filter to get it to work in different cases (http/ vs https/, www. vs no www., etc).

For example, I had to do the following for an app which would open when the user opened a link to Google Drive forms (www.docs.google.com/forms)

Note that path prefix is optional.

        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data android:scheme="http" />
            <data android:scheme="https" />

            <data android:host="www.docs.google.com" />
            <data android:host="docs.google.com" />

            <data android:pathPrefix="/forms" />
        </intent-filter>

How do I add a resources folder to my Java project in Eclipse

If aim is to create a resources folder parallel to src/main/java, then do the following:

Right Click on your project > New > Source Folder
Provide Folder Name as src/main/resources
Finish

How to calculate a logistic sigmoid function in Python?

It is also available in scipy: http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.logistic.html

In [1]: from scipy.stats import logistic

In [2]: logistic.cdf(0.458)
Out[2]: 0.61253961344091512

which is only a costly wrapper (because it allows you to scale and translate the logistic function) of another scipy function:

In [3]: from scipy.special import expit

In [4]: expit(0.458)
Out[4]: 0.61253961344091512

If you are concerned about performances continue reading, otherwise just use expit.

Some benchmarking:

In [5]: def sigmoid(x):
  ....:     return 1 / (1 + math.exp(-x))
  ....: 

In [6]: %timeit -r 1 sigmoid(0.458)
1000000 loops, best of 1: 371 ns per loop


In [7]: %timeit -r 1 logistic.cdf(0.458)
10000 loops, best of 1: 72.2 µs per loop

In [8]: %timeit -r 1 expit(0.458)
100000 loops, best of 1: 2.98 µs per loop

As expected logistic.cdf is (much) slower than expit. expit is still slower than the python sigmoid function when called with a single value because it is a universal function written in C ( http://docs.scipy.org/doc/numpy/reference/ufuncs.html ) and thus has a call overhead. This overhead is bigger than the computation speedup of expit given by its compiled nature when called with a single value. But it becomes negligible when it comes to big arrays:

In [9]: import numpy as np

In [10]: x = np.random.random(1000000)

In [11]: def sigmoid_array(x):                                        
   ....:    return 1 / (1 + np.exp(-x))
   ....: 

(You'll notice the tiny change from math.exp to np.exp (the first one does not support arrays, but is much faster if you have only one value to compute))

In [12]: %timeit -r 1 -n 100 sigmoid_array(x)
100 loops, best of 1: 34.3 ms per loop

In [13]: %timeit -r 1 -n 100 expit(x)
100 loops, best of 1: 31 ms per loop

But when you really need performance, a common practice is to have a precomputed table of the the sigmoid function that hold in RAM, and trade some precision and memory for some speed (for example: http://radimrehurek.com/2013/09/word2vec-in-python-part-two-optimizing/ )

Also, note that expit implementation is numerically stable since version 0.14.0: https://github.com/scipy/scipy/issues/3385

Converting Swagger specification JSON to HTML documentation

I spent a lot of time and tried a lot of different solutions - in the end I did it this way :

<html>
    <head>    
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/swagger-ui.css">
        <script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script>
        <script>

            function render() {
                var ui = SwaggerUIBundle({
                    url:  `path/to/my/swagger.yaml`,
                    dom_id: '#swagger-ui',
                    presets: [
                        SwaggerUIBundle.presets.apis,
                        SwaggerUIBundle.SwaggerUIStandalonePreset
                    ]
                });
            }

        </script>
    </head>

    <body onload="render()">
        <div id="swagger-ui"></div>
    </body>
</html>

You just need to have path/to/my/swagger.yaml served from the same location.
(or use CORS headers)

Tool to generate JSON schema from JSON data

Seeing that this question is getting quite some upvotes, I add new information (I am not sure if this is new, but I couldn't find it at the time)

Use dynamic variable names in `dplyr`

After a lot of trial and error, I found the pattern UQ(rlang::sym("some string here"))) really useful for working with strings and dplyr verbs. It seems to work in a lot of surprising situations.

Here's an example with mutate. We want to create a function that adds together two columns, where you pass the function both column names as strings. We can use this pattern, together with the assignment operator :=, to do this.

## Take column `name1`, add it to column `name2`, and call the result `new_name`
mutate_values <- function(new_name, name1, name2){
  mtcars %>% 
    mutate(UQ(rlang::sym(new_name)) :=  UQ(rlang::sym(name1)) +  UQ(rlang::sym(name2)))
}
mutate_values('test', 'mpg', 'cyl')

The pattern works with other dplyr functions as well. Here's filter:

## filter a column by a value 
filter_values <- function(name, value){
  mtcars %>% 
    filter(UQ(rlang::sym(name)) != value)
}
filter_values('gear', 4)

Or arrange:

## transform a variable and then sort by it 
arrange_values <- function(name, transform){
  mtcars %>% 
    arrange(UQ(rlang::sym(name)) %>%  UQ(rlang::sym(transform)))
}
arrange_values('mpg', 'sin')

For select, you don't need to use the pattern. Instead you can use !!:

## select a column 
select_name <- function(name){
  mtcars %>% 
    select(!!name)
}
select_name('mpg')

laravel compact() and ->with()

Route::get('/', function () {
    return view('greeting', ['name' => 'James']);
});
<html>
    <body>
        <h1>Hello, {{ $name }}</h1>
    </body>
</html>

or

public function index($id)
{
    $category = Category::find($id);
    $topics = $category->getTopicPaginator();
    $message = Message::find(1);

    // here I would just use "->with([$category, $topics, $message])"
    return View::make('category.index')->with(compact('category', 'topics', 'message'));
}

Count character occurrences in a string in C++

I would have done this way :

#include <iostream>
#include <string>
using namespace std;
int main()
{

int count = 0;
string s("Hello_world");

for (int i = 0; i < s.size(); i++) 
    {
       if (s.at(i) == '_')    
           count++;
    }
cout << endl << count;
cin.ignore();
return 0;
}

Styling the last td in a table with css

You can use the :last-of-type to catch last column of your table.

<style>
.table > tbody > tr > td:last-of-type {
    /* Give your style Here; */
}
</style>

MySQL JOIN the most recent row only?

I know this question is old, but it's got a lot of attention over the years and I think it's missing a concept which may help someone in a similar case. I'm adding it here for completeness sake.

If you cannot modify your original database schema, then a lot of good answers have been provided and solve the problem just fine.

If you can, however, modify your schema, I would advise to add a field in your customer table that holds the id of the latest customer_data record for this customer:

CREATE TABLE customer (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  current_data_id INT UNSIGNED NULL DEFAULT NULL
);

CREATE TABLE customer_data (
   id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
   customer_id INT UNSIGNED NOT NULL, 
   title VARCHAR(10) NOT NULL,
   forename VARCHAR(10) NOT NULL,
   surname VARCHAR(10) NOT NULL
);

Querying customers

Querying is as easy and fast as it can be:

SELECT c.*, d.title, d.forename, d.surname
FROM customer c
INNER JOIN customer_data d on d.id = c.current_data_id
WHERE ...;

The drawback is the extra complexity when creating or updating a customer.

Updating a customer

Whenever you want to update a customer, you insert a new record in the customer_data table, and update the customer record.

INSERT INTO customer_data (customer_id, title, forename, surname) VALUES(2, 'Mr', 'John', 'Smith');
UPDATE customer SET current_data_id = LAST_INSERT_ID() WHERE id = 2;

Creating a customer

Creating a customer is just a matter of inserting the customer entry, then running the same statements:

INSERT INTO customer () VALUES ();

SET @customer_id = LAST_INSERT_ID();
INSERT INTO customer_data (customer_id, title, forename, surname) VALUES(@customer_id, 'Mr', 'John', 'Smith');
UPDATE customer SET current_data_id = LAST_INSERT_ID() WHERE id = @customer_id;

Wrapping up

The extra complexity for creating/updating a customer might be fearsome, but it can easily be automated with triggers.

Finally, if you're using an ORM, this can be really easy to manage. The ORM can take care of inserting the values, updating the ids, and joining the two tables automatically for you.

Here is how your mutable Customer model would look like:

class Customer
{
    private int id;
    private CustomerData currentData;

    public Customer(String title, String forename, String surname)
    {
        this.update(title, forename, surname);
    }

    public void update(String title, String forename, String surname)
    {
        this.currentData = new CustomerData(this, title, forename, surname);
    }

    public String getTitle()
    {
        return this.currentData.getTitle();
    }

    public String getForename()
    {
        return this.currentData.getForename();
    }

    public String getSurname()
    {
        return this.currentData.getSurname();
    }
}

And your immutable CustomerData model, that contains only getters:

class CustomerData
{
    private int id;
    private Customer customer;
    private String title;
    private String forename;
    private String surname;

    public CustomerData(Customer customer, String title, String forename, String surname)
    {
        this.customer = customer;
        this.title    = title;
        this.forename = forename;
        this.surname  = surname;
    }

    public String getTitle()
    {
        return this.title;
    }

    public String getForename()
    {
        return this.forename;
    }

    public String getSurname()
    {
        return this.surname;
    }
}

No space left on device

You can execute the following commands

lsof / |grep deleted

kill the process id's, which free up the disk space.

Send email with PHP from html form on submit with the same script

You need a SMPT Server in order for

... mail($to,$subject,$message,$headers);

to work.

You could try light weight SMTP servers like xmailer

How to search in array of object in mongodb

as explained in above answers Also, to return only one field from the entire array you can use projection into find. and use $

db.getCollection("sizer").find(
  { awards: { $elemMatch: { award: "National Medal", year: 1975 } } },
  { "awards.$": 1, name: 1 }
);

will be reutrn

{
    _id: 1,
    name: {
        first: 'John',
        last: 'Backus'
    },
    awards: [
        {
            award: 'National Medal',
            year: 1975,
            by: 'NSF'
        }
    ]
}

Is there a way to access an iteration-counter in Java's for-each loop?

Though there are soo many other ways mentioned to achieve the same, I will share my way for some unsatisfied users. I am using the Java 8 IntStream feature.

1. Arrays

Object[] obj = {1,2,3,4,5,6,7};
IntStream.range(0, obj.length).forEach(index-> {
    System.out.println("index: " + index);
    System.out.println("value: " + obj[index]);
});

2. List

List<String> strings = new ArrayList<String>();
Collections.addAll(strings,"A","B","C","D");

IntStream.range(0, strings.size()).forEach(index-> {
    System.out.println("index: " + index);
    System.out.println("value: " + strings.get(index));
});

javascript variable reference/alias

To some degree this is possible, you can create an alias to a variable using closures:

Function.prototype.toString = function() {
    return this();
}

var x = 1;
var y = function() { return x }
x++;
alert(y); // prints 2, no need for () because of toString redefinition 

Javascript Error Null is not an Object

I agree with alex about making sure the DOM is loaded. I also think that the submit button will trigger a refresh.

This is what I would do

<html>
<head>
<title>webpage</title>
</head>
<script type="text/javascript">
var myButton;
var myTextfield;

function setup() {
  myButton = document.getElementById("myButton");
  myTextfield = document.getElementById("myTextfield");
  myButton.onclick = function() {
    var userName = myTextfield.value;
    greetUser(userName);
    return false;
  }
}

function greetUser(userName) {
  var greeting = "Hello " + userName + "!";
  document.getElementsByTagName("h2")[0].innerHTML = greeting;
}

</script>
<body onload="setup()">
  <h2>Hello World!</h2>
  <p id="myParagraph">This is an example website</p>

  <form>
    <input type="text" id="myTextfield" placeholder="Type your name" />
    <input type="button" id="myButton" value="Go" />
  </form>
  </body>
</html>

have fun!

Joining two table entities in Spring Data JPA

@Query("SELECT rd FROM ReleaseDateType rd, CacheMedia cm WHERE ...")

Can someone post a well formed crossdomain.xml sample?

A version of crossdomain.xml used to be packaged with the HTML5 Boilerplate which is the product of many years of iterative development and combined community knowledge. However, it has since been deleted from the repository. I've copied it verbatim here, and included a link to the commit where it was deleted below.

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
  <!-- Read this: https://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html -->

  <!-- Most restrictive policy: -->
  <site-control permitted-cross-domain-policies="none"/>

  <!-- Least restrictive policy: -->
  <!--
  <site-control permitted-cross-domain-policies="all"/>
  <allow-access-from domain="*" to-ports="*" secure="false"/>
  <allow-http-request-headers-from domain="*" headers="*" secure="false"/>
  -->
</cross-domain-policy>

Deleted in #1881
https://github.com/h5bp/html5-boilerplate/commit/58a2ba81d250301e7b5e3da28ae4c1b42d91b2c2

set option "selected" attribute from dynamic created option

Instead of modifying the HTML itself, you should just set the value you want from the relative option element:

$(function() {
    $("#country").val("ID");
});

In this case "ID" is the value of the option "Indonesia"

How do I find duplicate values in a table in Oracle?

SELECT   SocialSecurity_Number, Count(*) no_of_rows
FROM     SocialSecurity 
GROUP BY SocialSecurity_Number
HAVING   Count(*) > 1
Order by Count(*) desc 

Adding a new array element to a JSON object

First we need to parse the JSON object and then we can add an item.

var str = '{"theTeam":[{"teamId":"1","status":"pending"},
{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';

var obj = JSON.parse(str);
obj['theTeam'].push({"teamId":"4","status":"pending"});
str = JSON.stringify(obj);

Finally we JSON.stringify the obj back to JSON

How to change text and background color?

You can use the function system.

system("color *background**foreground*");

For background and foreground, type in a number from 0 - 9 or a letter from A - F.

For example:

system("color A1");
std::cout<<"hi"<<std::endl;

That would display the letters "hi" with a green background and blue text.

To see all the color choices, just type in:

system("color %");

to see what number or letter represents what color.

Break string into list of characters in Python

I'm a bit late it seems to be, but...

a='hello'
print list(a)
# ['h','e','l','l', 'o']

Make an Android button change background on click through XML

Try:

public void onclick(View v){
            ImageView activity= (ImageView) findViewById(R.id.imageview1);
        button1.setImageResource(R.drawable.buttonpressed);}

.htaccess redirect www to non-www with SSL/HTTPS

Your condition will never be true, because its like "if (a == a + b)".

I'd try the following:

RewriteCond %{HTTP_HOST} ^www\.(.*)
RewriteRule ^.*$ https://%1/$1 [R=301,L]

This will capture "google.com" from "www.google.com" into %1, the rest in $1 and after that combining the 2, when HTTP_HOST starts with www (with or without https).

java.lang.UnsupportedClassVersionError Unsupported major.minor version 51.0

I encountered the same issue, when jdk 1.7 was used to compile then jre 1.4 was used for execution.

My solution was to set environment variable PATH by adding pathname C:\glassfish3\jdk7\bin in front of the existing PATH setting. The updated value is "C:\glassfish3\jdk7\bin;C:\Sun\SDK\bin". After the update, the problem was gone.

RegEx match open tags except XHTML self-contained tags

I used a open source tool called HTMLParser before. It's designed to parse HTML in various ways and serves the purpose quite well. It can parse HTML as different treenode and you can easily use its API to get attributes out of the node. Check it out and see if this can help you.

How to include scripts located inside the node_modules folder?

To use multiple files from node_modules in html, the best way I've found is to put them to an array and then loop on them to make them visible for web clients, for example to use filepond modules from node_modules:

const filePondModules = ['filepond-plugin-file-encode', 'filepond-plugin-image-preview', 'filepond-plugin-image-resize', 'filepond']
filePondModules.forEach(currentModule => {
    let module_dir = require.resolve(currentModule)
                           .match(/.*\/node_modules\/[^/]+\//)[0];
    app.use('/' + currentModule, express.static(module_dir + 'dist/'));
})

And then in the html (or layout) file, just call them like this :

    <link rel="stylesheet" href="/filepond/filepond.css">
    <link rel="stylesheet" href="/filepond-plugin-image-preview/filepond-plugin-image-preview.css">
...
    <script src="/filepond-plugin-image-preview/filepond-plugin-image-preview.js" ></script>
    <script src="/filepond-plugin-file-encode/filepond-plugin-file-encode.js"></script>
    <script src="/filepond-plugin-image-resize/filepond-plugin-image-resize.js"></script>
    <script src="/filepond/filepond.js"></script>

How do I set the background color of my main screen in Flutter?

you should return Scaffold widget and add your widget inside Scaffold

suck as this code :

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return Scaffold(
          backgroundColor: Colors.white,
          body: Center(child: new Text("Hello, World!"));
    );
  }
}

How do I access refs of a child component in the parent component

First of all, I want to say a big screw you to React for designing an interface that doesn't let us access 'ref' on the instantiated child components, in whatever context, without having to use the 'forwardRef' "hack" (which technically only works on specific/single instances, and not dynamic collections). Thanks for making our lives harder with your proprietary hook crap and now forcing us to use functional components (which can't inherit base functionality without more hacks). Why did JavaScript add class support to begin with? Right...

With that said, here is how I solve the problem for dynamic components:

On the parent, dynamically create references to the child components, for example:

class Form extends Component {
    fieldRefs: [];

    componentWillMount = () => {
        this.fieldRefs = [];
        for(let f of this.props.children) {
            if (f && f.type.name == 'FormField') {
                f.ref = createRef();
                this.fieldRefs.push(f);
            }
        }
    }

    public getFields = () => {
        let data = {};

        for(let r of this.fieldRefs) {
            let f = r.ref.current;
            data[f.props.id] = f.field.current.value;
        }

        return data;
    }
}

The Child component (ie <FormField />) implements it's own 'field' ref, to be referred to from the parent:

class FormField extends Component {
    field = createRef();
    
    render() {
        return(
            <input ref={this.field} type={type} />
        );
    }
}

Then in your main page, "Parent Parent" component, you can get the field values from the reference with:

class Page extends Component {
    form = createRef();

    onSubmit = () => {
        let fields = this.form.current.getFields();
    }

    render() {
        return (
            <Form ref={this.form}>
                <FormField id="email" type="email" autoComplete="email" label="E-mail" />
                <FormField id="password" type="password" autoComplete="password" label="Password" />

                <div class="button" onClick={this.onSubmit}>Submit</div>
            </Form>
        );
    }
}

I implemented this because I wanted to encapsulate all generic form functionality from a main <Form /> component, and the only way to be able to have the main client/page component set and style its own inner components was to use child components (ie. <FormField /> items within the parent <Form />, which is inside some other <Page /> component).

So, while some might consider this a hack, it's just as hackey as React's attempts to block the actual 'ref' from any parent, which I think is a ridiculous design, however they want to rationalize it.

Also wtf SO. It's 2021 and we still don't have get proper code-editing tools in your editor. Ffs.

error: RPC failed; curl transfer closed with outstanding read data remaining

These steps are working for me:

cd [dir]
git init
git clone [your Repository Url]

I hope that works for you too.

Warning:No JDK specified for module 'Myproject'.when run my project in Android studio

Restart intelliJ and import project as maven if it is a maven project

How to set cellpadding and cellspacing in table with CSS?

The padding inside a table-divider (TD) is a padding property applied to the cell itself.

CSS

td, th {padding:0}

The spacing in-between the table-dividers is a space between cell borders of the TABLE. To make it effective, you have to specify if your table cells borders will 'collapse' or be 'separated'.

CSS

table, td, th {border-collapse:separate}
table {border-spacing:6px}

Try this : https://www.google.ca/search?num=100&newwindow=1&q=css+table+cellspacing+cellpadding+site%3Astackoverflow.com ( 27 100 results )

Java recursive Fibonacci sequence

Michael Goodrich et al provide a really clever algorithm in Data Structures and Algorithms in Java, for solving fibonacci recursively in linear time by returning an array of [fib(n), fib(n-1)].

public static long[] fibGood(int n) {
    if (n < = 1) {
        long[] answer = {n,0};
        return answer;
    } else {
        long[] tmp = fibGood(n-1);
        long[] answer = {tmp[0] + tmp[1], tmp[0]};
        return answer;
    }
}

This yields fib(n) = fibGood(n)[0].

How to determine whether code is running in DEBUG / RELEASE build?

Just one more idea to detect:

DebugMode.h

#import <Foundation/Foundation.h>

@interface DebugMode: NSObject
    +(BOOL) isDebug;
@end

DebugMode.m

#import "DebugMode.h"

@implementation DebugMode
+(BOOL) isDebug {
#ifdef DEBUG
    return true;
#else
    return false;
#endif
}
@end

add into header bridge file:

#include "DebugMode.h"

usage:

DebugMode.isDebug()

It is not needed to write something inside project properties swift flags.

PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT (in windows 10)

Go to Control Panel>>System and Security>>System>>Advance system settings>>Environment Variables then set variable value of ANDROID_HOME set it like this "C:\Users\username\AppData\Local\Android\sdk" set username as your pc name, then restart your android studio. after that you can create your AVD again than the error will gone than it will start the virtual device.

Python - abs vs fabs

Edit: as @aix suggested, a better (more fair) way to compare the speed difference:

In [1]: %timeit abs(5)
10000000 loops, best of 3: 86.5 ns per loop

In [2]: from math import fabs

In [3]: %timeit fabs(5)
10000000 loops, best of 3: 115 ns per loop

In [4]: %timeit abs(-5)
10000000 loops, best of 3: 88.3 ns per loop

In [5]: %timeit fabs(-5)
10000000 loops, best of 3: 114 ns per loop

In [6]: %timeit abs(5.0)
10000000 loops, best of 3: 92.5 ns per loop

In [7]: %timeit fabs(5.0)
10000000 loops, best of 3: 93.2 ns per loop

In [8]: %timeit abs(-5.0)
10000000 loops, best of 3: 91.8 ns per loop

In [9]: %timeit fabs(-5.0)
10000000 loops, best of 3: 91 ns per loop

So it seems abs() only has slight speed advantage over fabs() for integers. For floats, abs() and fabs() demonstrate similar speed.


In addition to what @aix has said, one more thing to consider is the speed difference:

In [1]: %timeit abs(-5)
10000000 loops, best of 3: 102 ns per loop

In [2]: import math

In [3]: %timeit math.fabs(-5)
10000000 loops, best of 3: 194 ns per loop

So abs() is faster than math.fabs().

Is try-catch like error handling possible in ASP Classic?

There are two approaches, you can code in JScript or VBScript which do have the construct or you can fudge it in your code.

Using JScript you'd use the following type of construct:

<script language="jscript" runat="server">
try  {
    tryStatements
}
catch(exception) {
    catchStatements
}
finally {
    finallyStatements
}
</script>

In your ASP code you fudge it by using on error resume next at the point you'd have a try and checking err.Number at the point of a catch like:

<%
' Turn off error Handling
On Error Resume Next


'Code here that you want to catch errors from

' Error Handler
If Err.Number <> 0 Then
   ' Error Occurred - Trap it
   On Error Goto 0 ' Turn error handling back on for errors in your handling block
   ' Code to cope with the error here
End If
On Error Goto 0 ' Reset error handling.

%>

Checking whether a string starts with XXXX

Can also be done this way..

regex=re.compile('^hello')

## THIS WAY YOU CAN CHECK FOR MULTIPLE STRINGS
## LIKE
## regex=re.compile('^hello|^john|^world')

if re.match(regex, somestring):
    print("Yes")

In Python, when to use a Dictionary, List or Set?

When use them, I make an exhaustive cheatsheet of their methods for your reference:

class ContainerMethods:
    def __init__(self):
        self.list_methods_11 = {
                    'Add':{'append','extend','insert'},
                    'Subtract':{'pop','remove'},
                    'Sort':{'reverse', 'sort'},
                    'Search':{'count', 'index'},
                    'Entire':{'clear','copy'},
                            }
        self.tuple_methods_2 = {'Search':'count','index'}

        self.dict_methods_11 = {
                    'Views':{'keys', 'values', 'items'},
                    'Add':{'update'},
                    'Subtract':{'pop', 'popitem',},
                    'Extract':{'get','setdefault',},
                    'Entire':{ 'clear', 'copy','fromkeys'},
                            }
        self.set_methods_17 ={
                    'Add':{['add', 'update'],['difference_update','symmetric_difference_update','intersection_update']},
                    'Subtract':{'pop', 'remove','discard'},
                    'Relation':{'isdisjoint', 'issubset', 'issuperset'},
                    'operation':{'union' 'intersection','difference', 'symmetric_difference'}
                    'Entire':{'clear', 'copy'}}

how to get all markers on google-maps-v3

If you mean "how can I get a reference to all markers on a given map" - then I think the answer is "Sorry, you have to do it yourself". I don't think there is any handy "maps.getMarkers()" type function: you have to keep your own references as the points are created:

var allMarkers = [];
....
// Create some markers
for(var i = 0; i < 10; i++) {
    var marker = new google.maps.Marker({...});
    allMarkers.push(marker);
}
...

Then you can loop over the allMarkers array to and do whatever you need to do.

Reading a column from CSV file using JAVA

Read the input continuously within the loop so that the variable line is assigned a value other than the initial value

while ((line = br.readLine()) !=null) {
  ...
}

Aside: This problem has already been solved using CSV libraries such as OpenCSV. Here are examples for reading and writing CSV files

How to give a Linux user sudo access?

Edit /etc/sudoers file either manually or using the visudo application. Remember: System reads /etc/sudoers file from top to the bottom, so you could overwrite a particular setting by putting the next one below. So to be on the safe side - define your access setting at the bottom.

ORA-00907: missing right parenthesis

ORA-00907: missing right parenthesis

This is one of several generic error messages which indicate our code contains one or more syntax errors. Sometimes it may mean we literally have omitted a right bracket; that's easy enough to verify if we're using an editor which has a match bracket capability (most text editors aimed at coders do). But often it means the compiler has come across a keyword out of context. Or perhaps it's a misspelled word, a space instead of an underscore or a missing comma.

Unfortunately the possible reasons why our code won't compile is virtually infinite and the compiler just isn't clever enough to distinguish them. So it hurls a generic, slightly cryptic, message like ORA-00907: missing right parenthesis and leaves it to us to spot the actual bloomer.

The posted script has several syntax errors. First I will discuss the error which triggers that ORA-0097 but you'll need to fix them all.

Foreign key constraints can be declared in line with the referencing column or at the table level after all the columns have been declared. These have different syntaxes; your scripts mix the two and that's why you get the ORA-00907.

In-line declaration doesn't have a comma and doesn't include the referencing column name.

CREATE TABLE historys_T    (
    history_record    VARCHAR2 (8),
    customer_id       VARCHAR2 (8) 
          CONSTRAINT historys_T_FK FOREIGN KEY REFERENCES T_customers ON DELETE CASCADE,
    order_id           VARCHAR2 (10) NOT NULL,
          CONSTRAINT fk_order_id_orders REFERENCES orders ON DELETE CASCADE)

Table level constraints are a separate component, and so do have a comma and do mention the referencing column.

CREATE TABLE historys_T    (
    history_record    VARCHAR2 (8),
    customer_id       VARCHAR2 (8),    
    order_id           VARCHAR2 (10) NOT NULL,
    CONSTRAINT historys_T_FK FOREIGN KEY (customer_id) REFERENCES T_customers ON DELETE CASCADE,   
   CONSTRAINT fk_order_id_orders FOREIGN KEY (order_id) REFERENCES orders ON DELETE CASCADE)

Here is a list of other syntax errors:

  1. The referenced table (and the referenced primary key or unique constraint) must already exist before we can create a foreign key against them. So you cannot create a foreign key for HISTORYS_T before you have created the referenced ORDERS table.
  2. You have misspelled the names of the referenced tables in some of the foreign key clauses (LIBRARY_T and FORMAT_T).
  3. You need to provide an expression in the DEFAULT clause. For DATE columns that is usually the current date, DATE DEFAULT sysdate.

Looking at our own code with a cool eye is a skill we all need to gain to be successful as developers. It really helps to be familiar with Oracle's documentation. A side-by-side comparison of your code and the examples in the SQL Reference would have helped you resolved these syntax errors in considerably less than two days. Find it here (11g) and here (12c).

As well as syntax errors, your scripts contain design mistakes. These are not failures, but bad practice which should not become habits.

  1. You have not named most of your constraints. Oracle will give them a default name but it will be a horrible one, and makes the data dictionary harder to understand. Explicitly naming every constraint helps us navigate the physical database. It also leads to more comprehensible error messages when our SQL trips a constraint violation.
  2. Name your constraints consistently. HISTORY_T has constraints called historys_T_FK and fk_order_id_orders, neither of which is helpful. A useful convention is <child_table>_<parent_table>_fk. So history_customer_fk and history_order_fk respectively.
  3. It can be useful to create the constraints with separate statements. Creating tables then primary keys then foreign keys will avoid the problems with dependency ordering identified above.
  4. You are trying to create cyclic foreign keys between LIBRARY_T and FORMATS. You could do this by creating the constraints in separate statement but don't: you will have problems when inserting rows and even worse problems with deletions. You should reconsider your data model and find a way to model the relationship between the two tables so that one is the parent and the other the child. Or perhaps you need a different kind of relationship, such as an intersection table.
  5. Avoid blank lines in your scripts. Some tools will handle them but some will not. We can configure SQL*Plus to handle them but it's better to avoid the need.
  6. The naming convention of LIBRARY_T is ugly. Try to find a more expressive name which doesn't require a needless suffix to avoid a keyword clash.
  7. T_CUSTOMERS is even uglier, being both inconsistent with your other tables and completely unnecessary, as customers is not a keyword.

Naming things is hard. You wouldn't believe the wrangles I've had about table names over the years. The most important thing is consistency. If I look at a data dictionary and see tables called T_CUSTOMERS and LIBRARY_T my first response would be confusion. Why are these tables named with different conventions? What conceptual difference does this express? So, please, decide on a naming convention and stick to. Make your table names either all singular or all plural. Avoid prefixes and suffixes as much as possible; we already know it's a table, we don't need a T_ or a _TAB.

@property retain, assign, copy, nonatomic in Objective-C

Before you know about the attributes of @property, you should know what is the use of @property.

  • @property offers a way to define the information that a class is intended to encapsulate. If you declare an object/variable using @property, then that object/variable will be accessible to other classes importing its class.

  • If you declare an object using @property in the header file, then you have to synthesize it using @synthesize in the implementation file. This makes the object KVC compliant. By default, compiler will synthesize accessor methods for this object.

  • accessor methods are : setter and getter.

Example: .h

@interface XYZClass : NSObject
@property (nonatomic, retain) NSString *name;
@end

.m

@implementation XYZClass
@synthesize name;
@end

Now the compiler will synthesize accessor methods for name.

XYZClass *obj=[[XYZClass alloc]init];
NSString *name1=[obj name]; // get 'name'
[obj setName:@"liza"]; // first letter of 'name' becomes capital in setter method
  • List of attributes of @property

    atomic, nonatomic, retain, copy, readonly, readwrite, assign, strong, getter=method, setter=method, unsafe_unretained

  • atomic is the default behavior. If an object is declared as atomic then it becomes thread-safe. Thread-safe means, at a time only one thread of a particular instance of that class can have the control over that object.

If the thread is performing getter method then other thread cannot perform setter method on that object. It is slow.

@property NSString *name; //by default atomic`
@property (atomic)NSString *name; // explicitly declared atomic`
  • nonatomic is not thread-safe. You can use the nonatomic property attribute to specify that synthesized accessors simply set or return a value directly, with no guarantees about what happens if that same value is accessed simultaneously from different threads.

For this reason, it’s faster to access a nonatomic property than an atomic one.

@property (nonatomic)NSString *name;   
  • retain is required when the attribute is a pointer to an object.

The setter method will increase retain count of the object, so that it will occupy memory in autorelease pool.

@property (retain)NSString *name;
  • copy If you use copy, you can't use retain. Using copy instance of the class will contain its own copy.

Even if a mutable string is set and subsequently changed, the instance captures whatever value it has at the time it is set. No setter and getter methods will be synthesized.

@property (copy) NSString *name;

now,

NSMutableString *nameString = [NSMutableString stringWithString:@"Liza"];    
xyzObj.name = nameString;    
[nameString appendString:@"Pizza"]; 

name will remain unaffected.

  • readonly If you don't want to allow the property to be changed via setter method, you can declare the property readonly.

Compiler will generate a getter, but not a setter.

@property (readonly) NSString *name;
  • readwrite is the default behavior. You don't need to specify readwrite attribute explicitly.

It is opposite of readonly.

@property (readwrite) NSString *name;
  • assign will generate a setter which assigns the value to the instance variable directly, rather than copying or retaining it. This is best for primitive types like NSInteger and CGFloat, or objects you don't directly own, such as delegates.

Keep in mind retain and assign are basically interchangeable when garbage collection is enabled.

@property (assign) NSInteger year;
  • strong is a replacement for retain.

It comes with ARC.

@property (nonatomic, strong) AVPlayer *player; 
  • getter=method If you want to use a different name for a getter method, it’s possible to specify a custom name by adding attributes to the property.

In the case of Boolean properties (properties that have a YES or NO value), it’s customary for the getter method to start with the word “is”

@property (getter=isFinished) BOOL finished;
  • setter=method If you want to use a different name for a setter method, it’s possible to specify a custom name by adding attributes to the property.

The method should end with a colon.

@property(setter = boolBool:) BOOL finished;
  • unsafe_unretained There are a few classes in Cocoa and Cocoa Touch that don’t yet support weak references, which means you can’t declare a weak property or weak local variable to keep track of them. These classes include NSTextView, NSFont and NSColorSpace,etc. If you need to use a weak reference to one of these classes, you must use an unsafe reference.

An unsafe reference is similar to a weak reference in that it doesn’t keep its related object alive, but it won’t be set to nil if the destination object is deallocated.

@property (unsafe_unretained) NSObject *unsafeProperty;

If you need to specify multiple attributes, simply include them as a comma-separated list, like this:

@property (readonly, getter=isFinished) BOOL finished;

How to unapply a migration in ASP.NET Core with EF Core

Use:

CLI

> dotnet ef database update <previous-migration-name>

Package Manager Console

PM> Update-Database <previous-migration-name>

Example:

PM> Update-Database MyInitialMigration

Then try to remove last migration.

Removing migration without database update doesn't work because you applied changes to database.

If using PMC, Try: PM> update-database 0 This will wipe the database and allow you to remove the Migration Snapshot on your Solution

How to call servlet through a JSP page

You could use <jsp:include> for this.

<jsp:include page="/servletURL" />

It's however usually the other way round. You call the servlet which in turn forwards to the JSP to display the results. Create a Servlet which does something like following in doGet() method.

request.setAttribute("result", "This is the result of the servlet call");
request.getRequestDispatcher("/WEB-INF/result.jsp").forward(request, response);

and in /WEB-INF/result.jsp

<p>The result is ${result}</p>

Now call the Servlet by the URL which matches its <url-pattern> in web.xml, e.g. http://example.com/contextname/servletURL.

Do note that the JSP file is explicitly placed in /WEB-INF folder. This will prevent the user from opening the JSP file individually. The user can only call the servlet in order to open the JSP file.


If your actual question is "How to submit a form to a servlet?" then you just have to specify the servlet URL in the HTML form action.

<form action="servletURL" method="post">

Its doPost() method will then be called.


See also:

How to compare two tags with git?

For a side-by-side visual representation, I use git difftool with openDiff set to the default viewer.

Example usage:

git difftool tags/<FIRST TAG> tags/<SECOND TAG>

If you are only interested in a specific file, you can use:

git difftool tags/<FIRST TAG>:<FILE PATH> tags/<SECOND TAG>:<FILE PATH>

As a side-note, the tags/<TAG>s can be replaced with <BRANCH>es if you are interested in diffing branches.

Jquery validation plugin - TypeError: $(...).validate is not a function

For me problem solved by changing http://ajax... into https://ajax... (add an S to http)

https://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js

Git push failed, "Non-fast forward updates were rejected"

(One) Solution for Netbeans 7.1: Try a pull. This will probably also fail. Now have a look into the logs (they are usually shown now in the IDE). There's one/more line saying:

"Pull failed due to this file:"

Search that file, delete it (make a backup before). Usually it's a .gitignore file, so you will not delete code. Redo the push. Everything should work fine now.

Javascript to Select Multiple options

This type of thing should be done server-side, so as to limit the amount of resources used on the client for such trivial tasks. That being said, if you were to do it on the front-end, I would encourage you to consider using something like underscore.js to keep the code clean and concise:

var values = ["Red", "Green"],
    colors = document.getElementById("colors");

_.each(colors.options, function (option) {
    option.selected = ~_.indexOf(values, option.text);
});

If you're using jQuery, it could be even more terse:

var values = ["Red", "Green"];

$("#colors option").prop("selected", function () {
    return ~$.inArray(this.text, values);
});

If you were to do this without a tool like underscore.js or jQuery, you would have a bit more to write, and may find it to be a bit more complicated:

var color, i, j,
    values = ["Red", "Green"],
    options = document.getElementById("colors").options;

for ( i = 0; i < values.length; i++ ) {
    for ( j = 0, color = values[i]; j < options.length; j++ ) {
        options[j].selected = options[j].selected || color === options[j].text;
    }
}

ASP.NET Core 1.0 on IIS error 502.5

I got the same problem and the reason in my case was that the EF core was trying to read connection string from appsettings.development.json file. I opened it and found the connection string was commented.

//{
//  "ConnectionStrings": {
//    "DefaultConnection": "Server=vaio;Database=Goldentaurus;Trusted_Connection=True;",
//    "IdentityConnection": "Server=vaio;Database=GTIdentity;Trusted_Connection=True;"
//  }
//}

I then uncommitted them like below and the problem solved:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=vaio;Database=Goldentaurus;Trusted_Connection=True;",
    "IdentityConnection": "Server=vaio;Database=GTIdentity;Trusted_Connection=True;"
  }
}

Twitter Bootstrap 3: how to use media queries?

To improve the main response:

You can use the media attribute of the <link> tag (it support media queries) in order to download just the code the user needs.

<link href="style.css" rel="stylesheet">
<link href="deviceSizeDepending.css" rel="stylesheet" media="(min-width: 40em)">

With this, the browser will download all CSS resources, regardless of the media attribute. The difference is that if the media-query of the media attribute is evaluated to false then that .css file and his content will not be render-blocking.

Therefore, it is recommended to use the media attribute in the <link> tag since it guarantees a better user experience.

Here you can read a Google article about this issue https://developers.google.com/web/fundamentals/performance/critical-rendering-path/render-blocking-css

Some tools that will help you to automate the separation of your css code in different files according to your media-querys

Webpack https://www.npmjs.com/package/media-query-plugin https://www.npmjs.com/package/media-query-splitting-plugin

PostCSS https://www.npmjs.com/package/postcss-extract-media-query

Removing leading and trailing spaces from a string

Boost string trim algorithm

#include <boost/algorithm/string/trim.hpp>

[...]

std::string msg = "   some text  with spaces  ";
boost::algorithm::trim(msg);

How to get the instance id from within an ec2 instance?

On Ubuntu you can:

sudo apt-get install cloud-utils

And then you can:

EC2_INSTANCE_ID=$(ec2metadata --instance-id)

You can get most of the metadata associated with the instance this way:

ec2metadata --help
Syntax: /usr/bin/ec2metadata [options]

Query and display EC2 metadata.

If no options are provided, all options will be displayed

Options:
    -h --help               show this help

    --kernel-id             display the kernel id
    --ramdisk-id            display the ramdisk id
    --reservation-id        display the reservation id

    --ami-id                display the ami id
    --ami-launch-index      display the ami launch index
    --ami-manifest-path     display the ami manifest path
    --ancestor-ami-ids      display the ami ancestor id
    --product-codes         display the ami associated product codes
    --availability-zone     display the ami placement zone

    --instance-id           display the instance id
    --instance-type         display the instance type

    --local-hostname        display the local hostname
    --public-hostname       display the public hostname

    --local-ipv4            display the local ipv4 ip address
    --public-ipv4           display the public ipv4 ip address

    --block-device-mapping  display the block device id
    --security-groups       display the security groups

    --mac                   display the instance mac address
    --profile               display the instance profile
    --instance-action       display the instance-action

    --public-keys           display the openssh public keys
    --user-data             display the user data (not actually metadata)

Where does the @Transactional annotation belong?

It's better to keep @Transactional in a separate middle layer between DAO and Service Layer. Since, rollback is very important, you can place all your DB manipulation in the middle layer and write business logic in Service Layer. Middle layer will interact with your DAO layers.

This will help you in many situations like ObjectOptimisticLockingFailureException - This exception occurs only after your Transaction is over. So, you cannot catch it in middle layer but you can catch in your service layer now. This would not be possible if you have @Transactional in Service layer. Although you can catch in Controller but Controller should be as clean as possible.

If you are sending mail or sms in seperate thread after completing all the save,delete and update options, you can do this in service after Transaction is completed in your middle layer. Again, if you mention @Transactional in service layer, you mail will go even if your transaction fails.

So having a middle @Transaction layer will help to make your code better and easy to handle. Otherwise, If you use in DAO layer, you may not be able to Rollback all operations. If you use in Service layer, you may have to use AOP(Aspect Oriented Programming) in certain cases.

How to create a Jar file in Netbeans

Please do right click on the project and go to properties. Then go to Build and Packaging. You can see the JAR file location that is produced by defualt setting of netbean in the dist directory.

How to center a component in Material-UI and make it responsive?

With other answers used, xs='auto' did a trick for me.

<Grid container
    alignItems='center'
    justify='center'
    style={{ minHeight: "100vh" }}>

    <Grid item xs='auto'>
        <GoogleLogin
            clientId={process.env.REACT_APP_GOOGLE_CLIENT_ID}
            buttonText="Log in with Google"
            onSuccess={this.handleLogin}
            onFailure={this.handleLogin}
             cookiePolicy={'single_host_origin'}
         />
    </Grid>
</Grid>

Select Specific Columns from Spark DataFrame

Problem was to select columns of on dataframe after joining with other dataframe.

I tried below and select the columns of salaryDf from the joined dataframe.

Hope this will help

        val empDf=spark.read.option("header","true").csv("/data/tech.txt")

        val salaryDf=spark.read.option("header","true").csv("/data/salary.txt")

        val joinData= empDf.join(salaryDf,empDf.col("first") === salaryDf.col("first") and  empDf.col("last") === salaryDf.col("last"))

      //**below will select the colums of salaryDf only**

     val finalDF=joinData.select(salaryDf.columns map  salaryDf.col:_*)

//same way we can select the columns of empDf
joinData.select(empDf.columns map  empDf.col:_*)

Python convert decimal to hex

def main():
    result = int(input("Enter a whole, positive, number to be converted to hexadecimal: "))
    hexadecimal = ""
    while result != 0:
        remainder = changeDigit(result % 16)
        hexadecimal = str(remainder) + hexadecimal
        result = int(result / 16)
    print(hexadecimal)

def changeDigit(digit):
    decimal =     [10 , 11 , 12 , 13 , 14 , 15 ]
    hexadecimal = ["A", "B", "C", "D", "E", "F"]
    for counter in range(7):
        if digit == decimal[counter - 1]:
            digit = hexadecimal[counter - 1]
    return digit

main()

This is the densest I could make for converting decimal to hexadecimal. NOTE: This is in Python version 3.5.1

Is there any way to set environment variables in Visual Studio Code?

My response is fairly late. I faced the same problem. I am on Windows 10. This is what I did:

  • Open a new Command prompt (CMD.EXE)
  • Set the environment variables . set myvar1=myvalue1
  • Launch VS Code from that Command prompt by typing code and then press ENTER
  • VS code was launched and it inherited all the custom variables that I had set in the parent CMD window

Optionally, you can also use the Control Panel -> System properties window to set the variables on a more permanent basis

Hope this helps.

Convert a string to an enum in C#

Enum.Parse is your friend:

StatusEnum MyStatus = (StatusEnum)Enum.Parse(typeof(StatusEnum), "Active");

C# - Making a Process.Start wait until the process has start-up

I used the EventWaitHandle class. On the parent process, create a named EventWaitHandle with initial state of the event set to non-signaled. The parent process blocks until the child process calls the Set method, changing the state of the event to signaled, as shown below.

Parent Process:

using System;
using System.Threading;
using System.Diagnostics;

namespace MyParentProcess
{
    class Program
    {
        static void Main(string[] args)
        {
            EventWaitHandle ewh = null;
            try
            {
                ewh = new EventWaitHandle(false, EventResetMode.AutoReset, "CHILD_PROCESS_READY");

                Process process = Process.Start("MyChildProcess.exe", Process.GetCurrentProcess().Id.ToString());
                if (process != null)
                {
                    if (ewh.WaitOne(10000))
                    {
                        // Child process is ready.
                    }
                }
            }
            catch(Exception exception)
            { }
            finally
            {
                if (ewh != null)
                    ewh.Close();
            }
        }
    }
}

Child Process:

using System;
using System.Threading;
using System.Diagnostics;

namespace MyChildProcess
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Representing some time consuming work.
                Thread.Sleep(5000);

                EventWaitHandle.OpenExisting("CHILD_PROCESS_READY")
                    .Set();

                Process.GetProcessById(Convert.ToInt32(args[0]))
                    .WaitForExit();
            }
            catch (Exception exception)
            { }
        }
    }
}

check if file exists on remote host with ssh

Test if a file exists:

HOST="example.com"
FILE="/path/to/file"

if ssh $HOST "test -e $FILE"; then
    echo "File exists."
else
    echo "File does not exist."
fi

And the opposite, test if a file does not exist:

HOST="example.com"
FILE="/path/to/file"

if ! ssh $HOST "test -e $FILE"; then
    echo "File does not exist."
else
    echo "File exists."
fi

Changing background color of selected cell?

Works for me

UIView *customColorView = [[UIView alloc] init];
    customColorView.backgroundColor = [UIColor colorWithRed:180/255.0 
                                                      green:138/255.0 
                                                       blue:171/255.0 
                                                      alpha:0.5];
    cell.selectedBackgroundView =  customColorView;

What's the difference between passing by reference vs. passing by value?

When passing by ref you are basically passing a pointer to the variable. Pass by value you are passing a copy of the variable. In basic usage this normally means pass by ref changes to the variable will seen be the calling method and pass by value they wont.

Returning a value from callback function in Node.js

Its undefined because, console.log(response) runs before doCall(urlToCall); is finished. You have to pass in a callback function aswell, that runs when your request is done.

First, your function. Pass it a callback:

function doCall(urlToCall, callback) {
    urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {                              
        var statusCode = response.statusCode;
        finalData = getResponseJson(statusCode, data.toString());
        return callback(finalData);
    });
}

Now:

var urlToCall = "http://myUrlToCall";
doCall(urlToCall, function(response){
    // Here you have access to your variable
    console.log(response);
})

@Rodrigo, posted a good resource in the comments. Read about callbacks in node and how they work. Remember, it is asynchronous code.

wampserver doesn't go green - stays orange

WAMP Server may turn orange for various reason as it is not working. This is also a another type of issue. that can be due to webservices is running in services.msc This is explained in the below blog. Please try it. How to resolve HTTP Error 404 and launch localhost with WAMP Server for PHP & MySql?

Print raw string from variable? (not getting the answers)

You can't turn an existing string "raw". The r prefix on literals is understood by the parser; it tells it to ignore escape sequences in the string. However, once a string literal has been parsed, there's no difference between a raw string and a "regular" one. If you have a string that contains a newline, for instance, there's no way to tell at runtime whether that newline came from the escape sequence \n, from a literal newline in a triple-quoted string (perhaps even a raw one!), from calling chr(10), by reading it from a file, or whatever else you might be able to come up with. The actual string object constructed from any of those methods looks the same.

How to import RecyclerView for Android L-preview

compile 'com.android.support:recyclerview-v7:24.2.1'

This works for me. Try it.

How to save to local storage using Flutter?

A late answer but I hope it will help anyone visiting here later too..

I will provide categories to save and their respective best methods...

  1. Shared Preferences Use this when storing simple values on storage e.g Color theme, app language, last scroll position(in reading apps).. these are simple settings that you would want to persist when the app restarts.. You could, however, use this to store large things(Lists, Maps, Images) but that would require serialization and deserialization.. To learn more on this deserialization and serialization go here.
  2. Files This helps a lot when you have data that is defined more by you for example log files, image files and maybe you want to export csv files.. I heard that this type of persistence can be washed by storage cleaners once disk runs out of space.. Am not sure as i have never seen it.. This also can store almost anything but with the help of serialization and deserialization..
  3. Saving to a database This is enormously helpful in data which is a bit complex. And I think this doesn't get washed up by disc cleaners as it is stored in AppData(for android).. In this, your data is stored in an SQLite database. Its plugin is SQFLite. Kinds of data that you might wanna put in here are like everything that can be represented by a database.

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

It's because of the Security options.

Go to System Preferences... > Security & Privacy and there should be a button saying Open Anyway, under the General tab.

You can avoid doing this by changing the options under Allow apps downloaded from:, however I would recommend keeping it at the default Mac App Store and identified developers.

.datepicker('setdate') issues, in jQuery

As Scobal's post implies, the datepicker is looking for a Date object - not just a string! So, to modify your example code to do what you want:

var queryDate = new Date('2009/11/01'); // Dashes won't work
$('#datePicker').datepicker('setDate', queryDate);

ORA-00972 identifier is too long alias column name

As others have referred, names in Oracle SQL must be less or equal to 30 characters. I would add that this rule applies not only to table names but to field names as well. So there you have it.

Where to find htdocs in XAMPP Mac

Make sure no other apache servers are running as it generates an error when you try to access it on the browser even with a different port. Go to Finder and below Device you will usually see the lampp icon. You can also open the htdocs from any of the ide or code editor by opening files or project once you locate the lampp icon. Make sure you mount the stack.

What are best practices for REST nested resources?

Rails provides a solution to this: shallow nesting.

I think this is a good because when you deal directly with a known resource, there's no need to use nested routes, as has been discussed in other answers here.

Return Boolean Value on SQL Select Statement

I do it like this:

SELECT 1 FROM [dbo].[User] WHERE UserID = 20070022

Seeing as a boolean can never be null (at least in .NET), it should default to false or you can set it to that yourself if it's defaulting true. However 1 = true, so null = false, and no extra syntax.

Note: I use Dapper as my micro orm, I'd imagine ADO should work the same.

Node: log in a file instead of the console

const fs = require("fs");
const {keys} = Object;
const {Console} = console;

/**
 * Redirect console to a file.  Call without path or with false-y
 * value to restore original behavior.
 * @param {string} [path]
 */
function file(path) {
    const con = path ? new Console(fs.createWriteStream(path)) : null;

    keys(Console.prototype).forEach(key => {
        if (path) {
            this[key] = (...args) => con[key](...args);
        } else {
            delete this[key];
        }
    });
};

// patch global console object and export
module.exports = console.file = file;

To use it, do something like:

require("./console-file");
console.file("/path/to.log");
console.log("write to file!");
console.error("also write to file!");
console.file();    // go back to writing to stdout

Difference between Big-O and Little-O Notation

I find that when I can't conceptually grasp something, thinking about why one would use X is helpful to understand X. (Not to say you haven't tried that, I'm just setting the stage.)

[stuff you know]A common way to classify algorithms is by runtime, and by citing the big-Oh complexity of an algorithm, you can get a pretty good estimation of which one is "better" -- whichever has the "smallest" function in the O! Even in the real world, O(N) is "better" than O(N²), barring silly things like super-massive constants and the like.[/stuff you know]

Let's say there's some algorithm that runs in O(N). Pretty good, huh? But let's say you (you brilliant person, you) come up with an algorithm that runs in O(NloglogloglogN). YAY! Its faster! But you'd feel silly writing that over and over again when you're writing your thesis. So you write it once, and you can say "In this paper, I have proven that algorithm X, previously computable in time O(N), is in fact computable in o(n)."

Thus, everyone knows that your algorithm is faster --- by how much is unclear, but they know its faster. Theoretically. :)

How to do something to each file in a directory with a batch script

Use

for /r path %%var in (*.*) do some_command %%var

with:

  • path being the starting path.
  • %%var being some identifier.
  • *.* being a filemask OR the contents of a variable.
  • some_command being the command to execute with the path and var concatenated as parameters.

Default behavior of "git push" without a branch specified

You can change that default behavior in your .gitconfig, for example:

[push]
  default = current

To check the current settings, run:

git config --global --get push.default