Programs & Examples On #Ora 01861

ORA-01861: Literal does not match format string

ORA-01861: literal does not match format string

Remove the TO_DATE in the WHERE clause

TO_DATE (alarm_datetime,'DD.MM.YYYY HH24:MI:SS')

and change the code to

alarm_datetime

The error comes from to_date conversion of a date column.

Added Explanation: Oracle converts your alarm_datetime into a string using its nls depended date format. After this it calls to_date with your provided date mask. This throws the exception.

Convert a string date into datetime in Oracle

Try this: TO_DATE('2011-07-28T23:54:14Z', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')

How do I pipe or redirect the output of curl -v?

Your URL probably has ampersands in it. I had this problem, too, and I realized that my URL was full of ampersands (from CGI variables being passed) and so everything was getting sent to background in a weird way and thus not redirecting properly. If you put quotes around the URL it will fix it.

Find the division remainder of a number

The remainder of a division can be discovered using the operator %:

>>> 26%7
5

In case you need both the quotient and the modulo, there's the builtin divmod function:

>>> seconds= 137
>>> minutes, seconds= divmod(seconds, 60)

Is there any way to debug chrome in any IOS device

Old Answer (July 2016):

You can't directly debug Chrome for iOS due to restrictions on the published WKWebView apps, but there are a few options already discussed in other SO threads:

  1. If you can reproduce the issue in Safari as well, then use Remote Debugging with Safari Web Inspector. This would be the easiest approach.

  2. WeInRe allows some simple debugging, using a simple client-server model. It's not fully featured, but it may well be enough for your problem. See instructions on set up here.

  3. You could try and create a simple WKWebView browser app (some instructions here), or look for an existing one on GitHub. Since Chrome uses the same rendering engine, you could debug using that, as it will be close to what Chrome produces.

There's a "bug" opened up for WebKit: Allow Web Inspector usage for release builds of WKWebView. If and when we get an API to WKWebView, Chrome for iOS would be debuggable.

Update January 2018:

Since my answer back in 2016, some work has been done to improve things.

There is a recent project called RemoteDebug iOS WebKit Adapter, by some of the Microsoft team. It's an adapter that handles the API differences between Webkit Remote Debugging Protocol and Chrome Debugging Protocol, and this allows you to debug iOS WebViews in any app that supports the protocol - Chrome DevTools, VS Code etc.

Check out the getting started guide in the repo, which is quite detailed.

If you are interesting, you can read up on the background and architecture here.

Is there a better way to do optional function parameters in JavaScript?

During a project I noticed I was repeating myself too much with the optional parameters and settings, so I made a class that handles the type checking and assigns a default value which results in neat and readable code. See example and let me know if this works for you.

var myCar           = new Car('VW', {gearbox:'automatic', options:['radio', 'airbags 2x']});
var myOtherCar      = new Car('Toyota');

function Car(brand, settings) {
    this.brand      = brand;

    // readable and adjustable code
    settings        = DefaultValue.object(settings, {});
    this.wheels     = DefaultValue.number(settings.wheels, 4);
    this.hasBreaks  = DefaultValue.bool(settings.hasBreaks, true);
    this.gearbox    = DefaultValue.string(settings.gearbox, 'manual');
    this.options    = DefaultValue.array(settings.options, []);

    // instead of doing this the hard way
    settings        = settings || {};
    this.wheels     = (!isNaN(settings.wheels)) ? settings.wheels : 4;
    this.hasBreaks  = (typeof settings.hasBreaks !== 'undefined') ? (settings.hasBreaks === true) : true;
    this.gearbox    = (typeof settings.gearbox === 'string') ? settings.gearbox : 'manual';
    this.options    = (typeof settings.options !== 'undefined' && Array.isArray(settings.options)) ? settings.options : [];
}

Using this class:

(function(ns) {

    var DefaultValue = {

        object: function(input, defaultValue) {
            if (typeof defaultValue !== 'object') throw new Error('invalid defaultValue type');
            return (typeof input !== 'undefined') ? input : defaultValue;
        },

        bool: function(input, defaultValue) {
            if (typeof defaultValue !== 'boolean') throw new Error('invalid defaultValue type');
            return (typeof input !== 'undefined') ? (input === true) : defaultValue;
        },

        number: function(input, defaultValue) {
            if (isNaN(defaultValue)) throw new Error('invalid defaultValue type');
            return (typeof input !== 'undefined' && !isNaN(input)) ? parseFloat(input) : defaultValue;
        },

        // wrap the input in an array if it is not undefined and not an array, for your convenience
        array: function(input, defaultValue) {
            if (typeof defaultValue === 'undefined') throw new Error('invalid defaultValue type');
            return (typeof input !== 'undefined') ? (Array.isArray(input) ? input : [input]) : defaultValue;
        },

        string: function(input, defaultValue) {
            if (typeof defaultValue !== 'string') throw new Error('invalid defaultValue type');
            return (typeof input === 'string') ? input : defaultValue;
        },

    };

    ns.DefaultValue = DefaultValue;

}(this));

TypeError: Object of type 'bytes' is not JSON serializable

I was dealing with this issue today, and I knew that I had something encoded as a bytes object that I was trying to serialize as json with json.dump(my_json_object, write_to_file.json). my_json_object in this case was a very large json object that I had created, so I had several dicts, lists, and strings to look at to find what was still in bytes format.

The way I ended up solving it: the write_to_file.json will have everything up to the bytes object that is causing the issue.

In my particular case this was a line obtained through

for line in text:
    json_object['line'] = line.strip()

I solved by first finding this error with the help of the write_to_file.json, then by correcting it to:

for line in text:
    json_object['line'] = line.strip().decode()

Find a string by searching all tables in SQL Server Management Studio 2008

There's no need for nested looping (outer looping through tables and inner looping through all table columns). One can retrieve all (or arbitrary selected/filtered) table-column combinations from INFORMATION_SCHEMA.COLUMNS and in one loop simply pass through (search) all of them:

DECLARE @search VARCHAR(100), @table SYSNAME, @column SYSNAME

DECLARE curTabCol CURSOR FOR
    SELECT c.TABLE_SCHEMA + '.' + c.TABLE_NAME, c.COLUMN_NAME
    FROM INFORMATION_SCHEMA.COLUMNS c
    JOIN INFORMATION_SCHEMA.TABLES t 
      ON t.TABLE_NAME=c.TABLE_NAME AND t.TABLE_TYPE='BASE TABLE' -- avoid views
    WHERE c.DATA_TYPE IN ('varchar','nvarchar') -- searching only in these column types
    --AND c.COLUMN_NAME IN ('NAME','DESCRIPTION') -- searching only in these column names

SET @search='john'

OPEN curTabCol
FETCH NEXT FROM curTabCol INTO @table, @column

WHILE (@@FETCH_STATUS = 0)
BEGIN
    EXECUTE('IF EXISTS 
             (SELECT * FROM ' + @table + ' WHERE ' + @column + ' = ''' + @search + ''') 
             PRINT ''' + @table + '.' + @column + '''')
    FETCH NEXT FROM curTabCol INTO @table, @column
END

CLOSE curTabCol
DEALLOCATE curTabCol

Loop through each cell in a range of cells when given a Range object

I'm resurrecting the dead here, but because a range can be defined as "A:A", using a for each loop ends up with a potential infinite loop. The solution, as far as I know, is to use the Do Until loop.

Do Until Selection.Value = ""
  Rem Do things here...
Loop

What is the difference between prefix and postfix operators?

Actually what happens is when you use postfix i.e. i++, the initial value of i is used for returning rather than the incremented one. After this the value of i is increased by 1. And this happens with any statement that uses i++, i.e. first initial value of i is used in the expression and then it is incremented.

And the exact opposite happens in prefix. If you would have returned ++i, then the incremented value i.e. 11 is returned, which is because adding 1 is performed first and then it is returned.

git recover deleted file where no commit was made after the delete

The output tells you what you need to do. git reset HEAD cc.properties etc.

This will unstage the rm operation. After that, running a git status again will tell you that you need to do a git checkout -- cc.properties to get the file back.

Update: I have this in my config file

$ git config alias.unstage
reset HEAD

which I usually use to unstage stuff.

A generic error occurred in GDI+, JPEG Image to MemoryStream

if your code is as follows then also this error occurs

private Image GetImage(byte[] byteArray)
{
   using (var stream = new MemoryStream(byteArray))
   {
       return Image.FromStream(stream);
    }
}

The correct one is

private Image GetImage(byte[] byteArray)
{
   var stream = new MemoryStream(byteArray))
   return Image.FromStream(stream);        
}

This may be because we are returning from the using block

What is the difference between map and flatMap and a good use case for each?

If you are asking the difference between RDD.map and RDD.flatMap in Spark, map transforms an RDD of size N to another one of size N . eg.

myRDD.map(x => x*2)

for example, if myRDD is composed of Doubles .

While flatMap can transform the RDD into anther one of a different size: eg.:

myRDD.flatMap(x =>new Seq(2*x,3*x))

which will return an RDD of size 2*N or

myRDD.flatMap(x =>if x<10 new Seq(2*x,3*x) else new Seq(x) )

DB2 SQL error sqlcode=-104 sqlstate=42601

You miss the from clause

SELECT *  from TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME  BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP

get user timezone

This will get you the timezone as a PHP variable. I wrote a function using jQuery and PHP. This is tested, and does work!

On the PHP page where you are want to have the timezone as a variable, have this snippet of code somewhere near the top of the page:

<?php    
    session_start();
    $timezone = $_SESSION['time'];
?>

This will read the session variable "time", which we are now about to create.

On the same page, in the <head> section, first of all you need to include jQuery:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

Also in the <head> section, paste this jQuery:

<script type="text/javascript">
    $(document).ready(function() {
        if("<?php echo $timezone; ?>".length==0){
            var visitortime = new Date();
            var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
            $.ajax({
                type: "GET",
                url: "http://example.com/timezone.php",
                data: 'time='+ visitortimezone,
                success: function(){
                    location.reload();
                }
            });
        }
    });
</script>

You may or may not have noticed, but you need to change the url to your actual domain.

One last thing. You are probably wondering what the heck timezone.php is. Well, it is simply this: (create a new file called timezone.php and point to it with the above url)

<?php
    session_start();
    $_SESSION['time'] = $_GET['time'];
?>

If this works correctly, it will first load the page, execute the JavaScript, and reload the page. You will then be able to read the $timezone variable and use it to your pleasure! It returns the current UTC/GMT time zone offset (GMT -7) or whatever timezone you are in.

You can read more about this on my blog

Error: Cannot find module 'webpack'

npm link webpack worked for me.

My webpack configuration: "webpack": "^4.41.2", "webpack-dev-server": "^3.9.0", "webpack-cli": "^3.3.10"

Python requests library how to pass Authorization header with single token

You can try something like this

r = requests.get(ENDPOINT, params=params, headers={'Authorization': 'Basic %s' %  API_KEY})

What is use of c_str function In c++

Most OLD c++ and c functions, when deal with strings, use const char*.
With STL and std::string, string.c_str() is introduced to be able to convert from std::string to const char*.

That means that if you promise not to change the buffer, you'll be able to use read only string contents. PROMISE = const char*

How to test abstract class in Java with JUnit?

If you need a solution anyway (e.g. because you have too many implementations of the abstract class and the testing would always repeat the same procedures) then you could create an abstract test class with an abstract factory method which will be excuted by the implementation of that test class. This examples works or me with TestNG:

The abstract test class of Car:

abstract class CarTest {

// the factory method
abstract Car createCar(int speed, int fuel);

// all test methods need to make use of the factory method to create the instance of a car
@Test
public void testGetSpeed() {
    Car car = createCar(33, 44);
    assertEquals(car.getSpeed(), 33);
    ...

Implementation of Car

class ElectricCar extends Car {

    private final int batteryCapacity;

    public ElectricCar(int speed, int fuel, int batteryCapacity) {
        super(speed, fuel);
        this.batteryCapacity = batteryCapacity;
    }

    ...

Unit test class ElectricCarTest of the Class ElectricCar:

class ElectricCarTest extends CarTest {

    // implementation of the abstract factory method
    Car createCar(int speed, int fuel) {
        return new ElectricCar(speed, fuel, 0);
    }

    // here you cann add specific test methods
    ...

How to convert array to a string using methods other than JSON?

readable output!

echo json_encode($array);     //outputs--->    "name1":"value1",  "name2":"value2",  ...

OR

echo print_r($array, true);

Select All distinct values in a column using LINQ

var uniq = allvalues.GroupBy(x => x.Id).Select(y=>y.First()).Distinct();

Easy and simple

Error in Python script "Expected 2D array, got 1D array instead:"?

I was facing the same issue earlier but I have somehow found the solution, You can try reg.predict([[3300]]).

The API used to allow scalar value but now you need to give a 2D array.

Why does typeof array with objects return "object" and not "array"?

One of the weird behaviour and spec in Javascript is the typeof Array is Object.

You can check if the variable is an array in couple of ways:

var isArr = data instanceof Array;
var isArr = Array.isArray(data);

But the most reliable way is:

isArr = Object.prototype.toString.call(data) == '[object Array]';

Since you tagged your question with jQuery, you can use jQuery isArray function:

var isArr = $.isArray(data);

How to get Spinner value?

If you already know the item is a String, I prefer:

String itemText = (String) mySpinner.getSelectedItem();

Calling toString() on an Object that you know is a String seems like a more roundabout path than just casting the Object to String.

Using NULL in C++?

In C++ NULL expands to 0 or 0L. See this quote from Stroustrup's FAQ:

Should I use NULL or 0?

In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.

If you have to name the null pointer, call it nullptr; that's what it's called in C++11. Then, "nullptr" will be a keyword.

Django: Calling .update() on a single model instance retrieved by .get()?

As @Nils mentionned, you can use the update_fields keyword argument of the save() method to manually specify the fields to update.

obj_instance = Model.objects.get(field=value)
obj_instance.field = new_value
obj_instance.field2 = new_value2

obj_instance.save(update_fields=['field', 'field2'])

The update_fields value should be a list of the fields to update as strings.

See https://docs.djangoproject.com/en/2.1/ref/models/instances/#specifying-which-fields-to-save

How to hide a mobile browser's address bar?

create host file = manifest.json

html tag head

<link rel="manifest" href="/manifest.json">

file

manifest.json

{
"name": "news",
"short_name": "news",
"description": "des news application day",
"categories": [
"news",
"business"
],
"theme_color": "#ffffff",
"background_color": "#ffffff",
"display": "standalone",
"orientation": "natural",
"lang": "fa",
"dir": "rtl",
"start_url": "/?application=true",
"gcm_sender_id": "482941778795",
"DO_NOT_CHANGE_GCM_SENDER_ID": "Do not change the GCM Sender ID",
"icons": [
{
"src": "https://s100.divarcdn.com/static/thewall-assets/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "https://s100.divarcdn.com/static/thewall-assets/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"related_applications": [
{
"platform": "play",
"url": "https://play.google.com/store/apps/details?id=ir.divar"
}
],
"prefer_related_applications": true
}

How to set the initial zoom/width for a webview

It is and old question but let me add a detail just in case more people like me arrive here.

The excellent answer posted by Brian is not working for me in Jelly Bean. I have to add also:

browser.setInitialScale(30);

The parameter can be any percentage tha accomplishes that the resized content is smaller than the webview width. Then setUseWideViewPort(true) extends the content width to the maximum of the webview width.

Merge two dataframes by index

This answer has been resolved for a while and all the available options are already out there. However in this answer I'll attempt to shed a bit more light on these options to help you understand when to use what.

This post will go through the following topics:

  • Merging with index under different conditions
    • options for index-based joins: merge, join, concat
    • merging on indexes
    • merging on index of one, column of other
  • effectively using named indexes to simplify merging syntax


Index-based joins

TL;DR

There are a few options, some simpler than others depending on the use case.

  1. DataFrame.merge with left_index and right_index (or left_on and right_on using named indexes)
  2. DataFrame.join (joins on index)
  3. pd.concat (joins on index)
PROS CONS
merge

• supports inner/left/right/full
• supports column-column, index-column, index-index joins

• can only join two frames at a time

join

• supports inner/left (default)/right/full
• can join multiple DataFrames at a time

• only supports index-index joins

concat

• specializes in joining multiple DataFrames at a time
• very fast (concatenation is linear time)

• only supports inner/full (default) joins
• only supports index-index joins


Index to index joins

Typically, an inner join on index would look like this:

left.merge(right, left_index=True, right_index=True)

Other types of joins (left, right, outer) follow similar syntax (and can be controlled using how=...).

Notable Alternatives

  1. DataFrame.join defaults to a left outer join on the index.

     left.join(right, how='inner',)
    

    If you happen to get ValueError: columns overlap but no suffix specified, you will need to specify lsuffix and rsuffix= arguments to resolve this. Since the column names are same, a differentiating suffix is required.

  2. pd.concat joins on the index and can join two or more DataFrames at once. It does a full outer join by default.

     pd.concat([left, right], axis=1, sort=False)
    

    For more information on concat, see this post.


Index to Column joins

To perform an inner join using index of left, column of right, you will use DataFrame.merge a combination of left_index=True and right_on=....

left.merge(right, left_index=True, right_on='key')

Other joins follow a similar structure. Note that only merge can perform index to column joins. You can join on multiple levels/columns, provided the number of index levels on the left equals the number of columns on the right.

join and concat are not capable of mixed merges. You will need to set the index as a pre-step using DataFrame.set_index.


This post is an abridged version of my work in Pandas Merging 101. Please follow this link for more examples and other topics on merging.

"Object doesn't support property or method 'find'" in IE

I solved same issue by adding polyfill following:

<script src="https://cdn.polyfill.io/v3/polyfill.min.js?features=default,Array.prototype.includes,Array.prototype.find"></script>

A polyfill is a piece of code (usually JavaScript on the Web) used to provide modern functionality on older browsers that do not natively support it.

Hope someone find this helpful.

How to keep a Python script output window open?

In python 2 you can do it with: raw_input()

>>print("Hello World!")    
>>raw_input('Waiting a key...')

In python 3 you can do it with: input()

>>print("Hello world!")    
>>input('Waiting a key...')

Also, you can do it with the time.sleep(time)

>>import time
>>print("The program will close in 5 seconds")
>>time.sleep(5)

Facebook API error 191

I have noticed also that even if you specify your website under secion - Website With Facebook Login -> Site url as e.g. http://example.com, but if your App Domains section is empty, and you open website as www.example.com you will get this error, too. To avoid it in "App Domains" section write example.com, that will allow subdomains, like www.example.com, something.example.com etc

How to get the text of the selected value of a dropdown list?

You can use option:selected to get the chosen option of the select element, then the text() method:

$("select option:selected").text();

Here's an example:

_x000D_
_x000D_
console.log($("select option:selected").text());
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
<select>_x000D_
    <option value="1">Volvo</option>_x000D_
    <option value="2" selected="selected">Saab</option>_x000D_
    <option value="3">Mercedes</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to install a private NPM module without my own registry?

I had this same problem, and after some searching around, I found Reggie (https://github.com/mbrevoort/node-reggie). It looks pretty solid. It allows for lightweight publishing of NPM modules to private servers. Not perfect (no authentication upon installation), and it's still really young, but I tested it locally, and it seems to do what it says it should do.

That is... (and this just from their docs)

npm install -g reggie
reggie-server -d ~/.reggie

then cd into your module directory and...

reggie -u http://<host:port> publish 
reggie -u http://127.0.0.1:8080 publish 

finally, you can install packages from reggie just by using that url either in a direct npm install command, or from within a package.json... like so

npm install http://<host:port>/package/<name>/<version>
npm install http://<host:port>/package/foo/1.0.0

or..

dependencies: {
    "foo": "http://<host:port>/package/foo/1.0.0"
}

Click to call html

tl;dr What to do in modern (2018) times? Assume tel: is supported, use it and forget about anything else.


The tel: URI scheme RFC5431 (as well as sms: but also feed:, maps:, youtube: and others) is handled by protocol handlers (as mailto: and http: are).

They're unrelated to HTML5 specification (it has been out there from 90s and documented first time back in 2k with RFC2806) then you can't check for their support using tools as modernizr. A protocol handler may be installed by an application (for example Skype installs a callto: protocol handler with same meaning and behaviour of tel: but it's not a standard), natively supported by browser or installed (with some limitations) by website itself.

What HTML5 added is support for installing custom web based protocol handlers (with registerProtocolHandler() and related functions) simplifying also the check for their support through isProtocolHandlerRegistered() function.

There is some easy ways to determine if there is an handler or not:" How to detect browser's protocol handlers?).

In general what I suggest is:

  1. If you're running on a mobile device then you can safely assume tel: is supported (yes, it's not true for very old devices but IMO you can ignore them).
  2. If JS isn't active then do nothing.
  3. If you're running on desktop browsers then you can use one of the techniques in the linked post to determine if it's supported.
  4. If tel: isn't supported then change links to use callto: and repeat check desctibed in 3.
  5. If tel: and callto: aren't supported (or - in a desktop browser - you can't detect their support) then simply remove that link replacing URL in href with javascript:void(0) and (if number isn't repeated in text span) putting, telephone number in title. Here HTML5 microdata won't help users (just search engines). Note that newer versions of Skype handle both callto: and tel:.

Please note that (at least on latest Windows versions) there is always a - fake - registered protocol handler called App Picker (that annoying window that let you choose with which application you want to open an unknown file). This may vanish your tests so if you don't want to handle Windows environment as a special case you can simplify this process as:

  1. If you're running on a mobile device then assume tel: is supported.
  2. If you're running on desktop then replace tel: with callto:. then drop tel: or leave it as is (assuming there are good chances Skype is installed).

How to show/hide an element on checkbox checked/unchecked states using jQuery?

Try this

<script>
    $().ready(function(){
        $('.coupon_question').live('click',function() 
        {
            if ($('.coupon_question').is(':checked')) {
                $(".answer").show();
            } else {
                $(".answer").hide();
            } 
        });
    });
</script>

Bootstrap carousel width and height

just put height="400px" into image attribute like

<img class="d-block w-100" src="../assets/img/natural-backdrop.jpg" height="400px" alt="First slide">

How to add font-awesome to Angular 2 + CLI project

You can use Angular Font Awesome package

npm install --save font-awesome angular-font-awesome

and then import in your module:

import { AngularFontAwesomeModule } from 'angular-font-awesome';
     @NgModule({
       //...
      imports: [
        //...
        AngularFontAwesomeModule
      ],
      //...
    })
    export class AppModule { }

and import the style in angular-cli file:

   "styles": [
        "styles.css",
        "../node_modules/font-awesome/css/font-awesome.css"
    ],

see more details about the package in npm library:

https://www.npmjs.com/package/angular-font-awesome

and then use it like this:

<i class="fa fa-coffee"></i>

html "data-" attribute as javascript parameter

If you are using jQuery you can easily fetch the data attributes by

$(this).data("id") or $(event.target).data("id")

Changing default shell in Linux

Try linux command chsh.

The detailed command is chsh -s /bin/bash. It will prompt you to enter your password. Your default login shell is /bin/bash now. You must log out and log back in to see this change.

The following is quoted from man page:

The chsh command changes the user login shell. This determines the name of the users initial login command. A normal user may only change the login shell for her own account, the superuser may change the login shell for any account

This command will change the default login shell permanently.

Note: If your user account is remote such as on Kerberos authentication (e.g. Enterprise RHEL) then you will not be able to use chsh.

How to construct a REST API that takes an array of id's for the resources

I find another way of doing the same thing by using @PathParam. Here is the code sample.

@GET
@Path("data/xml/{Ids}")
@Produces("application/xml")
public Object getData(@PathParam("zrssIds") String Ids)
{
  System.out.println("zrssIds = " + Ids);
  //Here you need to use String tokenizer to make the array from the string.
}

Call the service by using following url.

http://localhost:8080/MyServices/resources/cm/data/xml/12,13,56,76

where

http://localhost:8080/[War File Name]/[Servlet Mapping]/[Class Path]/data/xml/12,13,56,76

Non greedy (reluctant) regex matching in sed?

sed does not support "non greedy" operator.

You have to use "[]" operator to exclude "/" from match.

sed 's,\(http://[^/]*\)/.*,\1,'

P.S. there is no need to backslash "/".

How to nicely format floating numbers to string without unnecessary decimal 0's

Format price with grouping, rounding, and no unnecessary zeroes (in double).

Rules:

  1. No zeroes at the end (2.0000 = 2; 1.0100000 = 1.01)
  2. Two digits maximum after a point (2.010 = 2.01; 0.20 = 0.2)
  3. Rounding after the 2nd digit after a point (1.994 = 1.99; 1.995 = 2; 1.006 = 1.01; 0.0006 -> 0)
  4. Returns 0 (null/-0 = 0)
  5. Adds $ (= $56/-$56)
  6. Grouping (101101.02 = $101,101.02)

More examples:

-99.985 = -$99.99

10 = $10

10.00 = $10

20.01000089 = $20.01

It is written in Kotlin as a fun extension of Double (because it is used in Android), but it can be converted to Java easily, because Java classes were used.

/**
 * 23.0 -> $23
 *
 * 23.1 -> $23.1
 *
 * 23.01 -> $23.01
 *
 * 23.99 -> $23.99
 *
 * 23.999 -> $24
 *
 * -0.0 -> $0
 *
 * -5.00 -> -$5
 *
 * -5.019 -> -$5.02
 */
fun Double?.formatUserAsSum(): String {
    return when {
        this == null || this == 0.0 -> "$0"
        this % 1 == 0.0 -> DecimalFormat("$#,##0;-$#,##0").format(this)
        else -> DecimalFormat("$#,##0.##;-$#,##0.##").format(this)
    }
}

How to use:

var yourDouble: Double? = -20.00
println(yourDouble.formatUserAsSum()) // will print -$20

yourDouble = null
println(yourDouble.formatUserAsSum()) // will print $0

About DecimalFormat: https://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html

How do I concatenate or merge arrays in Swift?

Here's the shortest way to merge two arrays.

 var array1 = [1,2,3]
 let array2 = [4,5,6]

Concatenate/merge them

array1 += array2
New value of array1 is [1,2,3,4,5,6]

How can I simulate an array variable in MySQL?

I Think I can improve on this answer. Try this:

The parameter 'Pranks' is a CSV. ie. '1,2,3,4.....etc'

CREATE PROCEDURE AddRanks(
IN Pranks TEXT
)
BEGIN
  DECLARE VCounter INTEGER;
  DECLARE VStringToAdd VARCHAR(50);
  SET VCounter = 0;
  START TRANSACTION;
  REPEAT
    SET VStringToAdd = (SELECT TRIM(SUBSTRING_INDEX(Pranks, ',', 1)));
    SET Pranks = (SELECT RIGHT(Pranks, TRIM(LENGTH(Pranks) - LENGTH(SUBSTRING_INDEX(Pranks, ',', 1))-1)));
    INSERT INTO tbl_rank_names(rank)
    VALUES(VStringToAdd);
    SET VCounter = VCounter + 1;
  UNTIL (Pranks = '')
  END REPEAT;
  SELECT VCounter AS 'Records added';
  COMMIT;
END;

This method makes the searched string of CSV values progressively shorter with each iteration of the loop, which I believe would be better for optimization.

Set System.Drawing.Color values

You can make extension to just change one color component

static class ColorExtension
{
    public static Color ChangeG(Color this color,byte g) 
    {
        return Color.FromArgb(color.A,color.R,g,color.B);
    }
}

then you can use this:

  yourColor = yourColor.ChangeG(100);

Visual Studio setup problem - 'A problem has been encountered while loading the setup components. Canceling setup.'

Thanks, riaraos, uninstalling KB952241 was the solution for me, too. Before doing that I tried to run the installer from "Programs and Features" and from the installation DVD without success. I did not want to completely remove the VS 2008 installation but only add a few components.

Notes on my system:

Windows 7 Beta 1 Visual Studio 2008 SP1

Android Google Maps API V2 Zoom to Current Location

Try this coding:

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();

Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null)
{
    map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 13));

    CameraPosition cameraPosition = new CameraPosition.Builder()
        .target(new LatLng(location.getLatitude(), location.getLongitude()))      // Sets the center of the map to location user
        .zoom(17)                   // Sets the zoom
        .bearing(90)                // Sets the orientation of the camera to east
        .tilt(40)                   // Sets the tilt of the camera to 30 degrees
        .build();                   // Creates a CameraPosition from the builder
    map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));       
}

How to restore to a different database in sql server?

  • I have the same error as this topic when I restore a new database using an old database. (using .bak gives the same error)

  • I Changed the name of old database by name of new database (same this picture). It worked.

enter image description here

How to set CATALINA_HOME variable in windows 7?

Here is tutorial how to do that (CATALINA_HOME is path to your Tomcat, so I suppose something like C:/Program Files/Tomcat/. And for starting server, you need to execute script startup.bat from command line, this will make it:)

Hibernate: flush() and commit()

One common case for explicitly flushing is when you create a new persistent entity and you want it to have an artificial primary key generated and assigned to it, so that you can use it later on in the same transaction. In that case calling flush would result in your entity being given an id.

Another case is if there are a lot of things in the 1st-level cache and you'd like to clear it out periodically (in order to reduce the amount of memory used by the cache) but you still want to commit the whole thing together. This is the case that Aleksei's answer covers.

ExecuteReader requires an open and available Connection. The connection's current state is Connecting

Sorry for only commenting in the first place, but i'm posting almost every day a similar comment since many people think that it would be smart to encapsulate ADO.NET functionality into a DB-Class(me too 10 years ago). Mostly they decide to use static/shared objects since it seems to be faster than to create a new object for any action.

That is neither a good idea in terms of peformance nor in terms of fail-safety.

Don't poach on the Connection-Pool's territory

There's a good reason why ADO.NET internally manages the underlying Connections to the DBMS in the ADO-NET Connection-Pool:

In practice, most applications use only one or a few different configurations for connections. This means that during application execution, many identical connections will be repeatedly opened and closed. To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling.

Connection pooling reduces the number of times that new connections must be opened. The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls Close on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call.

So obviously there's no reason to avoid creating,opening or closing connections since actually they aren't created,opened and closed at all. This is "only" a flag for the connection pool to know when a connection can be reused or not. But it's a very important flag, because if a connection is "in use"(the connection pool assumes), a new physical connection must be openend to the DBMS what is very expensive.

So you're gaining no performance improvement but the opposite. If the maximum pool size specified (100 is the default) is reached, you would even get exceptions(too many open connections ...). So this will not only impact the performance tremendously but also be a source for nasty errors and (without using Transactions) a data-dumping-area.

If you're even using static connections you're creating a lock for every thread trying to access this object. ASP.NET is a multithreading environment by nature. So theres a great chance for these locks which causes performance issues at best. Actually sooner or later you'll get many different exceptions(like your ExecuteReader requires an open and available Connection).

Conclusion:

  • Don't reuse connections or any ADO.NET objects at all.
  • Don't make them static/shared(in VB.NET)
  • Always create, open(in case of Connections), use, close and dispose them where you need them(f.e. in a method)
  • use the using-statement to dispose and close(in case of Connections) implicitely

That's true not only for Connections(although most noticable). Every object implementing IDisposable should be disposed(simplest by using-statement), all the more in the System.Data.SqlClient namespace.

All the above speaks against a custom DB-Class which encapsulates and reuse all objects. That's the reason why i commented to trash it. That's only a problem source.


Edit: Here's a possible implementation of your retrievePromotion-method:

public Promotion retrievePromotion(int promotionID)
{
    Promotion promo = null;
    var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        var queryString = "SELECT PromotionID, PromotionTitle, PromotionURL FROM Promotion WHERE PromotionID=@PromotionID";
        using (var da = new SqlDataAdapter(queryString, connection))
        {
            // you could also use a SqlDataReader instead
            // note that a DataTable does not need to be disposed since it does not implement IDisposable
            var tblPromotion = new DataTable();
            // avoid SQL-Injection
            da.SelectCommand.Parameters.Add("@PromotionID", SqlDbType.Int);
            da.SelectCommand.Parameters["@PromotionID"].Value = promotionID;
            try
            {
                connection.Open(); // not necessarily needed in this case because DataAdapter.Fill does it otherwise 
                da.Fill(tblPromotion);
                if (tblPromotion.Rows.Count != 0)
                {
                    var promoRow = tblPromotion.Rows[0];
                    promo = new Promotion()
                    {
                        promotionID    = promotionID,
                        promotionTitle = promoRow.Field<String>("PromotionTitle"),
                        promotionUrl   = promoRow.Field<String>("PromotionURL")
                    };
                }
            }
            catch (Exception ex)
            {
                // log this exception or throw it up the StackTrace
                // we do not need a finally-block to close the connection since it will be closed implicitely in an using-statement
                throw;
            }
        }
    }
    return promo;
}

the best way to make codeigniter website multi-language. calling from lang arrays depends on lang session?

I've used Wiredesignz's MY_Language class with great success.

I've just published it on github, as I can't seem to find a trace of it anywhere.

https://github.com/meigwilym/CI_Language

My only changes are to rename the class to CI_Lang, in accordance with the new v2 changes.

How do I read a string entered by the user in C?

I think the best and safest way to read strings entered by the user is using getline()

Here's an example how to do this:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
    char *buffer = NULL;
    int read;
    unsigned int len;
    read = getline(&buffer, &len, stdin);
    if (-1 != read)
        puts(buffer);
    else
        printf("No line read...\n");

    printf("Size read: %d\n Len: %d\n", read, len);
    free(buffer);
    return 0;
}

