Programs & Examples On #Fatwire

where is create-react-app webpack config and files?

The files are located in your node_modules/react-scripts folder:

Webpack config:

https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/config/webpack.config.js

Start Script:

https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/scripts/start.js

Build Script:

https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/scripts/build.js

Test Script:

https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/scripts/test.js

and so on ...

Now, the purpose of CRA is not to worry about these.

From the documentation:

You don’t need to install or configure tools like Webpack or Babel. They are preconfigured and hidden so that you can focus on the code.

If you want to have access to the config files, you need to eject by running:

npm run eject

Note: this is a one-way operation. Once you eject, you can’t go back!

In most scenarios, it is best not to eject and try to find a way to make it work for you in another way.

If you need to override some of the config options, you can have a look at https://github.com/gsoft-inc/craco

Select a dummy column with a dummy value in SQL?

If you meant just ABC as simple value, answer above is the one that works fine.

If you meant concatenation of values of rows that are not selected by your main query, you will need to use a subquery.

Something like this may work:

SELECT t1.col1, 
t1.col2, 
(SELECT GROUP_CONCAT(col2 SEPARATOR '') FROM  Table1 t2 WHERE t2.col1 != 0) as col3 
FROM Table1 t1
WHERE t1.col1 = 0;

Actual syntax maybe a bit off though

Format timedelta to string

maybe:

>>> import datetime
>>> dt0 = datetime.datetime(1,1,1)
>>> td = datetime.timedelta(minutes=34, hours=12, seconds=56)
>>> (dt0+td).strftime('%X')
'12:34:56'
>>> (dt0+td).strftime('%M:%S')
'34:56'
>>> (dt0+td).strftime('%H:%M')
'12:34'
>>>

Raise an event whenever a property's value changed?

Raising an event when a property changes is precisely what INotifyPropertyChanged does. There's one required member to implement INotifyPropertyChanged and that is the PropertyChanged event. Anything you implemented yourself would probably be identical to that implementation, so there's no advantage to not using it.

Why use prefixes on member variables in C++ classes

I prefer postfix underscores, like such:

class Foo
{
   private:
      int bar_;

   public:
      int bar() { return bar_; }
};

How do I get the picture size with PIL?

Since scipy's imread is deprecated, use imageio.imread.

  1. Install - pip install imageio
  2. Use height, width, channels = imageio.imread(filepath).shape

Purge or recreate a Ruby on Rails database

Because in development , you will always want to recreate the database,you can define a rake task in your lib/tasks folder like that.

  namespace :db do
      task :all => [:environment, :drop, :create, :migrate] do
   end 
end

and in terminal you will run

rake db:all

it will rebuild your database

Adding space/padding to a UILabel

Swift 3

import UIKit

class PaddingLabel: UILabel {

   @IBInspectable var topInset: CGFloat = 5.0
   @IBInspectable var bottomInset: CGFloat = 5.0
   @IBInspectable var leftInset: CGFloat = 5.0
   @IBInspectable var rightInset: CGFloat = 5.0

   override func drawText(in rect: CGRect) {
      let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
      super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
   }

   override var intrinsicContentSize: CGSize {
      get {
         var contentSize = super.intrinsicContentSize
         contentSize.height += topInset + bottomInset
         contentSize.width += leftInset + rightInset
         return contentSize
      }
   }
}

Design DFA accepting binary strings divisible by a number 'n'

You can build DFA using simple modular arithmetics. We can interpret w which is a string of k-ary numbers using a following rule

V[0] = 0
V[i] = (S[i-1] * k) + to_number(str[i])

V[|w|] is a number that w is representing. If modify this rule to find w mod N, the rule becomes this.

V[0] = 0
V[i] = ((S[i-1] * k) + to_number(str[i])) mod N

and each V[i] is one of a number from 0 to N-1, which corresponds to each state in DFA. We can use this as the state transition.

See an example.

k = 2, N = 5

| V | (V*2 + 0) mod 5     | (V*2 + 1) mod 5     |
+---+---------------------+---------------------+
| 0 | (0*2 + 0) mod 5 = 0 | (0*2 + 1) mod 5 = 1 |
| 1 | (1*2 + 0) mod 5 = 2 | (1*2 + 1) mod 5 = 3 |
| 2 | (2*2 + 0) mod 5 = 4 | (2*2 + 1) mod 5 = 0 |
| 3 | (3*2 + 0) mod 5 = 1 | (3*2 + 1) mod 5 = 2 |
| 4 | (4*2 + 0) mod 5 = 3 | (4*2 + 1) mod 5 = 4 |

k = 3, N = 5

| V | 0 | 1 | 2 |
+---+---+---+---+
| 0 | 0 | 1 | 2 |
| 1 | 3 | 4 | 0 |
| 2 | 1 | 2 | 3 |
| 3 | 4 | 0 | 1 |
| 4 | 2 | 3 | 4 |

Now you can see a very simple pattern. You can actually build a DFA transition just write repeating numbers from left to right, from top to bottom, from 0 to N-1.

Which characters are valid/invalid in a JSON key name?

The following characters must be escaped in JSON data to avoid any problems:

  • " (double quote)
  • \ (backslash)
  • all control characters like \n, \t

JSON Parser can help you to deal with JSON.

Is unsigned integer subtraction defined behavior?

The result of a subtraction generating a negative number in an unsigned type is well-defined:

  1. [...] A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type. (ISO/IEC 9899:1999 (E) §6.2.5/9)

As you can see, (unsigned)0 - (unsigned)1 equals -1 modulo UINT_MAX+1, or in other words, UINT_MAX.

Note that although it does say "A computation involving unsigned operands can never overflow", which might lead you to believe that it applies only for exceeding the upper limit, this is presented as a motivation for the actual binding part of the sentence: "a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type." This phrase is not restricted to overflow of the upper bound of the type, and applies equally to values too low to be represented.

How do I include the string header?

The C++ string class is std::string. To use it you need to include the <string> header.

For the fundamentals of how to use std::string, you'll want to consult a good introductory C++ book.

How do I get SUM function in MySQL to return '0' if no values are found?

Can't get exactly what you are asking but if you are using an aggregate SUM function which implies that you are grouping the table.

The query goes for MYSQL like this

Select IFNULL(SUM(COLUMN1),0) as total from mytable group by condition

How to position a Bootstrap popover?

I solved this (partially) by adding some lines of code to the bootstrap css library. You will have to modify tooltip.js, tooltip.less, popover.js, and popover.less

in tooltip.js, add this case in the switch statement there

case 'bottom-right':
          tp = {top: pos.top + pos.height, left: pos.left + pos.width}
          break

in tooltip.less, add these two lines in .tooltip{}

