Programs & Examples On #Zpl

ZPL stands for the "Zebra Programming Language" and is a proprietary programming language used to communicate to Zebra branded printers.

Send raw ZPL to Zebra printer via USB

I found the answer... or at least, the easiest answer (if there are multiple). When I installed the printer, I renamed it to "ICS Label Printer". Here's how to change the options to allow pass-through ZPL commands:

  1. Right-click on the "ICS Label Printer" and choose "Properties".
  2. On the "General" tab, click on the "Printing Preferences..." button.
  3. On the "Advanced Setup" tab, click on the "Other" button.
  4. Make sure there is a check in the box labeled "Enable Passthrough Mode".
  5. Make sure the "Start sequence:" is "${".
  6. Make sure the "End sequence:" is "}$".
  7. Click on the "Close" button.
  8. Click on the "OK" button.
  9. Click on the "OK" button.

In my code, I just have to add "${" to the beginning of my ZPL and "}$" to the end and print it as plain text. This is with the "Windows driver for ZDesigner LP 2844-Z printer Version 2.6.42 (Build 2382)". Works like a charm!

.NET code to send ZPL to Zebra printers

I've managed a project that does this with sockets for years. Zebra's typically use port 6101. I'll look through the code and post what I can.

public void SendData(string zpl)
{
    NetworkStream ns = null;
    Socket socket = null;

    try
    {
        if (printerIP == null)
        {
            /* IP is a string property for the printer's IP address. */
            /* 6101 is the common port of all our Zebra printers. */
            printerIP = new IPEndPoint(IPAddress.Parse(IP), 6101);  
        }

        socket = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream,
            ProtocolType.Tcp);
        socket.Connect(printerIP);

        ns = new NetworkStream(socket);

        byte[] toSend = Encoding.ASCII.GetBytes(zpl);
        ns.Write(toSend, 0, toSend.Length);
    }
    finally
    {
        if (ns != null)
            ns.Close();

        if (socket != null && socket.Connected)
            socket.Close();
    }
}

Update Top 1 record in table sql server

For those who are finding for a thread safe solution, take a look here.

Code:

UPDATE Account 
SET    sg_status = 'A'
OUTPUT INSERTED.AccountId --You only need this if you want to return some column of the updated item
WHERE  AccountId = 
(
    SELECT TOP 1 AccountId 
    FROM Account WITH (UPDLOCK) --this is what makes the query thread safe!
    ORDER  BY CreationDate 
)

Password masking console application

Here is my simple version. Every time you hit a key, delete all from console and draw as many '*' as the length of password string is.

int chr = 0;
string pass = "";
const int ENTER = 13;
const int BS = 8;

do
{
   chr = Console.ReadKey().KeyChar;
   Console.Clear(); //imediately clear the char you printed

   //if the char is not 'return' or 'backspace' add it to pass string
   if (chr != ENTER && chr != BS) pass += (char)chr;

   //if you hit backspace remove last char from pass string
   if (chr == BS) pass = pass.Remove(pass.Length-1, 1);

   for (int i = 0; i < pass.Length; i++)
   {
      Console.Write('*');
   }
} 
 while (chr != ENTER);

Console.Write("\n");
Console.Write(pass);

Console.Read(); //just to see the pass

How to position a div in the middle of the screen when the page is bigger than the screen

Try this one.

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Auto-Submit Form using JavaScript

Try using document.getElementById("myForm") instead of document.myForm.

<script>
var auto_refresh = setInterval(function() { submitform(); }, 10000);

function submitform()
{
  alert('test');
  document.getElementById("myForm").submit();
}
</script>

What does asterisk * mean in Python?

I only have one thing to add that wasn't clear from the other answers (for completeness's sake).

You may also use the stars when calling the function. For example, say you have code like this:

>>> def foo(*args):
...     print(args)
...
>>> l = [1,2,3,4,5]

You can pass the list l into foo like so...

>>> foo(*l)
(1, 2, 3, 4, 5)

You can do the same for dictionaries...

>>> def foo(**argd):
...     print(argd)
...
>>> d = {'a' : 'b', 'c' : 'd'}
>>> foo(**d)
{'a': 'b', 'c': 'd'}

Numpy isnan() fails on an array of floats (from pandas dataframe apply)

On top of @unutbu answer, you could coerce pandas numpy object array to native (float64) type, something along the line

import pandas as pd
pd.to_numeric(df['tester'], errors='coerce')

Specify errors='coerce' to force strings that can't be parsed to a numeric value to become NaN. Column type would be dtype: float64, and then isnan check should work

What's the point of the X-Requested-With header?

A good reason is for security - this can prevent CSRF attacks because this header cannot be added to the AJAX request cross domain without the consent of the server via CORS.

Only the following headers are allowed cross domain:

  • Accept
  • Accept-Language
  • Content-Language
  • Last-Event-ID
  • Content-Type

any others cause a "pre-flight" request to be issued in CORS supported browsers.

Without CORS it is not possible to add X-Requested-With to a cross domain XHR request.

If the server is checking that this header is present, it knows that the request didn't initiate from an attacker's domain attempting to make a request on behalf of the user with JavaScript. This also checks that the request wasn't POSTed from a regular HTML form, of which it is harder to verify it is not cross domain without the use of tokens. (However, checking the Origin header could be an option in supported browsers, although you will leave old browsers vulnerable.)

New Flash bypass discovered

You may wish to combine this with a token, because Flash running on Safari on OSX can set this header if there's a redirect step. It appears it also worked on Chrome, but is now remediated. More details here including different versions affected.

OWASP Recommend combining this with an Origin and Referer check:

This defense technique is specifically discussed in section 4.3 of Robust Defenses for Cross-Site Request Forgery. However, bypasses of this defense using Flash were documented as early as 2008 and again as recently as 2015 by Mathias Karlsson to exploit a CSRF flaw in Vimeo. But, we believe that the Flash attack can't spoof the Origin or Referer headers so by checking both of them we believe this combination of checks should prevent Flash bypass CSRF attacks. (NOTE: If anyone can confirm or refute this belief, please let us know so we can update this article)

However, for the reasons already discussed checking Origin can be tricky.

Update

Written a more in depth blog post on CORS, CSRF and X-Requested-With here.

Programmatically add custom event in the iPhone Calendar

Update for swift 4 for Dashrath answer

import UIKit
import EventKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let eventStore = EKEventStore()

        eventStore.requestAccess( to: EKEntityType.event, completion:{(granted, error) in

            if (granted) && (error == nil) {


                let event = EKEvent(eventStore: eventStore)

                event.title = "My Event"
                event.startDate = Date(timeIntervalSinceNow: TimeInterval())
                event.endDate = Date(timeIntervalSinceNow: TimeInterval())
                event.notes = "Yeah!!!"
                event.calendar = eventStore.defaultCalendarForNewEvents

                var event_id = ""
                do{
                    try eventStore.save(event, span: .thisEvent)
                    event_id = event.eventIdentifier
                }
                catch let error as NSError {
                    print("json error: \(error.localizedDescription)")
                }

                if(event_id != ""){
                    print("event added !")
                }
            }
        })
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

also don't forget to add permission for calendar usage image for privary setting

Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

Your code is in the <head> => runs before the elements are rendered, so document.getElementById('compute'); returns null, as MDN promise...

element = document.getElementById(id);
element is a reference to an Element object, or null if an element with the specified ID is not in the document.

MDN

Solutions:

  1. Put the scripts in the bottom of the page.
  2. Call the attach code in the load event.
  3. Use jQuery library and it's DOM ready event.

What is the jQuery ready event and why is it needed?
(why no just JavaScript's load event):

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers...
...

ready docs

Could not autowire field:RestTemplate in Spring boot application

It's exactly what the error says. You didn't create any RestTemplate bean, so it can't autowire any. If you need a RestTemplate you'll have to provide one. For example, add the following to TestMicroServiceApplication.java:

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

Note, in earlier versions of the Spring cloud starter for Eureka, a RestTemplate bean was created for you, but this is no longer true.

How to start new activity on button click

Write the code in your first activity .

button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {


Intent intent = new Intent(MainActivity.this, SecondAcitvity.class);
                       //You can use String ,arraylist ,integer ,float and all data type.
                       intent.putExtra("Key","value");
                       startActivity(intent);
                        finish();
            }
         });

In secondActivity.class

String name = getIntent().getStringExtra("Key");

C - function inside struct

How about this?

#include <stdio.h>

typedef struct hello {
    int (*someFunction)();
} hello;

int foo() {
    return 0;
}

hello Hello() {
    struct hello aHello;
    aHello.someFunction = &foo;
    return aHello;
}

int main()
{
    struct hello aHello = Hello();
    printf("Print hello: %d\n", aHello.someFunction());

    return 0;
} 

How to remove a key from Hash and get the remaining hash in Ruby/Rails?

Hash#except (Ruby 3.0+)

Starting from Ruby 3.0, Hash#except is a build-in method.

As a result, there is no more need to depend on ActiveSupport or write monkey-patches in order to use it.

h = { a: 1, b: 2, c: 3 }
p h.except(:a) #=> {:b=>2, :c=>3}

Sources:

How do I update all my CPAN modules to their latest versions?

An easy way to upgrade all Perl packages (CPAN modules) is the following way:

cpan upgrade /(.*)/

cpan will recognize the regular expression like this and will update/upgrade all packages installed.

How do I use Wget to download all images into a single folder, from a URL?

Try this:

wget -nd -r -P /save/location -A jpeg,jpg,bmp,gif,png http://www.somedomain.com

Here is some more information:

-nd prevents the creation of a directory hierarchy (i.e. no directories).

-r enables recursive retrieval. See Recursive Download for more information.

-P sets the directory prefix where all files and directories are saved to.

-A sets a whitelist for retrieving only certain file types. Strings and patterns are accepted, and both can be used in a comma separated list (as seen above). See Types of Files for more information.

Disable/turn off inherited CSS3 transitions

The use of transition: none seems to be supported (with a specific adjustment for Opera) given the following HTML:

<a href="#" class="transition">Content</a>
<a href="#" class="transition">Content</a>
<a href="#" class="noTransition">Content</a>
<a href="#" class="transition">Content</a>

...and CSS:

a {
    color: #f90;
    -webkit-transition:color 0.8s ease-in, background-color 0.1s ease-in ;  
    -moz-transition:color 0.8s ease-in, background-color 0.1s ease-in;  
    -o-transition:color 0.8s ease-in, background-color 0.1s ease-in;  
    transition:color 0.8s ease-in, background-color 0.1s ease-in; 
}
a:hover {
    color: #f00;
    -webkit-transition:color 0.8s ease-in, background-color 0.1s ease-in ;  
    -moz-transition:color 0.8s ease-in, background-color 0.1s ease-in;  
    -o-transition:color 0.8s ease-in, background-color 0.1s ease-in;  
    transition:color 0.8s ease-in, background-color 0.1s ease-in; 
}
a.noTransition {
    -moz-transition: none;
    -webkit-transition: none;
    -o-transition: color 0 ease-in;
    transition: none;
}

JS Fiddle demo.

Tested with Chromium 12, Opera 11.x and Firefox 5 on Ubuntu 11.04.

The specific adaptation to Opera is the use of -o-transition: color 0 ease-in; which targets the same property as specified in the other transition rules, but sets the transition time to 0, which effectively prevents the transition from being noticeable. The use of the a.noTransition selector is simply to provide a specific selector for the elements without transitions.


Edited to note that @Frédéric Hamidi's answer, using all (for Opera, at least) is far more concise than listing out each individual property-name that you don't want to have transition.

Updated JS Fiddle demo, showing the use of all in Opera: -o-transition: all 0 none, following self-deletion of @Frédéric's answer.

Confused about UPDLOCK, HOLDLOCK

UPDLOCK is used when you want to lock a row or rows during a select statement for a future update statement. The future update might be the very next statement in the transaction.

Other sessions can still see the data. They just cannot obtain locks that are incompatiable with the UPDLOCK and/or HOLDLOCK.

You use UPDLOCK when you wan to keep other sessions from changing the rows you have locked. It restricts their ability to update or delete locked rows.

You use HOLDLOCK when you want to keep other sessions from changing any of the data you are looking at. It restricts their ability to insert, update, or delete the rows you have locked. This allows you to run the query again and see the same results.

matplotlib: Group boxplots

Just to add to the conversation, I have found a more elegant way to change the color of the box plot by iterating over the dictionary of the object itself

import numpy as np
import matplotlib.pyplot as plt

def color_box(bp, color):

    # Define the elements to color. You can also add medians, fliers and means
    elements = ['boxes','caps','whiskers']

    # Iterate over each of the elements changing the color
    for elem in elements:
        [plt.setp(bp[elem][idx], color=color) for idx in xrange(len(bp[elem]))]
    return

a = np.random.uniform(0,10,[100,5])    

bp = plt.boxplot(a)
color_box(bp, 'red')

Original box plot

Modified box plot

Cheers!

batch script - read line by line

This has worked for me in the past and it will even expand environment variables in the file if it can.

for /F "delims=" %%a in (LogName.txt) do (
     echo %%a>>MyDestination.txt
)

How can I test if a letter in a string is uppercase or lowercase using JavaScript?

The problem with the other answers is, that some characters like numbers or punctuation also return true when checked for lowercase/uppercase.

I found this to work very well for it:

function isLowerCase(str)
{
    return str == str.toLowerCase() && str != str.toUpperCase();
}

This will work for punctuation, numbers and letters:

assert(isLowerCase("a"))
assert(!isLowerCase("Ü"))
assert(!isLowerCase("4"))
assert(!isLowerCase("_"))

To check one letter just call it using isLowerCase(str[charIndex])

JetBrains / IntelliJ keyboard shortcut to collapse all methods

In Rider, this would be Ctrl +Shift+Keypad *, 2

But!, you cannot use the number 2 on keypad, only number 2 on the top row of the keyboard would work.

Using .text() to retrieve only text not nested in child tags

You can try this

alert(document.getElementById('listItem').firstChild.data)

Import numpy on pycharm

I added Anaconda3/Library/Bin to the environment path and PyCharm no longer complained with the error.

