Programs & Examples On #Xpcom

XPCOM (Cross Platform Component Object Model) is a cross-platform component model from Mozilla. It is similar to Microsoft COM and CORBA.

JavaScript - onClick to get the ID of the clicked button

You need to send the ID as the function parameters. Do it like this:

_x000D_
_x000D_
<button id="1" onClick="reply_click(this.id)">B1</button>_x000D_
<button id="2" onClick="reply_click(this.id)">B2</button>_x000D_
<button id="3" onClick="reply_click(this.id)">B3</button>_x000D_
    _x000D_
<script type="text/javascript">_x000D_
  function reply_click(clicked_id)_x000D_
  {_x000D_
      alert(clicked_id);_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_

This will send the ID this.id as clicked_id which you can use in your function. See it in action here.

Laravel 5.2 Missing required parameters for [Route: user.profile] [URI: user/{nickname}/profile]

My Solution in laravel 5.2

{{ Form::open(['route' => ['votes.submit', $video->id],  'method' => 'POST']) }}
    <button type="submit" class="btn btn-primary">
        <span class="glyphicon glyphicon-thumbs-up"></span> Votar
    </button>
{{ Form::close() }}

My Routes File (under middleware)

Route::post('votar/{id}', [
    'as' => 'votes.submit',
    'uses' => 'VotesController@submit'
]);

Route::delete('votar/{id}', [
    'as' => 'votes.destroy',
    'uses' => 'VotesController@destroy'
]);

java.lang.ClassNotFoundException:com.mysql.jdbc.Driver

If you get this error when you are running it, then probably its because you have not included mysql-connector JAR file to your webserver's lib folder.

Now it is important to add mysql-connector-java-5.1.25-bin.jar to your classpath and also to your webserver's lib directory. Tomcat lib path is given as an example Tomcat 6.0\lib

Does Index of Array Exist

You can check the length of the array to see if item 25 is valid in the sense of being in the array, then you could use

if (array.Length > 25)
{ 
   if (array[25] != null)
   {
       //good
   }
}

to see if the array item itself has been set.

Get table names using SELECT statement in MySQL

Besides using the INFORMATION_SCHEMA table, to use SHOW TABLES to insert into a table you would use the following

<?php
 $sql = "SHOW TABLES FROM $dbname";
 $result = mysql_query($sql);
 $arrayCount = 0
 while ($row = mysql_fetch_row($result)) {
  $tableNames[$arrayCount] = $row[0];
  $arrayCount++; //only do this to make sure it starts at index 0
 }
 foreach ($tableNames as &$name {
  $query = "INSERT INTO metadata (table_name) VALUES ('".$name."')";
  mysql_query($query);
 }
?>

Including non-Python files with setup.py

This works in 2020!

As others said create "MANIFEST.in" where your setup.py is located.

Next in manifest include/exclude all the necessary things. Be careful here regarding the syntax. Ex: lets say we have template folder to be included in the source package.

in manifest file do this :

recursive-include template *

Make sure you leave space between dir-name and pattern for files/dirs like above. Dont do like this like we do in .gitignore

recursive-include template/* [this won't work]

Other option is to use include. There are bunch of options. Look up here at their docs for Manifest.in

And the final important step, include this param in your setup.py and you are good to go!

   setup(
    ...
    include_package_data=True,
    ......
)

Hope that helps! Happy Coding!

Browser/HTML Force download of image from src="data:image/jpeg;base64..."

Simply replace image/jpeg with application/octet-stream. The client would not recognise the URL as an inline-able resource, and prompt a download dialog.

A simple JavaScript solution would be:

//var img = reference to image
var url = img.src.replace(/^data:image\/[^;]+/, 'data:application/octet-stream');
window.open(url);
// Or perhaps: location.href = url;
// Or even setting the location of an <iframe> element, 

Another method is to use a blob: URI:

var img = document.images[0];
img.onclick = function() {
    // atob to base64_decode the data-URI
    var image_data = atob(img.src.split(',')[1]);
    // Use typed arrays to convert the binary data to a Blob
    var arraybuffer = new ArrayBuffer(image_data.length);
    var view = new Uint8Array(arraybuffer);
    for (var i=0; i<image_data.length; i++) {
        view[i] = image_data.charCodeAt(i) & 0xff;
    }
    try {
        // This is the recommended method:
        var blob = new Blob([arraybuffer], {type: 'application/octet-stream'});
    } catch (e) {
        // The BlobBuilder API has been deprecated in favour of Blob, but older
        // browsers don't know about the Blob constructor
        // IE10 also supports BlobBuilder, but since the `Blob` constructor
        //  also works, there's no need to add `MSBlobBuilder`.
        var bb = new (window.WebKitBlobBuilder || window.MozBlobBuilder);
        bb.append(arraybuffer);
        var blob = bb.getBlob('application/octet-stream'); // <-- Here's the Blob
    }

    // Use the URL object to create a temporary URL
    var url = (window.webkitURL || window.URL).createObjectURL(blob);
    location.href = url; // <-- Download!
};

Relevant documentation

How to maintain state after a page refresh in React.js?

We have an application that allows the user to set "parameters" in the page. What we do is set those params on the URL, using React Router (in conjunction with History) and a library that URI-encodes JavaScript objects into a format that can be used as your query string.

When the user selects an option, we can push the value of that onto the current route with:

history.push({pathname: 'path/', search: '?' + Qs.stringify(params)});

pathname can be the current path. In your case params would look something like:

{
  selectedOption: 5
}

Then at the top level of the React tree, React Router will update the props of that component with a prop of location.search which is the encoded value we set earlier, so there will be something in componentWillReceiveProps like:

params = Qs.parse(nextProps.location.search.substring(1));
this.setState({selectedOption: params.selectedOption});

Then that component and its children will re-render with the updated setting. As the information is on the URL it can be bookmarked (or emailed around - this was our use case) and a refresh will leave the app in the same state. This has been working really well for our application.

React Router: https://github.com/reactjs/react-router

History: https://github.com/ReactTraining/history

The query string library: https://github.com/ljharb/qs

Correct use for angular-translate in controllers

What is happening is that Angular-translate is watching the expression with an event-based system, and just as in any other case of binding or two-way binding, an event is fired when the data is retrieved, and the value changed, which obviously doesn't work for translation. Translation data, unlike other dynamic data on the page, must, of course, show up immediately to the user. It can't pop in after the page loads.

Even if you can successfully debug this issue, the bigger problem is that the development work involved is huge. A developer has to manually extract every string on the site, put it in a .json file, manually reference it by string code (ie 'pageTitle' in this case). Most commercial sites have thousands of strings for which this needs to happen. And that is just the beginning. You now need a system of keeping the translations in synch when the underlying text changes in some of them, a system for sending the translation files out to the various translators, of reintegrating them into the build, of redeploying the site so the translators can see their changes in context, and on and on.

Also, as this is a 'binding', event-based system, an event is being fired for every single string on the page, which not only is a slower way to transform the page but can slow down all the actions on the page, if you start adding large numbers of events to it.

Anyway, using a post-processing translation platform makes more sense to me. Using GlobalizeIt for example, a translator can just go to a page on the site and start editing the text directly on the page for their language, and that's it: https://www.globalizeit.com/HowItWorks. No programming needed (though it can be programmatically extensible), it integrates easily with Angular: https://www.globalizeit.com/Translate/Angular, the transformation of the page happens in one go, and it always displays the translated text with the initial render of the page.

Full disclosure: I'm a co-founder :)

Boolean checking in the 'if' condition

Former, of course. Latter is redundant, and only goes to show that you haven't understood the concept of booleans very well.

One more suggestion: Choose a different name for your boolean variable. As per this Java style guide:

is prefix should be used for boolean variables and methods.

isSet, isVisible, isFinished, isFound, isOpen

This is the naming convention for boolean methods and variables used by Sun for the Java core packages.

Using the is prefix solves a common problem of choosing bad boolean names like status or flag. isStatus or isFlag simply doesn't fit, and the programmer is forced to chose more meaningful names.

Setter methods for boolean variables must have set prefix as in:

void setFound(boolean isFound);

There are a few alternatives to the is prefix that fits better in some situations. These are has, can and should prefixes:

boolean hasLicense();
boolean canEvaluate();
boolean shouldAbort = false;

HTML 5 Video "autoplay" not automatically starting in CHROME

Try this:

<video src="{{ asset('path/to/your_video.mp4' )}}" muted autoplay loop playsinline></video>

And put this js after that:

window.addEventListener('load', async () => {
  let video = document.querySelector('video[muted][autoplay]');
  try {
    await video.play();
  } catch (err) {
    video.controls = true;
  }
});

ORA-12516, TNS:listener could not find available handler

You opened a lot of connections and that's the issue. I think in your code, you did not close the opened connection.

A database bounce could temporarily solve, but will re-appear when you do consecutive execution. Also, it should be verified the number of concurrent connections to the database. If maximum DB processes parameter has been reached this is a common symptom.

Courtesy of this thread: https://community.oracle.com/thread/362226?tstart=-1

Remove ALL white spaces from text

Using .replace(/\s+/g,'') works fine;

Example:

this.slug = removeAccent(this.slug).replace(/\s+/g,'');

Simple way to get element by id within a div tag?

A given ID can be only used once in a page. It's invalid HTML to have multiple objects with the same ID, even if they are in different parts of the page.

You could change your HTML to this:

<div id="div1" >
    <input type="text" class="edit1" />
    <input type="text" class="edit2" />
</div>
<div id="div2" >
    <input type="text" class="edit1" />
    <input type="text" class="edit2" />
</div>

Then, you could get the first item in div1 with a CSS selector like this:

#div1 .edit1

On in jQuery:

$("#div1 .edit1")

Or, if you want to iterate the items in one of your divs, you can do it like this:

$("#div1 input").each(function(index) {
    // do something with one of the input objects
});

If I couldn't use a framework like jQuery or YUI, I'd go get Sizzle and include that for it's selector logic (it's the same selector engine as is inside of jQuery) because DOM manipulation is massively easier with a good selector library.

If I couldn't use even Sizzle (which would be a massive drop in developer productivity), you could use plain DOM functions to traverse the children of a given element.

You would use DOM functions like childNodes or firstChild and nextSibling and you'd have to check the nodeType to make sure you only got the kind of elements you wanted. I never write code that way because it's so much less productive than using a selector library.

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

We were having the same issue in .NET core. The solution was to download 32-bit .netcore runtime, and having your project target x86

In your csproj file add

  <PropertyGroup>
    <PlatformTarget>x86</PlatformTarget>  
  </PropertyGroup>

  <PropertyGroup>
    <RunCommand Condition="'$(PlatformTarget)' == 'x86'">$(MSBuildProgramFiles32)\dotnet\dotnet</RunCommand>    
  </PropertyGroup>

This was used for a Windows machine, you'd have to adjust paths and such for Linux/OSX

Mockito - difference between doReturn() and when()

The two syntaxes for stubbing are roughly equivalent. However, you can always use doReturn/when for stubbing; but there are cases where you can't use when/thenReturn. Stubbing void methods is one such. Others include use with Mockito spies, and stubbing the same method more than once.

One thing that when/thenReturn gives you, that doReturn/when doesn't, is type-checking of the value that you're returning, at compile time. However, I believe this is of almost no value - if you've got the type wrong, you'll find out as soon as you run your test.

I strongly recommend only using doReturn/when. There is no point in learning two syntaxes when one will do.

You may wish to refer to my answer at Forming Mockito "grammars" - a more detailed answer to a very closely related question.

net::ERR_INSECURE_RESPONSE in Chrome

I was having this issue when testing my Cordova app on android. It just so happens that this android device does not persist its date, and will reset back to its factory date somehow. The API that it calls has a cert that is valid starting this year, while the device date after bootup is in 2017. For now, I have to adb shell and change the date manually.

Embed Youtube video inside an Android app

there is an official YouTube Android Player API wich you can use. This is a bit more complicated but it is working better than other solutions using webclients.

First you must register your app in Googles API Console. This is completely free until your app gets over 25k request a month (or something like that). There are complete anf great tutorials under the link. I hope you can understand them. If not, ask! :)

CSS selector for a checked radio button's label

If your input is a child element of the label and you have more than one labels, you can combine @Mike's trick with Flexbox + order.

enter image description here

_x000D_
_x000D_
label.switchLabel {
  display: flex;
  justify-content: space-between;
  width: 150px;
}
.switchLabel .left   { order: 1; }
.switchLabel .switch { order: 2; }
.switchLabel .right  { order: 3; }

/* sibling selector ~ */
.switchLabel .switch:not(:checked) ~ span.left { color: lightblue }
.switchLabel .switch:checked ~ span.right { color: lightblue }



/* style the switch */

:root {
  --radio-size: 14px;
}

.switchLabel input.switch  {
  width: var(--radio-size);
  height: var(--radio-size);
  border-radius: 50%;
  border: 1px solid #999999;
  box-sizing: border-box;
  outline: none;
  -webkit-appearance: inherit;
  -moz-appearance: inherit;
  appearance: inherit;
  
  box-shadow: calc(var(--radio-size) / 2) 0 0 0 gray, calc(var(--radio-size) / 4) 0 0 0 gray;
  margin: 0 calc(5px + var(--radio-size) / 2) 0 5px;
}

.switchLabel input.switch:checked {
  box-shadow: calc(-1 * var(--radio-size) / 2) 0 0 0 gray, calc(-1 * var(--radio-size) / 4) 0 0 0 gray;
  margin: 0 5px 0 calc(5px + var(--radio-size) / 2);
}
_x000D_
<label class="switchLabel">
  <input type="checkbox" class="switch" />
  <span class="left">Left</span>
  <span class="right">Right</span>
</label>
_x000D_
_x000D_
_x000D_ asd

html
<label class="switchLabel">
  <input type="checkbox" class="switch"/>
  <span class="left">Left</span>
  <span class="right">Right</span>
</label>
css
label.switchLabel {
  display: flex;
  justify-content: space-between;
  width: 150px;
}
.switchLabel .left   { order: 1; }
.switchLabel .switch { order: 2; }
.switchLabel .right  { order: 3; }

/* sibling selector ~ */
.switchLabel .switch:not(:checked) ~ span.left { color: lightblue }
.switchLabel .switch:checked ~ span.right { color: lightblue }

See it on JSFiddle.

note: Sibling selector only works within the same parent. To work around this, you can make the input hidden at top-level using @Nathan Blair hack.

Error with multiple definitions of function

Here is a highly simplified but hopefully relevant view of what happens when you build your code in C++.

C++ splits the load of generating machine executable code in following different phases -

  1. Preprocessing - This is where any macros - #defines etc you might be using get expanded.

  2. Compiling - Each cpp file along with all the #included files in that file directly or indirectly (together called a compilation unit) is converted into machine readable object code.

    This is where C++ also checks that all functions defined (i.e. containing a body in { } e.g. void Foo( int x){ return Boo(x); }) are referring to other functions in a valid manner.

    The way it does that is by insisting that you provide at least a declaration of these other functions (e.g. void Boo(int); ) before you call it so it can check that you are calling it properly among other things. This can be done either directly in the cpp file where it is called or usually in an included header file.

    Note that only the machine code that corresponds to functions defined in this cpp and included files gets built as the object (binary) version of this compilation unit (e.g. Foo) and not the ones that are merely declared (e.g. Boo).

  3. Linking - This is the stage where C++ goes hunting for stuff declared and called in each compilation unit and links it to the places where it is getting called. Now if there was no definition found of this function the linker gives up and errors out. Similarly if it finds multiple definitions of the same function signature (essentially the name and parameter types it takes) it also errors out as it considers it ambiguous and doesn't want to pick one arbitrarily.

The latter is what is happening in your case. By doing a #include of the fun.cpp file, both fun.cpp and mainfile.cpp have a definition of funct() and the linker doesn't know which one to use in your program and is complaining about it.

The fix as Vaughn mentioned above is to not include the cpp file with the definition of funct() in mainfile.cpp and instead move the declaration of funct() in a separate header file and include that in mainline.cpp. This way the compiler will get the declaration of funct() to work with and the linker would get just one definition of funct() from fun.cpp and will use it with confidence.

C# how to use enum with switch

Two things. First, you need to qualify the enum reference in your test - rather than "PLUS", it should be "Operator.PLUS". Second, this code would be a lot more readable if you used the enum member names rather than their integral values in the switch statement. I've updated your code:

public enum Operator
{
    PLUS, MINUS, MULTIPLY, DIVIDE
}

public static double Calculate(int left, int right, Operator op)
{
    switch (op)
    {
        default:
        case Operator.PLUS:
            return left + right;

        case Operator.MINUS:
            return left - right;

        case Operator.MULTIPLY:
            return left * right;

        case Operator.DIVIDE:
            return left / right;
    }
}

Call this with:

Console.WriteLine("The sum of 5 and 5 is " + Calculate(5, 5, Operator.PLUS));

How to check if a process is running via a batch script

I'm assuming windows here. So, you'll need to use WMI to get that information. Check out The Scripting Guy's archives for a lot of examples on how to use WMI from a script.

How to remove part of a string?

If you want to remove part of string

let str = "test_23";
str.replace("test_", "");
// 23

If you want to replace part of string

let str = "test_23";
str.replace("test_", "student-");
// student-23

What is the Maximum Size that an Array can hold?

Since Length is an int I'd say Int.MaxValue

android start activity from service

UPDATE ANDROID 10 AND HIGHER

Start an activity from service (foreground or background) is no longer allowed.

There are still some restrictions that can be seen in the documentation

https://developer.android.com/guide/components/activities/background-starts

Get a DataTable Columns DataType

if (dr[dc.ColumnName].GetType().ToString() == "System.DateTime")

Read connection string from web.config

Everybody seems to be suggesting that adding

using System.Configuration;

which is true.

But might I suggest that you think about installing ReSharper's Visual Studio extension?

With it installed, instead of seeing an error that a class isn't defined, you'll see a prompt that tells you which assembly it is in, asking you if you want it to add the needed using statement.

How to extract text from an existing docx file using python-docx

There are two "generations" of python-docx. The initial generation ended with the 0.2.x versions and the "new" generation started at v0.3.0. The new generation is a ground-up, object-oriented rewrite of the legacy version. It has a distinct repository located here.

The opendocx() function is part of the legacy API. The documentation is for the new version. The legacy version has no documentation to speak of.

Neither reading nor writing hyperlinks are supported in the current version. That capability is on the roadmap, and the project is under active development. It turns out to be quite a broad API because Word has so much functionality. So we'll get to it, but probably not in the next month unless someone decides to focus on that aspect and contribute it. UPDATE Hyperlink support was added subsequent to this answer.

Pycharm and sys.argv arguments

Add the following to the top of your Python file.

import sys

sys.argv = [
    __file__,
    'arg1',
    'arg2'
]

Now, you can simply right click on the Python script.

JavaScript: Create and destroy class instance through class method

No. JavaScript is automatically garbage collected; the object's memory will be reclaimed only if the GC decides to run and the object is eligible for collection.

Seeing as that will happen automatically as required, what would be the purpose of reclaiming the memory explicitly?

What is the difference between a heuristic and an algorithm?

Heuristic, in a nutshell is an "Educated guess". Wikipedia explains it nicely. At the end, a "general acceptance" method is taken as an optimal solution to the specified problem.

Heuristic is an adjective for experience-based techniques that help in problem solving, learning and discovery. A heuristic method is used to rapidly come to a solution that is hoped to be close to the best possible answer, or 'optimal solution'. Heuristics are "rules of thumb", educated guesses, intuitive judgments or simply common sense. A heuristic is a general way of solving a problem. Heuristics as a noun is another name for heuristic methods.

In more precise terms, heuristics stand for strategies using readily accessible, though loosely applicable, information to control problem solving in human beings and machines.

While an algorithm is a method containing finite set of instructions used to solving a problem. The method has been proven mathematically or scientifically to work for the problem. There are formal methods and proofs.

Heuristic algorithm is an algorithm that is able to produce an acceptable solution to a problem in many practical scenarios, in the fashion of a general heuristic, but for which there is no formal proof of its correctness.

How do I set the path to a DLL file in Visual Studio?

The search path that the loader uses when you call LoadLibrary() can be altered by using the SetDllDirectory() function. So you could just call this and add the path to your dependency before you load it.

See also DLL Search Order.

Getting Date or Time only from a DateTime Object

You can use Instance.ToShortDateString() for the date,
and Instance.ToShortTimeString() for the time to get date and time from the same instance.

How to use mouseover and mouseout in Angular 6

To avoid blinking problem use following code
its not mouseover and mouseout instead of that use mouseenter and mouseleave


**app.component.html**

    <div (mouseenter)="changeText=true" (mouseleave)="changeText=false">
      <span *ngIf="!changeText">Hide</span>
      <span *ngIf="changeText">Show</span>
    </div>

**app.component.ts**

@Component({
   selector: 'app-main',
   templateUrl: './app.component.html'
})
export class AppComponent {
    changeText: boolean;
    constructor() {
       this.changeText = false;
    }
}

Python group by

result = []
# Make a set of your "types":
input_set = set([tpl[1] for tpl in input])
>>> set(['ETH', 'KAT', 'NOT'])
# Iterate over the input_set
for type_ in input_set:
    # a dict to gather things:
    D = {}
    # filter all tuples from your input with the same type as type_
    tuples = filter(lambda tpl: tpl[1] == type_, input)
    # write them in the D:
    D["type"] = type_
    D["itmes"] = [tpl[0] for tpl in tuples]
    # append D to results:
    result.append(D)

result
>>> [{'itmes': ['9085267', '11788544'], 'type': 'NOT'}, {'itmes': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'itmes': ['11013331', '9843236'], 'type': 'KAT'}]

mailto link multiple body lines

You can use URL encoding to encode the newline as %0A.

mailto:[email protected]?subject=test&body=type%20your%0Amessage%20here

While the above appears to work in many cases, user olibre points out that the RFC governing the mailto URI scheme specifies that %0D%0A (carriage return + line feed) should be used instead of %0A (line feed). See also: Newline Representations.

PHP: merge two arrays while keeping keys instead of reindexing?

While this question is quite old I just want to add another possibility of doing a merge while keeping keys.

Besides adding key/values to existing arrays using the + sign you could do an array_replace.

$a = array('foo' => 'bar', 'some' => 'string');
$b = array(42 => 'answer to the life and everything', 1337 => 'leet');

$merged = array_replace($a, $b);

The result will be:

Array
(
  [foo] => bar
  [some] => string
  [42] => answer to the life and everything
  [1337] => leet
)

Same keys will be overwritten by the latter array.
There is also an array_replace_recursive, which do this for subarrays, too.

Live example on 3v4l.org

Custom height Bootstrap's navbar

You need also to set .min-height: 0px; please see bellow:

.navbar-inner {
    min-height: 0px;
}

.navbar-brand,
.navbar-nav li a {
    line-height: 150px;
    height: 150px;
    padding-top: 0;
}

If you set .min-height: 0px; then you can choose any height you want!

Good Luck!

Finding Variable Type in JavaScript

To be a little more ECMAScript-5.1-precise than the other answers (some might say pedantic):

In JavaScript, variables (and properties) don't have types: values do. Further, there are only 6 types of values: Undefined, Null, Boolean, String, Number, and Object. (Technically, there are also 7 "specification types", but you can't store values of those types as properties of objects or values of variables--they are only used within the spec itself, to define how the language works. The values you can explicitly manipulate are of only the 6 types I listed.)

The spec uses the notation "Type(x)" when it wants to talk about "the type of x". This is only a notation used within the spec: it is not a feature of the language.

As other answers make clear, in practice you may well want to know more than the type of a value--particularly when the type is Object. Regardless, and for completeness, here is a simple JavaScript implementation of Type(x) as it is used in the spec:

function Type(x) { 
    if (x === null) {
        return 'Null';
    }

    switch (typeof x) {
    case 'undefined': return 'Undefined';
    case 'boolean'  : return 'Boolean';
    case 'number'   : return 'Number';
    case 'string'   : return 'String';
    default         : return 'Object';
    }
}

Unsafe JavaScript attempt to access frame with URL

Crossframe-Scripting is not possible when the two frames have different domains -> Security.

See this: http://javascript.about.com/od/reference/a/frame3.htm

Now to answer your question: there is no solution or work around, you simply should check your website-design why there must be two frames from different domains that changes the url of the other one.

How do I search for files in Visual Studio Code?

Also works in ubuntu with Ctrl+E

How to convert JSON object to JavaScript array?

var json_data = {"2013-01-21":1,"2013-01-22":7};
var result = [];

for(var i in json_data)
    result.push([i, json_data [i]]);


var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows(result);

http://jsfiddle.net/MV5rj/

Insert line after first match using sed

Sed command that works on MacOS (at least, OS 10) and Unix alike (ie. doesn't require gnu sed like Gilles' (currently accepted) one does):

sed -e '/CLIENTSCRIPT="foo"/a\'$'\n''CLIENTSCRIPT2="hello"' file

This works in bash and maybe other shells too that know the $'\n' evaluation quote style. Everything can be on one line and work in older/POSIX sed commands. If there might be multiple lines matching the CLIENTSCRIPT="foo" (or your equivalent) and you wish to only add the extra line the first time, you can rework it as follows:

sed -e '/^ *CLIENTSCRIPT="foo"/b ins' -e b -e ':ins' -e 'a\'$'\n''CLIENTSCRIPT2="hello"' -e ': done' -e 'n;b done' file

(this creates a loop after the line insertion code that just cycles through the rest of the file, never getting back to the first sed command again).

You might notice I added a '^ *' to the matching pattern in case that line shows up in a comment, say, or is indented. Its not 100% perfect but covers some other situations likely to be common. Adjust as required...

These two solutions also get round the problem (for the generic solution to adding a line) that if your new inserted line contains unescaped backslashes or ampersands they will be interpreted by sed and likely not come out the same, just like the \n is - eg. \0 would be the first line matched. Especially handy if you're adding a line that comes from a variable where you'd otherwise have to escape everything first using ${var//} before, or another sed statement etc.

This solution is a little less messy in scripts (that quoting and \n is not easy to read though), when you don't want to put the replacement text for the a command at the start of a line if say, in a function with indented lines. I've taken advantage that $'\n' is evaluated to a newline by the shell, its not in regular '\n' single-quoted values.

Its getting long enough though that I think perl/even awk might win due to being more readable.

Update query PHP MySQL

Need to add quote for that need to use dot operator:

mysql_query("UPDATE blogEntry SET content = '".$udcontent."', title = '".$udtitle."' WHERE id = '".$id."'");

Prevent wrapping of span or div

Looks like divs will not go outside of their body's width. Even within another div.

I threw this up to test (without a doctype though) and it does not work as thought.

_x000D_
_x000D_
.slideContainer {_x000D_
    overflow-x: scroll;_x000D_
}_x000D_
.slide {_x000D_
    float: left;_x000D_
}
_x000D_
<div class="slideContainer">_x000D_
    <div class="slide" style="background: #f00">Some content Some content Some content Some content Some content Some content</div>_x000D_
    <div class="slide" style="background: #ff0">More content More content More content More content More content More content</div>_x000D_
    <div class="slide" style="background: #f0f">Even More content! Even More content! Even More content!</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What i am thinking is that the inner div's could be loaded through an iFrame, since that is another page and its content could be very wide.

Export JAR with Netbeans

You need to enable the option

Project Properties -> Build -> Packaging -> Build JAR after compiling

(but this is enabled by default)

Whitespace Matching Regex - Java

You can’t use \s in Java to match white space on its own native character set, because Java doesn’t support the Unicode white space property — even though doing so is strictly required to meet UTS#18’s RL1.2! What it does have is not standards-conforming, alas.

Unicode defines 26 code points as \p{White_Space}: 20 of them are various sorts of \pZ GeneralCategory=Separator, and the remaining 6 are \p{Cc} GeneralCategory=Control.

White space is a pretty stable property, and those same ones have been around virtually forever. Even so, Java has no property that conforms to The Unicode Standard for these, so you instead have to use code like this:

String whitespace_chars =  ""       /* dummy empty string for homogeneity */
                        + "\\u0009" // CHARACTER TABULATION
                        + "\\u000A" // LINE FEED (LF)
                        + "\\u000B" // LINE TABULATION
                        + "\\u000C" // FORM FEED (FF)
                        + "\\u000D" // CARRIAGE RETURN (CR)
                        + "\\u0020" // SPACE
                        + "\\u0085" // NEXT LINE (NEL) 
                        + "\\u00A0" // NO-BREAK SPACE
                        + "\\u1680" // OGHAM SPACE MARK
                        + "\\u180E" // MONGOLIAN VOWEL SEPARATOR
                        + "\\u2000" // EN QUAD 
                        + "\\u2001" // EM QUAD 
                        + "\\u2002" // EN SPACE
                        + "\\u2003" // EM SPACE
                        + "\\u2004" // THREE-PER-EM SPACE
                        + "\\u2005" // FOUR-PER-EM SPACE
                        + "\\u2006" // SIX-PER-EM SPACE
                        + "\\u2007" // FIGURE SPACE
                        + "\\u2008" // PUNCTUATION SPACE
                        + "\\u2009" // THIN SPACE
                        + "\\u200A" // HAIR SPACE
                        + "\\u2028" // LINE SEPARATOR
                        + "\\u2029" // PARAGRAPH SEPARATOR
                        + "\\u202F" // NARROW NO-BREAK SPACE
                        + "\\u205F" // MEDIUM MATHEMATICAL SPACE
                        + "\\u3000" // IDEOGRAPHIC SPACE
                        ;        
/* A \s that actually works for Java’s native character set: Unicode */
String     whitespace_charclass = "["  + whitespace_chars + "]";    
/* A \S that actually works for  Java’s native character set: Unicode */
String not_whitespace_charclass = "[^" + whitespace_chars + "]";

Now you can use whitespace_charclass + "+" as the pattern in your replaceAll.


Sorry ’bout all that. Java’s regexes just don’t work very well on its own native character set, and so you really have to jump through exotic hoops to make them work.

And if you think white space is bad, you should see what you have to do to get \w and \b to finally behave properly!

Yes, it’s possible, and yes, it’s a mindnumbing mess. That’s being charitable, even. The easiest way to get a standards-comforming regex library for Java is to JNI over to ICU’s stuff. That’s what Google does for Android, because OraSun’s doesn’t measure up.

If you don’t want to do that but still want to stick with Java, I have a front-end regex rewriting library I wrote that “fixes” Java’s patterns, at least to get them conform to the requirements of RL1.2a in UTS#18, Unicode Regular Expressions.

Repeat command automatically in Linux

"watch" does not allow fractions of a second in Busybox, while "sleep" does. If that matters to you, try this:

while true; do ls -l; sleep .5; done

jQuery Ajax simple call

You could also make the ajax call more generic, reusable, so you can call it from different CRUD(create, read, update, delete) tasks for example and treat the success cases from those calls.

makePostCall = function (url, data) { // here the data and url are not hardcoded anymore
   var json_data = JSON.stringify(data);

    return $.ajax({
        type: "POST",
        url: url,
        data: json_data,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    });
}

// and here a call example
makePostCall("index.php?action=READUSERS", {'city' : 'Tokio'})
    .success(function(data){
               // treat the READUSERS data returned
   })
    .fail(function(sender, message, details){
           alert("Sorry, something went wrong!");
  });

How do I create a crontab through a script

Here is how to modify cron a entry without directly editing the cron file (which is frowned upon).

crontab -l -u <user> | sed 's/find/replace/g' | crontab -u <user> -

If you want to remove a cron entry, use this:

crontab -l -u <user> | sed '/find/d' | crontab -u <user> -

I realize this is not what gaurav was asking for, but why not have all the solutions in one place?

git - Server host key not cached

In Windows 7 or 10, the trick that worked for me is deleting the GIT_SSH system variable. It was set before to use Plink, and now was replaced by Putty. This was causing Plink.exe error

There was also an old installation of Git (32-bit version) and updating to Git(e.g. Git-2.20.1-64-bit.exe) since the PC was 64-bit OS.

Anyway the Putty/Plink was not even used by Git since in the Git installation it was default to use Open SSH.

Create hyperlink to another sheet

Something like the following will loop through column A in the Control sheet and turn the values in the cells into Hyperlinks. Not something I've had to do before so please excuse bugs:

Sub CreateHyperlinks()

Dim mySheet As String
Dim myRange As Excel.Range
Dim cell As Excel.Range
Set myRange = Excel.ThisWorkbook.Sheets("Control").Range("A1:A5") '<<adjust range to suit

For Each cell In myRange
    Excel.ThisWorkbook.Sheets("Control").Hyperlinks.Add Anchor:=cell, Address:="", SubAddress:=cell.Value & "!A1" '<<from recorded macro
Next cell

End Sub

How do I get an animated gif to work in WPF?

Thanks for your post Joel, it helped me solve WPF's absence of support for animated GIFs. Just adding a little code since I had a heck of a time with setting the pictureBoxLoading.Image property due to the Winforms api.

I had to set my animated gif image's Build Action as "Content" and the Copy to output directory to "Copy if newer" or "always". Then in the MainWindow() I called this method. Only issue is that when I tried to dispose of the stream, it gave me a red envelope graphic instead of my image. I'll have to solve that problem. This removed the pain of loading a BitmapImage and changing it into a Bitmap (which obviously killed my animation because it is no longer a gif).

private void SetupProgressIcon()
{
   Uri uri = new Uri("pack://application:,,,/WPFTest;component/Images/animated_progress_apple.gif");
   if (uri != null)
   {
      Stream stream = Application.GetContentStream(uri).Stream;   
      imgProgressBox.Image = new System.Drawing.Bitmap(stream);
   }
}

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

This is another version which work in case you have some tasks to cleanup. Code will leave clean up process in their method.

package main

import (
    "fmt"
    "os"
    "os/signal"
    "syscall"

)



func main() {

    _,done1:=doSomething1()
    _,done2:=doSomething2()

    //do main thread


    println("wait for finish")
    <-done1
    <-done2
    fmt.Print("clean up done, can exit safely")

}

func doSomething1() (error, chan bool) {
    //do something
    done:=make(chan bool)
    c := make(chan os.Signal, 2)
    signal.Notify(c, os.Interrupt, syscall.SIGTERM)
    go func() {
        <-c
        //cleanup of something1
        done<-true
    }()
    return nil,done
}


func doSomething2() (error, chan bool) {
    //do something
    done:=make(chan bool)
    c := make(chan os.Signal, 2)
    signal.Notify(c, os.Interrupt, syscall.SIGTERM)
    go func() {
        <-c
        //cleanup of something2
        done<-true
    }()
    return nil,done
}

in case you need to clean main function you need to capture signal in main thread using go func() as well.

How to handle ListView click in Android

The two answers before mine are correct - you can use OnItemClickListener.

It's good to note that the difference between OnItemClickListener and OnItemSelectedListener, while sounding subtle, is in fact significant, as item selection and focus are related with the touch mode of your AdapterView.

By default, in touch mode, there is no selection and focus. You can take a look here for further info on the subject.

How to enable support of CPU virtualization on Macbook Pro?

CPU Virtualization is enabled by default on all MacBooks with compatible CPUs (i7 is compatible). You can try to reset PRAM if you think it was disabled somehow, but I doubt it.

I think the issue might be in the old version of OS. If your MacBook is i7, then you better upgrade OS to something newer.

Can you overload controller methods in ASP.NET MVC?

No,No and No. Go and try the controller code below where we have the "LoadCustomer" overloaded.

public class CustomerController : Controller
    {
        //
        // GET: /Customer/

        public ActionResult LoadCustomer()
        {
            return Content("LoadCustomer");
        }
        public ActionResult LoadCustomer(string str)
        {
            return Content("LoadCustomer with a string");
        }
    }

If you try to invoke the "LoadCustomer" action you will get error as shown in the below figure.

enter image description here

Polymorphism is a part of C# programming while HTTP is a protocol. HTTP does not understand polymorphism. HTTP works on the concept's or URL and URL can only have unique name's. So HTTP does not implement polymorphism.

In order to fix the same we need to use "ActionName" attribute.

public class CustomerController : Controller
    {
        //
        // GET: /Customer/

        public ActionResult LoadCustomer()
        {
            return Content("LoadCustomer");
        }

        [ActionName("LoadCustomerbyName")]
        public ActionResult LoadCustomer(string str)
        {
            return Content("LoadCustomer with a string");
        }
    }

So now if you make a call to URL "Customer/LoadCustomer" the "LoadCustomer" action will be invoked and with URL structure "Customer/LoadCustomerByName" the "LoadCustomer(string str)" will be invoked.

enter image description here

enter image description here

The above answer i have taken from this codeproject article --> MVC Action overloading

Pad left or right with string.format (not padleft or padright) with arbitrary string

There is another solution.

Implement IFormatProvider to return a ICustomFormatter that will be passed to string.Format :

public class StringPadder : ICustomFormatter
{
  public string Format(string format, object arg,
       IFormatProvider formatProvider)
  {
     // do padding for string arguments
     // use default for others
  }
}

public class StringPadderFormatProvider : IFormatProvider
{
  public object GetFormat(Type formatType)
  { 
     if (formatType == typeof(ICustomFormatter))
        return new StringPadder();

     return null;
  }
  public static readonly IFormatProvider Default =
     new StringPadderFormatProvider();
}

Then you can use it like this :

string.Format(StringPadderFormatProvider.Default, "->{0:x20}<-", "Hello");

sql like operator to get the numbers only

You can try this

ISNUMERIC (Transact-SQL)

ISNUMERIC returns 1 when the input expression evaluates to a valid numeric data type; otherwise it returns 0.

DECLARE @Table TABLE(
        Col VARCHAR(50)
)

INSERT INTO @Table SELECT 'ABC' 
INSERT INTO @Table SELECT 'Italy' 
INSERT INTO @Table SELECT 'Apple' 
INSERT INTO @Table SELECT '234.62' 
INSERT INTO @Table SELECT '2:234:43:22' 
INSERT INTO @Table SELECT 'France' 
INSERT INTO @Table SELECT '6435.23'
INSERT INTO @Table SELECT '2' 
INSERT INTO @Table SELECT 'Lions'

SELECT  *
FROM    @Table
WHERE   ISNUMERIC(Col) = 1

Why do I get "a label can only be part of a statement and a declaration is not a statement" if I have a variable that is initialized after a label?

The language standard simply doesn't allow for it. Labels can only be followed by statements, and declarations do not count as statements in C. The easiest way to get around this is by inserting an empty statement after your label, which relieves you from keeping track of the scope the way you would need to inside a block.

#include <stdio.h>
int main () 
{
    printf("Hello ");
    goto Cleanup;
Cleanup: ; //This is an empty statement.
    char *str = "World\n";
    printf("%s\n", str);
}

How to add header data in XMLHttpRequest when using formdata?

Use: xmlhttp.setRequestHeader(key, value);

How to add content to html body using JS?

Just:

    document.getElementById('myDiv').innerHTMl += "New Content";

How to convert this var string to URL in Swift

In Swift3:
let fileUrl = Foundation.URL(string: filePath)

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

Python dict how to create key or append an element to key?

Use dict.setdefault():

dic.setdefault(key,[]).append(value)

help(dict.setdefault):

    setdefault(...)
        D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

How do I apply a style to all children of an element

As commented by David Thomas, descendants of those child elements will (likely) inherit most of the styles assigned to those child elements.

You need to wrap your .myTestClass inside an element and apply the styles to descendants by adding .wrapper * descendant selector. Then, add .myTestClass > * child selector to apply the style to the elements children, not its grand children. For example like this:

JSFiddle - DEMO

_x000D_
_x000D_
.wrapper * {_x000D_
    color: blue;_x000D_
    margin: 0 100px; /* Only for demo */_x000D_
}_x000D_
.myTestClass > * {_x000D_
    color:red;_x000D_
    margin: 0 20px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
    <div class="myTestClass">Text 0_x000D_
        <div>Text 1</div>_x000D_
        <span>Text 1</span>_x000D_
        <div>Text 1_x000D_
            <p>Text 2</p>_x000D_
            <div>Text 2</div>_x000D_
        </div>_x000D_
        <p>Text 1</p>_x000D_
    </div>_x000D_
    <div>Text 0</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Flexbox and Internet Explorer 11 (display:flex in <html>?)

According to http://caniuse.com/#feat=flexbox:

"IE10 and IE11 default values for flex are 0 0 auto rather than 0 1 auto, as per the draft spec, as of September 2013"

So in plain words, if somewhere in your CSS you have something like this: flex:1 , that is not translated the same way in all browsers. Try changing it to 1 0 0 and I believe you will immediately see that it -kinda- works.

The problem is that this solution will probably mess up firefox, but then you can use some hacks to target only Mozilla and change it back:

@-moz-document url-prefix() {
 #flexible-content{
      flex: 1;
    }
}

Since flexbox is a W3C Candidate and not official, browsers tend to give different results, but I guess that will change in the immediate future.

If someone has a better answer I would like to know!

Multi-select dropdown list in ASP.NET

I've used the open source control at http://dropdowncheckboxes.codeplex.com/ and been very happy with it. My addition was to allow a list of checked files to use just file names instead of full paths if the 'selected' caption gets too long. My addition is called instead of UpdateSelection in your postback handler:

// Update the caption assuming that the items are files<br/> 
// If the caption is too long, eliminate paths from file names<br/> 
public void UpdateSelectionFiles(int maxChars) {
  StringBuilder full = new StringBuilder(); 
  StringBuilder shorter = new StringBuilder();
  foreach (ListItem item in Items) { 
    if (item.Selected) { 
      full.AppendFormat("{0}; ", item.Text);
      shorter.AppendFormat("{0}; ", new FileInfo(item.Text).Name);
    } 
  } 
  if (full.Length == 0) Texts.SelectBoxCaption = "Select...";
  else if (full.Length <= maxChars) Texts.SelectBoxCaption = full.ToString(); 
  else Texts.SelectBoxCaption = shorter.ToString();
} 

jquery change class name

EDIT:

If you're saying that you're changing it from a nested element, you don't need the ID at all. You can do this instead:

$(this).closest('td').toggleClass('change_me some_other_class');
    //or
$(this).parents('td:first').toggleClass('change_me some_other_class');

Original answer:

$('#td_id').removeClass('change_me').addClass('some_other_class');

Another option is:

$('#td_id').toggleClass('change_me some_other_class');

How to get the error message from the error code returned by GetLastError()?

In general, you need to use FormatMessage to convert from a Win32 error code to text.

From the MSDN documentation:

Formats a message string. The function requires a message definition as input. The message definition can come from a buffer passed into the function. It can come from a message table resource in an already-loaded module. Or the caller can ask the function to search the system's message table resource(s) for the message definition. The function finds the message definition in a message table resource based on a message identifier and a language identifier. The function copies the formatted message text to an output buffer, processing any embedded insert sequences if requested.

The declaration of FormatMessage:

DWORD WINAPI FormatMessage(
  __in      DWORD dwFlags,
  __in_opt  LPCVOID lpSource,
  __in      DWORD dwMessageId, // your error code
  __in      DWORD dwLanguageId,
  __out     LPTSTR lpBuffer,
  __in      DWORD nSize,
  __in_opt  va_list *Arguments
);

Simulating a click in jQuery/JavaScript on a link

Try this

function submitRequest(buttonId) {
    if (document.getElementById(buttonId) == null
            || document.getElementById(buttonId) == undefined) {
        return;
    }
    if (document.getElementById(buttonId).dispatchEvent) {
        var e = document.createEvent("MouseEvents");
        e.initEvent("click", true, true);
        document.getElementById(buttonId).dispatchEvent(e);
    } else {
        document.getElementById(buttonId).click();
    }
}

and you can use it like

submitRequest("target-element-id");

How to find the index of an element in an array in Java?

The problem with your code is that when you do

 list[] == "e"

you're asking if the array object (not the contents) is equal to the string "e", which is clearly not the case.

You'll want to iterate over the contents in order to do the check you want:

 for(String element : list) {
      if (element.equals("e")) {
           // do something here
      }
 }

How to add \newpage in Rmarkdown in a smart way?

You can make the pagebreak conditional on knitting to PDF. This worked for me.

```{r, results='asis', eval=(opts_knit$get('rmarkdown.pandoc.to') == 'latex')}
cat('\\pagebreak')
```

How to use an arraylist as a prepared statement parameter

@JulienD Best way is to break above process into two steps.

Step 1 : Lets say 'rawList' as your list that you want to add as parameters in prepared statement.

Create another list :

ArrayList<String> listWithQuotes = new ArrayList<String>();

for(String element : rawList){
    listWithQuotes.add("'"+element+"'");
}

Step 2 : Make 'listWithQuotes' comma separated.

String finalString = StringUtils.join(listWithQuotes.iterator(),",");

'finalString' will be string parameters with each element as single quoted and comma separated.

Maven and adding JARs to system scope

System scope was only designed to deal with 'system' files; files sitting in some fixed location. Files in /usr/lib, or ${java.home} (e.g. tools.jar). It wasn't designed to support miscellaneous .jar files in your project.

The authors intentionally refused to make the pathname expansions work right for that to discourage you. As a result, in the short term you can use install:install-file to install into the local repo, and then some day use a repo manager to share.

Doing a join across two databases with different collations on SQL Server and getting an error

A general purpose way is to coerce the collation to DATABASE_DEFAULT. This removes hardcoding the collation name which could change.

It's also useful for temp table and table variables, and where you may not know the server collation (eg you are a vendor placing your system on the customer's server)

select
    sone_field collate DATABASE_DEFAULT
from
    table_1
    inner join
    table_2 on table_1.field collate DATABASE_DEFAULT = table_2.field
where whatever

fork() and wait() with two child processes

It looks to me as though the basic problem is that you have one wait() call rather than a loop that waits until there are no more children. You also only wait if the last fork() is successful rather than if at least one fork() is successful.

You should only use _exit() if you don't want normal cleanup operations - such as flushing open file streams including stdout. There are occasions to use _exit(); this is not one of them. (In this example, you could also, of course, simply have the children return instead of calling exit() directly because returning from main() is equivalent to exiting with the returned status. However, most often you would be doing the forking and so on in a function other than main(), and then exit() is often appropriate.)


Hacked, simplified version of your code that gives the diagnostics I'd want. Note that your for loop skipped the first element of the array (mine doesn't).

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int main(void)
{
    pid_t child_pid, wpid;
    int status = 0;
    int i;
    int a[3] = {1, 2, 1};

    printf("parent_pid = %d\n", getpid());
    for (i = 0; i < 3; i++)
    {
        printf("i = %d\n", i);
        if ((child_pid = fork()) == 0)
        {
            printf("In child process (pid = %d)\n", getpid());
            if (a[i] < 2)
            {
                printf("Should be accept\n");
                exit(1);
            }
            else
            {
                printf("Should be reject\n");
                exit(0);
            }
            /*NOTREACHED*/
        }
    }

    while ((wpid = wait(&status)) > 0)
    {
        printf("Exit status of %d was %d (%s)\n", (int)wpid, status,
               (status > 0) ? "accept" : "reject");
    }
    return 0;
}

