Programs & Examples On #Dynamic class

How to make the division of 2 ints produce a float instead of another int?

Just cast one of the two operands to a float first.

v = (float)s / t;

The cast has higher precedence than the division, so happens before the division.

The other operand will be effectively automatically cast to a float by the compiler because the rules say that if either operand is of floating point type then the operation will be a floating point operation, even if the other operand is integral. Java Language Specification, §4.2.4 and §15.17

Simplest way to display current month and year like "Aug 2016" in PHP?

Here is a simple and more update format of getting the data:

   $now = new \DateTime('now');
   $month = $now->format('m');
   $year = $now->format('Y');

How to get Domain name from URL using jquery..?

While pure JavaScript is sufficient here, I still prefer the jQuery approach. After all, the ask was to get the hostname using jQuery.

var hostName = $(location).attr('hostname');      // www.example.com

"elseif" syntax in JavaScript

Conditional statements are used to perform different actions based on different conditions.

Use if to specify a block of code to be executed, if a specified condition is true

Use else to specify a block of code to be executed, if the same condition is false

Use else if to specify a new condition to test, if the first condition is false

How to convert a String to a Date using SimpleDateFormat?

You have used some type errors. If you want to set 08/16/2011 to following pattern. It is wrong because,

mm stands for minutes, use MM as it is for Months

DD is wrong, it should be dd which represents Days

Try this to achieve the output you want to get ( Tue Aug 16 "Whatever Time" IST 2011 ),

    String date = "08/16/2011"; //input date as String

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy"); // date pattern

    Date myDate = simpleDateFormat.parse(date); // returns date object 

    System.out.println(myDate); //outputs: Tue Aug 16 00:00:00 IST 2011

How to compare two dates to find time difference in SQL Server 2005, date manipulation

Try this in Sql Server

SELECT 
      start_date as firstdate,end_date as seconddate
       ,cast(datediff(MI,start_date,end_date)as decimal(10,3)) as minutediff
      ,cast(cast(cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60) as int ) as varchar(10)) + ' ' + 'Days' + ' ' 
      + cast(cast((cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60) - 
        floor(cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60)) ) * 24 as int) as varchar(10)) + ':' 

     + cast( cast(((cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60) 
      - floor(cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60)))*24
        -
        cast(floor((cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60) 
      - floor(cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60)))*24) as decimal)) * 60 as int) as varchar(10))

    FROM [AdventureWorks2012].dbo.learndate

Where are static methods and static variables stored in Java?

When we create a static variable or method it is stored in the special area on heap: PermGen(Permanent Generation), where it lays down with all the data applying to classes(non-instance data). Starting from Java 8 the PermGen became - Metaspace. The difference is that Metaspace is auto-growing space, while PermGen has a fixed Max size, and this space is shared among all of the instances. Plus the Metaspace is a part of a Native Memory and not JVM Memory.

You can look into this for more details.

Private vs Protected - Visibility Good-Practice Concern

Let me preface this by saying I'm talking primarily about method access here, and to a slightly lesser extent, marking classes final, not member access.

The old wisdom

"mark it private unless you have a good reason not to"

made sense in days when it was written, before open source dominated the developer library space and VCS/dependency mgmt. became hyper collaborative thanks to Github, Maven, etc. Back then there was also money to be made by constraining the way(s) in which a library could be utilized. I spent probably the first 8 or 9 years of my career strictly adhering to this "best practice".

Today, I believe it to be bad advice. Sometimes there's a reasonable argument to mark a method private, or a class final but it's exceedingly rare, and even then it's probably not improving anything.

Have you ever:

  • Been disappointed, surprised or hurt by a library etc. that had a bug that could have been fixed with inheritance and few lines of code, but due to private / final methods and classes were forced to wait for an official patch that might never come? I have.
  • Wanted to use a library for a slightly different use case than was imagined by the authors but were unable to do so because of private / final methods and classes? I have.
  • Been disappointed, surprised or hurt by a library etc. that was overly permissive in it's extensibility? I have not.

These are the three biggest rationalizations I've heard for marking methods private by default:

Rationalization #1: It's unsafe and there's no reason to override a specific method

I can't count the number of times I've been wrong about whether or not there will ever be a need to override a specific method I've written. Having worked on several popular open source libs, I learned the hard way the true cost of marking things private. It often eliminates the only practical solution to unforseen problems or use cases. Conversely, I've never in 16+ years of professional development regretted marking a method protected instead of private for reasons related to API safety. When a developer chooses to extend a class and override a method, they are consciously saying "I know what I'm doing." and for the sake of productivity that should be enough. period. If it's dangerous, note it in the class/method Javadocs, don't just blindly slam the door shut.

Marking methods protected by default is a mitigation for one of the major issues in modern SW development: failure of imagination.

Rationalization #2: It keeps the public API / Javadocs clean

This one is more reasonable, and depending on the target audience it might even be the right thing to do, but it's worth considering what the cost of keeping the API "clean" actually is: extensibility. For the reasons mentioned above, it probably makes more sense to mark things protected by default just in case.

Rationalization #3: My software is commercial and I need to restrict it's use.

This is reasonable too, but as a consumer I'd go with the less restrictive competitor (assuming no significant quality differences exist) every time.

Never say never

I'm not saying never mark methods private. I'm saying the better rule of thumb is to "make methods protected unless there's a good reason not to".

This advice is best suited for those working on libraries or larger scale projects that have been broken into modules. For smaller or more monolithic projects it doesn't tend to matter as much since you control all the code anyway and it's easy to change the access level of your code if/when you need it. Even then though, I'd still give the same advice :-)

JavaScript blob filename without link

The only way I'm aware of is the trick used by FileSaver.js:

  1. Create a hidden <a> tag.
  2. Set its href attribute to the blob's URL.
  3. Set its download attribute to the filename.
  4. Click on the <a> tag.

Here is a simplified example (jsfiddle):

var saveData = (function () {
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    return function (data, fileName) {
        var json = JSON.stringify(data),
            blob = new Blob([json], {type: "octet/stream"}),
            url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = fileName;
        a.click();
        window.URL.revokeObjectURL(url);
    };
}());

var data = { x: 42, s: "hello, world", d: new Date() },
    fileName = "my-download.json";

saveData(data, fileName);

I wrote this example just to illustrate the idea, in production code use FileSaver.js instead.

Notes

  • Older browsers don't support the "download" attribute, since it's part of HTML5.
  • Some file formats are considered insecure by the browser and the download fails. Saving JSON files with txt extension works for me.

Return JSON for ResponseEntity<String>

public ResponseEntity<?> ApiCall(@PathVariable(name = "id") long id) {
    JSONObject resp = new JSONObject();
    resp.put("status", 0);
    resp.put("id", id);

    return new ResponseEntity<String>(resp.toString(), HttpStatus.CREATED);
}

Select first occurring element after another element

#many .more.selectors h4 + p { ... }

This is called the adjacent sibling selector.

How to check if a variable is a dictionary in Python?

How would you check if a variable is a dictionary in Python?

This is an excellent question, but it is unfortunate that the most upvoted answer leads with a poor recommendation, type(obj) is dict.

(Note that you should also not use dict as a variable name - it's the name of the builtin object.)

If you are writing code that will be imported and used by others, do not presume that they will use the dict builtin directly - making that presumption makes your code more inflexible and in this case, create easily hidden bugs that would not error the program out.

I strongly suggest, for the purposes of correctness, maintainability, and flexibility for future users, never having less flexible, unidiomatic expressions in your code when there are more flexible, idiomatic expressions.

is is a test for object identity. It does not support inheritance, it does not support any abstraction, and it does not support the interface.

So I will provide several options that do.

Supporting inheritance:

This is the first recommendation I would make, because it allows for users to supply their own subclass of dict, or a OrderedDict, defaultdict, or Counter from the collections module:

if isinstance(any_object, dict):

But there are even more flexible options.

Supporting abstractions:

from collections.abc import Mapping

if isinstance(any_object, Mapping):

This allows the user of your code to use their own custom implementation of an abstract Mapping, which also includes any subclass of dict, and still get the correct behavior.

Use the interface

You commonly hear the OOP advice, "program to an interface".

This strategy takes advantage of Python's polymorphism or duck-typing.

So just attempt to access the interface, catching the specific expected errors (AttributeError in case there is no .items and TypeError in case items is not callable) with a reasonable fallback - and now any class that implements that interface will give you its items (note .iteritems() is gone in Python 3):

try:
    items = any_object.items()
except (AttributeError, TypeError):
    non_items_behavior(any_object)
else: # no exception raised
    for item in items: ...

Perhaps you might think using duck-typing like this goes too far in allowing for too many false positives, and it may be, depending on your objectives for this code.

Conclusion

Don't use is to check types for standard control flow. Use isinstance, consider abstractions like Mapping or MutableMapping, and consider avoiding type-checking altogether, using the interface directly.

Two versions of python on linux. how to make 2.7 the default

Add /usr/local/bin to your PATH environment variable, earlier in the list than /usr/bin.

Generally this is done in your shell's rc file, e.g. for bash, you'd put this in .bashrc:

export PATH="/usr/local/bin:$PATH"

This will cause your shell to look first for a python in /usr/local/bin, before it goes with the one in /usr/bin.

(Of course, this means you also need to have /usr/local/bin/python point to python2.7 - if it doesn't already, you'll need to symlink it.)

When to use Common Table Expression (CTE)

 ;with cte as
  (
  Select Department, Max(salary) as MaxSalary
  from test
  group by department
  )  
  select t.* from test t join cte c on c.department=t.department 
  where t.salary=c.MaxSalary;

try this

Sending arrays with Intent.putExtra

You are setting the extra with an array. You are then trying to get a single int.

Your code should be:

int[] arrayB = extras.getIntArray("numbers");

How to get files in a relative path in C#

string currentDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string archiveFolder = Path.Combine(currentDirectory, "archive");
string[] files = Directory.GetFiles(archiveFolder, "*.zip");

The first parameter is the path. The second is the search pattern you want to use.

How to remove the querystring and get only the url?

Because I deal with both relative and absolute URLs, I updated veritas's solution like the code below.
You can try yourself here: https://ideone.com/PvpZ4J

function removeQueryStringFromUrl($url) {
    if (substr($url,0,4) == "http") {
        $urlPartsArray = parse_url($url);
        $outputUrl = $urlPartsArray['scheme'] . '://' . $urlPartsArray['host'] . ( isset($urlPartsArray['path']) ? $urlPartsArray['path'] : '' );
    } else {
        $URLexploded = explode("?", $url, 2);
        $outputUrl = $URLexploded[0];
    }
    return $outputUrl;
}

How to discard uncommitted changes in SourceTree?

I like to use

git stash

This stores all uncommitted changes in the stash. If you want to discard these changes later just git stash drop (or git stash pop to restore them).

Though this is technically not the "proper" way to discard changes (as other answers and comments have pointed out).

SourceTree: On the top bar click on icon 'Stash', type its name and create. Then in left vertical menu you can "show" all Stash and delete in right-click menu. There is probably no other way in ST to discard all files at once.

How do I solve the "server DNS address could not be found" error on Windows 10?

Steps to manually configure DNS:

  1. You can access Network and Sharing center by right clicking on the Network icon on the taskbar.

  2. Now choose adapter settings from the side menu.

  3. This will give you a list of the available network adapters in the system . From them right click on the adapter you are using to connect to the internet now and choose properties option.

  4. In the networking tab choose ‘Internet Protocol Version 4 (TCP/IPv4)’.

  5. Now you can see the properties dialogue box showing the properties of IPV4. Here you need to change some properties.

    Select ‘use the following DNS address’ option. Now fill the following fields as given here.

    Preferred DNS server: 208.67.222.222

    Alternate DNS server : 208.67.220.220

    This is an available Open DNS address. You may also use google DNS server addresses.

    After filling these fields. Check the ‘validate settings upon exit’ option. Now click OK.

You have to add this DNS server address in the router configuration also (by referring the router manual for more information).

Refer : for above method & alternative

If none of this works, then open command prompt(Run as Administrator) and run these:

ipconfig /flushdns
ipconfig /registerdns
ipconfig /release
ipconfig /renew
NETSH winsock reset catalog
NETSH int ipv4 reset reset.log
NETSH int ipv6 reset reset.log
Exit

Hopefully that fixes it, if its still not fixed there is a chance that its a NIC related issue(driver update or h/w).

Also FYI, this has a thread on Microsoft community : Windows 10 - DNS Issue

Change color and appearance of drop down arrow

Try changing the color of your "border-top" attribute to white

Truncate Two decimal places without rounding

would this work for you?

Console.Write(((int)(3.4679999999*100))/100.0);

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

Swift 5 You can use a UIView extension so that you can add bottom border to any view:

extension UIView {

    func addBottomLine(width: CGFloat, color: UIColor) {
        let lineView: UIView = {
            let view = UIView()
            view.translatesAutoresizingMaskIntoConstraints = false
            view.backgroundColor = color
            return view
        }()
        addSubview(lineView)
        NSLayoutConstraint.activate([
            lineView.heightAnchor.constraint(equalToConstant: width),
            lineView.leadingAnchor.constraint(equalTo: leadingAnchor),
            lineView.trailingAnchor.constraint(equalTo: trailingAnchor),
            lineView.bottomAnchor.constraint(equalTo: bottomAnchor)
        ])
    }

}

How to insert a SQLite record with a datetime set to 'now' in Android application?

Works for me perfect:

    values.put(DBHelper.COLUMN_RECEIVEDATE, geo.getReceiveDate().getTime());

Save your date as a long.

How do I make a file:// hyperlink that works in both IE and Firefox?

file Protocol
Opens a file on a local or network drive.

Syntax

Copy
 file:///sDrives[|sFile]
Tokens 

sDrives
Specifies the local or network drive.

sFile
Optional. Specifies the file to open. If sFile is omitted and the account accessing the drive has permission to browse the directory, a list of accessible files and directories is displayed.

Remarks

The file protocol and sDrives parameter can be omitted and substituted with just the command line representation of the drive letter and file location. For example, to browse the My Documents directory, the file protocol can be specified as file:///C|/My Documents/ or as C:\My Documents. In addition, a single '\' is equivalent to specifying the root directory on the primary local drive. On most computers, this is C:.

Available as of Microsoft Internet Explorer 3.0 or later.

Note Internet Explorer 6 Service Pack 1 (SP1) no longer allows browsing a local machine from the Internet zone. For instance, if an Internet site contains a link to a local file, Internet Explorer 6 SP1 displays a blank page when a user clicks on the link. Previous versions of Windows Internet Explorer followed the link to the local file.

Example

The following sample demonstrates four ways to use the File protocol.

Copy

//Specifying a drive and a file name. 

file:///C|/My Documents/ALetter.html

//Specifying only a drive and a path to browse the directory. 

file:///C|/My Documents/

//Specifying a drive and a directory using the command line representation of the directory location. 

C:\My Documents\

//Specifying only the directory on the local primary drive. 

\My Documents\

http://msdn.microsoft.com/en-us/library/aa767731

Javascript - Open a given URL in a new tab by clicking a button

You can forget about using JavaScript because the browser controls whether or not it opens in a new tab. Your best option is to do something like the following instead:

<form action="http://www.yoursite.com/dosomething" method="get" target="_blank">
    <input name="dynamicParam1" type="text"/>
    <input name="dynamicParam2" type="text" />
    <input type="submit" value="submit" />
</form>

This will always open in a new tab regardless of which browser a client uses due to the target="_blank" attribute.

If all you need is to redirect with no dynamic parameters you can use a link with the target="_blank" attribute as Tim Büthe suggests.

The module ".dll" was loaded but the entry-point was not found

The error indicates that the DLL is either not a COM DLL or it's corrupt. If it's not a COM DLL and not being used as a COM DLL by an application then there is no need to register it.
From what you say in your question (the service is not registered) it seems that we are talking about a service not correctly installed. I will try to reinstall the application.

JavaScript: How to pass object by value?

As a consideration to jQuery users, there is also a way to do this in a simple way using the framework. Just another way jQuery makes our lives a little easier.

var oShallowCopy = jQuery.extend({}, o);
var oDeepCopy    = jQuery.extend(true, {}, o); 

references :

Local Storage vs Cookies

It is also worth mentioning that localStorage cannot be used when users browse in "private" mode in some versions of mobile Safari.

Quoted from MDN (https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage):

Note: Starting with iOS 5.1, Safari Mobile stores localStorage data in the cache folder, which is subject to occasional clean up, at the behest of the OS, typically if space is short. Safari Mobile's Private Browsing mode also prevents writing to localStorage entirely.

Disable HTTP OPTIONS, TRACE, HEAD, COPY and UNLOCK methods in IIS

This worked for me but only after forcing the specific verbs to be handled by the default handler.

<system.web>
...
  <httpHandlers>
  ... 
    <add path="*" verb="OPTIONS" type="System.Web.DefaultHttpHandler" validate="true"/>
    <add path="*" verb="TRACE" type="System.Web.DefaultHttpHandler" validate="true"/>
    <add path="*" verb="HEAD" type="System.Web.DefaultHttpHandler" validate="true"/>

You still use the same configuration as you have above, but also force the verbs to be handled with the default handler and validated. Source: http://forums.asp.net/t/1311323.aspx

An easy way to test is just to deny GET and see if your site loads.

Why Local Users and Groups is missing in Computer Management on Windows 10 Home?

Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.

You can use User Accounts by pressing Window+R, typing netplwiz and pressing OK as described here.

How to set array length in c# dynamically

Or in C# 3.0 using System.Linq you can skip the intermediate list:

private Update BuildMetaData(MetaData[] nvPairs)
{
        Update update = new Update();
        var ip = from nv in nvPairs
                 select new InputProperty()
                 {
                     Name = "udf:" + nv.Name,
                     Val = nv.Value
                 };
        update.Items = ip.ToArray();
        return update;
}

FIFO class in Java

if you want to have a pipe to write/read data, you can use the http://docs.oracle.com/javase/6/docs/api/java/io/PipedWriter.html

How to check if a float value is a whole number

You can use a modulo operation for that.

if (n ** (1.0/3)) % 1 != 0:
    print("We have a decimal number here!")

How to create a new file in unix?

The command is lowercase: touch filename.

Keep in mind that touch will only create a new file if it does not exist! Here's some docs for good measure: http://unixhelp.ed.ac.uk/CGI/man-cgi?touch

If you always want an empty file, one way to do so would be to use:

echo "" > filename

How to install JQ on Mac by command-line?

On a Mac, the "most efficient" way to install jq would probably be using homebrew, e.g.

brew install jq

If you want the development version, you could try:

brew install --HEAD jq

but this has various pre-requisites.

Detailed instructions are on the "Installation" page of the jq wiki: https://github.com/stedolan/jq/wiki/Installation

The same page also includes details regarding installation from source, and has notes on installing with MacPorts.

Google drive limit number of download

Sure Google has a limit of downloads so that you don't abuse the system. These are the limits if you are using Gmail:

The following limits apply for Google Apps for Business or Education editions. Limits for domains during trial are lower. These limits may change without notice in order to protect Google’s infrastructure.

Bandwidth limits

Limit                          Per hour            Per day
Download via web client        750 MB              1250 MB
Upload via web client          300 MB              500 MB
POP and IMAP bandwidth limits

Limit                Per day
Download via IMAP    2500 MB
Download via POP     1250 MB
Upload via IMAP      500 MB

check out this link

TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

You have to import FormsModule into not only the root AppModule, but also into every subModule that uses any angular forms directives.

// SubModule A

import { CommonModule } from '@angular/common';
import { FormsModule }   from '@angular/forms';

@NgModule({
  imports: [
    CommonModule,
    FormsModule      //<----------make sure you have added this.
  ],
  ....
})

How to customize the back button on ActionBar

tray this:

getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close);