Stated by https://intellij-support.jetbrains.com/hc/en-us/community/posts/360001194720/comments/360000341500

How to hide "Showing 1 of N Entries" with the dataTables.js library

If you also need to disable the drop-down (not to hide the text) then set the lengthChange option to false

$('#datatable').dataTable( {
  "lengthChange": false
} );

Works for DataTables 1.10+

Read more in the official documentation

Server certificate verification failed: issuer is not trusted

Just install the server certificate in the client's trusted root certificates container (if certified it's expired may not work). For further details see this post of similar question.

https://stackoverflow.com/a/21238125/3215589

Confirm button before running deleting routine from website

You have 2 options

1) Use javascript to confirm deletion (use onsubmit event handler), however if the client has JS disabled, you're in trouble.

2) Use PHP to echo out a confirmation message, along with the contents of the form (hidden if you like) as well as a submit button called "confirmation", in PHP check if $_POST["confirmation"] is set.

How to disable horizontal scrolling of UIScrollView?

You can select the view, then under Attributes Inspector uncheck User Interaction Enabled .

How to Set Selected value in Multi-Value Select in Jquery-Select2.?

This doesn't work. only one value is ever pre-selected even though both options are available in the list only the first is shown ('#searchproject').select2('val', ['New Co-location','Expansion']);

How to underline a UILabel in swift?

You can do this using NSAttributedString

Example:

let underlineAttribute = [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.thick.rawValue]
let underlineAttributedString = NSAttributedString(string: "StringWithUnderLine", attributes: underlineAttribute)
myLabel.attributedText = underlineAttributedString

EDIT

To have the same attributes for all texts of one UILabel, I suggest you to subclass UILabel and overriding text, like that:

Swift 5

Same as Swift 4.2 but: You should prefer the Swift initializer NSRange over the old NSMakeRange, you can shorten to .underlineStyle and linebreaks improve readibility for long method calls.

class UnderlinedLabel: UILabel {

override var text: String? {
    didSet {
        guard let text = text else { return }
        let textRange = NSRange(location: 0, length: text.count)
        let attributedText = NSMutableAttributedString(string: text)
        attributedText.addAttribute(.underlineStyle,
                                    value: NSUnderlineStyle.single.rawValue,
                                    range: textRange)
        // Add other attributes if needed
        self.attributedText = attributedText
        }
    }
}

Swift 4.2

class UnderlinedLabel: UILabel {

override var text: String? {
    didSet {
        guard let text = text else { return }
        let textRange = NSMakeRange(0, text.count)
        let attributedText = NSMutableAttributedString(string: text)
        attributedText.addAttribute(NSAttributedString.Key.underlineStyle , value: NSUnderlineStyle.single.rawValue, range: textRange)
        // Add other attributes if needed
        self.attributedText = attributedText
        }
    }
}

Swift 3.0

class UnderlinedLabel: UILabel {
    
    override var text: String? {
        didSet {
            guard let text = text else { return }
            let textRange = NSMakeRange(0, text.characters.count)
            let attributedText = NSMutableAttributedString(string: text)
            attributedText.addAttribute(NSUnderlineStyleAttributeName , value: NSUnderlineStyle.styleSingle.rawValue, range: textRange)
            // Add other attributes if needed
            self.attributedText = attributedText
        }
    }
}

And you put your text like this :

@IBOutlet weak var label: UnderlinedLabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        label.text = "StringWithUnderLine"
    }

OLD:

Swift (2.0 to 2.3):

class UnderlinedLabel: UILabel {
    
    override var text: String? {
        didSet {
            guard let text = text else { return }
            let textRange = NSMakeRange(0, text.characters.count)
            let attributedText = NSMutableAttributedString(string: text)
            attributedText.addAttribute(NSUnderlineStyleAttributeName, value:NSUnderlineStyle.StyleSingle.rawValue, range: textRange)
            // Add other attributes if needed
            
            self.attributedText = attributedText
        }
    }
}

Swift 1.2:

class UnderlinedLabel: UILabel {
    
    override var text: String! {
        didSet {
            let textRange = NSMakeRange(0, count(text))
            let attributedText = NSMutableAttributedString(string: text)
            attributedText.addAttribute(NSUnderlineStyleAttributeName, value:NSUnderlineStyle.StyleSingle.rawValue, range: textRange)
            // Add other attributes if needed
            
            self.attributedText = attributedText
        }
    }
}

add class with JavaScript

I like to use a custom "foreach" function of sorts for these kinds of things:

function Each( objs, func )
{
    if ( objs.length ) for ( var i = 0, ol = objs.length, v = objs[ 0 ]; i < ol && func( v, i ) !== false; v = objs[ ++i ] );
    else for ( var p in objs ) if ( func( objs[ p ], p ) === false ) break;
}

(Can't remember where I found the above function, but it has been quite useful.)

Then after fetching your objects (to elements in this example) just do

Each( elements, function( element )
{
    element.addEventListener( "mouseover", function()
    {
        element.classList.add( "active" );
        //element.setAttribute( "class", "active" );
        element.setAttribute( "src", "newsource" );
    });

    // Remove class and new src after "mouseover" ends, if you wish.
    element.addEventListener( "mouseout", function()
    {
        element.classList.remove( "active" );
        element.setAttribute( "src", "originalsource" );
    });
});

classList is a simple way for handling elements' classes. Just needs a shim for a few browsers. If you must use setAttribute you must remember that whatever is set with it will overwrite the previous values.

EDIT: Forgot to mention that you need to use attachEvent instead of addEventListener on some IE versions. Test with if ( document.addEventListener ) {...}.

date format yyyy-MM-ddTHH:mm:ssZ

In C# 6+ you can use string interpolation and make this more terse:

$"{DateTime.UtcNow:s}Z"

Jquery set radio button checked, using id and class selectors

"...by a class and a div."

I assume when you say "div" you mean "id"? Try this:

$('#test2.test1').prop('checked', true);

No need to muck about with your [attributename=value] style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".

Or more generally to select an input where you want to specify a multiple attribute selector:

$('input:radio[class=test1][id=test2]').prop('checked', true);

That is, list each attribute with its own square brackets.

Note that unless you have a pretty old version of jQuery you should use .prop() rather than .attr() for this purpose.

Eclipse/Java code completion not working

Just in case anyone got to a desperate point where nothing works... It happened to us that the content assist somehow shrunk so no suggestion was shown, just the "Press Ctrl+Space for non-Java..." could be seen. So, it was just a matter of dragging the corner of the content assist to enlarge the pop-up.

I know, embarrassing. Hope it helps.

Note: this was an Ubuntu server with Xfce4 using Eclipse Oxygen.

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

First thing, define a type or interface for your object, it will make things much more readable:

type Product = { productId: number; price: number; discount: number };

You used a tuple of size one instead of array, it should look like this:

let myarray: Product[];
let priceListMap : Map<number, Product[]> = new Map<number, Product[]>();

So now this works fine:

myarray.push({productId : 1 , price : 100 , discount : 10});
myarray.push({productId : 2 , price : 200 , discount : 20});
myarray.push({productId : 3 , price : 300 , discount : 30});
priceListMap.set(1 , this.myarray);
myarray = null;

(code in playground)

Deep copy in ES6 using the spread syntax

From MDN

Note: Spread syntax effectively goes one level deep while copying an array. Therefore, it may be unsuitable for copying multidimensional arrays as the following example shows (it's the same with Object.assign() and spread syntax).

Personally, I suggest using Lodash's cloneDeep function for multi-level object/array cloning.

Here is a working example:

_x000D_
_x000D_
const arr1 = [{ 'a': 1 }];_x000D_
_x000D_
const arr2 = [...arr1];_x000D_
_x000D_
const arr3 = _.clone(arr1);_x000D_
_x000D_
const arr4 = arr1.slice();_x000D_
_x000D_
const arr5 = _.cloneDeep(arr1);_x000D_
_x000D_
const arr6 = [...{...arr1}]; // a bit ugly syntax but it is working!_x000D_
_x000D_
_x000D_
// first level_x000D_
console.log(arr1 === arr2); // false_x000D_
console.log(arr1 === arr3); // false_x000D_
console.log(arr1 === arr4); // false_x000D_
console.log(arr1 === arr5); // false_x000D_
console.log(arr1 === arr6); // false_x000D_
_x000D_
// second level_x000D_
console.log(arr1[0] === arr2[0]); // true_x000D_
console.log(arr1[0] === arr3[0]); // true_x000D_
console.log(arr1[0] === arr4[0]); // true_x000D_
console.log(arr1[0] === arr5[0]); // false_x000D_
console.log(arr1[0] === arr6[0]); // false
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
_x000D_
_x000D_
_x000D_

How do I embed a mp4 movie into my html?

If you have an mp4 video residing at your server, and you want the visitors to stream that over your HTML page.

<video width="480" height="320" controls="controls">
<source src="http://serverIP_or_domain/location_of_video.mp4" type="video/mp4">
</video>

WampServer: php-win.exe The program can't start because MSVCR110.dll is missing

Windows 10 x64 released August 2015 - same issue arising. MSVCR110.dll is also found in the sysWOW64 folder (which is where I found it, copying to system32 does not help). To resolve:

  1. uninstall the x86 versions of VC 11 vcredist_x64/86.exe for 2012 and 2013
  2. uninstall WAMP Server 2.5
  3. delete (maybe back up first) the WAMP folder
  4. restart windows
  5. reinstall WAMP 2.5

Hopefully like me you have a MySQL database backup handy!

Creating a segue programmatically

First of, suppose you have two different views in storyboard, and you want to navigate from one screen to another, so follow this steps:

1). Define all your views with class file and also storyboard id in identity inspector.

2). Make sure you add a navigation controller to the first view. Select it in the Storyboard and then Editor >Embed In > Navigation Controller

3). In your first class, import the "secondClass.h"

#import "ViewController.h
#import "secondController.h"

4). Add this command in the IBAction that has to perform the segue

secondController *next=[self.storyboard instantiateViewControllerWithIdentifier:@"second"];
[self.navigationController pushViewController:next animated:YES];

5). @"second" is secondview controller class, storyboard id.

Array of char* should end at '\0' or "\0"?

Null termination is a bad design pattern best left in the history books. There's still plenty of inertia behind c-strings, so it can't be avoided there. But there's no reason to use it in the OP's example.

Don't use any terminator, and use sizeof(array) / sizeof(array[0]) to get the number of elements.

Changing Shell Text Color (Windows)

Been looking into this for a while and not got any satisfactory answers, however...

1) ANSI escape sequences do work in a terminal on Linux

2) if you can tolerate a limited set of colo(u)rs try this:

print("hello", end=''); print("error", end='', file=sys.stderr); print("goodbye")

In idle "hello" and "goodbye" are in blue and "error" is in red.

Not fantastic, but good enough for now, and easy!

How to compare two JSON have the same properties without order?

We use the node-deep-equal project which implements the same deep-equal comparison as nodejs

A google serach for deep-equal on npm will show you many alternatives

R Apply() function on specific dataframe columns

I think what you want is mapply. You could apply the function to all columns, and then just drop the columns you don't want. However, if you are applying different functions to different columns, it seems likely what you want is mutate, from the dplyr package.

How to loop through all the files in a directory in c # .net?

try below code

Directory.GetFiles(txtFolderPath.Text, "*ProfileHandler.cs",SearchOption.AllDirectories)

How does inline Javascript (in HTML) work?

Try this in the console:

var div = document.createElement('div');

div.setAttribute('onclick', 'alert(event)');

div.onclick

In Chrome, it shows this:

function onclick(event) {
  alert(event)
}

...and the non-standard name property of div.onclick is "onclick".

So, whether or not this is anonymous depends your definition of "anonymous." Compare with something like var foo = new Function(), where foo.name is an empty string, and foo.toString() will produce something like

function anonymous() {

}

How to merge a transparent png image with another image using PIL

from PIL import Image

background = Image.open("test1.png")
foreground = Image.open("test2.png")

background.paste(foreground, (0, 0), foreground)
background.show()

First parameter to .paste() is the image to paste. Second are coordinates, and the secret sauce is the third parameter. It indicates a mask that will be used to paste the image. If you pass a image with transparency, then the alpha channel is used as mask.

Check the docs.

Time stamp in the C programming language

Use @Arkaitz Jimenez's code to get two timevals:

#include <sys/time.h>
//...
struct timeval tv1, tv2, diff;

// get the first time:
gettimeofday(&tv1, NULL);

// do whatever it is you want to time
// ...

// get the second time:
gettimeofday(&tv2, NULL);

// get the difference:

int result = timeval_subtract(&diff, &tv1, &tv2);

// the difference is storid in diff now.

Sample code for timeval_subtract can be found at this web site:

 /* Subtract the `struct timeval' values X and Y,
    storing the result in RESULT.
    Return 1 if the difference is negative, otherwise 0.  */

 int
 timeval_subtract (result, x, y)
      struct timeval *result, *x, *y;
 {
   /* Perform the carry for the later subtraction by updating y. */
   if (x->tv_usec < y->tv_usec) {
     int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
     y->tv_usec -= 1000000 * nsec;
     y->tv_sec += nsec;
   }
   if (x->tv_usec - y->tv_usec > 1000000) {
     int nsec = (x->tv_usec - y->tv_usec) / 1000000;
     y->tv_usec += 1000000 * nsec;
     y->tv_sec -= nsec;
   }

   /* Compute the time remaining to wait.
      tv_usec is certainly positive. */
   result->tv_sec = x->tv_sec - y->tv_sec;
   result->tv_usec = x->tv_usec - y->tv_usec;

   /* Return 1 if result is negative. */
   return x->tv_sec < y->tv_sec;
 }

How to increase memory limit for PHP over 2GB?

For unlimited memory limit set -1 in memory_limit variable:

ini_set('memory_limit', '-1');

Code coverage for Jest built on top of Jasmine

UPDATE: 7/20/2018 - Added links and updated name for coverageReporters.

UPDATE: 8/14/2017 - This answer is totally outdated. Just look at the Jest docs now. They have official support and documentation about how to do this.