Disable all Database related auto configuration in Spring Boot

I add in myApp.java, after @SpringBootApplication

@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})

And changed

@SpringBootApplication => @Configuration

So, I have this in my main class (myApp.java)

package br.com.company.project.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class SomeApplication {

public static void main(String[] args) {
    SpringApplication.run(SomeApplication.class, args);
}

}

And work for me! =)

How to see log files in MySQL?

You have to activate the query logging in mysql.

  1. edit /etc/my.cnf

    [mysqld]
    log=/tmp/mysql.log
    
  2. restart the computer or the mysqld service

    service mysqld restart
    
  3. open phpmyadmin/any application that uses mysql/mysql console and run a query

  4. cat /tmp/mysql.log ( you should see the query )

Find max and second max salary for a employee table MySQL

$q="select * from info order by salary desc limit 1,0"; // display highest 2 salary

or

$q="select * from info order by salary desc limit 1,0"; // display 2nd highest salary

Why should I use var instead of a type?

It's really just a coding style. The compiler generates the exact same for both variants.

See also here for the performance question:

Placing/Overlapping(z-index) a view above another view in android

I solved the same problem by add android:elevation="1dp" to which view you want it over another. But it can't display below 5.0, and it will have a little shadow, if you can accept it, it's OK.

So, the most correct solution which is @kcoppock said.