inside onCreate();

How to stop a PowerShell script on the first error?

Sadly, due to buggy cmdlets like New-RegKey and Clear-Disk, none of these answers are enough. I've currently settled on the following code in a file called ps_support.ps1:

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$PSDefaultParameterValues['*:ErrorAction']='Stop'
function ThrowOnNativeFailure {
    if (-not $?)
    {
        throw 'Native Failure'
    }
}

Then in any powershell file, after the CmdletBinding and Param for the file (if present), I have the following:

$ErrorActionPreference = "Stop"
. "$PSScriptRoot\ps_support.ps1"

The duplicated ErrorActionPreference = "Stop" line is intentional. If I've goofed and somehow gotten the path to ps_support.ps1 wrong, that needs to not silently fail!

I keep ps_support.ps1 in a common location for my repo/workspace, so the path to it for the dot-sourcing may change depending on where the current .ps1 file is.

Any native call gets this treatment:

native_call.exe
ThrowOnNativeFailure

Having that file to dot-source has helped me maintain my sanity while writing powershell scripts. :-)

Android webview & localStorage

The following was missing:

settings.setDomStorageEnabled(true);

Adding/removing items from a JavaScript object with jQuery

Splice is good, everyone explain splice so I didn't explain it. You can also use delete keyword in JavaScript, it's good. You can use $.grep also to manipulate this using jQuery.

The jQuery Way :

data.items = jQuery.grep(
                data.items, 
                function (item,index) { 
                  return item.id !=  "1"; 
                });

DELETE Way:

delete data.items[0]

For Adding PUSH is better the splice, because splice is heavy weighted function. Splice create a new array , if you have a huge size of array then it may be troublesome. delete is sometime useful, after delete if you look for the length of the array then there is no change in length there. So use it wisely.

Check number of arguments passed to a Bash script

A simple one liner that works can be done using:

[ "$#" -ne 1 ] && ( usage && exit 1 ) || main

This breaks down to:

  1. test the bash variable for size of parameters $# not equals 1 (our number of sub commands)
  2. if true then call usage() function and exit with status 1
  3. else call main() function

Things to note:

  • usage() can just be simple echo "$0: params"
  • main can be one long script

Finding square root without using sqrt function?

Here is a very awesome code to find sqrt and even faster than original sqrt function.

float InvSqrt (float x) 
{
    float xhalf = 0.5f*x;
    int i = *(int*)&x;
    i = 0x5f375a86 - (i>>1);
    x = *(float*)&i;
    x = x*(1.5f - xhalf*x*x);
    x = x*(1.5f - xhalf*x*x);
    x = x*(1.5f - xhalf*x*x);
    x=1/x;
    return x;
}

Add a space (" ") after an element using :after

There can be a problem with "\00a0" in pseudo-elements because it takes the text-decoration of its defining element, so that, for example, if the defining element is underlined, then the white space of the pseudo-element is also underlined.

The easiest way to deal with this is to define the opacity of the pseudo-element to be zero, eg:

element:before{
  content: "_";
  opacity: 0;
}

Java constant examples (Create a java file having only constants)

Neither one. Use final class for Constants declare them as public static final and static import all constants wherever necessary.

public final class Constants {

    private Constants() {
            // restrict instantiation
    }

    public static final double PI = 3.14159;
    public static final double PLANCK_CONSTANT = 6.62606896e-34;
}

Usage :

import static Constants.PLANCK_CONSTANT;
import static Constants.PI;//import static Constants.*;

public class Calculations {

        public double getReducedPlanckConstant() {
                return PLANCK_CONSTANT / (2 * PI);
        }
}

See wiki link : http://en.wikipedia.org/wiki/Constant_interface

Change an image with onclick()

To change image onclik with javascript you need to have image with id:

<p>
        <img alt="" src="http://www.userinterfaceicons.com/80x80/minimize.png" 
            style="height: 85px; width: 198px" id="imgClickAndChange" onclick="changeImage()"  />
</p>

Then you could call javascript function when image is clicked:

<script language="javascript">
    function changeImage() {

        if (document.getElementById("imgClickAndChange").src == "http://www.userinterfaceicons.com/80x80/minimize.png") 
        {
            document.getElementById("imgClickAndChange").src = "http://www.userinterfaceicons.com/80x80/maximize.png";
        }
        else 
        {
            document.getElementById("imgClickAndChange").src = "http://www.userinterfaceicons.com/80x80/minimize.png";
        }
    }
</script>

This code will set image to maximize.png if current img.src is set to minimize.png and vice versa. For more details visit: Change image onclick with javascript link

How can I exclude $(this) from a jQuery selector?

Try using the not() method instead of the :not() selector.

$(".content a").click(function() {
    $(".content a").not(this).hide("slow");
});

Difference Between Cohesion and Coupling

Increased cohesion and decreased coupling do lead to good software design.

Cohesion partitions your functionality so that it is concise and closest to the data relevant to it, whilst decoupling ensures that the functional implementation is isolated from the rest of the system.

Decoupling allows you to change the implementation without affecting other parts of your software.

Cohesion ensures that the implementation more specific to functionality and at the same time easier to maintain.

The most effective method of decreasing coupling and increasing cohesion is design by interface.

That is major functional objects should only 'know' each other through the interface(s) that they implement. The implementation of an interface introduces cohesion as a natural consequence.

Whilst not realistic in some senarios it should be a design goal to work by.

Example (very sketchy):

public interface IStackoverFlowQuestion
      void SetAnswered(IUserProfile user);
      void VoteUp(IUserProfile user);
      void VoteDown(IUserProfile user);
}

public class NormalQuestion implements IStackoverflowQuestion {
      protected Integer vote_ = new Integer(0);
      protected IUserProfile user_ = null;
      protected IUserProfile answered_ = null;

      public void VoteUp(IUserProfile user) {
           vote_++;
           // code to ... add to user profile
      }

      public void VoteDown(IUserProfile user) {
          decrement and update profile
      }

      public SetAnswered(IUserProfile answer) {
           answered_ = answer
           // update u
      }
}