@hankhsiao has got a forked repo where Istanbul is working with Jest. Add this to your dev dependencies

 "devDependencies": {
     "jest-cli": "git://github.com/hankhsiao/jest.git"
 }

Also make sure coverage is enabled in your package.json jest entry and you can also specify formats you want. (The html is pretty bad ass).

 "jest": {
     "collectCoverage": true,
     "coverageReporters": ["json", "html"],
 }

See Jest documentation for coverageReporters (default is ["json", "lcov", "text"])

Or add --coverage when you invoke jest.

How to get an Array with jQuery, multiple <input> with the same name

For multiple elements, you should give it a class rather than id eg:

<input type="text" class="task" name="task[]" />

Now you can get those using jquery something like this:

$('.task').each(function(){
   alert($(this).val());
});

What is Bootstrap?

It is an HTML, CSS, and JavaScript open-source framework (initially created by Twitter) that you can use as a basis for creating web sites or web applications.

Update

The official bootstrap website is updated and includes a clear definition.

"Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile first projects on the web."

"Designed and built with all the love in the world by @mdo and @fat."

git pull remote branch cannot find remote ref

You need to set your local branch to track the remote branch, which it won't do automatically if they have different capitalizations.

Try:

git branch --set-upstream downloadmanager origin/DownloadManager
git pull

UPDATE:

'--set-upstream' option is no longer supported.

git branch --set-upstream-to downloadmanager origin/DownloadManager
git pull

Python loop that also accesses previous and next values

Pythonic and elegant way:

objects = [1, 2, 3, 4, 5]
value = 3
if value in objects:
   index = objects.index(value)
   previous_value = objects[index-1]
   next_value = objects[index+1] if index + 1 < len(objects) else None

EXTRACT() Hour in 24 Hour format

select to_char(tran_datetime,'HH24') from test;

TO_CHAR(tran_datetime,'HH24')
------------------
16      

How to make a background 20% transparent on Android

Now Android Studio 3.3 and later version provide an inbuilt feature to change an Alpha value of the color,

Just click on a color in Android studio editor and provide Alpha value in percentage.

For more information see below image

enter image description here

Disable click outside of bootstrap modal area to close modal

This is the easiest one

You can define your modal behavior, defining data-keyboard and data-backdrop.

<div id="modal" class="modal hide fade in" data-keyboard="false" data-backdrop="static">

What is the difference between ng-if and ng-show/ng-hide

To note, a thing that happened to me now: ng-show does hide the content via css, yes, but it resulted in strange glitches in div's supposed to be buttons.

I had a card with two buttons on the bottom and depending on the actual state one is exchanged with an third, example edit button with new entry. Using ng-show=false to hide the left one(present first in the file) it happened that the following button ended up with the right border outside of the card. ng-if fixes that by not including the code at all. (Just checked here if there are some hidden surprises using ng-if instead of ng-show)

PHP Fatal error: Call to undefined function json_decode()

CENTOS

Scene

I installed PHP in Centos Docker, this is my DockerFile:

FROM centos:7.6.1810

LABEL maintainer="[email protected]"

RUN yum install httpd-2.4.6-88.el7.centos -y
RUN rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
RUN rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm
RUN yum install php72w -y
ENTRYPOINT ["/usr/sbin/httpd", "-D", "FOREGROUND"]

The app returned the same error with json_decode and json_encode

Resolution

Install PHP Common that has json_encode and json_decode

yum install -y php72w-common-7.2.14-1.w7.x86_64

How to find the resolution?

I have another Docker File what build the container for the API and it has the order to install php-mysql client:

yum install php72w-mysql.x86_64 -y

If i use these image to mount the app, the json_encode and json_decode works!! Ok..... What dependencies does this have?

[root@c023b46b720c etc]# yum install php72w-mysql.x86_64
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
 * base: mirror.gtdinternet.com
 * epel: mirror.globo.com
 * extras: linorg.usp.br
 * updates: mirror.gtdinternet.com
 * webtatic: us-east.repo.webtatic.com
Resolving Dependencies
--> Running transaction check
---> Package php72w-mysql.x86_64 0:7.2.14-1.w7 will be installed
--> Processing Dependency: php72w-pdo(x86-64) for package: php72w-mysql-7.2.14-1.w7.x86_64
--> Processing Dependency: libmysqlclient.so.18(libmysqlclient_18)(64bit) for package: php72w-mysql-7.2.14-1.w7.x86_64
--> Processing Dependency: libmysqlclient.so.18()(64bit) for package: php72w-mysql-7.2.14-1.w7.x86_64
--> Running transaction check
---> Package mariadb-libs.x86_64 1:5.5.60-1.el7_5 will be installed
---> Package php72w-pdo.x86_64 0:7.2.14-1.w7 will be installed
--> Processing Dependency: php72w-common(x86-64) = 7.2.14-1.w7 for package: php72w-pdo-7.2.14-1.w7.x86_64
--> Running transaction check
---> Package php72w-common.x86_64 0:7.2.14-1.w7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

========================================================================================================
 Package                   Arch               Version                        Repository            Size
========================================================================================================
Installing:
 php72w-mysql              x86_64             7.2.14-1.w7                    webtatic              82 k
Installing for dependencies:
 mariadb-libs              x86_64             1:5.5.60-1.el7_5               base                 758 k
 php72w-common             x86_64             7.2.14-1.w7                    webtatic             1.3 M
 php72w-pdo                x86_64             7.2.14-1.w7                    webtatic              89 k

Transaction Summary
========================================================================================================
Install  1 Package (+3 Dependent packages)

Total download size: 2.2 M
Installed size: 17 M
Is this ok [y/d/N]: y
Downloading packages:
(1/4): mariadb-libs-5.5.60-1.el7_5.x86_64.rpm                                    | 758 kB  00:00:00     
(2/4): php72w-mysql-7.2.14-1.w7.x86_64.rpm                                       |  82 kB  00:00:01     
(3/4): php72w-pdo-7.2.14-1.w7.x86_64.rpm                                         |  89 kB  00:00:01     
(4/4): php72w-common-7.2.14-1.w7.x86_64.rpm                                      | 1.3 MB  00:00:06     
--------------------------------------------------------------------------------------------------------
Total                                                                   336 kB/s | 2.2 MB  00:00:06     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : 1:mariadb-libs-5.5.60-1.el7_5.x86_64                                                 1/4 
  Installing : php72w-common-7.2.14-1.w7.x86_64                                                     2/4 
  Installing : php72w-pdo-7.2.14-1.w7.x86_64                                                        3/4 
  Installing : php72w-mysql-7.2.14-1.w7.x86_64                                                      4/4 
  Verifying  : php72w-common-7.2.14-1.w7.x86_64                                                     1/4 
  Verifying  : 1:mariadb-libs-5.5.60-1.el7_5.x86_64                                                 2/4 
  Verifying  : php72w-pdo-7.2.14-1.w7.x86_64                                                        3/4 
  Verifying  : php72w-mysql-7.2.14-1.w7.x86_64                                                      4/4 

Installed:
  php72w-mysql.x86_64 0:7.2.14-1.w7                                                                     

Dependency Installed:
  mariadb-libs.x86_64 1:5.5.60-1.el7_5                php72w-common.x86_64 0:7.2.14-1.w7               
  php72w-pdo.x86_64 0:7.2.14-1.w7                    

Complete!

Yes! Inside the dependences is the common packages. I Installed it into my other container and it works! After, i put de directive into DockerFile, Git commit!! Git Tag!!!! Git Push!!!! Ready!

How to stretch in width a WPF user control to its window?

Instead use Width and Height in user controls, use MinHeight and MinWidth. Then you can configure the UC well, and will be able to stretch inside other window.

Well, as Im seeing in WPF Microsoft made a re-thinking about windows properties and behaviors, but so far, I didn't miss anything from olds windows forms, in WPF the controls are there, but in a new point of view.

How to get VM arguments from inside of Java application?

I found that HotSpot lists all the VM arguments in the management bean except for -client and -server. Thus, if you infer the -client/-server argument from the VM name and add this to the runtime management bean's list, you get the full list of arguments.

Here's the SSCCE:

import java.util.*;
import java.lang.management.ManagementFactory;

class main {
  public static void main(final String[] args) {
    System.out.println(fullVMArguments());
  }

  static String fullVMArguments() {
    String name = javaVmName();
    return (contains(name, "Server") ? "-server "
      : contains(name, "Client") ? "-client " : "")
      + joinWithSpace(vmArguments());
  }

  static List<String> vmArguments() {
    return ManagementFactory.getRuntimeMXBean().getInputArguments();
  }

  static boolean contains(String s, String b) {
    return s != null && s.indexOf(b) >= 0;
  }

  static String javaVmName() {
    return System.getProperty("java.vm.name");
  }

  static String joinWithSpace(Collection<String> c) {
    return join(" ", c);
  }

  public static String join(String glue, Iterable<String> strings) {
    if (strings == null) return "";
    StringBuilder buf = new StringBuilder();
    Iterator<String> i = strings.iterator();
    if (i.hasNext()) {
      buf.append(i.next());
      while (i.hasNext())
        buf.append(glue).append(i.next());
    }
    return buf.toString();
  }
}

Could be made shorter if you want the arguments in a List<String>.

Final note: We might also want to extend this to handle the rare case of having spaces within command line arguments.

How do I load an HTML page in a <div> using JavaScript?

This is usually needed when you want to include header.php or whatever page.

In Java it's easy especially if you have HTML page and don't want to use php include function but at all you should write php function and add it as Java function in script tag.

In this case you should write it without function followed by name Just. Script rage the function word and start the include header.php I.e convert the php include function to Java function in script tag and place all your content in that included file.

How to run a PowerShell script without displaying a window?

Here is a working solution in windows 10 that does not include any third-party components. It works by wrapping the PowerShell script into VBScript.

Step 1: we need to change some windows features to allow VBScript to run PowerShell and to open .ps1 files with PowerShell by default.

-go to run and type "regedit". Click on ok and then allow it to run.

-paste this path "HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell" and press enter.

-now open the entry on the right and change the value to 0.

-open PowerShell as an administrator and type "Set-ExecutionPolicy -ExecutionPolicy RemoteSigned", press enter and confirm the change with "y" and then enter.

Step 2: Now we can start wrapping our script.

-save your Powershell script as a .ps1 file.

-create a new text document and paste this script.

Dim objShell,objFSO,objFile

Set objShell=CreateObject("WScript.Shell")
Set objFSO=CreateObject("Scripting.FileSystemObject")

'enter the path for your PowerShell Script
 strPath="c:\your script path\script.ps1"

'verify file exists
 If objFSO.FileExists(strPath) Then
   'return short path name
   set objFile=objFSO.GetFile(strPath)
   strCMD="powershell -nologo -command " & Chr(34) & "&{" &_
    objFile.ShortPath & "}" & Chr(34)
   'Uncomment next line for debugging
   'WScript.Echo strCMD

  'use 0 to hide window
   objShell.Run strCMD,0

Else

  'Display error message
   WScript.Echo "Failed to find " & strPath
   WScript.Quit

End If

-now change the file path to the location of your .ps1 script and save the text document.

-Now right-click on the file and go to rename. Then change the filename extension to .vbs and press enter and then click ok.

DONE! If you now open the .vbs you should see no console window while your script is running in the background.

make sure to upvote if this worked for you!

Best way to check if object exists in Entity Framework?

Why not do it?

var result= ctx.table.Where(x => x.UserName == "Value").FirstOrDefault();

if(result?.field == value)
{
  // Match!
}

How do I use Linq to obtain a unique list of properties from a list of objects?

When taking Distinct we have to cast into IEnumerable too. If list is model means, need to write code like this

 IEnumerable<T> ids = list.Select(x => x).Distinct();

Usage of $broadcast(), $emit() And $on() in AngularJS

  • Broadcast: We can pass the value from parent to child (i.e parent -> child controller.)
  • Emit: we can pass the value from child to parent (i.e.child ->parent controller.)
  • On: catch the event dispatched by $broadcast or $emit.

jQuery show/hide not working

if (grid.selectedKeyNames().length > 0) {
            $('#btnRemoveFromList').show();
        } else {
            $('#btnRemoveFromList').hide();
        }

}

() - calls the method

no parentheses - returns the property

How do I check if an integer is even or odd?

int isOdd(int i){
  return(i % 2);
}

done.

How to uninstall Golang?

sudo apt-get remove golang-go
sudo apt-get remove --auto-remove golang-go

This is perfect for Ubuntu 18.18

How to enable C++11/C++0x support in Eclipse CDT?

  • right-click the project and go to "Properties"
  • C/C++ Build -> Settings -> Tool Settings -> GCC C++ Compiler -> Miscellaneous -> Other Flags. Put -lm at the end of other flags text box and OK.

How to use onClick() or onSelect() on option tag in a JSP page?

Other option, for similar example but with anidated selects, think that you have two select, the name of the first is "ea_pub_dest" and the name of the second is "ea_pub_dest_2", ok, now take the event click of the first and display the second.

<script>

function test()
{
    value = document.getElementById("ea_pub_dest").value;
    if ( valor == "value_1" )
        document.getElementById("ea_pub_dest_nivel").style.display = "block";
}
</script>

Unable to capture screenshot. Prevented by security policy. Galaxy S6. Android 6.0

Go to Phone Settings --> Developer Options --> Simulate Secondary Displays and turn it to None. If you don't see Developer Options in the settings menu (it should be at the bottom, go Settings ==> About phone and tap on the Build number a lot of times)

How do I vertically align text in a div?

If you need to use with the min-height property you must add this CSS on:

.outerContainer .innerContainer {
    height: 0;
    min-height: 100px;
}

SVN Repository on Google Drive or DropBox

For free private SVN hosting try the following:

Or use BitBucket for free private git/mercurial repositories

Fill remaining vertical space - only CSS

Have you tried changing the wrapper height to vh instead of %?

#wrapper {
width:300px;
height:100vh;
}

That worked great for me when I wanted to fill my page with a gradient background for instance...

How to get the Parent's parent directory in Powershell?