How can I get query string values in JavaScript?

This is a function I created a while back and I'm quite happy with. It is not case sensitive - which is handy. Also, if the requested QS doesn't exist, it just returns an empty string.

I use a compressed version of this. I'm posting uncompressed for the novice types to better explain what's going on.

I'm sure this could be optimized or done differently to work faster, but it's always worked great for what I need.

Enjoy.

function getQSP(sName, sURL) {
    var theItmToRtn = "";
    var theSrchStrg = location.search;
    if (sURL) theSrchStrg = sURL;
    var sOrig = theSrchStrg;
    theSrchStrg = theSrchStrg.toUpperCase();
    sName = sName.toUpperCase();
    theSrchStrg = theSrchStrg.replace("?", "&") theSrchStrg = theSrchStrg + "&";
    var theSrchToken = "&" + sName + "=";
    if (theSrchStrg.indexOf(theSrchToken) != -1) {
        var theSrchTokenLth = theSrchToken.length;
        var theSrchTokenLocStart = theSrchStrg.indexOf(theSrchToken) + theSrchTokenLth;
        var theLocOfNextAndSign = theSrchStrg.indexOf("&", theSrchTokenLocStart);
        theItmToRtn = unescape(sOrig.substring(theSrchTokenLocStart, theLocOfNextAndSign));
    }
    return unescape(theItmToRtn);
}

How to update nested state properties in React

Create a copy of the state:

let someProperty = JSON.parse(JSON.stringify(this.state.someProperty))

make changes in this object:

someProperty.flag = "false"

now update the state

this.setState({someProperty})

What are SP (stack) and LR in ARM?

SP is the stack register a shortcut for typing r13. LR is the link register a shortcut for r14. And PC is the program counter a shortcut for typing r15.

When you perform a call, called a branch link instruction, bl, the return address is placed in r14, the link register. the program counter pc is changed to the address you are branching to.

There are a few stack pointers in the traditional ARM cores (the cortex-m series being an exception) when you hit an interrupt for example you are using a different stack than when running in the foreground, you dont have to change your code just use sp or r13 as normal the hardware has done the switch for you and uses the correct one when it decodes the instructions.

The traditional ARM instruction set (not thumb) gives you the freedom to use the stack in a grows up from lower addresses to higher addresses or grows down from high address to low addresses. the compilers and most folks set the stack pointer high and have it grow down from high addresses to lower addresses. For example maybe you have ram from 0x20000000 to 0x20008000 you set your linker script to build your program to run/use 0x20000000 and set your stack pointer to 0x20008000 in your startup code, at least the system/user stack pointer, you have to divide up the memory for other stacks if you need/use them.

Stack is just memory. Processors normally have special memory read/write instructions that are PC based and some that are stack based. The stack ones at a minimum are usually named push and pop but dont have to be (as with the traditional arm instructions).

If you go to http://github.com/lsasim I created a teaching processor and have an assembly language tutorial. Somewhere in there I go through a discussion about stacks. It is NOT an arm processor but the story is the same it should translate directly to what you are trying to understand on the arm or most other processors.

Say for example you have 20 variables you need in your program but only 16 registers minus at least three of them (sp, lr, pc) that are special purpose. You are going to have to keep some of your variables in ram. Lets say that r5 holds a variable that you use often enough that you dont want to keep it in ram, but there is one section of code where you really need another register to do something and r5 is not being used, you can save r5 on the stack with minimal effort while you reuse r5 for something else, then later, easily, restore it.

Traditional (well not all the way back to the beginning) arm syntax:

...
stmdb r13!,{r5}
...temporarily use r5 for something else...
ldmia r13!,{r5}
...

stm is store multiple you can save more than one register at a time, up to all of them in one instruction.

db means decrement before, this is a downward moving stack from high addresses to lower addresses.

You can use r13 or sp here to indicate the stack pointer. This particular instruction is not limited to stack operations, can be used for other things.

The ! means update the r13 register with the new address after it completes, here again stm can be used for non-stack operations so you might not want to change the base address register, leave the ! off in that case.

Then in the brackets { } list the registers you want to save, comma separated.

ldmia is the reverse, ldm means load multiple. ia means increment after and the rest is the same as stm

So if your stack pointer were at 0x20008000 when you hit the stmdb instruction seeing as there is one 32 bit register in the list it will decrement before it uses it the value in r13 so 0x20007FFC then it writes r5 to 0x20007FFC in memory and saves the value 0x20007FFC in r13. Later, assuming you have no bugs when you get to the ldmia instruction r13 has 0x20007FFC in it there is a single register in the list r5. So it reads memory at 0x20007FFC puts that value in r5, ia means increment after so 0x20007FFC increments one register size to 0x20008000 and the ! means write that number to r13 to complete the instruction.

Why would you use the stack instead of just a fixed memory location? Well the beauty of the above is that r13 can be anywhere it could be 0x20007654 when you run that code or 0x20002000 or whatever and the code still functions, even better if you use that code in a loop or with recursion it works and for each level of recursion you go you save a new copy of r5, you might have 30 saved copies depending on where you are in that loop. and as it unrolls it puts all the copies back as desired. with a single fixed memory location that doesnt work. This translates directly to C code as an example:

void myfun ( void )
{
   int somedata;
}

In a C program like that the variable somedata lives on the stack, if you called myfun recursively you would have multiple copies of the value for somedata depending on how deep in the recursion. Also since that variable is only used within the function and is not needed elsewhere then you perhaps dont want to burn an amount of system memory for that variable for the life of the program you only want those bytes when in that function and free that memory when not in that function. that is what a stack is used for.

A global variable would not be found on the stack.

Going back...

Say you wanted to implement and call that function you would have some code/function you are in when you call the myfun function. The myfun function wants to use r5 and r6 when it is operating on something but it doesnt want to trash whatever someone called it was using r5 and r6 for so for the duration of myfun() you would want to save those registers on the stack. Likewise if you look into the branch link instruction (bl) and the link register lr (r14) there is only one link register, if you call a function from a function you will need to save the link register on each call otherwise you cant return.

...
bl myfun
    <--- the return from my fun returns here
...


myfun:
stmdb sp!,{r5,r6,lr}
sub sp,#4 <--- make room for the somedata variable
...
some code here that uses r5 and r6
bl more_fun <-- this modifies lr, if we didnt save lr we wouldnt be able to return from myfun
   <---- more_fun() returns here
...
add sp,#4 <-- take back the stack memory we allocated for the somedata variable
ldmia sp!,{r5,r6,lr}
mov pc,lr <---- return to whomever called myfun.

So hopefully you can see both the stack usage and link register. Other processors do the same kinds of things in a different way. for example some will put the return value on the stack and when you execute the return function it knows where to return to by pulling a value off of the stack. Compilers C/C++, etc will normally have a "calling convention" or application interface (ABI and EABI are names for the ones ARM has defined). if every function follows the calling convention, puts parameters it is passing to functions being called in the right registers or on the stack per the convention. And each function follows the rules as to what registers it does not have to preserve the contents of and what registers it has to preserve the contents of then you can have functions call functions call functions and do recursion and all kinds of things, so long as the stack does not go so deep that it runs into the memory used for globals and the heap and such, you can call functions and return from them all day long. The above implementation of myfun is very similar to what you would see a compiler produce.

ARM has many cores now and a few instruction sets the cortex-m series works a little differently as far as not having a bunch of modes and different stack pointers. And when executing thumb instructions in thumb mode you use the push and pop instructions which do not give you the freedom to use any register like stm it only uses r13 (sp) and you cannot save all the registers only a specific subset of them. the popular arm assemblers allow you to use

push {r5,r6}
...
pop {r5,r6}

in arm code as well as thumb code. For the arm code it encodes the proper stmdb and ldmia. (in thumb mode you also dont have the choice as to when and where you use db, decrement before, and ia, increment after).

No you absolutly do not have to use the same registers and you dont have to pair up the same number of registers.

push {r5,r6,r7}
...
pop {r2,r3}
...
pop {r1}

assuming there is no other stack pointer modifications in between those instructions if you remember the sp is going to be decremented 12 bytes for the push lets say from 0x1000 to 0x0FF4, r5 will be written to 0xFF4, r6 to 0xFF8 and r7 to 0xFFC the stack pointer will change to 0x0FF4. the first pop will take the value at 0x0FF4 and put that in r2 then the value at 0x0FF8 and put that in r3 the stack pointer gets the value 0x0FFC. later the last pop, the sp is 0x0FFC that is read and the value placed in r1, the stack pointer then gets the value 0x1000, where it started.

The ARM ARM, ARM Architectural Reference Manual (infocenter.arm.com, reference manuals, find the one for ARMv5 and download it, this is the traditional ARM ARM with ARM and thumb instructions) contains pseudo code for the ldm and stm ARM istructions for the complete picture as to how these are used. Likewise well the whole book is about the arm and how to program it. Up front the programmers model chapter walks you through all of the registers in all of the modes, etc.

If you are programming an ARM processor you should start by determining (the chip vendor should tell you, ARM does not make chips it makes cores that chip vendors put in their chips) exactly which core you have. Then go to the arm website and find the ARM ARM for that family and find the TRM (technical reference manual) for the specific core including revision if the vendor has supplied that (r2p0 means revision 2.0 (two point zero, 2p0)), even if there is a newer rev, use the manual that goes with the one the vendor used in their design. Not every core supports every instruction or mode the TRM tells you the modes and instructions supported the ARM ARM throws a blanket over the features for the whole family of processors that that core lives in. Note that the ARM7TDMI is an ARMv4 NOT an ARMv7 likewise the ARM9 is not an ARMv9. ARMvNUMBER is the family name ARM7, ARM11 without a v is the core name. The newer cores have names like Cortex and mpcore instead of the ARMNUMBER thing, which reduces confusion. Of course they had to add the confusion back by making an ARMv7-m (cortex-MNUMBER) and the ARMv7-a (Cortex-ANUMBER) which are very different families, one is for heavy loads, desktops, laptops, etc the other is for microcontrollers, clocks and blinking lights on a coffee maker and things like that. google beagleboard (Cortex-A) and the stm32 value line discovery board (Cortex-M) to get a feel for the differences. Or even the open-rd.org board which uses multiple cores at more than a gigahertz or the newer tegra 2 from nvidia, same deal super scaler, muti core, multi gigahertz. A cortex-m barely brakes the 100MHz barrier and has memory measured in kbytes although it probably runs of a battery for months if you wanted it to where a cortex-a not so much.

sorry for the very long post, hope it is useful.

Unzip All Files In A Directory

for i in *.zip; do
  newdir="${i:0:-4}" && mkdir "$newdir"
  unzip "$i" -d  "$newdir"
done

This will unzip all the zip archives into new folders named with the filenames of the zip archives.

a.zip b.zip c.zip will be unzipped into a b c folders respectively.

Javascript Src Path

This works:

<script src="/clock.js" type="text/javascript"></script>

The leading slash means the root directory of your site. Strictly speaking, language="Javascript" has been deprecated by type="text/javascript".

Capitalization of tags and attributes is also widely discouraged.

What does "collect2: error: ld returned 1 exit status" mean?

Include: #include<stdlib.h>

and use System("cls") instead of clrscr()

Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice

I've had a very similar issue using spring-boot-starter-data-redis. To my implementation there was offered a @Bean for RedisTemplate as follows:

@Bean
public RedisTemplate<String, List<RoutePlantCache>> redisTemplate(RedisConnectionFactory connectionFactory) {
    final RedisTemplate<String, List<RoutePlantCache>> template = new RedisTemplate<>();
    template.setConnectionFactory(connectionFactory);
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache.class));

    // Add some specific configuration here. Key serializers, etc.
    return template;
}

The fix was to specify an array of RoutePlantCache as following:

template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache[].class));

Below the exception I had:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `[...].RoutePlantCache` out of START_ARRAY token
 at [Source: (byte[])"[{ ... },{ ... [truncated 1478 bytes]; line: 1, column: 1]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1468) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1242) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1190) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeFromArray(BeanDeserializer.java:604) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:190) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:166) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3572) ~[jackson-databind-2.11.4.jar:2.11.4]

jQuery get the location of an element relative to window

function getWindowRelativeOffset(parentWindow, elem) {
        var offset = {
            left : 0,
            top : 0
        };
        // relative to the target field's document
        offset.left = elem.getBoundingClientRect().left;
        offset.top = elem.getBoundingClientRect().top;
        // now we will calculate according to the current document, this current
        // document might be same as the document of target field or it may be
        // parent of the document of the target field
        var childWindow = elem.document.frames.window;
        while (childWindow != parentWindow) {
            offset.left = offset.left + childWindow.frameElement.getBoundingClientRect().left;
            offset.top = offset.top + childWindow.frameElement.getBoundingClientRect().top;
            childWindow = childWindow.parent;
        }
        return offset;
    };

you can call it like this

getWindowRelativeOffset(top, inputElement);

I focus for IE only as per my requirement but similar can be done for other browsers

CSS Input field text color of inputted text

I always do input prompts, like this:

    <input style="color: #C0C0C0;" value="[email protected]" 
    onfocus="this.value=''; this.style.color='#000000'">

Of course, if your user fills in the field, changes focus and comes back to the field, the field will once again be cleared. If you do it like that, be sure that's what you want. You can make it a one time thing by setting a semaphore, like this:

    <script language = "text/Javascript"> 
    cleared[0] = cleared[1] = cleared[2] = 0; //set a cleared flag for each field
    function clearField(t){                   //declaring the array outside of the
    if(! cleared[t.id]){                      // function makes it static and global
        cleared[t.id] = 1;  // you could use true and false, but that's more typing
        t.value='';         // with more chance of typos
        t.style.color='#000000';
        }
    }
    </script>

Your <input> field then looks like this:

    <input id = 0; style="color: #C0C0C0;" value="[email protected]" 
    onfocus=clearField(this)>

How to find the mime type of a file in python?

I'm surprised that nobody has mentioned it but Pygments is able to make an educated guess about the mime-type of, particularly, text documents.

Pygments is actually a Python syntax highlighting library but is has a method that will make an educated guess about which of 500 supported document types your document is. i.e. c++ vs C# vs Python vs etc

import inspect

def _test(text: str):
    from pygments.lexers import guess_lexer
    lexer = guess_lexer(text)
    mimetype = lexer.mimetypes[0] if lexer.mimetypes else None
    print(mimetype)

if __name__ == "__main__":
    # Set the text to the actual defintion of _test(...) above
    text = inspect.getsource(_test)
    print('Text:')
    print(text)
    print()
    print('Result:')
    _test(text)

Output:

Text:
def _test(text: str):
    from pygments.lexers import guess_lexer
    lexer = guess_lexer(text)
    mimetype = lexer.mimetypes[0] if lexer.mimetypes else None
    print(mimetype)


Result:
text/x-python

Now, it's not perfect, but if you need to be able to tell which of 500 document formats are being used, this is pretty darn useful.

How to read multiple Integer values from a single line of input in Java?

You want to take the numbers in as a String and then use String.split(" ") to get the 3 numbers.

String input = scanner.nextLine();    // get the entire line after the prompt 
String[] numbers = input.split(" "); // split by spaces

Each index of the array will hold a String representation of the numbers which can be made to be ints by Integer.parseInt()

Escape Character in SQL Server

To keep the code easy to read, you can use square brackets [] to quote the string containing ' or vice versa .

Enable 'xp_cmdshell' SQL Server

Even if this question has resolved, I want to add my advice about that.... since as developer I ignored.

Is important to know that we're talking about MSSQL xp_cmdshell enabled is critical to security, as indicated in the message warning:

Blockquote SQL Server blocked access to procedure 'sys.xp_cmdshell' of component 'xp_cmdshell' because this component is turned off as part of the security configuration for this server. [...]

Leaving the service enabled is a kind of weakness, that for example in a web-app could reflect and execute commands SQL from an attacker. The popular CWE-89: SQL Injection it could be weakness in the our software, and therefore these type of scenarios could pave the way to possible attacks, such as CAPEC-108: Command Line Execution through SQL Injection

I hope to have done something pleasant, we Developers and Engineer do things with awareness and we will be safer!

Set Windows process (or user) memory limit

Depending on your applications, it might be easier to limit the memory the language interpreter uses. For example with Java you can set the amount of RAM the JVM will be allocated.

Otherwise it is possible to set it once for each process with the windows API

SetProcessWorkingSetSize Function

Android Button Onclick

Use Layout inflater method in your button click. it will change your current .xml to targeted .xml file. Google for layout inflater code.

error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)' -- Missing /var/run/mysqld/mysqld.sock

Okay just copy and paste these codes: This should be done in the terminal, inside a server, when your mysql database is not properly installed, and when you are getting this error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)'.

Stop MySql

sudo /etc/init.d/mysqld stop

Restart it or start it

sudo /etc/init.d/mysqld restart or sudo /etc/init.d/mysqld start

Make a link like this and give it to the system

ln -s /tmp/mysql.sock /var/lib/mysql/mysql.sock

Run a secure installation which guides all the process you need to do to configure mysql

/usr/bin/mysql_secure_installation

MySQL join with where clause

You need to put it in the join clause, not the where:

SELECT *
FROM categories
LEFT JOIN user_category_subscriptions ON 
    user_category_subscriptions.category_id = categories.category_id
    and user_category_subscriptions.user_id =1

See, with an inner join, putting a clause in the join or the where is equivalent. However, with an outer join, they are vastly different.

As a join condition, you specify the rowset that you will be joining to the table. This means that it evaluates user_id = 1 first, and takes the subset of user_category_subscriptions with a user_id of 1 to join to all of the rows in categories. This will give you all of the rows in categories, while only the categories that this particular user has subscribed to will have any information in the user_category_subscriptions columns. Of course, all other categories will be populated with null in the user_category_subscriptions columns.

Conversely, a where clause does the join, and then reduces the rowset. So, this does all of the joins and then eliminates all rows where user_id doesn't equal 1. You're left with an inefficient way to get an inner join.

Hopefully this helps!

Laravel 5 Failed opening required bootstrap/../vendor/autoload.php

Delete vendor folder and run composer install command. It is working 100%

Display Parameter(Multi-value) in Report

I didn't know about the join function - Nice! I had written a function that I placed in the code section (report properties->code tab:

Public Function ShowParmValues(ByVal parm as Parameter) as string
   Dim s as String 

      For i as integer = 0 to parm.Count-1
         s &= CStr(parm.value(i)) & IIF( i < parm.Count-1, ", ","")
      Next
  Return s
End Function  

What is the difference between readonly="true" & readonly="readonly"?

This is a property setting rather than a valued attribute

These property settings are values per see and don't need any assignments to them. When they are present, an element has this boolean property set to true, when they're absent they're false.

<input type="text" readonly />

It's actually browsers that are liberal toward value assignment to them. If you assign any value to them it will simply get ignored. Browsers will only see the presence of a particular property and ignore the value you're trying to assign to them.

This is of course good, because some frameworks don't have the ability to add such properties without providing their value along with them. Asp.net MVC Html helpers are one of them. jQuery used to be the same until version 1.6 where they added the concept of properties.

There are of course some implications that are related to XHTML as well, because attributes in XML need values in order to be well formed. But that's a different story. Hence browsers have to ignore value assignments.

Anyway. Never mind the value you're assigning to them as long as the name is correctly spelled so it will be detected by browsers. But for readability and maintainability it's better to assign meaningful values to them like:

readonly="true" <-- arguably best human readable
readonly="readonly"

as opposed to

readonly="johndoe"
readonly="01/01/2000"

that may confuse future developers maintaining your code and may interfere with future specification that may define more strict rules to such property settings.

Writing Python lists to columns in csv

If you are happy to use a 3rd party library, you can do this with Pandas. The benefits include seamless access to specialized methods and row / column labeling:

import pandas as pd

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]

df = pd.DataFrame(list(zip(*[list1, list2, list3]))).add_prefix('Col')

df.to_csv('file.csv', index=False)

print(df)

   Col0  Col1  Col2
0     1     4     7
1     2     5     8
2     3     6     9

How can I declare and use Boolean variables in a shell script?

POSIX (Portable Operating System Interface)

I miss here the key point, which is portability. That's why my header has POSIX in itself.

Essentially, all of the voted answers are correct, with the exception they are Bash-specific too much.

Basically, I only wish to add more information about portability.


  1. [ and ] brackets like in [ "$var" = true ] are not necessary, and you can omit them and use the test command directly:

    test "$var" = true && yourCodeIfTrue || yourCodeIfFalse
    

    Important note: I no longer recommend this as it's being slowly deprecated and more difficult to combine multiple statements.

  2. Imagine what those words true and false mean to the shell, test it yourself:

    echo $(( true ))
    
    0
    
    echo $(( false ))
    
    1
    

    But using quotes:

    echo $(( "true" ))
    
    bash: "true": syntax error: operand expected (error token is ""true"")
    sh (dash): sh: 1: arithmetic expression: expecting primary: ""true""
    

    The same goes for:

    echo $(( "false" ))
    

    The shell can't interpret it other than a string. I hope you are getting the idea of how good it is using proper keyword without quotes.

    But no one said it in previous answers.

  3. What does this mean? Well, several things.

    • You should get used to the Boolean keywords are actually treated like numbers, that is true = 0 and false = 1, remember all non-zero values are treated like false.

    • Since they are treated as numbers, you should treat them like that too, i.e. if you define variable say:

      var_bool=true
      echo "$var_bool"
      
       true
      

      you can create an opposite value of it with:

      var_bool=$(( 1 - $var_bool ))  # same as $(( ! $var_bool ))
      echo "$var_bool"
      
      1
      

    As you can see for yourself, the shell does print true string for the first time you use it, but since then, it all works via number 0 representing trueor 1 representing false, respectively.


Finally, what you should do with all that information

  • First, one good habit would be assigning 0 instead of true; 1 instead of false.

  • Second good habit would be to test if the variable is / isn't equal to zero:

    if [ "$var_bool" -eq 0 ]; then
         yourCodeIfTrue
    else
         yourCodeIfFalse
    fi
    

How to get the process ID to kill a nohup process?

If your application always uses the same port, you can kill all the processes in that port like this.

kill -9 $(lsof -t -i:8080)

Check if array is empty or null

I think it is dangerous to use $.isEmptyObject from jquery to check whether the array is empty, as @jesenko mentioned. I just met that problem.

In the isEmptyObject doc, it mentions:

The argument should always be a plain JavaScript Object

which you can determine by $.isPlainObject. The return of $.isPlainObject([]) is false.

Can anyone explain me StandardScaler?

The idea behind StandardScaler is that it will transform your data such that its distribution will have a mean value 0 and standard deviation of 1.
In case of multivariate data, this is done feature-wise (in other words independently for each column of the data).
Given the distribution of the data, each value in the dataset will have the mean value subtracted, and then divided by the standard deviation of the whole dataset (or feature in the multivariate case).

Overriding interface property type defined in Typescript d.ts file

I have created this type that allows me to easily override nested interfaces:

export type DeepPartialAny<T> = {
  [P in keyof T]?: T[P] extends Obj ? DeepPartialAny<T[P]> : any;
};

export type Override<A extends Obj, AOverride extends DeepPartialAny<A>> = { [K in keyof A]:
  AOverride[K] extends never
    ? A[K]
    : AOverride[K] extends Obj
    ? Override<A[K], AOverride[K]>
    : AOverride[K]
};

And then you can use it like that:

interface Foo {
  Bar: {
    Baz: string;
  };
}
type Foo2 = Override<Foo, { Bar: { Baz: number } }>;

const bar: Foo2['Bar']['Baz'] = 1; // number;

How to secure phpMyAdmin

Most likely, somewhere on your webserver will be an Alias directive like this;

Alias /phpmyadmin "c:/wamp/apps/phpmyadmin3.1.3.1/"

In my wampserver / localhost setup, it was in c:/wamp/alias/phpmyadmin.conf.

Just change the alias directive and you should be good to go.

How to debug apk signed for release?

I tried with the following and it's worked:

release {
            debuggable true
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

ORA-01830: date format picture ends before converting entire input string / Select sum where date query

What you have written in your sql string is a Timestamp not Date. You must convert it to Date or change type of database field to Timestamp for it to be seen correctly.

Set the maximum character length of a UITextField in Swift

This answer is for Swift 4, and is pretty straight forward with the ability to let backspace through.

func textField(_ textField: UITextField, 
               shouldChangeCharactersIn range: NSRange, 
               replacementString string: String) -> Bool {
    return textField.text!.count < 10 || string == ""
}

How to concatenate characters in java?

You need to tell the compiler you want to do String concatenation by starting the sequence with a string, even an empty one. Like so:

System.out.println("" + char1 + char2 + char3...);

Get a random boolean in python?

A new take on this question would involve the use of Faker which you can install easily with pip.

from faker import Factory

#----------------------------------------------------------------------
def create_values(fake):
    """"""
    print fake.boolean(chance_of_getting_true=50) # True
    print fake.random_int(min=0, max=1) # 1

if __name__ == "__main__":
    fake = Factory.create()
    create_values(fake)

Convert int to a bit array in .NET

I just ran into an instance where...

int val = 2097152;
var arr = Convert.ToString(val, 2).ToArray();
var myVal = arr[21];

...did not produce the results I was looking for. In 'myVal' above, the value stored in the array in position 21 was '0'. It should have been a '1'. I'm not sure why I received an inaccurate value for this and it baffled me until I found another way in C# to convert an INT to a bit array:

int val = 2097152;
var arr = new BitArray(BitConverter.GetBytes(val));
var myVal = arr[21];

This produced the result 'true' as a boolean value for 'myVal'.

I realize this may not be the most efficient way to obtain this value, but it was very straight forward, simple, and readable.

What are the differences between B trees and B+ trees?

Adegoke A, Amit

I guess one crucial point you people are missing is difference between data and pointers as explained in this section.

Pointer : pointer to other nodes.

Data :- In context of database indexes, data is just another pointer to real data (row) which reside somewhere else.

Hence in case of B tree each node has three information keys, pointers to data associated with the keys and pointer to child nodes.

In B+ tree internal node keep keys and pointers to child node while leaf node keep keys and pointers to associated data. This allows more number of key for a given size of node. Size of node is determined mainly by block size.

Advantage of having more key per node is explained well above so I will save my typing effort.

Get date from input form within PHP

Validate the INPUT.

$time = strtotime($_POST['dateFrom']);
if ($time) {
  $new_date = date('Y-m-d', $time);
  echo $new_date;
} else {
   echo 'Invalid Date: ' . $_POST['dateFrom'];
  // fix it.
}

Get a list of all git commits, including the 'lost' ones

I've had luck recovering the commit by looking at the reflog, which was located at .git/logs/HEAD

I then had to scoll down to the end of the file, and I found the commit I just lost.

Array to String PHP?

You can use json_encode()

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
?>

Later just use json_decode() to decode the string from your DB. Anything else is useless, JSON keeps the array relationship intact for later usage!

How do I install and use curl on Windows?

Install Chocolatey package manager for Windows. Once installed, simply enter choco install curl. Then you can use curl from a terminal.

Splitting comma separated string in a PL/SQL stored proc

I am not sure if this fits your oracle version. On my 10g I can use pipelined table functions:

set serveroutput on

create type number_list as table of number;

-- since you want this solution
create or replace function split_csv (i_csv varchar2) return number_list pipelined 
  is 
    mystring varchar2(2000):= i_csv;
  begin
    for r in
    ( select regexp_substr(mystring,'[^,]+',1,level) element
        from dual
     connect by level <= length(regexp_replace(mystring,'[^,]+')) + 1
    )
    loop
      --dbms_output.put_line(r.element);
      pipe row(to_number(r.element, '999999.99'));
    end loop;
  end;
/

insert into foo
select column_a,column_b from 
  (select column_value column_a, rownum rn from table(split_csv('0.75, 0.64, 0.56, 0.45'))) a 
 ,(select column_value column_b, rownum rn from table(split_csv('0.25, 0.5, 0.65, 0.8'))) b
 where a.rn = b.rn
;

Unable to open debugger port in IntelliJ IDEA

My assumption that this exception usually occurs when Tomcat is improperly closed and still holding the ports. Usually it is enough to kill any process listening to 1099 port. For Window 10:

netstat -aon | find "1099"


taskkill /F /PID $processId

How do I convert a factor into date format?

You were close. format= needs to be added to the as.Date call:

mydate <- factor("1/15/2006 0:00:00")
as.Date(mydate, format = "%m/%d/%Y")
## [1] "2006-01-15"

Can I use DIV class and ID together in CSS?

Yes, why not? Then CSS that applies to class "x" AND CSS that applies to ID "y" applies to the div.

MySQL - sum column value(s) based on row from the same table

SUM CASE using example:

    SELECT 
  DISTINCT(p.`ProductID`) AS ProductID,
  SUM(IF(p.`PaymentMethod`='Cash',Amount,0)) AS Cash_,
  SUM(IF(p.`PaymentMethod`='Check',Amount,0)) AS Check_,
  SUM(IF(p.`PaymentMethod`='Credit Card',Amount,0)) AS Credit_Card_,
  SUM( CASE PaymentMethod 
      WHEN 'Cash' THEN Amount
      WHEN 'Check' THEN Amount
      WHEN 'Credit Card' THEN Amount
     END) AS Total
FROM
  `payments` AS p 
GROUP BY p.`ProductID`;

SQL FIDDLE: http://www.sqlfiddle.com/#!9/23d07d/18

Result and Table view

How to make a movie out of images in python

Here is a minimal example using moviepy. For me this was the easiest solution.

import os
import moviepy.video.io.ImageSequenceClip
image_folder='folder_with_images'
fps=1

image_files = [image_folder+'/'+img for img in os.listdir(image_folder) if img.endswith(".png")]
clip = moviepy.video.io.ImageSequenceClip.ImageSequenceClip(image_files, fps=fps)
clip.write_videofile('my_video.mp4')

python pandas convert index to datetime

In my case, my dataframe has the following characteristics

<class 'pandas.core.frame.DataFrame'>
Index: 3040 entries, 15/12/2008 to  
Data columns (total 1 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   Close   3038 non-null   float64
dtypes: float64(1)
memory usage: 47.5+ KB

enter image description here

The first option data.index = pd.to_datetime(data.index) returned

ParserError: String does not contain a date: ParserError: String does not contain a date:

The second option: data.index.to_datetime() returned

AttributeError: 'Index' object has no attribute 'to_datetime'

It returned

Another option I have tested is. data.index = pd.to_datetime(data.index)

It returned: ParserError: String does not contain a date:

What could be my problem? Thanks

How to convert XML to java.util.Map and vice versa

Now it's 2017, The latest version of XStream requires a converter to make it works as your expected.

A converter supports nested map:

public class MapEntryConverter implements Converter {

    @Override
    public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext marshallingContext) {
        AbstractMap map = (AbstractMap) value;
        for (Object obj : map.entrySet()) {
            Map.Entry entry = (Map.Entry) obj;
            writer.startNode(entry.getKey().toString());
            Object val = entry.getValue();
            if (val instanceof Map) {
                marshal(val, writer, marshallingContext);
            } else if (null != val) {
                writer.setValue(val.toString());
            }
            writer.endNode();
        }
    }

    @Override
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext unmarshallingContext) {
        Map<String, Object> map = new HashMap<>();

        while(reader.hasMoreChildren()) {
            reader.moveDown();

            String key = reader.getNodeName(); // nodeName aka element's name
            String value = reader.getValue().replaceAll("\\n|\\t", "");
            if (StringUtils.isBlank(value)) {
                map.put(key, unmarshal(reader, unmarshallingContext));
            } else {
                map.put(key, value);
            }

            reader.moveUp();
        }

        return map;
    }

    @Override
    public boolean canConvert(Class clazz) {
        return AbstractMap.class.isAssignableFrom(clazz);
    }
} 

Are (non-void) self-closing tags valid in HTML5?

However -just for the record- this is invalid:

<address class="vcard">
  <svg viewBox="0 0 800 400">
    <rect width="800" height="400" fill="#000">
  </svg>
</address>

And a slash here would make it valid again:

    <rect width="800" height="400" fill="#000"/>

Tesseract OCR simple example

Try updating the line to:

ocr.Init(@"C:\", "eng", false); // the path here should be the parent folder of tessdata

Select the top N values by group

Since dplyr 1.0.0, the slice_max()/slice_min() functions were implemented:

mtcars %>%
 group_by(cyl) %>%
 slice_max(mpg, n = 2, with_ties = FALSE)

    mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1  33.9     4  71.1    65  4.22  1.84  19.9     1     1     4     1
2  32.4     4  78.7    66  4.08  2.2   19.5     1     1     4     1
3  21.4     6 258     110  3.08  3.22  19.4     1     0     3     1
4  21       6 160     110  3.9   2.62  16.5     0     1     4     4
5  19.2     8 400     175  3.08  3.84  17.0     0     0     3     2
6  18.7     8 360     175  3.15  3.44  17.0     0     0     3     2

The documentation on with_ties parameter:

Should ties be kept together? The default, TRUE, may return more rows than you request. Use FALSE to ignore ties, and return the first n rows.

What is the difference between a JavaBean and a POJO?

Java beans are special type of POJOs.

Specialities listed below with reason

enter image description here

set date in input type date

Datetimepicker always needs input format YYYY-MM-DD, it doesn't care about display format of your model, or about you local system datetime. But the output format of datetime picker is the your wanted (your local system). There is simple example in my post.

Creating a "logical exclusive or" operator in Java

Here is a var arg XOR method for java...

public static boolean XOR(boolean... args) {
  boolean r = false;
  for (boolean b : args) {
    r = r ^ b;
  }
  return r;
}

Enjoy

How to select a record and update it, with a single queryset in Django?

only in a case in serializer things, you can update in very simple way!

my_model_serializer = MyModelSerializer(
    instance=my_model, data=validated_data)
if my_model_serializer.is_valid():

    my_model_serializer.save()

only in a case in form things!

instance = get_object_or_404(MyModel, id=id)
form = MyForm(request.POST or None, instance=instance)
if form.is_valid():
    form.save()

ClassNotFoundException com.mysql.jdbc.Driver

I keep the mysql-connector jar with my project rather than in Javahome. As a result, you can be sure it can be found by being sure its in the local classpath. A big upside is that you you can more the project to another machine and not have to worry about (or forget) to set this up again. I personally like including it in version control.

Converting dd/mm/yyyy formatted string to Datetime

You need to use DateTime.ParseExact with format "dd/MM/yyyy"

DateTime dt=DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);

Its safer if you use d/M/yyyy for the format, since that will handle both single digit and double digits day/month. But that really depends if you are expecting single/double digit values.


Your date format day/Month/Year might be an acceptable date format for some cultures. For example for Canadian Culture en-CA DateTime.Parse would work like:

DateTime dt = DateTime.Parse("24/01/2013", new CultureInfo("en-CA"));

Or

System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-CA");
DateTime dt = DateTime.Parse("24/01/2013"); //uses the current Thread's culture

Both the above lines would work because the the string's format is acceptable for en-CA culture. Since you are not supplying any culture to your DateTime.Parse call, your current culture is used for parsing which doesn't support the date format. Read more about it at DateTime.Parse.


Another method for parsing is using DateTime.TryParseExact

DateTime dt;
if (DateTime.TryParseExact("24/01/2013", 
                            "d/M/yyyy", 
                            CultureInfo.InvariantCulture, 
                            DateTimeStyles.None,
    out dt))
{
    //valid date
}
else
{
    //invalid date
}

The TryParse group of methods in .Net framework doesn't throw exception on invalid values, instead they return a bool value indicating success or failure in parsing.

Notice that I have used single d and M for day and month respectively. Single d and M works for both single/double digits day and month. So for the format d/M/yyyy valid values could be:

  • "24/01/2013"
  • "24/1/2013"
  • "4/12/2013" //4 December 2013
  • "04/12/2013"

For further reading you should see: Custom Date and Time Format Strings

Get ID of element that called a function

You can use 'this' in event handler:

document.getElementById("preview").onmouseover = function() {
    alert(this.id);
}

Or pass event object to handler as follows:

document.getElementById("preview").onmouseover = function(evt) {
    alert(evt.target.id);
}

It's recommended to use attachEvent(for IE < 9)/addEventListener(IE9 and other browsers) to attach events. Example above is for brevity.

function myHandler(evt) {
    alert(evt.target.id);
}

var el = document.getElementById("preview");
if (el.addEventListener){
    el.addEventListener('click', myHandler, false); 
} else if (el.attachEvent){
    el.attachEvent('onclick', myHandler);
}

C++ auto keyword. Why is it magic?

The auto keyword specifies that the type of the variable that is being declared will be automatically deducted from its initializer. In case of functions, if their return type is auto then that will be evaluated by return type expression at runtime.

It can be very useful when we have to use the iterator. For e.g. for below code we can simply use the "auto" instead of writing the whole iterator syntax .

int main() 
{ 

// Initialize set 
set<int> s; 

s.insert(1); 
s.insert(4); 
s.insert(2); 
s.insert(5); 
s.insert(3); 

// iterator pointing to 
// position where 2 is 
auto pos = s.find(3); 

// prints the set elements 
cout << "The set elements after 3 are: "; 
for (auto it = pos; it != s.end(); it++) 
    cout << *it << " "; 

return 0; 
}

This is how we can use "auto" keyword

Disable same origin policy in Chrome

I use this sometimes, for posting a localhost front-end site to a localhost back-end API (e.g. React to an old .NET API). I created a separate shortcut on my Windows 10 desktop, so that it never is used for normal browsing, only for debugging locally. I did the following:-

  1. Right click on desktop, add new shortcut
  2. Add the target as "[PATH_TO_CHROME]\chrome.exe" --disable-web-security
  3. Click OK.

You will get a warning on load of this browser, that it is not secure, just take care with what you browser on it. I tend to rename this new shortcut on the desktop, something in capital, and move it away from my other icons, so it can't be confused for normal Chrome.

Hope this helps!

Copying formula to the next row when inserting a new row

Private Sub Worksheet_Change(ByVal Target As Range)

'data starts on row 3 which has the formulas
'the sheet is protected - input cells not locked - formula cells locked
'this routine is triggered on change of any cell on the worksheet so first check if
' it's a cell that we're interested in - and the row doesn't already have formulas
If Target.Column = 3 And Target.Row > 3 _
And Range("M" & Target.Row).Formula = "" Then

    On Error GoTo ERROR_OCCURRED

    'unprotect the sheet - otherwise can't copy and paste
    ActiveSheet.Unprotect
    'disable events - this prevents this routine from triggering again when
    'copy and paste below changes the cell values
    Application.EnableEvents = False

    'copy col D (with validation list) from row above to new row (not locked)
    Range("D" & Target.Row - 1).Copy
    Range("D" & Target.Row).PasteSpecial

    'copy col M to P (with formulas) from row above to new row
    Range("M" & Target.Row - 1 & ":P" & Target.Row - 1).Copy
    Range("M" & Target.Row).PasteSpecial

'make sure if an error occurs (or not) events are re-enabled and sheet re-protected

ERROR_OCCURRED:

    If Err.Number <> 0 Then
        MsgBox "An error occurred. Formulas may not have been copied." & vbCrLf & vbCrLf & _
            Err.Number & " - " & Err.Description
    End If

    're-enable events
    Application.EnableEvents = True
    're-protect the sheet
    ActiveSheet.Protect

    'put focus back on the next cell after routine was triggered
    Range("D" & Target.Row).Select

End If

End Sub

When does socket.recv(recv_size) return?

It'll have the same behavior as the underlying recv libc call see the man page for an official description of behavior (or read a more general description of the sockets api).

Debugging WebSocket in Google Chrome

The other answers cover the most common scenario: watch the content of the frames (Developer Tools -> Network tab -> Right click on the websocket connection -> frames).

If you want to know some more informations, like which sockets are currently open/idle or be able to close them you'll find this url useful

chrome://net-internals/#sockets

How do I get the last day of a month?

// Use any date you want, for the purpose of this example we use 1980-08-03.
var myDate = new DateTime(1980,8,3);
var lastDayOfMonth = new DateTime(myDate.Year, myDate.Month, DateTime.DaysInMonth(myDate.Year, myDate.Month));

iframe to Only Show a Certain Part of the Page

An <iframe> gives you a complete window to work with. The most direct way to do what you want is to have your server give you a complete page that only contains the fragment you want to show.

As an alternative, you could just use a simple <div> and use the jQuery "load" function to load the whole page and pluck out just the section you want:

$('#target-div').load('http://www.mywebsite.com/portfolio.php #portfolio-sports');

There may be other things you need to do, and a significant difference is that the content will become part of the main page instead of being segregated into a separate window.

How to monitor the memory usage of Node.js?

You can use node.js memoryUsage

const formatMemoryUsage = (data) => `${Math.round(data / 1024 / 1024 * 100) / 100} MB`

const memoryData = process.memoryUsage()

const memoryUsage = {
                rss: `${formatMemoryUsage(memoryData.rss)} -> Resident Set Size - total memory allocated for the process execution`,
                heapTotal: `${formatMemoryUsage(memoryData.heapTotal)} -> total size of the allocated heap`,
                heapUsed: `${formatMemoryUsage(memoryData.heapUsed)} -> actual memory used during the execution`,
                external: `${formatMemoryUsage(memoryData.external)} -> V8 external memory`,
}

console.log(memoryUsage)
/*
{
    "rss": "177.54 MB -> Resident Set Size - total memory allocated for the process execution",
    "heapTotal": "102.3 MB -> total size of the allocated heap",
    "heapUsed": "94.3 MB -> actual memory used during the execution",
    "external": "3.03 MB -> V8 external memory"
}
*/

C - error: storage size of ‘a’ isn’t known

Your struct is called struct xyx but a is of type struct xyz. Once you fix that, the output is 100.

#include <stdio.h>

struct xyx {
    int x;
    int y;
    char c;
    char str[20];
    int arr[2];
};

int main(void)
{
    struct xyx a;
    a.x = 100;
    printf("%d\n", a.x);
    return 0;
}

How to implement debounce in Vue2?

If you need a very minimalistic approach to this, I made one (originally forked from vuejs-tips to also support IE) which is available here: https://www.npmjs.com/package/v-debounce

Usage:

<input v-model.lazy="term" v-debounce="delay" placeholder="Search for something" />

Then in your component:

<script>
export default {
  name: 'example',
  data () {
    return {
      delay: 1000,
      term: '',
    }
  },
  watch: {
    term () {
      // Do something with search term after it debounced
      console.log(`Search term changed to ${this.term}`)
    }
  },
  directives: {
    debounce
  }
}
</script>

Eclipse CDT project built but "Launch Failed. Binary Not Found"

This happened to me and I found a solution, see if this works for you:

Once you have built your project with the hammer icon:

  1. select "Run".
  2. Run Configurations.
  3. Choose "C++ Application".
  4. Click on the "New Launch Configuration" icon on the top left of the open window.
  5. Select "Browse" under the C/C++ Application.
  6. Browse to the folder where you made your project initially.
  7. Enter the Debug folder.
  8. Click on the binary file with the same name as the project.
  9. Select "OK".
  10. Click "Apply" to confirm the link you just set.
  11. Close that window.

Afterwards you should be able to run the project as much as you'd like.

Hopefully this works for you.

Find duplicates and delete all in notepad++

You could use

Click TextFX ? Click TextFX Tools ? Click Sort lines case insensitive (at column) Duplicates and blank lines have been removed and the data has been sorted alphabetically.

as indicated above. However, the way I did it because I need to replace the duplicates by blank lines and not just remove the lines, once sorted alphabetically:

REPLACE:
((^.*$)(\n))(?=\k<1>)

by

$3

This will convert:

Shorts
Shorts
Shorts
Shorts
Shorts
Shorts Two Pack
Shorts Two Pack
Signature Braces
Signature Braces
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers

to:

Shorts

Shorts Two Pack

Signature Braces










Signature Cotton Trousers

That's how I did it because I specifically needed those lines.

How to have a transparent ImageButton: Android

Try using null for the background ...

android:background="@null"

Is ini_set('max_execution_time', 0) a bad idea?

At the risk of irritating you;

You're asking the wrong question. You don't need a reason NOT to deviate from the defaults, but the other way around. You need a reason to do so. Timeouts are absolutely essential when running a web server and to disable that setting without a reason is inherently contrary to good practice, even if it's running on a web server that happens to have a timeout directive of its own.

Now, as for the real answer; probably it doesn't matter at all in this particular case, but it's bad practice to go by the setting of a separate system. What if the script is later run on a different server with a different timeout? If you can safely say that it will never happen, fine, but good practice is largely about accounting for seemingly unlikely events and not unnecessarily tying together the settings and functionality of completely different systems. The dismissal of such principles is responsible for a lot of pointless incompatibilities in the software world. Almost every time, they are unforeseen.

What if the web server later is set to run some other runtime environment which only inherits the timeout setting from the web server? Let's say for instance that you later need a 15-year-old CGI program written in C++ by someone who moved to a different continent, that has no idea of any timeout except the web server's. That might result in the timeout needing to be changed and because PHP is pointlessly relying on the web server's timeout instead of its own, that may cause problems for the PHP script. Or the other way around, that you need a lesser web server timeout for some reason, but PHP still needs to have it higher.

It's just not a good idea to tie the PHP functionality to the web server because the web server and PHP are responsible for different roles and should be kept as functionally separate as possible. When the PHP side needs more processing time, it should be a setting in PHP simply because it's relevant to PHP, not necessarily everything else on the web server.

In short, it's just unnecessarily conflating the matter when there is no need to.

Last but not least, 'stillstanding' is right; you should at least rather use set_time_limit() than ini_set().

Hope this wasn't too patronizing and irritating. Like I said, probably it's fine under your specific circumstances, but it's good practice to not assume your circumstances to be the One True Circumstance. That's all. :)

How to convert 'binary string' to normal string in Python3?

Please, see oficial encode() and decode() documentation from codecs library. utf-8 is the default encoding for the functions, but there are severals standard encodings in Python 3, like latin_1 or utf_32.

What is the purpose of Node.js module.exports and how do you use it?

the refer link is like this:

exports = module.exports = function(){
    //....
}

the properties of exports or module.exports ,such as functions or variables , will be exposed outside

there is something you must pay more attention : don't override exports .

why ?

because exports just the reference of module.exports , you can add the properties onto the exports ,but if you override the exports , the reference link will be broken .

good example :

exports.name = 'william';

exports.getName = function(){
   console.log(this.name);
}

bad example :

exports = 'william';

exports = function(){
     //...
}

If you just want to exposed only one function or variable , like this:

// test.js
var name = 'william';

module.exports = function(){
    console.log(name);
}   

// index.js
var test = require('./test');
test();

this module only exposed one function and the property of name is private for the outside .

How to get elements with multiple classes

querySelectorAll with standard class selectors also works for this.

document.querySelectorAll('.class1.class2');

Python - Dimension of Data Frame

Summary of all ways to get info on dimensions of DataFrame or Series

There are a number of ways to get information on the attributes of your DataFrame or Series.

Create Sample DataFrame and Series

df = pd.DataFrame({'a':[5, 2, np.nan], 'b':[ 9, 2, 4]})
df

     a  b
0  5.0  9
1  2.0  2
2  NaN  4

s = df['a']
s

0    5.0
1    2.0
2    NaN
Name: a, dtype: float64

shape Attribute

The shape attribute returns a two-item tuple of the number of rows and the number of columns in the DataFrame. For a Series, it returns a one-item tuple.

df.shape
(3, 2)

s.shape
(3,)

len function

To get the number of rows of a DataFrame or get the length of a Series, use the len function. An integer will be returned.

len(df)
3

len(s)
3

size attribute

To get the total number of elements in the DataFrame or Series, use the size attribute. For DataFrames, this is the product of the number of rows and the number of columns. For a Series, this will be equivalent to the len function:

df.size
6

s.size
3

ndim attribute

The ndim attribute returns the number of dimensions of your DataFrame or Series. It will always be 2 for DataFrames and 1 for Series:

df.ndim
2

s.ndim
1

The tricky count method

The count method can be used to return the number of non-missing values for each column/row of the DataFrame. This can be very confusing, because most people normally think of count as just the length of each row, which it is not. When called on a DataFrame, a Series is returned with the column names in the index and the number of non-missing values as the values.

df.count() # by default, get the count of each column

a    2
b    3
dtype: int64


df.count(axis='columns') # change direction to get count of each row

0    2
1    2
2    1
dtype: int64

For a Series, there is only one axis for computation and so it just returns a scalar:

s.count()
2

Use the info method for retrieving metadata

The info method returns the number of non-missing values and data types of each column

df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
a    2 non-null float64
b    3 non-null int64
dtypes: float64(1), int64(1)
memory usage: 128.0 bytes

How to replace text in a column of a Pandas dataframe?

For anyone else arriving here from Google search on how to do a string replacement on all columns (for example, if one has multiple columns like the OP's 'range' column): Pandas has a built in replace method available on a dataframe object.

df.replace(',', '-', regex=True)

Source: Docs

Remove the complete styling of an HTML button/submit

I'm assuming that when you say 'click the button, it moves to the top a little' you're talking about the mouse down click state for the button, and that when you release the mouse click, it returns to its normal state? And that you're disabling the default rendering of the button by using:

input, button, submit { border:none; } 

If so..

Personally, I've found that you can't actually stop/override/disable this IE native action, which led me to change my markup a little to allow for this movement and not affect the overall look of the button for the various states.

This is my final mark-up:

_x000D_
_x000D_
<span class="your-button-class">_x000D_
    <span>_x000D_
        <input type="Submit" value="View Person">_x000D_
    </span>_x000D_
</span>
_x000D_
_x000D_
_x000D_

How to create unique keys for React elements?

I am using this:

<div key={+new Date() + Math.random()}>

C# : assign data to properties via constructor vs. instantiating

Object initializers are cool because they allow you to set up a class inline. The tradeoff is that your class cannot be immutable. Consider:

public class Album 
{
    // Note that we make the setter 'private'
    public string Name { get; private set; }
    public string Artist { get; private set; }
    public int Year { get; private set; }

    public Album(string name, string artist, int year)
    {
        this.Name = name;
        this.Artist = artist;
        this.Year = year;
    }
}

If the class is defined this way, it means that there isn't really an easy way to modify the contents of the class after it has been constructed. Immutability has benefits. When something is immutable, it is MUCH easier to determine that it's correct. After all, if it can't be modified after construction, then there is no way for it to ever be 'wrong' (once you've determined that it's structure is correct). When you create anonymous classes, such as:

new { 
    Name = "Some Name",
    Artist = "Some Artist",
    Year = 1994
};

the compiler will automatically create an immutable class (that is, anonymous classes cannot be modified after construction), because immutability is just that useful. Most C++/Java style guides often encourage making members const(C++) or final (Java) for just this reason. Bigger applications are just much easier to verify when there are fewer moving parts.

That all being said, there are situations when you want to be able quickly modify the structure of your class. Let's say I have a tool that I want to set up:

public void Configure(ConfigurationSetup setup);

and I have a class that has a number of members such as:

class ConfigurationSetup {
    public String Name { get; set; }
    public String Location { get; set; }
    public Int32 Size { get; set; }
    public DateTime Time { get; set; }

    // ... and some other configuration stuff... 
}

Using object initializer syntax is useful when I want to configure some combination of properties, but not neccesarily all of them at once. For example if I just want to configure the Name and Location, I can just do:

ConfigurationSetup setup = new ConfigurationSetup {
    Name = "Some Name",
    Location = "San Jose"
};

and this allows me to set up some combination without having to define a new constructor for every possibly permutation.

On the whole, I would argue that making your classes immutable will save you a great deal of development time in the long run, but having object initializer syntax makes setting up certain configuration permutations much easier.

PHP regular expression - filter number only

You could do something like this if you want only whole numbers.

function make_whole($v){
    $v = floor($v);
    if(is_numeric($v)){
      echo (int)$v;
      // if you want only positive whole numbers
      //echo (int)$v = abs($v);
    }
}

Remove Item from ArrayList

You can remove elements from ArrayList using ListIterator,

ListIterator listIterator = List_Of_Array.listIterator();

 /* Use void remove() method of ListIterator to remove an element from List.
     It removes the last element returned by next or previous methods.
 */
listIterator.next();

//remove element returned by last next method
listIterator.remove();//remove element at 1st position
listIterator.next();
listIterator.next();
listIterator.remove();//remove element at 3rd position
listIterator.next();
listIterator.next();
listIterator.remove();//remove element at 5th position

Connecting an input stream to an outputstream

You can use a circular buffer :

Code

// buffer all data in a circular buffer of infinite size
CircularByteBuffer cbb = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE);
class1.putDataOnOutputStream(cbb.getOutputStream());
class2.processDataFromInputStream(cbb.getInputStream());


Maven dependency

<dependency>
    <groupId>org.ostermiller</groupId>
    <artifactId>utils</artifactId>
    <version>1.07.00</version>
</dependency>


Mode details

http://ostermiller.org/utils/CircularBuffer.html

MVC 4 - how do I pass model data to a partial view?

Also, this could make it works:

@{
Html.RenderPartial("your view", your_model, ViewData);
}

or

@{
Html.RenderPartial("your view", your_model);
}

For more information on RenderPartial and similar HTML helpers in MVC see this popular StackOverflow thread

How to convert xml into array in php?

easy!

$xml = simplexml_load_string($xmlstring, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

Chart.js v2 - hiding grid lines

Please refer to the official documentation:

https://www.chartjs.org/docs/latest/axes/styling.html#grid-line-configuration

Below code changes would hide the gridLines:

        gridLines: {
            display:false
        }

enter image description here

Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop

Easiest way to deep clone Array or Object:

var dup_array = JSON.parse(JSON.stringify(original_array))

How do I include a pipe | in my linux find -exec command?

The job of interpreting the pipe symbol as an instruction to run multiple processes and pipe the output of one process into the input of another process is the responsibility of the shell (/bin/sh or equivalent).

In your example you can either choose to use your top level shell to perform the piping like so:

find -name 'file_*' -follow -type f -exec zcat {} \; | agrep -dEOE 'grep'

In terms of efficiency this results costs one invocation of find, numerous invocations of zcat, and one invocation of agrep.

This would result in only a single agrep process being spawned which would process all the output produced by numerous invocations of zcat.

If you for some reason would like to invoke agrep multiple times, you can do:

find . -name 'file_*' -follow -type f \
    -printf "zcat %p | agrep -dEOE 'grep'\n" | sh

This constructs a list of commands using pipes to execute, then sends these to a new shell to actually be executed. (Omitting the final "| sh" is a nice way to debug or perform dry runs of command lines like this.)

In terms of efficiency this results costs one invocation of find, one invocation of sh, numerous invocations of zcat and numerous invocations of agrep.

The most efficient solution in terms of number of command invocations is the suggestion from Paul Tomblin:

find . -name "file_*" -follow -type f -print0 | xargs -0 zcat | agrep -dEOE 'grep'

... which costs one invocation of find, one invocation of xargs, a few invocations of zcat and one invocation of agrep.

Measuring elapsed time with the Time module

For users that want better formatting,

import time
start_time = time.time()
# your script
elapsed_time = time.time() - start_time
time.strftime("%H:%M:%S", time.gmtime(elapsed_time))

will print out, for 2 seconds:

'00:00:02'

and for 7 minutes one second:

'00:07:01'

note that the minimum time unit with gmtime is seconds. If you need microseconds consider the following:

import datetime
start = datetime.datetime.now()
# some code
end = datetime.datetime.now()
elapsed = end - start
print(elapsed)
# or
print(elapsed.seconds,":",elapsed.microseconds) 

strftime documentation

Add target="_blank" in CSS

This is actually javascript but related/relevant because .querySelectorAll targets by CSS syntax:

var i_will_target_self = document.querySelectorAll("ul.menu li a#example")

this example uses css to target links in a menu with id = "example"

that creates a variable which is a collection of the elements we want to change, but we still have actually change them by setting the new target ("_blank"):

for (var i = 0; i < 5; i++) {
i_will_target_self[i].target = "_blank";
}

That code assumes that there are 5 or less elements. That can be changed easily by changing the phrase "i < 5."

read more here: http://xahlee.info/js/js_get_elements.html

post ajax data to PHP and return data

So what does count_votes look like? Is it a script? Anything that you want to get back from an ajax call can be retrieved using a simple echo (of course you could use JSON or xml, but for this simple example you would just need to output something in count_votes.php like:

$id = $_POST['id'];

function getVotes($id){
    // call your database here
    $query = ("SELECT votes FROM poll WHERE ID = $id");
    $result = @mysql_query($query);
    $row = mysql_fetch_row($result);

    return $row->votes;
}
$votes = getVotes($id);
echo $votes;

This is just pseudocode, but should give you the idea. What ever you echo from count_votes will be what is returned to "data" in your ajax call.

Rounding BigDecimal to *always* have two decimal places

value = value.setScale(2, RoundingMode.CEILING)

Meaning of .Cells(.Rows.Count,"A").End(xlUp).row

.Cells(.Rows.Count,"A").End(xlUp).row

I think the first dot in the parenthesis should not be there, I mean, you should write it in this way:

.Cells(Rows.Count,"A").End(xlUp).row

Before the Cells, you can write your worksheet name, for example:

Worksheets("sheet1").Cells(Rows.Count, 2).End(xlUp).row

The worksheet name is not necessary when you operate on the same worksheet.

SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable

In my case i had the error sdk location not found

What i did: I went to the cloned project from git opened the project directory opened the app directory inside the project copied the local.properties file and then pasted it in the project directory Then it worked

AcquireConnection method call to the connection manager <Excel Connection Manager> failed with error code 0xC0202009

I don't think it's 64/32 bit error. My Dev machine and DB server are 32bit. But I could make it work. I had to set Delay Validation property of Data Flow tasks to TRUE.

ADB Install Fails With INSTALL_FAILED_TEST_ONLY

add this line to your ‘gradle.properties’

android.injected.testOnly=false

How do I replace all line breaks in a string with <br /> elements?

If the accepted answer isn't working right for you then you might try.

str.replace(new RegExp('\n','g'), '<br />')

It worked for me.

Doctrine 2: Update query with query builder

I think you need to use Expr with ->set() (However THIS IS NOT SAFE and you shouldn't do it):

$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
        ->set('u.username', $qb->expr()->literal($username))
        ->set('u.email', $qb->expr()->literal($email))
        ->where('u.id = ?1')
        ->setParameter(1, $editId)
        ->getQuery();
$p = $q->execute();

It's much safer to make all your values parameters instead:

$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
        ->set('u.username', '?1')
        ->set('u.email', '?2')
        ->where('u.id = ?3')
        ->setParameter(1, $username)
        ->setParameter(2, $email)
        ->setParameter(3, $editId)
        ->getQuery();
$p = $q->execute();

What does $(function() {} ); do?

I think you may be confusing Javascript with jQuery methods. Vanilla or plain Javascript is something like:

function example() {
}

A function of that nature can be called at any time, anywhere.

jQuery (a library built on Javascript) has built in functions that generally required the DOM to be fully rendered before being called. The syntax for when this is completed is:

$(document).ready(function() {
});

So a jQuery function, which is prefixed with the $ or the word jQuery generally is called from within that method.

$(document).ready(function() {        
    // Assign all list items on the page to be the  color red.  
    //      This does not work until AFTER the entire DOM is "ready", hence the $(document).ready()
    $('li').css('color', 'red');   
});

The pseudo-code for that block is:

When the document object model $(document) is ready .ready(), call the following function function() { }. In that function, check for all <li>'s on the page $('li') and using the jQuery method .CSS() to set the CSS property "color" to the value "red" .css('color', 'red');

How to iterate over the file in python

This is probably because an empty line at the end of your input file.

Try this:

for x in f:
    try:
        print int(x.strip(),16)
    except ValueError:
        print "Invalid input:", x

How do I parse a URL query parameters, in Javascript?

Today (2.5 years after this answer) you can safely use Array.forEach. As @ricosrealm suggests, decodeURIComponent was used in this function.

function getJsonFromUrl(url) {
  if(!url) url = location.search;
  var query = url.substr(1);
  var result = {};
  query.split("&").forEach(function(part) {
    var item = part.split("=");
    result[item[0]] = decodeURIComponent(item[1]);
  });
  return result;
}

actually it's not that simple, see the peer-review in the comments, especially:

  • hash based routing (@cmfolio)
  • array parameters (@user2368055)
  • proper use of decodeURIComponent and non-encoded = (@AndrewF)
  • non-encoded + (added by me)

For further details, see MDN article and RFC 3986.

Maybe this should go to codereview SE, but here is safer and regexp-free code:

function getJsonFromUrl(url) {
  if(!url) url = location.href;
  var question = url.indexOf("?");
  var hash = url.indexOf("#");
  if(hash==-1 && question==-1) return {};
  if(hash==-1) hash = url.length;
  var query = question==-1 || hash==question+1 ? url.substring(hash) : 
  url.substring(question+1,hash);
  var result = {};
  query.split("&").forEach(function(part) {
    if(!part) return;
    part = part.split("+").join(" "); // replace every + with space, regexp-free version
    var eq = part.indexOf("=");
    var key = eq>-1 ? part.substr(0,eq) : part;
    var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
    var from = key.indexOf("[");
    if(from==-1) result[decodeURIComponent(key)] = val;
    else {
      var to = key.indexOf("]",from);
      var index = decodeURIComponent(key.substring(from+1,to));
      key = decodeURIComponent(key.substring(0,from));
      if(!result[key]) result[key] = [];
      if(!index) result[key].push(val);
      else result[key][index] = val;
    }
  });
  return result;
}

This function can parse even URLs like

var url = "?foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a",  "c",  "[x]":"b"]}

var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
  console.log(key,":",obj[key]);
}
/*
  0 : a a
  1 : c
  [x] : b
*/

Return multiple values from a function, sub or type?

I always approach returning more than one result from a function by always returning an ArrayList. By using an ArrayList I can return only one item, consisting of many multiple values, mixing between Strings and Integers.

Once I have the ArrayList returned in my main sub, I simply use ArrayList.Item(i).ToString where i is the index of the value I want to return from the ArrayList

An example:

 Public Function Set_Database_Path()
        Dim Result As ArrayList = New ArrayList
        Dim fd As OpenFileDialog = New OpenFileDialog()


        fd.Title = "Open File Dialog"
        fd.InitialDirectory = "C:\"
        fd.RestoreDirectory = True
        fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
        fd.FilterIndex = 2
        fd.Multiselect = False


        If fd.ShowDialog() = DialogResult.OK Then

            Dim Database_Location = Path.GetFullPath(fd.FileName)

            Dim Database_Connection_Var = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=""" & Database_Location & """"

            Result.Add(Database_Connection_Var)
            Result.Add(Database_Location)

            Return (Result)

        Else

            Return (Nothing)

        End If
    End Function

And then call the Function like this:

Private Sub Main_Load()
  Dim PathArray As ArrayList

            PathArray = Set_Database_Path()
            My.Settings.Database_Connection_String = PathArray.Item(0).ToString
            My.Settings.FilePath = PathArray.Item(1).ToString
            My.Settings.Save()
End Sub

convert big endian to little endian in C [without using provided func]

Will this work / be faster?

 uint32_t swapped, result;

((byte*)&swapped)[0] = ((byte*)&result)[3];
((byte*)&swapped)[1] = ((byte*)&result)[2];
((byte*)&swapped)[2] = ((byte*)&result)[1];
((byte*)&swapped)[3] = ((byte*)&result)[0];

HTML - Display image after selecting filename

Here You Go:

HTML

<!DOCTYPE html>
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
</style>
</head>
<body>
  <input type='file' onchange="readURL(this);" />
    <img id="blah" src="#" alt="your image" />
</body>
</html>

Script:

function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah')
                    .attr('src', e.target.result)
                    .width(150)
                    .height(200);
            };

            reader.readAsDataURL(input.files[0]);
        }
    }

Live Demo

Git: which is the default configured remote for branch?

the command to get the effective push remote for the branch, e.g., master, is:

git config branch.master.pushRemote || git config remote.pushDefault || git config branch.master.remote

Here's why (from the "man git config" output):

branch.name.remote [...] tells git fetch and git push which remote to fetch from/push to [...] [for push] may be overridden with remote.pushDefault (for all branches) [and] for the current branch [..] further overridden by branch.name.pushRemote [...]

For some reason, "man git push" only tells about branch.name.remote (even though it has the least precedence of the three) + erroneously states that if it is not set, push defaults to origin - it does not, it's just that when you clone a repo, branch.name.remote is set to origin, but if you remove this setting, git push will fail, even though you still have the origin remote

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

It fails "when trying to execute the function manually" because you have a different 'this'. This will refer not to the thing you have in mind when invoking the method manually, but something else, probably the window object, or whatever context object you have when invoking manually.

Show whitespace characters in Visual Studio Code

The option to make whitespace visible now appears as an option on the View menu, as "Toggle Render Whitespace" in version 1.15.1 of Visual Studio Code.

How to get cumulative sum

Late answer but showing one more possibility...

Cumulative Sum generation can be more optimized with the CROSS APPLY logic.

Works better than the INNER JOIN & OVER Clause when analyzed the actual query plan ...

/* Create table & populate data */
IF OBJECT_ID('tempdb..#TMP') IS NOT NULL
DROP TABLE #TMP 

SELECT * INTO #TMP 
FROM (
SELECT 1 AS id
UNION 
SELECT 2 AS id
UNION 
SELECT 3 AS id
UNION 
SELECT 4 AS id
UNION 
SELECT 5 AS id
) Tab


/* Using CROSS APPLY 
Query cost relative to the batch 17%
*/    
SELECT   T1.id, 
         T2.CumSum 
FROM     #TMP T1 
         CROSS APPLY ( 
         SELECT   SUM(T2.id) AS CumSum 
         FROM     #TMP T2 
         WHERE    T1.id >= T2.id
         ) T2

/* Using INNER JOIN 
Query cost relative to the batch 46%
*/
SELECT   T1.id, 
         SUM(T2.id) CumSum
FROM     #TMP T1
         INNER JOIN #TMP T2
                 ON T1.id > = T2.id
GROUP BY T1.id

/* Using OVER clause
Query cost relative to the batch 37%
*/
SELECT   T1.id, 
         SUM(T1.id) OVER( PARTITION BY id)
FROM     #TMP T1

Output:-
  id       CumSum
-------   ------- 
   1         1
   2         3
   3         6
   4         10
   5         15

Reflection: How to Invoke Method with parameters

I m invoking the weighted average through reflection. And had used method with more than one parameter.

Class cls = Class.forName(propFile.getProperty(formulaTyp));// reading class name from file

Object weightedobj = cls.newInstance(); // invoke empty constructor

Class<?>[] paramTypes = { String.class, BigDecimal[].class, BigDecimal[].class }; // 3 parameter having first is method name and other two are values and their weight
Method printDogMethod = weightedobj.getClass().getMethod("applyFormula", paramTypes); // created the object 
return BigDecimal.valueOf((Double) printDogMethod.invoke(weightedobj, formulaTyp, decimalnumber, weight)); calling the method

Android Relative Layout Align Center

If you want to make it center then use android:layout_centerVertical="true" in the TextView.

How can I represent 'Authorization: Bearer <token>' in a Swagger Spec (swagger.json)

Why "Accepted Answer" works... but it wasn't enough for me

This works in the specification. At least swagger-tools (version 0.10.1) validates it as a valid.

But if you are using other tools like swagger-codegen (version 2.1.6) you will find some difficulties, even if the client generated contains the Authentication definition, like this:

this.authentications = {
  'Bearer': {type: 'apiKey', 'in': 'header', name: 'Authorization'}
};

There is no way to pass the token into the header before method(endpoint) is called. Look into this function signature:

this.rootGet = function(callback) { ... }

This means that, I only pass the callback (in other cases query parameters, etc) without a token, which leads to a incorrect build of the request to server.

My alternative

Unfortunately, it's not "pretty" but it works until I get JWT Tokens support on Swagger.

Note: which is being discussed in

So, it's handle authentication like a standard header. On path object append an header paremeter:

swagger: '2.0'
info:
  version: 1.0.0
  title: Based on "Basic Auth Example"
  description: >
    An example for how to use Auth with Swagger.

host: localhost
schemes:
  - http
  - https
paths:
  /:
    get:
      parameters:
        - 
          name: authorization
          in: header
          type: string
          required: true
      responses:
        '200':
          description: 'Will send `Authenticated`'
        '403': 
          description: 'You do not have necessary permissions for the resource'

This will generate a client with a new parameter on method signature:

this.rootGet = function(authorization, callback) {
  // ...
  var headerParams = {
    'authorization': authorization
  };
  // ...
}

To use this method in the right way, just pass the "full string"

// 'token' and 'cb' comes from elsewhere
var header = 'Bearer ' + token;
sdk.rootGet(header, cb);

And works.

Pipe to/from the clipboard in Bash script

2018 answer

Use clipboard-cli. It works with macOS, Windows, Linux, OpenBSD, FreeBSD, and Android without any real issues.

Install it with:

npm install -g clipboard-cli

Then you can do:

echo foo | clipboard 

If you want, you can alias to cb by putting the following in your .bashrc, .bash_profile, or .zshrc:

alias cb=clipboard

Return JSON with error status code MVC

The thing that worked for me (and that I took from another stackoverflow response), is to set the flag:

Response.TrySkipIisCustomErrors = true;

Saving a select count(*) value to an integer (SQL Server)

If @myInt is zero it means no rows in the table: it would be NULL if never set at all.

COUNT will always return a row, even for no rows in a table.

Edit, Apr 2012: the rules for this are described in my answer here:Does COUNT(*) always return a result?

Your count/assign is correct but could be either way:

select @myInt = COUNT(*) from myTable
set @myInt = (select COUNT(*) from myTable)

However, if you are just looking for the existence of rows, (NOT) EXISTS is more efficient:

IF NOT EXISTS (SELECT * FROM myTable)

Displaying standard DataTables in MVC

This is not "wrong" at all, it's just not what the cool guys typically do with MVC. As an aside, I wish some of the early demos of ASP.NET MVC didn't try to cram in Linq-to-Sql at the same time. It's pretty awesome and well suited for MVC, sure, but it's not required. There is nothing about MVC that prevents you from using ADO.NET. For example:

Controller action:

public ActionResult Index()
{
    ViewData["Message"] = "Welcome to ASP.NET MVC!";

    DataTable dt = new DataTable("MyTable");
    dt.Columns.Add(new DataColumn("Col1", typeof(string)));
    dt.Columns.Add(new DataColumn("Col2", typeof(string)));
    dt.Columns.Add(new DataColumn("Col3", typeof(string)));

    for (int i = 0; i < 3; i++)
    {
        DataRow row = dt.NewRow();
        row["Col1"] = "col 1, row " + i;
        row["Col2"] = "col 2, row " + i;
        row["Col3"] = "col 3, row " + i;
        dt.Rows.Add(row);
    }

    return View(dt); //passing the DataTable as my Model
}

View: (w/ Model strongly typed as System.Data.DataTable)

<table border="1">
    <thead>
        <tr>
            <%foreach (System.Data.DataColumn col in Model.Columns) { %>
                <th><%=col.Caption %></th>
            <%} %>
        </tr>
    </thead>
    <tbody>
    <% foreach(System.Data.DataRow row in Model.Rows) { %>
        <tr>
            <% foreach (var cell in row.ItemArray) {%>
                <td><%=cell.ToString() %></td>
            <%} %>
        </tr>
    <%} %>         
    </tbody>
</table>

Now, I'm violating a whole lot of principles and "best-practices" of ASP.NET MVC here, so please understand this is just a simple demonstration. The code creating the DataTable should reside somewhere outside of the controller, and the code in the View might be better isolated to a partial, or html helper, to name a few ways you should do things.

You absolutely are supposed to pass objects to the View, if the view is supposed to present them. (Separation of concerns dictates the view shouldn't be responsible for creating them.) In this case I passed the DataTable as the actual view Model, but you could just as well have put it in ViewData collection. Alternatively you might make a specific IndexViewModel class that contains the DataTable and other objects, such as the welcome message.

I hope this helps!

Centering floating divs within another div

With Flexbox you can easily horizontally (and vertically) center floated children inside a div.

So if you have simple markup like so:

<div class="wpr">
    <span></span>
    <span></span>
    <span></span>
    <span></span>
    <span></span>
</div>

with CSS:

.wpr
{
    width: 400px;
    height: 100px;
    background: pink;
    padding: 10px 30px;
}

.wpr span
{
    width: 50px;
    height: 50px;
    background: green;
    float: left; /* **children floated left** */
    margin: 0 5px;
}

(This is the (expected - and undesirable) RESULT)

Now add the following rules to the wrapper:

display: flex;
justify-content: center; /* align horizontal */

and the floated children get aligned center (DEMO)

Just for fun, to get vertical alignment as well just add:

align-items: center; /* align vertical */

DEMO

Iterate over each line in a string in PHP

I would like to propose a significantly faster (and memory efficient) alternative: strtok rather than preg_split.

$separator = "\r\n";
$line = strtok($subject, $separator);

while ($line !== false) {
    # do something with $line
    $line = strtok( $separator );
}

Testing the performance, I iterated 100 times over a test file with 17 thousand lines: preg_split took 27.7 seconds, whereas strtok took 1.4 seconds.

Note that though the $separator is defined as "\r\n", strtok will separate on either character - and as of PHP4.1.0, skip empty lines/tokens.

See the strtok manual entry: http://php.net/strtok

How do you check current view controller class in Swift?

 var top = window?.rootViewController
            while ((top?.presentedViewController) != nil) {
                top = top?.presentedViewController
            }
            
            if !(type(of: top!) === CallingVC.self) {
                top?.performSegue(withIdentifier: "CallingVC", sender: call)
            }

How to bind Close command to a button

For .NET 4.5 SystemCommands class will do the trick (.NET 4.0 users can use WPF Shell Extension google - Microsoft.Windows.Shell or Nicholas Solution).

    <Window.CommandBindings>
        <CommandBinding Command="{x:Static SystemCommands.CloseWindowCommand}" 
                        CanExecute="CloseWindow_CanExec" 
                        Executed="CloseWindow_Exec" />
    </Window.CommandBindings>
    <!-- Binding Close Command to the button control -->
    <Button ToolTip="Close Window" Content="Close" Command="{x:Static SystemCommands.CloseWindowCommand}"/>

In the Code Behind you can implement the handlers like this:

    private void CloseWindow_CanExec(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = true;
    }

    private void CloseWindow_Exec(object sender, ExecutedRoutedEventArgs e)
    {
        SystemCommands.CloseWindow(this);
    }

How to give ASP.NET access to a private key in a certificate in the certificate store?

I figured out how to do this in Powershell that someone asked about:

$keyname=(((gci cert:\LocalMachine\my | ? {$_.thumbprint -like $thumbprint}).PrivateKey).CspKeyContainerInfo).UniqueKeyContainerName
$keypath = $env:ProgramData + “\Microsoft\Crypto\RSA\MachineKeys\”
$fullpath=$keypath+$keyname

$Acl = Get-Acl $fullpath
$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("IIS AppPool\$iisAppPoolName", "Read", "Allow")
$Acl.SetAccessRule($Ar)
Set-Acl $fullpath $Acl

Error: could not find function ... in R

If this occurs while you check your package (R CMD check), take a look at your NAMESPACE.

You can solve this by adding the following statement to the NAMESPACE:

exportPattern("^[^\\\\.]")

This exports everything that doesn't start with a dot ("."). This allows you to have your hidden functions, starting with a dot:

.myHiddenFunction <- function(x) cat("my hidden function")

How to change the background color of a UIButton while it's highlighted?

There is no need to override highlighted as computed property. You can use property observer to trigger background color change:

override var highlighted: Bool {
    didSet {
        backgroundColor = highlighted ? UIColor.lightGrayColor() : UIColor.whiteColor()
    }
}

Swift 4

override open var isHighlighted: Bool {
    didSet {
        backgroundColor = isHighlighted ? UIColor.lightGray : UIColor.white
    }
}

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

u should add a theme to ur all activities (u should add theme for all application in ur <application> in ur manifest) but if u have set different theme to ur activity u can use :

 android:theme="@style/Theme.AppCompat"

or each kind of AppCompat theme!

Git: can't undo local changes (error: path ... is unmerged)

You did it the wrong way around. You are meant to reset first, to unstage the file, then checkout, to revert local changes.

Try this:

$ git reset foo/bar.txt
$ git checkout foo/bar.txt

Merge or combine by rownames

Using merge and renaming your t vector as tt (see the PS of Andrie) :

merge(tt,z,by="row.names",all.x=TRUE)[,-(5:8)]

Now if you would work with dataframes instead of matrices, this would even become a whole lot easier :

z <- as.data.frame(z)
tt <- as.data.frame(tt)
merge(tt,z["symbol"],by="row.names",all.x=TRUE)

In Java, how to append a string more efficiently?

- Each time you append or do any modification with it, it creates a new String object.

- So use append() method of StringBuilder(If thread safety is not important), else use StringBuffer(If thread safety is important.), that will be efficient way to do it.

Principal Component Analysis (PCA) in Python

You can find a PCA function in the matplotlib module:

import numpy as np
from matplotlib.mlab import PCA

data = np.array(np.random.randint(10,size=(10,3)))
results = PCA(data)

results will store the various parameters of the PCA. It is from the mlab part of matplotlib, which is the compatibility layer with the MATLAB syntax

EDIT: on the blog nextgenetics I found a wonderful demonstration of how to perform and display a PCA with the matplotlib mlab module, have fun and check that blog!

What is the difference between lower bound and tight bound?

Θ-notation (theta notation) is called tight-bound because it's more precise than O-notation and Ω-notation (omega notation).

If I were lazy, I could say that binary search on a sorted array is O(n2), O(n3), and O(2n), and I would be technically correct in every case. That's because O-notation only specifies an upper bound, and binary search is bounded on the high side by all of those functions, just not very closely. These lazy estimates would be useless.

Θ-notation solves this problem by combining O-notation and Ω-notation. If I say that binary search is Θ(log n), that gives you more precise information. It tells you that the algorithm is bounded on both sides by the given function, so it will never be significantly faster or slower than stated.

How to access static resources when mapping a global front controller servlet on /*

With Spring 3.0.4.RELEASE and higher you can use

<mvc:resources mapping="/resources/**" location="/public-resources/"/>

As seen in Spring Reference.

How to find all positions of the maximum value in a list?

You can also use the numpy package:

import numpy as np
A = np.array(a)
maximum_indices = np.where(A==max(a))

This will return an numpy array of all the indices that contain the max value

if you want to turn this to a list:

maximum_indices_list = maximum_indices.tolist()

Mailto: Body formatting

Use %0D%0A for a line break in your body

Example (Demo):

<a href="mailto:[email protected]?subject=Suggestions&body=name:%0D%0Aemail:">test</a>?
                                                                  ^^^^^^

Using Google maps API v3 how do I get LatLng with a given address?

If you need to do this on the backend you can use the following URL structure:

https://maps.googleapis.com/maps/api/geocode/json?address=[STREET_ADDRESS]&key=[YOUR_API_KEY]

Sample PHP code using curl:

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, 'https://maps.googleapis.com/maps/api/geocode/json?address=' . rawurlencode($address) . '&key=' . $api_key);

curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);

$json = curl_exec($curl);

curl_close ($curl);

$obj = json_decode($json);

See additional documentation for more details and expected json response.

The docs provide sample output and will assist you in getting your own API key in order to be able to make requests to the Google Maps Geocoding API.

Pass a PHP array to a JavaScript function

In the following example you have an PHP array, then firstly create a JavaScript array by a PHP array:

<script type="javascript">
    day = new Array(<?php echo implode(',', $day); ?>);
    week = new Array(<?php echo implode(',',$week); ?>);
    month = new Array(<?php echo implode(',',$month); ?>);

    <!--  Then pass it to the JavaScript function:   -->

    drawChart(<?php echo count($day); ?>, day, week, month);
</script>

SQL Query for Logins

Have a look in the syslogins or sysusers tables in the master schema. Not sure if this still still around in more recent MSSQL versions though. In MSSQL 2005 there are views called sys.syslogins and sys.sysusers.

What is the difference between a symbolic link and a hard link?

From MSDN,

Symbolic link

A symbolic link is a file-system object that points to another file system object. The object being pointed to is called the target.

Symbolic links are transparent to users; the links appear as normal files or directories, and can be acted upon by the user or application in exactly the same manner.

Symbolic links are designed to aid in migration and application compatibility with UNIX operating systems. Microsoft has implemented its symbolic links to function just like UNIX links.

Symbolic links can either be absolute or relative links. Absolute links are links that specify each portion of the path name; relative links are determined relative to where relative–link specifiers are in a specified path

An example of Absolute Symbolic Link

X: "C:\alpha\beta\absLink\gamma\file"
Link: "absLink" maps to "\\machineB\share"
Modified Path: "\\machineB\share\gamma\file"

An example of Relative Symbolic Links

X: C:\alpha\beta\link\gamma\file
Link: "link" maps to "..\..\theta"
Modified Path: "C:\alpha\beta\..\..\theta\gamma\file"
Final Path: "C:\theta\gamma\file"

Hard link

A hard link is the file system representation of a file by which more than one path references a single file in the same volume.

To create a hard link in windows, navigate to where link is to be created and enter this command:

mklink /H Link_name target_path

Note that you can delete hard links any order, regardless of the order in which they were created. Also, hard links can not be created when

  • references are in different local drives
  • references include network drive. In other words, one of the references is a network drive
  • hard link to be created is in the same path as the target

Junction

NTFS supports another link type called junction. MSDN defines it as follows:

A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, and a junction can link directories located on different local volumes on the same computer. Otherwise, junctions operate identically to hard links.

The bolded parts in hard link section and junction section show the basic difference between the two.

Command to create a junction in windows, navigate to where link is to be created and then enter:

mklink /J link_name target_path

Dropping connected users in Oracle database

Users are all capitals in v$session (and data dictionary views). If you match with capitals you should find your session to kill.

SELECT s.sid, s.serial#, s.status, p.spid 
  FROM v$session s, v$process p 
 WHERE s.username = 'TEST' --<<<--
  AND p.addr(+) = s.paddr
 /

Pass actual SID and SERIAL# values for user TEST then drop user...:

ALTER SYSTEM KILL SESSION '<SID>, <SERIAL>'
/

@Html.DropDownListFor how to set default value

SelectListItem has a Selected property. If you are creating the SelectListItems dynamically, you can just set the one you want as Selected = true and it will then be the default.

SelectListItem defaultItem = new SelectListItem()
{
   Value = 1,
   Text = "Default Item",
   Selected = true
};

How to split a string and assign it to variables

There's are multiple ways to split a string :

  1. If you want to make it temporary then split like this:

_

import net package

host, port, err := net.SplitHostPort("0.0.0.1:8080")
if err != nil {
fmt.Println("Error is splitting : "+err.error());
//do you code here
}
fmt.Println(host, port)
  1. Split based on struct :

    • Create a struct and split like this

_

type ServerDetail struct {
    Host       string
    Port       string
    err        error
}

ServerDetail = net.SplitHostPort("0.0.0.1:8080") //Specific for Host and Port

Now use in you code like ServerDetail.Host and ServerDetail.Port

If you don't want to split specific string do it like this:

type ServerDetail struct {
    Host       string
    Port       string
}

ServerDetail = strings.Split([Your_String], ":") // Common split method

and use like ServerDetail.Host and ServerDetail.Port.

That's All.

Url.Action parameters?

you can returns a private collection named HttpValueCollection even the documentation says it's a NameValueCollection using the ParseQueryString utility. Then add the keys manually, HttpValueCollection do the encoding for you. And then just append the QueryString manually :

var qs = HttpUtility.ParseQueryString(""); 
qs.Add("name", "John")
qs.Add("contact", "calgary");
qs.Add("contact", "vancouver")

<a href="<%: Url.Action("GetByList", "Listing")%>?<%:qs%>">
    <span>People</span>
</a>

What is the difference between docker-compose ports vs expose

I totally agree with the answers before. I just like to mention that the difference between expose and ports is part of the security concept in docker. It goes hand in hand with the networking of docker. For example:

Imagine an application with a web front-end and a database back-end. The outside world needs access to the web front-end (perhaps on port 80), but only the back-end itself needs access to the database host and port. Using a user-defined bridge, only the web port needs to be opened, and the database application doesn’t need any ports open, since the web front-end can reach it over the user-defined bridge.

This is a common use case when setting up a network architecture in docker. So for example in a default bridge network, not ports are accessible from the outer world. Therefor you can open an ingresspoint with "ports". With using "expose" you define communication within the network. If you want to expose the default ports you don't need to define "expose" in your docker-compose file.

getting a checkbox array value from POST

Check out the implode() function as an alternative. This will convert the array into a list. The first param is how you want the items separated. Here I have used a comma with a space after it.

$invite = implode(', ', $_POST['invite']);
echo $invite;

How can I delete all Git branches which have been merged?

On Windows with git bash installed egrep -v will not work

git branch --merged | grep -E -v "(master|test|dev)" | xargs git branch -d

where grep -E -v is equivalent of egrep -v

Use -d to remove already merged branches or -D to remove unmerged branches