public class CommunityWikiQuestion implements IStackoverflowQuestion {
     public void VoteUp(IUserProfile user) { // do not update profile }
     public void VoteDown(IUserProfile user) { // do not update profile }
     public void SetAnswered(IUserProfile user) { // do not update profile }
}

Some where else in your codebase you could have a module that processes questions regardless of what they are:

public class OtherModuleProcessor {
    public void Process(List<IStackoverflowQuestion> questions) {
       ... process each question.
    }
}

How to open local file on Jupyter?

On osX, Your path should be:

path = "/Users/name/Downloads/filename"

with name the current user logged in

What is the difference between 127.0.0.1 and localhost

Well, the most likely difference is that you still have to do an actual lookup of localhost somewhere.

If you use 127.0.0.1, then (intelligent) software will just turn that directly into an IP address and use it. Some implementations of gethostbyname will detect the dotted format (and presumably the equivalent IPv6 format) and not do a lookup at all.

Otherwise, the name has to be resolved. And there's no guarantee that your hosts file will actually be used for that resolution (first, or at all) so localhost may become a totally different IP address.

By that I mean that, on some systems, a local hosts file can be bypassed. The host.conf file controls this on Linux (and many other Unices).

Python - abs vs fabs

Edit: as @aix suggested, a better (more fair) way to compare the speed difference:

In [1]: %timeit abs(5)
10000000 loops, best of 3: 86.5 ns per loop

In [2]: from math import fabs

In [3]: %timeit fabs(5)
10000000 loops, best of 3: 115 ns per loop

In [4]: %timeit abs(-5)
10000000 loops, best of 3: 88.3 ns per loop

In [5]: %timeit fabs(-5)
10000000 loops, best of 3: 114 ns per loop

In [6]: %timeit abs(5.0)
10000000 loops, best of 3: 92.5 ns per loop

In [7]: %timeit fabs(5.0)
10000000 loops, best of 3: 93.2 ns per loop

In [8]: %timeit abs(-5.0)
10000000 loops, best of 3: 91.8 ns per loop

In [9]: %timeit fabs(-5.0)
10000000 loops, best of 3: 91 ns per loop

So it seems abs() only has slight speed advantage over fabs() for integers. For floats, abs() and fabs() demonstrate similar speed.


In addition to what @aix has said, one more thing to consider is the speed difference:

In [1]: %timeit abs(-5)
10000000 loops, best of 3: 102 ns per loop

In [2]: import math

In [3]: %timeit math.fabs(-5)
10000000 loops, best of 3: 194 ns per loop

So abs() is faster than math.fabs().

What are the ways to make an html link open a folder

A bit late to the party, but I had to solve this for myself recently, though slightly different, it might still help someone with similar circumstances to my own.

I'm using xampp on a laptop to run a purely local website app on windows. (A very specific environment I know). In this instance, I use a html link to a php file and run:

shell_exec('cd C:\path\to\file');
shell_exec('start .');

This opens a local Windows explorer window.

Static variable inside of a function in C

Let's just read the Wikipedia article on Static Variables...

Static local variables: variables declared as static inside a function are statically allocated while having the same scope as automatic local variables. Hence whatever values the function puts into its static local variables during one call will still be present when the function is called again.

Difference between System.DateTime.Now and System.DateTime.Today

Time. .Now includes the 09:23:12 or whatever; .Today is the date-part only (at 00:00:00 on that day).

So use .Now if you want to include the time, and .Today if you just want the date!

.Today is essentially the same as .Now.Date

How do I make JavaScript beep?

This will enable you to play the sound multiple times, in contrast to the top-voted answer:

var playSound = (function beep() {
    var snd = new Audio("data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYkXgoQwAEaYLWfkWgAI0wWs/ItAAAGDgYtAgAyN+QWaAAihwMWm4G8QQRDiMcCBcH3Cc+CDv/7xA4Tvh9Rz/y8QADBwMWgQAZG/ILNAARQ4GLTcDeIIIhxGOBAuD7hOfBB3/94gcJ3w+o5/5eIAIAAAVwWgQAVQ2ORaIQwEMAJiDg95G4nQL7mQVWI6GwRcfsZAcsKkJvxgxEjzFUgfHoSQ9Qq7KNwqHwuB13MA4a1q/DmBrHgPcmjiGoh//EwC5nGPEmS4RcfkVKOhJf+WOgoxJclFz3kgn//dBA+ya1GhurNn8zb//9NNutNuhz31f////9vt///z+IdAEAAAK4LQIAKobHItEIYCGAExBwe8jcToF9zIKrEdDYIuP2MgOWFSE34wYiR5iqQPj0JIeoVdlG4VD4XA67mAcNa1fhzA1jwHuTRxDUQ//iYBczjHiTJcIuPyKlHQkv/LHQUYkuSi57yQT//uggfZNajQ3Vmz+Zt//+mm3Wm3Q576v////+32///5/EOgAAADVghQAAAAA//uQZAUAB1WI0PZugAAAAAoQwAAAEk3nRd2qAAAAACiDgAAAAAAABCqEEQRLCgwpBGMlJkIz8jKhGvj4k6jzRnqasNKIeoh5gI7BJaC1A1AoNBjJgbyApVS4IDlZgDU5WUAxEKDNmmALHzZp0Fkz1FMTmGFl1FMEyodIavcCAUHDWrKAIA4aa2oCgILEBupZgHvAhEBcZ6joQBxS76AgccrFlczBvKLC0QI2cBoCFvfTDAo7eoOQInqDPBtvrDEZBNYN5xwNwxQRfw8ZQ5wQVLvO8OYU+mHvFLlDh05Mdg7BT6YrRPpCBznMB2r//xKJjyyOh+cImr2/4doscwD6neZjuZR4AgAABYAAAABy1xcdQtxYBYYZdifkUDgzzXaXn98Z0oi9ILU5mBjFANmRwlVJ3/6jYDAmxaiDG3/6xjQQCCKkRb/6kg/wW+kSJ5//rLobkLSiKmqP/0ikJuDaSaSf/6JiLYLEYnW/+kXg1WRVJL/9EmQ1YZIsv/6Qzwy5qk7/+tEU0nkls3/zIUMPKNX/6yZLf+kFgAfgGyLFAUwY//uQZAUABcd5UiNPVXAAAApAAAAAE0VZQKw9ISAAACgAAAAAVQIygIElVrFkBS+Jhi+EAuu+lKAkYUEIsmEAEoMeDmCETMvfSHTGkF5RWH7kz/ESHWPAq/kcCRhqBtMdokPdM7vil7RG98A2sc7zO6ZvTdM7pmOUAZTnJW+NXxqmd41dqJ6mLTXxrPpnV8avaIf5SvL7pndPvPpndJR9Kuu8fePvuiuhorgWjp7Mf/PRjxcFCPDkW31srioCExivv9lcwKEaHsf/7ow2Fl1T/9RkXgEhYElAoCLFtMArxwivDJJ+bR1HTKJdlEoTELCIqgEwVGSQ+hIm0NbK8WXcTEI0UPoa2NbG4y2K00JEWbZavJXkYaqo9CRHS55FcZTjKEk3NKoCYUnSQ0rWxrZbFKbKIhOKPZe1cJKzZSaQrIyULHDZmV5K4xySsDRKWOruanGtjLJXFEmwaIbDLX0hIPBUQPVFVkQkDoUNfSoDgQGKPekoxeGzA4DUvnn4bxzcZrtJyipKfPNy5w+9lnXwgqsiyHNeSVpemw4bWb9psYeq//uQZBoABQt4yMVxYAIAAAkQoAAAHvYpL5m6AAgAACXDAAAAD59jblTirQe9upFsmZbpMudy7Lz1X1DYsxOOSWpfPqNX2WqktK0DMvuGwlbNj44TleLPQ+Gsfb+GOWOKJoIrWb3cIMeeON6lz2umTqMXV8Mj30yWPpjoSa9ujK8SyeJP5y5mOW1D6hvLepeveEAEDo0mgCRClOEgANv3B9a6fikgUSu/DmAMATrGx7nng5p5iimPNZsfQLYB2sDLIkzRKZOHGAaUyDcpFBSLG9MCQALgAIgQs2YunOszLSAyQYPVC2YdGGeHD2dTdJk1pAHGAWDjnkcLKFymS3RQZTInzySoBwMG0QueC3gMsCEYxUqlrcxK6k1LQQcsmyYeQPdC2YfuGPASCBkcVMQQqpVJshui1tkXQJQV0OXGAZMXSOEEBRirXbVRQW7ugq7IM7rPWSZyDlM3IuNEkxzCOJ0ny2ThNkyRai1b6ev//3dzNGzNb//4uAvHT5sURcZCFcuKLhOFs8mLAAEAt4UWAAIABAAAAAB4qbHo0tIjVkUU//uQZAwABfSFz3ZqQAAAAAngwAAAE1HjMp2qAAAAACZDgAAAD5UkTE1UgZEUExqYynN1qZvqIOREEFmBcJQkwdxiFtw0qEOkGYfRDifBui9MQg4QAHAqWtAWHoCxu1Yf4VfWLPIM2mHDFsbQEVGwyqQoQcwnfHeIkNt9YnkiaS1oizycqJrx4KOQjahZxWbcZgztj2c49nKmkId44S71j0c8eV9yDK6uPRzx5X18eDvjvQ6yKo9ZSS6l//8elePK/Lf//IInrOF/FvDoADYAGBMGb7FtErm5MXMlmPAJQVgWta7Zx2go+8xJ0UiCb8LHHdftWyLJE0QIAIsI+UbXu67dZMjmgDGCGl1H+vpF4NSDckSIkk7Vd+sxEhBQMRU8j/12UIRhzSaUdQ+rQU5kGeFxm+hb1oh6pWWmv3uvmReDl0UnvtapVaIzo1jZbf/pD6ElLqSX+rUmOQNpJFa/r+sa4e/pBlAABoAAAAA3CUgShLdGIxsY7AUABPRrgCABdDuQ5GC7DqPQCgbbJUAoRSUj+NIEig0YfyWUho1VBBBA//uQZB4ABZx5zfMakeAAAAmwAAAAF5F3P0w9GtAAACfAAAAAwLhMDmAYWMgVEG1U0FIGCBgXBXAtfMH10000EEEEEECUBYln03TTTdNBDZopopYvrTTdNa325mImNg3TTPV9q3pmY0xoO6bv3r00y+IDGid/9aaaZTGMuj9mpu9Mpio1dXrr5HERTZSmqU36A3CumzN/9Robv/Xx4v9ijkSRSNLQhAWumap82WRSBUqXStV/YcS+XVLnSS+WLDroqArFkMEsAS+eWmrUzrO0oEmE40RlMZ5+ODIkAyKAGUwZ3mVKmcamcJnMW26MRPgUw6j+LkhyHGVGYjSUUKNpuJUQoOIAyDvEyG8S5yfK6dhZc0Tx1KI/gviKL6qvvFs1+bWtaz58uUNnryq6kt5RzOCkPWlVqVX2a/EEBUdU1KrXLf40GoiiFXK///qpoiDXrOgqDR38JB0bw7SoL+ZB9o1RCkQjQ2CBYZKd/+VJxZRRZlqSkKiws0WFxUyCwsKiMy7hUVFhIaCrNQsKkTIsLivwKKigsj8XYlwt/WKi2N4d//uQRCSAAjURNIHpMZBGYiaQPSYyAAABLAAAAAAAACWAAAAApUF/Mg+0aohSIRobBAsMlO//Kk4soosy1JSFRYWaLC4qZBYWFRGZdwqKiwkNBVmoWFSJkWFxX4FFRQWR+LsS4W/rFRb/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////VEFHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU291bmRib3kuZGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMjAwNGh0dHA6Ly93d3cuc291bmRib3kuZGUAAAAAAAAAACU=");  
    return function() {     
        snd.play(); 
    }
})();

playSound(); // Play first time
playSound(); // Play second time

'pip install' fails for every package ("Could not find a version that satisfies the requirement")

Support for TLS 1.0 and 1.1 was dropped for PyPI. If your system does not use a more recent version, it could explain your error.

Could you try reinstalling pip system-wide, to update your system dependencies to a newer version of TLS?

This seems to be related to Unable to install Python libraries

See Dominique Barton's answer:

Apparently pip is trying to access PyPI via HTTPS (which is encrypted and fine), but with an old (insecure) SSL version. Your system seems to be out of date. It might help if you update your packages.

On Debian-based systems I'd try:

apt-get update && apt-get upgrade python-pip

On Red Hat Linux-based systems:

yum update python-pip # (or python2-pip, at least on Red Hat Linux 7)

On Mac:

sudo easy_install -U pip

You can also try to update openssl separately.

Difference between res.send and res.json in Express.js

res.json forces the argument to JSON. res.send will take an non-json object or non-json array and send another type. For example:

This will return a JSON number.

res.json(100)

This will return a status code and issue a warning to use sendStatus.

res.send(100)

If your argument is not a JSON object or array (null,undefined,boolean,string), and you want to ensure it is sent as JSON, use res.json.

Map with Key as String and Value as List in Groovy

One additional small piece that is helpful when dealing with maps/list as the value in a map is the withDefault(Closure) method on maps in groovy. Instead of doing the following code:

Map m = [:]
for(object in listOfObjects)
{
  if(m.containsKey(object.myKey))
  {
    m.get(object.myKey).add(object.myValue)
  }
  else
  {
    m.put(object.myKey, [object.myValue]
  }
}

You can do the following:

Map m = [:].withDefault{key -> return []}
for(object in listOfObjects)
{
  List valueList = m.get(object.myKey)
  m.put(object.myKey, valueList)
}

With default can be used for other things as well, but I find this the most common use case for me.

API: http://www.groovy-lang.org/gdk.html

Map -> withDefault(Closure)

How can I add (simple) tracing in C#?

DotNetCoders has a starter article on it: http://www.dotnetcoders.com/web/Articles/ShowArticle.aspx?article=50. They talk about how to set up the switches in the configuration file and how to write the code, but it is pretty old (2002).

There's another article on CodeProject: A Treatise on Using Debug and Trace classes, including Exception Handling, but it's the same age.

CodeGuru has another article on custom TraceListeners: Implementing a Custom TraceListener

How to get length of a list of lists in python

You can do it with reduce:

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [], [1, 2]]
print(reduce(lambda count, l: count + len(l), a, 0))
# result is 11

How to get the name of a class without the package?

Class.getSimpleName()

Returns the simple name of the underlying class as given in the source code. Returns an empty string if the underlying class is anonymous.

The simple name of an array is the simple name of the component type with "[]" appended. In particular the simple name of an array whose component type is anonymous is "[]".

It is actually stripping the package information from the name, but this is hidden from you.

Converting a factor to numeric without losing information R (as.numeric() doesn't seem to work)

First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.

For example,

> z <- factor(letters[c(3, 2, 3, 4)])

# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d

# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"

here, z has 4 elements.
The index is 2, 1, 2, 3 in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.

Then, as.numeric converts simply the index part of factor into numeric.
as.character handles the index and levels, and generates character vector expressed by its level.

?as.numeric says that Factors are handled by the default method.

Redirecting output to $null in PowerShell, but ensuring the variable remains set

Warning messages should be written using the Write-Warning cmdlet, which allows the warning messages to be suppressed with the -WarningAction parameter or the $WarningPreference automatic variable. A function needs to use CmdletBinding to implement this feature.

function WarningTest {
    [CmdletBinding()]
    param($n)

    Write-Warning "This is a warning message for: $n."
    "Parameter n = $n"
}

$a = WarningTest 'test one' -WarningAction SilentlyContinue

# To turn off warnings for multiple commads,
# use the WarningPreference variable
$WarningPreference = 'SilentlyContinue'
$b = WarningTest 'test two'
$c = WarningTest 'test three'
# Turn messages back on.
$WarningPreference = 'Continue'
$c = WarningTest 'test four'

To make it shorter at the command prompt, you can use -wa 0:

PS> WarningTest 'parameter alias test' -wa 0

Write-Error, Write-Verbose and Write-Debug offer similar functionality for their corresponding types of messages.

Update multiple rows in same query using PostgreSQL

For updating multiple rows in a single query, you can try this

UPDATE table_name
SET 
column_1 = CASE WHEN any_column = value and any_column = value THEN column_1_value end,
column_2 = CASE WHEN any_column = value and any_column = value THEN column_2_value end,
column_3 = CASE WHEN any_column = value and any_column = value THEN column_3_value end,
.
.
.
column_n = CASE WHEN any_column = value and any_column = value THEN column_n_value end

if you don't need additional condition then remove and part of this query

What is the best (and safest) way to merge a Git branch into master?

How I would do this

git checkout master
git pull origin master
git merge test
git push origin master

If I have a local branch from a remote one, I don't feel comfortable with merging other branches than this one with the remote. Also I would not push my changes, until I'm happy with what I want to push and also I wouldn't push things at all, that are only for me and my local repository. In your description it seems, that test is only for you? So no reason to publish it.

git always tries to respect yours and others changes, and so will --rebase. I don't think I can explain it appropriately, so have a look at the Git book - Rebasing or git-ready: Intro into rebasing for a little description. It's a quite cool feature

How to get complete current url for Cakephp

The simplest way I found is it that includes host/path/query and
works in Controllers (Cakephp 3.4):

Cake\View\Helper\UrlHelper::build($this->request->getRequestTarget());

which returns something like this (we use it as login callback url) :

http://192.168.0.57/archive?melkId=12

How to format LocalDate to string?

Could be short as:

LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));

Check if a string is palindrome

I'm no c++ guy, but you should be able to get the gist from this.

public static string Reverse(string s) {
    if (s == null || s.Length < 2) {
        return s;
    }

    int length = s.Length;
    int loop = (length >> 1) + 1;
    int j;
    char[] chars = new char[length];
    for (int i = 0; i < loop; i++) {
        j = length - i - 1;
        chars[i] = s[j];
        chars[j] = s[i];
    }
    return new string(chars);
}

Why is there still a row limit in Microsoft Excel?

Probably because of optimizations. Excel 2007 can have a maximum of 16 384 columns and 1 048 576 rows. Strange numbers?

14 bits = 16 384, 20 bits = 1 048 576

14 + 20 = 34 bits = more than one 32 bit register can hold.

But they also need to store the format of the cell (text, number etc) and formatting (colors, borders etc). Assuming they use two 32-bit words (64 bit) they use 34 bits for the cell number and have 30 bits for other things.

Why is that important? In memory they don't need to allocate all the memory needed for the whole spreadsheet but only the memory necessary for your data, and every data is tagged with in what cell it is supposed to be in.

Update 2016:

Found a link to Microsoft's specification for Excel 2013 & 2016

  • Open workbooks: Limited by available memory and system resources
  • Worksheet size: 1,048,576 rows (20 bits) by 16,384 columns (14 bits)
  • Column width: 255 characters (8 bits)
  • Row height: 409 points
  • Page breaks: 1,026 horizontal and vertical (unexpected number, probably wrong, 10 bits is 1024)
  • Total number of characters that a cell can contain: 32,767 characters (signed 16 bits)
  • Characters in a header or footer: 255 (8 bits)
  • Sheets in a workbook: Limited by available memory (default is 1 sheet)
  • Colors in a workbook: 16 million colors (32 bit with full access to 24 bit color spectrum)
  • Named views in a workbook: Limited by available memory
  • Unique cell formats/cell styles: 64,000 (16 bits = 65536)
  • Fill styles: 256 (8 bits)
  • Line weight and styles: 256 (8 bits)
  • Unique font types: 1,024 (10 bits) global fonts available for use; 512 per workbook
  • Number formats in a workbook: Between 200 and 250, depending on the language version of Excel that you have installed
  • Names in a workbook: Limited by available memory
  • Windows in a workbook: Limited by available memory
  • Hyperlinks in a worksheet: 66,530 hyperlinks (unexpected number, probably wrong. 16 bits = 65536)
  • Panes in a window: 4
  • Linked sheets: Limited by available memory
  • Scenarios: Limited by available memory; a summary report shows only the first 251 scenarios
  • Changing cells in a scenario: 32
  • Adjustable cells in Solver: 200
  • Custom functions: Limited by available memory
  • Zoom range: 10 percent to 400 percent
  • Reports: Limited by available memory
  • Sort references: 64 in a single sort; unlimited when using sequential sorts
  • Undo levels: 100
  • Fields in a data form: 32
  • Workbook parameters: 255 parameters per workbook
  • Items displayed in filter drop-down lists: 10,000

How do I remove time part from JavaScript date?

This is probably the easiest way:

new Date(<your-date-object>.toDateString());

Example: To get the Current Date without time component:

new Date(new Date().toDateString());

gives: Thu Jul 11 2019 00:00:00 GMT-0400 (Eastern Daylight Time)

Note this works universally, because toDateString() produces date string with your browser's localization (without the time component), and the new Date() uses the same localization to parse that date string.

android View not attached to window manager

according to the code of the windowManager (link here), this occurs when the view you are trying to update (which probably belongs to a dialog, but not necessary) is no longer attached to the real root of the windows.

as others have suggested, you should check the status of the activity before performing special operations on your dialogs.

here's the relavant code, which is the cause to the problem (copied from Android source code) :

public void updateViewLayout(View view, ViewGroup.LayoutParams params) {
    if (!(params instanceof WindowManager.LayoutParams)) {
        throw new IllegalArgumentException("Params must be WindowManager.LayoutParams");
    }

    final WindowManager.LayoutParams wparams
            = (WindowManager.LayoutParams)params;

    view.setLayoutParams(wparams);

    synchronized (this) {
        int index = findViewLocked(view, true);
        ViewRootImpl root = mRoots[index];
        mParams[index] = wparams;
        root.setLayoutParams(wparams, false);
    }
}

private int findViewLocked(View view, boolean required) {
        synchronized (this) {
            final int count = mViews != null ? mViews.length : 0;
            for (int i=0; i<count; i++) {
                if (mViews[i] == view) {
                    return i;
                }
            }
            if (required) {
                throw new IllegalArgumentException(
                        "View not attached to window manager");
            }
            return -1;
        }
    }

How do I get the current timezone name in Postgres 9.3?

It seems to work fine in Postgresql 9.5:

SELECT current_setting('TIMEZONE');

Javascript: Easier way to format numbers?

No, there is no built-in support for number formatting, but googling will turn up loads of code snippets that will do this for you.

EDIT: I missed the last sentence of your post. Try http://code.google.com/p/jquery-utils/wiki/StringFormat for a jQuery solution.

Inline functions in C#?

No, there is no such construct in C#, but the .NET JIT compiler could decide to do inline function calls on JIT time. But i actually don't know if it is really doing such optimizations.
(I think it should :-))

Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine

If your computer is a 64bit, all you need to do is uninstall your Java x86 version and install a 64bit version. I had the same problem and this worked. Nothing further needs to be done.

Assigning more than one class for one event

Have you tried this:

 function doSomething() {
     if ($(this).hasClass('clickedTag')){
         // code here
     } else {
         // and here
     }
 }

 $('.tag1, .tag2').click(doSomething);

Angular 2 beta.17: Property 'map' does not exist on type 'Observable<Response>'

I upgraded my gulp-typescript plugin to the latest version (2.13.0) and now it compiles without hitch.

UPDATE 1: I was previously using gulp-typescript version 2.12.0

UPDATE 2: If you are upgrading to the Angular 2.0.0-rc.1, you need to do the following in your appBoot.ts file:

///<reference path="./../typings/browser/ambient/es6-shim/index.d.ts"/>
import { bootstrap } from "@angular/platform-browser-dynamic";
import { ROUTER_PROVIDERS } from '@angular/router-deprecated';
import { HTTP_PROVIDERS } from '@angular/http';
import { AppComponent } from "./path/AppComponent";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
// import 'rxjs/Rx'; this will load all features
import { enableProdMode } from '@angular/core';
import { Title } from '@angular/platform-browser';



//enableProdMode();
bootstrap(AppComponent, [
    ROUTER_PROVIDERS,
    HTTP_PROVIDERS,
    Title
]);

The important thing being the reference to es6-shim/index.d.ts

This assumes you have installed the es6-shim typings as shown here: enter image description here

More on the typings install from Angular here: https://angular.io/docs/ts/latest/guide/typescript-configuration.html#!#typings

Eclipse cannot load SWT libraries

Simply specify the path to the libraries:

echo "-Djava.library.path=/usr/lib/jni/" >> /etc/eclipse.ini

Easiest way to rotate by 90 degrees an image using OpenCV?

Rotation is a composition of a transpose and a flip.

R_{+90} = F_x \circ T

R_{-90} = F_y \circ T

Which in OpenCV can be written like this (Python example below):

img = cv.LoadImage("path_to_image.jpg")
timg = cv.CreateImage((img.height,img.width), img.depth, img.channels) # transposed image

# rotate counter-clockwise
cv.Transpose(img,timg)
cv.Flip(timg,timg,flipMode=0)
cv.SaveImage("rotated_counter_clockwise.jpg", timg)

# rotate clockwise
cv.Transpose(img,timg)
cv.Flip(timg,timg,flipMode=1)
cv.SaveImage("rotated_clockwise.jpg", timg)

Jenkins returned status code 128 with github

When I got a similar status code 128 error from Jenkins:

status code 128:
stdout: 
stderr: fatal: Couldn't find remote ref refs/heads/jenkins

    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:2172)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandWithCredentials(CliGitAPIImpl.java:1864)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.access$500(CliGitAPIImpl.java:78)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$1.execute(CliGitAPIImpl.java:545)
    at jenkins.plugins.git.GitSCMFileSystem$BuilderImpl.build(GitSCMFileSystem.java:358)
    at jenkins.scm.api.SCMFileSystem.of(SCMFileSystem.java:197)
    at jenkins.scm.api.SCMFileSystem.of(SCMFileSystem.java:173)
    at org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition.create(CpsScmFlowDefinition.java:113)
    at org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition.create(CpsScmFlowDefinition.java:67)
    at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:299)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:429)
Finished: FAILURE

It was because I hadn't pushed my new branch "jenkins" that had my Jenkinsfile. So the solution was to just push my changes

How do you add an SDK to Android Studio?

You can change from the "build.gradle" file the line:

compileSdkVersion 18

to the sdk that you want to be used.

"std::endl" vs "\n"

Not a big deal, but endl won't work in boost::lambda.

(cout<<_1<<endl)(3); //error

(cout<<_1<<"\n")(3); //OK , prints 3

Convert R vector to string vector of 1 element

Use the collapse argument to paste:

paste(a,collapse=" ")
[1] "aa bb cc"

org.hibernate.QueryException: could not resolve property: filename

Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity).

Make sure you refer to the property as fileName in the Criteria query, not filename.

Specifically, Hibernate will call the getter method of the filename property when executing that Criteria query, so it will look for a method called getFilename(). But the property is called FileName and the getter getFileName().

So, change the projection like so:

criteria.setProjection(Projections.property("fileName"));

Can I make a phone call from HTML on Android?

I have just written an app which can make a call from a web page - I don't know if this is any use to you, but I include anyway:

in your onCreate you'll need to use a webview and assign a WebViewClient, as below:

browser = (WebView) findViewById(R.id.webkit);
browser.setWebViewClient(new InternalWebViewClient());

then handle the click on a phone number like this:

private class InternalWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
         if (url.indexOf("tel:") > -1) {
            startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
            return true;
        } else {
            return false;
        }
    }
}

Let me know if you need more pointers.

Drag and drop menuitems

jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div (or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.

Append lines to a file using a StreamWriter

Actually only Jon's answer (Sep 5 '11 at 9:37) with BaseStream.Seek worked for my case. Thanks Jon! I needed to append lines to a zip archived txt file.

using (FileStream zipFS = new FileStream(@"c:\Temp\SFImport\test.zip",FileMode.OpenOrCreate))
{
    using (ZipArchive arch = new ZipArchive(zipFS,ZipArchiveMode.Update))
    {
        ZipArchiveEntry entry = arch.GetEntry("testfile.txt");
        if (entry == null)
        {
            entry = arch.CreateEntry("testfile.txt");
        }
        using (StreamWriter sw = new StreamWriter(entry.Open()))
        {
            sw.BaseStream.Seek(0,SeekOrigin.End);
            sw.WriteLine("text content");
        }
    }
}

How to add a line break in an Android TextView?

In my case, I solved this problem by adding the following:

android:inputType="textMultiLine"

How should I call 3 functions in order to execute them one after the other?

your functions should take a callback function, that gets called when it finishes.

function fone(callback){
...do something...
callback.apply(this,[]);

}

function ftwo(callback){
...do something...
callback.apply(this,[]);
}

then usage would be like:

fone(function(){
  ftwo(function(){
   ..ftwo done...
  })
});

What is the difference between compare() and compareTo()?

When you want to sort a List which include the Object Foo, the Foo class has to implement the Comparable interface, because the sort methode of the List is using this methode.

When you want to write a Util class which compares two other classes you can implement the Comparator class.

Re-doing a reverted merge in Git

Instead of using git-revert you could have used this command in the devel branch to throw away (undo) the wrong merge commit (instead of just reverting it).

git checkout devel
git reset --hard COMMIT_BEFORE_WRONG_MERGE

This will also adjust the contents of the working directory accordingly. Be careful:

  • Save your changes in the develop branch (since the wrong merge) because they too will be erased by the git-reset. All commits after the one you specify as the git reset argument will be gone!
  • Also, don't do this if your changes were already pulled from other repositories because the reset will rewrite history.

I recommend to study the git-reset man-page carefully before trying this.

Now, after the reset you can re-apply your changes in devel and then do

git checkout devel
git merge 28s