You can simply chain as many split-path as you need:

$rootPath = $scriptPath | split-path | split-path

Adding VirtualHost fails: Access Forbidden Error 403 (XAMPP) (Windows 7)

I'm using XAMPP 1.6.7 on Windows 7. This article worked for me.

I added the following lines in the file httpd-vhosts.conf at C:/xampp/apache/conf/extra.
I had also uncommented the line # NameVirtualHost *:80

<VirtualHost mysite.dev:80>
    DocumentRoot "C:/xampp/htdocs/mysite"
    ServerName mysite.dev
    ServerAlias mysite.dev
    <Directory "C:/xampp/htdocs/mysite">
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

After restarting the apache, it were still not working. Then I had to follow the step 9 mentioned in the article by editing the file C:/Windows/System32/drivers/etc/hosts.

# localhost name resolution is handled within DNS itself.
     127.0.0.1       localhost
     ::1             localhost
     127.0.0.1       mysite.dev  

Then I got working http://mysite.dev

What is the difference between dict.items() and dict.iteritems() in Python2?

dict.iteritems is gone in Python3.x So use iter(dict.items()) to get the same output and memory alocation

Open an html page in default browser with VBA?

You can use the Windows API function ShellExecute to do so:

Option Explicit

Private Declare Function ShellExecute _
  Lib "shell32.dll" Alias "ShellExecuteA" ( _
  ByVal hWnd As Long, _
  ByVal Operation As String, _
  ByVal Filename As String, _
  Optional ByVal Parameters As String, _
  Optional ByVal Directory As String, _
  Optional ByVal WindowStyle As Long = vbMinimizedFocus _
  ) As Long

Public Sub OpenUrl()

    Dim lSuccess As Long
    lSuccess = ShellExecute(0, "Open", "www.google.com")

End Sub

Just a short remark concerning security: If the URL comes from user input make sure to strictly validate that input as ShellExecute would execute any command with the user's permissions, also a format c: would be executed if the user is an administrator.

Karma: Running a single test file from command line

First you need to start karma server with

karma start

Then, you can use grep to filter a specific test or describe block:

karma run -- --grep=testDescriptionFilter

sqldeveloper error message: Network adapter could not establish the connection error

I had this error after fresh Oracle installation.

To fix this I've launched Net configuration assistant (from start menu or netca.bat in the bin folder) and simply added a Listener.

How do I check whether an array contains a string in TypeScript?

The same as in JavaScript, using Array.prototype.indexOf():

console.log(channelArray.indexOf('three') > -1);

Or using ECMAScript 2016 Array.prototype.includes():

console.log(channelArray.includes('three'));

Note that you could also use methods like showed by @Nitzan to find a string. However you wouldn't usually do that for a string array, but rather for an array of objects. There those methods were more sensible. For example

const arr = [{foo: 'bar'}, {foo: 'bar'}, {foo: 'baz'}];
console.log(arr.find(e => e.foo === 'bar')); // {foo: 'bar'} (first match)
console.log(arr.some(e => e.foo === 'bar')); // true
console.log(arr.filter(e => e.foo === 'bar')); // [{foo: 'bar'}, {foo: 'bar'}]

Reference

Array.find()

Array.some()

Array.filter()

Changing WPF title bar background color

Here's an example on how to achieve this:

    <Grid DockPanel.Dock="Right"
      HorizontalAlignment="Right">

        <StackPanel Orientation="Horizontal"
                HorizontalAlignment="Right"
                VerticalAlignment="Center">

            <Button x:Name="MinimizeButton"
                KeyboardNavigation.IsTabStop="False"
                Click="MinimizeWindow"
                Style="{StaticResource MinimizeButton}" 
                Template="{StaticResource MinimizeButtonControlTemplate}" />

            <Button x:Name="MaximizeButton"
                KeyboardNavigation.IsTabStop="False"
                Click="MaximizeClick"
                Style="{DynamicResource MaximizeButton}" 
                Template="{DynamicResource MaximizeButtonControlTemplate}" />

            <Button x:Name="CloseButton"
                KeyboardNavigation.IsTabStop="False"
                Command="{Binding ApplicationCommands.Close}"
                Style="{DynamicResource CloseButton}" 
                Template="{DynamicResource CloseButtonControlTemplate}"/>

        </StackPanel>
    </Grid>
</DockPanel>

Handle Click Events in the code-behind.

For MouseDown -

App.Current.MainWindow.DragMove();

For Minimize Button -

App.Current.MainWindow.WindowState = WindowState.Minimized;

For DoubleClick and MaximizeClick

if (App.Current.MainWindow.WindowState == WindowState.Maximized)
{
    App.Current.MainWindow.WindowState = WindowState.Normal;
}
else if (App.Current.MainWindow.WindowState == WindowState.Normal)
{
    App.Current.MainWindow.WindowState = WindowState.Maximized;
}

how to add value to combobox item

Now you can use insert method instead add

' Visual Basic
CheckedListBox1.Items.Insert(0, "Copenhagen")

GC overhead limit exceeded

From Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning

the following

Excessive GC Time and OutOfMemoryError

The concurrent collector will throw an OutOfMemoryError if too much time is being spent in garbage collection: if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, an OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.

The policy is the same as that in the parallel collector, except that time spent performing concurrent collections is not counted toward the 98% time limit. In other words, only collections performed while the application is stopped count toward excessive GC time. Such collections are typically due to a concurrent mode failure or an explicit collection request (e.g., a call to System.gc()).

in conjunction with a passage further down

One of the most commonly encountered uses of explicit garbage collection occurs with RMIs distributed garbage collection (DGC). Applications using RMI refer to objects in other virtual machines. Garbage cannot be collected in these distributed applications without occasionally collection the local heap, so RMI forces full collections periodically. The frequency of these collections can be controlled with properties. For example,

java -Dsun.rmi.dgc.client.gcInterval=3600000

-Dsun.rmi.dgc.server.gcInterval=3600000 specifies explicit collection once per hour instead of the default rate of once per minute. However, this may also cause some objects to take much longer to be reclaimed. These properties can be set as high as Long.MAX_VALUE to make the time between explicit collections effectively infinite, if there is no desire for an upper bound on the timeliness of DGC activity.

Seems to imply that the evaluation period for determining the 98% is one minute long, but it might be configurable on Sun's JVM with the correct define.

Of course, other interpretations are possible.

Using JQuery to check if no radio button in a group has been checked

Use .length refer to http://api.jquery.com/checked-selector/

if ($('input[name="html_elements"]:checked').length === 0) alert("Not checked");
else alert("Checked");

Set value of hidden field in a form using jQuery's ".val()" doesn't work

$('input[name=hidden_field_name]').val('newVal');

worked for me, when neither

$('input[id=hidden_field_id]').val('newVal');

nor

$('#hidden_field_id').val('newVal');

did.

Python error when trying to access list by index - "List indices must be integers, not str"

A list is a chain of spaces that can be indexed by (0, 1, 2 .... etc). So if players was a list, players[0] or players[1] would have worked. If players is a dictionary, players["name"] would have worked.

How to change the pop-up position of the jQuery DatePicker control

.ui-datepicker {-ms-transform: translate(100px,100px); -webkit-transform: translate(100px,100px); transform: translate(100px,100px);}

Editable text to string

Based on this code (which you provided in response to Alex's answer):

Editable newTxt=(Editable)userName1.getText(); 
String newString = newTxt.toString();

It looks like you're trying to get the text out of a TextView or EditText. If that's the case then this should work:

String newString = userName1.getText().toString(); 

Convert a Map<String, String> to a POJO

if you have generic types in your class you should use TypeReference with convertValue().

final ObjectMapper mapper = new ObjectMapper();
final MyPojo<MyGenericType> pojo = mapper.convertValue(map, new TypeReference<MyPojo<MyGenericType>>() {});

Also you can use that to convert a pojo to java.util.Map back.

final ObjectMapper mapper = new ObjectMapper();
final Map<String, Object> map = mapper.convertValue(pojo, new TypeReference<Map<String, Object>>() {});

Transaction isolation levels relation with locks on table

I want to understand the lock each transaction isolation takes on the table

For example, you have 3 concurrent processes A, B and C. A starts a transaction, writes data and commit/rollback (depending on results). B just executes a SELECT statement to read data. C reads and updates data. All these process work on the same table T.

  • READ UNCOMMITTED - no lock on the table. You can read data in the table while writing on it. This means A writes data (uncommitted) and B can read this uncommitted data and use it (for any purpose). If A executes a rollback, B still has read the data and used it. This is the fastest but most insecure way to work with data since can lead to data holes in not physically related tables (yes, two tables can be logically but not physically related in real-world apps =\).
  • READ COMMITTED - lock on committed data. You can read the data that was only committed. This means A writes data and B can't read the data saved by A until A executes a commit. The problem here is that C can update data that was read and used on B and B client won't have the updated data.
  • REPEATABLE READ - lock on a block of SQL(which is selected by using select query). This means B reads the data under some condition i.e. WHERE aField > 10 AND aField < 20, A inserts data where aField value is between 10 and 20, then B reads the data again and get a different result.
  • SERIALIZABLE - lock on a full table(on which Select query is fired). This means, B reads the data and no other transaction can modify the data on the table. This is the most secure but slowest way to work with data. Also, since a simple read operation locks the table, this can lead to heavy problems on production: imagine that T table is an Invoice table, user X wants to know the invoices of the day and user Y wants to create a new invoice, so while X executes the read of the invoices, Y can't add a new invoice (and when it's about money, people get really mad, especially the bosses).

I want to understand where we define these isolation levels: only at JDBC/hibernate level or in DB also

Using JDBC, you define it using Connection#setTransactionIsolation.

Using Hibernate:

<property name="hibernate.connection.isolation">2</property>

Where

  • 1: READ UNCOMMITTED
  • 2: READ COMMITTED
  • 4: REPEATABLE READ
  • 8: SERIALIZABLE

