Programs & Examples On #Network tools

How to retrieve current workspace using Jenkins Pipeline Groovy script?

There is no variable included for that yet, so you have to use shell-out-read-file method:

sh 'pwd > workspace'
workspace = readFile('workspace').trim()

Or (if running on master node):

workspace = pwd()

How to permanently export a variable in Linux?

A particular example: I have Java 7 and Java 6 installed, I need to run some builds with 6, others with 7. Therefore I need to dynamically alter JAVA_HOME so that maven picks up what I want for each build. I did the following:

  • created j6.sh script which simply does export JAVA_HOME=... path to j6 install...
  • then, as suggested by one of the comments above, whenever I need J6 for a build, I run source j6.sh in that respective command terminal. By default, my JAVA_HOME is set to J7.

Hope this helps.

Find if variable is divisible by 2

if (x & 1)
 itIsOddNumber();
else
 itIsEvenNumber();

Escaping Strings in JavaScript

http://locutus.io/php/strings/addslashes/

function addslashes( str ) {
    return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}

Phonegap Cordova installation Windows

I have found this Multi-Device Hybrid Apps for Visual Studio Documentation for CTP1.1 Last updated: May 29, 2014 .

Some of the content from the documentation as follows.

This release supports building apps for the following device targets:

Android 4+ (4.4 providing the optimal developer experience) iOS 6 & 7 Windows 8.0 (Store) Windows Phone 8.0

Requirements: Windows 8.1

Visual Studio 2013 Update 2 - Professional, Ultimate, or Premium with the following optional features installed:

Tools for Maintaining Store apps for Windows 8 Windows Phone 8.0 SDK

Additional system requirements vary by device platform:

The Android emulator works best with PCs capable of installing the Intel HAXM driver

Windows Phone 8 requires a Hyper-V capable PC to run the emulator Building for iOS and using the iOS Simulator requires a Mac capable of running Xcode 5.1

Third Party Dependencies :

Joyent Node.js – Enables Visual Studio to integrate with the Apache Cordova Command Line Interface (CLI) and Apache Ripple™ Emulator Git CLI – Required only if you need to manually add git URIs for plugins

Google Chrome – Required to run the Apache Ripple emulator for iOS and Android

Apache Ant 1.8.0+ – Required as a dependency for the Android build process

Oracle Java JDK 7 – Required as a dependency for the Android build process

Android SDK – Required as a dependency for the Android build process and Ripple

SQLLite for Windows Runtime – required to add SQL connectivity to Windows apps (for the WebSQL Polyfill plugin)

Apple iTunes – Required for deploying an app to an iOS device connected to your Windows PC

enter image description here

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2

Python 2

The error is caused because ElementTree did not expect to find non-ASCII strings set the XML when trying to write it out. You should use Unicode strings for non-ASCII instead. Unicode strings can be made either by using the u prefix on strings, i.e. u'€' or by decoding a string with mystr.decode('utf-8') using the appropriate encoding.

The best practice is to decode all text data as it's read, rather than decoding mid-program. The io module provides an open() method which decodes text data to Unicode strings as it's read.

ElementTree will be much happier with Unicodes and will properly encode it correctly when using the ET.write() method.

Also, for best compatibility and readability, ensure that ET encodes to UTF-8 during write() and adds the relevant header.

Presuming your input file is UTF-8 encoded (0xC2 is common UTF-8 lead byte), putting everything together, and using the with statement, your code should look like:

with io.open('myText.txt', "r", encoding='utf-8') as f:
    data = f.read()

root = ET.Element("add")
doc = ET.SubElement(root, "doc")

field = ET.SubElement(doc, "field")
field.set("name", "text")
field.text = data

tree = ET.ElementTree(root)
tree.write("output.xml", encoding='utf-8', xml_declaration=True)

Output:

<?xml version='1.0' encoding='utf-8'?>
<add><doc><field name="text">data€</field></doc></add>

Switch between two frames in tkinter

One way is to stack the frames on top of each other, then you can simply raise one above the other in the stacking order. The one on top will be the one that is visible. This works best if all the frames are the same size, but with a little work you can get it to work with any sized frames.

Note: for this to work, all of the widgets for a page must have that page (ie: self) or a descendant as a parent (or master, depending on the terminology you prefer).

Here's a bit of a contrived example to show you the general concept:

try:
    import tkinter as tk                # python 3
    from tkinter import font as tkfont  # python 3
except ImportError:
    import Tkinter as tk     # python 2
    import tkFont as tkfont  # python 2

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")

        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, PageOne, PageTwo):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()


class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is the start page", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)

        button1 = tk.Button(self, text="Go to Page One",
                            command=lambda: controller.show_frame("PageOne"))
        button2 = tk.Button(self, text="Go to Page Two",
                            command=lambda: controller.show_frame("PageTwo"))
        button1.pack()
        button2.pack()


class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()


class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 2", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()


if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

start page page 1 page 2

If you find the concept of creating instance in a class confusing, or if different pages need different arguments during construction, you can explicitly call each class separately. The loop serves mainly to illustrate the point that each class is identical.

For example, to create the classes individually you can remove the loop (for F in (StartPage, ...) with this:

self.frames["StartPage"] = StartPage(parent=container, controller=self)
self.frames["PageOne"] = PageOne(parent=container, controller=self)
self.frames["PageTwo"] = PageTwo(parent=container, controller=self)

self.frames["StartPage"].grid(row=0, column=0, sticky="nsew")
self.frames["PageOne"].grid(row=0, column=0, sticky="nsew")
self.frames["PageTwo"].grid(row=0, column=0, sticky="nsew")

Over time people have asked other questions using this code (or an online tutorial that copied this code) as a starting point. You might want to read the answers to these questions:

Delete files older than 15 days using PowerShell

$limit = (Get-Date).AddDays(-15)
$path = "C:\Some\Path"

# Delete files older than the $limit.
Get-ChildItem -Path $path -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force -Recurse

This will delete old folders and it content.

How to insert double and float values to sqlite?

I think you should give the data types of the column as NUMERIC or DOUBLE or FLOAT or REAL

Read http://sqlite.org/datatype3.html to more info.

How to send a header using a HTTP request through a curl call?

I've switched from curl to Httpie; the syntax looks like:

http http://myurl HeaderName:value

SQL 'LIKE' query using '%' where the search criteria contains '%'

Select * from table where name like search_criteria

if you are expecting the user to add their own wildcards...

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake during web service communicaiton

I run my application with Java 8 and Java 8 brought security certificate onto its trust store. Then I switched to Java 7 and added the following into VM options:

-Djavax.net.ssl.trustStore=C:\<....>\java8\jre\lib\security\cacerts

Simply I pointed to the location where a certificate is.

How to show particular image as thumbnail while implementing share on Facebook?

From Facebook's spec, use a code like this:

<meta property="og:image" content="http://siim.lepisk.com/wp-content/uploads/2011/01/siim-blog-fb.png" />

Source: Facebook Share

Yarn: How to upgrade yarn version using terminal?

For macOS users, if you installed yarn via brew, you can upgrade it using the below command:

brew upgrade yarn

On Linux, just run the below command at the terminal:

$ curl --compressed -o- -L https://yarnpkg.com/install.sh | bash

On Windows, upgrade with Chocolatey

choco upgrade yarn

Credits: Added answers with the help of the below answers

Maven dependency update on commandline

mvn clean install -U

-U means force update of dependencies.

Also, if you want to import the project into eclipse, I first run:

mvn eclipse:eclipse

then run

mvn eclipse:clean

Seems to work for me, but that's just my pennies worth.

How to copy text to the client's clipboard using jQuery?

Copying to the clipboard is a tricky task to do in Javascript in terms of browser compatibility. The best way to do it is using a small flash. It will work on every browser. You can check it in this article.

Here's how to do it for Internet Explorer:

function copy (str)
{
    //for IE ONLY!
    window.clipboardData.setData('Text',str);
}

PostgreSQL : cast string to date DD/MM/YYYY

The documentation says

The output format of the date/time types can be set to one of the four styles ISO 8601, SQL (Ingres), traditional POSTGRES (Unix date format), or German. The default is the ISO format.

So this particular format can be controlled with postgres date time output, eg:

t=# select now();
              now
-------------------------------
 2017-11-29 09:15:25.348342+00
(1 row)

t=# set datestyle to DMY, SQL;
SET
t=# select now();
              now
-------------------------------
 29/11/2017 09:15:31.28477 UTC
(1 row)

t=# select now()::date;
    now
------------
 29/11/2017
(1 row)

Mind that as @Craig mentioned in his answer, changing datestyle will also (and in first turn) change the way postgres parses date.

How to show imageView full screen on imageView click?

It's easy to achieve this is to just use an Intent like this: (I put the method in a custom class that takes in an Activity as a parameter so it can be called from any Fragment or Activity)

    public class UIutils {

private Activity mActivity;

    public UIutils(Activity activity){
        mActivity = activity;
    }

public void showPhoto(Uri photoUri){
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(photoUri, "image/*");
        mActivity.startActivity(intent);
    }
}

Then to use it just do this:

imageView.setOnClickListener(v1 -> new UIutils(getActivity()).showPhoto(Uri.parse(imageURI)));

I use this with an Image URL but it can be used with stored files as well. If you are accessing images form the phones memory you should use a content provider.

How to trigger the window resize event in JavaScript?

Where possible, I prefer to call the function rather than dispatch an event. This works well if you have control over the code you want to run, but see below for cases where you don't own the code.

window.onresize = doALoadOfStuff;

function doALoadOfStuff() {
    //do a load of stuff
}

In this example, you can call the doALoadOfStuff function without dispatching an event.

In your modern browsers, you can trigger the event using:

window.dispatchEvent(new Event('resize'));

This doesn't work in Internet Explorer, where you'll have to do the longhand:

var resizeEvent = window.document.createEvent('UIEvents'); 
resizeEvent.initUIEvent('resize', true, false, window, 0); 
window.dispatchEvent(resizeEvent);

jQuery has the trigger method, which works like this:

$(window).trigger('resize');

And has the caveat:

Although .trigger() simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally-occurring event.

You can also simulate events on a specific element...

function simulateClick(id) {
  var event = new MouseEvent('click', {
    'view': window,
    'bubbles': true,
    'cancelable': true
  });

  var elem = document.getElementById(id); 

  return elem.dispatchEvent(event);
}

git pull fails "unable to resolve reference" "unable to update local ref"

To Answer this in very short, this issue comes when your local has some information about the remote and someone changes something which makes remote and your changes unsync.

I was getting this issue because someone has deleted remote branch and again created with the same name.

For dealing with such issues, do a pull or fetch from remote.

git remote prune origin

or if you are using any GUI, do a fetch from remote.

enter image description here

how to count the total number of lines in a text file using python

This link (How to get line count cheaply in Python?) has lots of potential solutions, but they all ignore one way to make this run considerably faster, namely by using the unbuffered (raw) interface, using bytearrays, and doing your own buffering.

Using a modified version of the timing tool, I believe the following code is faster (and marginally more pythonic) than any of the solutions offered:

def _make_gen(reader):
    b = reader(1024 * 1024)
    while b:
        yield b
        b = reader(1024*1024)

def rawpycount(filename):
    f = open(filename, 'rb')
    f_gen = _make_gen(f.raw.read)
    return sum( buf.count(b'\n') for buf in f_gen )

Here are my timings:

rawpycount        0.0048  0.0046   1.00
bufcount          0.0074  0.0066   1.43
wccount             0.01    0.01   2.17
itercount          0.014   0.014   3.04
opcount            0.021    0.02   4.43
kylecount          0.023   0.021   4.58
simplecount        0.022   0.022   4.81
mapcount           0.038   0.032   6.82

I would post it there, but I'm a relatively new user to stack exchange and don't have the requisite manna.

EDIT:

This can be done completely with generators expressions in-line using itertools, but it gets pretty weird looking:

from itertools import (takewhile,repeat)

def rawbigcount(filename):
    f = open(filename, 'rb')
    bufgen = takewhile(lambda x: x, (f.raw.read(1024*1024) for _ in repeat(None)))
    return sum( buf.count(b'\n') for buf in bufgen if buf )

Scrolling an iframe with JavaScript?

A jQuery solution:

$("#frame1").ready( function() {

  $("#frame1").contents().scrollTop( $("#frame1").contents().scrollTop() + 10 );

});

No connection could be made because the target machine actively refused it?

In my case this was caused by a faulty deployment where a setting in my web.config was not made.

A collegue explained that the IP address in the error message represents the localhost.

When I corrected the web.config I was then using the correct url to make the server calls and it worked.

I thought I would post this in case it might help someone.

Converting JSON String to Dictionary Not List

Here is a simple snippet that read's in a json text file from a dictionary. Note that your json file must follow the json standard, so it has to have " double quotes rather then ' single quotes.

Your JSON dump.txt File:

{"test":"1", "test2":123}

Python Script:

import json
with open('/your/path/to/a/dict/dump.txt') as handle:
    dictdump = json.loads(handle.read())

PHP foreach loop key value

foreach($shipmentarr as $index=>$val){    
    $additionalService = array();

    foreach($additionalService[$index] as $key => $value) {

        array_push($additionalService,$value);

    }
}

How do I get the calling method name and type using reflection?

Yes, in principe it is possible, but it doesn't come for free.

You need to create a StackTrace, and then you can have a look at the StackFrame's of the call stack.

How to unset a JavaScript variable?

?? The accepted answer (and others) are outdated!

TL;DR

  • delete does not remove variables.
    (It's only for removing a property from an object.)

  • The correct way to "unset" is to simply set the variable to null. (source)
    (This enables JavaScript's automatic processes to remove the variable from memory.)

Example:

x = null;


More info:

Use of the delete operator on a variable is deprecated since 2012, when all browsers implemented (automatic) mark-and-sweep garbage-collection. The process works by automatically determining when objects/variables become "unreachable" (deciding whether or not the code still requires them).

With JavaScript, in all modern browsers:

  • Garbage collection is performed automatically. We cannot force or prevent it.
  • Objects are retained in memory while they are reachable.
  • Being referenced is not the same as being reachable: a pack of interlinked objects can become unreachable as a whole. (source)

The delete operator is only used to remove a property from an object; it does not remove variables.

Unlike what common belief suggests (perhaps due to other programming languages like delete in C++), the delete operator has nothing to do with directly freeing memory. Memory management is done indirectly via breaking references. (source)

When using strict mode ('use strict';, as opposed to regular/"sloppy mode") an attempt to delete a variable will throw an error and is not allowed. Normal variables in JavaScript can't be deleted using the delete operator (source) (or any other way, as of 2021).

 


 

...alas, the only solution:

Freeing the contents of a variable

To free the contents of a variable, you can simply set it to null:

var x;

// ...

x = null;    // (x can now be garbage collected)

(source)


Further Reading:

Defining private module functions in python

For methods: (I am not sure if this exactly what you want)

print_thrice.py

def private(method):
    def methodist(string):
        if __name__ == "__main__":
            method(string)
    return methodist
    
@private
def private_print3(string):
    print(string * 3)

private_print3("Hello ") # output: Hello Hello Hello

other_file.py

from print_thrice import private_print3
private_print3("Hello From Another File? ") # no output

This is probably not a perfect solution, as you can still "see" and/or "call" the method. Regardless, it doesn't execute.

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

for anyone who comes across this problem now, with android studio 4.0+ you just have to enable java 8 as mentioned here

android {
    defaultConfig {
            ...
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

How to add custom Http Header for C# Web Service Client consuming Axis 1.4 Web service

If you want to send a custom HTTP Header (not a SOAP Header) then you need to use the HttpWebRequest class the code would look like:

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("Authorization", token);

You cannot add HTTP headers using the visual studio generated proxy, which can be a real pain.

mysql-python install error: Cannot open include file 'config-win.h'

for 64-bit windows

Responsive image align center bootstrap 3

You can fix it with defining margin:0 auto

or you can use col-md-offset also

_x000D_
_x000D_
<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<style>
.img-responsive{
margin:0 auto;
}
</style>
<body>

<div class="container">
  <h2>Image</h2>
<div class="row">
<div class="col-md-12">
  <p>The .img-responsive class makes the image scale nicely to the parent element (resize the browser window to see the effect):</p>                  
  <img src="http://www.w3schools.com/bootstrap/cinqueterre.jpg" class="img-responsive" alt="Cinque Terre" width="304" height="236"> 
</div>
</div>
</div>

</body>
</html>
_x000D_
_x000D_
_x000D_

Generating HTML email body in C#

Emitting handbuilt html like this is probably the best way so long as the markup isn't too complicated. The stringbuilder only starts to pay you back in terms of efficiency after about three concatenations, so for really simple stuff string + string will do.

Other than that you can start to use the html controls (System.Web.UI.HtmlControls) and render them, that way you can sometimes inherit them and make your own clasess for complex conditional layout.

jquery animate background position

You don't need to use the background animate plugin if you just use separate values like this:

$('.pop').animate({
  'background-position-x': '10%',
  'background-position-y': '20%'
}, 10000, 'linear');

Make columns of equal width in <table>

Found this on HTML table: keep the same width for columns

If you set the style table-layout: fixed; on your table, you can override the browser's automatic column resizing. The browser will then set column widths based on the width of cells in the first row of the table. Change your to and remove the inside of it, and then set fixed widths for the cells in .

React-Router: No Not Found Route?

In newer versions of react-router you want to wrap the routes in a Switch which only renders the first matched component. Otherwise you would see multiple components rendered.

For example:

import React from 'react';
import ReactDOM from 'react-dom';
import {
  BrowserRouter as Router,
  Route,
  browserHistory,
  Switch
} from 'react-router-dom';

import App from './app/App';
import Welcome from './app/Welcome';
import NotFound from './app/NotFound';

const Root = () => (
  <Router history={browserHistory}>
    <Switch>
      <Route exact path="/" component={App}/>
      <Route path="/welcome" component={Welcome}/>
      <Route component={NotFound}/>
    </Switch>
  </Router>
);

ReactDOM.render(
  <Root/>,
  document.getElementById('root')
);

Convert object to JSON in Android

download the library Gradle:

compile 'com.google.code.gson:gson:2.8.2'

To use the library in a method.

Gson gson = new Gson();

//transform a java object to json
System.out.println("json =" + gson.toJson(Object.class).toString());

//Transform a json to java object
String json = string_json;
List<Object> lstObject = gson.fromJson(json_ string, Object.class);

Convert a PHP script into a stand-alone windows executable

ExeOutput is also can Turn PHP Websites into Windows Applications and Software

Turn PHP Websites into Windows Applications and Software

Applications made with ExeOutput for PHP run PHP scripts, PHP applications, and PHP websites natively, and do not require a web server, a web browser, or PHP distribution. They are stand-alone and work on any computer with recent Windows versions.

ExeOutput for PHP is a powerful website compiler that works with all of the elements found on modern sites: PHP scripts, JavaScript, HTML, CSS, XML, PDF files, Flash, Flash videos, Silverlight videos, databases, and images. Combining these elements with PHP Runtime and PHP Extensions, ExeOutput for PHP builds an EXE file that contains your complete application.

http://www.exeoutput.com/

jquery how to empty input field

You can clear the input field by using $('#shares').val('');

How do I write a Windows batch script to copy the newest file from a directory?

This will open a second cmd.exe window. If you want it to go away, replace the /K with /C.

Obviously, replace new_file_loc with whatever your new file location will be.

@echo off
for /F %%i in ('dir /B /O:-D *.txt') do (
    call :open "%%i"
    exit /B 0
)
:open
    start "window title" "cmd /K copy %~1 new_file_loc"
exit /B 0

Regular expression to remove HTML tags from a string

You could do it with jsoup http://jsoup.org/

Whitelist whitelist = Whitelist.none();
String cleanStr = Jsoup.clean(yourText, whitelist);

SVN how to resolve new tree conflicts when file is added on two branches

I just managed to wedge myself pretty thoroughly trying to follow user619330's advice above. The situation was: (1): I had added some files while working on my initial branch, branch1; (2) I created a new branch, branch2 for further development, branching it off from the trunk and then merging in my changes from branch1 (3) A co-worker had copied my mods from branch1 to his own branch, added further mods, and then merged back to the trunk; (4) I now wanted to merge the latest changes from trunk into my current working branch, branch2. This is with svn 1.6.17.

The merge had tree conflicts with the new files, and I wanted the new version from the trunk where they differed, so from a clean copy of branch2, I did an svn delete of the conflicting files, committed these branch2 changes (thus creating a temporary version of branch2 without the files in question), and then did my merge from the trunk. I did this because I wanted the history to match the trunk version so that I wouldn't have more problems later when trying to merge back to trunk. Merge went fine, I got the trunk version of the files, svn st shows all ok, and then I hit more tree conflicts while trying to commit the changes, between the delete I had done earlier and the add from the merge. Did an svn resolve of the conflicts in favor of my working copy (which now had the trunk version of the files), and got it to commit. All should be good, right?

Well, no. An update of another copy of branch2 resulted in the old version of the files (pre-trunk merge). So now I have two different working copies of branch2, supposedly updated to the same version, with two different versions of the files, and both insisting that they are fully up to date! Checking out a clean copy of branch2 resulted in the old (pre-trunk) version of the files. I manually update these to the trunk version and commit the changes, go back to my first working copy (from which I had submitted the trunk changes originally), try to update it, and now get a checksum error on the files in question. Blow the directory in question away, get a new version via update, and finally I have what should be a good version of branch2 with the trunk changes. I hope. Caveat developer.

Regex for allowing alphanumeric,-,_ and space

/^[-\w\s]+$/

\w matches letters, digits, and underscores

\s matches spaces, tabs, and line breaks

- matches the hyphen (if you have hyphen in your character set example [a-z], be sure to place the hyphen at the beginning like so [-a-z])

Variable is accessed within inner class. Needs to be declared final

Here's a funny answer.

You can declare a final one-element array and change the elements of the array all you want apparently. I'm sure it breaks the very reason why this compiler rule was implemented in the first place but it's handy when you're in a time-bind as I was today.

I actually can't claim credit for this one. It was IntelliJ's recommendation! Feels a bit hacky. But doesn't seem as bad as a global variable so I thought it worth mentioning here. It's just one solution to the problem. Not necessarily the best one.

final int[] tapCount = {0};

addSiteButton.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
       tapCount[0]++;
    }

});

In CSS what is the difference between "." and "#" when declaring a set of styles?

A couple of quick extensions on what has already been said...

An id must be unique, but you can use the same id to make different styles more specific.

For example, given this HTML extract:

<div id="sidebar">
    <h2>Heading</h2>
    <ul class="menu">
        ...
    </ul>
</div>
<div id="content">
    <h2>Heading</h2>
    ...
</div>
<div id="footer">
    <ul class="menu">
        ...
    </ul>
</div>

You could apply different styles with these:

#sidebar h2
{ ... }

#sidebar .menu
{ ... }

#content h2
{ ... }

#footer .menu
{ ... }


Another useful thing to know: you can have multiple classes on an element, by space-delimiting them...

<ul class="main menu">...</ul>
<ul class="other menu">...</ul>

Which allows you to have common styling in .menu with specific styles using .main.menu and .sub.menu

.menu
{ ... }

.main.menu
{ ... }

.other.menu
{ ... }

How to read a file in other directory in python

In case you're not in the specified directory (i.e. direct), you should use (in linux):

x_file = open('path/to/direct/filename.txt')

Note the quotes and the relative path to the directory.

This may be your problem, but you also don't have permission to access that file. Maybe you're trying to open it as another user.

Disabling Warnings generated via _CRT_SECURE_NO_DEPRECATE

You could disable the warnings temporarily in places where they appear by using

#pragma warning(push)
#pragma warning(disable: warning-code) //4996 for _CRT_SECURE_NO_WARNINGS equivalent
// deprecated code here
#pragma warning(pop)

so you don't disable all warnings, which can be harmful at times.

To show a new Form on click of a button in C#

This worked for me using it in a toolstrip menu:

 private void calculatorToolStripMenuItem_Click(object sender, EventArgs e)
 {
     calculator form = new calculator();
     form.Show(); // or form.ShowDialog(this);
 }

HTML5 validation when the input type is not "submit"

Try this out:

<script type="text/javascript">
    function test
    {
        alert("hello world");  //write your logic here like ajax
    }
</script>

<form action="javascript:test();" >
    firstName : <input type="text" name="firstName" id="firstName" required/><br/>
    lastName : <input type="text" name="lastName" id="lastName" required/><br/>
    email : <input type="email" name="email" id="email"/><br/>
    <input type="submit" value="Get It!" name="submit" id="submit"/>
</form>

Bootstrap tab activation with JQuery

Having just struggled with this - I'll explain my situation.

I have my tabs within a bootstrap modal and set the following on load (pre the modal being triggered):

$('#subMenu li:first-child a').tab('show');

Whilst the tab was selected the actual pane wasn't visible. As such you need to add active class to the pane as well:

$('#profile').addClass('active');

In my case the pane had #profile (but this could have easily been .pane:first-child) which then displayed the correct pane.

VBA paste range

I would try

Sheets("Sheet1").Activate
Set Ticker = Range(Cells(2, 1), Cells(65, 1))
Ticker.Copy

Worksheets("Sheet2").Range("A1").Offset(0,0).Cells.Select
Worksheets("Sheet2").paste

What is the advantage of using REST instead of non-REST HTTP?

It's written down in the Fielding dissertation. But if you don't want to read a lot:

  • increased scalability (due to stateless, cache and layered system constraints)
  • decoupled client and server (due to stateless and uniform interface constraints)
    • reusable clients (client can use general REST browsers and RDF semantics to decide which link to follow and how to display the results)
    • non breaking clients (clients break only by application specific semantics changes, because they use the semantics instead of some API specific knowledge)

Python Traceback (most recent call last)

In Python2, input is evaluated, input() is equivalent to eval(raw_input()). When you enter klj, Python tries to evaluate that name and raises an error because that name is not defined.

Use raw_input to get a string from the user in Python2.

Demo 1: klj is not defined:

>>> input()
klj
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'klj' is not defined

Demo 2: klj is defined:

>>> klj = 'hi'
>>> input()
klj
'hi'

Demo 3: getting a string with raw_input:

>>> raw_input()
klj
'klj'

The most efficient way to implement an integer based power function pow(int, int)

If you want to get the value of an integer for 2 raised to the power of something it is always better to use the shift option:

pow(2,5) can be replaced by 1<<5

This is much more efficient.

Iterating through array - java

If you are using an array (and purely an array), the lookup of "contains" is O(N), because worst case, you must iterate the entire array. Now if the array is sorted you can use a binary search, which reduces the search time to log(N) with the overhead of the sort.

If this is something that is invoked repeatedly, place it in a function:

private boolean inArray(int[] array, int value)
{  
     for (int i = 0; i < array.length; i++)
     {
        if (array[i] == value) 
        {
            return true;
        }
     }
    return false;  
}  

git pull error "The requested URL returned error: 503 while accessing"

Try disabling all the system wide HTTP and HTTPS proxies:

export http_proxy="" 
export https_proxy=""
export HTTP_PROXY=""
export HTTPS_PROXY=""

Playing a MP3 file in a WinForm application

  1. first go to the properties of your project
  2. click on add references
  3. add the library under COM object for window media player then type your code where you want


    Source:

        WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
    
        wplayer.URL = @"C:\Users\Adil M\Documents\Visual Studio 2012\adil.mp3";
        wplayer.controls.play();
    

Retrieving Dictionary Value Best Practices

I imagine that trygetvalue is doing something more like:

if(myDict.ReallyOptimisedVersionofContains(someKey))
{ 
  someVal = myDict[someKey];
  return true;
}
return false;

So hopefully no try/catch anywhere.

I think it is just a method of convenience really. I generally use it as it saves a line of code or two.

How do I get the total Json record count using JQuery?

Perhaps you might want to try JSON.parse your return result first then you can get the count by .length

Converting string into datetime

datetime.strptime is the main routine for parsing strings into datetimes. It can handle all sorts of formats, with the format determined by a format string you give it:

from datetime import datetime

datetime_object = datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')

The resulting datetime object is timezone-naive.

Links:

Notes:

  • strptime = "string parse time"
  • strftime = "string format time"
  • Pronounce it out loud today & you won't have to search for it again in 6 months.

How to get distinct values for non-key column fields in Laravel?

$users = User::select('column1', 'column2', 'column3')->distinct()->get(); retrieves all three coulmns for distinct rows in the table. You can add as many columns as you wish.

How can I make one python file run another?

You could use this script:

def run(runfile):
  with open(runfile,"r") as rnf:
    exec(rnf.read())

Syntax:

run("file.py")

Java 8 Lambda Stream forEach with multiple statements

You don't have to cram multiple operations into one stream/lambda. Consider separating them into 2 statements (using static import of toList()):

entryList.forEach(e->e.setTempId(tempId));

List<Entry> updatedEntries = entryList.stream()
  .map(e->entityManager.update(entry, entry.getId()))
  .collect(toList());

How to get base url with jquery or javascript?

Here's a short one:

_x000D_
_x000D_
const base = new URL('/', location.href).href;

console.log(base);
_x000D_
_x000D_
_x000D_

Given two directory trees, how can I find out which files differ by content?

To report differences between dirA and dirB, while also updating/syncing.

rsync -auv <dirA> <dirB>

SCCM 2012 application install "Failed" in client Software Center

The execmgr.log will show the commandline and ccmcache folder used for installation. Typically, required apps don't show on appenforce.log and some clients will have outdated appenforce or no ppenforce.log files. execmgr.log also shows required hidden uninstall actions as well.

You may want to save the blog link. I still reference it from time to time.

How to pass props to {this.props.children}

The slickest way to do this:

    {React.cloneElement(this.props.children, this.props)}

How do I set up the database.yml file in Rails?

At first I would use http://ruby.railstutorial.org/.

And database.yml is place where you put setup for database your application use - username, password, host - for each database. With new application you dont need to change anything - simply use default sqlite setup.

How much does it cost to develop an iPhone application?

The Barack Obama app took 22 days to develop from first code to release. Three developers (although not all of them were full time). 10 people total. Figure 500-1000 man hours. Contracting rates are $100-150/hr. Figure $50000-$150000. Compare your app to Obama.app and scale accordingly.

Select a dummy column with a dummy value in SQL?

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

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

Something like this may work:

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

Actual syntax maybe a bit off though

Sass - Converting Hex to RGBa for background opacity

you can try this solution, is the best... url(github)

// Transparent Background
// From: http://stackoverflow.com/questions/6902944/sass-mixin-for-background-transparency-back-to-ie8

// Extend this class to save bytes
.transparent-background {
  background-color: transparent;
  zoom: 1;
}

// The mixin
@mixin transparent($color, $alpha) {
  $rgba: rgba($color, $alpha);
  $ie-hex-str: ie-hex-str($rgba);
  @extend .transparent-background;
  background-color: $rgba;
  filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#{$ie-hex-str},endColorstr=#{$ie-hex-str});
}

// Loop through opacities from 90 to 10 on an alpha scale
@mixin transparent-shades($name, $color) {
  @each $alpha in 90, 80, 70, 60, 50, 40, 30, 20, 10 {
    .#{$name}-#{$alpha} {
      @include transparent($color, $alpha / 100);
    }
  }
}

// Generate semi-transparent backgrounds for the colors we want
@include transparent-shades('dark', #000000);
@include transparent-shades('light', #ffffff);

MySQL query to select events between start/end date

select * from tbl where (endDate>=@starDate and startDate<=@endDate)

attached the diagram for explanationenter image description here

storing simple data in DB StartDate =10/01/2020 and endDate=20/01/2020. user can provide @startDate(d1) and @endDate(d2) to search.

here 6 scenarios can happen depicted by the 4 red lines (match data) 2 green lines (no match data).

so by conclusion from the image, to get data from DB by providing d1,d2. ED must be greater than d1(@startDate) and SD must be less than d2(@endDate).

Batch file to run a command in cmd within a directory

For me, the following is working and running activiti server as well as opening the explorer in browser (with the help of zb226's answer and comment);

START "runas /user:administrator" cmd /K "cd C:\activiti-5.9\setup & ant demo.start"

START /wait localhost:8080/activiti-explorer

Foreach Control in form, how can I do something to all the TextBoxes in my Form?

The trick here is that Controls is not a List<> or IEnumerable but a ControlCollection.

I recommend using an extension of Control that will return something more..queriyable ;)

public static IEnumerable<Control> All(this ControlCollection controls)
    {
        foreach (Control control in controls)
        {
            foreach (Control grandChild in control.Controls.All())
                yield return grandChild;

            yield return control;
        }
    }

Then you can do :

foreach(var textbox in this.Controls.All().OfType<TextBox>)
{
    // Apply logic to the textbox here
}

What is a JavaBean exactly?

They are serializable, have a zero-argument constructor, and allow access to properties using getter and setter methods. The name "Bean" was given to encompass this standard, which aims to create reusable software components for Java. According to Wikipedia.

The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application. According to Spring IoC.

Netbeans installation doesn't find JDK

We managed installation of netbeans 6.8 under windows 8 successfully the following way:

  • Don't execute but unzip netbeans-6.8-ml-windows.exe with 7zip (or other unzipper) in an emtpy folder
  • execute cmd.exe as administrator
  • cd to the folder in which you unzipped the installer
  • execute 'java org.netbeans.installer.Installer'

-> installation executes without any errors

Regular expression \p{L} and \p{N}

\p{L} matches a single code point in the category "letter".
\p{N} matches any kind of numeric character in any script.

Source: regular-expressions.info

If you're going to work with regular expressions a lot, I'd suggest bookmarking that site, it's very useful.

How to mark a build unstable in Jenkins when running shell scripts

Modern Jenkins versions (since 2.26, October 2016) solved this: it's just an advanced option for the Execute shell build step!

exit code for build

You can just choose and set an arbitrary exit value; if it matches, the build will be unstable. Just pick a value which is unlikely to be launched by a real process in your build.

Get all parameters from JSP page

This should print out all Parameters that start with "Question".

<html><body>
<%@ page import = "java.util.*" %>
<b>Parameters:</b><br>
<%
  Enumeration parameterList = request.getParameterNames();
  while( parameterList.hasMoreElements() )
  {
    String sName = parameterList.nextElement().toString();
    if(sName.toLowerCase.startsWith("question")){
      String[] sMultiple = request.getParameterValues( sName );
      if( 1 >= sMultiple.length )
        // parameter has a single value. print it.
        out.println( sName + " = " + request.getParameter( sName ) + "<br>" );
      else
        for( int i=0; i<sMultiple.length; i++ )
          // if a paramater contains multiple values, print all of them
          out.println( sName + "[" + i + "] = " + sMultiple[i] + "<br>" );
    }
  }
%>
</body></html>

Remove final character from string

What you are trying to do is an extension of string slicing in Python:

Say all strings are of length 10, last char to be removed:

>>> st[:9]
'abcdefghi'

To remove last N characters:

>>> N = 3
>>> st[:-N]
'abcdefg'

How to remove an app with active device admin enabled on Android?

Go to SETTINGS->Location and Security-> Device Administrator and deselect the admin which you want to uninstall.

Now uninstall the application. If it still says you need to deactivate the application before uninstalling, you may need to Force Stop the application before uninstalling.

Check if an HTML input element is empty or has no value entered by user

Your first one was basically right. This, FYI, is bad. It does an equality check between a DOM node and a string:

if (document.getElementById('customx') == ""){

DOM nodes are actually their own type of JavaScript object. Thus this comparison would never work at all since it's doing an equality comparison on two distinctly different data types.

Python - round up to the nearest ten

You can use math.ceil() to round up, and then multiply by 10

import math

def roundup(x):
    return int(math.ceil(x / 10.0)) * 10

To use just do

>>roundup(45)
50

Capturing Groups From a Grep RegEx

I prefer the one line python or perl command, both often included in major linux disdribution

echo $'
<a href="http://stackoverflow.com">
</a>
<a href="http://google.com">
</a>
' |  python -c $'
import re
import sys
for i in sys.stdin:
  g=re.match(r\'.*href="(.*)"\',i);
  if g is not None:
    print g.group(1)
'

and to handle files:

ls *.txt | python -c $'
import sys
import re
for i in sys.stdin:
  i=i.strip()
  f=open(i,"r")
  for j in f:
    g=re.match(r\'.*href="(.*)"\',j);
    if g is not None:
      print g.group(1)
  f.close()
'

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

From the official jQuery documentation

  • .mouseover()
    Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.

  • .hover() Bind one or two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.

    Calling $(selector).hover(handlerIn, handlerOut) is shorthand for: $(selector).mouseenter(handlerIn).mouseleave(handlerOut);


  • .mouseenter()

    Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.

    mouseover fires when the pointer moves into the child element as well, while mouseenter fires only when the pointer moves into the bound element.


What this means

Because of this, .mouseover() is not the same as .hover(), for the same reason .mouseover() is not the same as .mouseenter().

$('selector').mouseover(over_function) // may fire multiple times

// enter and exit functions only called once per element per entry and exit
$('selector').hover(enter_function, exit_function) 

if, elif, else statement issues in Bash

I would recommend you having a look at the basics of conditioning in bash.

The symbol "[" is a command and must have a whitespace prior to it. If you don't give whitespace after your elif, the system interprets elif[ as a a particular command which is definitely not what you'd want at this time.

Usage:

elif(A COMPULSORY WHITESPACE WITHOUT PARENTHESIS)[(A WHITE SPACE WITHOUT PARENTHESIS)conditions(A WHITESPACE WITHOUT PARENTHESIS)]

In short, edit your code segment to:

elif [ "$seconds" -gt 0 ]

You'd be fine with no compilation errors. Your final code segment should look like this:

#!/bin/sh    
if [ "$seconds" -eq 0 ];then
       $timezone_string="Z"
    elif [ "$seconds" -gt 0 ]
    then
       $timezone_string=`printf "%02d:%02d" $seconds/3600 ($seconds/60)%60`
    else
       echo "Unknown parameter"
    fi

Java 32-bit vs 64-bit compatibility

The Java JNI requires OS libraries of the same "bittiness" as the JVM. If you attempt to build something that depends, for example, on IESHIMS.DLL (lives in %ProgramFiles%\Internet Explorer) you need to take the 32bit version when your JVM is 32bit, the 64bit version when your JVM is 64bit. Likewise for other platforms.

Apart from that, you should be all set. The generated Java bytecode s/b the same.

Note that you should use 64bit Java compiler for larger projects because it can address more memory.

mongo - couldn't connect to server 127.0.0.1:27017

I was getting this error on ubuntu but you can try with the following command:

sudo service mongod start

jQuery: Can I call delay() between addClass() and such?

You can create a new queue item to do your removing of the class:

$("#div").addClass("error").delay(1000).queue(function(next){
    $(this).removeClass("error");
    next();
});

Or using the dequeue method:

$("#div").addClass("error").delay(1000).queue(function(){
    $(this).removeClass("error").dequeue();
});

The reason you need to call next or dequeue is to let jQuery know that you are done with this queued item and that it should move on to the next one.

What is System, out, println in System.out.println() in Java

Whenever you're confused, I would suggest consulting the Javadoc as the first place for your clarification.

From the javadoc about System, here's what the doc says:

public final class System
extends Object

The System class contains several useful class fields and methods. It cannot be instantiated.
Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.

Since:
JDK1.0

Regarding System.out

public static final PrintStream out
The "standard" output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user.
For simple stand-alone Java applications, a typical way to write a line of output data is:

     System.out.println(data)

What is the best or most commonly used JMX Console / Client

JRockit Mission Control is becoming Java Mission Control and will be dedicated exclusively to Hotspot. If you are an Oracle customer, you can download the 5.x versions of Java Mission Control from MOS (My Oracle Support). Java Mission Control will eventually be released together with the Oracle JDK. The reason it is not yet generally available is that there are some serious limitations, especially when using the Flight Recorder. However, if you are only interested in using the JMX console, you should be golden!

Why use the params keyword?

Using params allows you to call the function with no arguments. Without params:

static public int addTwoEach(int[] args)
{
    int sum = 0;

    foreach (var item in args)
    {
        sum += item + 2;
    }

    return sum;
}

addtwoEach(); // throws an error

Compare with params:

static public int addTwoEach(params int[] args)
{
    int sum = 0;

    foreach (var item in args)
    {
        sum += item + 2;
    }

    return sum;
}

addtwoEach(); // returns 0

Generally, you can use params when the number of arguments can vary from 0 to infinity, and use an array when numbers of arguments vary from 1 to infinity.

C++ trying to swap values in a vector

Both proposed possibilities (std::swap and std::iter_swap) work, they just have a slightly different syntax. Let's swap a vector's first and second element, v[0] and v[1].

We can swap based on the objects contents:

std::swap(v[0],v[1]);

Or swap based on the underlying iterator:

std::iter_swap(v.begin(),v.begin()+1);

Try it:

int main() {
  int arr[] = {1,2,3,4,5,6,7,8,9};
  std::vector<int> * v = new std::vector<int>(arr, arr + sizeof(arr) / sizeof(arr[0]));
  // put one of the above swap lines here
  // ..
  for (std::vector<int>::iterator i=v->begin(); i!=v->end(); i++)
    std::cout << *i << " ";
  std::cout << std::endl;
}

Both times you get the first two elements swapped:

2 1 3 4 5 6 7 8 9

How to output git log with the first line only?

If you don't want hashes and just the first lines (subject lines):

git log --pretty=format:%s

Pandas: Convert Timestamp to datetime.date

As of pandas 0.20.3, use .to_pydatetime() to convert any pandas.DateTimeIndex instances to Python datetime.datetime.

Get file name from a file location in Java

new File(fileName).getName();

or

int idx = fileName.replaceAll("\\\\", "/").lastIndexOf("/");
return idx >= 0 ? fileName.substring(idx + 1) : fileName;

Notice that the first solution is system dependent. It only takes the system's path separator character into account. So if your code runs on a Unix system and receives a Windows path, it won't work. This is the case when processing file uploads being sent by Internet Explorer.

Using Excel VBA to export data to MS Access table

@Ahmed

Below is code that specifies fields from a named range for insertion into MS Access. The nice thing about this code is that you can name your fields in Excel whatever the hell you want (If you use * then the fields have to match exactly between Excel and Access) as you can see I have named an Excel column "Haha" even though the Access column is called "dte".

Sub test()
    dbWb = Application.ActiveWorkbook.FullName
    dsh = "[" & Application.ActiveSheet.Name & "$]" & "Data2"  'Data2 is a named range


sdbpath = "C:\Users\myname\Desktop\Database2.mdb"
sCommand = "INSERT INTO [main] ([dte], [test1], [values], [values2]) SELECT [haha],[test1],[values],[values2] FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh

Dim dbCon As New ADODB.Connection
Dim dbCommand As New ADODB.Command

dbCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sdbpath & "; Jet OLEDB:Database Password=;"
dbCommand.ActiveConnection = dbCon

dbCommand.CommandText = sCommand
dbCommand.Execute

dbCon.Close


End Sub

Calculate execution time of a SQL query?

I found this one more helpful and simple

DECLARE @StartTime datetime,@EndTime datetime   
SELECT @StartTime=GETDATE() 
--Your Query to be run goes here--  
SELECT @EndTime=GETDATE()   
SELECT DATEDIFF(ms,@StartTime,@EndTime) AS [Duration in milliseconds]   

Is there a difference between x++ and ++x in java?

yes

++x increments the value of x and then returns x
x++ returns the value of x and then increments

example:

x=0;
a=++x;
b=x++;

after the code is run both a and b will be 1 but x will be 2.

equivalent to push() or pop() for arrays?

In Java an array has a fixed size (after initialisation), meaning that you can't add or remove items from an array.

int[] i = new int[10];

The above snippet mean that the array of integers has a length of 10. It's not possible add an eleventh integer, without re-assign the reference to a new array, like the following:

int[] i = new int[11];

In Java the package java.util contains all kinds of data structures that can handle adding and removing items from array-like collections. The classic data structure Stack has methods for push and pop.

How to fix UITableView separator on iOS 7?

UITableView has a property separatorInset. You can use that to set the insets of the table view separators to zero to let them span the full width of the screen.

[tableView setSeparatorInset:UIEdgeInsetsZero];

Note: If your app is also targeting other iOS versions, you should check for the availability of this property before calling it by doing something like this:

if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
    [tableView setSeparatorInset:UIEdgeInsetsZero];
}

Detecting IE11 using CSS Capability/Feature Detection

This worked for me

if(navigator.userAgent.match(/Trident.*rv:11\./)) {
    $('body').addClass('ie11');
}

And then in the css file things prefixed with

body.ie11 #some-other-div

When is this browser ready to die?

how do I query sql for a latest record date for each user

SELECT MAX(DATE) AS dates 
FROM assignment  
JOIN paper_submission_detail ON  assignment.PAPER_SUB_ID = 
     paper_submission_detail.PAPER_SUB_ID 

Make selected block of text uppercase

I'm using the change-case extension and it works fine. I defined the shortcuts:

{ 
  "key": "ctrl+shift+u", 
  "command": "extension.changeCase.upper", 
  "when": "editorTextFocus" 
},
{ 
  "key": "ctrl+u",
  "command": "extension.changeCase.lower", 
  "when": "editorTextFocus" 
},

Running Internet Explorer 6, Internet Explorer 7, and Internet Explorer 8 on the same machine

I did this on my Windows 7 computer today:

  1. Installed Windows Virtual PC, and ran XP Mode
  2. Created two Windows XP images. One with Internet Explorer 6 and one with Internet Explorer 7.
  3. Now I can run these to browsers from my Windows 7 desktop! Just like any other application. No need to open Virtual PC.

http://www.microsoft.com/windows/virtual-pc/

How can I get form data with JavaScript/jQuery?

$('form').serialize() //this produces: "foo=1&bar=xxx&this=hi"

demo

MVC4 input field placeholder

An alternative to using a plugin is using an editor template. What you need to do is to create a template file in Shared\EditorTemplates folder and call it String.cshtml. Then put this in that file:

@Html.TextBox("",ViewData.TemplateInfo.FormattedModelValue, 
    new { placeholder = ViewData.ModelMetadata.Watermark })

Then use it in your view like this:

@Html.EditorFor(m=>Model.UnitPercent)

The downside, this works for properties of type string, and you will have to create a template for each type that you want support for a watermark.

Writing to a new file if it doesn't exist, and appending to a file if it does

It's not clear to me exactly where the high-score that you're interested in is stored, but the code below should be what you need to check if the file exists and append to it if desired. I prefer this method to the "try/except".

import os
player = 'bob'

filename = player+'.txt'

if os.path.exists(filename):
    append_write = 'a' # append if already exists
else:
    append_write = 'w' # make a new file if not

highscore = open(filename,append_write)
highscore.write("Username: " + player + '\n')
highscore.close()

How to convert string to double with proper cultureinfo

You can change your UI culture to anything you want, but you should change the number separator like this:

CultureInfo info = new CultureInfo("fa-IR");
info.NumberFormat.NumberDecimalSeparator = ".";
Thread.CurrentThread.CurrentCulture = info;
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;

With this, your strings converts like this: "12.49" instead of "12,49" or "12/49"

Add support library to Android Studio project

This is way more simpler with Maven dependency feature:

  1. Open File -> Project Structure... menu.
  2. Select Modules in the left pane, choose your project's main module in the middle pane and open Dependencies tab in the right pane.
  3. Click the plus sign in the right panel and select "Maven dependency" from the list. A Maven dependency dialog will pop up.
  4. Enter "support-v4" into the search field and click the icon with magnifying glass.
  5. Select "com.google.android:support-v4:r7@jar" from the drop-down list.
  6. Click "OK".
  7. Clean and rebuild your project.

Hope this will help!

Using form input to access camera and immediately upload photos using web app

It's really easy to do this, simply send the file via an XHR request inside of the file input's onchange handler.

<input id="myFileInput" type="file" accept="image/*;capture=camera">

var myInput = document.getElementById('myFileInput');

function sendPic() {
    var file = myInput.files[0];

    // Send file here either by adding it to a `FormData` object 
    // and sending that via XHR, or by simply passing the file into 
    // the `send` method of an XHR instance.
}

myInput.addEventListener('change', sendPic, false);

Capitalize the first letter of string in AngularJs

I'd say don't use angular/js as you can simply use css instead:

In your css, add the class:

.capitalize {
   text-transform: capitalize;
}

Then, simply wrap the expression (for ex) in your html:

<span class="capitalize">{{ uppercase_expression }}</span>

No js needed ;)

Language Books/Tutorials for popular languages

For Java, I highly recommend Core Java. It's a large tome (or two large tomes), but I've found it to be one of the best references on Java I've read.

"The system cannot find the file specified" when running C++ program

This is a first step for somebody that is a beginner. Same thing happened to me:

Look in the Solution Explorer box to the left. Make sure that there is actually a .cpp file there. You can do the same by looking the .cpp file where the .sln file for the project is stored. If there is not one, then you will get that error.

When adding a cpp file you want to use the Add new item icon. (top left with a gold star on it, hover over it to see the name) For some reason Ctrl+N does not actually add a .cpp file to the project.

CodeIgniter: "Unable to load the requested class"

If you're using a linux server for your application then it is necessary to use lowercase file name and class name to avoid this issue.

Ex.

Filename: csvsample.php

class csvsample {

}

Quickly reading very large tables as dataframes

Strangely, no one answered the bottom part of the question for years even though this is an important one -- data.frames are simply lists with the right attributes, so if you have large data you don't want to use as.data.frame or similar for a list. It's much faster to simply "turn" a list into a data frame in-place:

attr(df, "row.names") <- .set_row_names(length(df[[1]]))
class(df) <- "data.frame"

This makes no copy of the data so it's immediate (unlike all other methods). It assumes that you have already set names() on the list accordingly.

[As for loading large data into R -- personally, I dump them by column into binary files and use readBin() - that is by far the fastest method (other than mmapping) and is only limited by the disk speed. Parsing ASCII files is inherently slow (even in C) compared to binary data.]

Concept behind putting wait(),notify() methods in Object class

These methods works on the locks and locks are associated with Object and not Threads. Hence, it is in Object class.

The methods wait(), notify() and notifyAll() are not only just methods, these are synchronization utility and used in communication mechanism among threads in Java.

For more detailed explanation, please visit : http://parameshk.blogspot.in/2013/11/why-wait-notify-and-notifyall-methods.html

django change default runserver port

If you wish to change the default configurations then follow this steps:

  1. Open terminal type command

     $ /usr/local/lib/python<2/3>.x/dist-packages/django/core/management/commands
    
  2. Now open runserver.py file in nano editor as superuser

     $ sudo nano runserver.py
    
  3. find the 'default_port' variable then you will see the default port no is '8000'. Now you can change it to whatever you want.

  4. Now exit and save the file using "CTRL + X and Y to save the file"

Note: Replace <2/3>.x with your usable version of python

Curl GET request with json parameter

For username and password protected services use the following

curl -u admin:password -X GET http://172.16.2.125:9200 -d '{"sort":[{"lastUpdateTime":{"order":"desc"}}]}'

SpringMVC RequestMapping for GET parameters

This will get ALL parameters from the request. For Debugging purposes only:

@RequestMapping (value = "/promote", method = {RequestMethod.POST, RequestMethod.GET})
public ModelAndView renderPromotePage (HttpServletRequest request) {
    Map<String, String[]> parameters = request.getParameterMap();

    for(String key : parameters.keySet()) {
        System.out.println(key);
        String[] vals = parameters.get(key);
        for(String val : vals)
            System.out.println(" -> " + val);
    }

    ModelAndView mv = new ModelAndView();
    mv.setViewName("test");
    return mv;
}

UnicodeEncodeError: 'charmap' codec can't encode characters

if you are using windows try to pass encoding='latin1', encoding='iso-8859-1' or encoding='cp1252' example:

csv_data = pd.read_csv(csvpath,encoding='iso-8859-1')
print(print(soup.encode('iso-8859-1')))

WHERE vs HAVING

Having is only used with aggregation but where with non aggregation statements If you have where word put it before aggregation (group by)

Passing event and argument to v-on in Vue.js

You can also do something like this...

<input @input="myHandler('foo', 'bar', ...arguments)">

Evan You himself recommended this technique in one post on Vue forum. In general some events may emit more than one argument. Also as documentation states internal variable $event is meant for passing original DOM event.

What is the .idea folder?

It contains your local IntelliJ IDE configs. I recommend adding this folder to your .gitignore file:

# intellij configs
.idea/

This application has no explicit mapping for /error

Main class need to be outside of your app packages tree structure. For example: example

Eclipse 3.5 Unable to install plugins

Its the Windows OS that make the problem. I got the same problem. Then I tried some other app which use JavaVM to connect the internet, and they fails. Try update JRE, you will notice it. If JRE cannot update itself, then there is some socket inaccessibility that prevent internet access apart from using native windows API. I reinstall Win7 and it fixed the problem.

How do I create test and train samples from one dataframe with pandas?

To split into more than two classes such as train, test, and validation, one can do:

probs = np.random.rand(len(df))
training_mask = probs < 0.7
test_mask = (probs>=0.7) & (probs < 0.85)
validatoin_mask = probs >= 0.85


df_training = df[training_mask]
df_test = df[test_mask]
df_validation = df[validatoin_mask]

This will put approximately 70% of data in training, 15% in test, and 15% in validation.

Normal arguments vs. keyword arguments

Positional Arguments

They have no keywords before them. The order is important!

func(1,2,3, "foo")

Keyword Arguments

They have keywords in the front. They can be in any order!

func(foo="bar", baz=5, hello=123)

func(baz=5, foo="bar", hello=123)

You should also know that if you use default arguments and neglect to insert the keywords, then the order will then matter!

def func(foo=1, baz=2, hello=3): ...
func("bar", 5, 123)

How to locate the git config file in Mac

The solution to the problem is:

  1. Find the .gitconfig file

  2. [user] name = 1wQasdTeedFrsweXcs234saS56Scxs5423 email = [email protected] [credential] helper = osxkeychain [url ""] insteadOf = git:// [url "https://"] [url "https://"] insteadOf = git://

there would be a blank url="" replace it with url="https://"

[user]
    name = 1wQasdTeedFrsweXcs234saS56Scxs5423
    email = [email protected]
[credential]
    helper = osxkeychain
[url "https://"]
    insteadOf = git://
[url "https://"]
[url "https://"]
    insteadOf = git://

This will work :)

Happy Bower-ing

How to use SVN, Branch? Tag? Trunk?

For committing, I use the following strategies:

  • commit as often as possible.

  • Each feature change/bugfix should get its own commit (don't commit many files at once since that will make the history for that file unclear -- e.g. If I change a logging module and a GUI module independently and I commit both at once, both changes will be visible in both file histories. This makes reading a file history difficult),

  • don't break the build on any commit -- it should be possible to retrieve any version of the repository and build it.

All files that are necessary for building and running the app should be in SVN. Test files and such should not, unless they are part of the unit tests.

Dynamically Fill Jenkins Choice Parameter With Git Branches In a Specified Repo

I am facing a similar problem here. Our users are migrating their jobs from freestyle to pipeline. They do not want Jenkinsfile stored in their repos(historical reason) and still want to use "Git Parameter" plugin

So we have to use use "Pipeline script" and develop a different plugin which works like "Git Parameter".

This new plugin does not integrate with SCM setting in the project. The plugin is at https://plugins.jenkins.io/list-git-branches-parameter

Hope it helps you as well

JAVA How to remove trailing zeros from a double

Use DecimalFormat

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

How to convert integer to string in C?

Use sprintf():

int someInt = 368;
char str[12];
sprintf(str, "%d", someInt);

All numbers that are representable by int will fit in a 12-char-array without overflow, unless your compiler is somehow using more than 32-bits for int. When using numbers with greater bitsize, e.g. long with most 64-bit compilers, you need to increase the array size—at least 21 characters for 64-bit types.

Post parameter is always null

I know the OP was originally sending a single string, but for future reference, it is also worth noting that malformed JSON will also arrive as null into the post method. In my case, a missing comma between two properties caused what was otherwise fine, to break.

Move branch pointer to different commit without checkout

You can also pass git reset --hard a commit reference.

For example:

git checkout branch-name
git reset --hard new-tip-commit

I find I do something like this semi-frequently:

Assuming this history

$ git log --decorate --oneline --graph
* 3daed46 (HEAD, master) New thing I shouldn't have committed to master
* a0d9687 This is the commit that I actually want to be master

# Backup my latest commit to a wip branch
$ git branch wip_doing_stuff

# Ditch that commit on this branch
$ git reset --hard HEAD^

# Now my changes are in a new branch
$ git log --decorate --oneline --graph
* 3daed46 (wip_doing_stuff) New thing I shouldn't have committed to master
* a0d9687 (HEAD, master) This is the commit that I actually want to be master

What does OpenCV's cvWaitKey( ) function do?

cvWaitKey(0) stops your program until you press a button.

cvWaitKey(10) doesn't stop your program but wake up and alert to end your program when you press a button. Its used into loops because cvWaitkey doesn't stop loop.

Normal use

char k;

k=cvWaitKey(0);

if(k == 'ESC')

with k you can see what key was pressed.

How to create a String with carriage returns?

Do this: Step 1: Your String

String str = ";;;;;;\n" +
            "Name, number, address;;;;;;\n" + 
             "01.01.12-16.02.12;;;;;;\n" + 
             ";;;;;;\n" + 
             ";;;;;;";

Step 2: Just replace all "\n" with "%n" the result looks like this

String str = ";;;;;;%n" +
             "Name, number, address;;;;;;%n" + 
             "01.01.12-16.02.12;;;;;;%n" + 
            ";;;;;;%n" + 
            ";;;;;;";

Notice I've just put "%n" in place of "\n"

Step 3: Now simply call format()

str=String.format(str);

That's all you have to do.

PHP equivalent of .NET/Java's toString()

You can use the casting operators:

$myText = (string)$myVar;

There are more details for string casting and conversion in the Strings section of the PHP manual, including special handling for booleans and nulls.

How to listen for 'props' changes

I use props and variables computed properties if I need create logic after to receive the changes

export default {
name: 'getObjectDetail',
filters: {},
components: {},
props: {
    objectDetail: {
      type: Object,
      required: true
    }
},
computed: {
    _objectDetail: {
        let value = false
        ...

        if (someValidation)
        ...
    }
}

Activate a virtualenv with a Python script

For python2/3, Using below code snippet we can activate virtual env.

activate_this = "/home/<--path-->/<--virtual env name -->/bin/activate_this.py" #for ubuntu
activate_this = "D:\<-- path -->\<--virtual env name -->\Scripts\\activate_this.py" #for windows
with open(activate_this) as f:
    code = compile(f.read(), activate_this, 'exec')
    exec(code, dict(__file__=activate_this))

SASS and @font-face

For those looking for an SCSS mixin instead, including woff2:

@mixin fface($path, $family, $type: '', $weight: 400, $svg: '', $style: normal) {
  @font-face {
    font-family: $family;
    @if $svg == '' {
      // with OTF without SVG and EOT
      src: url('#{$path}#{$type}.otf') format('opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype');
    } @else {
      // traditional src inclusions
      src: url('#{$path}#{$type}.eot');
      src: url('#{$path}#{$type}.eot?#iefix') format('embedded-opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype'), url('#{$path}#{$type}.svg##{$svg}') format('svg');
    }
    font-weight: $weight;
    font-style: $style;
  }
}
// ========================================================importing
$dir: '/assets/fonts/';
$famatic: 'AmaticSC';
@include fface('#{$dir}amatic-sc-v11-latin-regular', $famatic, '', 400, $famatic);

$finter: 'Inter';
// adding specific types of font-weights
@include fface('#{$dir}#{$finter}', $finter, '-Thin-BETA', 100);
@include fface('#{$dir}#{$finter}', $finter, '-Regular', 400);
@include fface('#{$dir}#{$finter}', $finter, '-Medium', 500);
@include fface('#{$dir}#{$finter}', $finter, '-Bold', 700);
// ========================================================usage
.title {
  font-family: Inter;
  font-weight: 700; // Inter-Bold font is loaded
}
.special-title {
  font-family: AmaticSC;
  font-weight: 700; // default font is loaded
}

The $type parameter is useful for stacking related families with different weights.

The @if is due to the need of supporting the Inter font (similar to Roboto), which has OTF but doesn't have SVG and EOT types at this time.

If you get a can't resolve error, remember to double check your fonts directory ($dir).

Passing capturing lambda as function pointer

A simular answer but i made it so you don't have to specify the type of returned pointer (note that the generic version requires C++20):

#include <iostream>


template<typename Function>
struct function_traits;

template <typename Ret, typename... Args>
struct function_traits<Ret(Args...)> {
    typedef Ret(*ptr)(Args...);
};

template <typename Ret, typename... Args>
struct function_traits<Ret(*const)(Args...)> : function_traits<Ret(Args...)> {};

template <typename Cls, typename Ret, typename... Args>
struct function_traits<Ret(Cls::*)(Args...) const> : function_traits<Ret(Args...)> {};

using voidfun = void(*)();

template <typename F>
voidfun lambda_to_void_function(F lambda) {
    static auto lambda_copy = lambda;

    return []() {
        lambda_copy();
    };
}

// requires C++20
template <typename F>
auto lambda_to_pointer(F lambda) -> typename function_traits<decltype(&F::operator())>::ptr {
    static auto lambda_copy = lambda;
    
    return []<typename... Args>(Args... args) {
        return lambda_copy(args...);
    };
}



int main() {
    int num;

    void(*foo)() = lambda_to_void_function([&num]() {
        num = 1234;
    });
    foo();
    std::cout << num << std::endl; // 1234

    int(*bar)(int) = lambda_to_pointer([&](int a) -> int {
        num = a;
        return a;
    });
    std::cout << bar(4321) << std::endl; // 4321
    std::cout << num << std::endl; // 4321
}

Visual Studio opens the default browser instead of Internet Explorer

In the Solution Explorer, right-click any ASPX page and select "Browse With" and select IE as the default.

Note... the same steps can be used to add Google Chrome as a browser option and to optionally set it as the default browser.

Error Code 1292 - Truncated incorrect DOUBLE value - Mysql

Had this issue with ES6 and TypeORM while trying to pass .where("order.id IN (:orders)", { orders }), where orders was a comma separated string of numbers. When I converted to a template literal, the problem was resolved.

.where(`order.id IN (${orders})`);

jQuery Screen Resolution Height Adjustment

To get screen resolution in JS use screen object

screen.height;
screen.width;

Based on that values you can calculate your margin to whatever suits you.

Converting a datetime string to timestamp in Javascript

Date.parse() isn't a constructor, its a static method.

So, just use

var timeInMillis = Date.parse(s);

instead of

var timeInMillis = new Date.parse(s);

Angularjs - ng-cloak/ng-show elements blink

you'd better reference angular document, becuase the version[1.4.9] has update to below that make it could support data-ng-cloak directive.

[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  display: none !important;
}

Install mysql-python (Windows)

For folks using Python 3.0+ (which should be everyone now):

Unfortunately, MySQL-Python 1.2.5 does not support Python 3.0+ yet (which is kinda unreasonable IMHO, Python 3+ has been out for a while). Reference : https://pypi.python.org/pypi/MySQL-python/1.2.5

So, my workaround is to use Oracle's MySQL connector. In settings.py, change DATABASE's 'ENGINE' field to: 'ENGINE': 'mysql.connector.django',

More info could be found in the last paragraph of the first answer to this question: Setting Django up to use MySQL

Hope this helps!!

What does "Git push non-fast-forward updates were rejected" mean?

you might want to use force with push operation in this case

git push origin master --force

jQuery SVG, why can't I addClass?

Based on above answers I created the following API

/*
 * .addClassSVG(className)
 * Adds the specified class(es) to each of the set of matched SVG elements.
 */
$.fn.addClassSVG = function(className){
    $(this).attr('class', function(index, existingClassNames) {
        return ((existingClassNames !== undefined) ? (existingClassNames + ' ') : '') + className;
    });
    return this;
};

/*
 * .removeClassSVG(className)
 * Removes the specified class to each of the set of matched SVG elements.
 */
$.fn.removeClassSVG = function(className){
    $(this).attr('class', function(index, existingClassNames) {
        var re = new RegExp('\\b' + className + '\\b', 'g');
        return existingClassNames.replace(re, '');
    });
    return this;
};

A method to reverse effect of java String.split()?

I got the following example here

/*
7) Join Strings using separator >>>AB$#$CD$#$EF

 */

import org.apache.commons.lang.StringUtils;

public class StringUtilsTrial {
  public static void main(String[] args) {

    // Join all Strings in the Array into a Single String, separated by $#$
    System.out.println("7) Join Strings using separator >>>"
        + StringUtils.join(new String[] { "AB", "CD", "EF" }, "$#$"));
  }
}

Change value of input onchange?

for jQuery we can use below:

by input name:

$('input[name="textboxname"]').val('some value');

by input class:

$('input[type=text].textboxclass').val('some value');

by input id:

$('#textboxid').val('some value');

Convert pandas data frame to series

data = pd.DataFrame({"a":[1,2,3,34],"b":[5,6,7,8]})
new_data = pd.melt(data)
new_data.set_index("variable", inplace=True)

This gives a dataframe with index as column name of data and all data are present in "values" column

How to animate CSS Translate

There are jQuery-plugins that help you achieve this like: http://ricostacruz.com/jquery.transit/

Object spread vs. Object.assign

Other answers are old, could not get a good answer.
Below example is for object literals, helps how both can complement each other, and how it cannot complement each other (therefore difference):

var obj1 = { a: 1,  b: { b1: 1, b2: 'b2value', b3: 'b3value' } };

// overwrite parts of b key
var obj2 = {
      b: {
        ...obj1.b,
        b1: 2
      }
};
var res2 = Object.assign({}, obj1, obj2); // b2,b3 keys still exist
document.write('res2: ', JSON.stringify (res2), '<br>');
// Output:
// res2: {"a":1,"b":{"b1":2,"b2":"b2value","b3":"b3value"}}  // NOTE: b2,b3 still exists

// overwrite whole of b key
var obj3 = {
      b: {
        b1: 2
      }
};
var res3 = Object.assign({}, obj1, obj3); // b2,b3 keys are lost
document.write('res3: ', JSON.stringify (res3), '<br>');
// Output:
  // res3: {"a":1,"b":{"b1":2}}  // NOTE: b2,b3 values are lost

Several more small examples here, also for array & object:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

How do you remove all the options of a select box and then add one option and select it with jQuery?

$('#mySelect')
    .empty()
    .append('<option value="whatever">text</option>')
    .find('option:first')
    .attr("selected","selected")
;

PHP namespaces and "use"

The use operator is for giving aliases to names of classes, interfaces or other namespaces. Most use statements refer to a namespace or class that you'd like to shorten:

use My\Full\Namespace;

is equivalent to:

use My\Full\Namespace as Namespace;
// Namespace\Foo is now shorthand for My\Full\Namespace\Foo

If the use operator is used with a class or interface name, it has the following uses:

// after this, "new DifferentName();" would instantiate a My\Full\Classname
use My\Full\Classname as DifferentName;

// global class - making "new ArrayObject()" and "new \ArrayObject()" equivalent
use ArrayObject;

The use operator is not to be confused with autoloading. A class is autoloaded (negating the need for include) by registering an autoloader (e.g. with spl_autoload_register). You might want to read PSR-4 to see a suitable autoloader implementation.

File Upload without Form

All answers here are still using the FormData API. It is like a "multipart/form-data" upload without a form. You can also upload the file directly as content inside the body of the POST request using xmlHttpRequest like this:

var xmlHttpRequest = new XMLHttpRequest();

var file = ...file handle...
var fileName = ...file name...
var target = ...target...
var mimeType = ...mime type...

xmlHttpRequest.open('POST', target, true);
xmlHttpRequest.setRequestHeader('Content-Type', mimeType);
xmlHttpRequest.setRequestHeader('Content-Disposition', 'attachment; filename="' + fileName + '"');
xmlHttpRequest.send(file);

Content-Type and Content-Disposition headers are used for explaining what we are sending (mime-type and file name).

I posted similar answer also here.

Pull all images from a specified directory and then display them

You can display all image from a folder using simple php script. Suppose folder name “images” and put some image in this folder and then use any text editor and paste this code and run this script. This is php code

    <?php
     $files = glob("images/*.*");
     for ($i=0; $i<count($files); $i++)
      {
        $image = $files[$i];
        $supported_file = array(
                'gif',
                'jpg',
                'jpeg',
                'png'
         );

         $ext = strtolower(pathinfo($image, PATHINFO_EXTENSION));
         if (in_array($ext, $supported_file)) {
            echo basename($image)."<br />"; // show only image name if you want to show full path then use this code // echo $image."<br />";
             echo '<img src="'.$image .'" alt="Random image" />'."<br /><br />";
            } else {
                continue;
            }
          }
       ?>

if you do not check image type then use this code

<?php
$files = glob("images/*.*");
for ($i = 0; $i < count($files); $i++) {
    $image = $files[$i];
    echo basename($image) . "<br />"; // show only image name if you want to show full path then use this code // echo $image."<br />";
    echo '<img src="' . $image . '" alt="Random image" />' . "<br /><br />";

}
?>

How to make g++ search for header files in a specific directory?

Headers included with #include <> will be searched in all default directories , but you can also add your own location in the search path with -I command line arg.

I saw your edit you could install your headers in default locations usually

 /usr/local/include
 libdir/gcc/target/version/include
 /usr/target/include
 /usr/include

Confirm with compiler docs though.

Error: "Could Not Find Installable ISAM"

Have you checked this http://support.microsoft.com/kb/209805? In particular, whether you have Msrd3x40.dll.

You may also like to check that you have the latest version of Jet: http://support.microsoft.com/kb/239114

How does strcmp() work?

This, from the masters themselves (K&R, 2nd ed., pg. 106):

// strcmp: return < 0 if s < t, 0 if s == t, > 0 if s > t
int strcmp(char *s, char *t) 
{
    int i;

    for (i = 0; s[i] == t[i]; i++)
        if (s[i] == '\0')
            return 0;
    return s[i] - t[i];
}

Can I get a patch-compatible output from git-diff?

A useful trick to avoid creating temporary patch files:

git diff | patch -p1 -d [dst-dir]

IF EXISTS, THEN SELECT ELSE INSERT AND THEN SELECT

create schema tableName authorization dbo
go
IF OBJECT_ID ('tableName.put_fieldValue', 'P' ) IS NOT NULL 
drop proc tableName.put_fieldValue
go
create proc tableName.put_fieldValue(@fieldValue int) as
declare @tableid int = 0
select @tableid = tableid from table where fieldValue=''
if @tableid = 0 begin
   insert into table(fieldValue) values('')
   select @tableid = scope_identity()
end
return @tableid
go
declare @tablid int = 0
exec @tableid = tableName.put_fieldValue('')

Why use armeabi-v7a code over armeabi code?

Instead of having a fat APK file, I would like to use just the armeabi files and remove the armeabi-v7a folder.

The opposite is a much better strategy. If you have minSdkVersion to 14 and upload your apk to the play store, you'll notice you'll support the same number of devices whether you support armeabi or not. Therefore, there are no devices with Android 4 or higher which would benefit from armeabi at all.

This is probably why the Android NDK doesn't even support armeabi anymore as per revision r17b. [source]

Setting public class variables

If you are going to follow the examples given (using getter/setter or setting it in the constructor) change it to private since those are ways to control what is set in the variable.

It doesn't make sense to keep the property public with all those things added to the class.

Can I make a <button> not submit a form?

Just use good old HTML:

<input type="button" value="Submit" />

Wrap it as the subject of a link, if you so desire:

<a href="http://somewhere.com"><input type="button" value="Submit" /></a>

Or if you decide you want javascript to provide some other functionality:

<input type="button" value="Cancel" onclick="javascript: someFunctionThatCouldIncludeRedirect();"/>

How to find the size of a table in SQL?

SQL Server provides a built-in stored procedure that you can run to easily show the size of a table, including the size of the indexes… which might surprise you.

Syntax:

 sp_spaceused 'Tablename'

see in :

http://www.howtogeek.com/howto/database/determine-size-of-a-table-in-sql-server/

Select query with date condition

Be careful, you're unwittingly asking "where the date is greater than one divided by nine, divided by two thousand and eight".

Put # signs around the date, like this #1/09/2008#

Error 405 (Method Not Allowed) Laravel 5

The methodNotAllowed exception indicates that a route doesn't exist for the HTTP method you are requesting.

Your form is set up to make a DELETE request, so your route needs to use Route::delete() to receive this.

Route::delete('empresas/eliminar/{id}', [
        'as' => 'companiesDelete',
        'uses' => 'CompaniesController@delete'
]);

Convert all first letter to upper case, rest lower for each word

string s = "THIS IS MY TEXT RIGHT NOW";

s = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());

Is it possible to center text in select box?

this worked for me:

text-align: center;
text-align-last: center;

How to catch a unique constraint error in a PL/SQL block?

I suspect the condition you are looking for is DUP_VAL_ON_INDEX

EXCEPTION
    WHEN DUP_VAL_ON_INDEX THEN
        DBMS_OUTPUT.PUT_LINE('OH DEAR. I THINK IT IS TIME TO PANIC!')

Can the :not() pseudo-class have multiple arguments?

If you're using SASS in your project, I've built this mixin to make it work the way we all want it to:

@mixin not($ignorList...) {
    //if only a single value given
    @if (length($ignorList) == 1){
        //it is probably a list variable so set ignore list to the variable
        $ignorList: nth($ignorList,1);
    }
    //set up an empty $notOutput variable
    $notOutput: '';
    //for each item in the list
    @each $not in $ignorList {
        //generate a :not([ignored_item]) segment for each item in the ignore list and put them back to back
        $notOutput: $notOutput + ':not(#{$not})';
    }
    //output the full :not() rule including all ignored items
    &#{$notOutput} {
        @content;
    }
}

it can be used in 2 ways:

Option 1: list the ignored items inline

input {
  /*non-ignored styling goes here*/
  @include not('[type="radio"]','[type="checkbox"]'){
    /*ignored styling goes here*/
  }
}

Option 2: list the ignored items in a variable first

$ignoredItems:
  '[type="radio"]',
  '[type="checkbox"]'
;

input {
  /*non-ignored styling goes here*/
  @include not($ignoredItems){
    /*ignored styling goes here*/
  }
}

Outputted CSS for either option

input {
    /*non-ignored styling goes here*/
}

input:not([type="radio"]):not([type="checkbox"]) {
    /*ignored styling goes here*/
}

What exactly does an #if 0 ..... #endif block do?

Not only does it not get executed, it doesn't even get compiled.

#if is a preprocessor command, which gets evaluated before the actual compilation step. The code inside that block doesn't appear in the compiled binary.

It's often used for temporarily removing segments of code with the intention of turning them back on later.

Bootstrap button - remove outline on Chrome OS X

That CSS goes from this file "tab-focus.less" in mixins folder (it could be difficult to find, because mixins are not shown at chrome dev-tools). So you should edit this:

// WebKit-style focus 

.tab-focus() {
      // Default
      outline: thin dotted;
      // WebKit
      outline: 5px auto -webkit-focus-ring-color;
      outline-offset: -2px;
    }

dropping infinite values from dataframes in pandas?

Use (fast and simple):

df = df[np.isfinite(df).all(1)]

This answer is based on DougR's answer in an other question. Here an example code:

import pandas as pd
import numpy as np
df=pd.DataFrame([1,2,3,np.nan,4,np.inf,5,-np.inf,6])
print('Input:\n',df,sep='')
df = df[np.isfinite(df).all(1)]
print('\nDropped:\n',df,sep='')

Result:

Input:
    0
0  1.0000
1  2.0000
2  3.0000
3     NaN
4  4.0000
5     inf
6  5.0000
7    -inf
8  6.0000

Dropped:
     0
0  1.0
1  2.0
2  3.0
4  4.0
6  5.0
8  6.0

Can I find events bound on an element with jQuery?

I'm adding this for posterity; There's an easier way that doesn't involve writing more JS. Using the amazing firebug addon for firefox,

  1. Right click on the element and select 'Inspect element with Firebug'
  2. In the sidebar panels (shown in the screenshot), navigate to the events tab using the tiny > arrow
  3. The events tab shows the events and corresponding functions for each event
  4. The text next to it shows the function location

enter image description here

How to convert decimal to hexadecimal in JavaScript

Arbitrary precision

This solution take on input decimal string, and return hex string. A decimal fractions are supported. Algorithm

  • split number to sign (s), integer part (i) and fractional part (f) e.g for -123.75 we have s=true, i=123, f=75
  • integer part to hex:
    • if i='0' stop
    • get modulo: m=i%16 (in arbitrary precision)
    • convert m to hex digit and put to result string
    • for next step calc integer part i=i/16 (in arbitrary precision)
  • fractional part
    • count fractional digits n
    • multiply k=f*16 (in arbitrary precision)
    • split k to right part with n digits and put them to f, and left part with rest of digits and put them to d
    • convert d to hex and add to result.
    • finish when number of result fractional digits is enough

_x000D_
_x000D_
// @param decStr - string with non-negative integer
// @param divisor - positive integer
function dec2HexArbitrary(decStr, fracDigits=0) {   
    // Helper: divide arbitrary precision number by js number
    // @param decStr - string with non-negative integer
    // @param divisor - positive integer
    function arbDivision(decStr, divisor) 
    { 
        // algorithm https://www.geeksforgeeks.org/divide-large-number-represented-string/
        let ans=''; 
        let idx = 0; 
        let temp = +decStr[idx]; 
        while (temp < divisor) temp = temp * 10 + +decStr[++idx]; 

        while (decStr.length > idx) { 
            ans += (temp / divisor)|0 ; 
            temp = (temp % divisor) * 10 + +decStr[++idx]; 
        } 

        if (ans.length == 0) return "0"; 

        return ans; 
    } 

    // Helper: calc module of arbitrary precision number
    // @param decStr - string with non-negative integer
    // @param mod - positive integer
    function arbMod(decStr, mod) { 
      // algorithm https://www.geeksforgeeks.org/how-to-compute-mod-of-a-big-number/
      let res = 0; 

      for (let i = 0; i < decStr.length; i++) 
        res = (res * 10 + +decStr[i]) % mod; 

      return res; 
    } 

    // Helper: multiply arbitrary precision integer by js number
    // @param decStr - string with non-negative integer
    // @param mult - positive integer
    function arbMultiply(decStr, mult) {
      let r='';
      let m=0;
      for (let i = decStr.length-1; i >=0 ; i--) {
        let n = m+mult*(+decStr[i]);
        r= (i ? n%10 : n) + r 
        m= n/10|0;
      }
      return r;
    }
    
    
    // dec2hex algorithm starts here
    
    let h= '0123456789abcdef';                                         // hex 'alphabet'
    let m= decStr.match(/-?(.*?)\.(.*)?/) || decStr.match(/-?(.*)/);   // separate sign,integer,ractional
    let i= m[1].replace(/^0+/,'').replace(/^$/,'0');                   // integer part (without sign and leading zeros)
    let f= (m[2]||'0').replace(/0+$/,'').replace(/^$/,'0');            // fractional part (without last zeros)
    let s= decStr[0]=='-';                                                                             // sign

    let r='';                                                                                                          // result
    
    if(i=='0') r='0';
        
    while(i!='0') {                                                    // integer part
      r=h[arbMod(i,16)]+r; 
      i=arbDivision(i,16);
    }
            
    if(fracDigits) r+=".";
        
    let n = f.length;
    
    for(let j=0; j<fracDigits; j++) {                                  // frac part
      let k= arbMultiply(f,16);
      f = k.slice(-n);
      let d= k.slice(0,k.length-n); 
      r+= d.length ? h[+d] : '0';
    }
            
    return (s?'-':'')+r;
}








// -----------
// TESTS
// -----------



let tests = [
  ["0",2],
  ["000",2],  
  ["123",0],
  ["-123",0],  
  ["00.000",2],
  
  ["255.75",5],
  ["-255.75",5], 
  ["127.999",32], 
];

console.log('Input      Standard          Abitrary');
tests.forEach(t=> {
  let nonArb = (+t[0]).toString(16).padEnd(17,' ');
  let arb = dec2HexArbitrary(t[0],t[1]);
  console.log(t[0].padEnd(10,' '), nonArb, arb); 
});


// Long Example (40 digits after dot)
let example = "123456789012345678901234567890.09876543210987654321"
console.log(`\nLong Example:`);
console.log('dec:',example);
console.log('hex:     ',dec2HexArbitrary(example,40));
_x000D_
_x000D_
_x000D_

Make $JAVA_HOME easily changable in Ubuntu

You need to put variable definition in the ~/.bashrc file.

From bash man page:

When an interactive shell that is not a login shell is started, bash reads and executes commands from /etc/bash.bashrc and ~/.bashrc, if these files exist.

AngularJS: How to set a variable inside of a template?

Use ngInit: https://docs.angularjs.org/api/ng/directive/ngInit

<div ng-repeat="day in forecast_days" ng-init="f = forecast[day.iso]">
  {{$index}} - {{day.iso}} - {{day.name}}
  Temperature: {{f.temperature}}<br>
  Humidity: {{f.humidity}}<br>
  ...
</div>

Example: http://jsfiddle.net/coma/UV4qF/

What does the @Valid annotation indicate in Spring?

I wanted to add more details about how the @Valid works, especially in spring.

Everything you'd want to know about validation in spring is explained clearly and in detail in https://reflectoring.io/bean-validation-with-spring-boot/, but I'll copy the answer to how @Valid works incase the link goes down.

The @Valid annotation can be added to variables in a rest controller method to validate them. There are 3 types of variables that can be validated:

  • the request body,
  • variables within the path (e.g. id in /foos/{id}) and,
  • query parameters.

So now... how does spring "validate"? You can define constraints to the fields of a class by annotating them with certain annotations. Then, you pass an object of that class into a Validator which checks if the constraints are satisfied.

For example, suppose I had controller method like this:

@RestController
class ValidateRequestBodyController {

  @PostMapping("/validateBody")
  ResponseEntity<String> validateBody(@Valid @RequestBody Input input) {
    return ResponseEntity.ok("valid");
  }

}

So this is a POST request which takes in a response body, and we're mapping that response body to a class Input.

Here's the class Input:

class Input {

  @Min(1)
  @Max(10)
  private int numberBetweenOneAndTen;

  @Pattern(regexp = "^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$")
  private String ipAddress;
  
  // ...
}

The @Valid annotation will tell spring to go and validate the data passed into the controller by checking to see that the integer numberBetweenOneAndTen is between 1 and 10 inclusive because of those min and max annotations. It'll also check to make sure the ip address passed in matches the regular expression in the annotation.

side note: the regular expression isn't perfect.. you could pass in 3 digit numbers that are greater than 255 and it would still match the regular expression.


Here's an example of validating a query variable and path variable:

@RestController
@Validated
class ValidateParametersController {

  @GetMapping("/validatePathVariable/{id}")
  ResponseEntity<String> validatePathVariable(
      @PathVariable("id") @Min(5) int id) {
    return ResponseEntity.ok("valid");
  }
  
  @GetMapping("/validateRequestParameter")
  ResponseEntity<String> validateRequestParameter(
      @RequestParam("param") @Min(5) int param) { 
    return ResponseEntity.ok("valid");
  }
}

In this case, since the query variable and path variable are just integers instead of just complex classes, we put the constraint annotation @Min(5) right on the parameter instead of using @Valid.

Remove all special characters with RegExp

var desired = stringToReplace.replace(/[^\w\s]/gi, '')

As was mentioned in the comments it's easier to do this as a whitelist - replace the characters which aren't in your safelist.

The caret (^) character is the negation of the set [...], gi say global and case-insensitive (the latter is a bit redundant but I wanted to mention it) and the safelist in this example is digits, word characters, underscores (\w) and whitespace (\s).

SQL Server equivalent of MySQL's NOW()?

You can also use CURRENT_TIMESTAMP, if you feel like being more ANSI compliant (though if you're porting code between database vendors, that'll be the least of your worries). It's exactly the same as GetDate() under the covers (see this question for more on that).

There's no ANSI equivalent for GetUTCDate(), however, which is probably the one you should be using if your app operates in more than a single time zone ...

PHP Session data not being saved

Use phpinfo() and check the session.* settings.

Maybe the information is stored in cookies and your browser does not accept cookies, something like that.

Check that first and come back with the results.

You can also do a print_r($_SESSION); to have a dump of this variable and see the content....

Regarding your phpinfo(), is the session.save_path a valid one? Does your web server have write access to this directory?

Hope this helps.

git push: permission denied (public key)

I just had to deal with this issue. @user3445140's answer helped me, but was much more than I needed to do.

  1. Get your public SSH key with cat ~/.ssh/id_rsa.pub
  2. Copy the key, including the "ssh-rsa" but excluding your computer name at the end
  3. Go to https://github.com/settings/ssh
  4. Add your SSH key

How can I add to a List's first position?

 myList.Insert(0, item);

         

Move div to new line

I've found that you can move div elements to the next line simply by setting the property Display: block;

On each div.

How can I retrieve Id of inserted entity using Entity framework?

Repository.addorupdate(entity, entity.id);
Repository.savechanges();
Var id = entity.id;

This will work.

How can I make a button have a rounded border in Swift?

It is globally method for rounded border of UIButton

class func setRoundedBorderButton(btn:UIButton)
{
   btn.layer.cornerRadius = btn.frame.size.height/2
   btn.layer.borderWidth = 0.5
   btn.layer.borderColor = UIColor.darkGray.cgColor
}

CSS hide scroll bar if not needed

.selected-elementClass{
    overflow-y:auto;
}

Merge Two Lists in R

merged = map(names(first), ~c(first[[.x]], second[[.x]])
merged = set_names(merged, names(first))

Using purrr. Also solves the problem of your lists not being in order.

How to pad a string with leading zeros in Python 3

Make use of the zfill() helper method to left-pad any string, integer or float with zeros; it's valid for both Python 2.x and Python 3.x.

Sample usage:

print str(1).zfill(3);
# Expected output: 001

Description:

When applied to a value, zfill() returns a value left-padded with zeros when the length of the initial string value less than that of the applied width value, otherwise, the initial string value as is.

Syntax:

str(string).zfill(width)
# Where string represents a string, an integer or a float, and
# width, the desired length to left-pad.

Android get Current UTC time

System.currentTimeMillis() does give you the number of milliseconds since January 1, 1970 00:00:00 UTC. The reason you see local times might be because you convert a Date instance to a string before using it. You can use DateFormats to convert Dates to Strings in any timezone:

DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
String gmtTime = df.format(new Date());

Also see this related question.

JavaScript ES6 promise for loop

If you are limited to ES6, the best option is Promise all. Promise.all(array) also returns an array of promises after successfully executing all the promises in array argument. Suppose, if you want to update many student records in the database, the following code demonstrates the concept of Promise.all in such case-

let promises = students.map((student, index) => {
//where students is a db object
student.rollNo = index + 1;
student.city = 'City Name';
//Update whatever information on student you want
return student.save();
});
Promise.all(promises).then(() => {
  //All the save queries will be executed when .then is executed
  //You can do further operations here after as all update operations are completed now
});

Map is just an example method for loop. You can also use for or forin or forEach loop. So the concept is pretty simple, start the loop in which you want to do bulk async operations. Push every such async operation statement in an array declared outside the scope of that loop. After the loop completes, execute the Promise all statement with the prepared array of such queries/promises as argument.

The basic concept is that the javascript loop is synchronous whereas database call is async and we use push method in loop that is also sync. So, the problem of asynchronous behavior doesn't occur inside the loop.