This will be a real merge from 28s into devel like the initial one (which is now erased from git's history).

HTML5 form required attribute. Set custom validation message?

Adapting Salar's answer to JSX and React, I noticed that React Select doesn't behave just like an <input/> field regarding validation. Apparently, several workarounds are needed to show only the custom message and to keep it from showing at inconvenient times.

I've raised an issue here, if it helps anything. Here is a CodeSandbox with a working example, and the most important code there is reproduced here:

Hello.js

import React, { Component } from "react";
import SelectValid from "./SelectValid";

export default class Hello extends Component {
  render() {
    return (
      <form>
        <SelectValid placeholder="this one is optional" />
        <SelectValid placeholder="this one is required" required />
        <input
          required
          defaultValue="foo"
          onChange={e => e.target.setCustomValidity("")}
          onInvalid={e => e.target.setCustomValidity("foo")}
        />
        <button>button</button>
      </form>
    );
  }
}

SelectValid.js

import React, { Component } from "react";
import Select from "react-select";
import "react-select/dist/react-select.css";

export default class SelectValid extends Component {
  render() {
    this.required = !this.props.required
      ? false
      : this.state && this.state.value ? false : true;
    let inputProps = undefined;
    let onInputChange = undefined;
    if (this.props.required) {
      inputProps = {
        onInvalid: e => e.target.setCustomValidity(this.required ? "foo" : "")
      };
      onInputChange = value => {
        this.selectComponent.input.input.setCustomValidity(
          value
            ? ""
            : this.required
              ? "foo"
              : this.selectComponent.props.value ? "" : "foo"
        );
        return value;
      };
    }
    return (
      <Select
        onChange={value => {
          this.required = !this.props.required ? false : value ? false : true;
          let state = this && this.state ? this.state : { value: null };
          state.value = value;
          this.setState(state);
          if (this.props.onChange) {
            this.props.onChange();
          }
        }}
        value={this && this.state ? this.state.value : null}
        options={[{ label: "yes", value: 1 }, { label: "no", value: 0 }]}
        placeholder={this.props.placeholder}
        required={this.required}
        clearable
        searchable
        inputProps={inputProps}
        ref={input => (this.selectComponent = input)}
        onInputChange={onInputChange}
      />
    );
  }
}

Spring JUnit: How to Mock autowired component in autowired component

Spring Boot 1.4 introduced testing annotation called @MockBean. So now mocking and spying on Spring beans is natively supported by Spring Boot.

WSDL validator?

You can try using one of their tools: http://www.ws-i.org/deliverables/workinggroup.aspx?wg=testingtools

These will check both WSDL validity and Basic Profile 1.1 compliance.

How can I issue a single command from the command line through sql plus?

@find /v "@" < %0 | sqlplus -s scott/tiger@orcl & goto :eof

select sysdate from dual;

Adding a column to a dataframe in R

That is a pretty standard use case for apply():

R> vec <- 1:10
R> DF <- data.frame(start=c(1,3,5,7), end=c(2,6,7,9))
R> DF$newcol <- apply(DF,1,function(row) mean(vec[ row[1] : row[2] ] ))
R> DF
  start end newcol
1     1   2    1.5
2     3   6    4.5
3     5   7    6.0
4     7   9    8.0
R> 

You can also use plyr if you prefer but here is no real need to go beyond functions from base R.

How to convert a date to milliseconds

tl;dr

LocalDateTime.parse(           // Parse into an object representing a date with a time-of-day but without time zone and without offset-from-UTC.
    "2014/10/29 18:10:45"      // Convert input string to comply with standard ISO 8601 format.
    .replace( " " , "T" )      // Replace SPACE in the middle with a `T`.
    .replace( "/" , "-" )      // Replace SLASH in the middle with a `-`.
)
.atZone(                       // Apply a time zone to provide the context needed to determine an actual moment.
    ZoneId.of( "Europe/Oslo" ) // Specify the time zone you are certain was intended for that input.
)                              // Returns a `ZonedDateTime` object.
.toInstant()                   // Adjust into UTC.
.toEpochMilli()                // Get the number of milliseconds since first moment of 1970 in UTC, 1970-01-01T00:00Z.

1414602645000

Time Zone

The accepted answer is correct, except that it ignores the crucial issue of time zone. Is your input string 6:10 PM in Paris or Montréal? Or UTC?

Use a proper time zone name. Usually a continent plus city/region. For example, "Europe/Oslo". Avoid the 3 or 4 letter codes which are neither standardized nor unique.

java.time

The modern approach uses the java.time classes.

Alter your input to conform with the ISO 8601 standard. Replace the SPACE in the middle with a T. And replace the slash characters with hyphens. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.

String input = "2014/10/29 18:10:45".replace( " " , "T" ).replace( "/" , "-" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;

A LocalDateTime, like your input string, lacks any concept of time zone or offset-from-UTC. Without the context of a zone/offset, a LocalDateTime has no real meaning. Is it 6:10 PM in India, Europe, or Canada? Each of those places experience 6:10 PM at different moments, at different points on the timeline. So you must specify which you have in mind if you want to determine a specific point on the timeline.

ZoneId z = ZoneId.of( "Europe/Oslo" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;  

Now we have a specific moment, in that ZonedDateTime. Convert to UTC by extracting a Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = zdt.toInstant() ;

Now we can get your desired count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z.

long millisSinceEpoch = instant.toEpochMilli() ; 

Be aware of possible data loss. The Instant object is capable of carrying microseconds or nanoseconds, finer than milliseconds. That finer fractional part of a second will be ignored when getting a count of milliseconds.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


Joda-Time

Update: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. I will leave this section intact for history.

Below is the same kind of code but using the Joda-Time 2.5 library and handling time zone.

The java.util.Date, .Calendar, and .SimpleDateFormat classes are notoriously troublesome, confusing, and flawed. Avoid them. Use either Joda-Time or the java.time package (inspired by Joda-Time) built into Java 8.

ISO 8601

Your string is almost in ISO 8601 format. The slashes need to be hyphens and the SPACE in middle should be replaced with a T. If we tweak that, then the resulting string can be fed directly into constructor without bothering to specify a formatter. Joda-Time uses ISO 8701 formats as it's defaults for parsing and generating strings.

Example Code

String inputRaw = "2014/10/29 18:10:45";
String input = inputRaw.replace( "/", "-" ).replace( " ", "T" );
DateTimeZone zone = DateTimeZone.forID( "Europe/Oslo" ); // Or DateTimeZone.UTC
DateTime dateTime = new DateTime( input, zone );
long millisecondsSinceUnixEpoch = dateTime.getMillis();

Error 1053 the service did not respond to the start or control request in a timely fashion

One of possible solutions for this problem [It fixed issue at my end and my application is JAVA based application ]:

1) check your application is pointing to correct java version(check the java version and path in your application).

OR

2)check the configured java version i.e check whether it is 32-bit version or 64-bit version(based on your application). if you are using 32-bit then you should use 32-bit version JSL, else JSL will cause this issue.

Setting session variable using javascript

It is very important to understand both sessionStorage and localStorage as they both have different uses:

From MDN:

All of your web storage data is contained within two object-like structures inside the browser: sessionStorage and localStorage. The first one persists data for as long as the browser is open (the data is lost when the browser is closed) and the second one persists data even after the browser is closed and then opened again.

sessionStorage - Saves data until the browser is closed, the data is deleted when the tab/browser is closed.

localStorage - Saves data "forever" even after the browser is closed BUT you shouldn't count on the data you store to be there later, the data might get deleted by the browser at any time because of pretty much anything, or deleted by the user, best practice would be to validate that the data is there first, and continue the rest if it is there. (or set it up again if its not there)

To understand more, read here: localStorage | sessionStorage

When to use the different log levels

It's an old topic, but still relevant. This week, I wrote a small article about it, for my colleagues. For that purpose, I also created this cheat sheet, because I couldn't find any online.

cheat sheet: which log level should I use

What is a classpath and how do I set it?

Think of it as Java's answer to the PATH environment variable - OSes search for EXEs on the PATH, Java searches for classes and packages on the classpath.

How to increase font size in the Xcode editor?

Update! - Behold Xcode 9 to the rescue! Now you can use cmd + to increase the fonts with Xcode 9. It took 5 Major releases for you to get it, Apple! But better late than never.

figured it out - however it was not very intuitive.

First some Pain Points

  1. When You try to change the font size directly using edit -> format -> font, nothing happens! - Not a good UX ... moreover why play dumb when you can tell user that they are using default or "System-owned" theme and they cannot change it? - Bad Design and more bad UX ... Why keep this option (Cmd t) alive, which by the way is most standard way to increase font size across most well behaved mac apps, if you do not want user to change the font this way?

  2. In Xcode preferences, when you try to change the font size by clicking on "fonts and colors", thats when XCode gives a pop-up saying what needs to be done. Also making a duplicate and then changing the fonts and colors is a lot of work rather than giving a button that says "Restore to Defaults" if Apple is so worried about the user messing up the default settings!

The solution is that - you need to duplicate the theme and then modify the copy you just made and apply that copy - phew!

How can I simulate mobile devices and debug in Firefox Browser?

You could use the Firefox add-on User Agent Overrider. With this add-on you can use whatever user agent you want, for examlpe:

Firefox 28/Android: Mozilla/5.0 (Android; Mobile; rv:28.0) Gecko/24.0 Firefox/28.0

If your website detects mobile devices through the user agent then you can test your layout this way.


Update Nov '17:

Due to the release of Firefox 57 and the introduction of web extension this add-on sadly is no longer available. Alternatively you can edit the Firefox preference general.useragent.override in your configuration:

  1. In the address bar type about:config
  2. Search for general.useragent.override
  3. If the preference doesn't exist, right-click on the about:config page, click New, then select String
  4. Name the new preference general.useragent.override
  5. Set the value to the user agent you want

How do I implement __getattribute__ without an infinite recursion error?

Actually, I believe you want to use the __getattr__ special method instead.

Quote from the Python docs:

__getattr__( self, name)

Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.
Note that if the attribute is found through the normal mechanism, __getattr__() is not called. (This is an intentional asymmetry between __getattr__() and __setattr__().) This is done both for efficiency reasons and because otherwise __setattr__() would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the __getattribute__() method below for a way to actually get total control in new-style classes.

Note: for this to work, the instance should not have a test attribute, so the line self.test=20 should be removed.

Cropping an UIImage

I wasn't satisfied with other solutions because they either draw several time (using more power than necessary) or have problems with orientation. Here is what I used for a scaled square croppedImage from a UIImage * image.

CGFloat minimumSide = fminf(image.size.width, image.size.height);
CGFloat finalSquareSize = 600.;

//create new drawing context for right size
CGRect rect = CGRectMake(0, 0, finalSquareSize, finalSquareSize);
CGFloat scalingRatio = 640.0/minimumSide;
UIGraphicsBeginImageContext(rect.size);

//draw
[image drawInRect:CGRectMake((minimumSide - photo.size.width)*scalingRatio/2., (minimumSide - photo.size.height)*scalingRatio/2., photo.size.width*scalingRatio, photo.size.height*scalingRatio)];

UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

Download file from an ASP.NET Web API method using AngularJS

In your component i.e angular js code:

function getthefile (){
window.location.href='http://localhost:1036/CourseRegConfirm/getfile';
};

LINQ where clause with lambda expression having OR clauses and null values returning incomplete results

You are checking Parent properties for null in your delegate. The same should work with lambda expressions too.

List<AnalysisObject> analysisObjects = analysisObjectRepository
        .FindAll()
        .Where(x => 
            (x.ID == packageId) || 
            (x.Parent != null &&
                (x.Parent.ID == packageId || 
                (x.Parent.Parent != null && x.Parent.Parent.ID == packageId)))
        .ToList();

Return rows in random order

To be efficient, and random, it might be best to have two different queries.

Something like...

SELECT table_id FROM table

Then, in your chosen language, pick a random id, then pull that row's data.

SELECT * FROM table WHERE table_id = $rand_id

But that's not really a good idea if you're expecting to have lots of rows in the table. It would be better if you put some kind of limit on what you randomly select from. For publications, maybe randomly pick from only items posted within the last year.

jQuery: How to capture the TAB keypress within a Textbox

Edit: Since your element is dynamically inserted, you have to use delegated on() as in your example, but you should bind it to the keydown event, because as @Marc comments, in IE the keypress event doesn't capture non-character keys:

$("#parentOfTextbox").on('keydown', '#textbox', function(e) { 
  var keyCode = e.keyCode || e.which; 

  if (keyCode == 9) { 
    e.preventDefault(); 
    // call custom function here
  } 
});

Check an example here.

Local file access with JavaScript

Just an update of the HTML5 features is in http://www.html5rocks.com/en/tutorials/file/dndfiles/. This excellent article will explain in detail the local file access in JavaScript. Summary from the mentioned article:

The specification provides several interfaces for accessing files from a 'local' filesystem:

  1. File - an individual file; provides readonly information such as name, file size, MIME type, and a reference to the file handle.
  2. FileList - an array-like sequence of File objects. (Think <input type="file" multiple> or dragging a directory of files from the desktop).
  3. Blob - Allows for slicing a file into byte ranges.

See Paul D. Waite's comment below.

Access index of last element in data frame

The former answer is now superseded by .iloc:

>>> df = pd.DataFrame({"date": range(10, 64, 8)})
>>> df.index += 17
>>> df
    date
17    10
18    18
19    26
20    34
21    42
22    50
23    58
>>> df["date"].iloc[0]
10
>>> df["date"].iloc[-1]
58

The shortest way I can think of uses .iget():

>>> df = pd.DataFrame({"date": range(10, 64, 8)})
>>> df.index += 17
>>> df
    date
17    10
18    18
19    26
20    34
21    42
22    50
23    58
>>> df['date'].iget(0)
10
>>> df['date'].iget(-1)
58

Alternatively:

>>> df['date'][df.index[0]]
10
>>> df['date'][df.index[-1]]
58

There's also .first_valid_index() and .last_valid_index(), but depending on whether or not you want to rule out NaNs they might not be what you want.

Remember that df.ix[0] doesn't give you the first, but the one indexed by 0. For example, in the above case, df.ix[0] would produce

>>> df.ix[0]
Traceback (most recent call last):
  File "<ipython-input-489-494245247e87>", line 1, in <module>
    df.ix[0]
[...]
KeyError: 0

Convert JS object to JSON string

The existing JSON replacements where too much for me, so I wrote my own function. This seems to work, but I might have missed several edge cases (that don't occur in my project). And will probably not work for any pre-existing objects, only for self-made data.

function simpleJSONstringify(obj) {
    var prop, str, val,
        isArray = obj instanceof Array;

    if (typeof obj !== "object") return false;

    str = isArray ? "[" : "{";

    function quote(str) {
        if (typeof str !== "string") str = str.toString();
        return str.match(/^\".*\"$/) ? str : '"' + str.replace(/"/g, '\\"') + '"'
    }

    for (prop in obj) {
        if (!isArray) {
            // quote property
            str += quote(prop) + ": ";
        }

        // quote value
        val = obj[prop];
        str += typeof val === "object" ? simpleJSONstringify(val) : quote(val);
        str += ", ";
    }

    // Remove last colon, close bracket
    str = str.substr(0, str.length - 2)  + ( isArray ? "]" : "}" );

    return str;
}

Sleep function Visual Basic

Since you are asking about .NET, you should change the parameter from Long to Integer. .NET's Integer is 32-bit. (Classic VB's integer was only 16-bit.)

Declare Sub Sleep Lib "kernel32.dll" (ByVal Milliseconds As Integer)

Really though, the managed method isn't difficult...

System.Threading.Thread.CurrentThread.Sleep(5000)

Be careful when you do this. In a forms application, you block the message pump and what not, making your program to appear to have hanged. Rarely is sleep a good idea.

Controlling number of decimal digits in print output in R

If you are producing the entire output yourself, you can use sprintf(), e.g.

> sprintf("%.10f",0.25)
[1] "0.2500000000"

specifies that you want to format a floating point number with ten decimal points (in %.10f the f is for float and the .10 specifies ten decimal points).

I don't know of any way of forcing R's higher level functions to print an exact number of digits.

Displaying 100 digits does not make sense if you are printing R's usual numbers, since the best accuracy you can get using 64-bit doubles is around 16 decimal digits (look at .Machine$double.eps on your system). The remaining digits will just be junk.

How to copy selected lines to clipboard in vim

First check if your vim installation has clipboard support.

vim --version

If clipboard support is installed you will see:

+clipboard
+X11
+xterm_clipboard

If clipboard support is not installed you will see:

-clipboard
-X11
-xterm_clipboard

To install clipboard support:

apt-get install vim-gnome

Once you have verified that clipboard support is installed do the following:

  1. Position your cursor to the first line you want to copy.
  2. Press Shiftv to enter visual mode.
  3. Press ? to select multiple lines
  4. Press "+y to copy the selected text to system clipboard.
  5. Now you can copy the selected text to browser, text editor etc.
  6. Press "+p if you want to copy system clipboard text to vim.

Above steps might get tedious if you have to repeatedly copy from vim to system clipboard and vice versa. You can create vim shortcuts so that when you press Ctrlc selected text will be copied to system clipboard. And when you press Ctrlp system clipboard text is copied to vim. To create shortcuts :

  1. Open .vimrc file and add following text at the end of file:

     nnoremap <C-c> "+y
     vnoremap <C-c> "+y
     nnoremap <C-p> "+p
     vnoremap <C-p> "+p
    
  2. Save and reload your .vimrc to apply the new changes.

  3. Position your cursor to the first line you want to copy.

  4. Press Shiftv to enter visual mode.

  5. Press ? to select multiple lines

  6. Press Ctrlc to copy the selected text to system clipboard.

  7. Now you can copy the selected text to browser, text editor etc.

  8. Press Ctrlp if you want to copy system clipboard text to vim.

Note: This is for ubuntu systems.

Converting NSString to NSDictionary / JSON

Swift 3:

if let jsonString = styleDictionary as? String {
    let objectData = jsonString.data(using: String.Encoding.utf8)
    do {
        let json = try JSONSerialization.jsonObject(with: objectData!, options: JSONSerialization.ReadingOptions.mutableContainers) 
        print(String(describing: json)) 

    } catch {
        // Handle error
        print(error)
    }
}

Javascript call() & apply() vs bind()?

JavaScript Call()

const person = {
    name: "Lokamn",
    dob: 12,
    print: function (value,value2) {
        console.log(this.dob+value+value2)
    }
}
const anotherPerson= {
     name: "Pappu",
     dob: 12,
}
 person.print.call(anotherPerson,1,2)

JavaScript apply()

    name: "Lokamn",
    dob: 12,
    print: function (value,value2) {
        console.log(this.dob+value+value2)
    }
}
const anotherPerson= {
     name: "Pappu",
     dob: 12,
}
 person.print.apply(anotherPerson,[1,2])

**call and apply function are difference call take separate argument but apply take array like:[1,2,3] **

JavaScript bind()

    name: "Lokamn",
    dob: 12,
    anotherPerson: {
        name: "Pappu",
        dob: 12,
        print2: function () {
            console.log(this)
        }
    }
}

var bindFunction = person.anotherPerson.print2.bind(person)
 bindFunction()

WordPress path url in js script file

For users working with the Genesis framework.

Add the following to your child theme functions.php

add_action( 'genesis_before', 'script_urls' );

function script_urls() {
?>
    <script type="text/javascript">
     var stylesheetDir = '<?= get_bloginfo("stylesheet_directory"); ?>';
    </script>
<?php
}

And use that variable to set the relative url in your script. For example:

Reset.style.background = " url('"+stylesheetDir+"/images/searchfield_clear.png') ";

Waiting for HOME ('android.process.acore') to be launched

I noticed this is an old post. However I just ran into the same problem and found a solution. A) Make sure you have the CPU/ABI is atom B)Ram is 2048 C)VM Heap is 256 D)Internal Storage is 200 E)Make sure to check the Use Host GPU F)Device is Nexus 5 (My personal choice) G)Android 4.4.2 API Level 19

Python Pandas : pivot table with aggfunc = count unique distinct

For best performance I recommend doing DataFrame.drop_duplicates followed up aggfunc='count'.

Others are correct that aggfunc=pd.Series.nunique will work. This can be slow, however, if the number of index groups you have is large (>1000).

So instead of (to quote @Javier)

df2.pivot_table('X', 'Y', 'Z', aggfunc=pd.Series.nunique)

I suggest

df2.drop_duplicates(['X', 'Y', 'Z']).pivot_table('X', 'Y', 'Z', aggfunc='count')

This works because it guarantees that every subgroup (each combination of ('Y', 'Z')) will have unique (non-duplicate) values of 'X'.

Understanding REST: Verbs, error codes, and authentication

Simply put, you are doing this completely backward.

You should not be approaching this from what URLs you should be using. The URLs will effectively come "for free" once you've decided upon what resources are necessary for your system AND how you will represent those resources, and the interactions between the resources and application state.

To quote Roy Fielding

A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types. Any effort spent describing what methods to use on what URIs of interest should be entirely defined within the scope of the processing rules for a media type (and, in most cases, already defined by existing media types). [Failure here implies that out-of-band information is driving interaction instead of hypertext.]

Folks always start with the URIs and think this is the solution, and then they tend to miss a key concept in REST architecture, notably, as quoted above, "Failure here implies that out-of-band information is driving interaction instead of hypertext."

To be honest, many see a bunch of URIs and some GETs and PUTs and POSTs and think REST is easy. REST is not easy. RPC over HTTP is easy, moving blobs of data back and forth proxied through HTTP payloads is easy. REST, however, goes beyond that. REST is protocol agnostic. HTTP is just very popular and apt for REST systems.

REST lives in the media types, their definitions, and how the application drives the actions available to those resources via hypertext (links, effectively).

There are different view about media types in REST systems. Some favor application specific payloads, while others like uplifting existing media types in to roles that are appropriate for the application. For example, on the one hand you have specific XML schemas designed suited to your application versus using something like XHTML as your representation, perhaps through microformats and other mechanisms.

Both approaches have their place, I think, the XHTML working very well in scenarios that overlap both the human driven and machine driven web, whereas the former, more specific data types I feel better facilitate machine to machine interactions. I find the uplifting of commodity formats can make content negotiation potentially difficult. "application/xml+yourresource" is much more specific as a media type than "application/xhtml+xml", as the latter can apply to many payloads which may or may not be something a machine client is actually interested in, nor can it determine without introspection.

However, XHTML works very well (obviously) in the human web where web browsers and rendering is very important.

You application will guide you in those kinds of decisions.

Part of the process of designing a REST system is discovering the first class resources in your system, along with the derivative, support resources necessary to support the operations on the primary resources. Once the resources are discovered, then the representation of those resources, as well as the state diagrams showing resource flow via hypertext within the representations because the next challenge.

Recall that each representation of a resource, in a hypertext system, combines both the actual resource representation along with the state transitions available to the resource. Consider each resource a node in a graph, with the links being the lines leaving that node to other states. These links inform clients not only what can be done, but what is required for them to be done (as a good link combines the URI and the media type required).