Hibernate configuration is taken from here (sorry, it's in Spanish).

By the way, you can set the isolation level on RDBMS as well:

and on and on...

How to print instances of a class using print()?

>>> class Test:
...     def __repr__(self):
...         return "Test()"
...     def __str__(self):
...         return "member of Test"
... 
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test

The __str__ method is what happens when you print it, and the __repr__ method is what happens when you use the repr() function (or when you look at it with the interactive prompt). If this isn't the most Pythonic method, I apologize, because I'm still learning too - but it works.

If no __str__ method is given, Python will print the result of __repr__ instead. If you define __str__ but not __repr__, Python will use what you see above as the __repr__, but still use __str__ for printing.

How can you determine a point is between two other points on a line segment?

Here is my solution with C# in Unity.

private bool _isPointOnLine( Vector2 ptLineStart, Vector2 ptLineEnd, Vector2 ptPoint )
{
    bool bRes = false;
    if((Mathf.Approximately(ptPoint.x, ptLineStart.x) || Mathf.Approximately(ptPoint.x, ptLineEnd.x)))
    {
        if(ptPoint.y > ptLineStart.y && ptPoint.y < ptLineEnd.y)
        {
            bRes = true;
        }
    }
    else if((Mathf.Approximately(ptPoint.y, ptLineStart.y) || Mathf.Approximately(ptPoint.y, ptLineEnd.y)))
    {
        if(ptPoint.x > ptLineStart.x && ptPoint.x < ptLineEnd.x)
        {
            bRes = true;
        }
    }
    return bRes;
}

How to specify new GCC path for CMake

An alternative solution is to configure your project through cmake-gui, starting from a clean build directory. Among the options you have available at the beginning, there's the possibility to choose the exact path to the compilers

How to impose maxlength on textArea in HTML using JavaScript

Small problem with code above is that val() does not trigger change() event, so if you using backbone.js (or another frameworks for model binding), model won't be updated.

I'm posting the solution worked great for me.

$(function () {

    $(document).on('keyup', '.ie8 textarea[maxlength], .ie9 textarea[maxlength]', function (e) {
        var maxLength = $(this).attr('maxlength');
        if (e.keyCode > 47 && $(this).val().length >= maxLength) {
            $(this).val($(this).val().substring(0, maxLength)).trigger('change');
        }
        return true;
    });

});

Add a CSS border on hover without moving the element

add margin:-1px; which reduces 1px to each side. or if you need only for side you can do margin-left:-1px etc.

Scp command syntax for copying a folder from local machine to a remote server

In stall PuTTY in our system and set the environment variable PATH Pointing to putty path. open the command prompt and move to putty folder. Using PSCP command

Please check this

how to call a method in another Activity from Activity

public class ActivityB extends AppCompatActivity {

static Context mContext;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_b);

    try {

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String texto = bundle.getString("message");
            if (texto != null) {
              //code....
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void launch(String message) {
        Intent intent = new Intent(mContext, ActivityB.class);
        intent.putExtra("message", message);
        mContext.startActivity(intent);
    }
}

In ActivityA or Service.

public class Service extends Service{

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {    

        String text = "Value to send";
        ActivityB.launch(text);
        Log.d(TAG, text);
    }
}

What's the best way to do a backwards loop in C/C#/C++?

In C# using Linq:

foreach(var item in myArray.Reverse())
{
    // do something
}

Crystal Reports - Adding a parameter to a 'Command' query

Try this:

Select Project_Name, ReleaseDate, TaskName
From DB_Table
Where Project_Name like '{?Pm-?Proj_Name}'
  And ReleaseDate >= currentdate

currentdate should be a valid database function or field to work. If you are using MS SQL Server, use GETDATE() instead.

If all you want is to filter records in a subreport based on a parameter from the main report, it might be easier to simply add the table to the subreport, and then create a Project_Name link between the main report and subreport. You can then use the Select Expert to filter the ReleaseDate as well.

CSS background image alt attribute

In this Yahoo Developer Network (archived link) article it is suggested that if you absolutely must use a background-image instead of img element and alt attribute, use ARIA attributes as follows:

<div role="img" aria-label="adorable puppy playing on the grass">
  ...
</div>

The use case in the article describes how Flickr chose to use background images because performance was greatly improved on mobile devices.

How do I stop a program when an exception is raised in Python?

You can stop catching the exception, or - if you need to catch it (to do some custom handling), you can re-raise:

try:
  doSomeEvilThing()
except Exception, e:
  handleException(e)
  raise

Note that typing raise without passing an exception object causes the original traceback to be preserved. Typically it is much better than raise e.

Of course - you can also explicitly call

import sys 
sys.exit(exitCodeYouFindAppropriate)

This causes SystemExit exception to be raised, and (unless you catch it somewhere) terminates your application with specified exit code.

How to get certain commit from GitHub project

Instead of navigating through the commits, you can also hit the y key (Github Help, Keyboard Shortcuts) to get the "permalink" for the current revision / commit.
This will change the URL from https://github.com/<user>/<repository> (master / HEAD) to https://github.com/<user>/<repository>/tree/<commit id>.

In order to download the specific commit, you'll need to reload the page from that URL, so the Clone or Download button will point to the "snapshot" https://github.com/<user>/<repository>/archive/<commit id>.zip instead of the latest https://github.com/<user>/<repository>/archive/master.zip.

npm start error with create-react-app

It occurred to me but none of the above worked.

events.js:72
        throw er; // Unhandled 'error' event
              ^

npm ERR! [email protected] start: `react-scripts start`
npm ERR! spawn ENOENT

Error: spawn ENOENT
    at errnoException (child_process.js:1000:11)
    at Process.ChildProcess._handle.onexit (child_process.js:791:34)

This happens because you might have installed react-scripts globally.

To make this work...

  1. Go to your C:\Users\<USER>\AppData\Roaming
  2. Delete npm and npm-cache directories... (don't worry you can install npm globally later)
  3. Go back to your application directory and remove node_modules folder
  4. Now enter npm install to install the dependencies (delete package-lock.json if its already created)
  5. Now run npm install --save react react-dom react-scripts
  6. Get it started with npm start

This should get you back on track... Happy Coding

Node.js fs.readdir recursive directory search

This is my answer. Hope it can help somebody.

My focus is to make the searching routine can stop at anywhere, and for a file found, tells the relative depth to the original path.

var _fs = require('fs');
var _path = require('path');
var _defer = process.nextTick;

// next() will pop the first element from an array and return it, together with
// the recursive depth and the container array of the element. i.e. If the first
// element is an array, it'll be dug into recursively. But if the first element is
// an empty array, it'll be simply popped and ignored.
// e.g. If the original array is [1,[2],3], next() will return [1,0,[[2],3]], and
// the array becomes [[2],3]. If the array is [[[],[1,2],3],4], next() will return
// [1,2,[2]], and the array becomes [[[2],3],4].
// There is an infinity loop `while(true) {...}`, because I optimized the code to
// make it a non-recursive version.
var next = function(c) {
    var a = c;
    var n = 0;
    while (true) {
        if (a.length == 0) return null;
        var x = a[0];
        if (x.constructor == Array) {
            if (x.length > 0) {
                a = x;
                ++n;
            } else {
                a.shift();
                a = c;
                n = 0;
            }
        } else {
            a.shift();
            return [x, n, a];
        }
    }
}

// cb is the callback function, it have four arguments:
//    1) an error object if any exception happens;
//    2) a path name, may be a directory or a file;
//    3) a flag, `true` means directory, and `false` means file;
//    4) a zero-based number indicates the depth relative to the original path.
// cb should return a state value to tell whether the searching routine should
// continue: `true` means it should continue; `false` means it should stop here;
// but for a directory, there is a third state `null`, means it should do not
// dig into the directory and continue searching the next file.
var ls = function(path, cb) {
    // use `_path.resolve()` to correctly handle '.' and '..'.
    var c = [ _path.resolve(path) ];
    var f = function() {
        var p = next(c);
        p && s(p);
    };
    var s = function(p) {
        _fs.stat(p[0], function(err, ss) {
            if (err) {
                // use `_defer()` to turn a recursive call into a non-recursive call.
                cb(err, p[0], null, p[1]) && _defer(f);
            } else if (ss.isDirectory()) {
                var y = cb(null, p[0], true, p[1]);
                if (y) r(p);
                else if (y == null) _defer(f);
            } else {
                cb(null, p[0], false, p[1]) && _defer(f);
            }
        });
    };
    var r = function(p) {
        _fs.readdir(p[0], function(err, files) {
            if (err) {
                cb(err, p[0], true, p[1]) && _defer(f);
            } else {
                // not use `Array.prototype.map()` because we can make each change on site.
                for (var i = 0; i < files.length; i++) {
                    files[i] = _path.join(p[0], files[i]);
                }
                p[2].unshift(files);
                _defer(f);
            }
        });
    }
    _defer(f);
};

var printfile = function(err, file, isdir, n) {
    if (err) {
        console.log('-->   ' + ('[' + n + '] ') + file + ': ' + err);
        return true;
    } else {
        console.log('... ' + ('[' + n + '] ') + (isdir ? 'D' : 'F') + ' ' + file);
        return true;
    }
};

var path = process.argv[2];
ls(path, printfile);

PHP Pass by reference in foreach

I had to spend a few hours to figure out why a[3] is changing on each iteration. This is the explanation at which I arrived.

There are two types of variables in PHP: normal variables and reference variables. If we assign a reference of a variable to another variable, the variable becomes a reference variable.

for example in

$a = array('zero', 'one', 'two', 'three');

if we do

$v = &$a[0]

the 0th element ($a[0]) becomes a reference variable. $v points towards that variable; therefore, if we make any change to $v, it will be reflected in $a[0] and vice versa.

now if we do

$v = &$a[1]

$a[1] will become a reference variable and $a[0] will become a normal variable (Since no one else is pointing to $a[0] it is converted to a normal variable. PHP is smart enough to make it a normal variable when no one else is pointing towards it)

This is what happens in the first loop

foreach ($a as &$v) {

}

After the last iteration $a[3] is a reference variable.

Since $v is pointing to $a[3] any change to $v results in a change to $a[3]

in the second loop,

foreach ($a as $v) {
  echo $v.'-'.$a[3].PHP_EOL;
}

in each iteration as $v changes, $a[3] changes. (because $v still points to $a[3]). This is the reason why $a[3] changes on each iteration.

In the iteration before the last iteration, $v is assigned the value 'two'. Since $v points to $a[3], $a[3] now gets the value 'two'. Keep this in mind.

In the last iteration, $v (which points to $a[3]) now has the value of 'two', because $a[3] was set to two in the previous iteration. two is printed. This explains why 'two' is repeated when $v is printed in the last iteration.

Eclipse Intellisense?

If it's not working even when you already have Code Assist enabled, Eclipse's configuration files are probably corrupt. A solution that worked for me (on Eclipse 3.5.2) was to:

  1. Close Eclipse.
  2. Rename the workspace directory.
  3. Start Eclipse. (This creates a new workspace directory.)
  4. Import (with copy) the Java projects from the old workspace.

How to catch integer(0)?

Maybe off-topic, but R features two nice, fast and empty-aware functions for reducing logical vectors -- any and all:

if(any(x=='dolphin')) stop("Told you, no mammals!")

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

For anyone interested in a shorter way:

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

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

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

How to correctly write async method?

You are calling DoDownloadAsync() but you don't wait it. So your program going to the next line. But there is another problem, Async methods should return Task or Task<T>, if you return nothing and you want your method will be run asyncronously you should define your method like this:

private static async Task DoDownloadAsync()     {         WebClient w = new WebClient();          string txt = await w.DownloadStringTaskAsync("http://www.google.com/");         Debug.WriteLine(txt);     } 

And in Main method you can't await for DoDownloadAsync, because you can't use await keyword in non-async function, and you can't make Main async. So consider this:

var result = DoDownloadAsync();  Debug.WriteLine("DoDownload done"); result.Wait(); 

Excel Validation Drop Down list using VBA

You are defining your array as xlValidateList(), so when you try to assign the type, it gets confused as to what you are trying to assign to the type.

Instead, try this:

Dim MyList(5) As String
MyList(0) = 1
MyList(1) = 2
MyList(2) = 3
MyList(3) = 4
MyList(4) = 5
MyList(5) = 6

With Range("A1").Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
         Operator:=xlBetween, Formula1:=Join(MyList, ",")
End With

What does 'git blame' do?

From git-blame:

Annotates each line in the given file with information from the revision which last modified the line. Optionally, start annotating from the given revision.

When specified one or more times, -L restricts annotation to the requested lines.

Example:

[email protected]:~# git blame .htaccess
...
^e1fb2d7 (John Doe 2015-07-03 06:30:25 -0300  4) allow from all
^72fgsdl (Arthur King 2015-07-03 06:34:12 -0300  5)
^e1fb2d7 (John Doe 2015-07-03 06:30:25 -0300  6) <IfModule mod_rewrite.c>
^72fgsdl (Arthur King 2015-07-03 06:34:12 -0300  7)     RewriteEngine On
...

Please note that git blame does not show the per-line modifications history in the chronological sense. It only shows who was the last person to have changed a line in a document up to the last commit in HEAD.

That is to say that in order to see the full history/log of a document line, you would need to run a git blame path/to/file for each commit in your git log.

Linq : select value in a datatable column

Use linq and set the data table as Enumerable and select the fields from the data table field that matches what you are looking for.

Example

I want to get the currency Id and currency Name from the currency table where currency is local currency, and assign the currency id and name to a text boxes on the form:

DataTable dt = curData.loadCurrency();
            var curId = from c in dt.AsEnumerable()
                        where c.Field<bool>("LocalCurrency") == true
                        select c.Field<int>("CURID");

            foreach (int cid in curId)
            {
                txtCURID.Text = cid.ToString();
            }
            var curName = from c in dt.AsEnumerable()
                          where c.Field<bool>("LocalCurrency") == true
                          select c.Field<string>("CurName");
            foreach (string cName in curName)
            {
                txtCurrency.Text = cName.ToString();
            }

Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3

No-one of safe solution work for me so to be safer than Neeraj and easier than Matthew just add: System.Web.HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

In your controller's method. That work for me.

public IHttpActionResult Get()
{
    System.Web.HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
    return Ok("value");
}

PHP reindex array?

This might not be the simplest answer as compared to using array_values().

Try this

$array = array( 0 => 'string1', 2 => 'string2', 4 => 'string3', 5 => 'string4');
$arrays =$array;
print_r($array);
$array=array();
$i=0;
    foreach($arrays as $k => $item)
    {
    $array[$i]=$item;
        unset($arrays[$k]);
        $i++;

    }

print_r($array);

Demo

jQuery Set Select Index

Shortly:

$("#selectBox").attr("selectedIndex",index)

where index is the selected index as integer.

How to change or add theme to Android Studio?

(Note: the exact paths shown here are primarily for Windows and Linux. I know Mac has a few non-standard paths, so if you're on Mac, you may have to adjust the starting bit of the path. The point is, get into settings however you'd do that on a Mac)

Switch theme:

File -> Settings-> Appearance & behavior -> Appearance.

Select the "theme" dropdown, and change between whatever themes you have installed. It shows the default themes and any you have installed in the form of plugins.

Install new themes

As plugin from plugins.jetbrains.com

File-> Settings -> plugins -> install JetBrains plugin/browse repositories/install plugin from disk

Note: newer versions of Android Studio, and possibly IntelliJ, (at least Jan. 2021 and out) may instead have a Marketplace tab in place of the first and/or second one.

The last part has three different options. The first has a few amount of plugins, and looks like only the official plugins. Browse repositories have much more plugins, and seems to be like going to the plugin page. This is a shorter way than going to the intelliJ plugin page and downloading the plugins manually. If you download, click install plugin from disk. This allows you to drag and drop, or find .jar files.

In the install JetBrains plugins, browse repositories, and (newer versions) Marketplace tabs should have a search functionality. You can search for i.e. "theme" from there.

Edit existing excel workbooks and sheets with xlrd and xlwt

As I wrote in the edits of the op, to edit existing excel documents you must use the xlutils module (Thanks Oliver)

Here is the proper way to do it:

#xlrd, xlutils and xlwt modules need to be installed.  
#Can be done via pip install <module>
from xlrd import open_workbook
from xlutils.copy import copy

rb = open_workbook("names.xls")
wb = copy(rb)

s = wb.get_sheet(0)
s.write(0,0,'A1')
wb.save('names.xls')

This replaces the contents of the cell located at a1 in the first sheet of "names.xls" with the text "a1", and then saves the document.

Use jquery click to handle anchor onClick()

<div class = "solTitle"> <a href = "#"  id = "solution0" onClick = "openSolution();">Solution0 </a></div> <br>

<div class= "solTitle"> <a href = "#"  id = "solution1" onClick = "openSolution();">Solution1 </a></div> <br>



$(document).ready(function(){
    $('.solTitle a').click(function(e) {
        e.preventDefault();
        alert('here in');
         var divId = 'summary' +$(this).attr('id');

        document.getElementById(divId).className = ''; /* or $('#'+divid).removeAttr('class'); */

    });
 });

I changed few things:

  1. remove the onclick attr and bind click event inside the document.ready
  2. changed solTitle to be an ID to a CLASS: id cant be repeated

Count number of 1's in binary representation

Two ways::

/* Method-1 */
int count1s(long num)
{
    int tempCount = 0;

    while(num)
    {
        tempCount += (num & 1); //inc, based on right most bit checked
        num = num >> 1;         //right shift bit by 1
    }

    return tempCount;
}

/* Method-2 */
int count1s_(int num)
{
    int tempCount = 0;

    std::string strNum = std::bitset< 16 >( num ).to_string(); // string conversion
    cout << "strNum=" << strNum << endl;
    for(int i=0; i<strNum.size(); i++)
    {
        if('1' == strNum[i])
        {
            tempCount++;
        }
    }

    return tempCount;
}

/* Method-3 (algorithmically - boost string split could be used) */
1) split the binary string over '1'.
2) count = vector (containing splits) size - 1

Usage::

    int count = 0;

    count = count1s(0b00110011);
    cout << "count(0b00110011) = " << count << endl; //4

    count = count1s(0b01110110);
    cout << "count(0b01110110) = " << count << endl;  //5

    count = count1s(0b00000000);
    cout << "count(0b00000000) = " << count << endl;  //0

    count = count1s(0b11111111);
    cout << "count(0b11111111) = " << count << endl;  //8

    count = count1s_(0b1100);
    cout << "count(0b1100) = " << count << endl;  //2

    count = count1s_(0b11111111);
    cout << "count(0b11111111) = " << count << endl;  //8

    count = count1s_(0b0);
    cout << "count(0b0) = " << count << endl;  //0

    count = count1s_(0b1);
    cout << "count(0b1) = " << count << endl;  //1

Disable Scrolling on Body

To accomplish this, add 2 CSS properties on the <body> element.

body {
   height: 100%;
   overflow-y: hidden;
}

These days there are many news websites which require users to create an account. Typically they will give full access to the page for about a second, and then they show a pop-up, and stop users from scrolling down.

The Telegraph

What's the difference between the Window.Loaded and Window.ContentRendered events

I think there is little difference between the two events. To understand this, I created a simple example to manipulation:

XAML

<Window x:Class="LoadedAndContentRendered.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Name="MyWindow"
        Title="MainWindow" Height="1000" Width="525"
        WindowStartupLocation="CenterScreen"
        ContentRendered="Window_ContentRendered"     
        Loaded="Window_Loaded">

    <Grid Name="RootGrid">        
    </Grid>
</Window>

Code behind

private void Window_ContentRendered(object sender, EventArgs e)
{
    MessageBox.Show("ContentRendered");
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Loaded");
}   

In this case the message Loaded appears the first after the message ContentRendered. This confirms the information in the documentation.

In general, in WPF the Loaded event fires if the element:

is laid out, rendered, and ready for interaction.

Since in WPF the Window is the same element, but it should be generally content that is arranged in a root panel (for example: Grid). Therefore, to monitor the content of the Window and created an ContentRendered event. Remarks from MSDN:

If the window has no content, this event is not raised.

That is, if we create a Window:

<Window x:Class="LoadedAndContentRendered.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Name="MyWindow"        
    ContentRendered="Window_ContentRendered" 
    Loaded="Window_Loaded" />

It will only works Loaded event.

With regard to access to the elements in the Window, they work the same way. Let's create a Label in the main Grid of Window. In both cases we have successfully received access to Width:

private void Window_ContentRendered(object sender, EventArgs e)
{
    MessageBox.Show("ContentRendered: " + SampleLabel.Width.ToString());
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Loaded: " + SampleLabel.Width.ToString());
}   

As for the Styles and Templates, at this stage they are successfully applied, and in these events we will be able to access them.

For example, we want to add a Button:

private void Window_ContentRendered(object sender, EventArgs e)
{
    MessageBox.Show("ContentRendered: " + SampleLabel.Width.ToString());

    Button b1 = new Button();
    b1.Content = "ContentRendered Button";
    RootGrid.Children.Add(b1);
    b1.Height = 25;
    b1.Width = 200;
    b1.HorizontalAlignment = HorizontalAlignment.Right;
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Loaded: " + SampleLabel.Width.ToString());

    Button b1 = new Button();
    b1.Content = "Loaded Button";
    RootGrid.Children.Add(b1);
    b1.Height = 25;
    b1.Width = 200;
    b1.HorizontalAlignment = HorizontalAlignment.Left;
}

In the case of Loaded event, Button to add to Grid immediately at the appearance of the Window. In the case of ContentRendered event, Button to add to Grid after all its content will appear.

Therefore, if you want to add items or changes before load Window you must use the Loaded event. If you want to do the operations associated with the content of Window such as taking screenshots you will need to use an event ContentRendered.

CSS3 selector :first-of-type with class name?

I found a solution for your reference. from some group divs select from group of two same class divs the first one

p[class*="myclass"]:not(:last-of-type) {color:red}
p[class*="myclass"]:last-of-type {color:green}

BTW, I don't know why :last-of-type works, but :first-of-type does not work.

My experiments on jsfiddle... https://jsfiddle.net/aspanoz/m1sg4496/

How do you access the matched groups in a JavaScript regular expression?

You can access capturing groups like this:

_x000D_
_x000D_
var myString = "something format_abc";_x000D_
var myRegexp = /(?:^|\s)format_(.*?)(?:\s|$)/g;_x000D_
var match = myRegexp.exec(myString);_x000D_
console.log(match[1]); // abc
_x000D_
_x000D_
_x000D_

And if there are multiple matches you can iterate over them:

_x000D_
_x000D_
var myString = "something format_abc";_x000D_
var myRegexp = /(?:^|\s)format_(.*?)(?:\s|$)/g;_x000D_
match = myRegexp.exec(myString);_x000D_
while (match != null) {_x000D_
  // matched text: match[0]_x000D_
  // match start: match.index_x000D_
  // capturing group n: match[n]_x000D_
  console.log(match[0])_x000D_
  match = myRegexp.exec(myString);_x000D_
}
_x000D_
_x000D_
_x000D_

Edit: 2019-09-10

As you can see the way to iterate over multiple matches was not very intuitive. This lead to the proposal of the String.prototype.matchAll method. This new method is expected to ship in the ECMAScript 2020 specification. It gives us a clean API and solves multiple problems. It has been started to land on major browsers and JS engines as Chrome 73+ / Node 12+ and Firefox 67+.

The method returns an iterator and is used as follows:

_x000D_
_x000D_
const string = "something format_abc";_x000D_
const regexp = /(?:^|\s)format_(.*?)(?:\s|$)/g;_x000D_
const matches = string.matchAll(regexp);_x000D_
    _x000D_
for (const match of matches) {_x000D_
  console.log(match);_x000D_
  console.log(match.index)_x000D_
}
_x000D_
_x000D_
_x000D_

As it returns an iterator, we can say it's lazy, this is useful when handling particularly large numbers of capturing groups, or very large strings. But if you need, the result can be easily transformed into an Array by using the spread syntax or the Array.from method:

function getFirstGroup(regexp, str) {
  const array = [...str.matchAll(regexp)];
  return array.map(m => m[1]);
}

// or:
function getFirstGroup(regexp, str) {
  return Array.from(str.matchAll(regexp), m => m[1]);
}

In the meantime, while this proposal gets more wide support, you can use the official shim package.

Also, the internal workings of the method are simple. An equivalent implementation using a generator function would be as follows:

function* matchAll(str, regexp) {
  const flags = regexp.global ? regexp.flags : regexp.flags + "g";
  const re = new RegExp(regexp, flags);
  let match;
  while (match = re.exec(str)) {
    yield match;
  }
}

A copy of the original regexp is created; this is to avoid side-effects due to the mutation of the lastIndex property when going through the multple matches.

Also, we need to ensure the regexp has the global flag to avoid an infinite loop.

I'm also happy to see that even this StackOverflow question was referenced in the discussions of the proposal.

Can we convert a byte array into an InputStream in Java?

If you use Robert Harder's Base64 utility, then you can do:

InputStream is = new Base64.InputStream(cph);

Or with sun's JRE, you can do:

InputStream is = new
com.sun.xml.internal.messaging.saaj.packaging.mime.util.BASE64DecoderStream(cph)

However don't rely on that class continuing to be a part of the JRE, or even continuing to do what it seems to do today. Sun say not to use it.

There are other Stack Overflow questions about Base64 decoding, such as this one.

Java count occurrence of each item in an array

With , you can do it like this:

String[] array = {"name1","name2","name3","name4", "name5", "name2"};
Arrays.stream(array)
      .collect(Collectors.groupingBy(s -> s))
      .forEach((k, v) -> System.out.println(k+" "+v.size()));

Output:

name5 1
name4 1
name3 1
name2 2
name1 1

What it does is:

  • Create a Stream<String> from the original array
  • Group each element by identity, resulting in a Map<String, List<String>>
  • For each key value pair, print the key and the size of the list

If you want to get a Map that contains the number of occurences for each word, it can be done doing:

Map<String, Long> map = Arrays.stream(array)
    .collect(Collectors.groupingBy(s -> s, Collectors.counting()));

For more informations:

Hope it helps! :)