Example output (MacOS X 10.6.3):

parent_pid = 15820
i = 0
i = 1
In child process (pid = 15821)
Should be accept
i = 2
In child process (pid = 15822)
Should be reject
In child process (pid = 15823)
Should be accept
Exit status of 15823 was 256 (accept)
Exit status of 15822 was 0 (reject)
Exit status of 15821 was 256 (accept)

OS X: equivalent of Linux's wget

wget Precompiled Mac Binary

For those looking for a quick wget install on Mac, check out Quentin Stafford-Fraser's precompiled binary here, which has been around for over a decade:

https://statusq.org/archives/2008/07/30/1954/

MD5 for 2008 wget.zip: 24a35d499704eecedd09e0dd52175582
MD5 for 2005 wget.zip: c7b48ec3ff929d9bd28ddb87e1a76ffb

No make/install/port/brew/curl junk. Just download, install, and run. Works with Mac OS X 10.3-10.12+.

Execute command on all files in a directory

i think the simple solution is:

sh /dir/* > ./result.txt

How to convert "0" and "1" to false and true

(returnValue != "1" ? false : true);

How can I run NUnit tests in Visual Studio 2017?

Add the NUnit test adapter NuGet package to your test projects

Or install the Test Adapter Visual Studio extension. There is one for

I prefer the NuGet package, because it will be in sync with the NUnit version used by your project and will thus automatically match the version used in any build server.

How to cast an object in Objective-C

Casting for inclusion is just as important as casting for exclusion for a C++ programmer. Type casting is not the same as with RTTI in the sense that you can cast an object to any type and the resulting pointer will not be nil.

Base64 Java encode and decode a string

The accepted answer uses the Apache Commons package but this is how I did it using Java's native libraries

Java 11 and up

import java.util.Base64;

public class Base64Encoding {

    public static void main(String[] args) {
        Base64.Encoder enc = Base64.getEncoder();
        Base64.Decoder dec = Base64.getDecoder();
        String str = "77+9x6s=";

        // encode data using BASE64
        String encoded = enc.encodeToString(str.getBytes());
        System.out.println("encoded value is \t" + encoded);

        // Decode data
        String decoded = new String(dec.decode(encoded));
        System.out.println("decoded value is \t" + decoded);
        System.out.println("original value is \t" + str);
    }
}

Java 6 - 10

import java.io.UnsupportedEncodingException;    
import javax.xml.bind.DatatypeConverter;

public class EncodeString64 {
    public static void main(String[] args) throws UnsupportedEncodingException {

        String str = "77+9x6s=";
        // encode data using BASE64
        String encoded = DatatypeConverter.printBase64Binary(str.getBytes());
        System.out.println("encoded value is \t" + encoded);

        // Decode data 
        String decoded = new String(DatatypeConverter.parseBase64Binary(encoded));
        System.out.println("decoded value is \t" + decoded);

        System.out.println("original value is \t" + str);
    }
}

The better way would be to try/catch the encoding/decoding steps but hopefully you get the idea.

Why I am getting Cannot pass parameter 2 by reference error when I am using bindParam with a constant value?

If you want to insert NULL only when the value is empty or '', but insert the value when it is available.

A) Receives the form data using POST method, and calls function insert with those values.

insert( $_POST['productId'], // Will be set to NULL if empty    
        $_POST['productName'] ); // Will be to NULL if empty                                

B) Evaluates if a field was not filled up by the user, and inserts NULL if that's the case.

public function insert( $productId, $productName )
{ 
    $sql = "INSERT INTO products (  productId, productName ) 
                VALUES ( :productId, :productName )";

    //IMPORTANT: Repace $db with your PDO instance
    $query = $db->prepare($sql); 

    //Works with INT, FLOAT, ETC.
    $query->bindValue(':productId',  !empty($productId)   ? $productId   : NULL, PDO::PARAM_INT); 

    //Works with strings.
    $query->bindValue(':productName',!empty($productName) ? $productName : NULL, PDO::PARAM_STR);   

    $query->execute();      
}

For instance, if the user doesn't input anything on the productName field of the form, then $productName will be SET but EMPTY. So, you need check if it is empty(), and if it is, then insert NULL.

Tested on PHP 5.5.17

Good luck,

Can't open file 'svn/repo/db/txn-current-lock': Permission denied

I just had this problem

  1. Having multiple user using the same repo caused the problem
  2. Logout evey other user using the repo

Hope this helps

Convert list to tuple in Python

Expanding on eumiro's comment, normally tuple(l) will convert a list l into a tuple:

In [1]: l = [4,5,6]

In [2]: tuple
Out[2]: <type 'tuple'>

In [3]: tuple(l)
Out[3]: (4, 5, 6)

However, if you've redefined tuple to be a tuple rather than the type tuple:

In [4]: tuple = tuple(l)

In [5]: tuple
Out[5]: (4, 5, 6)

then you get a TypeError since the tuple itself is not callable:

In [6]: tuple(l)
TypeError: 'tuple' object is not callable

You can recover the original definition for tuple by quitting and restarting your interpreter, or (thanks to @glglgl):

In [6]: del tuple

In [7]: tuple
Out[7]: <type 'tuple'>

How to verify if nginx is running or not?

The modern (systemctl) way of doing it:

systemctl is-active nginx

You can use the exit value in your shell scripts as follows:

systemctl -q is-active nginx && echo "It is active, do something"

What's the fastest way to delete a large folder in Windows?

Using Windows Command Prompt:

rmdir /s /q folder

Using Powershell:

powershell -Command "Remove-Item -LiteralPath 'folder' -Force -Recurse"

Note that in more cases del and rmdir wil leave you with leftover files, where Powershell manages to delete the files.

Fast and simple String encrypt/decrypt in JAVA

If you are using Android then you can use android.util.Base64 class.

Encode:

passwd = Base64.encodeToString( passwd.getBytes(), Base64.DEFAULT );

Decode:

passwd = new String( Base64.decode( passwd, Base64.DEFAULT ) );

A simple and fast single line solution.

SVN 405 Method Not Allowed

The currently added directory is already committed in the repository. So delete the directory in the repository and commit the same directory again.

Can't access Eclipse marketplace

Considering this as a general programming problem, some possible causes are:

  • The service could be temporarily broken

  • You could have a problem with a firewall. These could be local or they could be implemented by your ISPs.

  • Your proxy HTTP settings (if you need one) could be incorrect. This Answer explains how to adjust the Eclipse-internal proxy settings ... if that is where the problem lies.

  • It is possible that your access may be blocked by over-active antivirus software.

  • The service could have blacklisted some net range and your hosts IP address is "collateral damage".

Try connecting to that URL with a web browser to try to see if it is just Eclipse that is affected ... or a broader problem.


Considering this in the context of the Eclipse Marketplace service, first address any local proxy / firewall / AV issues, if they apply. If that doesn't help, the best thing that you can do is to be patient.

  • It has been observed that the Eclipse Marketplace service does sometimes go down. It doesn't happen often, and when it does happen the problem does get fixed relatively quickly. (Hours, not days ...)

  • I can't find a "service status" page or feed or similar for the Eclipse services. (If you know of one, please add it as a comment below.)

  • There may be an "outage" notice on the Eclipse front page. Check for that.

  • Try to connect to the service URL (refer to the exception message!) using a web browser and/or from other locations. If you succeed, the real problem may be a networking issue at your end.

  • If you feel the need to complain about Eclipse's services, please don't do it here!! (It is off topic.)

How can I insert data into a MySQL database?

#Server Connection to MySQL:

import MySQLdb
conn = MySQLdb.connect(host= "localhost",
                  user="root",
                  passwd="newpassword",
                  db="engy1")
x = conn.cursor()

try:
   x.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
   conn.commit()
except:
   conn.rollback()

conn.close()

edit working for me:

>>> import MySQLdb
>>> #connect to db
... db = MySQLdb.connect("localhost","root","password","testdb" )
>>> 
>>> #setup cursor
... cursor = db.cursor()
>>> 
>>> #create anooog1 table
... cursor.execute("DROP TABLE IF EXISTS anooog1")
__main__:2: Warning: Unknown table 'anooog1'
0L
>>> 
>>> sql = """CREATE TABLE anooog1 (
...          COL1 INT,  
...          COL2 INT )"""
>>> cursor.execute(sql)
0L
>>> 
>>> #insert to table
... try:
...     cursor.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
...     db.commit()
... except:     
...     db.rollback()
... 
1L
>>> #show table
... cursor.execute("""SELECT * FROM anooog1;""")
1L
>>> print cursor.fetchall()
((188L, 90L),)
>>> 
>>> db.close()

table in mysql;

mysql> use testdb;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> SELECT * FROM anooog1;
+------+------+
| COL1 | COL2 |
+------+------+
|  188 |   90 |
+------+------+
1 row in set (0.00 sec)

mysql> 

Console.WriteLine does not show up in Output window

If you are developing a command line application, you can also use Console.ReadLine() at the end of your code to wait for the 'Enter' keypress before closing the console window so that you can read your output. However, both the Trace and Debug answers posted above are better options.

how to read value from string.xml in android?

String myString = getResources().getString(R.string.here_your_string_name);

Now your string is copied into myString. I hope it will work for you.

Declare a constant array

An array isn't immutable by nature; you can't make it constant.

The nearest you can get is:

var letter_goodness = [...]float32 {.0817, .0149, .0278, .0425, .1270, .0223, .0202, .0609, .0697, .0015, .0077, .0402, .0241, .0675, .0751, .0193, .0009, .0599, .0633, .0906, .0276, .0098, .0236, .0015, .0197, .0007 }

Note the [...] instead of []: it ensures you get a (fixed size) array instead of a slice. So the values aren't fixed but the size is.

Truncate (not round) decimal places in SQL Server

Try like this:

SELECT cast(round(123.456,2,1) as decimal(18,2)) 

Error Importing SSL certificate : Not an X.509 Certificate

Does your cacerts.pem file hold a single certificate? Since it is a PEM, have a look at it (with a text editor), it should start with

-----BEGIN CERTIFICATE-----

and end with

-----END CERTIFICATE-----

Finally, to check it is not corrupted, get hold of openssl and print its details using

openssl x509 -in cacerts.pem -text

How can I parse a String to BigDecimal?

Try the correct constructor http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#BigDecimal(java.lang.String)

You can directly instanciate the BigDecimal with the String ;)

Example:

BigDecimal bigDecimalValue= new BigDecimal("0.5");

JavaScript to get rows count of a HTML table

You can use the .rows property and check it's .length, like this:

var rowCount = document.getElementById('myTableID').rows.length;

How can I change the font size of ticks of axes object in matplotlib

fig = plt.figure()
ax = fig.add_subplot(111)
plt.xticks([0.4,0.14,0.2,0.2], fontsize = 50) # work on current fig
plt.show()

the x/yticks has the same properties as matplotlib.text

Why is 1/1/1970 the "epoch time"?

Epoch reference date

An epoch reference date is a point on the timeline from which we count time. Moments before that point are counted with a negative number, moments after are counted with a positive number.

Many epochs in use

Why is 1 January 1970 00:00:00 considered the epoch time?

No, not the epoch, an epoch. There are many epochs in use.

This choice of epoch is arbitrary.

Major computers systems and libraries use any of at least a couple dozen various epochs. One of the most popular epochs is commonly known as Unix Time, using the 1970 UTC moment you mentioned.

While popular, Unix Time’s 1970 may not be the most common. Also in the running for most common would be January 0, 1900 for countless Microsoft Excel & Lotus 1-2-3 spreadsheets, or January 1, 2001 used by Apple’s Cocoa framework in over a billion iOS/macOS machines worldwide in countless apps. Or perhaps January 6, 1980 used by GPS devices?

Many granularities

Different systems use different granularity in counting time.

Even the so-called “Unix Time” varies, with some systems counting whole seconds and some counting milliseconds. Many database such as Postgres use microseconds. Some, such as the modern java.time framework in Java 8 and later, use nanoseconds. Some use still other granularities.

ISO 8601

Because there is so much variance in the use of an epoch reference and in the granularities, it is generally best to avoid communicating moments as a count-from-epoch. Between the ambiguity of epoch & granularity, plus the inability of humans to perceive meaningful values (and therefore miss buggy values), use plain text instead of numbers.

The ISO 8601 standard provides an extensive set of practical well-designed formats for expressing date-time values as text. These formats are easy to parse by machine as well as easy to read by humans across cultures.

These include:

Is it possible to remove the hand cursor that appears when hovering over a link? (or keep it set as the normal pointer)

<style>
a{
cursor: default;
}
</style>

In the above code [cursor:default] is used. Default is the usual arrow cursor that appears.

And if you use [cursor: pointer] then you can access to the hand like cursor that appears when you hover over a link.

To know more about cursors and their appearance click the below link: https://www.w3schools.com/cssref/pr_class_cursor.asp

What are the safe characters for making URLs?

From an SEO perspective, hyphens are preferred over underscores. Convert to lowercase, remove all apostrophes, then replace all non-alphanumeric strings of characters with a single hyphen. Trim excess hyphens off the start and finish.

Insert text with single quotes in PostgreSQL

select concat('''','abc','''')

Convert NSData to String?

A simple way to convert arbitrary NSData to NSString is to base64 encode it.

NSString *base64EncodedKey = [keydata base64EncodedStringWithOptions: NSDataBase64Encoding64CharacterLineLength];

You can then store it into your database for reuse later. Just decode it back to NSData.

Import MySQL database into a MS SQL Server

Here is my approach for importing .sql files to MS SQL:

  1. Export table from MySQL with --compatible=mssql and --extended-insert=FALSE options:

    mysqldump -u [username] -p --compatible=mssql --extended-insert=FALSE db_name table_name > table_backup.sql

  2. Split the exported file with PowerShell by 300000 lines per file:

    $i=0; Get-Content exported.sql -ReadCount 300000 | %{$i++; $_ | Out-File out_$i.sql}

  3. Run each file in MS SQL Server Management Studio

There are few tips how to speed up the inserts.

Other approach is to use mysqldump –where option. By using this option you can split your table on any condition which is supported by where sql clause.

Getting all selected checkboxes in an array

Using Jquery

You only need to add class to every input, i have add class "source" you can change it of course

<input class="source" type="checkbox" name="type" value="4" />
<input class="source" type="checkbox" name="type" value="3" />
<input class="source" type="checkbox" name="type" value="1" />
<input class="source" type="checkbox" name="type" value="5" />

<script type="text/javascript">
$(document).ready(function() {
    var selected_value = []; // initialize empty array 
    $(".source:checked").each(function(){
        selected_value.push($(this).val());
    });
    console.log(selected_value); //Press F12 to see all selected values
});
</script>

How to map atan2() to degrees 0-360

theta_rad = Math.Atan2(y,x);
if(theta_rad < 0)
  theta_rad = theta_rad + 2 * Math.PI;    //if neg., add 2 PI to it
theta_deg = (theta_rad/M_PI*180) ;        //convert from radian to degree

//or
theta_rad = Math.Atan2(y,x);
theta_rad = (theta_rad < 0) ? theta_rad + 2 * Math.PI : theta_rad;
theta_deg = (theta_rad/M_PI*180) ;

-1 deg becomes (-1 + 360) = 359 deg
-179 deg becomes (-179 + 360) = 181 deg

What is the use of ByteBuffer in Java?

This is a good description of its uses and shortcomings. You essentially use it whenever you need to do fast low-level I/O. If you were going to implement a TCP/IP protocol or if you were writing a database (DBMS) this class would come in handy.

jQuery: Get the cursor position of text in input without browser specific code?

Using the syntax text_element.selectionStart we can get the starting position of the selection of a text in terms of the index of the first character of the selected text in the text_element.value and in case we want to get the same of the last character in the selection we have to use text_element.selectionEnd.

Use it as follows:

<input type=text id=t1 value=abcd>
<button onclick="alert(document.getElementById('t1').selectionStart)">check position</button>

I'm giving you the fiddle_demo

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

Here is how one can do it. I will give an example with joining so that it becomes super clear to someone.

$products = DB::table('products AS pr')
        ->leftJoin('product_families AS pf', 'pf.id', '=', 'pr.product_family_id')
        ->select('pr.id as id', 'pf.name as product_family_name', 'pf.id as product_family_id')
        ->orderBy('pr.id', 'desc')
        ->get();

Hope this helps.

How to install psycopg2 with "pip" on Python?

For lowly Windows users were stuck having to install psycopg2 from the link below, just install it to whatever Python installation you have setup. It will place the folder named "psycopg2" in the site-packages folder of your python installation.

After that, just copy that folder to the site-packages directory of your virtualenv and you will have no problems.

here is the link you can find the executable to install psycopg2

http://www.lfd.uci.edu/~gohlke/pythonlibs/

How do I add a reference to the MySQL connector for .NET?

When you download the connector/NET choose Select Platform = .NET & Mono (not windows!)

Regex for numbers only

It is matching because it is finding "a match" not a match of the full string. You can fix this by changing your regexp to specifically look for the beginning and end of the string.

^\d+$

Plotting 4 curves in a single plot, with 3 y-axes

PLOTYY allows two different y-axes. Or you might look into LayerPlot from the File Exchange. I guess I should ask if you've considered using HOLD or just rescaling the data and using regular old plot?

OLD, not what the OP was looking for: SUBPLOT allows you to break a figure window into multiple axes. Then if you want to have only one x-axis showing, or some other customization, you can manipulate each axis independently.

Ripple effect on Android Lollipop CardView

I managed to get the ripple effect on the cardview by :

<android.support.v7.widget.CardView 
    xmlns:card_view="http://schemas.android.com/apk/res-auto" 
    android:clickable="true" 
    android:foreground="@drawable/custom_bg"/>

and for the custom_bg that you can see in above code, you have to define a xml file for both lollipop(in drawable-v21 package) and pre-lollipop(in drawable package) devices. for custom_bg in drawable-v21 package the code is:

<ripple 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?android:attr/colorControlHighlight">
<item
    android:id="@android:id/mask"
    android:drawable="@android:color/white"/>
</ripple>

for custom_bg in the drawable package, code is:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true">
    <shape>
        <solid android:color="@color/colorHighlight"></solid>
    </shape>
</item>
<item>
    <shape>
        <solid android:color="@color/navigation_drawer_background"></solid>
    </shape>
</item>
</selector>

so on pre-lollipop devices you will have a solid click effect and on lollipop devices you will have a ripple effect on the cardview.

How can I return the current action in an ASP.NET MVC view?

I saw different answers and came up with a class helper:

using System;
using System.Web.Mvc;

namespace MyMvcApp.Helpers {
    public class LocationHelper {
        public static bool IsCurrentControllerAndAction(string controllerName, string actionName, ViewContext viewContext) {
            bool result = false;
            string normalizedControllerName = controllerName.EndsWith("Controller") ? controllerName : String.Format("{0}Controller", controllerName);

            if(viewContext == null) return false;
            if(String.IsNullOrEmpty(actionName)) return false;

            if (viewContext.Controller.GetType().Name.Equals(normalizedControllerName, StringComparison.InvariantCultureIgnoreCase) &&
                viewContext.Controller.ValueProvider.GetValue("action").AttemptedValue.Equals(actionName, StringComparison.InvariantCultureIgnoreCase)) {
                result = true;
            }

            return result;
        }
    }
}

So in View (or master/layout) you can use it like so (Razor syntax):

            <div id="menucontainer">

                <ul id="menu">
                    <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("home", "index", ViewContext)) {
                            @:class="selected"
                        }>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("account","logon", ViewContext)) {
                            @:class="selected"
                        }>@Html.ActionLink("Logon", "Logon", "Account")</li>
                    <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("home","about", ViewContext)) {
                            @:class="selected"
                        }>@Html.ActionLink("About", "About", "Home")</li>
                </ul>

            </div>

Hope it helps.

Simple export and import of a SQLite database on Android

To export db rather it is SQLITE or ROOM:

Firstly, add this permission in AndroidManifest.xml file:

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

Secondly, we drive to code the db functions:

private void exportDB() {
    try {
        File dbFile = new File(this.getDatabasePath(DATABASE_NAME).getAbsolutePath());
        FileInputStream fis = new FileInputStream(dbFile);

        String outFileName = DirectoryName + File.separator +
                DATABASE_NAME + ".db";

        // Open the empty db as the output stream
        OutputStream output = new FileOutputStream(outFileName);

        // Transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = fis.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
        // Close the streams
        output.flush();
        output.close();
        fis.close();


    } catch (IOException e) {
        Log.e("dbBackup:", e.getMessage());
    }
}

Create Folder on Daily basis with name of folder is Current date:

public void createBackup() {

    sharedPref = getSharedPreferences("dbBackUp", MODE_PRIVATE);
    editor = sharedPref.edit();

    String dt = sharedPref.getString("dt", new SimpleDateFormat("dd-MM-yy").format(new Date()));

    if (dt != new SimpleDateFormat("dd-MM-yy").format(new Date())) {
        editor.putString("dt", new SimpleDateFormat("dd-MM-yy").format(new Date()));

        editor.commit();
    }

    File folder = new File(Environment.getExternalStorageDirectory() + File.separator + "BackupDBs");
    boolean success = true;
    if (!folder.exists()) {
        success = folder.mkdirs();
    }
    if (success) {

        DirectoryName = folder.getPath() + File.separator + sharedPref.getString("dt", "");
        folder = new File(DirectoryName);
        if (!folder.exists()) {
            success = folder.mkdirs();
        }
        if (success) {
            exportDB();
        }
    } else {
        Toast.makeText(this, "Not create folder", Toast.LENGTH_SHORT).show();
    }

}

Assign the DATABASE_NAME without .db extension and its data type is string

Android Support Design TabLayout: Gravity Center and Mode Scrollable

My final solution

class DynamicModeTabLayout : TabLayout {

    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    override fun setupWithViewPager(viewPager: ViewPager?) {
        super.setupWithViewPager(viewPager)

        val view = getChildAt(0) ?: return
        view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED)
        val size = view.measuredWidth

        if (size > measuredWidth) {
            tabMode = MODE_SCROLLABLE
            tabGravity = GRAVITY_CENTER
        } else {
            tabMode = MODE_FIXED
            tabGravity = GRAVITY_FILL
        }
    }
}

PowerShell: Format-Table without headers

Try the -HideTableHeaders parameter to Format-Table:

gci | ft -HideTableHeaders

(I'm using PowerShell v2. I don't know if this was in v1.)

Auto reloading python Flask app upon code changes

from the terminal u can simply say

expoort FLASK_APP=app_name.py
export FLASK_ENV=development
flask run

or in ur file

if __name__ == "__main__":
    app.run(debug=True)

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

Here is a fairly concise way to do this:

static readonly string[] SizeSuffixes = 
                   { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
static string SizeSuffix(Int64 value, int decimalPlaces = 1)
{
    if (decimalPlaces < 0) { throw new ArgumentOutOfRangeException("decimalPlaces"); }
    if (value < 0) { return "-" + SizeSuffix(-value, decimalPlaces); } 
    if (value == 0) { return string.Format("{0:n" + decimalPlaces + "} bytes", 0); }

    // mag is 0 for bytes, 1 for KB, 2, for MB, etc.
    int mag = (int)Math.Log(value, 1024);

    // 1L << (mag * 10) == 2 ^ (10 * mag) 
    // [i.e. the number of bytes in the unit corresponding to mag]
    decimal adjustedSize = (decimal)value / (1L << (mag * 10));

    // make adjustment when the value is large enough that
    // it would round up to 1000 or more
    if (Math.Round(adjustedSize, decimalPlaces) >= 1000)
    {
        mag += 1;
        adjustedSize /= 1024;
    }

    return string.Format("{0:n" + decimalPlaces + "} {1}", 
        adjustedSize, 
        SizeSuffixes[mag]);
}

And here's the original implementation I suggested, which may be marginally slower, but a bit easier to follow:

static readonly string[] SizeSuffixes = 
                  { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };

static string SizeSuffix(Int64 value, int decimalPlaces = 1)
{
    if (value < 0) { return "-" + SizeSuffix(-value, decimalPlaces); } 

    int i = 0;
    decimal dValue = (decimal)value;
    while (Math.Round(dValue, decimalPlaces) >= 1000)
    {
        dValue /= 1024;
        i++;
    }

    return string.Format("{0:n" + decimalPlaces + "} {1}", dValue, SizeSuffixes[i]);
}

Console.WriteLine(SizeSuffix(100005000L));

One thing to bear in mind - in SI notation, "kilo" usually uses a lowercase k while all of the larger units use a capital letter. Windows uses KB, MB, GB, so I have used KB above, but you may consider kB instead.

Microsoft Visual C++ Compiler for Python 3.4

For the different python versions:

Visual C++ |CPython
--------------------
14.0       |3.5
10.0       |3.3, 3.4
9.0        |2.6, 2.7, 3.0, 3.1, 3.2

Source: Windows Compilers for py

Also refer: this answer

New Line Issue when copying data from SQL Server 2012 to Excel

In order to be able to copy and paste results from SQL Server Management Studio 2012 to Excel or to export to Csv with list separators you must first change the query option.

  1. Click on Query then options.

  2. Under Results click on the Grid.

  3. Check the box next to:

    Quote strings containing list separators when saving .csv results.

This should solve the problem.

If you can decode JWT, how are they secure?

JWTs can be either signed, encrypted or both. If a token is signed, but not encrypted, everyone can read its contents, but when you don't know the private key, you can't change it. Otherwise, the receiver will notice that the signature won't match anymore.

Answer to your comment: I'm not sure if I understand your comment the right way. Just to be sure: do you know and understand digital signatures? I'll just briefly explain one variant (HMAC, which is symmetrical, but there are many others).

Let's assume Alice wants to send a JWT to Bob. They both know some shared secret. Mallory doesn't know that secret, but wants to interfere and change the JWT. To prevent that, Alice calculates Hash(payload + secret) and appends this as signature.

When receiving the message, Bob can also calculate Hash(payload + secret) to check whether the signature matches. If however, Mallory changes something in the content, she isn't able to calculate the matching signature (which would be Hash(newContent + secret)). She doesn't know the secret and has no way of finding it out. This means if she changes something, the signature won't match anymore, and Bob will simply not accept the JWT anymore.

Let's suppose, I send another person the message {"id":1} and sign it with Hash(content + secret). (+ is just concatenation here). I use the SHA256 Hash function, and the signature I get is: 330e7b0775561c6e95797d4dd306a150046e239986f0a1373230fda0235bda8c. Now it's your turn: play the role of Mallory and try to sign the message {"id":2}. You can't because you don't know which secret I used. If I suppose that the recipient knows the secret, he CAN calculate the signature of any message and check if it's correct.

Batch file to copy files from one folder to another folder

To bypass the 'specify a file name or directory name on the target (F = file, D = directory)?' prompt with xcopy, you can do the following...

echo f | xcopy /f /y srcfile destfile

or for those of us just copying large substructures/folders:

use /i which specifies destination must be a directory if copying more than one file

How to change default timezone for Active Record in Rails?

I came to the same conclusion as Dean Perry after much anguish. config.time_zone = 'Adelaide' and config.active_record.default_timezone = :local was the winning combination. Here's what I found during the process.

How can I transform string to UTF-8 in C#?

Use the below code snippet to get bytes from csv file

protected byte[] GetCSVFileContent(string fileName)
    {
        StringBuilder sb = new StringBuilder();
        using (StreamReader sr = new StreamReader(fileName, Encoding.Default, true))
        {
            String line;
            // Read and display lines from the file until the end of 
            // the file is reached.
            while ((line = sr.ReadLine()) != null)
            {
                sb.AppendLine(line);
            }
        }
        string allines = sb.ToString();


        UTF8Encoding utf8 = new UTF8Encoding();


        var preamble = utf8.GetPreamble();

        var data = utf8.GetBytes(allines);


        return data;
    }

Call the below and save it as an attachment

           Encoding csvEncoding = Encoding.UTF8;
                   //byte[] csvFile = GetCSVFileContent(FileUpload1.PostedFile.FileName);
          byte[] csvFile = GetCSVFileContent("Your_CSV_File_NAme");


        string attachment = String.Format("attachment; filename={0}.csv", "uomEncoded");

        Response.Clear();
        Response.ClearHeaders();
        Response.ClearContent();
        Response.ContentType = "text/csv";
        Response.ContentEncoding = csvEncoding;
        Response.AppendHeader("Content-Disposition", attachment);
        //Response.BinaryWrite(csvEncoding.GetPreamble());
        Response.BinaryWrite(csvFile);
        Response.Flush();
        Response.End();

Android fade in and fade out with ImageView

This is probably the best solution you'll get. Simple and Easy. I learned it on udemy. Suppose you have two images having image id's id1 and id2 respectively and currently the image view is set as id1 and you want to change it to the other image everytime someone clicks in. So this is the basic code in MainActivity.java File

int clickNum=0;
public void click(View view){
clickNum++;
ImageView a=(ImageView)findViewById(R.id.id1);
ImageView b=(ImageView)findViewById(R.id.id2);
if(clickNum%2==1){
  a.animate().alpha(0f).setDuration(2000); //alpha controls the transpiracy
}
else if(clickNum%2==0){
  b.animate().alpha(0f).setDuration(2000); //alpha controls the transpiracy
}

}

I hope this will surely help

Throw keyword in function's signature

To add a bit more value to all the other answer's to this question, one should invest a few minutes in the question: What is the output of the following code?

#include <iostream>
void throw_exception() throw(const char *)
{
    throw 10;
}
void my_unexpected(){
    std::cout << "well - this was unexpected" << std::endl;
}
int main(int argc, char **argv){
    std::set_unexpected(my_unexpected);
    try{
        throw_exception();
    }catch(int x){
        std::cout << "catch int: " << x << std::endl;
    }catch(...){
        std::cout << "catch ..." << std::endl;
    }
}

Answer: As noted here, the program calls std::terminate() and thus none of the exception handlers will get called.

Details: First my_unexpected() function is called, but since it doesn't re-throw a matching exception type for the throw_exception() function prototype, in the end, std::terminate() is called. So the full output looks like this:

user@user:~/tmp$ g++ -o except.test except.test.cpp
user@user:~/tmp$ ./except.test
well - this was unexpected
terminate called after throwing an instance of 'int'
Aborted (core dumped)

Border Radius of Table is not working

A note to this old question:

My reset.css had set border-spacing: 0, causing the corners to get cut off. I had to set it to 3px for my radius to work properly (value will depend on the radius in question).

What are the pros and cons of parquet format compared to other formats?

Choosing the right file format is important to building performant data applications. The concepts outlined in this post carry over to Pandas, Dask, Spark, and Presto / AWS Athena.

Column pruning

Column pruning is a big performance improvement that's possible for column-based file formats (Parquet, ORC) and not possible for row-based file formats (CSV, Avro).

Suppose you have a dataset with 100 columns and want to read two of them into a DataFrame. Here's how you can perform this with Pandas if the data is stored in a Parquet file.

import pandas as pd

pd.read_parquet('some_file.parquet', columns = ['id', 'firstname'])

Parquet is a columnar file format, so Pandas can grab the columns relevant for the query and can skip the other columns. This is a massive performance improvement.

If the data is stored in a CSV file, you can read it like this:

import pandas as pd

pd.read_csv('some_file.csv', usecols = ['id', 'firstname'])

usecols can't skip over entire columns because of the row nature of the CSV file format.

Spark doesn't require users to explicitly list the columns that'll be used in a query. Spark builds up an execution plan and will automatically leverage column pruning whenever possible. Of course, column pruning is only possible when the underlying file format is column oriented.

Popularity

Spark and Pandas have built-in readers writers for CSV, JSON, ORC, Parquet, and text files. They don't have built-in readers for Avro.

Avro is popular within the Hadoop ecosystem. Parquet has gained significant traction outside of the Hadoop ecosystem. For example, the Delta Lake project is being built on Parquet files.

Arrow is an important project that makes it easy to work with Parquet files with a variety of different languages (C, C++, Go, Java, JavaScript, MATLAB, Python, R, Ruby, Rust), but doesn't support Avro. Parquet files are easier to work with because they are supported by so many different projects.

Schema

Parquet stores the file schema in the file metadata. CSV files don't store file metadata, so readers need to either be supplied with the schema or the schema needs to be inferred. Supplying a schema is tedious and inferring a schema is error prone / expensive.

Avro also stores the data schema in the file itself. Having schema in the files is a huge advantage and is one of the reasons why a modern data project should not rely on JSON or CSV.

Column metadata

Parquet stores metadata statistics for each column and lets users add their own column metadata as well.

The min / max column value metadata allows for Parquet predicate pushdown filtering that's supported by the Dask & Spark cluster computing frameworks.

Here's how to fetch the column statistics with PyArrow.

import pyarrow.parquet as pq

parquet_file = pq.ParquetFile('some_file.parquet')
print(parquet_file.metadata.row_group(0).column(1).statistics)
<pyarrow._parquet.Statistics object at 0x11ac17eb0>
  has_min_max: True
  min: 1
  max: 9
  null_count: 0
  distinct_count: 0
  num_values: 3
  physical_type: INT64
  logical_type: None
  converted_type (legacy): NONE

Complex column types

Parquet allows for complex column types like arrays, dictionaries, and nested schemas. There isn't a reliable method to store complex types in simple file formats like CSVs.

Compression

Columnar file formats store related types in rows, so they're easier to compress. This CSV file is relatively hard to compress.

first_name,age
ken,30
felicia,36
mia,2

This data is easier to compress when the related types are stored in the same row:

ken,felicia,mia
30,36,2

Parquet files are most commonly compressed with the Snappy compression algorithm. Snappy compressed files are splittable and quick to inflate. Big data systems want to reduce file size on disk, but also want to make it quick to inflate the flies and run analytical queries.

Mutable nature of file

Parquet files are immutable, as described here. CSV files are mutable.

Adding a row to a CSV file is easy. You can't easily add a row to a Parquet file.

Data lakes

In a big data environment, you'll be working with hundreds or thousands of Parquet files. Disk partitioning of the files, avoiding big files, and compacting small files is important. The optimal disk layout of data depends on your query patterns.

How to send a POST request with BODY in swift

If you are using swift4 and Alamofire v4.0 then the accepted code would look like this :

            let parameters: Parameters = [ "username" : email.text!, "password" : password.text! ]
            let urlString = "https://api.harridev.com/api/v1/login"
            let url = URL.init(string: urlString)
            Alamofire.request(url!, method: .put, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { response in
                 switch response.result
                {
                case .success(let json):
                    let jsonData = json as! Any
                    print(jsonData)
                case .failure(let error):
                    self.errorFailer(error: error)
                }
            }

Correct way to select from two tables in SQL Server with no common field to join on

You can (should) use CROSS JOIN. Following query will be equivalent to yours:

SELECT 
   table1.columnA
 , table2.columnA
FROM table1 
CROSS JOIN table2
WHERE table1.columnA = 'Some value'

or you can even use INNER JOIN with some always true conditon:

FROM table1 
INNER JOIN table2 ON 1=1

How to set the thumbnail image on HTML5 video?

<?php
$thumbs_dir = 'E:/xampp/htdocs/uploads/thumbs/';
$videos = array();
if (isset($_POST["name"])) {
 if (!preg_match('/data:([^;]*);base64,(.*)/', $_POST['data'], $matches)) {
  die("error");
 }
 $data = $matches[2];
 $data = str_replace(' ', '+', $data);
 $data = base64_decode($data);
 $file = 'text.jpg';
 $dataname = file_put_contents($thumbs_dir . $file, $data);
}
?>
//jscode
<script type="text/javascript">
 var videos = <?= json_encode($videos); ?>;
 var video = document.getElementById('video');
 video.addEventListener('canplay', function () {
     this.currentTime = this.duration / 2;
 }, false);
 var seek = true;
 video.addEventListener('seeked', function () {
    if (seek) {
         getThumb();
    }
 }, false);

 function getThumb() {
     seek = false;
     var filename = video.src;
     var w = video.videoWidth;//video.videoWidth * scaleFactor;
     var h = video.videoHeight;//video.videoHeight * scaleFactor;
     var canvas = document.createElement('canvas');
     canvas.width = w;
     canvas.height = h;
     var ctx = canvas.getContext('2d');
     ctx.drawImage(video, 0, 0, w, h);
     var data = canvas.toDataURL("image/jpg");
     var xmlhttp = new XMLHttpRequest;
     xmlhttp.onreadystatechange = function () {
         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
         }
     }
     xmlhttp.open("POST", location.href, true);
     xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
     xmlhttp.send('name=' + encodeURIComponent(filename) + '&data=' + data);
 }
  function failed(e) {
     // video playback failed - show a message saying why
     switch (e.target.error.code) {
         case e.target.error.MEDIA_ERR_ABORTED:
             console.log('You aborted the video playback.');
             break;
         case e.target.error.MEDIA_ERR_NETWORK:
             console.log('A network error caused the video download to fail part-way.');
             break;
         case e.target.error.MEDIA_ERR_DECODE:
             console.log('The video playback was aborted due to a corruption problem or because the video used features your browser did not support.');
              break;
          case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
              console.log('The video could not be loaded, either because the server or network failed or because the format is not supported.');
              break;
          default:
              console.log('An unknown error occurred.');
              break;
      }


  }
</script>
//Html
<div>
    <video   id="video" src="1499752288.mp4" autoplay="true"  onerror="failed(event)" controls="controls" preload="none"></video>
</div>

Pandas: change data type of Series to String

Personally none of the above worked for me. What did:

new_str = [str(x) for x in old_obj][0]

How to throw std::exceptions with variable messages?

The following class might come quite handy:

struct Error : std::exception
{
    char text[1000];

    Error(char const* fmt, ...) __attribute__((format(printf,2,3))) {
        va_list ap;
        va_start(ap, fmt);
        vsnprintf(text, sizeof text, fmt, ap);
        va_end(ap);
    }

    char const* what() const throw() { return text; }
};

Usage example:

throw Error("Could not load config file '%s'", configfile.c_str());

how to create inline style with :before and :after

You can, using CSS variables (more precisely called CSS custom properties).

  • Set your variable in your style attribute:
    style="--my-color-var: orange;"
  • Use the variable in your stylesheet:
    background-color: var(--my-color-var);

Browser compatibility

Minimal example:

_x000D_
_x000D_
div {
  width: 100px;
  height: 100px;
  position: relative;
  border: 1px solid black;
}

div:after {
  background-color: var(--my-color-var);
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
}
_x000D_
<div style="--my-color-var: orange;"></div>
_x000D_
_x000D_
_x000D_

Your example:

_x000D_
_x000D_
.bubble {
  position: relative;
  width: 30px;
  height: 15px;
  padding: 0;
  background: #FFF;
  border: 1px solid #000;
  border-radius: 5px;
  text-align: center;
  background-color: var(--bubble-color);
}

.bubble:after {
  content: "";
  position: absolute;
  top: 4px;
  left: -4px;
  border-style: solid;
  border-width: 3px 4px 3px 0;
  border-color: transparent var(--bubble-color);
   display: block;
  width: 0;
  z-index: 1;
  
}

.bubble:before {
  content: "";
  position: absolute;
  top: 4px;
  left: -5px;
  border-style: solid;
  border-width: 3px 4px 3px 0;
  border-color: transparent #000;
  display: block;
  width: 0;
  z-index: 0;
}
_x000D_
<div class='bubble' style="--bubble-color: rgb(100,255,255);"> 100 </div>
_x000D_
_x000D_
_x000D_

Java equivalent to C# extension methods

One could be use the decorator object-oriented design pattern. An example of this pattern being used in Java's standard library would be the DataOutputStream.

Here's some code for augmenting the functionality of a List:

public class ListDecorator<E> implements List<E>
{
    public final List<E> wrapee;

    public ListDecorator(List<E> wrapee)
    {
        this.wrapee = wrapee;
    }

    // implementation of all the list's methods here...

    public <R> ListDecorator<R> map(Transform<E,R> transformer)
    {
        ArrayList<R> result = new ArrayList<R>(size());
        for (E element : this)
        {
            R transformed = transformer.transform(element);
            result.add(transformed);
        }
        return new ListDecorator<R>(result);
    }
}

P.S. I'm a big fan of Kotlin. It has extension methods and also runs on the JVM.

Resolving tree conflict

Basically, tree conflicts arise if there is some restructure in the folder structure on the branch. You need to delete the conflict folder and use svn clean once. Hope this solves your conflict.

Get the first item from an iterable that matches a condition

As a reusable, documented and tested function

def first(iterable, condition = lambda x: True):
    """
    Returns the first item in the `iterable` that
    satisfies the `condition`.

    If the condition is not given, returns the first item of
    the iterable.

    Raises `StopIteration` if no item satysfing the condition is found.

    >>> first( (1,2,3), condition=lambda x: x % 2 == 0)
    2
    >>> first(range(3, 100))
    3
    >>> first( () )
    Traceback (most recent call last):
    ...
    StopIteration
    """

    return next(x for x in iterable if condition(x))

Version with default argument

@zorf suggested a version of this function where you can have a predefined return value if the iterable is empty or has no items matching the condition:

def first(iterable, default = None, condition = lambda x: True):
    """
    Returns the first item in the `iterable` that
    satisfies the `condition`.

    If the condition is not given, returns the first item of
    the iterable.

    If the `default` argument is given and the iterable is empty,
    or if it has no items matching the condition, the `default` argument
    is returned if it matches the condition.

    The `default` argument being None is the same as it not being given.

    Raises `StopIteration` if no item satisfying the condition is found
    and default is not given or doesn't satisfy the condition.

    >>> first( (1,2,3), condition=lambda x: x % 2 == 0)
    2
    >>> first(range(3, 100))
    3
    >>> first( () )
    Traceback (most recent call last):
    ...
    StopIteration
    >>> first([], default=1)
    1
    >>> first([], default=1, condition=lambda x: x % 2 == 0)
    Traceback (most recent call last):
    ...
    StopIteration
    >>> first([1,3,5], default=1, condition=lambda x: x % 2 == 0)
    Traceback (most recent call last):
    ...
    StopIteration
    """

    try:
        return next(x for x in iterable if condition(x))
    except StopIteration:
        if default is not None and condition(default):
            return default
        else:
            raise

What is the Git equivalent for revision number?

From the Git manual, tags are a brilliant answer to this issue:

Creating an annotated tag in Git is simple. The easiest way is to specify -a when you run the tag command:

$ git tag -a v1.4 -m 'my version 1.4'

$ git tag
v0.1
v1.3
v1.4

Check out 2.6 Git Basics - Tagging

How to determine if a type implements an interface with C# reflection

Use Type.IsAssignableFrom:

typeof(IMyInterface).IsAssignableFrom(typeof(MyType));

Can I add a custom attribute to an HTML tag?

I can think of a handy use for the custom tag "init". Include a JavaScript expression that gets evaluated at document.onLoad() time and provides a value for the tag, e.g.

<p>&lt;p&gt;The UTC date is &lt;span init="new Date().toUTCString()"&gt;?&lt;/span&gt;.&lt;p&gt;</p>

Some boilerplate JavaScript code would scan all the tags in the DOM at document.onload() time looking for the init attributes, evaluating the expressions that they contain, and assigning them to the containing tag's innerHTML. This would give HTML some of the power of JSP, PHP etc. Currently we have to split the HTML markup and the JavaScript code that illuminates it. Bugs love split code.

How to convert List to Json in Java

Try this:

public void test(){
// net.sf.json.JSONObject, net.sf.json.JSONArray    

List objList = new ArrayList();
objList.add("obj1");
objList.add("obj2");
objList.add("obj3");
HashMap objMap = new HashMap();
objMap.put("key1", "value1");
objMap.put("key2", "value2");
objMap.put("key3", "value3");
System.out.println("JSONArray :: "+(JSONArray)JSONSerializer.toJSON(objList));
System.out.println("JSONObject :: "+(JSONObject)JSONSerializer.toJSON(objMap));
}

you can find API here.

HTTP get with headers using RestTemplate

Take a look at the JavaDoc for RestTemplate.

There is the corresponding getForObject methods that are the HTTP GET equivalents of postForObject, but they doesn't appear to fulfil your requirements of "GET with headers", as there is no way to specify headers on any of the calls.

Looking at the JavaDoc, no method that is HTTP GET specific allows you to also provide header information. There are alternatives though, one of which you have found and are using. The exchange methods allow you to provide an HttpEntity object representing the details of the request (including headers). The execute methods allow you to specify a RequestCallback from which you can add the headers upon its invocation.

Button text toggle in jquery

With so many great answers, I thought I would toss one more into the mix. This one, unlike the others, would permit you to cycle through any number of messages with ease:

var index = 0,
    messg = [
        "PUSH ME", 
        "DON'T PUSH ME", 
        "I'M SO CONFUSED!"
    ];

$(".pushme").on("click", function() {
    $(this).text(function(index, text){
        index = $.inArray(text, messg);
        return messg[++index % messg.length];
    });
}??????????????????????????????????????????????);?

Demo: http://jsfiddle.net/DQK4v/2/

How to add Button over image using CSS?

If I understood correctly, I would change the HTML to something like this:

<div id="shop">
    <div class="content">
        <img src="http://placehold.it/182x121"/> 
        <a href="#">Counter-Strike 1.6 Steam</a>
    </div>
</div>

Then I would be able to use position:absolute and position:relative to force the blue button down.

I have created a jsfiddle: http://jsfiddle.net/y9w99/

How to stop text from taking up more than 1 line?

Sometimes using &nbsp; instead of spaces will work. Clearly it has drawbacks, though.

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

1 : if you are interested only in the static block of the class , the loading the class only would do , and would execute static blocks then all you need is:

Class.forName("Somthing");

2 : if you are interested in loading the class , execute its static blocks and also want to access its its non static part , then you need an instance and then you need:

Class.forName("Somthing").newInstance();

Plot smooth line with PyPlot

Here is a simple solution for dates:

from scipy.interpolate import make_interp_spline
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as dates
from datetime import datetime

data = {
    datetime(2016, 9, 26, 0, 0): 26060, datetime(2016, 9, 27, 0, 0): 23243,
    datetime(2016, 9, 28, 0, 0): 22534, datetime(2016, 9, 29, 0, 0): 22841,
    datetime(2016, 9, 30, 0, 0): 22441, datetime(2016, 10, 1, 0, 0): 23248 
}
#create data
date_np = np.array(list(data.keys()))
value_np = np.array(list(data.values()))
date_num = dates.date2num(date_np)
# smooth
date_num_smooth = np.linspace(date_num.min(), date_num.max(), 100) 
spl = make_interp_spline(date_num, value_np, k=3)
value_np_smooth = spl(date_num_smooth)
# print
plt.plot(date_np, value_np)
plt.plot(dates.num2date(date_num_smooth), value_np_smooth)
plt.show()

example

How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?

    [HttpPost]
    public bool parseAllDocs([FromBody] IList<docObject> data)
    {
        // do stuff

    }

Logical operator in a handlebars.js {{#if}} conditional

Following these 2 guides a-way-to-let-users-define-custom-made-bound-if-statements and custom bound helpers I was able to adjust my shared views in this post on stackoverflow to use this instead of the standard #if statement. This should be more secure than just tossing an #if in there.

The custom bound helpers in that gist are outstanding.

<li>
    <a href="{{unbound view.varProductSocialBlog}}">
        {{#if-equal view.showDiv "true"}}<div>{{/if-equal}}<i class="fa fa-rss-square"></i>{{#if-equal view.showDiv "true"}}</div>{{/if-equal}}
        {{#if-equal view.showTitle "true"}}Blog{{/if-equal}}
    </a>
</li>

I am using the ember cli project to build my ember application.

Current setup at the time of this post:

DEBUG: -------------------------------
DEBUG: Ember      : 1.5.1
DEBUG: Ember Data : 1.0.0-beta.7+canary.b45e23ba
DEBUG: Handlebars : 1.3.0
DEBUG: jQuery     : 2.1.1
DEBUG: -------------------------------

How to serve up images in Angular2?

Just put your images in the assets folder refer them in your html pages or ts files with that link.

How to get the Power of some Integer in Swift language?

Combining the answers into an overloaded set of functions (and using "**" instead of "^^" as some other languages use - clearer to me):

// http://stackoverflow.com/questions/24196689/how-to-get-the-power-of-some-integer-in-swift-language
// Put this at file level anywhere in your project
infix operator ** { associativity left precedence 160 }
func ** (radix: Double, power: Double) -> Double { return pow(radix, power) }
func ** (radix: Int,    power: Int   ) -> Double { return pow(Double(radix), Double(power)) }
func ** (radix: Float,  power: Float ) -> Double { return pow(Double(radix), Double(power)) }

When using Float, you may lose precision. If using numeric literals and a mix of integers and non-integers, you will end up with Double by default. I personally like the ability to use a mathematical expression instead of a function like pow(a, b) for stylistic/readability reasons, but that's just me.

Any operators that would cause pow() to throw an error will also cause these functions to throw an error, so the burden of error checking still lies with the code using the power function anyway. KISS, IMHO.

Using the native pow() function allows to eg take square roots (2 ** 0.5) or inverse (2 ** -3 = 1/8). Because of the possibility to use inverse or fractional exponents, I wrote all my code to return the default Double type of the pow() function, which should return the most precision (if I remember the documentation correctly). If needed, this can be type-casted down to Int or Float or whatever, possibly with the loss of precision.

2 ** -3  = 0.125
2 ** 0.5 = 1.4142135623731
2 ** 3   = 8

How do I find which transaction is causing a "Waiting for table metadata lock" state?

If you cannot find the process locking the table (cause it is alreay dead), it may be a thread still cleaning up like this

section TRANSACTION of

show engine innodb status;

at the end

---TRANSACTION 1135701157, ACTIVE 6768 sec
MySQL thread id 5208136, OS thread handle 0x7f2982e91700, query id 882213399 xxxIPxxx 82.235.36.49 my_user cleaning up

as mentionned in a comment in Clear transaction deadlock?

you can try killing the transaction thread directly, here with

 KILL 5208136;

worked for me.

Could not find method android() for arguments

This error appear because the compiler could not found "my-upload-key.keystore" file in your project

After you have generated the file you need to paste it into project's andorid/app folder

this worked for me!

How to place the ~/.composer/vendor/bin directory in your PATH?

The Composer bin directory is set and stored in bin-dir config variable and can be different depending on your setup. Running the command composer global config bin-dir --absolute will tell you the absolute path to your global composer bin directory. Using this command you can modify your .bash_profile to add it to your PATH exactly how it is configured.

# Add Composer bin-dir to PATH if it is installed.
command -v composer >/dev/null 2>&1 && {
        COMPOSER_BIN_DIR=$(composer global config bin-dir --absolute 2> /dev/null)
        PATH="$PATH:$COMPOSER_BIN_DIR";
}
export PATH

How to get item's position in a list?

If your list got large enough and you only expected to find the value in a sparse number of indices, consider that this code could execute much faster because you don't have to iterate every value in the list.

lookingFor = 1
i = 0
index = 0
try:
  while i < len(testlist):
    index = testlist.index(lookingFor,i)
    i = index + 1
    print index
except ValueError: #testlist.index() cannot find lookingFor
  pass

If you expect to find the value a lot you should probably just append "index" to a list and print the list at the end to save time per iteration.

Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

What I did was to create an extension to UITextField and added a Designer editable property. Setting this property to any color would change the border (bottom) to that color (setting other borders to none).

Since this also requires to change the place holder text color, I also added that to the extension.

    extension UITextField {

    @IBInspectable var placeHolderColor: UIColor? {
        get {
            return self.placeHolderColor
        }
        set {
            self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: newValue!])
        }
    }


    @IBInspectable var bottomBorderColor: UIColor? {
        get {
            return self.bottomBorderColor
        }
        set {
            self.borderStyle = UITextBorderStyle.None;
            let border = CALayer()
            let width = CGFloat(0.5)
            border.borderColor = newValue?.CGColor
            border.frame = CGRect(x: 0, y: self.frame.size.height - width,   width:  self.frame.size.width, height: self.frame.size.height)

            border.borderWidth = width
            self.layer.addSublayer(border)
            self.layer.masksToBounds = true

        }
    }
}

iPhone and WireShark

I recommend Charles Web Proxy

Charles is an HTTP proxy / HTTP monitor / Reverse Proxy that enables a developer to view all of the HTTP and SSL / HTTPS traffic between their machine and the Internet. This includes requests, responses and the HTTP headers (which contain the cookies and caching information).

  • SSL Proxying – view SSL requests and responses in plain text
  • Bandwidth Throttling to simulate slower Internet connections including latency
  • AJAX debugging – view XML and JSON requests and responses as a tree or as text
  • AMF – view the contents of Flash Remoting / Flex Remoting messages as a tree
  • Repeat requests to test back-end changes, Edit requests to test different inputs
  • Breakpoints to intercept and edit requests or responses
  • Validate recorded HTML, CSS and RSS/atom responses using the W3C validator

It's cross-platform, written in JAVA, and pretty good. Not nearly as overwhelming as Wireshark, and does a lot of the annoying stuff like setting up the proxies, etc. for you. The only bad part is that it costs money, $50 at that. Not cheap, but a useful tool.

Read more about Charles's features.

What is the list of supported languages/locales on Android?

Just FYI, if you are unable to set any locale, the problem might be below attribute in your app level gradle file:

resConfigs "en", "hi" //to specify allowed locales for your app

So, if you want to support any locale other than English and Hindi, specify your locale here or just remove above line. By default your app will support all the locales.

Thanks :)

Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done?

OK, there are two ways of doing that:

// GLOBAL_CONCURRENT_QUEUE


- (void)doCalculationsAndUpdateUIsWith_GlobalQUEUE 
{
    dispatch_queue_t globalConcurrentQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(globalConcurrentQ, ^{

       // DATA PROCESSING 1
       sleep(1);
       NSLog(@"Hello world chekpoint 1");
       dispatch_sync(dispatch_get_main_queue(), ^{
           // UI UPDATION 1
           sleep(1);
           NSLog(@"Hello world chekpoint 2");
       });

        /* the control to come here after UI UPDATION 1 */
        sleep(1);
        NSLog(@"Hello world chekpoint 3");
        // DATA PROCESSING 2

        dispatch_sync(dispatch_get_main_queue(), ^{
            // UI UPDATION 2
            sleep(1);
            NSLog(@"Hello world chekpoint 4");
        });

        /* the control to come here after UI UPDATION 2 */
        sleep(1);
        NSLog(@"Hello world chekpoint 5");
        // DATA PROCESSING 3

        dispatch_sync(dispatch_get_main_queue(), ^{
            // UI UPDATION 3
            sleep(1);
            NSLog(@"Hello world chekpoint 6");
        });
   });
}



// SERIAL QUEUE
- (void)doCalculationsAndUpdateUIsWith_GlobalQUEUE 
{

    dispatch_queue_t serialQ = dispatch_queue_create("com.example.MyQueue", NULL);
    dispatch_async(serialQ, ^{

       // DATA PROCESSING 1
       sleep(1);
       NSLog(@"Hello world chekpoint 1");

       dispatch_sync(dispatch_get_main_queue(), ^{
           // UI UPDATION 1
           sleep(1);
           NSLog(@"Hello world chekpoint 2");
       });


       sleep(1);
       NSLog(@"Hello world chekpoint 3");
       // DATA PROCESSING 2

       dispatch_sync(dispatch_get_main_queue(), ^{
           // UI UPDATION 2
           sleep(1);
           NSLog(@"Hello world chekpoint 4");
       });  
   });
}

What is the largest Safe UDP Packet Size on the Internet

I've read some good answers here; however, there are some minor mistakes. Some have answered that the Message Length field in the UDP header is a max of 65535 (0xFFFF); this is technically true. Some have answered that the actual maximum is (65535 - IPHL - UDPHL = 65507). The mistake, is that the Message Length field in the UDP Header includes all payload (Layers 5-7), plus the length of the UDP Header (8 Bytes). What this means is that if the message length field is 200 Bytes (0x00C8), the payload is actually 192 Bytes (0x00C0).

What is hard and fast is that the maximum size of an IP datagram is 65535 Bytes. This number is arrived at the sum total of the L3 and L4 headers, plus the Layers 5-7 payload. IP Header + UDP Header + Layers 5-7 = 65535 (Max).

The most correct answer for what is the maximum size of a UDP datagam is 65515 Bytes (0xFFEB), as a UDP datagram includes the UDP header. The most correct answer for what is the maximum size of a UDP payload is 65507 Bytes, as a UDP Payload does not include the UDP header.

Launch Minecraft from command line - username and password as prefix

Just create this batch command file in your game directory. Bat file takes one argument %1 as the username.

Also, I use a splash screen to make pretty. You will NOT be able to play online, but who cares.

Adjust your memory usage to fit your machine (-Xmx & -Xmns).

NOTE: this is for version of minecraft as of 2016-06-27

@ECHO OFF
SET DIR=%cd%
SET JAVA_HOME=%DIR%\runtime\jre-x64\1.8.0_25
SET JAVA=%JAVA_HOME%\bin\java.exe
SET LOW_MEM=768M
SET MAX_MEM=2G
SET LIBRARIES=versions\1.10.2\1.10.2-natives-59894925878961
SET MAIN_CLASS=net.minecraft.client.main.Main
SET CLASSPATH=libraries\com\mojang\netty\1.6\netty-1.6.jar;libraries\oshi-project\oshi-core\1.1\oshi-core-1.1.jar;libraries\net\java\dev\jna\jna\3.4.0\jna-3.4.0.jar;libraries\net\java\dev\jna\platform\3.4.0\platform-3.4.0.jar;libraries\com\ibm\icu\icu4j-core-mojang\51.2\icu4j-core-mojang-51.2.jar;libraries\net\sf\jopt-simple\jopt-simple\4.6\jopt-simple-4.6.jar;libraries\com\paulscode\codecjorbis\20101023\codecjorbis-20101023.jar;libraries\com\paulscode\codecwav\20101023\codecwav-20101023.jar;libraries\com\paulscode\libraryjavasound\20101123\libraryjavasound-20101123.jar;libraries\com\paulscode\librarylwjglopenal\20100824\librarylwjglopenal-20100824.jar;libraries\com\paulscode\soundsystem\20120107\soundsystem-20120107.jar;libraries\io\netty\netty-all\4.0.23.Final\netty-all-4.0.23.Final.jar;libraries\com\google\guava\guava\17.0\guava-17.0.jar;libraries\org\apache\commons\commons-lang3\3.3.2\commons-lang3-3.3.2.jar;libraries\commons-io\commons-io\2.4\commons-io-2.4.jar;libraries\commons-codec\commons-codec\1.9\commons-codec-1.9.jar;libraries\net\java\jinput\jinput\2.0.5\jinput-2.0.5.jar;libraries\net\java\jutils\jutils\1.0.0\jutils-1.0.0.jar;libraries\com\google\code\gson\gson\2.2.4\gson-2.2.4.jar;libraries\com\mojang\authlib\1.5.22\authlib-1.5.22.jar;libraries\com\mojang\realms\1.9.3\realms-1.9.3.jar;libraries\org\apache\commons\commons-compress\1.8.1\commons-compress-1.8.1.jar;libraries\org\apache\httpcomponents\httpclient\4.3.3\httpclient-4.3.3.jar;libraries\commons-logging\commons-logging\1.1.3\commons-logging-1.1.3.jar;libraries\org\apache\httpcomponents\httpcore\4.3.2\httpcore-4.3.2.jar;libraries\it\unimi\dsi\fastutil\7.0.12_mojang\fastutil-7.0.12_mojang.jar;libraries\org\apache\logging\log4j\log4j-api\2.0-beta9\log4j-api-2.0-beta9.jar;libraries\org\apache\logging\log4j\log4j-core\2.0-beta9\log4j-core-2.0-beta9.jar;libraries\org\lwjgl\lwjgl\lwjgl\2.9.4-nightly-20150209\lwjgl-2.9.4-nightly-20150209.jar;libraries\org\lwjgl\lwjgl\lwjgl_util\2.9.4-nightly-20150209\lwjgl_util-2.9.4-nightly-20150209.jar;versions\1.10.2\1.10.2.jar
SET JAVA_OPTIONS=-server -splash:splash.png -d64 -da -dsa -Xrs -Xms%LOW_MEM% -Xmx%MAX_MEM% -XX:NewSize=%LOW_MEM% -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode -XX:-UseAdaptiveSizePolicy -XX:+DisableExplicitGC -Djava.library.path=%LIBRARIES% -cp %CLASSPATH%  %MAIN_CLASS%

start /D %DIR% /I /HIGH %JAVA% %JAVA_OPTIONS% --username %1 --version 1.10.2 --gameDir %DIR% --assetsDir assets --assetIndex 1.10 --uuid 2536abce90e8476a871679918164abc5 --accessToken 99abe417230342cb8e9e2168ab46297a --userType legacy --versionType release --nativeLauncherVersion 307


Vue.js unknown custom element

I was following along the Vue documentation at https://vuejs.org/v2/guide/index.html when I ran into this issue.

Later they clarify the syntax:

So far, we’ve only registered components globally, using Vue.component:

   Vue.component('my-component-name', {
       // ... options ...
   })

Globally registered components can be used in the template of any root Vue instance (new Vue) created afterwards – and even inside all >subcomponents of that Vue instance’s component tree.

(https://vuejs.org/v2/guide/components.html#Organizing-Components)

So as Umesh Kadam says above, just make sure the global component definition comes before the var app = new Vue({}) instantiation.

Is there any way to change input type="date" format?

I believe the browser will use the local date format. Don't think it's possible to change. You could of course use a custom date picker.

Switch php versions on commandline ubuntu 16.04

You can use the below script to switch between PHP version easily I have included phpize configuration too.

https://github.com/anilkumararumulla/switch-php-version

Download the script file and run

sh switch.sh

Javascript counting number of objects in object

The easiest way to do this, with excellent performance and compatibility with both old and new browsers, is to include either Lo-Dash or Underscore in your page.

Then you can use either _.size(object) or _.keys(object).length

For your obj.Data, you could test this with:

console.log( _.size(obj.Data) );

or:

console.log( _.keys(obj.Data).length );

Lo-Dash and Underscore are both excellent libraries; you would find either one very useful in your code. (They are rather similar to each other; Lo-Dash is a newer version with some advantanges.)

Alternatively, you could include this function in your code, which simply loops through the object's properties and counts them:

function ObjectLength( object ) {
    var length = 0;
    for( var key in object ) {
        if( object.hasOwnProperty(key) ) {
            ++length;
        }
    }
    return length;
};

You can test this with:

console.log( ObjectLength(obj.Data) );

That code is not as fast as it could be in modern browsers, though. For a version that's much faster in modern browsers and still works in old ones, you can use:

function ObjectLength_Modern( object ) {
    return Object.keys(object).length;
}

function ObjectLength_Legacy( object ) {
    var length = 0;
    for( var key in object ) {
        if( object.hasOwnProperty(key) ) {
            ++length;
        }
    }
    return length;
}

var ObjectLength =
    Object.keys ? ObjectLength_Modern : ObjectLength_Legacy;

and as before, test it with:

console.log( ObjectLength(obj.Data) );

This code uses Object.keys(object).length in modern browsers and falls back to counting in a loop for old browsers.

But if you're going to all this work, I would recommend using Lo-Dash or Underscore instead and get all the benefits those libraries offer.

I set up a jsPerf that compares the speed of these various approaches. Please run it in any browsers you have handy to add to the tests.

Thanks to Barmar for suggesting Object.keys for newer browsers in his answer.

sqlalchemy IS NOT NULL select

In case anyone else is wondering, you can use is_ to generate foo IS NULL:

>>> from sqlalchemy.sql import column
>>> print column('foo').is_(None)
foo IS NULL
>>> print column('foo').isnot(None)
foo IS NOT NULL

How can I pad an int with leading zeros when using cout << operator?

With the following,

#include <iomanip>
#include <iostream>

int main()
{
    std::cout << std::setfill('0') << std::setw(5) << 25;
}

the output will be

00025

setfill is set to the space character (' ') by default. setw sets the width of the field to be printed, and that's it.


If you are interested in knowing how the to format output streams in general, I wrote an answer for another question, hope it is useful: Formatting C++ Console Output.

Maven error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

Besides what @khmarbaise has pointed out, I think you have mistyped your JAVA_HOME. If you have installed in the default location, then there should be no "-" (hyphen) between jdk and 1.7.0_04. So it would be

JAVA_HOME C:\Program Files\Java\jdk1.7.0_04 

How to test if a string is basically an integer in quotes using Ruby

Ruby 2.6.0 enables casting to an integer without raising an exception, and will return nil if the cast fails. And since nil mostly behaves like false in Ruby, you can easily check for an integer like so:

if Integer(my_var, exception: false)
  # do something if my_var can be cast to an integer
end

Using a dispatch_once singleton model in Swift

tl;dr: Use the class constant approach if you are using Swift 1.2 or above and the nested struct approach if you need to support earlier versions.

From my experience with Swift there are three approaches to implement the Singleton pattern that support lazy initialization and thread safety.

Class constant

class Singleton  {
   static let sharedInstance = Singleton()
}

This approach supports lazy initialization because Swift lazily initializes class constants (and variables), and is thread safe by the definition of let. This is now officially recommended way to instantiate a singleton.

Class constants were introduced in Swift 1.2. If you need to support an earlier version of Swift, use the nested struct approach below or a global constant.

Nested struct

class Singleton {
    class var sharedInstance: Singleton {
        struct Static {
            static let instance: Singleton = Singleton()
        }
        return Static.instance
    }
}

Here we are using the static constant of a nested struct as a class constant. This is a workaround for the lack of static class constants in Swift 1.1 and earlier, and still works as a workaround for the lack of static constants and variables in functions.

dispatch_once

The traditional Objective-C approach ported to Swift. I'm fairly certain there's no advantage over the nested struct approach but I'm putting it here anyway as I find the differences in syntax interesting.

class Singleton {
    class var sharedInstance: Singleton {
        struct Static {
            static var onceToken: dispatch_once_t = 0
            static var instance: Singleton? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = Singleton()
        }
        return Static.instance!
    }
}

See this GitHub project for unit tests.

Entity Framework Query for inner join

In case anyone's interested in the Method syntax, if you have a navigation property, it's way easy:

db.Services.Where(s=>s.ServiceAssignment.LocationId == 1);

If you don't, unless there's some Join() override I'm unaware of, I think it looks pretty gnarly (and I'm a Method syntax purist):