For example, you may have:

<link href="http://example.com/users" rel="users" type="application/xml+usercollection"/>
<link href="http://example.com/users?search" rel="search" type="application/xml+usersearchcriteria"/>

Your documentation will talk about the rel field named "users", and the media type of "application/xml+youruser".

These links may seem redundant, they're all talking to the same URI, pretty much. But they're not.

This is because for the "users" relation, that link is talking about the collection of users, and you can use the uniform interface to work with the collection (GET to retrieve all of them, DELETE to delete all of them, etc.)

If you POST to this URL, you will need to pass a "application/xml+usercollection" document, which will probably only contain a single user instance within the document so you can add the user, or not, perhaps, to add several at once. Perhaps your documentation will suggest that you can simply pass a single user type, instead of the collection.

You can see what the application requires in order to perform a search, as defined by the "search" link and it's mediatype. The documentation for the search media type will tell you how this behaves, and what to expect as results.

The takeaway here, though, is the URIs themselves are basically unimportant. The application is in control of the URIs, not the clients. Beyond a few 'entry points', your clients should rely on the URIs provided by the application for its work.

The client needs to know how to manipulate and interpret the media types, but doesn't much need to care where it goes.

These two links are semantically identical in a clients eyes:

<link href="http://example.com/users?search" rel="search" type="application/xml+usersearchcriteria"/>
<link href="http://example.com/AW163FH87SGV" rel="search" type="application/xml+usersearchcriteria"/>

So, focus on your resources. Focus on their state transitions in the application and how that's best achieved.

Create a temporary table in MySQL with an index from a select

I wrestled quite a while with the proper syntax for CREATE TEMPORARY TABLE SELECT. Having figured out a few things, I wanted to share the answers with the rest of the community.

Basic information about the statement is available at the following MySQL links:

CREATE TABLE SELECT and CREATE TABLE.

At times it can be daunting to interpret the spec. Since most people learn best from examples, I will share how I have created a working statement, and how you can modify it to work for you.

  1. Add multiple indexes

    This statement shows how to add multiple indexes (note that index names - in lower case - are optional):

    CREATE TEMPORARY TABLE core.my_tmp_table 
    (INDEX my_index_name (tag, time), UNIQUE my_unique_index_name (order_number))
    SELECT * FROM core.my_big_table
    WHERE my_val = 1
    
  2. Add a new primary key:

    CREATE TEMPORARY TABLE core.my_tmp_table 
    (PRIMARY KEY my_pkey (order_number),
    INDEX cmpd_key (user_id, time))
    SELECT * FROM core.my_big_table
    
  3. Create additional columns

    You can create a new table with more columns than are specified in the SELECT statement. Specify the additional column in the table definition. Columns specified in the table definition and not found in select will be first columns in the new table, followed by the columns inserted by the SELECT statement.

    CREATE TEMPORARY TABLE core.my_tmp_table 
    (my_new_id BIGINT NOT NULL AUTO_INCREMENT,  
    PRIMARY KEY my_pkey (my_new_id), INDEX my_unique_index_name (invoice_number))
    SELECT * FROM core.my_big_table
    
  4. Redefining data types for the columns from SELECT

    You can redefine the data type of a column being SELECTed. In the example below, column tag is a MEDIUMINT in core.my_big_table and I am redefining it to a BIGINT in core.my_tmp_table.

    CREATE TEMPORARY TABLE core.my_tmp_table 
    (tag BIGINT,
    my_time DATETIME,  
    INDEX my_unique_index_name (tag) )
    SELECT * FROM core.my_big_table
    
  5. Advanced field definitions during create

    All the usual column definitions are available as when you create a normal table. Example:

    CREATE TEMPORARY TABLE core.my_tmp_table 
    (id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    value BIGINT UNSIGNED NOT NULL DEFAULT 0 UNIQUE,
    location VARCHAR(20) DEFAULT "NEEDS TO BE SET",
    country CHAR(2) DEFAULT "XX" COMMENT "Two-letter country code",  
    INDEX my_index_name (location))
    ENGINE=MyISAM 
    SELECT * FROM core.my_big_table
    

How to make a smaller RatingBar?

Just use:

android:scaleX="0.5"
android:scaleY="0.5"

Change the scale factor according to your need.

In order to scale without creating a padding on the left also add

android:transformPivotX="0dp"

subtract time from date - moment js

Michael Richardson's solution is great. If you would like to subtract dates (because Google will point you here if you search for it), you could also say:

var date1 = moment( "2014-06-07 00:03:00" );
var date2 = moment( "2014-06-07 09:22:00" );

differenceInMs = date2.diff(date1); // diff yields milliseconds
duration = moment.duration(differenceInMs); // moment.duration accepts ms
differenceInMinutes = duration.asMinutes(); // if you would like to have the output 559

json_decode to array

This will also change it into an array:

<?php
    print_r((array) json_decode($object));
?>

How to convert java.util.Date to java.sql.Date?

try with this

public static String toMysqlDateStr(Date date) {
    String dateForMySql = "";
    if (date == null) {
        dateForMySql = null;
    } else {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateForMySql = sdf.format(date);
    }

    return dateForMySql;
}

How to remove an unpushed outgoing commit in Visual Studio?

I could not find a single good answer that helped me get rid of this issue.

Let's say the name of branch, you accidentally committed changes to, is master. Following four simple steps proved like a world to me:

  1. Go to Branches
  2. Choose or create any branch other than master
  3. Delete local/workspace version of master
  4. Switch to master from remotes/origin

jQuery: select an element's class and id at the same time?

How about this code?

$("a.save#country")

ByRef argument type mismatch in Excel VBA

While looping through your string one character at a time is a viable method, there's no need. VBA has built-in functions for this kind of thing:

Public Function ProcessString(input_string As String) As String
    ProcessString=Replace(input_string,"*","")
End Function

Unable to find valid certification path to requested target - error even after cert imported

Here is the solution , follow the below link Step by Step :

http://www.mkyong.com/webservices/jax-ws/suncertpathbuilderexception-unable-to-find-valid-certification-path-to-requested-target/

JAVA FILE : which is missing from the blog

/*
 * Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */



import java.io.*;
import java.net.URL;

import java.security.*;
import java.security.cert.*;

import javax.net.ssl.*;

public class InstallCert {

    public static void main(String[] args) throws Exception {
    String host;
    int port;
    char[] passphrase;
    if ((args.length == 1) || (args.length == 2)) {
        String[] c = args[0].split(":");
        host = c[0];
        port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
        String p = (args.length == 1) ? "changeit" : args[1];
        passphrase = p.toCharArray();
    } else {
        System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");
        return;
    }

    File file = new File("jssecacerts");
    if (file.isFile() == false) {
        char SEP = File.separatorChar;
        File dir = new File(System.getProperty("java.home") + SEP
            + "lib" + SEP + "security");
        file = new File(dir, "jssecacerts");
        if (file.isFile() == false) {
        file = new File(dir, "cacerts");
        }
    }
    System.out.println("Loading KeyStore " + file + "...");
    InputStream in = new FileInputStream(file);
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(in, passphrase);
    in.close();

    SSLContext context = SSLContext.getInstance("TLS");
    TrustManagerFactory tmf =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];
    SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
    context.init(null, new TrustManager[] {tm}, null);
    SSLSocketFactory factory = context.getSocketFactory();

    System.out.println("Opening connection to " + host + ":" + port + "...");
    SSLSocket socket = (SSLSocket)factory.createSocket(host, port);
    socket.setSoTimeout(10000);
    try {
        System.out.println("Starting SSL handshake...");
        socket.startHandshake();
        socket.close();
        System.out.println();
        System.out.println("No errors, certificate is already trusted");
    } catch (SSLException e) {
        System.out.println();
        e.printStackTrace(System.out);
    }

    X509Certificate[] chain = tm.chain;
    if (chain == null) {
        System.out.println("Could not obtain server certificate chain");
        return;
    }

    BufferedReader reader =
        new BufferedReader(new InputStreamReader(System.in));

    System.out.println();
    System.out.println("Server sent " + chain.length + " certificate(s):");
    System.out.println();
    MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    for (int i = 0; i < chain.length; i++) {
        X509Certificate cert = chain[i];
        System.out.println
            (" " + (i + 1) + " Subject " + cert.getSubjectDN());
        System.out.println("   Issuer  " + cert.getIssuerDN());
        sha1.update(cert.getEncoded());
        System.out.println("   sha1    " + toHexString(sha1.digest()));
        md5.update(cert.getEncoded());
        System.out.println("   md5     " + toHexString(md5.digest()));
        System.out.println();
    }

    System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
    String line = reader.readLine().trim();
    int k;
    try {
        k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
    } catch (NumberFormatException e) {
        System.out.println("KeyStore not changed");
        return;
    }

    X509Certificate cert = chain[k];
    String alias = host + "-" + (k + 1);
    ks.setCertificateEntry(alias, cert);

    OutputStream out = new FileOutputStream("jssecacerts");
    ks.store(out, passphrase);
    out.close();

    System.out.println();
    System.out.println(cert);
    System.out.println();
    System.out.println
        ("Added certificate to keystore 'jssecacerts' using alias '"
        + alias + "'");
    }

    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();

    private static String toHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 3);
        for (int b : bytes) {
            b &= 0xff;
            sb.append(HEXDIGITS[b >> 4]);
            sb.append(HEXDIGITS[b & 15]);
            sb.append(' ');
        }
        return sb.toString();
    }

    private static class SavingTrustManager implements X509TrustManager {

    private final X509TrustManager tm;
    private X509Certificate[] chain;

    SavingTrustManager(X509TrustManager tm) {
        this.tm = tm;
    }

    public X509Certificate[] getAcceptedIssuers() {
        throw new UnsupportedOperationException();
    }

    public void checkClientTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
        throw new UnsupportedOperationException();
    }

    public void checkServerTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
        this.chain = chain;
        tm.checkServerTrusted(chain, authType);
    }
    }

}

Use space as a delimiter with cut command

scut, a cut-like utility (smarter but slower I made) that can use any perl regex as a breaking token. Breaking on whitespace is the default, but you can also break on multi-char regexes, alternative regexes, etc.

scut -f='6 2 8 7' < input.file  > output.file

so the above command would break columns on whitespace and extract the (0-based) cols 6 2 8 7 in that order.

Jinja2 shorthand conditional

Yes, it's possible to use inline if-expressions:

{{ 'Update' if files else 'Continue' }}

Update a column in MySQL

You have to use UPDATE instead of INSERT:

For Example:

UPDATE table1 SET col_a='k1', col_b='foo' WHERE key_col='1';
UPDATE table1 SET col_a='k2', col_b='bar' WHERE key_col='2';

AngularJS does not send hidden field value

Here I would like to share my working code :

_x000D_
_x000D_
<input type="text" name="someData" ng-model="data" ng-init="data=2" style="display: none;"/>_x000D_
OR_x000D_
<input type="hidden" name="someData" ng-model="data" ng-init="data=2"/>_x000D_
OR_x000D_
<input type="hidden" name="someData" ng-init="data=2"/>
_x000D_
_x000D_
_x000D_

How to bind a List to a ComboBox?

Try something like this:

yourControl.DataSource = countryInstance.Cities;

And if you are using WebForms you will need to add this line:

yourControl.DataBind();

Extract a substring from a string in Ruby using a regular expression

Here's a slightly more flexible approach using the match method. With this, you can extract more than one string:

s = "<ants> <pants>"
matchdata = s.match(/<([^>]*)> <([^>]*)>/)

# Use 'captures' to get an array of the captures
matchdata.captures   # ["ants","pants"]

# Or use raw indices
matchdata[0]   # whole regex match: "<ants> <pants>"
matchdata[1]   # first capture: "ants"
matchdata[2]   # second capture: "pants"

How to set the UITableView Section title programmatically (iPhone/iPad)?

Note that -(NSString *)tableView: titleForHeaderInSection: is not called by UITableView if - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section is implemented in delegate of UITableView;

When to choose mouseover() and hover() function?

.hover() function accepts two function arguments, one for mouseenter event and one for mouseleave event.

How to add a class to body tag?

$('body').toggleClass("className");

perfectly works

Fatal error: Class 'ZipArchive' not found in

I faced this issue on GCP while deploying wordpress in the App Engine Standard environment. This solved it :

sudo apt-get install php7.2-zip

Why is the time complexity of both DFS and BFS O( V + E )

I think every edge has been considered twice and every node has been visited once, so the total time complexity should be O(2E+V).

Doctrine query builder using inner join with conditions

You can explicitly have a join like this:

$qb->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId');

But you need to use the namespace of the class Join from doctrine:

use Doctrine\ORM\Query\Expr\Join;

Or if you prefere like that:

$qb->innerJoin('c.phones', 'p', Doctrine\ORM\Query\Expr\Join::ON, 'c.id = p.customerId');

Otherwise, Join class won't be detected and your script will crash...

Here the constructor of the innerJoin method:

public function innerJoin($join, $alias, $conditionType = null, $condition = null);

You can find other possibilities (not just join "ON", but also "WITH", etc...) here: http://docs.doctrine-project.org/en/2.0.x/reference/query-builder.html#the-expr-class

EDIT

Think it should be:

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId')
    ->where('c.username = :username')
    ->andWhere('p.phone = :phone');

    $qb->setParameters(array(
        'username' => $username,
        'phone' => $phone->getPhone(),
    ));

Otherwise I think you are performing a mix of ON and WITH, perhaps the problem.

what is numeric(18, 0) in sql server 2008 r2

The first value is the precision and the second is the scale, so 18,0 is essentially 18 digits with 0 digits after the decimal place. If you had 18,2 for example, you would have 18 digits, two of which would come after the decimal...

example of 18,2: 1234567890123456.12

There is no functional difference between numeric and decimal, other that the name and I think I recall that numeric came first, as in an earlier version.

And to answer, "can I add (-10) in that column?" - Yes, you can.

How to implement the Softmax function in Python

To offer an alternative solution, consider the cases where your arguments are extremely large in magnitude such that exp(x) would underflow (in the negative case) or overflow (in the positive case). Here you want to remain in log space as long as possible, exponentiating only at the end where you can trust the result will be well-behaved.

import scipy.special as sc
import numpy as np

def softmax(x: np.ndarray) -> np.ndarray:
    return np.exp(x - sc.logsumexp(x))

Right way to convert data.frame to a numeric matrix, when df also contains strings?

Here is an alternative way if the data frame just contains numbers.

_x000D_
_x000D_
apply(as.matrix.noquote(SFI),2,as.numeric)
_x000D_
_x000D_
_x000D_

but the most reliable way of converting a data frame to a matrix is using data.matrix() function.

Filter dict to contain only certain keys?

Short form:

[s.pop(k) for k in list(s.keys()) if k not in keep]

As most of the answers suggest in order to maintain the conciseness we have to create a duplicate object be it a list or dict. This one creates a throw-away list but deletes the keys in original dict.

Converting a string to JSON object

You can use the JSON.parse() for that.

See docs at MDN

Example:

var myObj = JSON.parse('{"p": 5}');
console.log(myObj);

Find size and free space of the filesystem containing a given file

For the second part of your question, "get usage statistics of the given partition", psutil makes this easy with the disk_usage(path) function. Given a path, disk_usage() returns a named tuple including total, used, and free space expressed in bytes, plus the percentage usage.

Simple example from documentation:

>>> import psutil
>>> psutil.disk_usage('/')
sdiskusage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)

Psutil works with Python versions from 2.6 to 3.6 and on Linux, Windows, and OSX among other platforms.

Google Maps API v2: How to make markers clickable?

Below Kotlin code can help to you