Eclipse : Maven search dependencies doesn't work

For me for this issue worked to:

  • remove ~/.m2
  • enable "Full Index Enabled" in maven repository view on central repository
  • "Rebuild Index" on central maven repository

After eclipse restart everything worked well.

Compare two data.frames to find the rows in data.frame 1 that are not present in data.frame 2

This doesn't answer your question directly, but it will give you the elements that are in common. This can be done with Paul Murrell's package compare:

library(compare)
a1 <- data.frame(a = 1:5, b = letters[1:5])
a2 <- data.frame(a = 1:3, b = letters[1:3])
comparison <- compare(a1,a2,allowAll=TRUE)
comparison$tM
#  a b
#1 1 a
#2 2 b
#3 3 c

The function compare gives you a lot of flexibility in terms of what kind of comparisons are allowed (e.g. changing order of elements of each vector, changing order and names of variables, shortening variables, changing case of strings). From this, you should be able to figure out what was missing from one or the other. For example (this is not very elegant):

difference <-
   data.frame(lapply(1:ncol(a1),function(i)setdiff(a1[,i],comparison$tM[,i])))
colnames(difference) <- colnames(a1)
difference
#  a b
#1 4 d
#2 5 e

Client to send SOAP request and receive response

As an alternative, and pretty close to debiasej approach. Since a SOAP request is just a HTTP request, you can simply perform a GET or POST using with HTTP client, but it's not mandatory to build SOAP envelope.

Something like this:

using Microsoft.Extensions.Logging;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace HGF.Infraestructure.Communications
{
    public class SOAPSample
    {
        private readonly IHttpClientFactory _clientFactory;
        private readonly ILogger<DocumentProvider> _logger;

        public SOAPSample(ILogger<DocumentProvider> logger,
                          IHttpClientFactory clientFactory)
        {
            _clientFactory = clientFactory;
            _logger = logger;
        }

        public async Task<string> UsingGet(int value1, int value2)
        {
            try
            {
                var client = _clientFactory.CreateClient();
                var response = await client.GetAsync($"https://hostname.com/webservice.asmx/SampleMethod?value1={value1}&value2={value2}", HttpCompletionOption.ResponseHeadersRead);

                //NULL check, HTTP Status Check....

                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Oops! Something went wrong");
                return ex.Message;
            }
        }


        public async Task<string> UsingPost(int value1, int value2)
        {
            try
            {
                var content = new StringContent($"value1={value1}&value2={value2}", Encoding.UTF8, "application/x-www-form-urlencoded");

                var client = _clientFactory.CreateClient();
                var response = await client.PostAsync("https://hostname.com/webservice.asmx/SampleMethod", content);

                //NULL check, HTTP Status Check....

                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Oops! Something went wrong");
                return ex.Message;
            }
        }
    }
}

Of course, it depends on your scenario. If the payload is too complex, then this won't work

Mockito How to mock and assert a thrown exception?

Assert by exception message:

    try {
        MyAgent.getNameByNode("d");
    } catch (Exception e) {
        Assert.assertEquals("Failed to fetch data.", e.getMessage());
    }

How do I run a simple bit of code in a new thread?

Here how can use threads with a progressBar , its just for understing how the threads works, in the form there are three progressBar and 4 button:

 public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    Thread t, t2, t3;
    private void Form1_Load(object sender, EventArgs e)
    {

        CheckForIllegalCrossThreadCalls = false;

         t = new Thread(birinicBar); //evry thread workes with a new progressBar


         t2 = new Thread(ikinciBar);


         t3 = new Thread(ucuncuBar);

    }

    public void birinicBar() //to make progressBar work
    {
        for (int i = 0; i < 100; i++) {
            progressBar1.Value++;
            Thread.Sleep(100); // this progressBar gonna work faster
        }
    }

    public void ikinciBar()
    {
        for (int i = 0; i < 100; i++)
        {
            progressBar2.Value++;
            Thread.Sleep(200);
        }


    }

    public void ucuncuBar()
    {
        for (int i = 0; i < 100; i++)
        {
            progressBar3.Value++;
            Thread.Sleep(300);
        }
    }

    private void button1_Click(object sender, EventArgs e) //that button to start the threads
    {
        t.Start();
        t2.Start(); t3.Start();

    }

    private void button4_Click(object sender, EventArgs e)//that button to stup the threads with the progressBar
    {
        t.Suspend();
        t2.Suspend();
        t3.Suspend();
    }

    private void button2_Click(object sender, EventArgs e)// that is for contuniue after stuping
    {
        t.Resume();
        t2.Resume();
        t3.Resume();
    }

    private void button3_Click(object sender, EventArgs e) // finally with that button you can remove all of the threads
    {
        t.Abort();
        t2.Abort();
        t3.Abort();
    }
}

How to add Web API to an existing ASP.NET MVC 4 Web Application project?

Before you start merging MVC and Web API projects I would suggest to read about cons and pros to separate these as different projects. One very important thing (my own) is authentication systems, which is totally different.

IF you need to use authenticated requests on both MVC and Web API, you need to remember that Web API is RESTful (don't need to keep session, simple HTTP requests, etc.), but MVC is not.

To look on the differences of implementations simply create 2 different projects in Visual Studio 2013 from Templates: one for MVC and one for Web API (don't forget to turn On "Individual Authentication" during creation). You will see a lot of difference in AuthencationControllers.

So, be aware.

remove item from stored array in angular 2

That work for me

 this.array.pop(index);

 for example index = 3 

 this.array.pop(3);

Adding delay between execution of two following lines

I have a couple of turn-based games where I need the AI to pause before taking its turn (and between steps in its turn). I'm sure there are other, more useful, situations where a delay is the best solution. In Swift:

        let delay = 2.0 * Double(NSEC_PER_SEC) 
        let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) 
        dispatch_after(time, dispatch_get_main_queue()) { self.playerTapped(aiPlayView) }

I just came back here to see if the Objective-C calls were different.(I need to add this to that one, too.)

Animate a custom Dialog

Try below code:

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));// set transparent in window background

        View _v = inflater.inflate(R.layout.some_you_layout, container, false);

        //load animation
        //Animation transition_in_view = AnimationUtils.loadAnimation(getContext(), android.R.anim.fade_in);// system animation appearance
        Animation transition_in_view = AnimationUtils.loadAnimation(getContext(), R.anim.customer_anim);//customer animation appearance

        _v.setAnimation( transition_in_view );
        _v.startAnimation( transition_in_view );
        //really beautiful
        return _v;

    }