db.Services.Join(db.ServiceAssignments, 
     s => s.Id,
     sa => sa.ServiceId, 
     (s, sa) => new {service = s, asgnmt = sa})
.Where(ssa => ssa.asgnmt.LocationId == 1)
.Select(ssa => ssa.service);

performSelector may cause a leak because its selector is unknown

To ignore the error only in the file with the perform selector, add a #pragma as follows:

#pragma clang diagnostic ignored "-Warc-performSelector-leaks"

This would ignore the warning on this line, but still allow it throughout the rest of your project.

What is PECS (Producer Extends Consumer Super)?

public class Test {

    public class A {}

    public class B extends A {}

    public class C extends B {}

    public void testCoVariance(List<? extends B> myBlist) {
        B b = new B();
        C c = new C();
        myBlist.add(b); // does not compile
        myBlist.add(c); // does not compile
        A a = myBlist.get(0); 
    }

    public void testContraVariance(List<? super B> myBlist) {
        B b = new B();
        C c = new C();
        myBlist.add(b);
        myBlist.add(c);
        A a = myBlist.get(0); // does not compile
    }
}

How do I lowercase a string in Python?

Also, you can overwrite some variables:

s = input('UPPER CASE')
lower = s.lower()

If you use like this:

s = "Kilometer"
print(s.lower())     - kilometer
print(s)             - Kilometer

It will work just when called.

How to size an Android view based on its parent's dimensions

Roman, if you want to do your layout in Java code (ViewGroup descendant), it is possible. The trick is that you have to implement both onMeasure and onLayout methods. The onMeasure gets called first and you need to "measure" the subview (effectively sizing it to the desired value) there. You need to size it again in the onLayout call. If you fail to do this sequence or fail to call setMeasuredDimension() at the end of your onMeasure code, you won't get results. Why is this designed in such complicated and fragile way is beyond me.

Tomcat manager/html is not available?

In my case, the folder was _Manager. After I renamed it to Manager it worked.

Now, I see login popup and I enter credentials from conf/tomcat-users.xml, It all works fine.

How does origin/HEAD get set?

It is your setting as the owner of your local repo. Change it like this:

git remote set-head origin some_branch

And origin/HEAD will point to your branch instead of master. This would then apply to your repo only and not for others. By default, it will point to master, unless something else has been configured on the remote repo.

Manual entry for remote set-head provides some good information on this.

Edit: to emphasize: without you telling it to, the only way it would "move" would be a case like renaming the master branch, which I don't think is considered "organic". So, I would say organically it does not move.

Making Maven run all tests, even when some fail

Try to add the following configuration for surefire plugin in your pom.xml of root project:

<project>
  [...]
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
          <testFailureIgnore>true</testFailureIgnore>
        </configuration>
      </plugin>
    </plugins>
  </build>
  [...]
</project>

What is Java EE?

Java EE is actually a collection of technologies and APIs for the Java platform designed to support "Enterprise" Applications which can generally be classed as large-scale, distributed, transactional and highly-available applications designed to support mission-critical business requirements.

In terms of what an employee is looking for in specific techs, it is quite hard to say, because the playing field has kept changing over the last five years. It really is about the class of problems that are being solved more than anything else. Transactions and distribution are key.

How to decode Unicode escape sequences like "\u00ed" to proper UTF-8 encoded characters?

print_r(json_decode('{"t":"\u00ed"}')); // -> stdClass Object ( [t] => í )

Validate phone number using javascript

Here's how I do it.

_x000D_
_x000D_
function validate(phone) {_x000D_
  const regex = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;_x000D_
  console.log(regex.test(phone))_x000D_
}_x000D_
_x000D_
validate('1234567890')     // true_x000D_
validate(1234567890)       // true_x000D_
validate('(078)789-8908')  // true_x000D_
validate('123-345-3456')   // true
_x000D_
_x000D_
_x000D_

Classes vs. Modules in VB.NET

It is acceptable to use Module. Module is not used as a replacement for Class. Module serves its own purpose. The purpose of Module is to use as a container for

  • extension methods,
  • variables that are not specific to any Class, or
  • variables that do not fit properly in any Class.

Module is not like a Class since you cannot

  • inherit from a Module,
  • implement an Interface with a Module,
  • nor create an instance of a Module.

Anything inside a Module can be directly accessed within the Module assembly without referring to the Module by its name. By default, the access level for a Module is Friend.

Facebook Post Link Image

Old question but recently I seemed to be running into same issue with thumbnail images from my link not showing in status updates on Facebook. I post for many clients and this is relatively new.

FB doesn't seem to like long URLs anymore — if you use a URL shortener such as goo.gl or bitly.com, the thumbnail from your link/post will appear in your FB update.

LINQ Contains Case Insensitive

StringComparison.InvariantCultureIgnoreCase just do the job for me:

.Where(fi => fi.DESCRIPTION.Contains(description, StringComparison.InvariantCultureIgnoreCase));

Refresh or force redraw the fragment

To solve the problem, I use this:

Fragment frg = null;
frg = getFragmentManager().findFragmentByTag("Feedback");
final android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();

Specifying trust store information in spring boot application.properties

I was also having the same issue with Spring Boot and embedded Tomcat.

From what I understand these properties only set the Tomcat configuration parameters. According to the Tomcat documentation this is only used for Client authentication (i.e. for two-way SSL) and not for verifying remote certificates:

truststoreFile - The trust store file to use to validate client certificates.

https://tomcat.apache.org/tomcat-8.0-doc/config/http.html

In order to configure the trust store for HttpClient it largely depends on the HttpClient implementation you use. For instance for RestTemplate by default Spring Boot uses a SimpleClientHttpRequestFactory based on standard J2SE classes like java.net.HttpURLConnection.

I've come up with a solution based on the Apache HttpClient docs and these posts: http://vincentdevillers.blogspot.pt/2013/02/configure-best-spring-resttemplate.html http://literatejava.com/networks/ignore-ssl-certificate-errors-apache-httpclient-4-4/

Basically this allows for a RestTemplate bean that only trusts certificates signed by the root CA in the configured truststore.

@Configuration
public class RestClientConfig {

    // e.g. Add http.client.ssl.trust-store=classpath:ssl/truststore.jks to application.properties
    @Value("${http.client.ssl.trust-store}")
    private Resource trustStore;

    @Value("${http.client.ssl.trust-store-password}")
    private char[] trustStorePassword;

    @Value("${http.client.maxPoolSize}")
    private Integer maxPoolSize;


    @Bean
    public ClientHttpRequestFactory httpRequestFactory() {
        return new HttpComponentsClientHttpRequestFactory(httpClient());
    }

    @Bean
    public HttpClient httpClient() {

        // Trust own CA and all child certs
        Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
        try {
            SSLContext sslContext = SSLContexts
                    .custom()
                    .loadTrustMaterial(trustStore.getFile(),
                            trustStorePassword)
                    .build();

            // Since only our own certs are trusted, hostname verification is probably safe to bypass
            SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                    new HostnameVerifier() {

                        @Override
                        public boolean verify(final String hostname,
                                final SSLSession session) {
                            return true;
                        }
            });

            socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslSocketFactory)
                    .build();           

        } catch (Exception e) {
            //TODO: handle exceptions
            e.printStackTrace();
        }

        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        connectionManager.setMaxTotal(maxPoolSize);
        // This client is for internal connections so only one route is expected
        connectionManager.setDefaultMaxPerRoute(maxPoolSize);
        return HttpClientBuilder.create()
                .setConnectionManager(connectionManager)
                .disableCookieManagement()
                .disableAuthCaching()
                .build();
    }

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setRequestFactory(httpRequestFactory());
        return restTemplate;
    }    
}

And then you can use this custom Rest client whenever you need to, e.g.:

@Autowired
private RestTemplate restTemplate;

restTemplate.getForEntity(...)

This assumes your trying to connect to a Rest endpoint, but you can also use the above HttpClient bean for whatever you want.

C# Equivalent of SQL Server DataTypes

public static string FromSqlType(string sqlTypeString)
{
    if (! Enum.TryParse(sqlTypeString, out Enums.SQLType typeCode))
    {
        throw new Exception("sql type not found");
    }
    switch (typeCode)
    {
        case Enums.SQLType.varbinary:
        case Enums.SQLType.binary:
        case Enums.SQLType.filestream:
        case Enums.SQLType.image:
        case Enums.SQLType.rowversion:
        case Enums.SQLType.timestamp://?
            return "byte[]";
        case Enums.SQLType.tinyint:
            return "byte";
        case Enums.SQLType.varchar:
        case Enums.SQLType.nvarchar:
        case Enums.SQLType.nchar:
        case Enums.SQLType.text:
        case Enums.SQLType.ntext:
        case Enums.SQLType.xml:
            return "string";
        case Enums.SQLType.@char:
            return "char";
        case Enums.SQLType.bigint:
            return "long";
        case Enums.SQLType.bit:
            return "bool";
        case Enums.SQLType.smalldatetime:
        case Enums.SQLType.datetime:
        case Enums.SQLType.date:
        case Enums.SQLType.datetime2:
            return "DateTime";
        case Enums.SQLType.datetimeoffset:
            return "DateTimeOffset";
        case Enums.SQLType.@decimal:
        case Enums.SQLType.money:
        case Enums.SQLType.numeric:
        case Enums.SQLType.smallmoney:
            return "decimal";
        case Enums.SQLType.@float:
            return "double";
        case Enums.SQLType.@int:
            return "int";
        case Enums.SQLType.real:
            return "Single";
        case Enums.SQLType.smallint:
            return "short";
        case Enums.SQLType.uniqueidentifier:
            return "Guid";
        case Enums.SQLType.sql_variant:
            return "object";
        case Enums.SQLType.time:
            return "TimeSpan";
        default:
            throw new Exception("none equal type");
    }
}

public enum SQLType
{
    varbinary,//(1)
    binary,//(1)
    image,
    varchar,
    @char,
    nvarchar,//(1)
    nchar,//(1)
    text,
    ntext,
    uniqueidentifier,
    rowversion,
    bit,
    tinyint,
    smallint,
    @int,
    bigint,
    smallmoney,
    money,
    numeric,
    @decimal,
    real,
    @float,
    smalldatetime,
    datetime,
    sql_variant,
    table,
    cursor,
    timestamp,
    xml,
    date,
    datetime2,
    datetimeoffset,
    filestream,
    time,
}

How to escape special characters of a string with single backslashes

Simply using re.sub might also work instead of str.maketrans. And this would also work in python 2.x

>>> print(re.sub(r'(\-|\]|\^|\$|\*|\.|\\)',lambda m:{'-':'\-',']':'\]','\\':'\\\\','^':'\^','$':'\$','*':'\*','.':'\.'}[m.group()],"^stack.*/overflo\w$arr=1"))
\^stack\.\*/overflo\\w\$arr=1

How to fix "Headers already sent" error in PHP

I got this error many times before, and I am certain all PHP programmer got this error at least once before.

Possible Solution 1

This error may have been caused by the blank spaces before the start of the file or after the end of the file.These blank spaces should not be here.

ex) THERE SHOULD BE NO BLANK SPACES HERE

   echo "your code here";

?>
THERE SHOULD BE NO BLANK SPACES HERE

Check all files associated with file that causes this error.

Note: Sometimes EDITOR(IDE) like gedit (a default linux editor) add one blank line on save file. This should not happen. If you are using Linux. you can use VI editor to remove space/lines after ?> at the end of the page.

Possible Solution 2: If this is not your case, then use ob_start to output buffering:

<?php
  ob_start();

  // code 

 ob_end_flush();
?> 

This will turn output buffering on and your headers will be created after the page is buffered.

OnClick in Excel VBA

SelectionChange is the event built into the Excel Object model for this. It should do exactly as you want, firing any time the user clicks anywhere...

I'm not sure that I understand your objections to global variables here, you would only need 1 if you use the Application.SelectionChange event. However, you wouldn't need any if you utilize the Workbook class code behind (to trap the Workbook.SelectionChange event) or the Worksheet class code behind (to trap the Worksheet.SelectionChange) event. (Unless your issue is the "global variable reset" problem in VBA, for which there is only one solution: error handling everywhere. Do not allow any unhandled errors, instead log them and/or "soft-report" an error as a message box to the user.)

You might also need to trap the Worksheet.Activate() and Worksheet.Deactivate() events (or the equivalent in the Workbook class) and/or the Workbook.Activate and Workbook.Deactivate() events so that you know when the user has switched worksheets and/or workbooks. The Window activate and deactivate events should make this approach complete. They could all call the same exact procedure, however, they all denote the same thing: the user changed the "focus", if you will.

If you don't like VBA, btw, you can do the same using VB.NET or C#.

[Edit: Dbb makes a very good point about the SelectionChange event not picking up a click when the user clicks within the currently selected cell. If you need to pick that up, then you would need to use subclassing.]

How to add a custom HTTP header to every WCF call?

This is similar to NimsDotNet answer but shows how to do it programmatically.

Simply add the header to the binding

var cl = new MyServiceClient();

var eab = new EndpointAddressBuilder(cl.Endpoint.Address);

eab.Headers.Add( 
      AddressHeader.CreateAddressHeader("ClientIdentification",  // Header Name
                                         string.Empty,           // Namespace
                                         "JabberwockyClient"));  // Header Value

cl.Endpoint.Address = eab.ToEndpointAddress();

Display QImage with QtGui

Thanks All, I found how to do it, which is the same as Dave and Sergey:

I am using QT Creator:

In the main GUI window create using the drag drop GUI and create label (e.g. "myLabel")

In the callback of the button (clicked) do the following using the (*ui) pointer to the user interface window:

void MainWindow::on_pushButton_clicked()
{
     QImage imageObject;
     imageObject.load(imagePath);
     ui->myLabel->setPixmap(QPixmap::fromImage(imageObject));

     //OR use the other way by setting the Pixmap directly

     QPixmap pixmapObject(imagePath");
     ui->myLabel2->setPixmap(pixmapObject);
}

How to check if spark dataframe is empty?

For Java users you can use this on a dataset :

public boolean isDatasetEmpty(Dataset<Row> ds) {
        boolean isEmpty;
        try {
            isEmpty = ((Row[]) ds.head(1)).length == 0;
        } catch (Exception e) {
            return true;
        }
        return isEmpty;
}

This check all possible scenarios ( empty, null ).

Convert Java Date to UTC String

The following simplified code, based on the accepted answer above, worked for me:

public class GetSync {
    public static String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS zzz";
    private static final TimeZone utc = TimeZone.getTimeZone("UTC");
    private static final SimpleDateFormat isoFormatter = new SimpleDateFormat(ISO_FORMAT);
    static {
        isoFormatter.setTimeZone(utc);
    }

    public static String now() {
        return isoFormatter.format(new Date()).toString();
    }
}

I hope this helps somebody.