&.bottom-right { margin-top:   -2px; }
&.bottom-right .tooltip-arrow { #popoverArrow > .bottom(); }

do the same in popover.js and popover.less. Basically, wherever you find code where other positions are mentioned, add your desired position accordingly.

As I mentioned earlier, this solved the problem partially. My problem now is that the little arrow of the popover does not appear.

note: if you want to have the popover in top-left, use top attribute of '.top' and left attribute of '.left'

How to prevent "The play() request was interrupted by a call to pause()" error?

After hours of seaching and working, i found perfect solution.

// Initializing values
var isPlaying = true;

// On video playing toggle values
video.onplaying = function() {
    isPlaying = true;
};

// On video pause toggle values
video.onpause = function() {
    isPlaying = false;
};

// Play video function
function playVid() {      
    if (video.paused && !isPlaying) {
        video.play();
    }
} 

// Pause video function
function pauseVid() {     
    if (!video.paused && isPlaying) {
        video.pause();
    }
}

After that, you can toggle play/pause as fast as you can, it will work properly.

How can I make content appear beneath a fixed DIV element?

There is (at least) one wayhack to get truly dynamic height without javascript: insert the menu twice:

  • Once in the flow to position the following elements, and
  • once fixed for the desired visual effect.

_x000D_
_x000D_
<div id="the-menu-container">_x000D_
    <nav class="position-static">...</nav>_x000D_
    <nav class="position-fixed">...</nav>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Depending on the rest of your site, you might have to tweak the z-index styles of the <nav> elements.

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

Typically when you see this message, it is benign. If it says

INFO: validateJarFile(/<webapp>/WEB-INF/lib/servlet-api-2.5.jar) - jar not loaded. 
See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

It means it is ignoring your servlet-api-2.5.jar because tomcat already has a built-in version of that jar, so it isn't going to be using yours. Typically this doesn't cause an issue.

If however it says WEB-INF/lib/my_jar.jar - jar not loaded...Offending class: javax/servlet/Servlet.class

then what you can do (in my instance, it's a shaded jar) is run

$ mvn dependency:tree

and discover that you have a transitive dependency on "something" that depends on a jar that is either servlet-api or something like it (ex: tomcat-servlet-api-9.0.0). So add an exclusion to that to your pom, ex: (in my case, tomcat, in your case, probably the ones mentioned in the other answers):

 <dependency>
    ...
    <exclusions>
      <exclusion>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-servlet</artifactId>
      </exclusion>
    </exclusions> 
</dependency>

Operator overloading on class templates

This helped me with the exact same problem.

Solution:

  1. Forward declare the friend function before the definition of the class itself. For example:

       template<typename T> class MyClass;  // pre-declare the template class itself
       template<typename T> std::ostream& operator<< (std::ostream& o, const MyClass <T>& x);
    
  2. Declare your friend function in your class with "<>" appended to the function name.

       friend std::ostream& operator<< <> (std::ostream& o, const Foo<T>& x);
    

linux shell script: split string, put them in an array then loop through them

sentence="one;two;three"
a="${sentence};"
while [ -n "${a}" ]
do
    echo ${a%%;*}
    a=${a#*;}
done

Pivoting rows into columns dynamically in Oracle

To deal with situations where there are a possibility of multiple values (v in your example), I use PIVOT and LISTAGG:

SELECT * FROM
(
  SELECT id, k, v
  FROM _kv 
)
PIVOT 
(
  LISTAGG(v ,',') 
  WITHIN GROUP (ORDER BY k) 
  FOR k IN ('name', 'age','gender','status')
)
ORDER BY id;

Since you want dynamic values, use dynamic SQL and pass in the values determined by running a select on the table data before calling the pivot statement.

How to parseInt in Angular.js

Option 1 (via controller):

angular.controller('numCtrl', function($scope, $window) {
   $scope.num = parseInt(num , 10);
}

Option 2 (via custom filter):

app.filter('num', function() {
    return function(input) {
       return parseInt(input, 10);
    }
});

{{(num1 | num) + (num2 | num)}}

Option 3 (via expression):

Declare this first in your controller:

$scope.parseInt = parseInt;

Then:

{{parseInt(num1)+parseInt(num2)}}

Option 4 (from raina77ow)

{{(num1-0) + (num2-0)}}

How do I change the font-size of an <option> element within <select>?

Like most form controls in HTML, the results of applying CSS to <select> and <option> elements vary a lot between browsers. Chrome, as you've found, won't let you apply and font styles to an <option> element directly --- if you do Inspect Element on it, you'll see the font-size: 14px declaration is crossed through as if it's been overridden by the cascade, but it's actually because Chrome is ignoring it.

However, Chrome will let you apply font styles to the <optgroup> element, so to achieve the result you want you can wrap all the <option>s in an <optgroup> and then apply your font styles to a .styled-select optgroup selector. If you want the optgroup sans-label, you may have to do some clever CSS with positioning or something to hide the white area at the top where the label would be shown, but that should be possible.

Forked to a new JSFiddle to show you what I mean:

http://jsfiddle.net/zRtbZ/

Get protocol + host name from URL

I know it's an old question, but I too encountered it today. Solved this with an one-liner:

import re
result = re.sub(r'(.*://)?([^/?]+).*', '\g<1>\g<2>', url)

Why both no-cache and no-store should be used in HTTP response?

From the HTTP 1.1 specification:

no-store:

The purpose of the no-store directive is to prevent the inadvertent release or retention of sensitive information (for example, on backup tapes). The no-store directive applies to the entire message, and MAY be sent either in a response or in a request. If sent in a request, a cache MUST NOT store any part of either this request or any response to it. If sent in a response, a cache MUST NOT store any part of either this response or the request that elicited it. This directive applies to both non- shared and shared caches. "MUST NOT store" in this context means that the cache MUST NOT intentionally store the information in non-volatile storage, and MUST make a best-effort attempt to remove the information from volatile storage as promptly as possible after forwarding it. Even when this directive is associated with a response, users might explicitly store such a response outside of the caching system (e.g., with a "Save As" dialog). History buffers MAY store such responses as part of their normal operation. The purpose of this directive is to meet the stated requirements of certain users and service authors who are concerned about accidental releases of information via unanticipated accesses to cache data structures. While the use of this directive might improve privacy in some cases, we caution that it is NOT in any way a reliable or sufficient mechanism for ensuring privacy. In particular, malicious or compromised caches might not recognize or obey this directive, and communications networks might be vulnerable to eavesdropping.

Singletons vs. Application Context in Android?

They're actually the same. There's one difference I can see. With Application class you can initialize your variables in Application.onCreate() and destroy them in Application.onTerminate(). With singleton you have to rely VM initializing and destroying statics.

smooth scroll to top

Came up with this solution:

function scrollToTop() {
let currentOffset = window.pageYOffset;
const arr = [];

for (let i = 100; i >= 0; i--) {
    arr.push(new Promise(res => {
            setTimeout(() => {
                    res(currentOffset * (i / 100));
                },
                2 * (100 - i))
        })
    );
}

arr.reduce((acc, curr, index, arr) => {
    return acc.then((res) => {
        if (typeof res === 'number')
            window.scrollTo(0, res)
        return curr
    })
}, Promise.resolve(currentOffset)).then(() => {
    window.scrollTo(0, 0)
})}

Html encode in PHP

Encode.php

<h1>Encode HTML CODE</h1>

<form action='htmlencodeoutput.php' method='post'>
<textarea rows='30' cols='100'name='inputval'></textarea>
<input type='submit'>
</form>

htmlencodeoutput.php

<?php

$code=bin2hex($_POST['inputval']); 
$spilt=chunk_split($code,2,"%");
$totallen=strlen($spilt);
 $sublen=$totallen-1;
 $fianlop=substr($spilt,'0', $sublen);
$output="<script>
document.write(unescape('%$fianlop'));
</script>";

?> 
<textarea rows='20' cols='100'><?php echo $output?> </textarea> 

You can encode HTML like this .

How to make a <ul> display in a horizontal row

#ul_top_hypers li {
  display: flex;
}

Setting background-image using jQuery CSS property

Here is my code:

$('body').css('background-image', 'url("/apo/1.jpg")');

Enjoy, friend

How to hide the keyboard when I press return key in a UITextField?

If you want to hide the keyboard for a particular keyboard use [self.view resignFirstResponder]; If you want to hide any keyboard from view use [self.view endEditing:true];

Python, print all floats to 2 decimal places in output

Format String Syntax.

https://docs.python.org/3/library/string.html#formatstrings

from math import pi
var1, var2, var3, var4 = pi, pi*2, pi*3, pi*4
'{:0.2f}, kg={:0.2f}, lb={:0.2f}, gal={:0.2f}'.format(var1, var2, var3, var4)

The output would be:

'3.14, kg=6.28, lb=9.42, gal=12.57'

Padding or margin value in pixels as integer using jQuery

Here's how you can get the surrounding dimentions:

var elem = $('#myId');

var marginTopBottom  = elem.outerHeight(true) - elem.outerHeight();
var marginLeftRight  = elem.outerWidth(true)  - elem.outerWidth();

var borderTopBottom  = elem.outerHeight() - elem.innerHeight();
var borderLeftRight  = elem.outerWidth()  - elem.innerWidth();

var paddingTopBottom  = elem.innerHeight() - elem.height();
var paddingLeftRight  = elem.innerWidth()  - elem.width();

Pay attention that each variable, paddingTopBottom for example, contains the sum of the margins on the both sides of the element; i.e., paddingTopBottom == paddingTop + paddingBottom. I wonder if there is a way to get them separately. Of course, if they are equal you can divide by 2 :)

Laravel 5.5 ajax call 419 (unknown status)

You have to get the csrf token..

$.ajaxSetup({
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  }
});

After doing same issue is rise ,Just Add this meta tag< meta name="csrf-token" content="{{ csrf_token() }}" >

After this also the error arise ,you can check the Ajax error. Then Also check the Ajax error

$.ajax({
    url: 'some_unknown_page.html',
    success: function (response) {
        $('#post').html(response.responseText);
    },
    error: function (jqXHR, exception) {
        var msg = '';
        if (jqXHR.status === 0) {
            msg = 'Not connect.\n Verify Network.';
        } else if (jqXHR.status == 404) {
            msg = 'Requested page not found. [404]';
        } else if (jqXHR.status == 500) {
            msg = 'Internal Server Error [500].';
        } else if (exception === 'parsererror') {
            msg = 'Requested JSON parse failed.';
        } else if (exception === 'timeout') {
            msg = 'Time out error.';
        } else if (exception === 'abort') {
            msg = 'Ajax request aborted.';
        } else {
            msg = 'Uncaught Error.\n' + jqXHR.responseText;
        }
        $('#post').html(msg);
    },
});

How to insert a line break <br> in markdown

Try adding 2 spaces (or a backslash \) after the first line:

[Name of link](url)
My line of text\

Visually:

[Name of link](url)<space><space>
My line of text\

Output:

<p><a href="url">Name of link</a><br>
My line of text<br></p>

Set div height equal to screen size

Using CSS {height: 100%;} matches the height of the parent. This could be anything, meaning smaller or bigger than the screen. Using {height: 100vh;} matches the height of the viewport.

.container {
    height: 100vh;
    overflow: auto;
}

According to Mozilla's official documents, 1vh is:

Equal to 1% of the height of the viewport's initial containing block.

Google maps Marker Label with multiple characters

A much simpler solution to this problem that allows letters, numbers and words as the label is the following code. More specifically, the line of code starting with "icon:". Any string or variable could be substituted for 'k'.

for (i = 0; i < locations.length; i++) 
      { 
      k = i + 1;
      marker = new google.maps.Marker({
      position: new google.maps.LatLng(locations[i][1], locations[i][2]),     
      map: map,
      icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=' + k + '|FF0000|000000'
});

--- the locations array holds the lat and long and k is the row number for the address I was mapping. In other words if I had a 100 addresses to map my marker labels would be 1 to 100.

Easy way to concatenate two byte arrays

Most straightforward:

byte[] c = new byte[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);

Rails params explained?

On the Rails side, params is a method that returns an ActionController::Parameters object. See https://stackoverflow.com/a/44070358/5462485

Format datetime in asp.net mvc 4

Client validation issues can occur because of MVC bug (even in MVC 5) in jquery.validate.unobtrusive.min.js which does not accept date/datetime format in any way. Unfortunately you have to solve it manually.

My finally working solution:

$(function () {
    $.validator.methods.date = function (value, element) {
        return this.optional(element) || moment(value, "DD.MM.YYYY", true).isValid();
    }
});

You have to include before:

@Scripts.Render("~/Scripts/jquery-3.1.1.js")
@Scripts.Render("~/Scripts/jquery.validate.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
@Scripts.Render("~/Scripts/moment.js")

You can install moment.js using:

Install-Package Moment.js

Using comma as list separator with AngularJS

You can use CSS to fix it too

<div class="some-container">
[ <span ng-repeat="something in somethings">{{something}}<span class="list-comma">, </span></span> ]
</div>

.some-container span:last-child .list-comma{
    display: none;
}

But Andy Joslin's answer is best

Edit: I changed my mind I had to do this recently and I ended up going with a join filter.

git revert back to certain commit

git reset --hard 4a155e5 Will move the HEAD back to where you want to be. There may be other references ahead of that time that you would need to remove if you don't want anything to point to the history you just deleted.

Node.js setting up environment specific configs to be used with everyauth

set environment variable in deployment server(ex: like NODE_ENV=production). You can access your environmental variable through process.env.NODE_ENV. Find the following config file for the global settings

const env = process.env.NODE_ENV || "development"

const configs = {
    base: {
        env,
        host: '0.0.0.0',
        port: 3000,
        dbPort: 3306,
        secret: "secretKey for sessions",
        dialect: 'mysql',
        issuer : 'Mysoft corp',
        subject : '[email protected]',
    },
    development: {
        port: 3000,
        dbUser: 'root',
        dbPassword: 'root',

    },
    smoke: {
        port: 3000,
        dbUser: 'root',
    },
    integration: {
        port: 3000,
        dbUser: 'root',
    },
    production: {
        port: 3000,
        dbUser: 'root',
    }
};

const config = Object.assign(configs.base, configs[env]);

module.exports= config;

base contains common config for all environments.

then import in other modules like

const config =  require('path/to/config.js')
console.log(config.port)

Happy Coding...

Multi-key dictionary in c#?

I've also used tuples as jason in his answer does. However, I suggest you simply define a tuple as a struct:

public struct Tuple<T1, T2> {
    public readonly T1 Item1;
    public readonly T2 Item2;
    public Tuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2;} 
}

public static class Tuple { // for type-inference goodness.
    public static Tuple<T1,T2> Create<T1,T2>(T1 item1, T2 item2) { 
        return new Tuple<T1,T2>(item1, item2); 
    }
}

You get immutability, .GetHashcode and .Equals for free, which (while you're waiting for C# 4.0) is nice 'n simple...

One warning however: the default GetHashcode implementation (sometimes) only considers the first field so make sure to make the first field the most discriminating or implement GetHashcode yourself (e.g. using FieldwiseHasher.Hash(this) from ValueUtils), otherwise you'll likely run into scalability issues.

Also, you get to avoid nulls which tend to complicate matters (and if you really want nulls, you just make your Tuple<> nullable). Slightly offtopic, am I the only one annoyed at the framework-level lack of support for non-null references? I work on large project, and occasionally a null creeps in somewhere it really shouldn't -- and hey presto, you get a nullreference exception -- but with a stack trace that points you to the reference's first usage, not the actually faulty code.

Of course, .NET 4.0 is pretty old by now; most of us can just use .NET 4.0's tuple.

Edit: to workaround the poor GetHashCode implementation that .NET provides for structs I've written ValueUtils, which also allows you to use real names for your multi-field keys; that means you might write something like:

sealed class MyValueObject : ValueObject<MyValueObject> {
    public DayOfWeek day;
    public string NamedPart;
    //properties work fine too
}

...which hopefully makes it easier to have human-readable names for data with value semantics, at least until some future version of C# implements proper tuples with named members; hopefully with decent hashcodes ;-).

How can I use threading in Python?

Given a function, f, thread it like this:

import threading
threading.Thread(target=f).start()

To pass arguments to f

threading.Thread(target=f, args=(a,b,c)).start()

How can I limit the visible options in an HTML <select> dropdown?

A minor but important modification to existing solutions aiming at preserving framework styling (i.e. Bootstrap): replace this.size=0 with this.removeAttribute('size').

<select class="custom-select" onmousedown="if(this.options.length>5){this.size=5}"
    onchange='this.blur()' onblur="this.removeAttribute('size')">
    <option>option1</option>
    <option>option2</option>
    <option>option3</option>
    <option>option4</option>
    <option>option5</option>
    <option>option6</option>
    <option>option7</option>
</select>

vagrant login as root by default

vagrant destroy
vagrant up

Please add this to vagrant file:

config.ssh.username = 'vagrant'
config.ssh.password = 'vagrant'
config.ssh.insert_key = 'true'

How to print a two dimensional array?

How about trying this?

public static void main (String [] args)
{
   int [] [] listTwo = new int [5][5];
    // 2 Dimensional array 
    int x = 0;
    int y = 0;
    while (x < 5) {
        listTwo[x][y] = (int)(Math.random()*10);

        while (y <5){
            listTwo [x] [y] = (int)(Math.random()*10);
            System.out.print(listTwo[x][y]+" | ");
            y++;                
        }
        System.out.println("");
        y=0;
        x++;
    }
}

How can I convert radians to degrees with Python?

Python includes two functions in the math package; radians converts degrees to radians, and degrees converts radians to degrees.

To match the output of your calculator you need:

>>> math.cos(math.radians(1))
0.9998476951563913

Note that all of the trig functions convert between an angle and the ratio of two sides of a triangle. cos, sin, and tan take an angle in radians as input and return the ratio; acos, asin, and atan take a ratio as input and return an angle in radians. You only convert the angles, never the ratios.

I want to exception handle 'list index out of range.'

For anyone interested in a shorter way:

gotdata = len(dlist)>1 and dlist[1] or 'null'

But for best performance, I suggest using False instead of 'null', then a one line test will suffice:

gotdata = len(dlist)>1 and dlist[1]

Retrofit and GET using parameters

@QueryMap worked for me instead of FieldMap

If you have a bunch of GET params, another way to pass them into your url is a HashMap.

class YourActivity extends Activity {

private static final String BASEPATH = "http://www.example.com";

private interface API {
    @GET("/thing")
    void getMyThing(@QueryMap Map<String, String> params, new Callback<String> callback);
}

public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.your_layout);

   RestAdapter rest = new RestAdapter.Builder().setEndpoint(BASEPATH).build();
   API service = rest.create(API.class);

   Map<String, String> params = new HashMap<String, String>();
   params.put("key1", "val1");
   params.put("key2", "val2");
   // ... as much as you need.

   service.getMyThing(params, new Callback<String>() {
       // ... do some stuff here.
   });
}
}

The URL called will be http://www.example.com/thing/?key1=val1&key2=val2

Angular File Upload

Complete example of File upload using Angular and nodejs(express)

HTML Code

            <div class="form-group">
                <label for="file">Choose File</label><br/>
                <input type="file" id="file" (change)="uploadFile($event.target.files)" multiple>
            </div>

TS Component Code

uploadFile(files) {
    console.log('files', files)
        var formData = new FormData();

    for(let i =0; i < files.length; i++){
      formData.append("files", files[i], files[i]['name']);
        }

    this.httpService.httpPost('/fileUpload', formData)
      .subscribe((response) => {
        console.log('response', response)
      },
        (error) => {
      console.log('error in fileupload', error)
       })
  }

Node Js code

fileUpload API controller

function start(req, res) {
fileUploadService.fileUpload(req, res)
    .then(fileUploadServiceResponse => {
        res.status(200).send(fileUploadServiceResponse)
    })
    .catch(error => {
        res.status(400).send(error)
    })
}

module.exports.start = start

Upload service using multer

const multer = require('multer') // import library
const moment = require('moment')
const q = require('q')
const _ = require('underscore')
const fs = require('fs')
const dir = './public'

/** Store file on local folder */
let storage = multer.diskStorage({
destination: function (req, file, cb) {
    cb(null, 'public')
},
filename: function (req, file, cb) {
    let date = moment(moment.now()).format('YYYYMMDDHHMMSS')
    cb(null, date + '_' + file.originalname.replace(/-/g, '_').replace(/ /g,     '_'))
}
})

/** Upload files  */
let upload = multer({ storage: storage }).array('files')

/** Exports fileUpload function */
module.exports = {
fileUpload: function (req, res) {
    let deferred = q.defer()

    /** Create dir if not exist */
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir)
        console.log(`\n\n ${dir} dose not exist, hence created \n\n`)
    }

    upload(req, res, function (err) {
        if (req && (_.isEmpty(req.files))) {
            deferred.resolve({ status: 200, message: 'File not attached', data: [] })
        } else {
            if (err) {
                deferred.reject({ status: 400, message: 'error', data: err })
            } else {
                deferred.resolve({
                    status: 200,
                    message: 'File attached',
                    filename: _.pluck(req.files,
                        'filename'),
                    data: req.files
                })
            }
        }
    })
    return deferred.promise
}
}

Error retrieving parent for item: No resource found that matches the given name after upgrading to AppCompat v23

Your compile SDK version must match the support library major version. This is the solution to your problem. You can check it easily in your Gradle Scripts in build.gradle file. Fx: if your compileSdkVersion is 23 your compile library must start at 23.

  compileSdkVersion 23
    buildToolsVersion "23.0.0"
    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 340
        versionName "3.4.0"
    }
dependencies {
    compile 'com.android.support:appcompat-v7:23.1.0'
    compile 'com.android.support:recyclerview-v7:23.0.1'
}

And always check that your Android Studoi has the supported API Level. You can check it in your Android SDK, like this: enter image description here

How can I get a list of Git branches, ordered by most recent commit?

I also needed colors, tags and remote references without any duplicates:

for ref in $(git for-each-ref --sort=-committerdate --format="%(refname)" refs/heads/ refs/remotes ); do git log -n1 $ref --pretty=format:"%Cgreen%cr%Creset %C(yellow)%d%Creset %C(bold blue)<%an>%Creset%n" | cat ; done | awk '! a[$0]++'

Because quoting can be hard, here is the alias for Bash:

alias glist='for ref in $(git for-each-ref --sort=-committerdate --format="%(refname)" refs/heads/ refs/remotes ); do git log -n1 $ref --pretty=format:"%Cgreen%cr%Creset %C(yellow)%d%Creset %C(bold blue)<%an>%Creset%n" | cat ; done | awk '"'! a["'$0'"]++'"

How to truncate the time on a DateTime object in Python?

I think this is what you're looking for...

>>> import datetime
>>> dt = datetime.datetime.now()
>>> dt = dt.replace(hour=0, minute=0, second=0, microsecond=0) # Returns a copy
>>> dt
datetime.datetime(2011, 3, 29, 0, 0)

But if you really don't care about the time aspect of things, then you should really only be passing around date objects...

>>> d_truncated = datetime.date(dt.year, dt.month, dt.day)
>>> d_truncated
datetime.date(2011, 3, 29)

SQL Data Reader - handling Null column values

You may use the conditional operator:

employee.FirstName = sqlreader["indexFirstName"] != DBNull.Value ? sqlreader[indexFirstName].ToString() : "";

How do I specify "close existing connections" in sql script

Go to management studio and do everything you describe, only instead of clicking OK, click on Script. It will show the code it will run which you can then incorporate in your scripts.

In this case, you want:

ALTER DATABASE [MyDatabase] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO

Arduino Nano - "avrdude: ser_open():system can't open device "\\.\COM1": the system cannot find the file specified"

Instead of changing the COM port in Device manager, if you're using the Arduino software, I had to set the port in Tools > Port menu.

enter image description here

<img>: Unsafe value used in a resource URL context

Use Safe Pipe to fix it.

  • Create a safe pipe if u haven't any.

    ng g pipe safe

  • add Safe pipe in app.module.ts

    declarations: [SafePipe]

  • declare safe pipe in your ts

Import Dom Sanitizer and Safe Pipe to access url safely

import { Pipe, PipeTransform} from '@angular/core';
import { DomSanitizer } from "@angular/platform-browser";

@Pipe({ name: 'safe' })

export class SafePipe implements PipeTransform {

constructor(private sanitizer: DomSanitizer) { }
transform(url) {
 return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }
}
  • Add safe with src url

    <img width="900" height="500" [src]="link | safe"/>

Create code first, many to many, with additional fields in association table

TLDR; (semi-related to an EF editor bug in EF6/VS2012U5) if you generate the model from DB and you cannot see the attributed m:m table: Delete the two related tables -> Save .edmx -> Generate/add from database -> Save.

For those who came here wondering how to get a many-to-many relationship with attribute columns to show in the EF .edmx file (as it would currently not show and be treated as a set of navigational properties), AND you generated these classes from your database table (or database-first in MS lingo, I believe.)

Delete the 2 tables in question (to take the OP example, Member and Comment) in your .edmx and add them again through 'Generate model from database'. (i.e. do not attempt to let Visual Studio update them - delete, save, add, save)

It will then create a 3rd table in line with what is suggested here.

This is relevant in cases where a pure many-to-many relationship is added at first, and the attributes are designed in the DB later.

This was not immediately clear from this thread/Googling. So just putting it out there as this is link #1 on Google looking for the issue but coming from the DB side first.

How to make a rest post call from ReactJS code?

Here is a util function modified (another post on stack) for get and post both. Make Util.js file.

let cachedData = null;
let cachedPostData = null;

const postServiceData = (url, params) => {
    console.log('cache status' + cachedPostData );
    if (cachedPostData === null) {
        console.log('post-data: requesting data');
        return fetch(url, {
            method: 'POST',
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(params)
          })
        .then(response => {
            cachedPostData = response.json();
            return cachedPostData;
        });
    } else {
        console.log('post-data: returning cachedPostData data');
        return Promise.resolve(cachedPostData);
    }
}

const getServiceData = (url) => {
    console.log('cache status' + cachedData );
    if (cachedData === null) {
        console.log('get-data: requesting data');
        return fetch(url, {})
        .then(response => {
            cachedData = response.json();
            return cachedData;
        });
    } else {
        console.log('get-data: returning cached data');
        return Promise.resolve(cachedData);
    }
};

export  { getServiceData, postServiceData };

Usage like below in another component

import { getServiceData, postServiceData } from './../Utils/Util';

constructor(props) {
    super(props)
    this.state = {
      datastore : []
    }
  }

componentDidMount = () => {  
    let posturl = 'yoururl'; 
    let getdataString = { name: "xys", date:"today"};  
    postServiceData(posturl, getdataString)
      .then(items => { 
        this.setState({ datastore: items }) 
      console.log(items);   
    });
  }

Taking multiple inputs from user in python

You can try this.

import sys

for line in sys.stdin:
    j= int(line[0])
    e= float(line[1])
    t= str(line[2])

For details, please review,

https://en.wikibooks.org/wiki/Python_Programming/Input_and_Output#Standard_File_Objects

What's the difference between JPA and Hibernate?

Java - its independence is not only from the operating system, but also from the vendor.

Therefore, you should be able to deploy your application on different application servers. JPA is implemented in any Java EE- compliant application server and it allows to swap application servers, but then the implementation is also changing. A Hibernate application may be easier to deploy on a different application server.

Handling a Menu Item Click Event - Android

in addition to the options shown in your question, there is the possibility of implementing the action directly in your xml file from the menu, for example:

<item
   android:id="@+id/OK_MENU_ITEM"
   android:onClick="showMsgDirectMenuXml" />

And for your Java (Activity) file, you need to implement a public method with a single parameter of type MenuItem, for example:

 private void showMsgDirectMenuXml(MenuItem item) {
    Toast toast = Toast.makeText(this, "OK", Toast.LENGTH_LONG);
    toast.show();
  }

NOTE: This method will have behavior similar to the onOptionsItemSelected (MenuItem item)

What underlies this JavaScript idiom: var self = this?

See this article on alistapart.com. (Ed: The article has been updated since originally linked)

self is being used to maintain a reference to the original this even as the context is changing. It's a technique often used in event handlers (especially in closures).

Edit: Note that using self is now discouraged as window.self exists and has the potential to cause errors if you are not careful.

What you call the variable doesn't particularly matter. var that = this; is fine, but there's nothing magic about the name.

Functions declared inside a context (e.g. callbacks, closures) will have access to the variables/function declared in the same scope or above.

For example, a simple event callback:

_x000D_
_x000D_
function MyConstructor(options) {_x000D_
  let that = this;_x000D_
_x000D_
  this.someprop = options.someprop || 'defaultprop';_x000D_
_x000D_
  document.addEventListener('click', (event) => {_x000D_
    alert(that.someprop);_x000D_
  });_x000D_
}_x000D_
_x000D_
new MyConstructor({_x000D_
  someprop: "Hello World"_x000D_
});
_x000D_
_x000D_
_x000D_

How to convert any date format to yyyy-MM-dd

Convert your string to DateTime and then use DateTime.ToString("yyyy-MM-dd");

DateTime temp = DateTime.ParseExact(sourceDate, "dd-MM-yyyy", CultureInfo.InvariantCulture);
string str = temp.ToString("yyyy-MM-dd");

MVC pattern on Android

There is no universally unique MVC pattern. MVC is a concept rather than a solid programming framework. You can implement your own MVC on any platform. As long as you stick to the following basic idea, you are implementing MVC:

  • Model: What to render
  • View: How to render
  • Controller: Events, user input

Also think about it this way: When you program your model, the model should not need to worry about the rendering (or platform specific code). The model would say to the view, I don't care if your rendering is Android or iOS or Windows Phone, this is what I need you to render. The view would only handle the platform-specific rendering code.

This is particularly useful when you use Mono to share the model in order to develop cross-platform applications.

How to sort a dataFrame in python pandas by two or more columns?

As of the 0.17.0 release, the sort method was deprecated in favor of sort_values. sort was completely removed in the 0.20.0 release. The arguments (and results) remain the same:

df.sort_values(['a', 'b'], ascending=[True, False])

You can use the ascending argument of sort:

df.sort(['a', 'b'], ascending=[True, False])

For example:

In [11]: df1 = pd.DataFrame(np.random.randint(1, 5, (10,2)), columns=['a','b'])

In [12]: df1.sort(['a', 'b'], ascending=[True, False])
Out[12]:
   a  b
2  1  4
7  1  3
1  1  2
3  1  2
4  3  2
6  4  4
0  4  3
9  4  3
5  4  1
8  4  1

As commented by @renadeen

Sort isn't in place by default! So you should assign result of the sort method to a variable or add inplace=True to method call.

that is, if you want to reuse df1 as a sorted DataFrame:

df1 = df1.sort(['a', 'b'], ascending=[True, False])

or

df1.sort(['a', 'b'], ascending=[True, False], inplace=True)

nginx upload client_max_body_size issue

nginx "fails fast" when the client informs it that it's going to send a body larger than the client_max_body_size by sending a 413 response and closing the connection.

Most clients don't read responses until the entire request body is sent. Because nginx closes the connection, the client sends data to the closed socket, causing a TCP RST.

If your HTTP client supports it, the best way to handle this is to send an Expect: 100-Continue header. Nginx supports this correctly as of 1.2.7, and will reply with a 413 Request Entity Too Large response rather than 100 Continue if Content-Length exceeds the maximum body size.

Difference between nVidia Quadro and Geforce cards?

Hardware wise the Quadro and GeForce cards are often idential. Indeed it is sometimes possible to convert some models from GeForce into Quadro by simply uploading new firmware and changing a couple resistor jumpers.

The difference is in the intended market and hence cost.

Quadro cards are intended for CAD. High end CAD software still uses OpenGL, whereas games and lower end CAD software use Direct3D (aka DirectX).

Quadro cards simply have firmware that is optimised for OpenGL. In the early days OpenGL was better and faster than Direct3D but now there is little difference. Gaming cards only support a very limited set of OpenGL, hence they don't run it very well.

CAD companies, e.g. Dassault with SolidWorks actively push high end cards by offering no support for DirectX with any level of performance.

Other CAD companies such as Altium, with Altium Designer, made the decision that forcing their customers to buy more expensive cards is not worthwhile when Direct3D is as good (if not better these days) than OpenGL.

Because of the cost, there are often other differences in the hardware, such as less use of overclocking, more memory etc, but these have relatively minor effects compared with the firmware support.

How to start jenkins on different port rather than 8080 using command prompt in Windows?

Open Command Prompt as Administrator in Windows . Go to the directory where Jenkins is installed. and stop the Jenkins service first, using jenkins.exe stop

type the command to change the port using, java -jar jenkins.war --httpPort=9090 (enter the port number you want to use).

and at-last, restart the Jenkins services, using jenkins.exe restart

java, get set methods

To understand get and set, it's all related to how variables are passed between different classes.

The get method is used to obtain or retrieve a particular variable value from a class.

A set value is used to store the variables.

The whole point of the get and set is to retrieve and store the data values accordingly.

What I did in this old project was I had a User class with my get and set methods that I used in my Server class.

The User class's get set methods:

public int getuserID()
    {
        //getting the userID variable instance
        return userID;
    }
    public String getfirstName()
    {
        //getting the firstName variable instance
        return firstName;
    }
    public String getlastName()
    {
        //getting the lastName variable instance
        return lastName;
    }
    public int getage()
    {
        //getting the age variable instance
        return age;
    }

    public void setuserID(int userID)
    {
        //setting the userID variable value
        this.userID = userID;
    }
    public void setfirstName(String firstName)
    {
        //setting the firstName variable text
        this.firstName = firstName;
    }
    public void setlastName(String lastName)
    {
        //setting the lastName variable text
        this.lastName = lastName;
    }
    public void setage(int age)
    {
        //setting the age variable value
        this.age = age;
    }
}

Then this was implemented in the run() method in my Server class as follows:

//creates user object
                User use = new User(userID, firstName, lastName, age);
                //Mutator methods to set user objects
                use.setuserID(userID);
                use.setlastName(lastName);
                use.setfirstName(firstName);               
                use.setage(age); 

Can you require two form fields to match with HTML5?

The answers that use pattern and a regex write the user's password into the input properties as plain text pattern='mypassword'. This will only be visible if developer tools are open but it still doesn't seem like a good idea.

Another issue with using pattern to check for a match is that you are likely to want to use pattern to check that the password is of the right form, e.g. mixed letters and numbers.

I also think these methods won't work well if the user switches between inputs.

Here's my solution which uses a bit more JavaScript but performs a simple equality check when either input is updated and then sets a custom HTML validity. Both inputs can still be tested for a pattern such as email format or password complexity.

For a real page you would change the input types to 'password'.

<form>
    <input type="text" id="password1" oninput="setPasswordConfirmValidity();">
    <input type="text" id="password2" oninput="setPasswordConfirmValidity();">
</form>
<script>
    function setPasswordConfirmValidity(str) {
        const password1 = document.getElementById('password1');
        const password2 = document.getElementById('password2');

        if (password1.value === password2.value) {
             password2.setCustomValidity('');
        } else {
            password2.setCustomValidity('Passwords must match');
        }
        console.log('password2 customError ', document.getElementById('password2').validity.customError);
        console.log('password2 validationMessage ', document.getElementById('password2').validationMessage);
    }
</script>

No increment operator (++) in Ruby?

From a posting by Matz:

(1) ++ and -- are NOT reserved operator in Ruby.

(2) C's increment/decrement operators are in fact hidden assignment. They affect variables, not objects. You cannot accomplish assignment via method. Ruby uses +=/-= operator instead.

(3) self cannot be a target of assignment. In addition, altering the value of integer 1 might cause severe confusion throughout the program.

                      matz.

"/usr/bin/ld: cannot find -lz"

Try one of those three solution. It must work :) :

  1. sudo apt-get install zlib1g-dev
  2. sudo apt-get install libz-dev
  3. sudo apt-get install lib32z1-dev

In fact what is missing is not the lz command, but the development files for the zlib library.So you should install zlib1g-devlib for ex to get it.

For rhel7 like systems the package is zlib-devel

Entity Framework Timeouts

I know this is very old thread running, but still EF has not fixed this. For people using auto-generated DbContext can use the following code to set the timeout manually.

public partial class SampleContext : DbContext
{
    public SampleContext()
        : base("name=SampleContext")
    {
        this.SetCommandTimeOut(180);
    }

    public void SetCommandTimeOut(int Timeout)
    {
        var objectContext = (this as IObjectContextAdapter).ObjectContext;
        objectContext.CommandTimeout = Timeout;
    }

Html5 Full screen video

You can do it with jQuery.

I have my video and controls in their own <div> like this:

<div id="videoPlayer" style="width:520px; -webkit-border-radius:10px; height:420px; background-color:white; position:relative; float:left; left:25px; top:55px;" align="center">

    <video controls width="500" height="400" style="background-color:black; margin-top:10px; -webkit-border-radius:10px;">
         <source src="videos/gin.mp4" type="video/mp4" />
    </video>

    <script>  
        video.removeAttribute('controls');  
    </script> 

    <div id="vidControls" style="position:relative; width:100%; height:50px; background-color:white; -webkit-border-bottom-left-radius:10px; -webkit-border-bottom-right-radius:10px; padding-top:10px; padding-bottom:10px;">

         <table width="100%" height="100%" border="0">

             <tr>
                 <td width="100%" align="center" valign="middle" colspan="4"><input class="vidPos" type="range" value="0" step="0.1" style="width:500px;" /></td>
             </tr>

             <tr>
                 <td width="100%" align="center" valign="middle"><a href="javascript:;" class="playVid">Play</a></td>
                 <td width="100%" align="center" valign="middle"><a href="javascript:;" class="vol">Vol</a></td>
                 <td width="100%" align="left" valign="middle"><p class="timer"><strong>0:00</strong> / 0:00</p></td>
                 <td width="100%" align="center" valign="middle"><a href="javascript:;" class="fullScreen">Full</a></td>
              </tr>

            </table>

         </div>

      </div>

And then my jQuery for the .fullscreen class is:

var fullscreen = 0;

$(".fullscreen").click(function(){
  if(fullscreen == 0){
    fullscreen = 1;
    $("video").appendTo('body');
    $("#vidControls").appendTo('body');
    $("video").css('position', 'absolute').css('width', '100%').css('height', '90%').css('margin', 0).css('margin-top', '5%').css('top', '0').css('left', '0').css('float', 'left').css('z-index', 600);
    $("#vidControls").css('position', 'absolute').css('bottom', '5%').css('width', '90%').css('backgroundColor', 'rgba(150, 150, 150, 0.5)').css('float', 'none').css('left', '5%').css('z-index', 700).css('-webkit-border-radius', '10px');

}
else
    {

        fullscreen = 0;

        $("video").appendTo('#videoPlayer');
        $("#vidControls").appendTo('#videoPlayer');

        //change <video> css back to normal

        //change "#vidControls" css back to normal

    }

});

It needs a little cleaning up as I'm still working on it but that should work for most browsers as far as I can see.

Hope it helps!

SimpleDateFormat parse loses timezone

OP's solution to his problem, as he says, has dubious output. That code still shows confusion about representations of time. To clear up this confusion, and make code that won't lead to wrong times, consider this extension of what he did:

public static void _testDateFormatting() {
    SimpleDateFormat sdfGMT1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    sdfGMT1.setTimeZone(TimeZone.getTimeZone("GMT"));
    SimpleDateFormat sdfGMT2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
    sdfGMT2.setTimeZone(TimeZone.getTimeZone("GMT"));

    SimpleDateFormat sdfLocal1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    SimpleDateFormat sdfLocal2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");

    try {
        Date d = new Date();
        String s1 = d.toString();
        String s2 = sdfLocal1.format(d);
        // Store s3 or s4 in database.
        String s3 = sdfGMT1.format(d);
        String s4 = sdfGMT2.format(d);
        // Retrieve s3 or s4 from database, using LOCAL sdf.
        String s5 = sdfLocal1.parse(s3).toString();
        //EXCEPTION String s6 = sdfLocal2.parse(s3).toString();
        String s7 = sdfLocal1.parse(s4).toString();
        String s8 = sdfLocal2.parse(s4).toString();
        // Retrieve s3 from database, using GMT sdf.
        // Note that this is the SAME sdf that created s3.
        Date d2 = sdfGMT1.parse(s3);
        String s9 = d2.toString();
        String s10 = sdfGMT1.format(d2);
        String s11 = sdfLocal2.format(d2);
    } catch (Exception e) {
        e.printStackTrace();
    }       
}

examining values in a debugger:

s1  "Mon Sep 07 06:11:53 EDT 2015" (id=831698113128)    
s2  "2015.09.07 06:11:53" (id=831698114048) 
s3  "2015.09.07 10:11:53" (id=831698114968) 
s4  "2015.09.07 10:11:53 GMT+00:00" (id=831698116112)   
s5  "Mon Sep 07 10:11:53 EDT 2015" (id=831698116944)    
s6  -- omitted, gave parse exception    
s7  "Mon Sep 07 10:11:53 EDT 2015" (id=831698118680)    
s8  "Mon Sep 07 06:11:53 EDT 2015" (id=831698119584)    
s9  "Mon Sep 07 06:11:53 EDT 2015" (id=831698120392)    
s10 "2015.09.07 10:11:53" (id=831698121312) 
s11 "2015.09.07 06:11:53 EDT" (id=831698122256) 

sdf2 and sdfLocal2 include time zone, so we can see what is really going on. s1 & s2 are at 06:11:53 in zone EDT. s3 & s4 are at 10:11:53 in zone GMT -- equivalent to the original EDT time. Imagine we save s3 or s4 in a data base, where we are using GMT for consistency, so we can have times from anywhere in the world, without storing different time zones.

s5 parses the GMT time, but treats it as a local time. So it says "10:11:53" -- the GMT time -- but thinks it is 10:11:53 in local time. Not good.

s7 parses the GMT time, but ignores the GMT in the string, so still treats it as a local time.

s8 works, because now we include GMT in the string, and the local zone parser uses it to convert from one time zone to another.

Now suppose you don't want to store the zone, you want to be able to parse s3, but display it as a local time. The answer is to parse using the same time zone it was stored in -- so use the same sdf as it was created in, sdfGMT1. s9, s10, & s11 are all representations of the original time. They are all "correct". That is, d2 == d1. Then it is only a question of how you want to DISPLAY it. If you want to display what is stored in DB -- GMT time -- then you need to format it using a GMT sdf. Ths is s10.

So here is the final solution, if you don't want to explicitly store with " GMT" in the string, and want to display in GMT format:

public static void _testDateFormatting() {
    SimpleDateFormat sdfGMT1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    sdfGMT1.setTimeZone(TimeZone.getTimeZone("GMT"));

    try {
        Date d = new Date();
        String s3 = sdfGMT1.format(d);
        // Store s3 in DB.
        // ...
        // Retrieve s3 from database, using GMT sdf.
        Date d2 = sdfGMT1.parse(s3);
        String s10 = sdfGMT1.format(d2);
    } catch (Exception e) {
        e.printStackTrace();
    }       
}

Want to move a particular div to right

This will do the job:

_x000D_
_x000D_
<div style="position:absolute; right:0;">Hello world</div>
_x000D_
_x000D_
_x000D_

What's the advantage of a Java enum versus a class with public static final fields?

  1. Type safety and value safety.
  2. Guaranteed singleton.
  3. Ability to define and override methods.
  4. Ability to use values in switch statement case statements without qualification.
  5. Built-in sequentialization of values via ordinal().
  6. Serialization by name not by value, which offers a degree of future-proofing.
  7. EnumSet and EnumMap classes.

CSS selector based on element text?

I know it's not exactly what you are looking for, but maybe it'll help you.

You can try use a jQuery selector :contains(), add a class and then do a normal style for a class.

make an html svg object also a clickable link

Just don't use <object>. Here's a solution that worked for me with <a> and <svg> tags:

<a href="<your-link>" class="mr-5 p-1 border-2 border-transparent text-gray-400 rounded-full hover:text-white focus:outline-none focus:text-white focus:bg-red-700 transition duration-150 ease-in-out" aria-label="Notifications">
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="30" 
    height="30"><path class="heroicon-ui" fill="#fff" d="M17 16a3 3 0 1 1-2.83 
    2H9.83a3 3 0 1 1-5.62-.1A3 3 0 0 1 5 12V4H3a1 1 0 1 1 0-2h3a1 1 0 0 1 1 
    1v1h14a1 1 0 0 1 .9 1.45l-4 8a1 1 0 0 1-.9.55H5a1 1 0 0 0 0 2h12zM7 12h9.38l3- 
   6H7v6zm0 8a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm10 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2z"/>
    </svg>
</a>

module.exports vs. export default in Node.js and ES6

The issue is with

  • how ES6 modules are emulated in CommonJS
  • how you import the module

ES6 to CommonJS

At the time of writing this, no environment supports ES6 modules natively. When using them in Node.js you need to use something like Babel to convert the modules to CommonJS. But how exactly does that happen?

Many people consider module.exports = ... to be equivalent to export default ... and exports.foo ... to be equivalent to export const foo = .... That's not quite true though, or at least not how Babel does it.

ES6 default exports are actually also named exports, except that default is a "reserved" name and there is special syntax support for it. Lets have a look how Babel compiles named and default exports:

// input
export const foo = 42;
export default 21;

// output
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
var foo = exports.foo = 42;
exports.default = 21; 

Here we can see that the default export becomes a property on the exports object, just like foo.

Import the module

We can import the module in two ways: Either using CommonJS or using ES6 import syntax.

Your issue: I believe you are doing something like:

var bar = require('./input');
new bar();

expecting that bar is assigned the value of the default export. But as we can see in the example above, the default export is assigned to the default property!

So in order to access the default export we actually have to do

var bar = require('./input').default;

If we use ES6 module syntax, namely

import bar from './input';
console.log(bar);

Babel will transform it to

'use strict';

var _input = require('./input');

var _input2 = _interopRequireDefault(_input);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

console.log(_input2.default);

You can see that every access to bar is converted to access .default.

T-SQL: Using a CASE in an UPDATE statement to update certain columns depending on a condition

enter image description here

I want to change or update my ContactNo to 8018070999 where there is 8018070777 using Case statement

update [Contacts] set contactNo=(case 
when contactNo=8018070777 then 8018070999
else
contactNo
end)

enter image description here

Where do I mark a lambda expression async?

To mark a lambda async, simply prepend async before its argument list:

// Add a command to delete the current Group
contextMenu.Commands.Add(new UICommand("Delete this Group", async (contextMenuCmd) =>
{
    SQLiteUtils slu = new SQLiteUtils();
    await slu.DeleteGroupAsync(groupName);
}));

Getting the docstring from a function

On ipython or jupyter notebook, you can use all the above mentioned ways, but i go with

my_func?

or

?my_func

for quick summary of both method signature and docstring.

I avoid using

my_func??

(as commented by @rohan) for docstring and use it only to check the source code

Datatables - Setting column width

I set the column widths in the HTML markup like so:

    <thead>
        <tr>

            <th style='width: 5%;'>ProjectId</th>
            <th style='width: 15%;'>Title</th>
            <th style='width: 40%;'>Abstract</th>
            <th style='width: 20%;'>Keywords</th>
            <th style='width: 10%;'>PaperName</th>
            <th style='width: 10%;'>PaperURL</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr id="@item.ID">
                <td>@item.ProjectId</td>
                <td>@item.Title</td>
                <td>@item.Abstract</td>
                <td>@item.Keywords</td>
                <td>@item.PaperName</td>
                <td>@item.PaperURL</td>
            </tr>
        }
    </tbody>
</table>

Git merge is not possible because I have unmerged files

The error message:

merge: remote/master - not something we can merge

is saying that Git doesn't recognize remote/master. This is probably because you don't have a "remote" named "remote". You have a "remote" named "origin".

Think of "remotes" as an alias for the url to your Git server. master is your locally checked-out version of the branch. origin/master is the latest version of master from your Git server that you have fetched (downloaded). A fetch is always safe because it will only update the "origin/x" version of your branches.

So, to get your master branch back in sync, first download the latest content from the git server:

git fetch

Then, perform the merge:

git merge origin/master

...But, perhaps the better approach would be:

git pull origin master

The pull command will do the fetch and merge for you in one step.

Working with UTF-8 encoding in Python source

Do not forget to verify if your text editor encodes properly your code in UTF-8.

Otherwise, you may have invisible characters that are not interpreted as UTF-8.

How to determine the version of Gradle?

2019-05-08 Android Studios needs an upgrade. upgrade Android Studios to 3.3.- and the error with .R; goes away.

Also the above methods also work.

How to push both key and value into an Array in Jquery

There are no keys in JavaScript arrays. Use objects for that purpose.

var obj = {};

$.getJSON("displayjson.php",function (data) {
    $.each(data.news, function (i, news) {
        obj[news.title] = news.link;
    });                      
});

// later:
$.each(obj, function (index, value) {
    alert( index + ' : ' + value );
});

In JavaScript, objects fulfill the role of associative arrays. Be aware that objects do not have a defined "sort order" when iterating them (see below).

However, In your case it is not really clear to me why you transfer data from the original object (data.news) at all. Why do you not simply pass a reference to that object around?


You can combine objects and arrays to achieve predictable iteration and key/value behavior:

var arr = [];

$.getJSON("displayjson.php",function (data) {
    $.each(data.news, function (i, news) {
        arr.push({
            title: news.title, 
            link:  news.link
        });
    });                      
});

// later:
$.each(arr, function (index, value) {
    alert( value.title + ' : ' + value.link );
});

How to get javax.comm API?

Use RXTX.

On Debian install librxtx-java by typing:

sudo apt-get install librxtx-java

On Fedora or Enterprise Linux install rxtx by typing:

sudo yum install rxtx

How to do a logical OR operation for integer comparison in shell scripting?

have you tried something like this:

if [ $# -eq 0 ] || [ $# -gt 1 ] 
then
 echo "$#"
fi

Loop code for each file in a directory

scandir:

$files = scandir('folder/');
foreach($files as $file) {
  //do your work here
}

or glob may be even better for your needs:

$files = glob('folder/*.{jpg,png,gif}', GLOB_BRACE);
foreach($files as $file) {
  //do your work here
}

Where is the Global.asax.cs file?

It don't create normally; you need to add it by yourself.

After adding Global.asax by

  • Right clicking your website -> Add New Item -> Global Application Class -> Add

You need to add a class

  • Right clicking App_Code -> Add New Item -> Class -> name it Global.cs -> Add

Inherit the newly generated by System.Web.HttpApplication and copy all the method created Global.asax to Global.cs and also add an inherit attribute to the Global.asax file.

Your Global.asax will look like this: -

<%@ Application Language="C#" Inherits="Global" %>

Your Global.cs in App_Code will look like this: -

public class Global : System.Web.HttpApplication
{
    public Global()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

    }
    /// Many other events like begin request...e.t.c, e.t.c
}

python: urllib2 how to send cookie with urlopen request

Use cookielib. The linked doc page provides examples at the end. You'll also find a tutorial here.

_DEBUG vs NDEBUG

Be consistent and it doesn't matter which one. Also if for some reason you must interop with another program or tool using a certain DEBUG identifier it's easy to do

#ifdef THEIRDEBUG
#define MYDEBUG
#endif //and vice-versa

Why do we usually use || over |? What is the difference?

| does not do short-circuit evaluation in boolean expressions. || will stop evaluating if the first operand is true, but | won't.

In addition, | can be used to perform the bitwise-OR operation on byte/short/int/long values. || cannot.

How to split/partition a dataset into training and test datasets for, e.g., cross validation?

If you want to split the data set once in two halves, you can use numpy.random.shuffle, or numpy.random.permutation if you need to keep track of the indices:

import numpy
# x is your dataset
x = numpy.random.rand(100, 5)
numpy.random.shuffle(x)
training, test = x[:80,:], x[80:,:]

or

import numpy
# x is your dataset
x = numpy.random.rand(100, 5)
indices = numpy.random.permutation(x.shape[0])
training_idx, test_idx = indices[:80], indices[80:]
training, test = x[training_idx,:], x[test_idx,:]

There are many ways to repeatedly partition the same data set for cross validation. One strategy is to resample from the dataset, with repetition:

import numpy
# x is your dataset
x = numpy.random.rand(100, 5)
training_idx = numpy.random.randint(x.shape[0], size=80)
test_idx = numpy.random.randint(x.shape[0], size=20)
training, test = x[training_idx,:], x[test_idx,:]

Finally, sklearn contains several cross validation methods (k-fold, leave-n-out, ...). It also includes more advanced "stratified sampling" methods that create a partition of the data that is balanced with respect to some features, for example to make sure that there is the same proportion of positive and negative examples in the training and test set.

How can I get the current screen orientation?

int orientation = this.getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
    // code for portrait mode
} else {
    // code for landscape mode
}

When the superclass of this is Context

How to recognize swipe in all 4 directions

In Swift 5,

let swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe))
swipeGesture.direction = [.left, .right, .up, .down]
view.addGestureRecognizer(swipeGesture)

TSQL: How to convert local time to UTC? (SQL Server 2008)

SQL Server 2008 has a type called datetimeoffset. It's really useful for this type of stuff.

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

Then you can use the function SWITCHOFFSET to move it from one timezone to another, but still keeping the same UTC value.

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

Rob

Simple CSS Animation Loop – Fading In & Out "Loading" Text

As King King said, you must add the browser specific prefix. This should cover most browsers:

_x000D_
_x000D_
@keyframes flickerAnimation {_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-o-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-moz-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-webkit-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
.animate-flicker {_x000D_
   -webkit-animation: flickerAnimation 1s infinite;_x000D_
   -moz-animation: flickerAnimation 1s infinite;_x000D_
   -o-animation: flickerAnimation 1s infinite;_x000D_
    animation: flickerAnimation 1s infinite;_x000D_
}
_x000D_
<div class="animate-flicker">Loading...</div>
_x000D_
_x000D_
_x000D_

How to read specific lines from a file (by line number)?

Reading from specific line:

n = 4   # for reading from 5th line
with open("write.txt",'r') as t:
     for i,line in enumerate(t):
         if i >= n:             # i == n-1 for nth line
            print(line)

What is the difference between smoke testing and sanity testing?

THERE IS NO DIFFERENCE BETWEEN smoke and sanity as per ISTQB.

sanity is synonym of smoke.

Check it here : https://glossary.istqb.org/en/search/sanity

Google Chrome: This setting is enforced by your administrator

In my case, the setting was HKEY_CURRENT_USER\Software\Policies\Google\Chrome

I deleted Chrome and everything is fine now.

jQuery Datepicker with text input that doesn't allow user input

I know this thread is old, but for others who encounter the same problem, that implement @Brad8118 solution (which i prefer, because if you choose to make the input readonly then the user will not be able to delete the date value inserted from datepicker if he chooses) and also need to prevent the user from pasting a value (as @ErikPhilips suggested to be needed), I let this addition here, which worked for me: $("#my_txtbox").bind('paste',function(e) { e.preventDefault(); //disable paste }); from here https://www.dotnettricks.com/learn/jquery/disable-cut-copy-and-paste-in-textbox-using-jquery-javascript and the whole specific script used by me (using fengyuanchen/datepicker plugin instead):

$('[data-toggle="datepicker"]').datepicker({
    autoHide: true,
    pick: function (e) {
        e.preventDefault();
        $(this).val($(this).datepicker('getDate', true));
    }
}).keypress(function(event) {
    event.preventDefault(); // prevent keyboard writing but allowing value deletion
}).bind('paste',function(e) {
    e.preventDefault()
}); //disable paste;

Generate C# class from XML

Use below syntax to create schema class from XSD file.

C:\xsd C:\Test\test-Schema.xsd /classes /language:cs /out:C:\Test\

Creating a fixed sidebar alongside a centered Bootstrap 3 grid

As drew_w said, you can find a good example here.

HTML

<div id="wrapper">
    <div id="sidebar-wrapper">
        <ul class="sidebar-nav">
            <li class="sidebar-brand"><a href="#">Home</a></li>
            <li><a href="#">Another link</a></li>
            <li><a href="#">Next link</a></li>
            <li><a href="#">Last link</a></li>
        </ul>
    </div>
    <div id="page-content-wrapper">
        <div class="page-content">
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <!-- content of page -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

#wrapper {
  padding-left: 250px;
  transition: all 0.4s ease 0s;
}

#sidebar-wrapper {
  margin-left: -250px;
  left: 250px;
  width: 250px;
  background: #CCC;
  position: fixed;
  height: 100%;
  overflow-y: auto;
  z-index: 1000;
  transition: all 0.4s ease 0s;
}

#page-content-wrapper {
  width: 100%;
}

.sidebar-nav {
  position: absolute;
  top: 0;
  width: 250px;
  list-style: none;
  margin: 0;
  padding: 0;
}

@media (max-width:767px) {

    #wrapper {
      padding-left: 0;
    }

    #sidebar-wrapper {
      left: 0;
    }

    #wrapper.active {
      position: relative;
      left: 250px;
    }

    #wrapper.active #sidebar-wrapper {
      left: 250px;
      width: 250px;
      transition: all 0.4s ease 0s;
    }

}

JSFIDDLE

enumerate() for dictionary in python

Just thought I'd add, if you'd like to enumerate over the index, key, and values of a dictionary, your for loop should look like this:

for index, (key, value) in enumerate(your_dict.items()):
    print(index, key, value)

Eclipse C++: Symbol 'std' could not be resolved

You can rewrite the code likes this:

#include<iostream>
#include<stdio.h>

using namespace std;

How do I add a margin between bootstrap columns without wrapping

You should work with padding on the inner container rather than with margin. Try this!

HTML

<div class="row info-panel">
    <div class="col-md-4" id="server_1">
       <div class="server-action-menu">
           Server 1
       </div>
   </div>
</div>

CSS

.server-action-menu {
    background-color: transparent;
    background-image: linear-gradient(to bottom, rgba(30, 87, 153, 0.2) 0%, rgba(125, 185, 232, 0) 100%);
    background-repeat: repeat;
    border-radius:10px;
    padding: 5px;
}

selected value get from db into dropdown select box option using php mysql error

I think you are looking for below code changes:

<select name="course">
<option value="0">Please Select Option</option>
<option value="PHP" <?php if($options=="PHP") echo 'selected="selected"'; ?> >PHP</option>
<option value="ASP" <?php if($options=="ASP") echo 'selected="selected"'; ?> >ASP</option>
</select>

How can I use grep to find a word inside a folder?

The answer you selected is fine, and it works, but it isn't the correct way to do it, because:

grep -nr yourString* .

This actually searches the string "yourStrin" and "g" 0 or many times.

So the proper way to do it is:

grep -nr \w*yourString\w* .

This command searches the string with any character before and after on the current folder.

Finding current executable's path without /proc/self/exe

Just my two cents. You can find the current application's directory in C/C++ with cross-platform interfaces by using this code.

void getExecutablePath(char ** path, unsigned int * pathLength)
{
    // Early exit when invalid out-parameters are passed
    if (!checkStringOutParameter(path, pathLength))
    {
        return;
    }

#if defined SYSTEM_LINUX

    // Preallocate PATH_MAX (e.g., 4096) characters and hope the executable path isn't longer (including null byte)
    char exePath[PATH_MAX];

    // Return written bytes, indicating if memory was sufficient
    int len = readlink("/proc/self/exe", exePath, PATH_MAX);

    if (len <= 0 || len == PATH_MAX) // memory not sufficient or general error occured
    {
        invalidateStringOutParameter(path, pathLength);
        return;
    }

    // Copy contents to caller, create caller ownership
    copyToStringOutParameter(exePath, len, path, pathLength);

#elif defined SYSTEM_WINDOWS

    // Preallocate MAX_PATH (e.g., 4095) characters and hope the executable path isn't longer (including null byte)
    char exePath[MAX_PATH];

    // Return written bytes, indicating if memory was sufficient
    unsigned int len = GetModuleFileNameA(GetModuleHandleA(0x0), exePath, MAX_PATH);
    if (len == 0) // memory not sufficient or general error occured
    {
        invalidateStringOutParameter(path, pathLength);
        return;
    }

    // Copy contents to caller, create caller ownership
    copyToStringOutParameter(exePath, len, path, pathLength);

#elif defined SYSTEM_SOLARIS

    // Preallocate PATH_MAX (e.g., 4096) characters and hope the executable path isn't longer (including null byte)
    char exePath[PATH_MAX];

    // Convert executable path to canonical path, return null pointer on error
    if (realpath(getexecname(), exePath) == 0x0)
    {
        invalidateStringOutParameter(path, pathLength);
        return;
    }

    // Copy contents to caller, create caller ownership
    unsigned int len = strlen(exePath);
    copyToStringOutParameter(exePath, len, path, pathLength);

#elif defined SYSTEM_DARWIN

    // Preallocate PATH_MAX (e.g., 4096) characters and hope the executable path isn't longer (including null byte)
    char exePath[PATH_MAX];

    unsigned int len = (unsigned int)PATH_MAX;

    // Obtain executable path to canonical path, return zero on success
    if (_NSGetExecutablePath(exePath, &len) == 0)
    {
        // Convert executable path to canonical path, return null pointer on error
        char * realPath = realpath(exePath, 0x0);

        if (realPath == 0x0)
        {
            invalidateStringOutParameter(path, pathLength);
            return;
        }

        // Copy contents to caller, create caller ownership
        unsigned int len = strlen(realPath);
        copyToStringOutParameter(realPath, len, path, pathLength);

        free(realPath);
    }
    else // len is initialized with the required number of bytes (including zero byte)
    {
        char * intermediatePath = (char *)malloc(sizeof(char) * len);

        // Convert executable path to canonical path, return null pointer on error
        if (_NSGetExecutablePath(intermediatePath, &len) != 0)
        {
            free(intermediatePath);
            invalidateStringOutParameter(path, pathLength);
            return;
        }

        char * realPath = realpath(intermediatePath, 0x0);

        free(intermediatePath);

        // Check if conversion to canonical path succeeded
        if (realPath == 0x0)
        {
            invalidateStringOutParameter(path, pathLength);
            return;
        }

        // Copy contents to caller, create caller ownership
        unsigned int len = strlen(realPath);
        copyToStringOutParameter(realPath, len, path, pathLength);

        free(realPath);
    }

#elif defined SYSTEM_FREEBSD

    // Preallocate characters and hope the executable path isn't longer (including null byte)
    char exePath[2048];

    unsigned int len = 2048;

    int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };

    // Obtain executable path by syscall
    if (sysctl(mib, 4, exePath, &len, 0x0, 0) != 0)
    {
        invalidateStringOutParameter(path, pathLength);
        return;
    }

    // Copy contents to caller, create caller ownership
    copyToStringOutParameter(exePath, len, path, pathLength);

#else

    // If no OS could be detected ... degrade gracefully
    invalidateStringOutParameter(path, pathLength);

#endif
}

You can take a look in detail here.

Passing a 2D array to a C++ function

Surprised that no one mentioned this yet, but you can simply template on anything 2D supporting [][] semantics.

template <typename TwoD>
void myFunction(TwoD& myArray){
     myArray[x][y] = 5;
     etc...
}

// call with
double anArray[10][10];
myFunction(anArray);

It works with any 2D "array-like" datastructure, such as std::vector<std::vector<T>>, or a user defined type to maximize code reuse.

Is there a way to get rid of accents and convert a whole string to regular letters?

I have faced the same issue related to Strings equality check, One of the comparing string has ASCII character code 128-255.

i.e., Non-breaking space - [Hex - A0] Space [Hex - 20]. To show Non-breaking space over HTML. I have used the following spacing entities. Their character and its bytes are like &emsp is very wide space[ ]{-30, -128, -125}, &ensp is somewhat wide space[ ]{-30, -128, -126}, &thinsp is narrow space[ ]{32} , Non HTML Space {}

String s1 = "My Sample Space Data", s2 = "My Sample Space Data";
System.out.format("S1: %s\n", java.util.Arrays.toString(s1.getBytes()));
System.out.format("S2: %s\n", java.util.Arrays.toString(s2.getBytes()));

Output in Bytes:

S1: [77, 121, 32, 83, 97, 109, 112, 108, 101, 32, 83, 112, 97, 99, 101, 32, 68, 97, 116, 97] S2: [77, 121, -30, -128, -125, 83, 97, 109, 112, 108, 101, -30, -128, -125, 83, 112, 97, 99, 101, -30, -128, -125, 68, 97, 116, 97]

Use below code for Different Spaces and their Byte-Codes: wiki for List_of_Unicode_characters

String spacing_entities = "very wide space,narrow space,regular space,invisible separator";
System.out.println("Space String :"+ spacing_entities);
byte[] byteArray = 
    // spacing_entities.getBytes( Charset.forName("UTF-8") );
    // Charset.forName("UTF-8").encode( s2 ).array();
    {-30, -128, -125, 44, -30, -128, -126, 44, 32, 44, -62, -96};
System.out.println("Bytes:"+ Arrays.toString( byteArray ) );
try {
    System.out.format("Bytes to String[%S] \n ", new String(byteArray, "UTF-8"));
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}
  • ? ASCII transliterations of Unicode string for Java. unidecode

    String initials = Unidecode.decode( s2 );
    
  • ? using Guava: Google Core Libraries for Java.

    String replaceFrom = CharMatcher.WHITESPACE.replaceFrom( s2, " " );
    

    For URL encode for the space use Guava laibrary.

    String encodedString = UrlEscapers.urlFragmentEscaper().escape(inputString);
    
  • ? To overcome this problem used String.replaceAll() with some RegularExpression.

    // \p{Z} or \p{Separator}: any kind of whitespace or invisible separator.
    s2 = s2.replaceAll("\\p{Zs}", " ");
    
    
    s2 = s2.replaceAll("[^\\p{ASCII}]", " ");
    s2 = s2.replaceAll(" ", " ");
    
  • ? Using java.text.Normalizer.Form. This enum provides constants of the four Unicode normalization forms that are described in Unicode Standard Annex #15 — Unicode Normalization Forms and two methods to access them.

    enter image description here

    s2 = Normalizer.normalize(s2, Normalizer.Form.NFKC);
    

Testing String and outputs on different approaches like ? Unidecode, Normalizer, StringUtils.

String strUni = "Thïs iš â funky Štring Æ,Ø,Ð,ß";

// This is a funky String AE,O,D,ss
String initials = Unidecode.decode( strUni );

// Following Produce this o/p: Th^i¨s^ i~s? a^ fu°n?k¸y^ S?t?r´i?n´g? Æ,Ø,Ð,ß
String temp = Normalizer.normalize(strUni, Normalizer.Form.NFD);
Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
temp = pattern.matcher(temp).replaceAll("");

String input = org.apache.commons.lang3.StringUtils.stripAccents( strUni );

Using Unidecode is the best choice, My final Code shown below.

public static void main(String[] args) {
    String s1 = "My Sample Space Data", s2 = "My Sample Space Data";
    String initials = Unidecode.decode( s2 );
    if( s1.equals(s2)) { //[ , ] %A0 - %2C - %20 « http://www.ascii-code.com/
        System.out.println("Equal Unicode Strings");
    } else if( s1.equals( initials ) ) {
        System.out.println("Equal Non Unicode Strings");
    } else {
        System.out.println("Not Equal");
    }

}

Disable cross domain web security in Firefox

I have not been able to find a Firefox option equivalent of --disable-web-security or an addon that does that for me. I really needed it for some testing scenarios where modifying the web server was not possible. What did help was to use Fiddler to auto-modify web responses so that they have the correct headers and CORS is no longer an issue.

The steps are:

  1. Open fiddler.

  2. If on https go to menu Tools -> Options -> Https and tick the Capture & Decrypt https options

  3. Go to menu Rules -> Customize rules. Modify the OnBeforeResponseFunction so that it looks like the following, then save:

     static function OnBeforeResponse(oSession: Session) {
        //....
        oSession.oResponse.headers.Remove("Access-Control-Allow-Origin");
        oSession.oResponse.headers.Add("Access-Control-Allow-Origin", "*");
        //...
     }
    

    This will make every web response to have the Access-Control-Allow-Origin: * header.

  4. This still won't work as the OPTIONS preflight will pass through and cause the request to block before our above rule gets the chance to modify the headers. So to fix this, in the fiddler main window, on the right hand side there's an AutoResponder tab. Add a new rule and response: METHOD:OPTIONS https://yoursite.com/ with auto response: *CORSPreflightAllow and tick the boxes: "Enable Rules" and "Unmatched requests passthrough".

See picture below for reference:

enter image description here

How to parse dates in multiple formats using SimpleDateFormat

For the modern answer I am ignoring the requirement to use SimpleDateFormat. While using this class for parsing was a good idea in 2010 when this question was asked, it is now long outdated. The replacement, DateTimeFormatter, came out in 2014. The idea in the following is pretty much the same as in the accepted answer.

private static DateTimeFormatter[] parseFormatters = Stream.of("M/yy", "M/y", "M/d/y", "M-d-y")
        .map(DateTimeFormatter::ofPattern)
        .toArray(DateTimeFormatter[]::new);

public static YearMonth parseYearMonth(String input) {
    for (DateTimeFormatter formatter : parseFormatters) {
        try {
            return YearMonth.parse(input, formatter);
        } catch (DateTimeParseException dtpe) {
            // ignore, try next format
        }
    }
    throw new IllegalArgumentException("Could not parse " + input);
}

This parses each of the input strings from the question into a year-month of 2009-09. It’s important to try the two-digit year first since "M/y" could also parse 9/09, but into 0009-09 instead.

A limitation of the above code is it ignores the day-of-month from the strings that have one, like 9/1/2009. Maybe it’s OK as long as most formats have only month and year. To pick it up, we’d have to try LocalDate.parse() rather then YearMonth.parse() for the formats that include d in the pattern string. Surely it can be done.

Calling virtual functions inside constructors

The vtables are created by the compiler. A class object has a pointer to its vtable. When it starts life, that vtable pointer points to the vtable of the base class. At the end of the constructor code, the compiler generates code to re-point the vtable pointer to the actual vtable for the class. This ensures that constructor code that calls virtual functions calls the base class implementations of those functions, not the override in the class.

How to install popper.js with Bootstrap 4?

I have the same problem while learning Node.js Here is my solution for it to install jquery

npm install [email protected] --save
npm install popper.js@^1.12.9 --save

View's SELECT contains a subquery in the FROM clause

As the more recent MySQL documentation on view restrictions says:

Before MySQL 5.7.7, subqueries cannot be used in the FROM clause of a view.

This means, that choosing a MySQL v5.7.7 or newer or upgrading the existing MySQL instance to such a version, would remove this restriction on views completely.

However, if you have a current production MySQL version that is earlier than v5.7.7, then the removal of this restriction on views should only be one of the criteria being assessed while making a decision as to upgrade or not. Using the workaround techniques described in the other answers may be a more viable solution - at least on the shorter run.

How to measure the a time-span in seconds using System.currentTimeMillis()?

For conversion of milliseconds to seconds, since 1 second = 10³ milliseconds:

//here m will be in seconds
long m = System.currentTimeMillis()/1000;

//here m will be in minutes
long m = System.currentTimeMillis()/1000/60; //this will give in mins

How does Task<int> become an int?

Does an implicit conversion occur between Task<> and int?

Nope. This is just part of how async/await works.

Any method declared as async has to have a return type of:

  • void (avoid if possible)
  • Task (no result beyond notification of completion/failure)
  • Task<T> (for a logical result of type T in an async manner)

The compiler does all the appropriate wrapping. The point is that you're asynchronously returning urlContents.Length - you can't make the method just return int, as the actual method will return when it hits the first await expression which hasn't already completed. So instead, it returns a Task<int> which will complete when the async method itself completes.

Note that await does the opposite - it unwraps a Task<T> to a T value, which is how this line works:

string urlContents = await getStringTask;

... but of course it unwraps it asynchronously, whereas just using Result would block until the task had completed. (await can unwrap other types which implement the awaitable pattern, but Task<T> is the one you're likely to use most often.)

This dual wrapping/unwrapping is what allows async to be so composable. For example, I could write another async method which calls yours and doubles the result:

public async Task<int> AccessTheWebAndDoubleAsync()
{
    var task = AccessTheWebAsync();
    int result = await task;
    return result * 2;
}

(Or simply return await AccessTheWebAsync() * 2; of course.)

You must add a reference to assembly 'netstandard, Version=2.0.0.0

Deleting Bin and Obj folders worked for me.

Fastest method to escape HTML tags as HTML entities?

You could try passing a callback function to perform the replacement:

var tagsToReplace = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;'
};

function replaceTag(tag) {
    return tagsToReplace[tag] || tag;
}

function safe_tags_replace(str) {
    return str.replace(/[&<>]/g, replaceTag);
}

Here is a performance test: http://jsperf.com/encode-html-entities to compare with calling the replace function repeatedly, and using the DOM method proposed by Dmitrij.

Your way seems to be faster...

Why do you need it, though?

Creating executable files in Linux

Make file executable:

chmod +x file

Find location of perl:

which perl

This should return something like

/bin/perl sometimes /usr/local/bin

Then in the first line of your script add:

#!"path"/perl with path from above e.g.

#!/bin/perl

Then you can execute the file

./file

There may be some issues with the PATH, so you may want to change that as well ...

Updating state on props change in React Form

There is also componentDidUpdate available.

Function signatur:

componentDidUpdate(prevProps, prevState, snapshot)

Use this as an opportunity to operate on the DOM when the component has been updated. Doesn't get called on initial render.

See You Probably Don't Need Derived State Article, which describes Anti-Pattern for both componentDidUpdate and getDerivedStateFromProps. I found it very useful.

Maximum value for long integer

You can use: max value of float is

float('inf')

for negative

float('-inf')

what does "error : a nonstatic member reference must be relative to a specific object" mean?

EncodeAndSend is not a static function, which means it can be called on an instance of the class CPMSifDlg. You cannot write this:

 CPMSifDlg::EncodeAndSend(/*...*/);  //wrong - EncodeAndSend is not static

It should rather be called as:

 CPMSifDlg dlg; //create instance, assuming it has default constructor!
 dlg.EncodeAndSend(/*...*/);   //correct 

How do I import other TypeScript files?

Quick Easy Process in Visual Studio

Drag and Drop the file with .ts extension from solution window to editor, it will generate inline reference code like..

/// <reference path="../../components/someclass.ts"/>

How to stop/terminate a python script from running?

When I have a python script running on a linux terminal, CTRL + \ works. (not CRTL + C or D)

Run parallel multiple commands at once in the same terminal

Use GNU Parallel:

(echo command1; echo command2) | parallel
parallel ::: command1 command2

To kill:

parallel ::: command1 command2 &
PID=$!
kill -TERM $PID
kill -TERM $PID

Print Combining Strings and Numbers

The other answers explain how to produce a string formatted like in your example, but if all you need to do is to print that stuff you could simply write:

first = 10
second = 20
print "First number is", first, "and second number is", second

jQuery Selector: Id Ends With?

If you know the element type then: (eg: replace 'element' with 'div')

$("element[id$='txtTitle']")

If you don't know the element type:

$("[id$='txtTitle']")

More information available


_x000D_
_x000D_
// the old way, needs exact ID: document.getElementById("hi").value = "kk";_x000D_
$(function() {_x000D_
  $("[id$='txtTitle']").val("zz");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id="ctl_blabla_txtTitle" type="text" />
_x000D_
_x000D_
_x000D_

How to keep Docker container running after starting services?

This is not really how you should design your Docker containers.

When designing a Docker container, you're supposed to build it such that there is only one process running (i.e. you should have one container for Nginx, and one for supervisord or the app it's running); additionally, that process should run in the foreground.

The container will "exit" when the process itself exits (in your case, that process is your bash script).


However, if you really need (or want) to run multiple service in your Docker container, consider starting from "Docker Base Image", which uses runit as a pseudo-init process (runit will stay online while Nginx and Supervisor run), which will stay in the foreground while your other processes do their thing.

They have substantial docs, so you should be able to achieve what you're trying to do reasonably easily.

Mongoose.js: Find user by username LIKE value

I had problems with this recently, i use this code and work fine for me.

var data = 'Peter';

db.User.find({'name' : new RegExp(data, 'i')}, function(err, docs){
    cb(docs);
});

Use directly /Peter/i work, but i use '/'+data+'/i' and not work for me.

What does "pending" mean for request in Chrome Developer Window?

I also get this when using the HTTPS everywhere plugin. This plugin has a list of sites that also have https instead of http. So I assume before the actual request is made it is already being cancelled somehow.

So for example when I go to http://stackexchange.com, in Developer I first see a request with status (terminated). This request has some headers, but only the GET, User-Agent, and Accept. No response as well.

Then there is request to https://stackexchange.com with full headers etc.

So I assume it is used for requests that aren't sent.

Count number of cells with any value (string or number) in a column in Google Docs Spreadsheet

In the cell you want your result to appear, use the following formula:

=COUNTIF(A1:A200,"<>")

That will count all cells which have a value and ignore all empty cells in the range of A1 to A200.

How to return value from function which has Observable subscription inside?

If you want to pre-subscribe to the same Observable which will be returned, just use

.do():

function getValueFromObservable() {
    return this.store.do(
        (data:any) => {
            console.log("Line 1: " +data);
        }
    );
}

getValueFromObservable().subscribe(
        (data:any) => {
            console.log("Line 2: " +data)
        }
    );

How to efficiently build a tree from a flat structure?

Most of the answers assume you are looking to do this outside of the database. If your trees are relatively static in nature and you just need to somehow map the trees into the database, you may want to consider using nested set representations on the database side. Check out books by Joe Celko (or here for an overview by Celko).

If tied to Oracle dbs anyway, check out their CONNECT BY for straight SQL approaches.

With either approach, you could completely skip mapping the trees before you load the data up in the database. Just thought I would offer this up as an alternative, it may be completely inappropriate for your specific needs. The whole "proper order" part of the original question somewhat implies you need the order to be "correct" in the db for some reason? This might push me towards handling the trees there as well.

Postgresql : syntax error at or near "-"

I have reproduced the issue in my system,

postgres=# alter user my-sys with password 'pass11';
ERROR:  syntax error at or near "-"
LINE 1: alter user my-sys with password 'pass11';
                       ^

Here is the issue,

psql is asking for input and you have given again the alter query see postgres-#That's why it's giving error at alter

postgres-# alter user "my-sys" with password 'pass11';
ERROR:  syntax error at or near "alter"
LINE 2: alter user "my-sys" with password 'pass11';
        ^

Solution is as simple as the error,

postgres=# alter user "my-sys" with password 'pass11';
ALTER ROLE

What CSS selector can be used to select the first div within another div

The closest thing to what you're looking for is the :first-child pseudoclass; unfortunately this will not work in your case because you have an <h1> before the <div>s. What I would suggest is that you either add a class to the <div>, like <div class="first"> and then style it that way, or use jQuery if you really can't add a class:

$('#content > div:first')

Retrieve specific commit from a remote Git repository

This works best:

git fetch origin specific_commit
git checkout -b temp FETCH_HEAD

name "temp" whatever you want...this branch might be orphaned though

What are the special dollar sign shell variables?

To help understand what do $#, $0 and $1, ..., $n do, I use this script:

#!/bin/bash

for ((i=0; i<=$#; i++)); do
  echo "parameter $i --> ${!i}"
done

Running it returns a representative output:

$ ./myparams.sh "hello" "how are you" "i am fine"
parameter 0 --> myparams.sh
parameter 1 --> hello
parameter 2 --> how are you
parameter 3 --> i am fine

Join between tables in two different databases?

SELECT <...>
FROM A.table1 t1 JOIN B.table2 t2 ON t2.column2 = t1.column1;

Just make sure that in the SELECT line you specify which table columns you are using, either by full reference, or by alias. Any of the following will work:

SELECT *
SELECT t1.*,t2.column2
SELECT A.table1.column1, t2.*
etc.

How to delete duplicate rows in SQL Server?

Oh wow, i feel so stupid by ready all this answers, they are like experts' answer with all CTE and temp table and etc.

And all I did to get it working was simply aggregated the ID column by using MAX.

DELETE FROM table WHERE col1 IN (
    SELECT MAX(id) FROM table GROUP BY id HAVING ( COUNT(col1) > 1 )
)

NOTE: you might need to run it multiple time to remove duplicate as this will only delete one set of duplicate rows at a time.

Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?

I've been quite happy with Swing for the desktop applications I've been involved in. However, I do share your view on Swing not offering advanced components. What I've done in these cases is to go for JIDE. It's not free, but not that pricey either and it gives you a whole lot more tools under your belt. Specifically, they do offer a filterable TreeTable.

Testing if a list of integer is odd or even

There's at least 7 different ways to test if a number is odd or even. But, if you read through these benchmarks, you'll find that as TGH mentioned above, the modulus operation is the fastest:

if (x % 2 == 0)
               //even number
        else
               //odd number

Here are a few other methods (from the website) :

//bitwise operation
if ((x & 1) == 0)
       //even number
else
      //odd number

//bit shifting
if (((x >> 1) << 1) == x)
       //even number
else
       //odd number

//using native library
System.Math.DivRem((long)x, (long)2, out outvalue);
if ( outvalue == 0)
       //even number
else
       //odd number

Send an Array with an HTTP Get

That depends on what the target server accepts. There is no definitive standard for this. See also a.o. Wikipedia: Query string:

While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field (e.g. field1=value1&field1=value2&field2=value3).[4][5]

Generally, when the target server uses a strong typed programming language like Java (Servlet), then you can just send them as multiple parameters with the same name. The API usually offers a dedicated method to obtain multiple parameter values as an array.

foo=value1&foo=value2&foo=value3
String[] foo = request.getParameterValues("foo"); // [value1, value2, value3]

The request.getParameter("foo") will also work on it, but it'll return only the first value.

String foo = request.getParameter("foo"); // value1

And, when the target server uses a weak typed language like PHP or RoR, then you need to suffix the parameter name with braces [] in order to trigger the language to return an array of values instead of a single value.

foo[]=value1&foo[]=value2&foo[]=value3
$foo = $_GET["foo"]; // [value1, value2, value3]
echo is_array($foo); // true

In case you still use foo=value1&foo=value2&foo=value3, then it'll return only the first value.

$foo = $_GET["foo"]; // value1
echo is_array($foo); // false

Do note that when you send foo[]=value1&foo[]=value2&foo[]=value3 to a Java Servlet, then you can still obtain them, but you'd need to use the exact parameter name including the braces.

String[] foo = request.getParameterValues("foo[]"); // [value1, value2, value3]

Add a common Legend for combined ggplots

Roland's answer needs updating. See: https://github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs

This method has been updated for ggplot2 v1.0.0.

library(ggplot2)
library(gridExtra)
library(grid)


grid_arrange_shared_legend <- function(...) {
    plots <- list(...)
    g <- ggplotGrob(plots[[1]] + theme(legend.position="bottom"))$grobs
    legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
    lheight <- sum(legend$height)
    grid.arrange(
        do.call(arrangeGrob, lapply(plots, function(x)
            x + theme(legend.position="none"))),
        legend,
        ncol = 1,
        heights = unit.c(unit(1, "npc") - lheight, lheight))
}

dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
p1 <- qplot(carat, price, data=dsamp, colour=clarity)
p2 <- qplot(cut, price, data=dsamp, colour=clarity)
p3 <- qplot(color, price, data=dsamp, colour=clarity)
p4 <- qplot(depth, price, data=dsamp, colour=clarity)
grid_arrange_shared_legend(p1, p2, p3, p4)

Note the lack of ggplot_gtable and ggplot_build. ggplotGrob is used instead. This example is a bit more convoluted than the above solution but it still solved it for me.

I can't install intel HAXM

THE SHORT ANSWER:

Disable Microsoft Defender Application Guard

None of the answers helped me. Also, most of the answers here were addressed elsewhere online. I spent hours trying to solve this problem. After much hesitation, I decided to go on a hunch. I was suspicious about msinfo32.exe showing a Hypervisor was running, but it would not provide additional detail. I went into the services manager. I saw an instance of a hypervisor service was running, I went to disable it. Before disabling, I was asked if I am sure and was informed that a couple of other services would stop. One of the other services was Microsoft Defender Application Guard for Internet Explorer. I disabled this and FINALLY after hours of research on this topic was able to install Intel HAXM for Android Studio on my i5-4430 with Z87 chipset.

It was not enough to merely disable Hyper V and Windows Hypervisor Platform.

Visual Studio 2012 Web Publish doesn't copy files

To take this a bit further. You have two files that are created when you create a publish profile.

  • NewProfile.pubxml
  • NewProfile.pubxml.user

When you open a project that has these files in the PublishProfile folder from a source control it only has the .pubxml file and not the .publxml.user file, so it creates the .publxml.user file on the fly when you open the project. When it creates the new .publxml.user on the fly the xml looks like:

<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
</Project>

When you create a new profile it creates xml that looks like:

<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
    <LastUsedPlatform>Any CPU</LastUsedPlatform>
    <TimeStampOfAssociatedLegacyPublishXmlFile />
    <EncryptedPassword />
  </PropertyGroup>
</Project>

If you take the <PropertyGroup> node and put it in the .pubxml.user file your PublishProfiles will start working again.

UIButton: set image for selected-highlighted state

If someone's wondering how this works in Swift, here's my solution:

button.setImage("normal.png", forState: .Normal)
button.setImage("highlighted.png", forState: .Highlighted)
button.setImage("selected.png", forState: .Selected)

var selectedHighLightedStates: UIControlState = UIControlState.Highlighted
selectedHighLightedStates = selectedHighLightedStates.union(UIControlState.Selected)
button.setImage("selectedHighlighted.png", forState: selectedHighLightedStates)

Eclipse cannot load SWT libraries

In my case, I was missing the /usr/lib/jni directory entirely. Fixed by

sudo apt-get install libswt-gtk-3-jni libswt-gtk-3-java

No need to symlink afterwards. Eclipse started normally.

Array[n] vs Array[10] - Initializing array with variable vs real number

In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic about following the C++ standard), you can do:

int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++

If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:

int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!

Or, better yet, use a standard container:

int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>

If you still want a proper array, you can use a constant, not a variable, when creating it:

const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)

Similarly, if you want to get the size from a function in C++11, you can use a constexpr:

constexpr int n()
{
    return 10;
}

double a[n()]; // n() is a compile time constant expression

Linq to Sql: Multiple left outer joins

I think you should be able to follow the method used in this post. It looks really ugly, but I would think you could do it twice and get the result you want.

I wonder if this is actually a case where you'd be better off using DataContext.ExecuteCommand(...) instead of converting to linq.

Jquery - How to get the style display attribute "none / block"

//animated show/hide

function showHide(id) {
      var hidden= ("none" == $( "#".concat(id) ).css("display"));
      if(hidden){
          $( "#".concat(id) ).show(1000);
      }else{
          $("#".concat(id) ).hide(1000);
      }
  }

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

I use the below approach.

reg = linear_model.LinearRegression()
reg.fit(df[['year']],df.income)

reg.predict([[2136]])

How do I programmatically force an onchange event on an input?

For some reason ele.onchange() is throwing a "method not found" expception for me in IE on my page, so I ended up using this function from the link Kolten provided and calling fireEvent(ele, 'change'), which worked:

function fireEvent(element,event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}

I did however, create a test page that confirmed calling should onchange() work:

<input id="test1" name="test1" value="Hello" onchange="alert(this.value);"/>
<input type="button" onclick="document.getElementById('test1').onchange();" value="Say Hello"/>

Edit: The reason ele.onchange() didn't work was because I hadn't actually declared anything for the onchange event. But the fireEvent still works.

HTTP Get with 204 No Content: Is that normal

Your current combination of a POST with an HTTP 204 response is fine.

Using a POST as a universal replacement for a GET is not supported by the RFC, as each has its own specific purpose and semantics.

The purpose of a GET is to retrieve a resource. Therefore, while allowed, an HTTP 204 wouldn't be the best choice since content IS expected in the response. An HTTP 404 Not Found or an HTTP 410 Gone would be better choices if the server was unable to provide the requested resource.

The RFC also specifically calls out an HTTP 204 as an appropriate response for PUT, POST and DELETE, but omits it for GET.

See the RFC for the semantics of GET.

There are other response codes that could also be returned, indicating no content, that would be more appropriate than an HTTP 204.

For example, for a conditional GET you could receive an HTTP 304 Not Modified response which would contain no body content.

Is there an arraylist in Javascript?

Just use array.push(something);. Javascript arrays are like ArrayLists in this respect - they can be treated like they have a flexible length (unlike java arrays).

Disable output buffering

I would rather put my answer in How to flush output of print function? or in Python's print function that flushes the buffer when it's called?, but since they were marked as duplicates of this one (what I do not agree), I'll answer it here.

Since Python 3.3, print() supports the keyword argument "flush" (see documentation):

print('Hello World!', flush=True)

Spark SQL: apply aggregate functions to a list of columns

Current answers are perfectly correct on how to create the aggregations, but none actually address the column alias/renaming that is also requested in the question.

Typically, this is how I handle this case:

val dimensionFields = List("col1")
val metrics = List("col2", "col3", "col4")
val columnOfInterests = dimensions ++ metrics

val df = spark.read.table("some_table"). 
    .select(columnOfInterests.map(c => col(c)):_*)
    .groupBy(dimensions.map(d => col(d)): _*)
    .agg(metrics.map( m => m -> "sum").toMap)
    .toDF(columnOfInterests:_*)    // that's the interesting part

The last line essentially renames every columns of the aggregated dataframe to the original fields, essentially changing sum(col2) and sum(col3) to simply col2 and col3.

What is the best alternative IDE to Visual Studio

For .NET development, VS2008 is the best but if you want to check for another best IDE, Eclipse probably the best after VS if you are rating it among the IDEs, ofcourse you cant do .NET development in Eclipse though

How do I calculate a point on a circle’s circumference?

Implemented in JavaScript (ES6):

/**
    * Calculate x and y in circle's circumference
    * @param {Object} input - The input parameters
    * @param {number} input.radius - The circle's radius
    * @param {number} input.angle - The angle in degrees
    * @param {number} input.cx - The circle's origin x
    * @param {number} input.cy - The circle's origin y
    * @returns {Array[number,number]} The calculated x and y
*/
function pointsOnCircle({ radius, angle, cx, cy }){

    angle = angle * ( Math.PI / 180 ); // Convert from Degrees to Radians
    const x = cx + radius * Math.sin(angle);
    const y = cy + radius * Math.cos(angle);
    return [ x, y ];

}

Usage:

const [ x, y ] = pointsOnCircle({ radius: 100, angle: 180, cx: 150, cy: 150 });
console.log( x, y );

Codepen

_x000D_
_x000D_
/**
 * Calculate x and y in circle's circumference
 * @param {Object} input - The input parameters
 * @param {number} input.radius - The circle's radius
 * @param {number} input.angle - The angle in degrees
 * @param {number} input.cx - The circle's origin x
 * @param {number} input.cy - The circle's origin y
 * @returns {Array[number,number]} The calculated x and y
 */
function pointsOnCircle({ radius, angle, cx, cy }){
  angle = angle * ( Math.PI / 180 ); // Convert from Degrees to Radians
  const x = cx + radius * Math.sin(angle);
  const y = cy + radius * Math.cos(angle);
  return [ x, y ];
}

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

function draw( x, y ){

  ctx.clearRect( 0, 0, canvas.width, canvas.height );
  ctx.beginPath();
  ctx.strokeStyle = "orange";
  ctx.arc( 100, 100, 80, 0, 2 * Math.PI);
  ctx.lineWidth = 3;
  ctx.stroke();
  ctx.closePath();

  ctx.beginPath();
  ctx.fillStyle = "indigo";
  ctx.arc( x, y, 6, 0, 2 * Math.PI);
  ctx.fill();
  ctx.closePath();
  
}

let angle = 0;  // In degrees
setInterval(function(){

  const [ x, y ] = pointsOnCircle({ radius: 80, angle: angle++, cx: 100, cy: 100 });
  console.log( x, y );
  draw( x, y );
  document.querySelector("#degrees").innerHTML = angle + "&deg;";
  document.querySelector("#points").textContent = x.toFixed() + "," + y.toFixed();

}, 100 );
_x000D_
<p>Degrees: <span id="degrees">0</span></p>
<p>Points on Circle (x,y): <span id="points">0,0</span></p>
<canvas width="200" height="200" style="border: 1px solid"></canvas>
_x000D_
_x000D_
_x000D_

javac error: Class names are only accepted if annotation processing is explicitly requested

I learned that you also can get this error by storing the source file in a folder named Java

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

TypeScript static classes

Abstract classes have been a first-class citizen of TypeScript since TypeScript 1.6. You cannot instantiate an abstract class.

Here is an example:

export abstract class MyClass {         
    public static myProp = "Hello";

    public static doSomething(): string {
      return "World";
    }
}

const okay = MyClass.doSomething();

//const errors = new MyClass(); // Error

Calculate logarithm in python

math.log10(1.5)

Use the log10 function in the math module.

Python Database connection Close

You can wrap the whole connection in a context manager, like the following:

from contextlib import contextmanager
import pyodbc
import sys

@contextmanager
def open_db_connection(connection_string, commit=False):
    connection = pyodbc.connect(connection_string)
    cursor = connection.cursor()
    try:
        yield cursor
    except pyodbc.DatabaseError as err:
        error, = err.args
        sys.stderr.write(error.message)
        cursor.execute("ROLLBACK")
        raise err
    else:
        if commit:
            cursor.execute("COMMIT")
        else:
            cursor.execute("ROLLBACK")
    finally:
        connection.close()

Then do something like this where ever you need a database connection:

with open_db_connection("...") as cursor:
    # Your code here

The connection will close when you leave the with block. This will also rollback the transaction if an exception occurs or if you didn't open the block using with open_db_connection("...", commit=True).

javascript multiple OR conditions in IF statement

because the OR operator will return true if any one of the conditions is true, and in your code there are two conditions that are true.

If '<selector>' is an Angular component, then verify that it is part of this module

are you importing it in your app.module.ts like so and remove the directives bit:-

@NgModule({
    bootstrap: [AppComponent],
    imports: [MyComponentModule],// or whatever the name of the module is that declares your component.

    declarations: [AppComponent],
    providers: []
})
export class AppModule {}

Your MyComponentModule should be like this:-

@NgModule({
    imports: [],
    exports: [MyComponentComponent],
    declarations: [MyComponentComponent],
    providers: [],
})
export class MyComponentModule {
}

jsPDF multi page PDF with HTML renderer

here's an example using html2canvas & jspdf, although how you generate the canvas doesn't matter--we're just going to use the height of that as the breakpoint on a for loop, in which a new page is created and content added to it.

after the for loop, the pdf is saved.

function makePDF() {

       var quotes = document.getElementById('container-fluid');
       html2canvas(quotes)
      .then((canvas) => {
            //! MAKE YOUR PDF
            var pdf = new jsPDF('p', 'pt', 'letter');

            for (var i = 0; i <= quotes.clientHeight/980; i++) {
                //! This is all just html2canvas stuff
                var srcImg  = canvas;
                var sX      = 0;
                var sY      = 980*i; // start 980 pixels down for every new page
                var sWidth  = 900;
                var sHeight = 980;
                var dX      = 0;
                var dY      = 0;
                var dWidth  = 900;
                var dHeight = 980;

                window.onePageCanvas = document.createElement("canvas");
                onePageCanvas.setAttribute('width', 900);
                onePageCanvas.setAttribute('height', 980);
                var ctx = onePageCanvas.getContext('2d');
                // details on this usage of this function: 
                // https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images#Slicing
                ctx.drawImage(srcImg,sX,sY,sWidth,sHeight,dX,dY,dWidth,dHeight);

                // document.body.appendChild(canvas);
                var canvasDataURL = onePageCanvas.toDataURL("image/png", 1.0);

                var width         = onePageCanvas.width;
                var height        = onePageCanvas.clientHeight;

                //! If we're on anything other than the first page,
                // add another page
                if (i > 0) {
                    pdf.addPage(612, 791); //8.5" x 11" in pts (in*72)
                }
                //! now we declare that we're working on that page
                pdf.setPage(i+1);
                //! now we add content to that page!
                pdf.addImage(canvasDataURL, 'PNG', 20, 40, (width*.62), (height*.62));

            }
            //! after the for loop is finished running, we save the pdf.
            pdf.save('Test.pdf');
        }
      });
    }

JAVA How to remove trailing zeros from a double

Use DecimalFormat

  double answer = 5.0;
   DecimalFormat df = new DecimalFormat("###.#");
  System.out.println(df.format(answer));

Configuring RollingFileAppender in log4j

I had a similar problem and just found a way to solve it (by single-stepping through log4j-extras source, no less...)

The good news is that, unlike what's written everywhere, it turns out that you actually CAN configure TimeBasedRollingPolicy using log4j.properties (XML config not needed! At least in versions of log4j >1.2.16 see this bug report)

Here is an example:

log4j.appender.File = org.apache.log4j.rolling.RollingFileAppender
log4j.appender.File.rollingPolicy = org.apache.log4j.rolling.TimeBasedRollingPolicy
log4j.appender.File.rollingPolicy.FileNamePattern = logs/worker-${instanceId}.%d{yyyyMMdd-HHmm}.log

BTW the ${instanceId} bit is something I am using on Amazon's EC2 to distinguish the logs from all my workers -- I just need to set that property before calling PropertyConfigurator.configure(), as follow:

p.setProperty("instanceId", EC2Util.getMyInstanceId());
PropertyConfigurator.configure(p);

Login with facebook android sdk app crash API 4

The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):

Mikhail,

The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.

Good luck with your implementation.

How to limit the maximum value of a numeric field in a Django model?

You could also create a custom model field type - see http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields

In this case, you could 'inherit' from the built-in IntegerField and override its validation logic.

The more I think about this, I realize how useful this would be for many Django apps. Perhaps a IntegerRangeField type could be submitted as a patch for the Django devs to consider adding to trunk.

This is working for me:

from django.db import models

class IntegerRangeField(models.IntegerField):
    def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs):
        self.min_value, self.max_value = min_value, max_value
        models.IntegerField.__init__(self, verbose_name, name, **kwargs)
    def formfield(self, **kwargs):
        defaults = {'min_value': self.min_value, 'max_value':self.max_value}
        defaults.update(kwargs)
        return super(IntegerRangeField, self).formfield(**defaults)

Then in your model class, you would use it like this (field being the module where you put the above code):

size = fields.IntegerRangeField(min_value=1, max_value=50)

OR for a range of negative and positive (like an oscillator range):

size = fields.IntegerRangeField(min_value=-100, max_value=100)

What would be really cool is if it could be called with the range operator like this:

size = fields.IntegerRangeField(range(1, 50))

But, that would require a lot more code since since you can specify a 'skip' parameter - range(1, 50, 2) - Interesting idea though...

Missing artifact com.oracle:ojdbc6:jar:11.2.0 in pom.xml

You might have problem on Windows while adding jar to maven because of syntax.

Try encapsulating -D parameters with double quotas like this;

mvn install:install-file "-Dfile=ojdbc6.jar" "-DgroupId=com.oracle" "-DartifactId=ojdbc6" "-Dversion=11.2.0" "-Dpackaging=jar" 

Be aware of you should use same version/atifactId/groupId inside your pom.xml. You can't use version 11.2.0.3 after command above. You have to put his in you pom.xml;

    <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc6</artifactId>
        <version>11.2.0</version>
    </dependency>

If you want to use another version, like 12.1.0.1, you should run above command with that version or other info

What MySQL data type should be used for Latitude/Longitude with 8 decimal places?

in laravel used decimal column type for migration

$table->decimal('latitude', 10, 8);
$table->decimal('longitude', 11, 8);

for more information see available column type

Swift addsubview and remove it

Assuming you have access to it via outlets or programmatic code, you can remove it by referencing your view foo and the removeFromSuperview method

foo.removeFromSuperview()

When should I use Memcache instead of Memcached?

When using Windows, the comparison is cut short: memcache appears to be the only client available.

How can I mock requests and the response?

Here is a solution with requests Response class. It is cleaner IMHO.

from unittest.mock import patch
from requests.models import Response

def mocked_request_get(*args, **kwargs):
    response_content = None
    request_url = kwargs.get('url', None)
    if request_url == 'aurl':
        response_content = json.dumps('a response')
    elif request_url == 'burl':
        response_content = json.dumps('b response')
    elif request_url == 'curl':
        response_content = json.dumps('c response')
    response = Response()
    response.status_code = 200
    response._content = str.encode(response_content)
    return response

@mock.patch('requests.get', side_effect=mocked_requests_get)
def test_fetch(self, mock_get):
     response = call_your_view()
     assert ...

How to display an error message in an ASP.NET Web Application

The errors in ASP.Net are saved on the Server.GetLastError property,

Or i would put a label on the asp.net page for displaying the error.

try
{
    do something
}
catch (YourException ex)
{
    errorLabel.Text = ex.Message;
    errorLabel.Visible = true;
}

Understanding SQL Server LOCKS on SELECT queries

At my work, we have a very big system that runs on many PCs at the same time, with very big tables with hundreds of thousands of rows, and sometimes many millions of rows.

When you make a SELECT on a very big table, let's say you want to know every transaction a user has made in the past 10 years, and the primary key of the table is not built in an efficient way, the query might take several minutes to run.

Then, our application might me running on many user's PCs at the same time, accessing the same database. So if someone tries to insert into the table that the other SELECT is reading (in pages that SQL is trying to read), then a LOCK can occur and the two transactions block each other.

We had to add a "NO LOCK" to our SELECT statement, because it was a huge SELECT on a table that is used a lot by a lot of users at the same time and we had LOCKS all the time.

I don't know if my example is clear enough? This is a real life example.

Exporting results of a Mysql query to excel?

Use the below query:

 SELECT * FROM document INTO OUTFILE 'c:/order-1.csv' FIELDS TERMINATED BY ','  
 ENCLOSED BY '"' LINES TERMINATED BY '\n';

How to read one single line of csv data in Python?

To print a range of line, in this case from line 4 to 7

import csv

with open('california_housing_test.csv') as csv_file:
    data = csv.reader(csv_file)
    for row in list(data)[4:7]:
        print(row)

error LNK2005, already defined?

Why this error?

You broke the one definition rule and hence the linking error.

Suggested Solutions:


If you need the same named variable in the two cpp files then You need to use Nameless namespace(Anonymous Namespace) to avoid the error.

namespace 
{
    int k;
}

If you need to share the same variable across multiple files then you need to use extern.

A.h

extern int k;

A.cpp

#include "A.h"
int k = 0;

B.cpp

#include "A.h"

//Use `k` anywhere in the file 

How to set button click effect in Android?

To make your item consistent with the system look and feel try referencing the system attribute android:attr/selectableItemBackground in your desired view's background or foreground tag:

<ImageView
    ...
    android:background="?android:attr/selectableItemBackground"      
    android:foreground="?android:attr/selectableItemBackground"
    ...
/>

Use both attributes to get desired effect before/after API level 23 respectively.

https://stackoverflow.com/a/11513474/4683601

How to use JavaScript to change the form action

Try this:

var frm = document.getElementById('search-theme-form') || null;
if(frm) {
   frm.action = 'whatever_you_need.ext' 
}

How do you grep a file and get the next 5 lines

You want:

grep -A 5 '19:55' file

From man grep:

Context Line Control

-A NUM, --after-context=NUM

Print NUM lines of trailing context after matching lines.  
Places a line containing a gup separator (described under --group-separator) 
between contiguous groups of matches.  With the -o or --only-matching
option, this has no effect and a warning is given.

-B NUM, --before-context=NUM

Print NUM lines of leading context before matching lines.  
Places a line containing a group separator (described under --group-separator) 
between contiguous groups of matches.  With the -o or --only-matching
option, this has no effect and a warning is given.

-C NUM, -NUM, --context=NUM

Print NUM lines of output context.  Places a line containing a group separator
(described under --group-separator) between contiguous groups of matches.  
With the -o or --only-matching option,  this  has  no effect and a warning
is given.

--group-separator=SEP

Use SEP as a group separator. By default SEP is double hyphen (--).

--no-group-separator

Use empty string as a group separator.

Key Presses in Python

Alternative way to set prefer window into foreground before send key press event.

hwnd = win32gui.FindWindowEx(0,0,0, "App title")
win32gui.SetForegroundWindow(hwnd)

Filter by Dates in SQL

If your dates column does not contain time information, you could get away with:

WHERE dates BETWEEN '20121211' and '20121213'

However, given your dates column is actually datetime, you want this

WHERE dates >= '20121211'
  AND dates < '20121214'  -- i.e. 00:00 of the next day

Another option for SQL Server 2008 onwards that retains SARGability (ability to use index for good performance) is:

WHERE CAST(dates as date) BETWEEN '20121211' and '20121213'

Note: always use ISO-8601 format YYYYMMDD with SQL Server for unambiguous date literals.

How can I pass arguments to a batch file?

I wrote a simple read_params script that can be called as a function (or external .bat) and will put all variables into the current environment. It won't modify the original parameters because the function is being called with a copy of the original parameters.

For example, given the following command:

myscript.bat some -random=43 extra -greeting="hello world" fluff

myscript.bat would be able to use the variables after calling the function:

call :read_params %*

echo %random%
echo %greeting%

Here's the function:

:read_params
if not %1/==/ (
    if not "%__var%"=="" (
        if not "%__var:~0,1%"=="-" (
            endlocal
            goto read_params
        )
        endlocal & set %__var:~1%=%~1
    ) else (
        setlocal & set __var=%~1
    )
    shift
    goto read_params
)
exit /B

Limitations

  • Cannot load arguments with no value such as -force. You could use -force=true but I can't think of a way to allow blank values without knowing a list of parameters ahead of time that won't have a value.

Changelog

  • 2/18/2016
    • No longer requires delayed expansion
    • Now works with other command line arguments by looking for - before parameters.

Show data on mouseover of circle

I assume that what you want is a tooltip. The easiest way to do this is to append an svg:title element to each circle, as the browser will take care of showing the tooltip and you don't need the mousehandler. The code would be something like

vis.selectAll("circle")
   .data(datafiltered).enter().append("svg:circle")
   ...
   .append("svg:title")
   .text(function(d) { return d.x; });

If you want fancier tooltips, you could use tipsy for example. See here for an example.

jQuery: Check if special characters exists in string

You are checking whether the string contains all illegal characters. Change the ||s to &&s.

*ngIf and *ngFor on same element causing error

You can not use more than one Structural Directive in Angular on the same element, it makes a bad confusion and structure, so you need to apply them in 2 separate nested elements(or you can use ng-container), read this statement from Angular team:

One structural directive per host element

Someday you'll want to repeat a block of HTML but only when a particular condition is true. You'll try to put both an *ngFor and an *ngIf on the same host element. Angular won't let you. You may apply only one structural directive to an element.

The reason is simplicity. Structural directives can do complex things with the host element and its descendents. When two directives lay claim to the same host element, which one takes precedence? Which should go first, the NgIf or the NgFor? Can the NgIf cancel the effect of the NgFor? If so (and it seems like it should be so), how should Angular generalize the ability to cancel for other structural directives?

There are no easy answers to these questions. Prohibiting multiple structural directives makes them moot. There's an easy solution for this use case: put the *ngIf on a container element that wraps the *ngFor element. One or both elements can be an ng-container so you don't have to introduce extra levels of HTML.

So you can use ng-container (Angular4) as the wrapper (will be deleted from the dom) or a div or span if you have class or some other attributes as below:

<div class="right" *ngIf="show">
  <div *ngFor="let thing of stuff">
    {{log(thing)}}
    <span>{{thing.name}}</span>
  </div>
</div>

Visual Studio 2015 is very slow

This might just help someone, in addition to what other answers have mentioned.

Clear the contents of AppData\Local\Microsoft\WebSiteCache folder.

In my case I had VS 2015 pro update 3 and this is what helped me speed up VS.

Amazon AWS Filezilla transfer permission denied

If you're using Ubuntu then use the following:

sudo chown -R ubuntu /var/www/html

sudo chmod -R 755 /var/www/html

Adding dictionaries together, Python

Here are quite a few ways to add dictionaries.

You can use Python3's dictionary unpacking feature.

ndic = {**dic0, **dic1}

Or create a new dict by adding both items.

ndic = dict(dic0.items() + dic1.items())

If your ok to modify dic0

dic0.update(dic1)

If your NOT ok to modify dic0

ndic = dic0.copy()
ndic.update(dic1)

If all the keys in one dict are ensured to be strings (dic1 in this case, of course args can be swapped)

ndic = dict(dic0, **dic1)

In some cases it may be handy to use dict comprehensions (Python 2.7 or newer),
Especially if you want to filter out or transform some keys/values at the same time.

ndic = {k: v for d in (dic0, dic1) for k, v in d.items()}