Create the custom Anim.: res/anim/customer_anim.xml:

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

    <translate
        android:duration="500"
        android:fromYDelta="100%"
        android:toYDelta="-7%"/>
    <translate
        android:duration="300"
        android:startOffset="500"
        android:toYDelta="7%" />
    <translate
        android:duration="200"
        android:startOffset="800"
        android:toYDelta="0%" />

</set>

How to select only date from a DATETIME field in MySQL?

Please try this answer.

SELECT * FROM `Yourtable` WHERE date(`dateField`) = '2018-09-25'

javascript return true or return false when and how to use it?

Your code makes no sense, maybe because it's out of context.

If you mean code like this:

$('a').click(function () {
    callFunction();
    return false;
});

The return false will return false to the click-event. That tells the browser to stop following events, like follow a link. It has nothing to do with the previous function call. Javascript runs from top to bottom more or less, so a line cannot affect a previous line.

Is there a max array length limit in C++?

There are two limits, both not enforced by C++ but rather by the hardware.

The first limit (should never be reached) is set by the restrictions of the size type used to describe an index in the array (and the size thereof). It is given by the maximum value the system's std::size_t can take. This data type is large enough to contain the size in bytes of any object

The other limit is a physical memory limit. The larger your objects in the array are, the sooner this limit is reached because memory is full. For example, a vector<int> of a given size n typically takes multiple times as much memory as an array of type vector<char> (minus a small constant value), since int is usually bigger than char. Therefore, a vector<char> may contain more items than a vector<int> before memory is full. The same counts for raw C-style arrays like int[] and char[].

Additionally, this upper limit may be influenced by the type of allocator used to construct the vector because an allocator is free to manage memory any way it wants. A very odd but nontheless conceivable allocator could pool memory in such a way that identical instances of an object share resources. This way, you could insert a lot of identical objects into a container that would otherwise use up all the available memory.

Apart from that, C++ doesn't enforce any limits.

How to uninstall Jenkins?

On Mac; these two below commands completely remove Jenkins from your machine. just open your Terminal and execute them:

  1. '/Library/Application Support/Jenkins/Uninstall.command' and
  2. sudo rm -rf /var/root/.jenkins ~/.jenkins

Thanks

How do I exit from a function?

Use the return keyword.

return; //exit this event

delete all from table

You can use the below query to remove all the rows from the table, also you should keep it in mind that it will reset the Identity too.

TRUNCATE TABLE table_name

How to convert buffered image to image and vice-versa?

You can try saving (or writing) the Buffered Image with the changes you made and then opening it as an Image.

EDIT:

try {
    // Retrieve Image
    BufferedImage buffer = ImageIO.read(new File("old.png"));;
    // Here you can rotate your image as you want (making your magic)
    File outputfile = new File("saved.png");
    ImageIO.write(buffer, "png", outputfile); // Write the Buffered Image into an output file
    Image image  = ImageIO.read(new File("saved.png")); // Opening again as an Image
} catch (IOException e) {
    ...
}

ReportViewer Client Print Control "Unable to load client print control"?

Found a Fix:

  1. First ensure that printing is working from Report Manager (open a report in Report Manager and print from there).

  2. If it works go to Step 3, if you received the same error you need to install the following patches on the Report Server.

  3. Download and install the following update:

How to get body of a POST in php?

If you have the pecl/http extension installed, you can also use this:

$request = new http\Env\Request();
$request->getBody();

rails bundle clean

Honestly, I had problems with bundler circular dependencies and the best way to go is rm -rf .bundle. Save yourselves the headache and just use the hammer.

What is "Linting"?

Interpreted languages like Python and JavaScript benefit greatly from linting, as these languages don’t have a compiling phase to display errors before execution.

Linters are also useful for code formatting and/or adhering to language specific best practices.

Lately I have been using ESLint for JS/React and will occasionally use it with an airbnb-config file.

Concatenating string and integer in python

if you only want to print yo can do this:

print(s , i)

Configuring IntelliJ IDEA for unit testing with JUnit

One way of doing this is to do add junit.jar to your $CLASSPATH as an external dependency.

adding junit intellij

So to do that, go to project structure, and then add JUnit as one of the libraries as shown in the gif.

In the 'Choose Modules' prompt choose only the modules that you'd need JUnit for.

How to select a range of the second row to the last row

Sub SelectAllCellsInSheet(SheetName As String)
    lastCol = Sheets(SheetName).Range("a1").End(xlToRight).Column
    Lastrow = Sheets(SheetName).Cells(1, 1).End(xlDown).Row
    Sheets(SheetName).Range("A2", Sheets(SheetName).Cells(Lastrow, lastCol)).Select
End Sub

To use with ActiveSheet:

Call SelectAllCellsInSheet(ActiveSheet.Name)

How to handle :java.util.concurrent.TimeoutException: android.os.BinderProxy.finalize() timed out after 10 seconds errors?

We see this constantly, all over our app, using Crashlytics. The crash usually happens way down in platform code. A small sampling:

android.database.CursorWindow.finalize() timed out after 10 seconds

java.util.regex.Matcher.finalize() timed out after 10 seconds

android.graphics.Bitmap$BitmapFinalizer.finalize() timed out after 10 seconds

org.apache.http.impl.conn.SingleClientConnManager.finalize() timed out after 10 seconds

java.util.concurrent.ThreadPoolExecutor.finalize() timed out after 10 seconds

android.os.BinderProxy.finalize() timed out after 10 seconds

android.graphics.Path.finalize() timed out after 10 seconds

The devices on which this happens are overwhelmingly (but not exclusively) devices manufactured by Samsung. That could just mean that most of our users are using Samsung devices; alternately it could indicate a problem with Samsung devices. I'm not really sure.

I suppose this doesn't really answer your questions, but I just wanted to reinforce that this seems quite common, and is not specific to your application.

"Unorderable types: int() < str()"

Just a side note, in Python 2.0 you could compare anything to anything (int to string). As this wasn't explicit, it was changed in 3.0, which is a good thing as you are not running into the trouble of comparing senseless values with each other or when you forget to convert a type.

What is the list of valid @SuppressWarnings warning names in Java?

If you're using SonarLint, try above the method or class the whole squid string: @SuppressWarnings("squid:S1172")

Javascript receipt printing using POS Printer

I have recently implemented the receipt printing simply by pressing a button on a web page, without having to enter the printer options. I have done it using EPSON javascript SDK for ePOS. I have test it on EPSON TM-m30 receipt printer.

Here is the sample code.

var printer = null;
var ePosDev = null;

function InitMyPrinter() {
    console.log("Init Printer");

    var printerPort = 8008;
    var printerAddress = "192.168.198.168";
    if (isSSL) {
        printerPort = 8043;
    }
    ePosDev = new epson.ePOSDevice();
    ePosDev.connect(printerAddress, printerPort, cbConnect);
}

//Printing
function cbConnect(data) {
    if (data == 'OK' || data == 'SSL_CONNECT_OK') {
        ePosDev.createDevice('local_printer', ePosDev.DEVICE_TYPE_PRINTER,
            {'crypto': false, 'buffer': false}, cbCreateDevice_printer);
    } else {
        console.log(data);
    }
}

function cbCreateDevice_printer(devobj, retcode) {
    if (retcode == 'OK') {
        printer = devobj;
        printer.timeout = 60000;
        printer.onreceive = function (res) { //alert(res.success);
            console.log("Printer Object Created");

        };
        printer.oncoveropen = function () { //alert('coveropen');
            console.log("Printer Cover Open");

        };
    } else {
        console.log(retcode);
        isRegPrintConnected = false;
    }
}

function print(salePrintObj) {
    debugger;
    if (isRegPrintConnected == false
        || printer == null) {
        return;
    }
    console.log("Printing Started");


    printer.addLayout(printer.LAYOUT_RECEIPT, 800, 0, 0, 0, 35, 0);
    printer.addTextAlign(printer.ALIGN_CENTER);
    printer.addTextSmooth(true);
    printer.addText('\n');
    printer.addText('\n');

    printer.addTextDouble(true, true);
    printer.addText(CompanyName + '\n');

    printer.addTextDouble(false, false);
    printer.addText(CompanyHeader + '\n');
    printer.addText('\n');

    printer.addTextAlign(printer.ALIGN_LEFT);
    printer.addText('DATE: ' + currentDate + '\t\t');

    printer.addTextAlign(printer.ALIGN_RIGHT);
    printer.addText('TIME: ' + currentTime + '\n');

    printer.addTextAlign(printer.ALIGN_LEFT);

    printer.addTextAlign(printer.ALIGN_RIGHT);
    printer.addText('REGISTER: ' + RegisterName + '\n');
    printer.addTextAlign(printer.ALIGN_LEFT);
    printer.addText('SALE # ' + SaleNumber + '\n');

    printer.addTextAlign(printer.ALIGN_CENTER);
    printer.addTextStyle(false, false, true, printer.COLOR_1);
    printer.addTextStyle(false, false, false, printer.COLOR_1);
    printer.addTextDouble(false, true);
    printer.addText('* SALE RECEIPT *\n');
    printer.addTextDouble(false, false);
....
....
....

}

Detect if the device is iPhone X

#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define IS_IPHONE_X (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 812.0f)

What is the difference between .py and .pyc files?

.pyc contain the compiled bytecode of Python source files. The Python interpreter loads .pyc files before .py files, so if they're present, it can save some time by not having to re-compile the Python source code. You can get rid of them if you want, but they don't cause problems, they're not big, and they may save some time when running programs.

Bootstrap 3 scrollable div for table

Well one way to do it is set the height of your body to the height that you want your page to be. In this example I did 600px.

Then set your wrapper height to a percentage of the body here I did 70% This will adjust your table so that it does not fill up the whole screen but in stead just takes up a percentage of the specified page height.

body {
   padding-top: 70px;
   border:1px solid black;
   height:600px;
}

.mygrid-wrapper-div {
   border: solid red 5px;
   overflow: scroll;
   height: 70%;
}

http://jsfiddle.net/4NB2N/7/

Update How about a jQuery approach.

$(function() {  
   var window_height = $(window).height(),
   content_height = window_height - 200;
   $('.mygrid-wrapper-div').height(content_height);
});

$( window ).resize(function() {
   var window_height = $(window).height(),
   content_height = window_height - 200;
   $('.mygrid-wrapper-div').height(content_height);
});

http://jsfiddle.net/4NB2N/11/

How to use GNU Make on Windows?

While make itself is available as a standalone executable (gnuwin32.sourceforge.net package make), using it in a proper development environment means using msys2.

Git 2.24 (Q4 2019) illustrates that:

See commit 4668931, commit b35304b, commit ab7d854, commit be5d88e, commit 5d65ad1, commit 030a628, commit 61d1d92, commit e4347c9, commit ed712ef, commit 5b8f9e2, commit 41616ef, commit c097b95 (04 Oct 2019), and commit dbcd970 (30 Sep 2019) by Johannes Schindelin (dscho).
(Merged by Junio C Hamano -- gitster -- in commit 6d5291b, 15 Oct 2019)

test-tool run-command: learn to run (parts of) the testsuite

Signed-off-by: Johannes Schindelin

Git for Windows jumps through hoops to provide a development environment that allows to build Git and to run its test suite.

To that end, an entire MSYS2 system, including GNU make and GCC is offered as "the Git for Windows SDK".
It does come at a price: an initial download of said SDK weighs in with several hundreds of megabytes, and the unpacked SDK occupies ~2GB of disk space.

A much more native development environment on Windows is Visual Studio. To help contributors use that environment, we already have a Makefile target vcxproj that generates a commit with project files (and other generated files), and Git for Windows' vs/master branch is continuously re-generated using that target.

The idea is to allow building Git in Visual Studio, and to run individual tests using a Portable Git.

Pass a JavaScript function as parameter

I chopped all my hair off with that issue. I couldn't make the examples above working, so I ended like :

function foo(blabla){
    var func = new Function(blabla);
    func();
}
// to call it, I just pass the js function I wanted as a string in the new one...
foo("alert('test')");

And that's working like a charm ... for what I needed at least. Hope it might help some.

ssl_error_rx_record_too_long and Apache SSL

Please see this link.

I looked in all my apache log files until I found the actual error (I had changed the <VirtualHost> from _default_ to my fqdn). When I fixed this error, everything worked fine.

What's faster, SELECT DISTINCT or GROUP BY in MySQL?

If you don't have to do any group functions (sum, average etc in case you want to add numeric data to the table), use SELECT DISTINCT. I suspect it's faster, but i have nothing to show for it.

In any case, if you're worried about speed, create an index on the column.

Find oldest/youngest datetime object in a list

Given a list of dates dates:

Max date is max(dates)

Min date is min(dates)

How to simulate a click with JavaScript?

You could save yourself a bunch of space by using jQuery. You only need to use:

$('#myElement').trigger("click")

How to enable GZIP compression in IIS 7.5

Sometimes no matter what you do or follow whole internet posts. Try on the MIMETYPES of applicationhost.config of the server.

https://docs.microsoft.com/en-us/iis/configuration/system.webserver/httpcompression/#configuration-sample

SQL Server: Multiple table joins with a WHERE clause

You need to do a LEFT JOIN.

SELECT Computer.ComputerName, Application.Name, Software.Version
FROM Computer
JOIN dbo.Software_Computer
    ON Computer.ID = Software_Computer.ComputerID
LEFT JOIN dbo.Software
    ON Software_Computer.SoftwareID = Software.ID
RIGHT JOIN dbo.Application
    ON Application.ID = Software.ApplicationID
WHERE Computer.ID = 1 

Here is the explanation:

The result of a left outer join (or simply left join) for table A and B always contains all records of the "left" table (A), even if the join-condition does not find any matching record in the "right" table (B). This means that if the ON clause matches 0 (zero) records in B, the join will still return a row in the result—but with NULL in each column from B. This means that a left outer join returns all the values from the left table, plus matched values from the right table (or NULL in case of no matching join predicate). If the right table returns one row and the left table returns more than one matching row for it, the values in the right table will be repeated for each distinct row on the left table. From Oracle 9i onwards the LEFT OUTER JOIN statement can be used as well as (+).

Is it possible to read the value of a annotation in java?

Elaborating to the answer of @Cephalopod, if you wanted all column names in a list you could use this oneliner:

List<String> columns = 
        Arrays.asList(MyClass.class.getFields())
              .stream()
              .filter(f -> f.getAnnotation(Column.class)!=null)
              .map(f -> f.getAnnotation(Column.class).columnName())
              .collect(Collectors.toList());

How to print last two columns using awk

awk '{print $NF-1, $NF}'  inputfile

Note: this works only if at least two columns exist. On records with one column you will get a spurious "-1 column1"

Google maps API V3 - multiple markers on exact same spot

Giving offset will make the markers faraway when the user zoom in to max. So i found a way to achieve that. this may not be a proper way but it worked very well.

// This code is in swift
for loop markers
{
//create marker
let mapMarker = GMSMarker()
mapMarker.groundAnchor = CGPosition(0.5, 0.5)
mapMarker.position = //set the CLLocation
//instead of setting marker.icon set the iconView
let image:UIIMage = UIIMage:init(named:"filename")
let imageView:UIImageView = UIImageView.init(frame:rect(0,0, ((image.width/2 * markerIndex) + image.width), image.height))
imageView.contentMode = .Right
imageView.image = image
mapMarker.iconView = imageView
mapMarker.map = mapView
}

set the zIndex of the marker so that you will see the marker icon which you want to see on top, otherwise it will animate the markers like auto swapping. when the user tap the marker handle the zIndex to bring the marker on top using zIndex Swap.

npm install hangs

For anyone on MacOS (I'm on Mojave 10.14), the following helped me out: https://github.com/reactioncommerce/reaction/issues/1938#issuecomment-284207213

You'd run these commands

echo kern.maxfiles=65536 | sudo tee -a /etc/sysctl.conf
echo kern.maxfilesperproc=65536 | sudo tee -a /etc/sysctl.conf
sudo sysctl -w kern.maxfiles=65536
sudo sysctl -w kern.maxfilesperproc=65536
ulimit -n 65536

Then try npm install once more.

Make Bootstrap Popover Appear/Disappear on Hover instead of Click

If you want to hover the popover itself as well you have to use a manual trigger.

This is what i came up with:

function enableThumbPopover() {
    var counter;

    $('.thumbcontainer').popover({
        trigger: 'manual',
        animation: false,
        html: true,
        title: function () {
            return $(this).parent().find('.thumbPopover > .title').html();
        },
        content: function () {
            return $(this).parent().find('.thumbPopover > .body').html();
        },
        container: 'body',
        placement: 'auto'
    }).on("mouseenter",function () {
        var _this = this; // thumbcontainer

        console.log('thumbcontainer mouseenter')
        // clear the counter
        clearTimeout(counter);
        // Close all other Popovers
        $('.thumbcontainer').not(_this).popover('hide');

        // start new timeout to show popover
        counter = setTimeout(function(){
            if($(_this).is(':hover'))
            {
                $(_this).popover("show");
            }
            $(".popover").on("mouseleave", function () {
                $('.thumbcontainer').popover('hide');
            });
        }, 400);

    }).on("mouseleave", function () {
        var _this = this;

        setTimeout(function () {
            if (!$(".popover:hover").length) {
                if(!$(_this).is(':hover')) // change $(this) to $(_this) 
                {
                    $(_this).popover('hide');
                }
            }
        }, 200);
    });
}

Python: avoid new line with print command

If you're using Python 2.5, this won't work, but for people using 2.6 or 2.7, try

from __future__ import print_function

print("abcd", end='')
print("efg")

results in

abcdefg

For those using 3.x, this is already built-in.

PowerShell: how to grep command output?

Try this:

PS C:\> ipconfig /displaydns | Select-String -Pattern 'www.yahoo.com' -Context 0,7

>     www.yahoo.com
      ----------------------------------------
>     Record Name . . . . . : www.yahoo.com
      Record Type . . . . . : 5
      Time To Live  . . . . : 27
      Data Length . . . . . : 8
      Section . . . . . . . : Answer
      CNAME Record  . . . . : new-fp-shed.wg1.b.yahoo.com

jquery/javascript convert date string to date

If you're running with jQuery you can use the datepicker UI library's parseDate function to convert your string to a date:

var d = $.datepicker.parseDate("DD, MM dd, yy",  "Sunday, February 28, 2010");

and then follow it up with the formatDate method to get it to the string format you want

var datestrInNewFormat = $.datepicker.formatDate( "mm/dd/yy", d);

If you're not running with jQuery of course its probably not the best plan given you'd need jQuery core as well as the datepicker UI module... best to go with the suggestion from Segfault above to use date.js.

HTH

Android Studio installation on Windows 7 fails, no JDK found

If you have a 64 bit windows OS, pointing the JAVA_HOME system variable to

C:\Program Files (x86)\Java\jdk1.7.0_21

Will work when

C:\Program Files\Java\jdk1.7.0_21

fails to work.

Close Bootstrap Modal

$('#modal').modal('toggle'); 

or

$('#modal').modal().hide();

should work.

But if nothing else works you can call the modal close button directly:

$("#modal .close").click()

PHP Swift mailer: Failed to authenticate on SMTP using 2 possible authenticators

try putting username in double quote "username", somehow that fixed for me.

How to get am pm from the date time string using moment js

you will get the time without specifying the date format. convert the string to date using Date object

var myDate = new Date('Mon 03-Jul-2017, 06:00 PM');

working solution:

_x000D_
_x000D_
var myDate= new Date('Mon 03-Jul-2017, 06:00 PM');_x000D_
console.log(moment(myDate).format('HH:mm')); // 24 hour format _x000D_
console.log(moment(myDate).format('hh:mm'));_x000D_
console.log(moment(myDate).format('hh:mm A'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

Resizing UITableView to fit content

As an extension of Anooj VM's answer, I suggest the following to refresh content size only when it changes.

This approach also disable scrolling properly and support larger lists and rotation. There is no need to dispatch_async because contentSize changes are dispatched on main thread.

- (void)viewDidLoad {
        [super viewDidLoad];
        [self.tableView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:NULL]; 
}


- (void)resizeTableAccordingToContentSize:(CGSize)newContentSize {
        CGRect superviewTableFrame  = self.tableView.superview.bounds;
        CGRect tableFrame = self.tableView.frame;
        BOOL shouldScroll = newContentSize.height > superviewTableFrame.size.height;
        tableFrame.size = shouldScroll ? superviewTableFrame.size : newContentSize;
        [UIView animateWithDuration:0.3
                                    delay:0
                                    options:UIViewAnimationOptionCurveLinear
                                    animations:^{
                            self.tableView.frame = tableFrame;
        } completion: nil];
        self.tableView.scrollEnabled = shouldScroll;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([change[NSKeyValueChangeKindKey] unsignedIntValue] == NSKeyValueChangeSetting &&
        [keyPath isEqualToString:@"contentSize"] &&
        !CGSizeEqualToSize([change[NSKeyValueChangeOldKey] CGSizeValue], [change[NSKeyValueChangeNewKey] CGSizeValue])) {
        [self resizeTableAccordingToContentSize:[change[NSKeyValueChangeNewKey] CGSizeValue]];
    } 
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
    [self resizeTableAccordingToContentSize:self.tableView.contentSize]; }

- (void)dealloc {
    [self.tableView removeObserver:self forKeyPath:@"contentSize"];
}

Create an array with same element repeated multiple times

>>> Array.apply(null, Array(10)).map(function(){return 5})
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
>>> //Or in ES6
>>> [...Array(10)].map((_, i) => 5)
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5]

Only on Firefox "Loading failed for the <script> with source"

I noticed that in Firefox this can happen when requests are aborted (switching page or quickly refreshing page), but it is hard to reproduce the error even if I try to.

Other possible reasons: cert related issues and this one talks about blockers (as other answers stated).

Disable native datepicker in Google Chrome

You could use:

jQuery('input[type="date"]').live('click', function(e) {e.preventDefault();}).datepicker();

How to add image for button in android?

You should try something like this

    <Button
    android:id="@+id/imageButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/qrcode"/>

the android:background="@drawable/qrcode" will do it

How can I clear the terminal in Visual Studio Code?

For a MacBook, it might not be Cmd + K...

There's a long discussion for cases where Cmd + K wouldn't work. In my case, I made a quick fix with

cmd+K +cmd+ K

Go to menu Preferences -> Key shortcuts -> Search ('clear'). Change it from a single K to a double K...

Why is my method undefined for the type object?

Try this.

public static void main(String[] args) {
    EchoServer0 myServer;
    myServer = new EchoServer0();
    myServer.listen();
}

What you were trying to do was declaring a variable of type Object, not creating anything for that variable to reference, then trying to call a method that didn't exist (in the class Object) on an object that hadn't been created. It was never going to work.

Copy all files with a certain extension from all subdirectories

From all of the above, I came up with this version. This version also works for me in the mac recovery terminal.

find ./ -name '*.xsl' -exec cp -prv '{}' '/path/to/targetDir/' ';'

It will look in the current directory and recursively in all of the sub directories for files with the xsl extension. It will copy them all to the target directory.

cp flags are:

  • p - preserve attributes of the file
  • r - recursive
  • v - verbose (shows you whats being copied)

docker entrypoint running bash script gets "permission denied"

An executable file needs to have permissions for execute set before you can execute it.

In your machine where you are building the docker image (not inside the docker image itself) try running:

ls -la path/to/directory

The first column of the output for your executable (in this case docker-entrypoint.sh) should have the executable bits set something like:

-rwxrwxr-x

If not then try:

chmod +x docker-entrypoint.sh

and then build your docker image again.

Docker uses it's own file system but it copies everything over (including permissions bits) from the source directories.

How to get CSS to select ID that begins with a string (not in Javascript)?

I'd do it like this:

[id^="product"] {
  ...
}

Ideally, use a class. This is what classes are for:

<div id="product176" class="product"></div>
<div id="product177" class="product"></div>
<div id="product178" class="product"></div>

And now the selector becomes:

.product {
  ...
}

TypeScript or JavaScript type casting

In typescript it is possible to do an instanceof check in an if statement and you will have access to the same variable with the Typed properties.

So let's say MarkerSymbolInfo has a property on it called marker. You can do the following:

if (symbolInfo instanceof MarkerSymbol) {
    // access .marker here
    const marker = symbolInfo.marker
}

It's a nice little trick to get the instance of a variable using the same variable without needing to reassign it to a different variable name.

Check out these two resources for more information:

TypeScript instanceof & JavaScript instanceof

How to make the HTML link activated by clicking on the <li>?

Or you can create an empty link at the end of your <li>:

<a href="link"></a>

.menu li{position:relative;padding:0;}
.link{
     bottom: 0;
     left: 0;
     position: absolute;
     right: 0;
     top: 0;
}

This will create a full clickable <li> and keep your formatting on your real link. It could be useful for <div> tag as well

Purge or recreate a Ruby on Rails database

On rails 4.2, to remove all data but preserve the database

$ bin/rake db:purge && bin/rake db:schema:load

https://github.com/rails/rails/blob/4-2-stable/activerecord/CHANGELOG.md

Sending POST data without form

You could use AJAX to send a POST request if you don't want forms.

Using jquery $.post method it is pretty simple:

$.post('/foo.php', { key1: 'value1', key2: 'value2' }, function(result) {
    alert('successfully posted key1=value1&key2=value2 to foo.php');
});

jQuery animate scroll

You can give this simple jQuery plugin (AnimateScroll) a whirl. It is quite easy to use.

1. Scroll to the top of the page:

$('body').animatescroll();

2. Scroll to an element with ID section-1:

$('#section-1').animatescroll({easing:'easeInOutBack'});

Disclaimer: I am the author of this plugin.

Purpose of a constructor in Java?

Constructors are used to initialize the instances of your classes. You use a constructor to create new objects often with parameters specifying the initial state or other important information about the object

From the official Java tutorial:

A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type. For example, Bicycle has one constructor:

public Bicycle(int startCadence, int startSpeed, int startGear) {
    gear = startGear;
    cadence = startCadence;
    speed = startSpeed;
}

To create a new Bicycle object called myBike, a constructor is called by the new operator:

Bicycle myBike = new Bicycle(30, 0, 8);

new Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields.

Although Bicycle only has one constructor, it could have others, including a no-argument constructor:

public Bicycle() { gear = 1; cadence = 10; speed = 0; }

Bicycle yourBike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle object called yourBike.

How do I make the scrollbar on a div only visible when necessary?

try

<div style='overflow:auto; width:400px;height:400px;'>here is some text</div>

How to set a default value with Html.TextBoxFor?

this worked for me , in this way we setting the default value to empty string

@Html.TextBoxFor(m => m.Id, new { @Value = "" })

What are the best JVM settings for Eclipse?

You can also try running with JRockit. It's a JVM optimized for servers, but many long running client applications, like IDE's, run very well on JRockit. Eclipse is no exception. JRockit doesn't have a perm-space so you don't need to configure it.

It's possible set a pause time target(ms) to avoid long gc pauses stalling the UI.

-showsplash
org.eclipse.platform
-vm
 C:\jrmc-3.1.2-1.6.0\bin\javaw.exe 
-vmargs
-XgcPrio:deterministic
-XpauseTarget:20

I usually don't bother setting -Xmx and -Xms and let JRockit grow the heap as it sees necessary. If you launch your Eclipse application with JRockit you can also monitor, profile and find memory leaks in your application using the JRockit Mission Control tools suite. You download the plugins from this update site. Note, only works for Eclipse 3.3 and Eclipse 3.4

Border around each cell in a range

xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeLeft).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeTop).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid