Programs & Examples On #Jacl

Implementation of the Tcl interpreter written in Java (Default scripting language expected by WAS administration)

Correct way to convert size in bytes to KB, MB, GB in JavaScript

_x000D_
_x000D_
function bytesToSize(bytes) {_x000D_
  var sizes = ['B', 'K', 'M', 'G', 'T', 'P'];_x000D_
  for (var i = 0; i < sizes.length; i++) {_x000D_
    if (bytes <= 1024) {_x000D_
      return bytes + ' ' + sizes[i];_x000D_
    } else {_x000D_
      bytes = parseFloat(bytes / 1024).toFixed(2)_x000D_
    }_x000D_
  }_x000D_
  return bytes + ' P';_x000D_
}_x000D_
_x000D_
console.log(bytesToSize(234));_x000D_
console.log(bytesToSize(2043));_x000D_
console.log(bytesToSize(20433242));_x000D_
console.log(bytesToSize(2043324243));_x000D_
console.log(bytesToSize(2043324268233));_x000D_
console.log(bytesToSize(2043324268233343));
_x000D_
_x000D_
_x000D_

How to set custom ActionBar color / style?

As I was using AppCompatActivity above answers didn't worked for me. But the below solution worked:

In res/styles.xml

<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
</style>


PS: I've used colorPrimary instead of android:colorPrimary

Finding the number of days between two dates

$start = '2013-09-08';
$end = '2013-09-15';
$diff = (strtotime($end)- strtotime($start))/24/3600; 
echo $diff;

slideToggle JQuery right to left

I would suggest you use the below css

.showhideoverlay { 
  width: 100%;
  height: 100%;
  right: 0px;
  top: 0px;
  position: fixed;
  background: #000;
  opacity: 0.75;
}

You can then use a simple toggle function:

$('a.open').click(function() {
  $('div.showhideoverlay').toggle("slow");
});

This will display the overlay menu from right to left. Alternatively, you can use the positioning for changing the effect from top or bottom, i.e. use bottom: 0; instead of top: 0; - you will see menu sliding from right-bottom corner.

Save text file UTF-8 encoded with VBA

I looked into the answer from Máta whose name hints at encoding qualifications and experience. The VBA docs say CreateTextFile(filename, [overwrite [, unicode]]) creates a file "as a Unicode or ASCII file. The value is True if the file is created as a Unicode file; False if it's created as an ASCII file. If omitted, an ASCII file is assumed." It's fine that a file stores unicode characters, but in what encoding? Unencoded unicode can't be represented in a file.

The VBA doc page for OpenTextFile(filename[, iomode[, create[, format]]]) offers a third option for the format:

  • TriStateDefault 2 "opens the file using the system default."
  • TriStateTrue 1 "opens the file as Unicode."
  • TriStateFalse 0 "opens the file as ASCII."

Máta passes -1 for this argument.

Judging from VB.NET documentation (not VBA but I think reflects realities about how underlying Windows OS represents unicode strings and echoes up into MS Office, I don't know) the system default is an encoding using 1 byte/unicode character using an ANSI code page for the locale. UnicodeEncoding is UTF-16. The docs also describe UTF-8 is also a "Unicode encoding," which makes sense to me. But I don't yet know how to specify UTF-8 for VBA output nor be confident that the data I write to disk with the OpenTextFile(,,,1) is UTF-16 encoded. Tamalek's post is helpful.

Linq order by, group by and order by each group?

Alternatively you can do like this :

     var _items = from a in StudentsGrades
                  group a by a.Name;

     foreach (var _itemGroup in _items)
     {
        foreach (var _item in _itemGroup.OrderBy(a=>a.grade))
        {
           ------------------------
           --------------------------
        }
     }

How to include CSS file in Symfony 2 and Twig?

And you can use %stylesheets% (assetic feature) tag:

{% stylesheets
    "@MainBundle/Resources/public/colorbox/colorbox.css"
    "%kerner.root_dir%/Resources/css/main.css"
%}
<link type="text/css" rel="stylesheet" media="all" href="{{ asset_url }}" />
{% endstylesheets %}

You can write path to css as parameter (%parameter_name%).

More about this variant: http://symfony.com/doc/current/cookbook/assetic/asset_management.html

Unfinished Stubbing Detected in Mockito

For those who use com.nhaarman.mockitokotlin2.mock {}

This error occurs when, for example, we create a mock inside another mock

mock {
    on { x() } doReturn mock {
        on { y() } doReturn z()
    }
}

The solution to this is to create the child mock in a variable and use the variable in the scope of the parent mock to prevent the mock creation from being explicitly nested.

val liveDataMock = mock {
        on { y() } doReturn z()
}
mock {
    on { x() } doReturn liveDataMock
}

GL

The best way to calculate the height in a binary search tree? (balancing an AVL-tree)

This BFS-like solution is pretty straightforward. Simply jumps levels one-by-one.

def getHeight(self,root, method='links'):
    c_node = root
    cur_lvl_nodes = [root]
    nxt_lvl_nodes = []
    height = {'links': -1, 'nodes': 0}[method]

    while(cur_lvl_nodes or nxt_lvl_nodes):
        for c_node in cur_lvl_nodes:
            for n_node in filter(lambda x: x is not None, [c_node.left, c_node.right]):
                nxt_lvl_nodes.append(n_node)

        cur_lvl_nodes = nxt_lvl_nodes
        nxt_lvl_nodes = []
        height += 1

    return height

EditorFor() and html properties

As at MVC 5, if you wish to add any attributes you can simply do

 @Html.EditorFor(m => m.Name, new { htmlAttributes = new { @required = "true", @anotherAttribute = "whatever" } })

Information found from this blog

Make git automatically remove trailing whitespace before committing

Slightly late but since this might help someone out there, here goes.

Open the file in VIM. To replace tabs with whitespaces, type the following in vim command line

:%s#\t#    #gc

To get rid of other trailing whitespaces

:%s#\s##gc

This pretty much did it for me. It's tedious if you have a lot of files to edit. But I found it easier than pre-commit hooks and working with multiple editors.

Creating layout constraints programmatically

Regarding your second question about properties, you can use self.myView only if you declared it as a property in class. Since myView is a local variable, you can not use it that way. For more details on this, I would recommend you to go through the apple documentation on Declared Properties,

How to change value of object which is inside an array using JavaScript or jQuery?

Here is a nice neat clear answer. I wasn't 100% sure this would work but it seems to be fine. Please let me know if a lib is required for this, but I don't think one is. Also if this doesn't work in x browser please let me know. I tried this in Chrome IE11 and Edge they all seemed to work fine.

    var Students = [
        { ID: 1, FName: "Ajay", LName: "Test1", Age: 20},
        { ID: 2, FName: "Jack", LName: "Test2", Age: 21},
        { ID: 3, FName: "John", LName: "Test3", age: 22},
        { ID: 4, FName: "Steve", LName: "Test4", Age: 22}
    ]

    Students.forEach(function (Student) {
        if (Student.LName == 'Test1') {
            Student.LName = 'Smith'
        }
        if (Student.LName == 'Test2') {
            Student.LName = 'Black'
        }
    });

    Students.forEach(function (Student) {
        document.write(Student.FName + " " + Student.LName + "<BR>");
    });

Output should be as follows

Ajay Smith

Jack Black

John Test3

Steve Test4

Maven skip tests

To skip the test case during maven clean install i used -DskipTests paramater in following command

mvn clean install -DskipTests

into terminal window

Link and execute external JavaScript file hosted on GitHub

I had the same issue as you, what I did is change to

<script type="application/javascript" src="bootstrap-wysiwyg.js"></script>

It works for me.

Why is Android Studio reporting "URI is not registered"?

Don't know the reason behind this error but I found out this somewhere and it solved my problem.

  • Go to "File > Project Structure > Modules"
  • Click "add (+)"
  • Click "android" and "apply" and then "ok"

What is the difference between require and require-dev sections in composer.json?

From the composer site (it's clear enough)

require#

Lists packages required by this package. The package will not be installed unless those requirements can be met.

require-dev (root-only)#

Lists packages required for developing this package, or running tests, etc. The dev requirements of the root package are installed by default. Both install or update support the --no-dev option that prevents dev dependencies from being installed.

Using require-dev in Composer you can declare the dependencies you need for development/testing the project but don't need in production. When you upload the project to your production server (using git) require-dev part would be ignored.

Also check this answer posted by the author and this post as well.

Error while trying to retrieve text for error ORA-01019

In my case, I just needed to install oracle 10g client on the server, becase there there was the 11g version.

Ps: I don't needed unistall nothing, I just install the 10g version and updated the tnsnames file (C:\oracle\product\10.2.0\client_1\NETWORK\ADMIN)

Convert categorical data in pandas dataframe

Here multiple columns need to be converted. So, one approach i used is ..

for col_name in df.columns:
    if(df[col_name].dtype == 'object'):
        df[col_name]= df[col_name].astype('category')
        df[col_name] = df[col_name].cat.codes

This converts all string / object type columns to categorical. Then applies codes to each type of category.

Running Groovy script from the command line

#!/bin/sh
sed '1,2d' "$0"|$(which groovy) /dev/stdin; exit;

println("hello");

Regex: Specify "space or start of string" and "space or end of string"

Here's what I would use:

 (?<!\S)stackoverflow(?!\S)

In other words, match "stackoverflow" if it's not preceded by a non-whitespace character and not followed by a non-whitespace character.

This is neater (IMO) than the "space-or-anchor" approach, and it doesn't assume the string starts and ends with word characters like the \b approach does.

Find common substring between two strings

As if this question doesn't have enough answers, here's another option:

from collections import defaultdict
def LongestCommonSubstring(string1, string2):
    match = ""
    matches = defaultdict(list)
    str1, str2 = sorted([string1, string2], key=lambda x: len(x))

    for i in range(len(str1)):
        for k in range(i, len(str1)):
            cur = match + str1[k]
            if cur in str2:
                match = cur
            else:
                match = ""
            
            if match:
                matches[len(match)].append(match)
        
    if not matches:
        return ""

    longest_match = max(matches.keys())
        
    return matches[longest_match][0]

Some example cases:

LongestCommonSubstring("whose car?", "this is my car")
> ' car'
LongestCommonSubstring("apple pies", "apple? forget apple pie!")
> 'apple pie'

How to remove all line breaks from a string

On mac, just use \n in regexp to match linebreaks. So the code will be string.replace(/\n/g, ''), ps: the g followed means match all instead of just the first.

On windows, it will be \r\n.

How to print Unicode character in Python?

In Python 2, you declare unicode strings with a u, as in u"?" and use decode() and encode() to translate to and from unicode, respectively.

It's quite a bit easier in Python 3. A very good overview can be found here. That presentation clarified a lot of things for me.

Replacing a fragment with another fragment inside activity group

hope you are doing well.when I started work with Android Fragments then I was also having the same problem then I read about 1- How to switch fragment with other. 2- How to add fragment if Fragment container does not have any fragment.

then after some R&D, I created a function which helps me in many Projects till now and I am still using this simple function.

public void switchFragment(BaseFragment baseFragment) {
    try {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
        if (getSupportFragmentManager().findFragmentById(R.id.home_frame) == null) {
            ft.add(R.id.home_frame, baseFragment);
        } else {
            ft.replace(R.id.home_frame, baseFragment);
        }
        ft.addToBackStack(null);
        ft.commit();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

enjoy your code time :)

Pass a simple string from controller to a view MVC3

Just define your action method like this

public string ThemePath()

and simply return the string itself.

Interface type check with Typescript

It's now possible, I just released an enhanced version of the TypeScript compiler that provides full reflection capabilities. You can instantiate classes from their metadata objects, retrieve metadata from class constructors and inspect interface/classes at runtime. You can check it out here

Usage example:

In one of your typescript files, create an interface and a class that implements it like the following:

interface MyInterface {
    doSomething(what: string): number;
}

class MyClass implements MyInterface {
    counter = 0;

    doSomething(what: string): number {
        console.log('Doing ' + what);
        return this.counter++;
    }
}

now let's print some the list of implemented interfaces.

for (let classInterface of MyClass.getClass().implements) {
    console.log('Implemented interface: ' + classInterface.name)
}

compile with reflec-ts and launch it:

$ node main.js
Implemented interface: MyInterface
Member name: counter - member kind: number
Member name: doSomething - member kind: function

See reflection.d.ts for Interface meta-type details.

UPDATE: You can find a full working example here

JavaScript for handling Tab Key press

try this

 <body>
   <div class="linkCollection">
             <a tabindex=1 href="www.demo1.com">link</a>    
             <a tabindex=2 href="www.demo2.com">link</a>    
             <a tabindex=3 href="www.demo3.com">link</a>    
             <a tabindex=4 href="www.demo4.com">link</a>    
             <a tabindex=5 href="www.demo5.com">link</a>    
             <a tabindex=6 href="www.demo6.com">link</a>    
             <a tabindex=7 href="www.demo7.com">link</a>    
             <a tabindex=8 href="www.demo8.com">link</a>    
             <a tabindex=9 href="www.demo9.com">link</a>    
             <a tabindex=10 href="www.demo10.com">link</a>   
        </div>

</body>

<script>
$(document).ready(function(){
  $(".linkCollection a").focus(function(){
    var href=$(this).attr('href');
    console.log(href);
    // href variable holds the active selected link.
  });
});
</script>

don't forgot to add jQuery library

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

Element implicitly has an 'any' type because expression of type 'string' can't be used to index

I have made a simulation of the problem. looks like the issue is how we should Access Object Properties Dynamically Using Bracket Notation in Typescript

interface IUserProps {
  name: string;
  age: number;
}

export default class User {
  constructor(private data: IUserProps) {}

  get(propName: string): string | number {
    return this.data[propName as keyof IUserProps];
  }
}

I found a blog that might be helpful to understand this better.

here is a link https://www.nadershamma.dev/blog/2019/how-to-access-object-properties-dynamically-using-bracket-notation-in-typescript/

Get the name of an object's type

A little trick I use:

function Square(){
    this.className = "Square";
    this.corners = 4;
}

var MySquare = new Square();
console.log(MySquare.className); // "Square"

How to add screenshot to READMEs in github repository?

One line below should be what you looking for

if your file is in repository

![ScreenShot](https://raw.github.com/{username}/{repository}/{branch}/{path})

if your file is in other external url

![ScreenShot](https://{url})

Regex for remove everything after | (with | )

If you want to get everything after | excluding set character use this code.

[^|]*$

Others solutions \|.*$

Results : | mypcworld

This one [^|]*$

Results : mypcworld

http://regexr.com/3elkd

PHP date() with timezone?

Not mentioned above. You could also crate a DateTime object by providing a timestamp as string in the constructor with a leading @ sign.

$dt = new DateTime('@123456789');
$dt->setTimezone(new DateTimeZone('America/New_York'));
echo $dt->format('F j, Y - G:i');

See the documentation about compound formats: https://www.php.net/manual/en/datetime.formats.compound.php

How would I run an async Task<T> method synchronously?

Be advised this answer is three years old. I wrote it based mostly on a experience with .Net 4.0, and very little with 4.5 especially with async-await. Generally speaking it's a nice simple solution, but it sometimes breaks things. Please read the discussion in the comments.

.Net 4.5

Just use this:

// For Task<T>: will block until the task is completed...
var result = task.Result; 

// For Task (not Task<T>): will block until the task is completed...
task2.RunSynchronously();

See: TaskAwaiter, Task.Result, Task.RunSynchronously


.Net 4.0

Use this:

var x = (IAsyncResult)task;
task.Start();

x.AsyncWaitHandle.WaitOne();

...or this:

task.Start();
task.Wait();

How to deep copy a list?

Regarding the list as a tree, the deep_copy in python can be most compactly written as

def deep_copy(x):
    if not isinstance(x, list): return x
    else: return map(deep_copy, x)

'react-scripts' is not recognized as an internal or external command

When I make a new project using React, to install the React modules I have to run "npm install" (PowerShell) from within the new projects ClientApp folder (e.g. "C:\Users\Chris\source\repos\HelloWorld2\HelloWorld2\ClientApp"). The .NET core WebApp with React needs to have the React files installed in the correct location for React commands to work properly.

Validating IPv4 addresses with regexp

-bash-3.2$ echo "191.191.191.39" | egrep 
  '(^|[^0-9])((2([6-9]|5[0-5]?|[0-4][0-9]?)?|1([0-9][0-9]?)?|[3-9][0-9]?|0)\.{3}
     (2([6-9]|5[0-5]?|[0-4][0-9]?)?|1([0-9][0-9]?)?|[3-9][0-9]?|0)($|[^0-9])'

>> 191.191.191.39

(This is a DFA that matches the entire addr space (including broadcasts, etc.) an nothing else.

How to create a batch file to run cmd as administrator

Press Ctrl+Shift and double-click a shortcut to run as an elevated process.

Works from the start menu as well.

JavaScript - Replace all commas in a string

The third parameter of String.prototype.replace() function was never defined as a standard, so most browsers simply do not implement it.

The best way is to use regular expression with g (global) flag.

_x000D_
_x000D_
var myStr = 'this,is,a,test';_x000D_
var newStr = myStr.replace(/,/g, '-');_x000D_
_x000D_
console.log( newStr );  // "this-is-a-test"
_x000D_
_x000D_
_x000D_

Still have issues?

It is important to note, that regular expressions use special characters that need to be escaped. As an example, if you need to escape a dot (.) character, you should use /\./ literal, as in the regex syntax a dot matches any single character (except line terminators).

_x000D_
_x000D_
var myStr = 'this.is.a.test';_x000D_
var newStr = myStr.replace(/\./g, '-');_x000D_
_x000D_
console.log( newStr );  // "this-is-a-test"
_x000D_
_x000D_
_x000D_

If you need to pass a variable as a replacement string, instead of using regex literal you may create RegExp object and pass a string as the first argument of the constructor. The normal string escape rules (preceding special characters with \ when included in a string) will be necessary.

_x000D_
_x000D_
var myStr = 'this.is.a.test';_x000D_
var reStr = '\\.';_x000D_
var newStr = myStr.replace(new RegExp(reStr, 'g'), '-');_x000D_
_x000D_
console.log( newStr );  // "this-is-a-test"
_x000D_
_x000D_
_x000D_

Is it possible to set async:false to $.getJSON call

If you just need to await to avoid nesting code:

let json;
await new Promise(done => $.getJSON('https://***', async function (data) {
    json = data;
    done();
}));

What is the best IDE to develop Android apps in?

I am a huge supporter of using the environment that is most familiar to you. However this isn't always the best option. In some cases, a different environment can result in (far?) greater efficency in the long run.

In this particular case I suspect that sticking with what you already know is a good option, but someone starting new would benifit from the easy setup and sdk/ndk integration offered by eclipse. I also don't know how available geolocation manipulation (or phone state manipulation - ie incoming call etc) is in other IDE's, but integration within eclipse feels seamless.

AIDE is a fun option that I use while traveling or when I don't feel like sitting at my desk all the time. It is an extrodinarly well put together IDE that runs on Android, compiles Android appications, and then lets you install, all without touching a computer. It includes a logcat readout, syntax highlighting and some git compatibility as well. Obviously you don't have a lot of screen real estate available and things can get cluttered or you can't see everything you want to at once, but for quick touchups or early in a project it is more than adequate.

How to insert an image in python

Install PIL(Python Image Library) :

then:

from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();

font-weight is not working properly?

I removed the text-transform: uppercase; and then set it to bold/bolder, and this seemed to work.

PHP CURL DELETE request

I finally solved this myself. If anyone else is having this problem, here is my solution:

I created a new method:

public function curl_del($path)
{
    $url = $this->__url.$path;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return $result;
}

Update 2

Since this seems to help some people, here is my final curl DELETE method, which returns the HTTP response in JSON decoded object:

  /**
 * @desc    Do a DELETE request with cURL
 *
 * @param   string $path   path that goes after the URL fx. "/user/login"
 * @param   array  $json   If you need to send some json with your request.
 *                         For me delete requests are always blank
 * @return  Obj    $result HTTP response from REST interface in JSON decoded.
 */
public function curl_del($path, $json = '')
{
    $url = $this->__url.$path;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    $result = json_decode($result);
    curl_close($ch);

    return $result;
}

How to set a bitmap from resource

Assuming you are calling this in an Activity class

Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);

The first parameter, Resources, is required. It is normally obtainable in any Context (and subclasses like Activity).

Why don’t my SVG images scale using the CSS "width" property?

I had to figure it out myself but some svgs your need to match the viewBox & width+height in.

E.g. if it already has width="x" height="y" then =>

add <svg ... viewBox="0 0 [width] [height]">

and the opposite.

After that it will scale with <svg ... style="width: xxx; height: yyy;">

What is the difference between gravity and layout_gravity in Android?

The basic difference between the two is that-

android:gravity is used for child elements of the view.

android:layout_gravity is used for this element with respect to parent view.

How to solve PHP error 'Notice: Array to string conversion in...'

You are using <input name='C[]' in your HTML. This creates an array in PHP when the form is sent.

You are using echo $_POST['C']; to echo that array - this will not work, but instead emit that notice and the word "Array".

Depending on what you did with the rest of the code, you should probably use echo $_POST['C'][0];

fitting data with numpy

Unfortunately, np.polynomial.polynomial.polyfit returns the coefficients in the opposite order of that for np.polyfit and np.polyval (or, as you used np.poly1d). To illustrate:

In [40]: np.polynomial.polynomial.polyfit(x, y, 4)
Out[40]: 
array([  84.29340848, -100.53595376,   44.83281408,   -8.85931101,
          0.65459882])

In [41]: np.polyfit(x, y, 4)
Out[41]: 
array([   0.65459882,   -8.859311  ,   44.83281407, -100.53595375,
         84.29340846])

In general: np.polynomial.polynomial.polyfit returns coefficients [A, B, C] to A + Bx + Cx^2 + ..., while np.polyfit returns: ... + Ax^2 + Bx + C.

So if you want to use this combination of functions, you must reverse the order of coefficients, as in:

ffit = np.polyval(coefs[::-1], x_new)

However, the documentation states clearly to avoid np.polyfit, np.polyval, and np.poly1d, and instead to use only the new(er) package.

You're safest to use only the polynomial package:

import numpy.polynomial.polynomial as poly

coefs = poly.polyfit(x, y, 4)
ffit = poly.polyval(x_new, coefs)
plt.plot(x_new, ffit)

Or, to create the polynomial function:

ffit = poly.Polynomial(coefs)    # instead of np.poly1d
plt.plot(x_new, ffit(x_new))

fit and data plot

Web.Config Debug/Release

It is possible using ConfigTransform build target available as a Nuget package - https://www.nuget.org/packages/CodeAssassin.ConfigTransform/

All "web.*.config" transform files will be transformed and output as a series of "web.*.config.transformed" files in the build output directory regardless of the chosen build configuration.

The same applies to "app.*.config" transform files in non-web projects.

and then adding the following target to your *.csproj.

<Target Name="TransformActiveConfiguration" Condition="Exists('$(ProjectDir)/Web.$(Configuration).config')" BeforeTargets="Compile" >
    <TransformXml Source="$(ProjectDir)/Web.Config" Transform="$(ProjectDir)/Web.$(Configuration).config" Destination="$(TargetDir)/Web.config" />
</Target>

Posting an answer as this is the first Stackoverflow post that appears in Google on the subject.

How to center a (background) image within a div?

If your background image is a vertically aligned sprite sheet, you can horizontally center each sprite like this:

#doit {
    background-image: url('images/pic.png'); 
    background-repeat: none;
    background-position: 50% [y position of sprite];
}

If your background image is a horizontally aligned sprite sheet, you can vertically center each sprite like this:

#doit {
    background-image: url('images/pic.png'); 
    background-repeat: none;
    background-position: [x position of sprite] 50%;
}

If your sprite sheet is compact, or you are not trying to center your background image in one of the aforementioned scenarios, these solutions do not apply.

Use .htaccess to redirect HTTP to HTTPs

Nothing of the above worked for me. But those lines solved the same problem on my WordPress site:

RewriteEngine On

RewriteCond %{HTTP:HTTPS} !on
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Is it a good practice to place C++ definitions in header files?

If this new way is really The Way, we might have been running into different direction in our projects.

Because we try to avoid all unnecessary things in headers. That includes avoiding header cascade. Code in headers will propably need some other header to be included, which will need another header and so on. If we are forced to use templates, we try avoid littering headers with template stuff too much.

Also we use "opaque pointer"-pattern when applicable.

With these practices we can do faster builds than most of our peers. And yes... changing code or class members will not cause huge rebuilds.

How to push to History in React Router v4?

I was able to accomplish this by using bind(). I wanted to click a button in index.jsx, post some data to the server, evaluate the response, and redirect to success.jsx. Here's how I worked that out...

index.jsx:

import React, { Component } from "react"
import { postData } from "../../scripts/request"

class Main extends Component {
    constructor(props) {
        super(props)
        this.handleClick = this.handleClick.bind(this)
        this.postData = postData.bind(this)
    }

    handleClick() {
        const data = {
            "first_name": "Test",
            "last_name": "Guy",
            "email": "[email protected]"
        }

        this.postData("person", data)
    }

    render() {
        return (
            <div className="Main">
                <button onClick={this.handleClick}>Test Post</button>
            </div>
        )
    }
}

export default Main

request.js:

import { post } from "./fetch"

export const postData = function(url, data) {
    // post is a fetch() in another script...
    post(url, data)
        .then((result) => {
            if (result.status === "ok") {
                this.props.history.push("/success")
            }
        })
}

success.jsx:

import React from "react"

const Success = () => {
    return (
        <div className="Success">
            Hey cool, got it.
        </div>
    )
}

export default Success

So by binding this to postData in index.jsx, I was able to access this.props.history in request.js... then I can reuse this function in different components, just have to make sure I remember to include this.postData = postData.bind(this) in the constructor().

How to write one new line in Bitbucket markdown?

Feb 3rd 2020:

  • Atlassian Bitbucket v5.8.3 local installation.
  • I wanted to add a new line around an horizontal line. --- did produce the line, but I could not get new lines to work with suggestions above.
  • note: I did not want to use the [space][space] suggestion, since my editor removes trailing spaces on save, and I like this feature on.

I ended up doing this:

TEXT...
<br><hr><br>
TEXT...

Resulting in:

TEXT...
<AN EMPTY LINE>
----------------- AN HORIZONTAL LINE ----------------
<AN EMPTY LINE>
TEXT...

Setting a windows batch file variable to the day of the week

I thought that my first answer gives the correct day of week as a number between 0 and 6. However, because you had not indicated why this answer does not give the result you want, I can only guess the reason.

The Batch file below create a log file each day with a digit in the name, 0=Sunday, 1=Monday, etc... The program assume that echo %date% show the date in MM/DD/YYYY format; if this is not the case, just change the position of mm and dd variables in the for command.

@echo off
for /F "tokens=1-3 delims=/" %%a in ("%date%") do set /A mm=10%%a %% 100, dd=10%%b %% 100, yy=%%c
if %mm% lss 3 set /A mm+=12, yy-=1
set /A a=yy/100, b=a/4, c=2-a+b, e=36525*(yy+4716)/100, f=306*(mm+1)/10, dow=(c+dd+e+f-1523)%%7
echo Today log data > Day-%dow%.txt

If this is not what you want, please indicate the problem so I can fix it.

EDIT: The version below get date parts independent of locale settings:

@echo off
for /F "skip=1 tokens=2-4 delims=(-/)" %%A in ('date ^< NUL') do (
   for /F "tokens=1-3 delims=/" %%a in ("%date%") do (
      set %%A=%%a
      set %%B=%%b
      set %%C=%%c
   )
)
set /A mm=10%mm% %% 100, dd=10%dd% %% 100
if %mm% lss 3 set /A mm+=12, yy-=1
set /A a=yy/100, b=a/4, c=2-a+b, e=36525*(yy+4716)/100, f=306*(mm+1)/10, 

dow=(c+dd+e+f-1523)%%7
echo Today log data > Day-%dow%.txt

EDIT: The version below insert day of week as 3-letter short name:

@echo off
for /F "skip=1 tokens=2-4 delims=(-/)" %%A in ('date ^< NUL') do (
   for /F "tokens=1-3 delims=/" %%a in ("%date%") do (
      set %%A=%%a
      set %%B=%%b
      set %%C=%%c
   )
)
set /A mm=10%mm% %% 100, dd=10%dd% %% 100
if %mm% lss 3 set /A mm+=12, yy-=1
set /A a=yy/100, b=a/4, c=2-a+b, e=36525*(yy+4716)/100, f=306*(mm+1)/10, 

dow=(c+dd+e+f-1523)%%7 + 1
for /F "tokens=%dow%" %%a in ("Sun Mon Tue Wed Thu Fri Sat") do set dow=%%a
echo Today log data > Day-%dow%.txt

Regards,

Antonio

Gradle sync failed: failed to find Build Tools revision 24.0.0 rc1

faced the same problem: Gradle sync failed: failed to find Build Tools revision x.x.x

reason: the build tools for that version was not down loaded properly solution:

  1. Click File > Settings (on a Mac, Android Studio > Preferences) to open the Settings dialog.
  2. Go to Appearance & Behavior > System Settings > Android SDK (Or simply search for Android SDK on the search bar)
  3. Go to SDK Tools tab > Check the Show Package Details checkbox
  4. uncheck the specific version to remove it.
  5. click apply.

then follow the steps 1 to 3 and 6.

  1. Select the specific version of the build tool and click on the Apply button After the installation, sync the project

ProcessStartInfo hanging on "WaitForExit"? Why?

Introduction

Currently accepted answer doesn't work (throws exception) and there are too many workarounds but no complete code. This is obviously wasting lots of people's time because this is a popular question.

Combining Mark Byers' answer and Karol Tyl's answer I wrote full code based on how I want to use the Process.Start method.

Usage

I have used it to create progress dialog around git commands. This is how I've used it:

    private bool Run(string fullCommand)
    {
        Error = "";
        int timeout = 5000;

        var result = ProcessNoBS.Start(
            filename: @"C:\Program Files\Git\cmd\git.exe",
            arguments: fullCommand,
            timeoutInMs: timeout,
            workingDir: @"C:\test");

        if (result.hasTimedOut)
        {
            Error = String.Format("Timeout ({0} sec)", timeout/1000);
            return false;
        }

        if (result.ExitCode != 0)
        {
            Error = (String.IsNullOrWhiteSpace(result.stderr)) 
                ? result.stdout : result.stderr;
            return false;
        }

        return true;
    }

In theory you can also combine stdout and stderr, but I haven't tested that.

Code

public struct ProcessResult
{
    public string stdout;
    public string stderr;
    public bool hasTimedOut;
    private int? exitCode;

    public ProcessResult(bool hasTimedOut = true)
    {
        this.hasTimedOut = hasTimedOut;
        stdout = null;
        stderr = null;
        exitCode = null;
    }

    public int ExitCode
    {
        get 
        {
            if (hasTimedOut)
                throw new InvalidOperationException(
                    "There was no exit code - process has timed out.");

            return (int)exitCode;
        }
        set
        {
            exitCode = value;
        }
    }
}

public class ProcessNoBS
{
    public static ProcessResult Start(string filename, string arguments,
        string workingDir = null, int timeoutInMs = 5000,
        bool combineStdoutAndStderr = false)
    {
        using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
        using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
        {
            using (var process = new Process())
            {
                var info = new ProcessStartInfo();

                info.CreateNoWindow = true;
                info.FileName = filename;
                info.Arguments = arguments;
                info.UseShellExecute = false;
                info.RedirectStandardOutput = true;
                info.RedirectStandardError = true;

                if (workingDir != null)
                    info.WorkingDirectory = workingDir;

                process.StartInfo = info;

                StringBuilder stdout = new StringBuilder();
                StringBuilder stderr = combineStdoutAndStderr
                    ? stdout : new StringBuilder();

                var result = new ProcessResult();

                try
                {
                    process.OutputDataReceived += (sender, e) =>
                    {
                        if (e.Data == null)
                            outputWaitHandle.Set();
                        else
                            stdout.AppendLine(e.Data);
                    };
                    process.ErrorDataReceived += (sender, e) =>
                    {
                        if (e.Data == null)
                            errorWaitHandle.Set();
                        else
                            stderr.AppendLine(e.Data);
                    };

                    process.Start();

                    process.BeginOutputReadLine();
                    process.BeginErrorReadLine();

                    if (process.WaitForExit(timeoutInMs))
                        result.ExitCode = process.ExitCode;
                    // else process has timed out 
                    // but that's already default ProcessResult

                    result.stdout = stdout.ToString();
                    if (combineStdoutAndStderr)
                        result.stderr = null;
                    else
                        result.stderr = stderr.ToString();

                    return result;
                }
                finally
                {
                    outputWaitHandle.WaitOne(timeoutInMs);
                    errorWaitHandle.WaitOne(timeoutInMs);
                }
            }
        }
    }
}

Select rows of a matrix that meet a condition

If the dataset is called data, then all the rows meeting a condition where value of column 'pm2.5' > 300 can be received by -

data[data['pm2.5'] >300,]

Could not resolve '...' from state ''

I've just had this same issue with Ionic.

It turns out nothing was wrong with my code, I simply had to quit the ionic serve session and run ionic serve again.

After going back into the app, my states worked fine.

I would also suggest pressing save on your app.js file a few times if you are running gulp, to make sure everything gets re-compiled.

How can I get relative path of the folders in my android project?

File relativeFile = new File(getClass().getResource("/icons/forIcon.png").toURI());
myJFrame.setIconImage(tk.getImage(relativeFile.getAbsolutePath()));

How to check if the request is an AJAX request with PHP

$headers = apache_request_headers();
$is_ajax = (isset($headers['X-Requested-With']) && $headers['X-Requested-With'] == 'XMLHttpRequest');

How to delete node from XML file using C#

It may be easier to use XPath to locate the nodes that you wish to delete. This stackoverflow thread might give you some ideas.

In your case you will find the four nodes that you want using this expression:

XmlDocument doc = new XmlDocument();
doc.Load(fileName);
XmlNodeList nodes = doc.SelectNodes("//Setting[@name='File1']");

Initialize array of strings

Its fine to just do char **strings;, char **strings = NULL, or char **strings = {NULL}

but to initialize it you'd have to use malloc:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(){
    // allocate space for 5 pointers to strings
    char **strings = (char**)malloc(5*sizeof(char*));
    int i = 0;
    //allocate space for each string
    // here allocate 50 bytes, which is more than enough for the strings
    for(i = 0; i < 5; i++){
        printf("%d\n", i);
        strings[i] = (char*)malloc(50*sizeof(char));
    }
    //assign them all something
    sprintf(strings[0], "bird goes tweet");
    sprintf(strings[1], "mouse goes squeak");
    sprintf(strings[2], "cow goes moo");
    sprintf(strings[3], "frog goes croak");
    sprintf(strings[4], "what does the fox say?");
    // Print it out
    for(i = 0; i < 5; i++){
        printf("Line #%d(length: %lu): %s\n", i, strlen(strings[i]),strings[i]);
    } 
    //Free each string
    for(i = 0; i < 5; i++){
        free(strings[i]);
    }
    //finally release the first string
    free(strings);
    return 0;
}

How to prevent http file caching in Apache httpd (MAMP)

Tried this? Should work in both .htaccess, httpd.conf and in a VirtualHost (usually placed in httpd-vhosts.conf if you have included it from your httpd.conf)

<filesMatch "\.(html|htm|js|css)$">
  FileETag None
  <ifModule mod_headers.c>
     Header unset ETag
     Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
     Header set Pragma "no-cache"
     Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
  </ifModule>
</filesMatch>

100% Prevent Files from being cached

This is similar to how google ads employ the header Cache-Control: private, x-gzip-ok="" > to prevent caching of ads by proxies and clients.

From http://www.askapache.com/htaccess/using-http-headers-with-htaccess.html

And optionally add the extension for the template files you are retrieving if you are using an extension other than .html for those.

How to set JAVA_HOME for multiple Tomcat instances?

Also, note that there shouldn't be any space after =:

set JAVA_HOME=C:\Program Files\Java\jdk1.6.0_27

websocket closing connection automatically

I found another, rather quick and dirty, solution. If you use the low level approach to implement the WebSocket and you Implement the onOpen method yourself you receive an object implementing the WebSocket.Connection interface. This object has a setMaxIdleTime method which you can adjust.

Eclipse: Frustration with Java 1.7 (unbound library)

Have you actually downloaded and installed one of the milestone builds from https://jdk7.dev.java.net/ ?

You can have a play with the features, though it's not stable so you shouldn't be releasing software against them.

How to host a Node.Js application in shared hosting

You should look for a hosting company that provides such feature, but standard simple static+PHP+MySQL hosting won't let you use node.js.

You need either find a hosting designed for node.js or buy a Virtual Private Server and install it yourself.

How to compare two maps by their values

Your attempts to construct different strings using concatenation will fail as it's being performed at compile-time. Both of those maps have a single pair; each pair will have "foo" and "barbar" as the key/value, both using the same string reference.

Assuming you really want to compare the sets of values without any reference to keys, it's just a case of:

Set<String> values1 = new HashSet<>(map1.values());
Set<String> values2 = new HashSet<>(map2.values());
boolean equal = values1.equals(values2);

It's possible that comparing map1.values() with map2.values() would work - but it's also possible that the order in which they're returned would be used in the equality comparison, which isn't what you want.

Note that using a set has its own problems - because the above code would deem a map of {"a":"0", "b":"0"} and {"c":"0"} to be equal... the value sets are equal, after all.

If you could provide a stricter definition of what you want, it'll be easier to make sure we give you the right answer.

Java: How to read a text file

All the answers so far given involve reading the file line by line, taking the line in as a String, and then processing the String.

There is no question that this is the easiest approach to understand, and if the file is fairly short (say, tens of thousands of lines), it'll also be acceptable in terms of efficiency. But if the file is long, it's a very inefficient way to do it, for two reasons:

  1. Every character gets processed twice, once in constructing the String, and once in processing it.
  2. The garbage collector will not be your friend if there are lots of lines in the file. You're constructing a new String for each line, and then throwing it away when you move to the next line. The garbage collector will eventually have to dispose of all these String objects that you don't want any more. Someone's got to clean up after you.

If you care about speed, you are much better off reading a block of data and then processing it byte by byte rather than line by line. Every time you come to the end of a number, you add it to the List you're building.

It will come out something like this:

private List<Integer> readIntegers(File file) throws IOException {
    List<Integer> result = new ArrayList<>();
    RandomAccessFile raf = new RandomAccessFile(file, "r");
    byte buf[] = new byte[16 * 1024];
    final FileChannel ch = raf.getChannel();
    int fileLength = (int) ch.size();
    final MappedByteBuffer mb = ch.map(FileChannel.MapMode.READ_ONLY, 0,
            fileLength);
    int acc = 0;
    while (mb.hasRemaining()) {
        int len = Math.min(mb.remaining(), buf.length);
        mb.get(buf, 0, len);
        for (int i = 0; i < len; i++)
            if ((buf[i] >= 48) && (buf[i] <= 57))
                acc = acc * 10 + buf[i] - 48;
            else {
                result.add(acc);
                acc = 0;
            }
    }
    ch.close();
    raf.close();
    return result;
}

The code above assumes that this is ASCII (though it could be easily tweaked for other encodings), and that anything that isn't a digit (in particular, a space or a newline) represents a boundary between digits. It also assumes that the file ends with a non-digit (in practice, that the last line ends with a newline), though, again, it could be tweaked to deal with the case where it doesn't.

It's much, much faster than any of the String-based approaches also given as answers to this question. There is a detailed investigation of a very similar issue in this question. You'll see there that there's the possibility of improving it still further if you want to go down the multi-threaded line.

Equivalent of LIMIT and OFFSET for SQL Server?

Another sample :

declare @limit int 
declare @offset int 
set @offset = 2;
set @limit = 20;
declare @count int
declare @idxini int 
declare @idxfim int 
select @idxfim = @offset * @limit
select @idxini = @idxfim - (@limit-1);
WITH paging AS
    (
        SELECT 
             ROW_NUMBER() OVER (order by object_id) AS rowid, *
        FROM 
            sys.objects 
    )
select *
    from 
        (select COUNT(1) as rowqtd from paging) qtd, 
            paging 
    where 
        rowid between @idxini and @idxfim
    order by 
        rowid;

How to install CocoaPods?

cocoa pod installation step :

Open Your Terminal :

sudo gem update --system

sudo gem install activesupport -v 4.2.6

sudo gem install cocoapods

pod setup

pod setup --verbose

Then Go To Your Project Directory with Terminal

cd Your Project Path

Then Enter below command in Terminal

pod init

open -a Xcode Podfile

[Edit POD file with pod ‘libname’ ]

pod install

Spring Rest POST Json RequestBody Content type not supported

I found solution. It's was because I had 2 setter with same name but different type.

My class had id property int that I replaced with Integer when à Hibernitify my object.

But apparently, I forgot to remove setters and I had :

/**
 * @param id
 *            the id to set
 */
public void setId(int id) {
    this.id = id;
}

/**
 * @param id
 *            the id to set
 */
public void setId(Integer id) {
    this.id = id;
}

When I removed this setter, rest resquest work very well.

Intead to throw unmarshalling error or reflect class error. Exception HttpMediaTypeNotSupportedException seams really strange here.

I hope this stackoverflow could be help someone else.

SIDE NOTE

You can check your Spring server console for the following error message:

Failed to evaluate Jackson deserialization for type [simple type, class your.package.ClassName]: com.fasterxml.jackson.databind.JsonMappingException: Conflicting setter definitions for property "propertyname"

Then you can be sure you are dealing with the issue mentioned above.

How do I split a string with multiple separators in JavaScript?

Pass in a regexp as the parameter:

js> "Hello awesome, world!".split(/[\s,]+/)
Hello,awesome,world!

Edited to add:

You can get the last element by selecting the length of the array minus 1:

>>> bits = "Hello awesome, world!".split(/[\s,]+/)
["Hello", "awesome", "world!"]
>>> bit = bits[bits.length - 1]
"world!"

... and if the pattern doesn't match:

>>> bits = "Hello awesome, world!".split(/foo/)
["Hello awesome, world!"]
>>> bits[bits.length - 1]
"Hello awesome, world!"

Force IE10 to run in IE10 Compatibility View?

You should try the IE 5 quirks compatibility mod (is the default IE10 compatibility view)

<meta http-equiv="X-UA-Compatible" content="IE=5">

important: set in the top of your iframe structure (if you use iframe structure)

more info 1, 2

When to use std::size_t?

Use std::size_t for indexing/counting C-style arrays.

For STL containers, you'll have (for example) vector<int>::size_type, which should be used for indexing and counting vector elements.

In practice, they are usually both unsigned ints, but it isn't guaranteed, especially when using custom allocators.

Custom method names in ASP.NET Web API

I am days into the MVC4 world.

For what its worth, I have a SitesAPIController, and I needed a custom method, that could be called like:

http://localhost:9000/api/SitesAPI/Disposition/0

With different values for the last parameter to get record with different dispositions.

What Finally worked for me was:

The method in the SitesAPIController:

// GET api/SitesAPI/Disposition/1
[ActionName("Disposition")]
[HttpGet]
public Site Disposition(int disposition)
{
    Site site = db.Sites.Where(s => s.Disposition == disposition).First();
    return site;
}

And this in the WebApiConfig.cs

// this was already there
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

// this i added
config.Routes.MapHttpRoute(
    name: "Action",
    routeTemplate: "api/{controller}/{action}/{disposition}"
 );

For as long as I was naming the {disposition} as {id} i was encountering:

{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:9000/api/SitesAPI/Disposition/0'.",
"MessageDetail": "No action was found on the controller 'SitesAPI' that matches the request."
}

When I renamed it to {disposition} it started working. So apparently the parameter name is matched with the value in the placeholder.

Feel free to edit this answer to make it more accurate/explanatory.

Install windows service without InstallUtil.exe

The InstallUtil.exe tool is simply a wrapper around some reflection calls against the installer component(s) in your service. As such, it really doesn't do much but exercise the functionality these installer components provide. Marc Gravell's solution simply provides a means to do this from the command line so that you no longer have to rely on having InstallUtil.exe on the target machine.

Here's my step-by-step that based on Marc Gravell's solution.

How to make a .NET Windows Service start right after the installation?

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

To augment PYTHONPATH, run regedit and navigate to KEY_LOCAL_MACHINE \SOFTWARE\Python\PythonCore and then select the folder for the python version you wish to use. Inside this is a folder labelled PythonPath, with one entry that specifies the paths where the default install stores modules. Right-click on PythonPath and choose to create a new key. You may want to name the key after the project whose module locations it will specify; this way, you can easily compartmentalize and track your path modifications.

thanks

$rootScope.$broadcast vs. $scope.$emit

They are not doing the same job: $emit dispatches an event upwards through the scope hierarchy, while $broadcast dispatches an event downwards to all child scopes.

How to add a tooltip to an svg graphic?

I always go with the generic css title with my setup. I'm just building analytics for my blog admin page. I don't need anything fancy. Here's some code...

let comps = g.selectAll('.myClass')
   .data(data)
   .enter()
   .append('rect')
   ...styling...
   ...transitions...
   ...whatever...

g.selectAll('.myClass')
   .append('svg:title')
   .text((d, i) => d.name + '-' + i);

And a screenshot of chrome...

enter image description here

Beautiful Soup and extracting a div and its contents by ID

from bs4 import BeautifulSoup
from requests_html import HTMLSession

url = 'your_url'
session = HTMLSession()
resp = session.get(url)

# if element with id "articlebody" is dynamic, else need not to render
resp.html.render()

soup = bs(resp.html.html, "lxml")
soup.find("div", {"id": "articlebody"})

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

See example here: Input and Output binary streams using JERSEY?

Pseudo code would be something like this (there are a few other similar options in above mentioned post):

@Path("file/")
@GET
@Produces({"application/pdf"})
public StreamingOutput getFileContent() throws Exception {
     public void write(OutputStream output) throws IOException, WebApplicationException {
        try {
          //
          // 1. Get Stream to file from first server
          //
          while(<read stream from first server>) {
              output.write(<bytes read from first server>)
          }
        } catch (Exception e) {
            throw new WebApplicationException(e);
        } finally {
              // close input stream
        }
    }
}

How to update Identity Column in SQL Server?

You need to

set identity_insert YourTable ON

Then delete your row and reinsert it with different identity.

Once you have done the insert don't forget to turn identity_insert off

set identity_insert YourTable OFF

How to output JavaScript with PHP

You need to escape the double quotes like this:

echo "<script type=\"text/javascript\">";
echo "document.write(\"Hello World!\")";
echo "</script>";

or use single quotes inside the double quotes instead, like this:

echo "<script type='text/javascript'>";
echo "document.write('Hello World!')";
echo "</script>";

or the other way around, like this:

echo '<script type="text/javascript">';
echo 'document.write("Hello World!")';
echo '</script>';

Also, checkout the PHP Manual for more info on Strings.

Also, why would you want to print JavaScript using PHP? I feel like there's something wrong with your design.

How to get values from selected row in DataGrid for Windows Form Application?

You could just use

DataGridView1.CurrentRow.Cells["ColumnName"].Value

Binary Data in JSON String. Something better than Base64

I dig a little bit more (during implementation of base128), and expose that when we send characters which ascii codes are bigger than 128 then browser (chrome) in fact send TWO characters (bytes) instead one :(. The reason is that JSON by defaul use utf8 characters for which characters with ascii codes above 127 are coded by two bytes what was mention by chmike answer. I made test in this way: type in chrome url bar chrome://net-export/ , select "Include raw bytes", start capturing, send POST requests (using snippet at the bottom), stop capturing and save json file with raw requests data. Then we look inside that json file:

  • We can find our base64 request by finding string 4142434445464748494a4b4c4d4e this is hex coding of ABCDEFGHIJKLMN and we will see that "byte_count": 639 for it.
  • We can find our above127 request by finding string C2BCC2BDC380C381C382C383C384C385C386C387C388C389C38AC38B this are request-hex utf8 codes of characters ¼½ÀÁÂÃÄÅÆÇÈÉÊË (however the ascii hex codes of this characters are c1c2c3c4c5c6c7c8c9cacbcccdce). The "byte_count": 703 so it is 64bytes longer than base64 request because characters with ascii codes above 127 are code by 2 bytes in request :(

So in fact we don't have profit with sending characters with codes >127 :( . For base64 strings we not observe such negative behaviour (probably for base85 too - I don check it) - however may be some solution for this problem will be sending data in binary part of POST multipart/form-data described in Ælex answer (however usually in this case we don't need to use any base coding at all...).

The alternative approach may rely on mapping two bytes data portion into one valid utf8 character by code it using something like base65280 / base65k but probably it would be less effective than base64 due to utf8 specification ...

_x000D_
_x000D_
function postBase64() {_x000D_
  let formData = new FormData();_x000D_
  let req = new XMLHttpRequest();_x000D_
_x000D_
  formData.append("base64ch", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");_x000D_
  req.open("POST", '/testBase64ch');_x000D_
  req.send(formData);_x000D_
}_x000D_
_x000D_
_x000D_
function postAbove127() {_x000D_
  let formData = new FormData();_x000D_
  let req = new XMLHttpRequest();_x000D_
_x000D_
  formData.append("above127", "¼½ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüý");_x000D_
  req.open("POST", '/testAbove127');_x000D_
  req.send(formData);_x000D_
}
_x000D_
<button onclick=postBase64()>POST base64 chars</button>_x000D_
<button onclick=postAbove127()>POST chars with codes>127</button>
_x000D_
_x000D_
_x000D_

PHP mPDF save file as PDF

The Go trough this link state that the first argument of Output() is the file path, second is the saving mode - you need to set it to 'F'.

 $upload_dir = public_path(); 
             $filename = $upload_dir.'/testing7.pdf'; 
              $mpdf = new \Mpdf\Mpdf();
              //$test = $mpdf->Image($pro_image, 0, 0, 50, 50);

              $html ='<h1> Project Heading </h1>';
              $mail = ' <p> Project Heading </p> ';
              
              $mpdf->autoScriptToLang = true;
              $mpdf->autoLangToFont = true;
              $mpdf->WriteHTML($mail);

              $mpdf->Output($filename,'F'); 
              $mpdf->debug = true;

Example :

 $mpdf->Output($filename,'F');

Example #2

$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML('Hello World');

// Saves file on the server as 'filename.pdf'
$mpdf->Output('filename.pdf', \Mpdf\Output\Destination::FILE);

Distinct() with lambda?

All solutions I've seen here rely on selecting an already comparable field. If one needs to compare in a different way, though, this solution here seems to work generally, for something like:

somedoubles.Distinct(new LambdaComparer<double>((x, y) => Math.Abs(x - y) < double.Epsilon)).Count()

How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

JavaScript Solution

/**
 * Calculate the column letter abbreviation from a 1 based index
 * @param {Number} value
 * @returns {string}
 */
getColumnFromIndex = function (value) {
    var base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
    var remainder, result = "";
    do {
        remainder = value % 26;
        result = base[(remainder || 26) - 1] + result;
        value = Math.floor(value / 26);
    } while (value > 0);
    return result;
};

MySql Inner Join with WHERE clause

Yes you are right. You have placed WHERE clause wrong. You can only use one WHERE clause in single query so try AND for multiple conditions like this:

 SELECT table1.f_id  FROM table1 
   INNER JOIN table2
     ON table2.f_id = table1.f_id
 WHERE table2.f_type = 'InProcess'
   AND f_com_id = '430'
   AND f_status = 'Submitted' 

How do you concatenate Lists in C#?

Concat returns a new sequence without modifying the original list. Try myList1.AddRange(myList2).

estimating of testing effort as a percentage of development time

Testing time is probably more closely correlated to feature scope than development time. I'd also argue (perhaps controversially) that testing time is correlated to the skill of your development team.

For a 6-to-9 month development effort, I demand a absolute minimum of 2 weeks testing time, performed by actual testers (not the development team) who are well-versed in the software they will be testing (i.e., 2 weeks does not include ramp-up time). This is for a project that has ~5 developers.

Rounding numbers to 2 digits after comma

EDIT 2:

Use the Number object's toFixed method like this:

var num = Number(0.005) // The Number() only visualizes the type and is not needed
var roundedString = num.toFixed(2);
var rounded = Number(roundedString); // toFixed() returns a string (often suitable for printing already)

It rounds 42.0054321 to 42.01

It rounds 0.005 to 0.01

It rounds -0.005 to -0.01 (So the absolute value increases on rounding at .5 border)

jsFiddle example

R numbers from 1 to 100

If you need the construct for a quick example to play with, use the : operator.

But if you are creating a vector/range of numbers dynamically, then use seq() instead.

Let's say you are creating the vector/range of numbers from a to b with a:b, and you expect it to be an increasing series. Then, if b is evaluated to be less than a, you will get a decreasing sequence but you will never be notified about it, and your program will continue to execute with the wrong kind of input.

In this case, if you use seq(), you can set the sign of the by argument to match the direction of your sequence, and an error will be raised if they do not match. For example,

seq(a, b, -1)

will raise an error for a=2, b=6, because the coder expected a decreasing sequence.

An explicit value for the identity column in table can only be specified when a column list is used and IDENTITY_INSERT is ON SQL Server

This code snippet shows how to insert into table when identity Primary Key column is ON.

SET IDENTITY_INSERT [dbo].[Roles] ON
GO
insert into Roles (Id,Name) values(1,'Admin')
GO
insert into Roles (Id,Name) values(2,'User')
GO
SET IDENTITY_INSERT [dbo].[Roles] OFF
GO

Test a string for a substring

There are several other ways, besides using the in operator (easiest):

index()

>>> try:
...   "xxxxABCDyyyy".index("test")
... except ValueError:
...   print "not found"
... else:
...   print "found"
...
not found

find()

>>> if "xxxxABCDyyyy".find("ABCD") != -1:
...   print "found"
...
found

re

>>> import re
>>> if re.search("ABCD" , "xxxxABCDyyyy"):
...  print "found"
...
found

pip issue installing almost any library

tried

pip --trusted-host pypi.python.org --trusted-host files.pythonhosted.org --trusted-host pypi.org install xxx 

and finally worked out, not quite understand why the domain pypi.python.org is changed.

Jquery select change not firing

Try this

$('body').on('change', '#multiid', function() {
    // your stuff
})

please check .on() selector

Add new row to excel Table (VBA)

I had the same error message and after lots of trial and error found out that it was caused by an advanced filter which was set on the ListObject. After clearing the advanced filter .listrows.add worked fine again. To clear the filter I use this - no idea how one could clear the filter only for the specific listobject instead of the complete worksheet.

Worksheets("mysheet").ShowAllData

How to use GNU Make on Windows?

Here's how I got it to work:

  copy c:\MinGW\bin\mingw32-make.exe c:\MinGW\bin\make.exe

Then I am able to open a command prompt and type make:

  C:\Users\Dell>make
  make: *** No targets specified and no makefile found.  Stop.

Which means it's working now!

What is a good game engine that uses Lua?

Game engines that use Lua

Free unless noted

  • Agen (2D Lua; Windows)
  • Amulet (2D Lua; Window, Linux, Mac, HTML5, iOS)
  • Cafu 3D (3D C++/Lua)
  • Cocos2d-x (2D C++/Lua/JS; Windows, Linux, Mac, iOS, Android, BlackBerry)
  • Codea (2D&3D Lua; iOS (Editor is iOs app); $14.99 USD)
  • Cryengine by Crytek (3D C++/Lua; Windows, Mac)
  • Defold (2D Lua; Windows, Linux, Mac, iOS, Android, Web, Switch)
  • gengine (2D Lua; Windows, Linux, HTML5)
  • Irrlicht (3D C++/.NET/Lua; Windows, Linux, Mac)
  • Leadwerks (3D C++/C#/Delphi/BlitzMax/Lua; Windows; $199.95 USD)
  • LÖVE (2D Lua; Windows, Linux, Mac)
  • MOAI (2D C++/Lua; Windows, Linux, Mac, iOS, Android, Google Chrome (Native Client))
  • Solar2D (was Corona) (2D Lua; Windows, Mac, iOS, Android)
  • Spring RTS Engine (3D C++/Lua; Linux, Windows, Mac)
  • Wicked Engine (3D C++/Lua; Linux, Windows 10, Windows Phone, XBox One)

Bindings:

  • Raylib via raylib-lua-sol (2D&3D C++/Lua/Others; Windows, Linux, Mac, Android, Web, Other Ports)
  • SDL2 via luasdl2 (2D&3D C++/Lua/Others; Windows, Linux, Mac, Android, Console Ports)

Fantasy Consoles:

Editor and games run in an emulated computer system

  • PICO-8 (2D Lua; Windows, Linux, Mac, Raspberry Pi, Web Player $14.99 USD)
  • TIC-80 (2D Lua; Windows, Linux, Mac, Web)

Inactive/Discontinued:

  • Baja Engine (3D C++/Lua; Windows, Mac, No Release since Dec 2008)
  • Blitwizard (2D Lua; Windows, Linux, Mac, Development stopped in May 2014)
  • Drystal (2D Lua; Linux, HTML5)
  • EGSL (2D Pascal/Lua; Windows, Linux, Mac, Haiku)
  • Glint 3d Engine (3D Lua, Development stopped in Nov 2011)
  • Grail Adventure Game Engine (2D C++/Lua; Windows, Linux, Mac (SDL))
  • Juno (2D Lua; Windows, Linux, Mac, last commit on Friday the 13th, May 2016)
  • Lavgine (2.5D C++/Lua, Windows)
  • Luxinia (3D C/Lua; Windows, Development stopped in Dec 2018)
  • Polycode (2D&3D C++/Lua; Windows, Linux, Mac)

Correct redirect URI for Google API and OAuth 2.0

There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.

You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.

When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.

Difference between binary tree and binary search tree

Binary tree

Binary tree can be anything which has 2 child and 1 parent. It can be implemented as linked list or array, or with your custom API. Once you start to add more specific rules into it, it becomes more specialized tree. Most common known implementation is that, add smaller nodes on left and larger ones on right.

For example, a labeled binary tree of size 9 and height 3, with a root node whose value is 2. Tree is unbalanced and not sorted. https://en.wikipedia.org/wiki/Binary_tree

enter image description here

For example, in the tree on the left, A has the 6 children {B,C,D,E,F,G}. It can be converted into the binary tree on the right.

enter image description here

Binary Search

Binary Search is technique/algorithm which is used to find specific item on node chain. Binary search works on sorted arrays.

Binary search compares the target value to the middle element of the array; if they are unequal, the half in which the target cannot lie is eliminated and the search continues on the remaining half until it is successful or the remaining half is empty. https://en.wikipedia.org/wiki/Binary_search_algorithm

enter image description here

A tree representing binary search. The array being searched here is [20, 30, 40, 50, 90, 100], and the target value is 40.

enter image description here

Binary search tree

This is one of the implementations of binary tree. This is specialized for searching.

Binary search tree and B-tree data structures are based on binary search.

Binary search trees (BST), sometimes called ordered or sorted binary trees, are a particular type of container: data structures that store "items" (such as numbers, names etc.) in memory. https://en.wikipedia.org/wiki/Binary_search_tree

A binary search tree of size 9 and depth 3, with 8 at the root. The leaves are not drawn.

enter image description here

And finally great schema for performance comparison of well-known data-structures and algorithms applied:

enter image description here

Image taken from Algorithms (4th Edition)

How to manage exceptions thrown in filters in Spring?

If you want a generic way, you can define an error page in web.xml:

<error-page>
  <exception-type>java.lang.Throwable</exception-type>
  <location>/500</location>
</error-page>

And add mapping in Spring MVC:

@Controller
public class ErrorController {

    @RequestMapping(value="/500")
    public @ResponseBody String handleException(HttpServletRequest req) {
        // you can get the exception thrown
        Throwable t = (Throwable)req.getAttribute("javax.servlet.error.exception");

        // customize response to what you want
        return "Internal server error.";
    }
}

How to add label in chart.js for pie chart

It is not necessary to use another library like newChart or use other people's pull requests to pull this off. All you have to do is define an options object and add the label wherever and however you want it in the tooltip.

var optionsPie = {
    tooltipTemplate: "<%= label %> - <%= value %>"
}

If you want the tooltip to be always shown you can make some other edits to the options:

 var optionsPie = {
        tooltipEvents: [],
        showTooltips: true,
        onAnimationComplete: function() {
            this.showTooltip(this.segments, true);
        },
        tooltipTemplate: "<%= label %> - <%= value %>"
    }

In your data items, you have to add the desired label property and value and that's all.

data = [
    {
        value: 480000,
        color:"#F7464A",
        highlight: "#FF5A5E",
        label: "Tobacco"
    }
];

Now, all you have to do is pass the options object after the data to the new Pie like this: new Chart(ctx).Pie(data,optionsPie) and you are done.

This probably works best for pies which are not very small in size.

Pie chart with labels

Test if characters are in a string

Also, can be done using "stringr" library:

> library(stringr)
> chars <- "test"
> value <- "es"
> str_detect(chars, value)
[1] TRUE

### For multiple value case:
> value <- c("es", "l", "est", "a", "test")
> str_detect(chars, value)
[1]  TRUE FALSE  TRUE FALSE  TRUE

xcode library not found

You need to set the "linker search paths" of the project (for both Debug and Release builds). If this library was in, say, a sibling directory to the project then you can set it like this:

$(PROJECT_DIR)/../GoogleAnalytics/lib

(you want to avoid using an absolute path, instead keep the library directory relative to the project).

VB6 IDE cannot load MSCOMCTL.OCX after update KB 2687323

I continued to have problems after trying the things suggested here. In the end, it turned out that I had the wrong version of mscomctl.ocx in my SysWOW64 folder. I found the following versions kicking around:

Mar. 09, 2004  01:00 AM   1,081,616  mscomctl.ocx
Jun. 06, 2012  07:59 PM   1,070,152  mscomctl.ocx
Dec. 08, 2015  03:57 AM   1,070,232  MSCOMCTL.OCX

Getting the last one (1,070,232) solved this problem for me.

Put spacing between divs in a horizontal row?

You can set left margins for li tags in percents and set the same negative left margin on parent:

_x000D_
_x000D_
ul {margin-left:-5%;}_x000D_
li {width:20%;margin-left:5%;float:left;}
_x000D_
<ul>_x000D_
  <li>A_x000D_
  <li>B_x000D_
  <li>C_x000D_
  <li>D_x000D_
</ul>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/UZHbS/

Sys is undefined

I was using telerik and had exactly same problem.

adding this to web.config resolved my issue :)

<location path="Telerik.Web.UI.WebResource.axd">   
   <system.web>  
     <authorization>  
       <allow users="*"/>  
     </authorization>  
   </system.web>  
</location>

maybe it will help you too. it was Authentication problem.

Source

Code snippet or shortcut to create a constructor in Visual Studio

If you want to see the list of all available snippets:

Press Ctrl + K and then X.

Linux Shell Script For Each File in a Directory Grab the filename and execute a program

bash:

for f in *.xls ; do xls2csv "$f" "${f%.xls}.csv" ; done

What is the fastest way to create a checksum for large files in C#

You can have a look to XxHash.Net ( https://github.com/wilhelmliao/xxHash.NET )
The xxHash algorythm seems to be faster than all other.
Some benchmark on the xxHash site : https://github.com/Cyan4973/xxHash

PS: I've not yet used it.

PostgreSQL database default location on Linux

/var/lib/postgresql/[version]/data/

At least in Gentoo Linux and Ubuntu 14.04 by default.

You can find postgresql.conf and look at param data_directory. If it is commented then database directory is the same as this config file directory.

Post order traversal of binary tree without recursion

import java.util.Stack;

public class IterativePostOrderTraversal extends BinaryTree {

    public static void iterativePostOrderTraversal(Node root){
        Node cur = root;
        Node pre = root;
        Stack<Node> s = new Stack<Node>();
        if(root!=null)
            s.push(root);
        System.out.println("sysout"+s.isEmpty());
        while(!s.isEmpty()){
            cur = s.peek();
            if(cur==pre||cur==pre.left ||cur==pre.right){// we are traversing down the tree
                if(cur.left!=null){
                    s.push(cur.left);
                }
                else if(cur.right!=null){
                    s.push(cur.right);
                }
                if(cur.left==null && cur.right==null){
                    System.out.println(s.pop().data);
                }
            }else if(pre==cur.left){// we are traversing up the tree from the left
                if(cur.right!=null){
                    s.push(cur.right);
                }else if(cur.right==null){
                    System.out.println(s.pop().data);
                }
            }else if(pre==cur.right){// we are traversing up the tree from the right
                System.out.println(s.pop().data);
            }
            pre=cur;
        }
    }

    public static void main(String args[]){
        BinaryTree bt = new BinaryTree();
        Node root = bt.generateTree();
        iterativePostOrderTraversal(root);
    }


}

How to post a file from a form with Axios

How to post file using an object in memory (like a JSON object):

import axios from 'axios';
import * as FormData  from 'form-data'

async function sendData(jsonData){
    // const payload = JSON.stringify({ hello: 'world'});
    const payload = JSON.stringify(jsonData);
    const bufferObject = Buffer.from(payload, 'utf-8');
    const file = new FormData();

    file.append('upload_file', bufferObject, "b.json");

    const response = await axios.post(
        lovelyURL,
        file,
        headers: file.getHeaders()
    ).toPromise();


    console.log(response?.data);
}

How do I resolve ClassNotFoundException?

I just did

1.Invalidate caches and restart

2.Rebuilt my project which solved the problem

Search and replace a particular string in a file using Perl

A one liner:

perl -pi.back -e 's/<PREF>/ABCD/g;' inputfile

How to check cordova android version of a cordova/phonegap project?

Run

cordova -v 

to see the currently running version. Run the npm info command

npm info cordova

for a longer listing that includes the current version along with other available version numbers

Convert Year/Month/Day to Day of Year in Python

DZinX's answer is a great answer for the question. I found this question and used DZinX's answer while looking for the inverse function: convert dates with the julian day-of-year into the datetimes.

I found this to work:

import datetime
datetime.datetime.strptime('1936-077T13:14:15','%Y-%jT%H:%M:%S')

>>>> datetime.datetime(1936, 3, 17, 13, 14, 15)

datetime.datetime.strptime('1936-077T13:14:15','%Y-%jT%H:%M:%S').timetuple().tm_yday

>>>> 77

Or numerically:

import datetime
year,julian = [1936,77]
datetime.datetime(year, 1, 1)+datetime.timedelta(days=julian -1)

>>>> datetime.datetime(1936, 3, 17, 0, 0)

Or with fractional 1-based jdates popular in some domains:

jdate_frac = (datetime.datetime(1936, 3, 17, 13, 14, 15)-datetime.datetime(1936, 1, 1)).total_seconds()/86400+1
display(jdate_frac)

>>>> 77.5515625

year,julian = [1936,jdate_frac]
display(datetime.datetime(year, 1, 1)+datetime.timedelta(days=julian -1))

>>>> datetime.datetime(1936, 3, 17, 13, 14, 15)

I'm not sure of etiquette around here, but I thought a pointer to the inverse functionality might be useful for others like me.

Variables not showing while debugging in Eclipse

My problem was that I couldn't see variables names, but just the value. After trying quite a while I got the solution: Click on the down arrow (in degub Variables tab) --> Layout --> show columns

It did the trick!

NGinx Default public www location?

Run the command nginx -V and look for the --prefix. Use that entry to locate your default paths.

How do I update a Mongo document after inserting it?

mycollection.find_one_and_update({"_id": mongo_id}, 
                                 {"$set": {"newfield": "abc"}})

should work splendidly for you. If there is no document of id mongo_id, it will fail, unless you also use upsert=True. This returns the old document by default. To get the new one, pass return_document=ReturnDocument.AFTER. All parameters are described in the API.

The method was introduced for MongoDB 3.0. It was extended for 3.2, 3.4, and 3.6.

Simple UDP example to send and receive data from same socket

(I presume you are aware that using UDP(User Datagram Protocol) does not guarantee delivery, checks for duplicates and congestion control and will just answer your question).

In your server this line:

var data = udpServer.Receive(ref groupEP);

re-assigns groupEP from what you had to a the address you receive something on.

This line:

udpServer.Send(new byte[] { 1 }, 1); 

Will not work since you have not specified who to send the data to. (It works on your client because you called connect which means send will always be sent to the end point you connected to, of course we don't want that on the server as we could have many clients). I would:

UdpClient udpServer = new UdpClient(UDP_LISTEN_PORT);

while (true)
{
    var remoteEP = new IPEndPoint(IPAddress.Any, 11000);
    var data = udpServer.Receive(ref remoteEP);
    udpServer.Send(new byte[] { 1 }, 1, remoteEP); // if data is received reply letting the client know that we got his data          
}

Also if you have server and client on the same machine you should have them on different ports.

Replace characters from a column of a data frame R

You can use the stringr library:

library('stringr')

a <- runif(10)
b <- letters[1:10]
c <- c(rep('A-B', 4), rep('A_B', 6))
data <- data.frame(a, b, c)

data

#             a b   c
# 1  0.19426707 a A-B
# 2  0.12902673 b A-B
# 3  0.78324955 c A-B
# 4  0.06469028 d A-B
# 5  0.34752264 e A_C
# 6  0.55313288 f A_C
# 7  0.31264280 g A_C
# 8  0.33759921 h A_C
# 9  0.72322599 i A_C
# 10 0.25223075 j A_C

data$c <- str_replace_all(data$c, '_', '-')

data

#             a b   c
# 1  0.19426707 a A-B
# 2  0.12902673 b A-B
# 3  0.78324955 c A-B
# 4  0.06469028 d A-B
# 5  0.34752264 e A-C
# 6  0.55313288 f A-C
# 7  0.31264280 g A-C
# 8  0.33759921 h A-C
# 9  0.72322599 i A-C
# 10 0.25223075 j A-C

Note that this does change factored variables into character.

Use a loop to plot n charts Python

Ok, so the easiest method to create several plots is this:

import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
for i in range(len(x)):
    plt.figure()
    plt.plot(x[i],y[i])
    # Show/save figure as desired.
    plt.show()
# Can show all four figures at once by calling plt.show() here, outside the loop.
#plt.show()

Note that you need to create a figure every time or pyplot will plot in the first one created.

If you want to create several data series all you need to do is:

import matplotlib.pyplot as plt
plt.figure()
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]
plt.plot(x[0],y[0],'r',x[1],y[1],'g',x[2],y[2],'b',x[3],y[3],'k')

You could automate it by having a list of colours like ['r','g','b','k'] and then just calling both entries in this list and corresponding data to be plotted in a loop if you wanted to. If you just want to programmatically add data series to one plot something like this will do it (no new figure is created each time so everything is plotted in the same figure):

import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]
colours=['r','g','b','k']
plt.figure() # In this example, all the plots will be in one figure.    
for i in range(len(x)):
    plt.plot(x[i],y[i],colours[i])
plt.show()

Hope this helps. If anything matplotlib has a very good documentation page with plenty of examples.

17 Dec 2019: added plt.show() and plt.figure() calls to clarify this part of the story.

Difference between map and collect in Ruby?

I've been told they are the same.

Actually they are documented in the same place under ruby-doc.org:

http://www.ruby-doc.org/core/classes/Array.html#M000249

  • ary.collect {|item| block } ? new_ary
  • ary.map {|item| block } ? new_ary
  • ary.collect ? an_enumerator
  • ary.map ? an_enumerator

Invokes block once for each element of self. Creates a new array containing the values returned by the block. See also Enumerable#collect.
If no block is given, an enumerator is returned instead.

a = [ "a", "b", "c", "d" ]
a.collect {|x| x + "!" }   #=> ["a!", "b!", "c!", "d!"]
a                          #=> ["a", "b", "c", "d"]

A project with an Output Type of Class Library cannot be started directly

If you convert the WPF application to Class library for get the projects .dll file.After that convert the same project to the WPF application you get the following error.

Error:".exe does not contain a static main method suitable for an entry point".

Steps to troubleshoot: 1.Include the App.xaml file in the respective project. 2.Right Click on App.xaml file change the build action to Application Definition 3.Now Build your project

if A vs if A is not None:

I created a file called test.py and ran it on the interpreter. You may change what you want to, to test for sure how things is going on behind the scenes.

import dis

def func1():

    matchesIterator = None

    if matchesIterator:

        print( "On if." );

def func2():

    matchesIterator = None

    if matchesIterator is not None:

        print( "On if." );

print( "\nFunction 1" );
dis.dis(func1)

print( "\nFunction 2" );
dis.dis(func2)

This is the assembler difference:

Source:

>>> import importlib
>>> reload( test )

Function 1
  6           0 LOAD_CONST               0 (None)
              3 STORE_FAST               0 (matchesIterator)

  8           6 LOAD_FAST                0 (matchesIterator)
              9 POP_JUMP_IF_FALSE       20

 10          12 LOAD_CONST               1 ('On if.')
             15 PRINT_ITEM
             16 PRINT_NEWLINE
             17 JUMP_FORWARD             0 (to 20)
        >>   20 LOAD_CONST               0 (None)
             23 RETURN_VALUE

Function 2
 14           0 LOAD_CONST               0 (None)
              3 STORE_FAST               0 (matchesIterator)

 16           6 LOAD_FAST                0 (matchesIterator)
              9 LOAD_CONST               0 (None)
             12 COMPARE_OP               9 (is not)
             15 POP_JUMP_IF_FALSE       26

 18          18 LOAD_CONST               1 ('On if.')
             21 PRINT_ITEM
             22 PRINT_NEWLINE
             23 JUMP_FORWARD             0 (to 26)
        >>   26 LOAD_CONST               0 (None)
             29 RETURN_VALUE
<module 'test' from 'test.py'>

How to drop a unique constraint from table column?

Expand to database name >> expand to table >> expand to keys >> copy the name of key then execute the below command:

ALTER TABLE Test DROP UQ__test__3213E83EB607700F;

Here UQ__test__3213E83EB607700F is the name of unique key which was created on a particular column on test table.

What does this expression language ${pageContext.request.contextPath} exactly do in JSP EL?

Include <%@ page isELIgnored="false"%> on top of your jsp page.

How do you add a JToken to an JObject?

I think you're getting confused about what can hold what in JSON.Net.

  • A JToken is a generic representation of a JSON value of any kind. It could be a string, object, array, property, etc.
  • A JProperty is a single JToken value paired with a name. It can only be added to a JObject, and its value cannot be another JProperty.
  • A JObject is a collection of JProperties. It cannot hold any other kind of JToken directly.

In your code, you are attempting to add a JObject (the one containing the "banana" data) to a JProperty ("orange") which already has a value (a JObject containing {"colour":"orange","size":"large"}). As you saw, this will result in an error.

What you really want to do is add a JProperty called "banana" to the JObject which contains the other fruit JProperties. Here is the revised code:

JObject foodJsonObj = JObject.Parse(jsonText);
JObject fruits = foodJsonObj["food"]["fruit"] as JObject;
fruits.Add("banana", JObject.Parse(@"{""colour"":""yellow"",""size"":""medium""}"));

Spring-Boot: How do I set JDBC pool properties like maximum number of connections?

It turns out setting these configuration properties is pretty straight forward, but the official documentation is more general so it might be hard to find when searching specifically for connection pool configuration information.

To set the maximum pool size for tomcat-jdbc, set this property in your .properties or .yml file:

spring.datasource.maxActive=5

You can also use the following if you prefer:

spring.datasource.max-active=5

You can set any connection pool property you want this way. Here is a complete list of properties supported by tomcat-jdbc.

To understand how this works more generally you need to dig into the Spring-Boot code a bit.

Spring-Boot constructs the DataSource like this (see here, line 102):

@ConfigurationProperties(prefix = DataSourceAutoConfiguration.CONFIGURATION_PREFIX)
@Bean
public DataSource dataSource() {
    DataSourceBuilder factory = DataSourceBuilder
            .create(this.properties.getClassLoader())
            .driverClassName(this.properties.getDriverClassName())
            .url(this.properties.getUrl())
            .username(this.properties.getUsername())
            .password(this.properties.getPassword());
    return factory.build();
}

The DataSourceBuilder is responsible for figuring out which pooling library to use, by checking for each of a series of know classes on the classpath. It then constructs the DataSource and returns it to the dataSource() function.

At this point, magic kicks in using @ConfigurationProperties. This annotation tells Spring to look for properties with prefix CONFIGURATION_PREFIX (which is spring.datasource). For each property that starts with that prefix, Spring will try to call the setter on the DataSource with that property.

The Tomcat DataSource is an extension of DataSourceProxy, which has the method setMaxActive().

And that's how your spring.datasource.maxActive=5 gets applied correctly!

What about other connection pools

I haven't tried, but if you are using one of the other Spring-Boot supported connection pools (currently HikariCP or Commons DBCP) you should be able to set the properties the same way, but you'll need to look at the project documentation to know what is available.

resize font to fit in a div (on one line)

There is a jquery plugin available on github that probably just do what you want. It is called jquery-quickfit. It uses Jquery to provide a quick and dirty approach to fitting text into its surrounding container.

HTML:

<div id="quickfit">Text to fit*</div>

Javascript:

<script src=".../jquery.min.js" type="text/javascript" />
<script src="../script/jquery.quickfit.js" type="text/javascript" />

<script type="text/javascript">
  $(function() {
    $('#quickfit').quickfit();
  });
</script>

More information: https://github.com/chunksnbits/jquery-quickfit

Is it possible to sort a ES6 map object?

Short answer

 new Map([...map].sort((a, b) => 
   // Some sort function comparing keys with a[0] b[0] or values with a[1] b[1]
 ))

If you're expecting strings: As normal for .sort you need to return -1 if lower and 0 if equal; for strings, the recommended way is using .localeCompare() which does this correctly and automatically handles awkward characters like ä where the position varies by user locale.

So here's how to sort a map by string keys:

 new Map([...map].sort((a, b) => String(a[0]).localeCompare(b[0])))

...and by string values:

 new Map([...map].sort((a, b) => String(a[1]).localeCompare(b[1])))

In detail with examples

tldr: ...map.entries() is redundant, just ...map is fine; and a lazy .sort() without passing a sort function risks weird edge case bugs caused by string coercion.

The .entries() in [...map.entries()] (suggested in many answers) is redundant, probably adding an extra iteration of the map unless the JS engine optimises that away for you.

In the simple test case, you can do what the question asks for with:

new Map([...map].sort())

...which, if the keys are all strings, compares squashed and coerced comma-joined key-value strings like '2-1,foo' and '0-1,[object Object]', returning a new Map with the new insertion order:

Note: if you see only {} in SO's console output, look in your real browser console

_x000D_
_x000D_
const map = new Map([
  ['2-1', 'foo'],
  ['0-1', { bar: 'bar' }],
  ['3-5', () => 'fuz'],
  ['3-2', [ 'baz' ]]
])

console.log(new Map([...map].sort()))
_x000D_
_x000D_
_x000D_

HOWEVER, it's not a good practice to rely on coercion and stringification like this. You can get surprises like:

_x000D_
_x000D_
const map = new Map([
  ['2', '3,buh?'],
  ['2,1', 'foo'],
  ['0,1', { bar: 'bar' }],
  ['3,5', () => 'fuz'],
  ['3,2', [ 'baz' ]],
])

// Compares '2,3,buh?' with '2,1,foo'
// Therefore sorts ['2', '3,buh?'] ******AFTER****** ['2,1', 'foo']
console.log('Buh?', new Map([...map].sort()))

// Let's see exactly what each iteration is using as its comparator
for (const iteration of map) {
  console.log(iteration.toString())
}
_x000D_
_x000D_
_x000D_

Bugs like this are really hard to debug - don't risk it!

If you want to sort on keys or values, it's best to access them explicitly with a[0] and b[0] in the sort function, like this. Note that we should return -1 and 1 for before and after, not false or 0 as with raw a[0] > b[0] because that is treated as equals:

_x000D_
_x000D_
const map = new Map([
  ['2,1', 'this is overwritten'],
  ['2,1', '0,1'],
  ['0,1', '2,1'],
  ['2,2', '3,5'],
  ['3,5', '2,1'],
  ['2', ',9,9']
])

const sortStringKeys = (a, b) => String(a[0]).localeCompare(b[0])
const sortStringValues = (a, b) => String(a[1]).localeCompare(b[1])

console.log('By keys:', new Map([...map].sort(sortStringKeys)))
console.log('By values:', new Map([...map].sort(sortStringValues)))
_x000D_
_x000D_
_x000D_

How to convert an int array to String with toString method in Java

This function returns a array of int in the string form like "6097321041141011026"

private String IntArrayToString(byte[] array) {
        String strRet="";
        for(int i : array) {
            strRet+=Integer.toString(i);
        }
        return strRet;
    }

Apply vs transform on a group object

you can use zscore to analyze the data in column C and D for outliers, where zscore is the series - series.mean / series.std(). Use apply too create a user defined function for difference between C and D creating a new resulting dataframe. Apply uses the group result set.

from scipy.stats import zscore

columns = ['A', 'B', 'C', 'D']
records = [
['foo', 'one', 0.162003, 0.087469],
['bar', 'one', -1.156319, -1.5262719999999999],
['foo', 'two', 0.833892, -1.666304],     
['bar', 'three', -2.026673, -0.32205700000000004],
['foo', 'two', 0.41145200000000004, -0.9543709999999999],
['bar', 'two', 0.765878, -0.095968],
['foo', 'one', -0.65489, 0.678091],
['foo', 'three', -1.789842, -1.130922]
]
df = pd.DataFrame.from_records(records, columns=columns)
print(df)

standardize=df.groupby('A')['C','D'].transform(zscore)
print(standardize)
outliersC= (standardize['C'] <-1.1) | (standardize['C']>1.1)
outliersD= (standardize['D'] <-1.1) | (standardize['D']>1.1)

results=df[outliersC | outliersD]
print(results)

   #Dataframe results
   A      B         C         D
   0  foo    one  0.162003  0.087469
   1  bar    one -1.156319 -1.526272
   2  foo    two  0.833892 -1.666304
   3  bar  three -2.026673 -0.322057
   4  foo    two  0.411452 -0.954371
   5  bar    two  0.765878 -0.095968
   6  foo    one -0.654890  0.678091
   7  foo  three -1.789842 -1.130922
 #C and D transformed Z score
           C         D
 0  0.398046  0.801292
 1 -0.300518 -1.398845
 2  1.121882 -1.251188
 3 -1.046514  0.519353
 4  0.666781 -0.417997
 5  1.347032  0.879491
 6 -0.482004  1.492511
 7 -1.704704 -0.624618

 #filtering using arbitrary ranges -1 and 1 for the z-score
      A      B         C         D
 1  bar    one -1.156319 -1.526272
 2  foo    two  0.833892 -1.666304
 5  bar    two  0.765878 -0.095968
 6  foo    one -0.654890  0.678091
 7  foo  three -1.789842 -1.130922


 >>>>>>>>>>>>> Part 2

 splitting = df.groupby('A')

 #look at how the data is grouped
 for group_name, group in splitting:
     print(group_name)

 def column_difference(gr):
      return gr['C']-gr['D']

 grouped=splitting.apply(column_difference)
 print(grouped)

 A     
 bar  1    0.369953
      3   -1.704616
      5    0.861846
 foo  0    0.074534
      2    2.500196
      4    1.365823
      6   -1.332981
      7   -0.658920

Viewing local storage contents on IE

In IE11, you can see local storage in console on dev tools:

  1. Show dev tools (press F12)
  2. Click "Console" or press Ctrl+2
  3. Type localStorage and press Enter

Also, if you need to clear the localStorage, type localStorage.clear() on console.

How to create custom view programmatically in swift having controls text field, button etc

The CGRectZero constant is equal to a rectangle at position (0,0) with zero width and height. This is fine to use, and actually preferred, if you use AutoLayout, since AutoLayout will then properly place the view.

But, I expect you do not use AutoLayout. So the most simple solution is to specify the size of the custom view by providing a frame explicitly:

customView = MyCustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
self.view.addSubview(customView)

Note that you also need to use addSubview otherwise your view is not added to the view hierarchy.

How can I inspect element in chrome when right click is disabled?

Use Ctrl+Shift+C (or Cmd+Shift+C on Mac) to open the DevTools in Inspect Element mode, or toggle Inspect Element mode if the DevTools are already open.

What does $1 mean in Perl?

Since you asked about the capture groups, you might want to know about $+ too... Pretty useful...

use Data::Dumper;
$text = "hiabc ihabc ads byexx eybxx";
while ($text =~ /(hi|ih)abc|(bye|eyb)xx/igs)
{
    print Dumper $+;
}

OUTPUT:
$VAR1 = 'hi';
$VAR1 = 'ih';
$VAR1 = 'bye';
$VAR1 = 'eyb';

How to change a table name using an SQL query?

execute this command

sp_rename 'Employee','EData'

Are nested try/except blocks in Python a good programming practice?

According to the documentation, it is better to handle multiple exceptions through tuples or like this:

import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as e:
    print "I/O error({0}): {1}".format(e.errno, e.strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error: ", sys.exc_info()[0]
    raise

How to get last items of a list in Python?

Slicing

Python slicing is an incredibly fast operation, and it's a handy way to quickly access parts of your data.

Slice notation to get the last nine elements from a list (or any other sequence that supports it, like a string) would look like this:

num_list[-9:]

When I see this, I read the part in the brackets as "9th from the end, to the end." (Actually, I abbreviate it mentally as "-9, on")

Explanation:

The full notation is

sequence[start:stop:step]

But the colon is what tells Python you're giving it a slice and not a regular index. That's why the idiomatic way of copying lists in Python 2 is

list_copy = sequence[:]

And clearing them is with:

del my_list[:]

(Lists get list.copy and list.clear in Python 3.)

Give your slices a descriptive name!

You may find it useful to separate forming the slice from passing it to the list.__getitem__ method (that's what the square brackets do). Even if you're not new to it, it keeps your code more readable so that others that may have to read your code can more readily understand what you're doing.

However, you can't just assign some integers separated by colons to a variable. You need to use the slice object:

last_nine_slice = slice(-9, None)

The second argument, None, is required, so that the first argument is interpreted as the start argument otherwise it would be the stop argument.

You can then pass the slice object to your sequence:

>>> list(range(100))[last_nine_slice]
[91, 92, 93, 94, 95, 96, 97, 98, 99]

islice

islice from the itertools module is another possibly performant way to get this. islice doesn't take negative arguments, so ideally your iterable has a __reversed__ special method - which list does have - so you must first pass your list (or iterable with __reversed__) to reversed.

>>> from itertools import islice
>>> islice(reversed(range(100)), 0, 9)
<itertools.islice object at 0xffeb87fc>

islice allows for lazy evaluation of the data pipeline, so to materialize the data, pass it to a constructor (like list):

>>> list(islice(reversed(range(100)), 0, 9))
[99, 98, 97, 96, 95, 94, 93, 92, 91]

Center div on the middle of screen

The best way to align a div in center both horizontally and vertically will be

HTML

<div></div>

CSS:

div {
    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    width: 100px;
    height: 100px;
    background-color: blue;
}

FIDDLE

Fastest way(s) to move the cursor on a terminal command line?

If you want to move forward a certain number of words, hit M-<n> (M- is for Meta and its usually the escape key) then hit a number. This sends a repeat argument to readline, so you can repeat whatever command you want - if you want to go forward then hit M-<n> M-f and the cursor will move forward <n> number of words.

E.g.

 $|echo "two three four five six seven"
 $ M-4
 (arg: 4) echo "two three four five six seven"
 $ M-f
 $ echo "two three four| five six seven"

So for your example from the cursor at the beginning of the line you would hit, M-26 M-f and your cursor would be at --option25| -or- from the end of the line M-26 M-b would put your cursor at --|option25

How do I remove/delete a folder that is not empty?

import shutil

shutil.rmtree('/folder_name')

Standard Library Reference: shutil.rmtree.

By design, rmtree fails on folder trees containing read-only files. If you want the folder to be deleted regardless of whether it contains read-only files, then use

shutil.rmtree('/folder_name', ignore_errors=True)

Transform only one axis to log10 scale with ggplot2

I think I got it at last by doing some manual transformations with the data before visualization:

d <- diamonds
# computing logarithm of prices
d$price <- log10(d$price)

And work out a formatter to later compute 'back' the logarithmic data:

formatBack <- function(x) 10^x 
# or with special formatter (here: "dollar")
formatBack <- function(x) paste(round(10^x, 2), "$", sep=' ') 

And draw the plot with given formatter:

m <- ggplot(d, aes(y = price, x = color))
m + geom_boxplot() + scale_y_continuous(formatter='formatBack')

alt text

Sorry to the community to bother you with a question I could have solved before! The funny part is: I was working hard to make this plot work a month ago but did not succeed. After asking here, I got it.

Anyway, thanks to @DWin for motivation!

How Do I Take a Screen Shot of a UIView?

There is new API from iOS 10

extension UIView {
    func makeScreenshot() -> UIImage {
        let renderer = UIGraphicsImageRenderer(bounds: self.bounds)
        return renderer.image { (context) in
            self.layer.render(in: context.cgContext)
        }
    }
}

How to access html form input from asp.net code behind

What I'm guessing is that you need to set those input elements to runat="server".

So you won't be able to access the control

<input type="text" name="email" id="myTextBox" />

But you'll be able to work with

<input type="text" name="email" id="myTextBox" runat="server" />

And read from it by using

string myStringFromTheInput = myTextBox.Value;

What is the `data-target` attribute in Bootstrap 3?

The toggle tells Bootstrap what to do and the target tells Bootstrap which element is going to open. So whenever a link like that is clicked, a modal with an id of “basicModal” will appear.

Xcode - Warning: Implicit declaration of function is invalid in C99

The compiler wants to know the function before it can use it

just declare the function before you call it

#include <stdio.h>

int Fibonacci(int number); //now the compiler knows, what the signature looks like. this is all it needs for now

int main(int argc, const char * argv[])
{
    int input;
    printf("Please give me a number : ");
    scanf("%d", &input);
    getchar();
    printf("The fibonacci number of %d is : %d", input, Fibonacci(input)); //!!!

}/* main */

int Fibonacci(int number)
{
//…

Java - get pixel array from image

Mota's answer is great unless your BufferedImage came from a Monochrome Bitmap. A Monochrome Bitmap has only 2 possible values for its pixels (for example 0 = black and 1 = white). When a Monochrome Bitmap is used then the

final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();

call returns the raw Pixel Array data in such a fashion that each byte contains more than one pixel.

So when you use a Monochrome Bitmap image to create your BufferedImage object then this is the algorithm you want to use:

/**
 * This returns a true bitmap where each element in the grid is either a 0
 * or a 1. A 1 means the pixel is white and a 0 means the pixel is black.
 * 
 * If the incoming image doesn't have any pixels in it then this method
 * returns null;
 * 
 * @param image
 * @return
 */
public static int[][] convertToArray(BufferedImage image)
{

    if (image == null || image.getWidth() == 0 || image.getHeight() == 0)
        return null;

    // This returns bytes of data starting from the top left of the bitmap
    // image and goes down.
    // Top to bottom. Left to right.
    final byte[] pixels = ((DataBufferByte) image.getRaster()
            .getDataBuffer()).getData();

    final int width = image.getWidth();
    final int height = image.getHeight();

    int[][] result = new int[height][width];

    boolean done = false;
    boolean alreadyWentToNextByte = false;
    int byteIndex = 0;
    int row = 0;
    int col = 0;
    int numBits = 0;
    byte currentByte = pixels[byteIndex];
    while (!done)
    {
        alreadyWentToNextByte = false;

        result[row][col] = (currentByte & 0x80) >> 7;
        currentByte = (byte) (((int) currentByte) << 1);
        numBits++;

        if ((row == height - 1) && (col == width - 1))
        {
            done = true;
        }
        else
        {
            col++;

            if (numBits == 8)
            {
                currentByte = pixels[++byteIndex];
                numBits = 0;
                alreadyWentToNextByte = true;
            }

            if (col == width)
            {
                row++;
                col = 0;

                if (!alreadyWentToNextByte)
                {
                    currentByte = pixels[++byteIndex];
                    numBits = 0;
                }
            }
        }
    }

    return result;
}

Functional style of Java 8's Optional.ifPresent and if-not-Present?

In case you want store the value:

Pair.of<List<>, List<>> output = opt.map(details -> Pair.of(details.a, details.b))).orElseGet(() -> Pair.of(Collections.emptyList(), Collections.emptyList()));

Current time in microseconds in java

LocalDateTime.now().truncatedTo(ChronoUnit.MICROS)

How to cin to a vector

#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
    vector<string>V;
    int num;
    cin>>num;
    string input;
    while (cin>>input && num != 0) //enter any non-integer to end the loop!
{
    //cin>>input;
   V.push_back(input);
   num--;
   if(num==0)
   {
   vector<string>::iterator it;
    for(it=V.begin();it!=V.end();it++)
        cout<<*it<<endl;
   };

}
return 0;

};

How do I disable the resizable property of a textarea?

To disable resize for all textareas:

textarea {
    resize: none;
}

To disable resize for a specific textarea, add an attribute, name, or an id and set it to something. In this case, it is named noresize

HTML

<textarea name='noresize' id='noresize'> </textarea>

CSS

/* Using the attribute name */
textarea[name=noresize] {
    resize: none;
}
/* Or using the id */

#noresize {
    resize: none;
}

How to perform Unwind segue programmatically?

Backwards compatible solution that will work for versions prior to ios6, for those interested:

- (void)unwindToViewControllerOfClass:(Class)vcClass animated:(BOOL)animated {

    for (int i=self.navigationController.viewControllers.count - 1; i >= 0; i--) {
        UIViewController *vc = [self.navigationController.viewControllers objectAtIndex:i];
        if ([vc isKindOfClass:vcClass]) {
            [self.navigationController popToViewController:vc animated:animated];
            return;
        }
    }
}

Sort an ArrayList based on an object field

Use a custom comparator:

Collections.sort(nodeList, new Comparator<DataNode>(){
     public int compare(DataNode o1, DataNode o2){
         if(o1.degree == o2.degree)
             return 0;
         return o1.degree < o2.degree ? -1 : 1;
     }
});

successful/fail message pop up box after submit?

You are echoing outside the body tag of your HTML. Put your echos there, and you should be fine.

Also, remove the onclick="alert()" from your submit. This is the cause for your first undefined message.

<?php
  $posted = false;
  if( $_POST ) {
    $posted = true;

    // Database stuff here...
    // $result = mysql_query( ... )
    $result = $_POST['name'] == "danny"; // Dummy result
  }
?>

<html>
  <head></head>
  <body>

  <?php
    if( $posted ) {
      if( $result ) 
        echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
      else
        echo "<script type='text/javascript'>alert('failed!')</script>";
    }
  ?>
    <form action="" method="post">
      Name:<input type="text" id="name" name="name"/>
      <input type="submit" value="submit" name="submit"/>
    </form>
  </body>
</html>

Send request to curl with post data sourced from a file

I had to use a HTTP connection, because on HTTPS there is default file size limit.

https://techcommunity.microsoft.com/t5/IIS-Support-Blog/Solution-for-Request-Entity-Too-Large-error/ba-p/501134

    curl -i -X 'POST' -F 'file=@/home/testeincremental.xlsx' 'http://example.com/upload.aspx?user=example&password=example123&type=XLSX'

How to check the input is an integer or not in Java?

        String input = "";
        int inputInteger = 0;
        BufferedReader br    = new BufferedReader(new InputStreamReader (System.in));

        System.out.println("Enter the radious: ");
        try {
            input = br.readLine();
            inputInteger = Integer.parseInt(input);
        } catch (NumberFormatException e) {
            System.out.println("Please Enter An Integer");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        float area = (float) (3.14*inputInteger*inputInteger);
        System.out.println("Area = "+area);

What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)

For me ComboBox.DropDownClosed Event did it.

private void cbValueType_DropDownClosed(object sender, EventArgs e)
    {
        if (cbValueType.SelectedIndex == someIntValue) //sel ind already updated
        {
            // change sel Index of other Combo for example
            cbDataType.SelectedIndex = someotherIntValue;
        }
    }

Stacking DIVs on top of each other?

You can now use CSS Grid to fix this.

<div class="outer">
  <div class="top"> </div>
  <div class="below"> </div>
</div>

And the css for this:

.outer {
  display: grid;
  grid-template: 1fr / 1fr;
  place-items: center;
}
.outer > * {
  grid-column: 1 / 1;
  grid-row: 1 / 1;
}
.outer .below {
  z-index: 2;
}
.outer .top {
  z-index: 1;
}

Access-Control-Allow-Origin and Angular.js $http

@Swapnil Niwane

I was able to solve this issue by calling an ajax request and formatting the data to 'jsonp'.

$.ajax({
          method: 'GET',
          url: url,
          defaultHeaders: {
              'Content-Type': 'application/json',
              "Access-Control-Allow-Origin": "*",
              'Accept': 'application/json'
           },

          dataType: 'jsonp',

          success: function (response) {
            console.log("success ");
            console.log(response);
          },
          error: function (xhr) {
            console.log("error ");
            console.log(xhr);
          }
});

Getting the Username from the HKEY_USERS values

It is possible to query this information from WMI. The following command will output a table with a row for every user along with the SID for each user.

wmic useraccount get name,sid

You can also export this information to CSV:

wmic useraccount get name,sid /format:csv > output.csv

I have used this on Vista and 7. For more information see WMIC - Take Command-line Control over WMI.

How to get the date 7 days earlier date from current date in Java

For all date related functionality, you should consider using Joda Library. Java's date api's are very poorly designed. Joda provides very nice API.

Why should I use the keyword "final" on a method parameter in Java?

Follow up by Michel's post. I made myself another example to explain it. I hope it could help.

public static void main(String[] args){
    MyParam myParam = thisIsWhy(new MyObj());
    myParam.setArgNewName();

    System.out.println(myParam.showObjName());
}

public static MyParam thisIsWhy(final MyObj obj){
    MyParam myParam = new MyParam() {
        @Override
        public void setArgNewName() {
            obj.name = "afterSet";
        }

        @Override
        public String showObjName(){
            return obj.name;
        }
    };

    return myParam;
}

public static class MyObj{
    String name = "beforeSet";
    public MyObj() {
    }
}

public abstract static class MyParam{
    public abstract void setArgNewName();
    public abstract String showObjName();
}

From the code above, in the method thisIsWhy(), we actually didn't assign the [argument MyObj obj] to a real reference in MyParam. In instead, we just use the [argument MyObj obj] in the method inside MyParam.

But after we finish the method thisIsWhy(), should the argument(object) MyObj still exist?

Seems like it should, because we can see in main we still call the method showObjName() and it needs to reach obj. MyParam will still use/reaches the method argument even the method already returned!

How Java really achieve this is to generate a copy also is a hidden reference of the argument MyObj obj inside the MyParam object ( but it's not a formal field in MyParam so that we can't see it )

As we call "showObjName", it will use that reference to get the corresponding value.

But if we didn't put the argument final, which leads a situation we can reassign a new memory(object) to the argument MyObj obj.

Technically there's no clash at all! If we are allowed to do that, below will be the situation:

  1. We now have a hidden [MyObj obj] point to a [Memory A in heap] now live in MyParam object.
  2. We also have another [MyObj obj] which is the argument point to a [Memory B in heap] now live in thisIsWhy method.

No clash, but "CONFUSING!!" Because they are all using the same "reference name" which is "obj".

To avoid this, set it as "final" to avoid programmer do the "mistake-prone" code.

Set variable in jinja

{{ }} tells the template to print the value, this won't work in expressions like you're trying to do. Instead, use the {% set %} template tag and then assign the value the same way you would in normal python code.

{% set testing = 'it worked' %}
{% set another = testing %}
{{ another }}

Result:

it worked

How to sort a Collection<T>?

If your collections object is a list, I would use the sort method, as proposed in the other answers.

However, if it is not a list, and you don't really care about what type of Collection object is returned, I think it is faster to create a TreeSet instead of a List:

TreeSet sortedSet = new TreeSet(myComparator);
sortedSet.addAll(myCollectionToBeSorted);

remove url parameters with javascript or jquery

Use this function:

_x000D_
_x000D_
var getCleanUrl = function(url) {_x000D_
  return url.replace(/#.*$/, '').replace(/\?.*$/, '');_x000D_
};_x000D_
_x000D_
// get rid of hash and params_x000D_
console.log(getCleanUrl('https://sidanmor.com/?firstname=idan&lastname=mor'));
_x000D_
_x000D_
_x000D_

If you want all the href parts, use this:

_x000D_
_x000D_
var url = document.createElement('a');_x000D_
url.href = 'https://developer.mozilla.org/en-US/search?q=URL#search-results-close-container';_x000D_
_x000D_
console.log(url.href); // https://developer.mozilla.org/en-US/search?q=URL#search-results-close-container_x000D_
console.log(url.protocol); // https:_x000D_
console.log(url.host); // developer.mozilla.org_x000D_
console.log(url.hostname); // developer.mozilla.org_x000D_
console.log(url.port); // (blank - https assumes port 443)_x000D_
console.log(url.pathname); // /en-US/search_x000D_
console.log(url.search); // ?q=URL_x000D_
console.log(url.hash); // #search-results-close-container_x000D_
console.log(url.origin); // https://developer.mozilla.org
_x000D_
_x000D_
_x000D_

How can I see the raw SQL queries Django is running?

Though you can do it with with the code supplied, I find that using the debug toolbar app is a great tool to show queries. You can download it from github here.

This gives you the option to show all the queries ran on a given page along with the time to query took. It also sums up the number of queries on a page along with total time for a quick review. This is a great tool, when you want to look at what the Django ORM does behind the scenes. It also have a lot of other nice features, that you can use if you like.

Remove ALL styling/formatting from hyperlinks

As Chris said before me, just an a should override. For example:

a { color:red; }
a:hover { color:blue; }
.nav a { color:green; }

In this instance the .nav a would ALWAYS be green, the :hover wouldn't apply to it.

If there's some other rule affecting it, you COULD use !important, but you shouldn't. It's a bad habit to fall into.

.nav a { color:green !important; } /*I'm a bad person and shouldn't use !important */

Then it'll always be green, irrelevant of any other rule.

How to add Python to Windows registry

When installing Python 3.4 the "Add python.exe to Path" came up unselected. Re-installed with this selected and problem resolved.

Can grep show only words that match search pattern?

grep command for only matching and perl

grep -o -P 'th.*? ' filename

How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?

I don't think the jar tool supports this natively, but you can just unzip a JAR file with "unzip" and specify the output directory with that with the "-d" option, so something like:

$ unzip -d /home/foo/bar/baz /home/foo/bar/Portal.ear Binaries.war

cout is not a member of std

add #include <iostream> to the start of io.cpp too.

how to run command "mysqladmin flush-hosts" on Amazon RDS database Server instance?

On Amazon RDS FLUSH HOSTS; can be executed from default user ("Master Username" in RDS info), and it helps.

How to import Angular Material in project?

Step 1

yarn add @angular/material @angular/cdk @angular/animations

Step 2 - Create a new file( /myApp/src/app/material.module.ts ) that includes all the material UI modules (there is no shortcut, you have to include individual modules one by one)

import { NgModule } from '@angular/core';

    import {
      MatButtonModule,
      MatMenuModule,
      MatToolbarModule,
      MatIconModule,
      MatCardModule
    } from '@angular/material';

    @NgModule({
      imports: [
        MatButtonModule,
        MatMenuModule,
        MatToolbarModule,
        MatIconModule,
        MatCardModule
      ],
      exports: [
        MatButtonModule,
        MatMenuModule,
        MatToolbarModule,
        MatIconModule,
        MatCardModule
      ]
    })
    export class MaterialModule {}

Step 3 - Import and add that newly created module to your app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { MaterialModule } from './material.module'; // material module imported

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    MaterialModule // MAteria module added
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Calling a function of a module by using its name (a string)

The answer (I hope) no one ever wanted

Eval like behavior

getattr(locals().get("foo") or globals().get("foo"), "bar")()

Why not add auto-importing

getattr(
    locals().get("foo") or 
    globals().get("foo") or
    __import__("foo"), 
"bar")()

In case we have extra dictionaries we want to check

getattr(next((x for x in (f("foo") for f in 
                          [locals().get, globals().get, 
                           self.__dict__.get, __import__]) 
              if x)),
"bar")()

We need to go deeper

getattr(next((x for x in (f("foo") for f in 
              ([locals().get, globals().get, self.__dict__.get] +
               [d.get for d in (list(dd.values()) for dd in 
                                [locals(),globals(),self.__dict__]
                                if isinstance(dd,dict))
                if isinstance(d,dict)] + 
               [__import__])) 
        if x)),
"bar")()

Java: Literal percent sign in printf statement

The percent sign is escaped using a percent sign:

System.out.printf("%s\t%s\t%1.2f%%\t%1.2f%%\n",ID,pattern,support,confidence);

The complete syntax can be accessed in java docs. This particular information is in the section Conversions of the first link.

The reason the compiler is generating an error is that only a limited amount of characters may follow a backslash. % is not a valid character.

Apache is not running from XAMPP Control Panel ( Error: Apache shutdown unexpectedly. This may be due to a blocked port)

I have installed VMWare Workstation. So, It was causing the error.

Services.msc and stopped the 'Workstation' Services.

This has solved my problems.

Thanks

Django -- Template tag in {% if %} block

Sorry for comment in an old post but if you want to use an else if statement this will help you

{% if title == source %}
    Do This
{% elif title == value %}
    Do This
{% else %}
    Do This
{% endif %}

For more info see Django Documentation

syntax error: unexpected token <

i checked all Included JS Paths

Example Change this

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

TO

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" type="text/javascript"></script>

Check if the number is integer

It appears that you do not see the need to incorporate some error tolerance. It would not be needed if all integers came entered as integers, however sometimes they come as a result of arithmetic operations that loose some precision. For example:

> 2/49*49
[1] 2
> check.integer(2/49*49)
[1] FALSE 
> is.wholenumber(2/49*49)
[1] TRUE

Note that this is not R's weakness, all computer software have some limits of precision.

Escape invalid XML characters in C#

string XMLWriteStringWithoutIllegalCharacters(string UnfilteredString)
{
    if (UnfilteredString == null)
        return string.Empty;

    return XmlConvert.EncodeName(UnfilteredString);
}

string XMLReadStringWithoutIllegalCharacters(string FilteredString)
{
    if (UnfilteredString == null)
        return string.Empty;

    return XmlConvert.DecodeName(UnfilteredString);
}

This simple method replace the invalid characters with the same value but accepted in the XML context.


To write string use XMLWriteStringWithoutIllegalCharacters(string UnfilteredString).
To read string use XMLReadStringWithoutIllegalCharacters(string FilteredString).

How to detect reliably Mac OS X, iOS, Linux, Windows in C preprocessor?

There are predefined macros that are used by most compilers, you can find the list here. GCC compiler predefined macros can be found here. Here is an example for gcc:

#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
   //define something for Windows (32-bit and 64-bit, this part is common)
   #ifdef _WIN64
      //define something for Windows (64-bit only)
   #else
      //define something for Windows (32-bit only)
   #endif
#elif __APPLE__
    #include <TargetConditionals.h>
    #if TARGET_IPHONE_SIMULATOR
         // iOS Simulator
    #elif TARGET_OS_IPHONE
        // iOS device
    #elif TARGET_OS_MAC
        // Other kinds of Mac OS
    #else
    #   error "Unknown Apple platform"
    #endif
#elif __linux__
    // linux
#elif __unix__ // all unices not caught above
    // Unix
#elif defined(_POSIX_VERSION)
    // POSIX
#else
#   error "Unknown compiler"
#endif

The defined macros depend on the compiler that you are going to use.

The _WIN64 #ifdef can be nested into the _WIN32 #ifdef because _WIN32 is even defined when targeting the Windows x64 version. This prevents code duplication if some header includes are common to both (also WIN32 without underscore allows IDE to highlight the right partition of code).

How to get a Docker container's IP address from the host

The accepted answer does not work well with multiple networks per container:

> docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' cc54d96d63ea

172.20.0.4172.18.0.5

The next best answer is closer:

> docker inspect cc54d96d63ea | grep "IPAddress"

"SecondaryIPAddresses": null,
"IPAddress": "",
    "IPAddress": "172.20.0.4",
    "IPAddress": "172.18.0.5",

I like to use jq to parse the network JSON:

> docker inspect cc54d96d63ea | jq -r 'map(.NetworkSettings.Networks) []'

{
  "proxy": {
    "IPAMConfig": null,
    "Links": [
      "server1_php_1:php",
      "server1_php_1:php_1",
      "server1_php_1:server1_php_1"
    ],
    "Aliases": [
      "cc54d96d63ea",
      "web"
    ],
    "NetworkID": "7779959d7383e9cef09c970c38c24a1a6ff44695178d314e3cb646bfa30d9935",
    "EndpointID": "4ac2c26113bf10715048579dd77304008904186d9679cdbc8fcea65eee0bf13b",
    "Gateway": "172.20.0.1",
    "IPAddress": "172.20.0.4",
    "IPPrefixLen": 24,
    "IPv6Gateway": "",
    "GlobalIPv6Address": "",
    "GlobalIPv6PrefixLen": 0,
    "MacAddress": "02:42:ac:14:00:04",
    "DriverOpts": null
  },
  "webservers": {
    "IPAMConfig": null,
    "Links": [
      "server1_php_1:php",
      "server1_php_1:php_1",
      "server1_php_1:server1_php_1"
    ],
    "Aliases": [
      "cc54d96d63ea",
      "web"
    ],
    "NetworkID": "907a7fba8816cd0ad89b7f5603bbc91122a2dd99902b504be6af16427c11a0a6",
    "EndpointID": "7febabe380d040b96b4e795417ba0954a103ac3fd37e9f6110189d9de92fbdae",
    "Gateway": "172.18.0.1",
    "IPAddress": "172.18.0.5",
    "IPPrefixLen": 24,
    "IPv6Gateway": "",
    "GlobalIPv6Address": "",
    "GlobalIPv6PrefixLen": 0,
    "MacAddress": "02:42:ac:12:00:05",
    "DriverOpts": null
  }
}

To list the IP addresses of every container then becomes:

for s in `docker ps -q`; do
  echo `docker inspect -f "{{.Name}}" ${s}`:
  docker inspect ${s} | jq -r 'map(.NetworkSettings.Networks) []' | grep "IPAddress";
done

/server1_web_1:
    "IPAddress": "172.20.0.4",
    "IPAddress": "172.18.0.5",
/server1_php_1:
    "IPAddress": "172.20.0.3",
    "IPAddress": "172.18.0.4",
/docker-gen:
    "IPAddress": "172.18.0.3",
/nginx-proxy:
    "IPAddress": "172.20.0.2",
    "IPAddress": "172.18.0.2",

How stable is the git plugin for eclipse?

I'm using if for day-to-day work and I find it stable. Lately the plugin has made good progress and has added:

  • merge support, including a in-Eclipse merge tool;
  • a basic synchronise view;
  • reading of .git/info/exclude and .gitignore files.
  • rebasing;
  • streamlined commands for pushing and pulling;
  • cherry-picking.

Git repositories view

Be sure to skim the EGit User Guide for a good overview of the current functionality.

I find that I only need to drop to the comand line for interactive rebases.

As an official Eclipse project I am confident that EGit will receive all the main features of the command-line client.

Enzyme - How to access and set <input> value?

Got it. (updated/improved version)

  it('cancels changes when user presses esc', done => {
    const wrapper = mount(<EditableText defaultValue="Hello" />);
    const input = wrapper.find('input');

    input.simulate('focus');
    input.simulate('change', { target: { value: 'Changed' } });
    input.simulate('keyDown', {
      which: 27,
      target: {
        blur() {
          // Needed since <EditableText /> calls target.blur()
          input.simulate('blur');
        },
      },
    });
    expect(input.get(0).value).to.equal('Hello');

    done();
  });

Check if file is already open

I don't think you'll ever get a definitive solution for this, the operating system isn't necessarily going to tell you if the file is open or not.

You might get some mileage out of java.nio.channels.FileLock, although the javadoc is loaded with caveats.

CSS content property: is it possible to insert HTML instead of Text?

It is not possible prolly cuz it would be so easy to XSS. Also , current HTML sanitizers that are available don't disallow content property.

(Definitely not the greatest answer here but I just wanted to share an insight other than the "according to spec... ")

Get filename from file pointer

You can get the path via fp.name. Example:

>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'

You might need os.path.basename if you want only the file name:

>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'

File object docs (for Python 2) here.

Is either GET or POST more secure than the other?

The difference between GET and POST should not be viewed in terms of security, but rather in their intentions towards the server. GET should never change data on the server - at least other than in logs - but POST can create new resources.

Nice proxies won't cache POST data, but they may cache GET data from the URL, so you could say that POST is supposed to be more secure. But POST data would still be available to proxies that don't play nicely.

As mentioned in many of the answers, the only sure bet is via SSL.

But DO make sure that GET methods do not commit any changes, such as deleting database rows, etc.