Create Marker

        for (i in arrayList.indices) {
            val marker = googleMap!!.addMarker(
                MarkerOptions().position(
                    LatLng(
                        arrayList[i].location_latitude!!.toDoubleOrNull()!!,
                        arrayList[i].location_latitude!!.toDoubleOrNull()!!
                    )
                ).title(arrayList[i].business_name)
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_marker))
            )
            marker.tag = i
        }

Marker Click

        googleMap!!.setOnMarkerClickListener { marker ->
            Log.d(TAG, "Clicked on  ${marker.tag}")
            true
        }

PDF Parsing Using Python - extracting formatted and plain texts

You can also take a look at PDFMiner (or for older versions of Python see PDFMiner and PDFMiner).

A particular feature of interest in PDFMiner is that you can control how it regroups text parts when extracting them. You do this by specifying the space between lines, words, characters, etc. So, maybe by tweaking this you can achieve what you want (that depends of the variability of your documents). PDFMiner can also give you the location of the text in the page, it can extract data by Object ID and other stuff. So dig in PDFMiner and be creative!

But your problem is really not an easy one to solve because, in a PDF, the text is not continuous, but made from a lot of small groups of characters positioned absolutely in the page. The focus of PDF is to keep the layout intact. It's not content oriented but presentation oriented.

How to obtain the location of cacerts of the default java installation?

In MacOS Mojave, the location is:

/Library/Java/JavaVirtualMachines/jdk1.8.0_192.jdk/Contents/Home/jre/lib/security/cacerts 

If using sdkman to manage java versions, the cacerts is in

~/.sdkman/candidates/java/current/jre/lib/security

How to Check byte array empty or not?

.Net V 4.6 OR C # 6.0

Try This

 if (Attachment?.Length > 0)

Add image in title bar

That method will not work. The <title> only supports plain text. You will need to create an .ico image with the filename of favicon.ico and save it into the root folder of your site (where your default page is).

Alternatively, you can save the icon where ever you wish and call it whatever you want, but simply insert the following code into the <head> section of your HTML and reference your icon:

<link rel="shortcut icon" href="your_image_path_and_name.ico" />

You can use Photoshop (with a plug in) or GIMP (free) to create an .ico file, or you can just use IcoFX, which is my personal favourite as it is really easy to use and does a great job (you can get an older version of the software for free from download.com).

Update 1: You can also use a number of online tools to create favicons such as ConvertIcon, which I've used successfully. There are other free online tools available now too, which do the same (accessible by a simple Google search), but also generate other icons such as the Windows 8/10 Start Menu icons and iOS App Icons.

Update 2: You can also use .png images as icons providing IE11 is the only version of IE you need to support. You just need to reference them using the HTML code above. Note that IE10 and older still require .ico files.

Update 3: You can now use Emoji characters in the title field. On Windows 10, it should generally fall back and use the Segoe UI Emoji font and display nicely, however you'll need to test and see how other systems support and display your chosen emoji, as not all devices may have the same Emoji available.

jQuery scrollTop not working in Chrome but working in Firefox

 $("html, body").animate({ scrollTop: 0 }, "slow");

This CSS conflict with scroll to top so take care of this

 html, body {
         overflow-x: hidden;        
    }

How do you do block comments in YAML?

In .gitlab-ci.yml file following works::

To comment out a block (multiline): Select the whole block section > Ctrl K C

To uncomment already commented out block (multiline): Select the whole block section > Ctrl K U

When to use in vs ref vs out

Still feel the need for a good summary, this is what I came up with.

Summary,

When we are inside the function, this is how we specify the variable data access control,

in = R

out = must W before R

ref = R+W


Explanation,

in

Function may only READ that variable.

out

Variable must not be initialised first because,
function MUST WRITE to it before READ.

ref

Function may READ/WRITE to that variable.


Why is it named as such?

Focusing on where data gets modified,

in

Data must only be set before entering (in) function.

out

Data must only be set before leaving (out) function.

ref

Data must be set before entering (in) function.
Data may be set before leaving (out) function.

Unable to access JSON property with "-" dash

In addition to this answer, note that in Node.js if you access JSON with the array syntax [] all nested JSON keys should follow that syntax

This is the wrong way

json.first.second.third['comment']

and will will give you the 'undefined' error.

This is the correct way

json['first']['second']['third']['comment'] 

Eclipse: Java was started but returned error code=13

My solution: Because all others did not work for me. I deleted the symlinks at C:\ProgramData\Oracle\Java\javapath. this makes eclipse to run with the jre declared in the PATH. This is better for me because I want to develop Java with the JRE I chose, not the system JRE. Often you want to develop with older versions and such

Redirect to specified URL on PHP script completion?

If "SOMETHING DONE" doesn't invovle any output via echo/print/etc, then:

<?php
   // SOMETHING DONE

   header('Location: http://stackoverflow.com');
?>

Angularjs $http.get().then and binding to a list

Try using the success() call back

$http.get('/Documents/DocumentsList/' + caseId).success(function (result) {
    $scope.Documents = result;
});

But now since Documents is an array and not a promise, remove the ()

<li ng-repeat="document in Documents" ng-class="IsFiltered(document.Filtered)"> <span>
           <input type="checkbox" name="docChecked" id="doc_{{document.Id}}" ng-model="document.Filtered" />
        </span>
 <span>{{document.Name}}</span>

</li>

Why is it important to override GetHashCode when Equals method is overridden?

We have two problems to cope with.

  1. You cannot provide a sensible GetHashCode() if any field in the object can be changed. Also often a object will NEVER be used in a collection that depends on GetHashCode(). So the cost of implementing GetHashCode() is often not worth it, or it is not possible.

  2. If someone puts your object in a collection that calls GetHashCode() and you have overrided Equals() without also making GetHashCode() behave in a correct way, that person may spend days tracking down the problem.

Therefore by default I do.

public class Foo
{
    public int FooId { get; set; }
    public string FooName { get; set; }

    public override bool Equals(object obj)
    {
        Foo fooItem = obj as Foo;

        if (fooItem == null)
        {
           return false;
        }

        return fooItem.FooId == this.FooId;
    }

    public override int GetHashCode()
    {
        // Some comment to explain if there is a real problem with providing GetHashCode() 
        // or if I just don't see a need for it for the given class
        throw new Exception("Sorry I don't know what GetHashCode should do for this class");
    }
}

NSNotificationCenter addObserver in Swift

Swift 5 Notification Observer

override func viewDidLoad() {
    super.viewDidLoad() 
    NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelChanged), name: UIDevice.batteryLevelDidChangeNotification, object: nil)
}

@objc func batteryLevelChanged(notification : NSNotification){
    //do here code
}

override func viewWillDisappear(_ animated: Bool) {
    NotificationCenter.default.removeObserver(self, name: UIDevice.batteryLevelDidChangeNotification, object: nil)

}

should use size_t or ssize_t

ssize_t is not included in the standard and isn't portable. size_t should be used when handling the size of objects (there's ptrdiff_t too, for pointer differences).

how to hide <li> bullets in navigation menu and footer links BUT show them for listing items

You can style li elements differently based on their class, their id or their ancestor elements:

li { /* styles all li elements*/
    list-style-type: none;
}

#ParentListID li { /* styles the li elements that have an ancestor element
                      of id="ParentListID" */
    list-style-type: bullet;
}

li.className { /* styles li elements of class="className" */
    list-style-type: bullet;
}

Or, to use the ancestor elements:

#navigationContainerID li { /* specifically styles the li elements with an ancestor of
                               id="navigationContainerID" */
    list-style-type: none;
}

li { /* then styles all other li elements that don't have that ancestor element */
    list-style-type: bullet;
}

jQuery - select the associated label element of a input field

There are two ways to specify label for element:

  1. Setting label's "for" attribute to element's id
  2. Placing element inside label

So, the proper way to find element's label is

   var $element = $( ... )

   var $label = $("label[for='"+$element.attr('id')+"']")
   if ($label.length == 0) {
     $label = $element.closest('label')
   }

   if ($label.length == 0) {
     // label wasn't found
   } else {
     // label was found
   }

How to remove a web site from google analytics

UPDATED ANSWER

Google Analytics Admin panel has 3 panels, wherein deleting can be done on any of the following :

  1. Account (Contains multiple properties, and views)
  2. Properties (Contains Views, a subset of Account)
  3. Views (subset of properties)

Google Analytics Admin Panel


Deleting an Account

Deleting the account, will remove all data pertaining to that account, along with all properties/profiles it contains. This is (usually) as good as removing the entire website data.

To delete the account, follow the following steps : (refer to image below)

  • Choose the account you want to delete.

Choose the account you want to delete

  • Click on Account Settings

Click Account Settings

  • Bottom right, a small link that says delete this account.

Delete account

  • You will get a confirmation, if you are sure to, click Delete Account
  • It will give you details, and will confirm deletion (and provide additional info like to remove GA snippet on your website, etc)

Note : If you have multiple accounts linked with your login, the other accounts are NOT touched, only this account will be deleted.


Deleting a property

Deleting a property will remove the selected property, and all the views it holds. To delete a property, delete all views it contains individually (see below for deleting views)

  • Choose the property

Property choice

  • All profiles related to that property appear on the right
  • Delete all the views related to the property individually (details in next section).

Deleting a View (profile)

Deleting a profile will remove only data pertaining to that view, if there is a single profile, the property is automatically deleted.

  • Choose the profile you want to delete

Choose profile

  • Click View Settings

Settings

  • Click on delete View (Bottom right)

Delete the view

  • Click Confirm, and that view will be deleted. If there is only a single view in the property, that property gets automatically deleted.

I want to keep the data, but not see them in the list

Sometimes you have a lot of websites, which you want to keep the data, but remove them from the list, since you don't view them often. I thought of a workaround, in case you do not want to delete the data.

Use another account.

  1. Say, your primary account is A, and you make another account B.
  2. Make B an administrator from A
  3. Remove A

Since A was your primary account, you no longer will be able to access it from the list!
And you still have your data saved, just that you'll have to log in via the other (spare) account.


Previous Answer :

These are the steps to delete a profile from Google Support page :

Delete profiles

Remember, too, that when you delete a profile, you also delete all data associated with that profile, and it is not possible to retrieve that deleted data.

To delete a profile:

  1. Click the Admin tab at the top right of any Analytics page.
  2. Click the account that contains the profile you want to delete.
  3. Click the web property from which you want to delete the profile.
  4. Use the Profile menu to select the profile.
  5. Click the Profile Settings tab.
  6. Click Delete this profile at the bottom of the page.
  7. Click Delete in the confirmation message.

Parse JSON object with string and value only

You need to get a list of all the keys, loop over them and add them to your map as shown in the example below:

    String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
    JSONObject jObject  = new JSONObject(s);
    JSONObject  menu = jObject.getJSONObject("menu");

    Map<String,String> map = new HashMap<String,String>();
    Iterator iter = menu.keys();
    while(iter.hasNext()){
        String key = (String)iter.next();
        String value = menu.getString(key);
        map.put(key,value);
    }

Printing with sed or awk a line following a matching pattern

This might work for you (GNU sed):

sed -n ':a;/regexp/{n;h;p;x;ba}' file

Use seds grep-like option -n and if the current line contains the required regexp replace the current line with the next, copy that line to the hold space (HS), print the line, swap the pattern space (PS) for the HS and repeat.

SQL Query To Obtain Value that Occurs more than once

For SQL Server 2005+

;WITH T AS
(
SELECT *, 
       COUNT(*) OVER (PARTITION BY Lastname) as Cnt
FROM Students
)
SELECT * /*TODO: Add column list. Don't use "*"                   */
FROM T
WHERE Cnt >= 3

How to create a file in Android?

I decided to write a class from this thread that may be helpful to others. Note that this is currently intended to write in the "files" directory only (e.g. does not write to "sdcard" paths).

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.content.Context;

public class AndroidFileFunctions {

    public static String getFileValue(String fileName, Context context) {
        try {
            StringBuffer outStringBuf = new StringBuffer();
            String inputLine = "";
            /*
             * We have to use the openFileInput()-method the ActivityContext
             * provides. Again for security reasons with openFileInput(...)
             */
            FileInputStream fIn = context.openFileInput(fileName);
            InputStreamReader isr = new InputStreamReader(fIn);
            BufferedReader inBuff = new BufferedReader(isr);
            while ((inputLine = inBuff.readLine()) != null) {
                outStringBuf.append(inputLine);
                outStringBuf.append("\n");
            }
            inBuff.close();
            return outStringBuf.toString();
        } catch (IOException e) {
            return null;
        }
    }

    public static boolean appendFileValue(String fileName, String value,
            Context context) {
        return writeToFile(fileName, value, context, Context.MODE_APPEND);
    }

    public static boolean setFileValue(String fileName, String value,
            Context context) {
        return writeToFile(fileName, value, context,
                Context.MODE_WORLD_READABLE);
    }

    public static boolean writeToFile(String fileName, String value,
            Context context, int writeOrAppendMode) {
        // just make sure it's one of the modes we support
        if (writeOrAppendMode != Context.MODE_WORLD_READABLE
                && writeOrAppendMode != Context.MODE_WORLD_WRITEABLE
                && writeOrAppendMode != Context.MODE_APPEND) {
            return false;
        }
        try {
            /*
             * We have to use the openFileOutput()-method the ActivityContext
             * provides, to protect your file from others and This is done for
             * security-reasons. We chose MODE_WORLD_READABLE, because we have
             * nothing to hide in our file
             */
            FileOutputStream fOut = context.openFileOutput(fileName,
                    writeOrAppendMode);
            OutputStreamWriter osw = new OutputStreamWriter(fOut);
            // Write the string to the file
            osw.write(value);
            // save and close
            osw.flush();
            osw.close();
        } catch (IOException e) {
            return false;
        }
        return true;
    }

    public static void deleteFile(String fileName, Context context) {
        context.deleteFile(fileName);
    }
}

How to write data to a text file without overwriting the current data

First of all check if the filename already exists, If yes then create a file and close it at the same time then append your text using AppendAllText. For more info check the code below.


string FILE_NAME = "Log" + System.DateTime.Now.Ticks.ToString() + "." + "txt"; 
string str_Path = HostingEnvironment.ApplicationPhysicalPath + ("Log") + "\\" +FILE_NAME;


 if (!File.Exists(str_Path))
 {
     File.Create(str_Path).Close();
    File.AppendAllText(str_Path, jsonStream + Environment.NewLine);

 }
 else if (File.Exists(str_Path))
 {

     File.AppendAllText(str_Path, jsonStream + Environment.NewLine);

 }

How do you rebase the current branch's changes on top of changes being merged in?

Another way to look at it is to consider git rebase master as:

Rebase the current branch on top of master

Here , 'master' is the upstream branch, and that explain why, during a rebase, ours and theirs are reversed.

Calculating distance between two points, using latitude longitude?

This wikipedia article provides the formulae and an example. The text is in german, but the calculations speak for themselves.

php check if array contains all array values from another array

A bit shorter with array_diff

$musthave = array('a','b');
$test1 = array('a','b','c');
$test2 = array('a','c');

$containsAllNeeded = 0 == count(array_diff($musthave, $test1));

// this is TRUE

$containsAllNeeded = 0 == count(array_diff($musthave, $test2));

// this is FALSE

Atom menu is missing. How do I re-enable

Open Atom and press ALT key you are done.

Compile throws a "User-defined type not defined" error but does not go to the offending line of code

I know this is old, but I had a similar problem and found a fix:

I had the same issue with a module I ported from Excel into Access, in an unrelated UDF I was dimming 'As Range' but ranges don't exist in Access. You may be using a variable type without having the proper reference library turned on.

If you have any non-standard dims google them and see if you're missing the reference to that library under tools.

-E

Jquery-How to grey out the background while showing the loading icon over it

1) "container" is a class and not an ID 2) .container - set z-index and display: none in your CSS and not inline unless there is a really good reason to do so. Demo@fiddle

$("#button").click(function() {
    $(".container").css("opacity", 0.2);
   $("#loading-img").css({"display": "block"});
});

CSS:

#loading-img {
    background: url(http://web.bogdanteodoru.com/wp-content/uploads/2012/01/bouncy-css3-loading-animation.jpg) center center no-repeat;  /* different for testing purposes */
    display: none;
    height: 100px; /* for testing purposes */
    z-index: 12;
}

And a demo with animated image.

Ignore Typescript Errors "property does not exist on value of type"

You can also use the following trick:

y.x = "some custom property"//gives typescript error

y["x"] = "some custom property"//no errors

Note, that to access x and dont get a typescript error again you need to write it like that y["x"], not y.x. So from this perspective the other options are better.

Checking if a SQL Server login already exists

As a minor addition to this thread, in general you want to avoid using the views that begin with sys.sys* as Microsoft is only including them for backwards compatibility. For your code, you should probably use sys.server_principals. This is assuming you are using SQL 2005 or greater.

Navigate to another page with a button in angular 2

Use it like this, should work:

 <a routerLink="/Service/Sign_in"><button class="btn btn-success pull-right" > Add Customer</button></a>

You can also use router.navigateByUrl('..') like this:

<button type="button" class="btn btn-primary-outline pull-right" (click)="btnClick();"><i class="fa fa-plus"></i> Add</button>    

import { Router } from '@angular/router';

btnClick= function () {
        this.router.navigateByUrl('/user');
};

Update 1

You have to inject Router in the constructor like this:

constructor(private router: Router) { }

only then you are able to use this.router. Remember also to import RouterModule in your module.

Update 2

Now, After Angular v4 you can directly add routerLink attribute on the button (As mentioned by @mark in comment section) like below (No "'/url?" since Angular 6, when a Route in RouterModule exists) -

 <button [routerLink]="'url'"> Button Label</button>

Setting PHP tmp dir - PHP upload not working

The problem described here was solved by me quite a long time ago but I don't really remember what was the main reason that uploads weren't working. There were multiple things that needed fixing so the upload could work. I have created checklist that might help others having similar problems and I will edit it to make it as helpful as possible. As I said before on chat, I was working on embedded system, so some points may be skipped on non-embedded systems.

  • Check upload_tmp_dir in php.ini. This is directory where PHP stores temporary files while uploading.

  • Check open_basedir in php.ini. If defined it limits PHP read/write rights to specified path and its subdirectories. Ensure that upload_tmp_dir is inside this path.

  • Check post_max_size in php.ini. If you want to upload 20 Mbyte files, try something a little bigger, like post_max_size = 21M. This defines largest size of POST message which you are probably using during upload.

  • Check upload_max_filesize in php.ini. This specifies biggest file that can be uploaded.

  • Check memory_limit in php.ini. That's the maximum amount of memory a script may consume. It's quite obvious that it can't be lower than upload size (to be honest I'm not quite sure about it-PHP is probably buffering while copying temporary files).

  • Ensure that you're checking the right php.ini file that is one used by PHP on your webserver. The best solution is to execute script with directive described here http://php.net/manual/en/function.php-ini-loaded-file.php (php_ini_loaded_file function)

  • Check what user php runs as (See here how to do it: How to check what user php is running as? ). I have worked on different distros and servers. Sometimes it is apache, but sometimes it can be root. Anyway, check that this user has rights for reading and writing in the temporary directory and directory that you're uploading into. Check all directories in the path in case you're uploading into subdirectory (for example /dir1/dir2/-check both dir1 and dir2.

  • On embedded platforms you sometimes need to restrict writing to root filesystem because it is stored on flash card and this helps to extend life of this card. If you are using scripts to enable/disable file writes, ensure that you enable writing before uploading.

  • I had serious problems with PHP >5.4 upload monitoring based on sessions (as described here http://phpmaster.com/tracking-upload-progress-with-php-and-javascript/ ) on some platforms. Try something simple at first (like here: http://www.dzone.com/snippets/very-simple-php-file-upload ). If it works, you can try more sophisticated mechanisms.

  • If you make any changes in php.ini remember to restart server so the configuration will be reloaded.

How can I stop the browser back button using JavaScript?

I create one HTML page (index.html). I also create a one (mechanism.js) inside a script folder / directory. Then, I lay all my content inside of (index.html) using form, table, span, and div tags as needed. Now, here's the trick that will make back / forward do nothing!

First, the fact that you have only one page! Second, the use of JavaScript with span / div tags to hide and display content on the same page when needed via regular links!

Inside 'index.html':

<td width="89px" align="right" valign="top" style="letter-spacing:1px;">
    <small>
        <b>
            <a href="#" class="traff" onClick="DisplayInTrafficTable();">IN</a>&nbsp;
        </b>
    </small>
    [&nbsp;<span id="inCountSPN">0</span>&nbsp;]
</td>

Inside 'mechanism.js':

function DisplayInTrafficTable()
{
    var itmsCNT = 0;
    var dsplyIn = "";
    for (i=0; i<inTraffic.length; i++)
    {
        dsplyIn += "<tr><td width='11'></td><td align='right'>" + (++itmsCNT) + "</td><td width='11'></td><td><b>" + inTraffic[i] + "</b></td><td width='11'></td><td>" + entryTimeArray[i] + "</td><td width='11'></td><td>" + entryDateArray[i] + "</td><td width='11'></td></tr>";
    }
    document.getElementById('inOutSPN').innerHTML =
        "" +
        "<table border='0' style='background:#fff;'><tr><th colspan='21' style='background:#feb;padding:11px;'><h3 style='margin-bottom:-1px;'>INCOMING TRAFFIC REPORT</h3>" +
        DateStamp() +
        "&nbsp;&nbsp;-&nbsp;&nbsp;<small><a href='#' style='letter-spacing:1px;' onclick='OpenPrintableIn();'>PRINT</a></small></th></tr><tr style='background:#eee;'><td></td><td><b>###</b></td><td></td><td><b>ID #</b></td><td></td><td width='79'><b>TYPE</b></td><td></td><td><b>FIRST</b></td><td></td><td><b>LAST</b></td><td></td><td><b>PLATE #</b></td><td></td><td><b>COMPANY</b></td><td></td><td><b>TIME</b></td><td></td><td><b>DATE</b></td><td></td><td><b>IN / OUT</b></td><td></td></tr>" +
        dsplyIn.toUpperCase() +
        "</table>" +
        "";
    return document.getElementById('inOutSPN').innerHTML;
}

It looks hairy, but note the function names and calls, embedded HTML, and the span tag id calls. This was to show how you can inject different HTML into same span tag on same page! How can Back/Forward affect this design? It cannot, because you are hiding objects and replacing others all on the same page!

How can we hide and display? Here goes:

Inside functions in ' mechanism.js ' as needed, use:

document.getElementById('textOverPic').style.display = "none"; //hide
document.getElementById('textOverPic').style.display = "";     //display

Inside ' index.html ' call functions through links:

<img src="images/someimage.jpg" alt="" />
<span class="textOverPic" id="textOverPic"></span>

and

<a href="#" style="color:#119;font-size:11px;text-decoration:none;letter-spacing:1px;" onclick="HiddenTextsManager(1);">Introduction</a>

Saving image from PHP URL

None of the answers here mention the fact that a URL image can be compressed (gzip), and none of them work in this case.

There are two solutions that can get you around this:

The first is to use the cURL method and set the curl_setopt CURLOPT_ENCODING, '':

// ... image validation ...

// Handle compression & redirection automatically
$ch = curl_init($image_url);
$fp = fopen($dest_path, 'wb');

curl_setopt($ch, CURLOPT_FILE, $fp);
// Exclude header data
curl_setopt($ch, CURLOPT_HEADER, 0);
// Follow redirected location
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
// Auto detect decoding of the response | identity, deflate, & gzip
curl_setopt($ch, CURLOPT_ENCODING, '');

curl_exec($ch);

curl_close($ch);
fclose($fp);

It works, but from hundreds of tests of different images (png, jpg, ico, gif, svg), it is not the most reliable way.

What worked out best is to detect whether an image url has content encoding (e.g. gzip):

// ... image validation ...

// Fetch all headers from URL
$data = get_headers($image_url, true);

// Check if content encoding is set
$content_encoding = isset($data['Content-Encoding']) ? $data['Content-Encoding'] : null;

// Set gzip decode flag
$gzip_decode = ($content_encoding == 'gzip') ? true : false;

if ($gzip_decode)
{
    // Get contents and use gzdecode to "unzip" data
    file_put_contents($dest_path, gzdecode(file_get_contents($image_url)));
}
else
{
    // Use copy method
    copy($image_url, $dest_path);
}

For more information regarding gzdecode see this thread. So far this works fine. If there's anything that can be done better, let us know in the comments below.

Is there any free OCR library for Android?

OCR can be pretty CPU intensive, you might want to reconsider doing it on a smart phone.

That aside, to my knowledge the popular OCR libraries are Aspire and Tesseract. Neither are straight up Java, so you're not going to get a drop-in Android OCR library.

However, Tesseract is open source (GitHub hosted infact); so you can throw some time at porting the subset you need to Java. My understanding is its not insane C++, so depending on how badly you need OCR it might be worth the time.

So short answer: No.

Long answer: if you're willing to work for it.

CronJob not running

For me, the solution was that the file cron was trying to run was in an encrypted directory, more specifcically a user diretory on /home/. Although the crontab was configured as root, because the script being run exisited in an encrypted user directory in /home/ cron could only read this directory when the user was actually logged in. To see if the directory is encrypted check if this directory exists:

/home/.ecryptfs/<yourusername>

if so then you have an encrypted home directory.

The fix for me was to move the script in to a non=encrypted directory and everythig worked fine.

cannot be cast to java.lang.Comparable

  • the object which implements Comparable is Fegan.

The method compareTo you are overidding in it should have a Fegan object as a parameter whereas you are casting it to a FoodItems. Your compareTo implementation should describe how a Fegan compare to another Fegan.

  • To actually do your sorting, you might want to make your FoodItems implement Comparable aswell and copy paste your actual compareTo logic in it.

Sum of two input value by jquery

_x000D_
_x000D_
<script>_x000D_
$(document).ready(function(){_x000D_
var a =parseInt($("#a").val());_x000D_
var b =parseInt($("#b").val());_x000D_
$("#submit").on("click",function(){_x000D_
var sum = a + b;_x000D_
alert(sum);_x000D_
});_x000D_
});_x000D_
</script>
_x000D_
_x000D_
_x000D_

javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

I was experiencing this error on Android 5.1.1 devices sending network requests using okhttp/4.0.0-RC1. Setting header Content-Length: <sizeof response> on the server side resolved the issue.

How to iterate through a list of dictionaries in Jinja template?

Data:

parent_list = [{'A': 'val1', 'B': 'val2'}, {'C': 'val3', 'D': 'val4'}]

in Jinja2 iteration:

{% for dict_item in parent_list %}
   {% for key, value in dict_item.items() %}
      <h1>Key: {{key}}</h1>
      <h2>Value: {{value}}</h2>
   {% endfor %}
{% endfor %}

Note:

Make sure you have the list of dict items. If you get UnicodeError may be the value inside the dict contains unicode format. That issue can be solved in your views.py. If the dict is unicode object, you have to encode into utf-8.

How to time Java program execution speed

Using System.currentTimeMillis() is the proper way of doing this. But, if you use command line, and you want to time the whole program approximately and quickly, think about:

time java App

which allows you not to modify the code and time your App.

How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting

You can also fit a set of a data to whatever function you like using curve_fit from scipy.optimize. For example if you want to fit an exponential function (from the documentation):

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

def func(x, a, b, c):
    return a * np.exp(-b * x) + c

x = np.linspace(0,4,50)
y = func(x, 2.5, 1.3, 0.5)
yn = y + 0.2*np.random.normal(size=len(x))

popt, pcov = curve_fit(func, x, yn)

And then if you want to plot, you could do:

plt.figure()
plt.plot(x, yn, 'ko', label="Original Noised Data")
plt.plot(x, func(x, *popt), 'r-', label="Fitted Curve")
plt.legend()
plt.show()

(Note: the * in front of popt when you plot will expand out the terms into the a, b, and c that func is expecting.)

Create a mocked list by mockito

We can mock list properly for foreach loop. Please find below code snippet and explanation.

This is my actual class method where I want to create test case by mocking list. this.nameList is a list object.

public void setOptions(){
    // ....
    for (String str : this.nameList) {
        str = "-"+str;
    }
    // ....
}

The foreach loop internally works on iterator, so here we crated mock of iterator. Mockito framework has facility to return pair of values on particular method call by using Mockito.when().thenReturn(), i.e. on hasNext() we pass 1st true and on second call false, so that our loop will continue only two times. On next() we just return actual return value.

@Test
public void testSetOptions(){
    // ...
    Iterator<SampleFilter> itr = Mockito.mock(Iterator.class);
    Mockito.when(itr.hasNext()).thenReturn(true, false);
    Mockito.when(itr.next()).thenReturn(Mockito.any(String.class);  

    List mockNameList = Mockito.mock(List.class);
    Mockito.when(mockNameList.iterator()).thenReturn(itr);
    // ...
}

In this way we can avoid sending actual list to test by using mock of list.

What is the effect of extern "C" in C++?

Just wanted to add a bit of info, since I haven't seen it posted yet.

You'll very often see code in C headers like so:

#ifdef __cplusplus
extern "C" {
#endif

// all of your legacy C code here

#ifdef __cplusplus
}
#endif

What this accomplishes is that it allows you to use that C header file with your C++ code, because the macro "__cplusplus" will be defined. But you can also still use it with your legacy C code, where the macro is NOT defined, so it won't see the uniquely C++ construct.

Although, I have also seen C++ code such as:

extern "C" {
#include "legacy_C_header.h"
}

which I imagine accomplishes much the same thing.

Not sure which way is better, but I have seen both.

Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

I was having the same problem while importing the certificate in local keystore. Whenever i issue the keytool command i got the following error.

Certificate was added to keystore keytool error: java.io.FileNotFoundException: C:\Program Files\Java\jdk1.8.0_151\jre\lib\security (Access is denied)

Following solution work for me.

1) make sure you are running command prompt in Rus as Administrator mode

2) Change your current directory to %JAVA_HOME%\jre\lib\security

3) then Issue the below command

keytool -import -alias "mycertificatedemo" -file "C:\Users\name\Downloads\abc.crt" -keystore cacerts

3) give the password changeit

4) enter y

5) you will see the following message on successful "Certificate was added to keystore"

Make sure you are giving the "cacerts" only in -keystore param value , as i was giving the full path like "C**:\Program Files\Java\jdk1.8.0_151\jre\lib\security**".

Hope this will work

@UniqueConstraint and @Column(unique = true) in hibernate annotation

From the Java EE documentation:

public abstract boolean unique

(Optional) Whether the property is a unique key. This is a shortcut for the UniqueConstraint annotation at the table level and is useful for when the unique key constraint is only a single field. This constraint applies in addition to any constraint entailed by primary key mapping and to constraints specified at the table level.

See doc

WooCommerce - get category for product page

A WC product may belong to none, one or more WC categories. Supposing you just want to get one WC category id.

global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
    $product_cat_id = $term->term_id;
    break;
}

Please look into the meta.php file in the "templates/single-product/" folder of the WooCommerce plugin.

<?php echo $product->get_categories( ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', sizeof( get_the_terms( $post->ID, 'product_cat' ) ), 'woocommerce' ) . ' ', '.</span>' ); ?>