Programs & Examples On #Quicksand

jQuery Quicksand is a jQuery plugin to reorder and filter items with a nice shuffling animation.

How to get the data-id attribute?

If we want to retrieve or update these attributes using existing, native JavaScript, then we can do so using the getAttribute and setAttribute methods as shown below:

Through JavaScript

<div id='strawberry-plant' data-fruit='12'></div>

<script>
// 'Getting' data-attributes using getAttribute
var plant = document.getElementById('strawberry-plant');
var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'

// 'Setting' data-attributes using setAttribute
plant.setAttribute('data-fruit','7'); // Pesky birds
</script>

Through jQuery

// Fetching data
var fruitCount = $(this).data('fruit');
OR 
// If you updated the value, you will need to use below code to fetch new value 
// otherwise above gives the old value which is intially set.
// And also above does not work in ***Firefox***, so use below code to fetch value
var fruitCount = $(this).attr('data-fruit');

// Assigning data
$(this).attr('data-fruit','7');

Read this documentation

I want to show all tables that have specified column name

SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name,*
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID 
WHERE c.name LIKE '%YOUR_COLUMN%' 
ORDER BY schema_name, table_name;

In depth article by SQL Authority

Java for loop syntax: "for (T obj : objects)"

yes... This is for each loop in java.

Generally this loop is become useful when you are retrieving data or object from the database.

Syntex :

for(Object obj : Collection obj)
{
     //Code enter code here
}

Example :

for(User user : userList)
{
     System.out.println("USer NAme :" + user.name);
   // etc etc
}

This is for each loop.

it will incremental by automatically. one by one from collection to USer object data has been filled. and working.

How to display a range input slider vertically

_x000D_
_x000D_
window.onload = function(){
var slider = document.getElementById("sss");
 var  result = document.getElementById("final");
slider.oninput = function(){
    result.innerHTML = slider.value ;
}
}
_x000D_
.slider{
    width: 100vw;
    height: 100vh;
   
    display: flex;
    justify-content: center;
    align-items: center;
}

.slider .container-slider{
    width: 600px;
    display: flex;
    justify-content: center;
    align-items: center;
    transform: rotate(90deg)
}

.slider .container-slider input[type="range"]{
    width: 60%;
    -webkit-appearance: none;
    background-color: blue;
    height: 7px;
    border-radius: 5px;;
    outline: none;
    margin: 0 20px
    
}

.slider .container-slider input[type="range"]::-webkit-slider-thumb{
    -webkit-appearance: none;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: red;
}



.slider .container-slider input[type="range"]::-webkit-slider-thumb:hover{

box-shadow: 0px 0px 10px rgba(255,255,255,.3),
            0px 0px 15px rgba(255,255,255,.4),
            0px 0px 20px rgba(255,255,255,.5),
            0px 0px 25px rgba(255,255,255,.6),
            0px 0px 30px rgba(255,255,255,.7)

}


.slider .container-slider .val {
    width: 60px;
    height: 40px;
    background-color: #ACB6E5;
    display: flex;
    justify-content: center;
    align-items: center;
    font-family: consolas;
    font-weight: 700;
    font-size: 20px;
    letter-spacing: 1.3px;
    transform: rotate(-90deg)
}

.slider .container-slider .val::before{
    content: "";
    position: absolute;
    width: 0;
    height: 0;
    display: block;
    border: 20px solid transparent;
    border-bottom-color: #ACB6E5;
    top: -30px;
}
_x000D_
<div class="slider">
  <div class="container-slider">
    <input type="range" min="0" max="100" step="1" value="" id="sss">
    <div class="val" id="final">0</div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

Powershell: A positional parameter cannot be found that accepts argument "xxx"

I had this issue after converting my Write-Host cmdlets to Write-Information and I was missing quotes and parens around the parameters. The cmdlet signatures are evidently not the same.

Write-Host this is a good idea $here
Write-Information this is a good idea $here <=BAD

This is the cmdlet signature that corrected after spending 20-30 minutes digging down the function stack...

Write-Information ("this is a good idea $here") <=GOOD

Can a java lambda have more than 1 parameter?

Some lambda function :

import org.junit.Test;
import java.awt.event.ActionListener;
import java.util.function.Function;

public class TestLambda {

@Test
public void testLambda() {

    System.out.println("test some lambda function");

    ////////////////////////////////////////////
    //1-any input | any output:
    //lambda define:
    Runnable lambda1 = () -> System.out.println("no parameter");
    //lambda execute:
    lambda1.run();


    ////////////////////////////////////////////
    //2-one input(as ActionEvent) | any output:
    //lambda define:
    ActionListener lambda2 = (p) -> System.out.println("One parameter as action");
    //lambda execute:
    lambda2.actionPerformed(null);


    ////////////////////////////////////////////
    //3-one input | by output(as Integer):
    //lambda define:
    Function<String, Integer> lambda3 = (p1) -> {
        System.out.println("one parameters: " + p1);
        return 10;
    };
    //lambda execute:
    lambda3.apply("test");


    ////////////////////////////////////////////
    //4-two input | any output
    //lambda define:
    TwoParameterFunctionWithoutReturn<String, Integer> lambda4 = (p1, p2) -> {
        System.out.println("two parameters: " + p1 + ", " + p2);
    };
    //lambda execute:
    lambda4.apply("param1", 10);


    ////////////////////////////////////////////
    //5-two input | by output(as Integer)
    //lambda define:
    TwoParameterFunctionByReturn<Integer, Integer> lambda5 = (p1, p2) -> {
        System.out.println("two parameters: " + p1 + ", " + p2);
        return p1 + p2;
    };
    //lambda execute:
    lambda5.apply(10, 20);


    ////////////////////////////////////////////
    //6-three input(Integer,Integer,String) | by output(as Integer)
    //lambda define:
    ThreeParameterFunctionByReturn<Integer, Integer, Integer> lambda6 = (p1, p2, p3) -> {
        System.out.println("three parameters: " + p1 + ", " + p2 + ", " + p3);
        return p1 + p2 + p3;
    };
    //lambda execute:
    lambda6.apply(10, 20, 30);

}


@FunctionalInterface
public interface TwoParameterFunctionWithoutReturn<T, U> {
    public void apply(T t, U u);
}

@FunctionalInterface
public interface TwoParameterFunctionByReturn<T, U> {
    public T apply(T t, U u);
}

@FunctionalInterface
public interface ThreeParameterFunctionByReturn<M, N, O> {
    public Integer apply(M m, N n, O o);
}
}

Does JavaScript guarantee object property order?

As of ES2015, property order is guaranteed for certain methods that iterate over properties. but not others. Unfortunately, the methods which are not guaranteed to have an order are generally the most often used:

  • Object.keys, Object.values, Object.entries
  • for..in loops
  • JSON.stringify

But, as of ES2020, property order for these previously untrustworthy methods will be guaranteed by the specification to be iterated over in the same deterministic manner as the others, due to to the finished proposal: for-in mechanics.

Just like with the methods which have a guaranteed iteration order (like Reflect.ownKeys and Object.getOwnPropertyNames), the previously-unspecified methods will also iterate in the following order:

  • Numeric array keys, in ascending numeric order
  • All other non-Symbol keys, in insertion order
  • Symbol keys, in insertion order

This is what pretty much every implementation does already (and has done for many years), but the new proposal has made it official.

Although the current specification leaves for..in iteration order "almost totally unspecified, real engines tend to be more consistent:"

The lack of specificity in ECMA-262 does not reflect reality. In discussion going back years, implementors have observed that there are some constraints on the behavior of for-in which anyone who wants to run code on the web needs to follow.

Because every implementation already iterates over properties predictably, it can be put into the specification without breaking backwards compatibility.


There are a few weird cases which implementations currently do not agree on, and in such cases, the resulting order will continue be unspecified. For property order to be guaranteed:

Neither the object being iterated nor anything in its prototype chain is a proxy, typed array, module namespace object, or host exotic object.

Neither the object nor anything in its prototype chain has its prototype change during iteration.

Neither the object nor anything in its prototype chain has a property deleted during iteration.

Nothing in the object's prototype chain has a property added during iteration.

No property of the object or anything in its prototype chain has its enumerability change during iteration.

No non-enumerable property shadows an enumerable one.

Swift: Convert enum value to String?

Not sure in which Swift version this feature was added, but right now (Swift 2.1) you only need this code:

enum Audience : String {
    case public
    case friends
    case private
}

let audience = Audience.public.rawValue // "public"

When strings are used for raw values, the implicit value for each case is the text of that case’s name.

[...]

enum CompassPoint : String {
    case north, south, east, west
}

In the example above, CompassPoint.south has an implicit raw value of "south", and so on.

You access the raw value of an enumeration case with its rawValue property:

let sunsetDirection = CompassPoint.west.rawValue
// sunsetDirection is "west"

Source.

How do I find all the files that were created today in Unix/Linux?

After going through may posts i found the best one that really works

find $file_path -type f -name "*.txt" -mtime -1 -printf "%f\n"

This prints only the file name like abc.txt not the /path/tofolder/abc.txt

Also also play around or customize with -mtime -1

Is it more efficient to copy a vector by reserving and copying, or by creating and swapping?

new_vector.assign(old_vector.begin(),old_vector.end()); // Method 1
new_vector = old_vector; // Method 2

Passing headers with axios POST request

Or, if you are using some property from vuejs prototype that can't be read on creation you can also define headers and write i.e.

storePropertyMaxSpeed(){
                axios.post('api/property', {
                    "property_name" : 'max_speed',
                    "property_amount" : this.newPropertyMaxSpeed
                    },
                    {headers :  {'Content-Type': 'application/json',
                                'Authorization': 'Bearer ' + this.$gate.token()}})
                  .then(() => { //this below peace of code isn't important 
                    Event.$emit('dbPropertyChanged');

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

                    Swal.fire({
                        position: 'center',
                        type: 'success',
                        title: 'Nova brzina unešena u bazu',
                        showConfirmButton: false,
                        timer: 1500
                        })
                })
                .catch(() => {
                     Swal.fire("Neuspješno!", "Nešto je pošlo do davola", "warning");
                })
            }
        },

Extract substring from a string

You can use subSequence , it's same as substr in C

 Str.subSequence(int Start , int End)

window.location.href and window.open () methods in JavaScript

  • window.open will open a new browser with the specified URL.

  • window.location.href will open the URL in the window in which the code is called.

Note also that window.open() is a function on the window object itself whereas window.location is an object that exposes a variety of other methods and properties.

413 Request Entity Too Large - File Upload Issue

I got the upload working with above changes. But when I made the changes I started getting 404 response in file upload which lead me to do further debugging and figured out its a permission issue by checking nginx error.log

Solution:

Check the current user and group ownership on /var/lib/nginx.

$ ls -ld /var/lib/nginx

drwx------. 3 nginx nginx 17 Oct 5 19:31 /var/lib/nginx

This tells that a possibly non-existent user and group named nginx owns this folder. This is preventing file uploading.

In my case, the username mentioned in "/etc/nginx/nginx.conf" was

user vagrant; 

Change the folder ownership to the user defined in nginx.conf in this case vagrant.

$ sudo chown -Rf vagrant:vagrant /var/lib/nginx

Verify that it actually changed.

$ ls -ld /var/lib/nginx
drwx------. 3 vagrant vagrant 17 Oct  5 19:31 /var/lib/nginx

Reload nginx and php-fpm for safer sade.

$ sudo service nginx reload
$ sudo service php-fpm reload

The permission denied error should now go away. Check the error.log (based on nginx.conf error_log location).

$ sudo nano /path/to/nginx/error.log

Read/Parse text file line by line in VBA

for the most basic read of a text file, use open

example:

Dim FileNum As Integer
Dim DataLine As String

FileNum = FreeFile()
Open "Filename" For Input As #FileNum

While Not EOF(FileNum)
    Line Input #FileNum, DataLine ' read in data 1 line at a time
    ' decide what to do with dataline, 
    ' depending on what processing you need to do for each case
Wend

httpd-xampp.conf: How to allow access to an external IP besides localhost?

For Ubuntu xampp,
Go to /opt/lampp/etc/extra/
and open httpd-xampp.conf file and add below lines to get remote access,
    Order allow,deny
    Require all granted
    Allow from all

in /opt/lampp/phpmyadmin section.

And restart lampp using, /opt/lampp/lampp restart

Android Studio rendering problems

Open your activity_main.xml . Switch to Design view if you are in text view. Look for the android version,with the android robo icon. Change the android version. Problem solved.

Pythonic way to print list items

Assuming you are fine with your list being printed [1,2,3], then an easy way in Python3 is:

mylist=[1,2,3,'lorem','ipsum','dolor','sit','amet']

print(f"There are {len(mylist):d} items in this lorem list: {str(mylist):s}")

Running this produces the following output:

There are 8 items in this lorem list: [1, 2, 3, 'lorem', 'ipsum', 'dolor', 'sit', 'amet']

Find the greatest number in a list of numbers

Use max()

>>> l = [1, 2, 5]
>>> max(l)
5
>>> 

Node.js version on the command line? (not the REPL)

find the installed node version.

$ node --version

or

 $ node -v

And if you want more information about installed node(i.e. node version,v8 version,platform,env variables info etc.)

then just do this.

$ node
> process
  process {
  title: 'node',
  version: 'v6.6.0',
  moduleLoadList: 
   [ 'Binding contextify',
     'Binding natives',
     'NativeModule events',
     'NativeModule util',
     'Binding uv',
     'NativeModule buffer',
     'Binding buffer',
     'Binding util',
     ...

where The process object is a global that provides information about, and control over, the current Node.js process.

Calling pylab.savefig without display in ipython

We don't need to plt.ioff() or plt.show() (if we use %matplotlib inline). You can test above code without plt.ioff(). plt.close() has the essential role. Try this one:

%matplotlib inline
import pylab as plt

# It doesn't matter you add line below. You can even replace it by 'plt.ion()', but you will see no changes.
## plt.ioff()

# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('test0.png')
plt.close(fig)

# Create a new figure, plot into it, then don't close it so it does get displayed
fig2 = plt.figure()
plt.plot([1,3,2])
plt.savefig('test1.png')

If you run this code in iPython, it will display a second plot, and if you add plt.close(fig2) to the end of it, you will see nothing.

In conclusion, if you close figure by plt.close(fig), it won't be displayed.

Objective-C : BOOL vs bool

Yup, BOOL is a typedef for a signed char according to objc.h.

I don't know about bool, though. That's a C++ thing, right? If it's defined as a signed char where 1 is YES/true and 0 is NO/false, then I imagine it doesn't matter which one you use.

Since BOOL is part of Objective-C, though, it probably makes more sense to use a BOOL for clarity (other Objective-C developers might be puzzled if they see a bool in use).

Jquery/Ajax Form Submission (enctype="multipart/form-data" ). Why does 'contentType:False' cause undefined index in PHP?

contentType option to false is used for multipart/form-data forms that pass files.

When one sets the contentType option to false, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multipart/form-data, one must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.


To try and fix your issue:

Use jQuery's .serialize() method which creates a text string in standard URL-encoded notation.

You need to pass un-encoded data when using contentType: false.

Try using new FormData instead of .serialize():

  var formData = new FormData($(this)[0]);

See for yourself the difference of how your formData is passed to your php page by using console.log().

  var formData = new FormData($(this)[0]);
  console.log(formData);

  var formDataSerialized = $(this).serialize();
  console.log(formDataSerialized);

Jasmine.js comparing arrays

just for the record you can always compare using JSON.stringify

const arr = [1,2,3]; expect(JSON.stringify(arr)).toBe(JSON.stringify([1,2,3])); expect(JSON.stringify(arr)).toEqual(JSON.stringify([1,2,3]));

It's all meter of taste, this will also work for complex literal objects

Parsing a pcap file in python

I would use python-dpkt. Here is the documentation: http://www.commercialventvac.com/dpkt.html

This is all I know how to do though sorry.

#!/usr/local/bin/python2.7

import dpkt

counter=0
ipcounter=0
tcpcounter=0
udpcounter=0

filename='sampledata.pcap'

for ts, pkt in dpkt.pcap.Reader(open(filename,'r')):

    counter+=1
    eth=dpkt.ethernet.Ethernet(pkt) 
    if eth.type!=dpkt.ethernet.ETH_TYPE_IP:
       continue

    ip=eth.data
    ipcounter+=1

    if ip.p==dpkt.ip.IP_PROTO_TCP: 
       tcpcounter+=1

    if ip.p==dpkt.ip.IP_PROTO_UDP:
       udpcounter+=1

print "Total number of packets in the pcap file: ", counter
print "Total number of ip packets: ", ipcounter
print "Total number of tcp packets: ", tcpcounter
print "Total number of udp packets: ", udpcounter

Update:

Project on GitHub, documentation here

How to get folder path for ClickOnce application

Assuming the question is about accessing files in the application folder after the ClickOnce (true == System.Deployment.ApplicationDeploy.IsNetworkDeployed) application is installed on the user's PC, their are three ways to get this folder by the application itself:

String path1 = System.AppDomain.CurrentDomain.BaseDirectory;
String path2 = System.IO.Directory.GetCurrentDirectory();    
String path3 = System.Reflection.Assembly.GetExecutingAssembly().CodeBase; //Remove the last path component, the executing assembly itself.

These work from VS IDE and from a deployed/installed ClickedOnce app, no "true == System.Deployment.ApplicationDeploy.IsNetworkDeployed" check required. ClickOnce picks up any files included in the Visual Studio 2017 project so really the application can access any and all deployed files using relative paths from within the application.

This is based on Windows 10 and Visual Studio 2017

How to not wrap contents of a div?

I don't know the reasoning behind this, but I set my parent container to display:flex and the child containers to display:inline-block and they stayed inline despite the combined width of the children exceeding the parent.

Didn't need to toy with max-width, max-height, white-space, or anything else.

Hope that helps someone.

How can I list all tags for a Docker image on a remote registry?

curl -u <username>:<password> https://$your_registry/v2/$image_name/tags/list -s -o - | \
    tr -d '{' | tr -d '}' | sed -e 's/[][]//g' -e 's/"//g' -e 's/ //g' | \
    awk -F: '{print $3}' | sed -e 's/,/\n/g'

You can use it if your env has no 'jq', = )

how to create 100% vertical line in css

Use an absolutely positioned pseudo element:

ul:after {
  content: '';
  width: 0;
  height: 100%;
  position: absolute;
  border: 1px solid black;
  top: 0;
  left: 100px;
}

Demo

Gitignore not working

Also, comments have to be on their own line. They can't be put after an entry. So this won't work:

/node_modules  # DON'T COMMENT HERE (since nullifies entire line)

But this will work:

# fine to comment here
/node_modules

Which is the default location for keystore/truststore of Java applications?

In Java, according to the JSSE Reference Guide, there is no default for the keystore, the default for the truststore is "jssecacerts, if it exists. Otherwise, cacerts".

A few applications use ~/.keystore as a default keystore, but this is not without problems (mainly because you might not want all the application run by the user to use that trust store).

I'd suggest using application-specific values that you bundle with your application instead, it would tend to be more applicable in general.

Resolving LNK4098: defaultlib 'MSVCRT' conflicts with

Right-click the project, select Properties then under 'Configuration properties | Linker | Input | Ignore specific Library and write msvcrtd.lib

MySQL > Table doesn't exist. But it does (or it should)

I have just spend three days on this nightmare. Ideally, you should have a backup that you can restore, then simply drop the damaged table. These sorts of errors can cause your ibdata1 to grow huge (100GB+ in size for modest tables)

If you don't have a recent backup, such as if you relied on mySqlDump, then your backups probably silently broke at some point in the past. You will need to export the databases, which of course you cant do, because you will get lock errors while running mySqlDump.

So, as a workaround, go to /var/log/mysql/database_name/ and remove the table_name.*

Then immediately try to dump the table; doing this should now work. Now restore the database to a new database and rebuild the missing table(s). Then dump the broken database.

In our case we were also constantly getting mysql has gone away messages at random intervals on all databases; once the damaged database were removed everything went back to normal.

How to replace a string in a SQL Server Table Column

UPDATE [table]
SET [column] = REPLACE([column], '/foo/', '/bar/')

Display progress bar while doing some work in C#?

It seems to me that you are operating on at least one false assumption.

1. You don't need to raise the ProgressChanged event to have a responsive UI

In your question you say this:

BackgroundWorker is not the answer because it may be that I don't get the progress notification, which means there would be no call to ProgressChanged as the DoWork is a single call to an external function . . .

Actually, it does not matter whether you call the ProgressChanged event or not. The whole purpose of that event is to temporarily transfer control back to the GUI thread to make an update that somehow reflects the progress of the work being done by the BackgroundWorker. If you are simply displaying a marquee progress bar, it would actually be pointless to raise the ProgressChanged event at all. The progress bar will continue rotating as long as it is displayed because the BackgroundWorker is doing its work on a separate thread from the GUI.

(On a side note, DoWork is an event, which means that it is not just "a single call to an external function"; you can add as many handlers as you like; and each of those handlers can contain as many function calls as it likes.)

2. You don't need to call Application.DoEvents to have a responsive UI

To me it sounds like you believe that the only way for the GUI to update is by calling Application.DoEvents:

I need to keep call the Application.DoEvents(); for the progress bar to keep rotating.

This is not true in a multithreaded scenario; if you use a BackgroundWorker, the GUI will continue to be responsive (on its own thread) while the BackgroundWorker does whatever has been attached to its DoWork event. Below is a simple example of how this might work for you.

private void ShowProgressFormWhileBackgroundWorkerRuns() {
    // this is your presumably long-running method
    Action<string, string> exec = DoSomethingLongAndNotReturnAnyNotification;

    ProgressForm p = new ProgressForm(this);

    BackgroundWorker b = new BackgroundWorker();

    // set the worker to call your long-running method
    b.DoWork += (object sender, DoWorkEventArgs e) => {
        exec.Invoke(path, parameters);
    };

    // set the worker to close your progress form when it's completed
    b.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs e) => {
        if (p != null && p.Visible) p.Close();
    };

    // now actually show the form
    p.Show();

    // this only tells your BackgroundWorker to START working;
    // the current (i.e., GUI) thread will immediately continue,
    // which means your progress bar will update, the window
    // will continue firing button click events and all that
    // good stuff
    b.RunWorkerAsync();
}

3. You can't run two methods at the same time on the same thread

You say this:

I just need to call Application.DoEvents() so that the Marque progress bar will work, while the worker function works in the Main thread . . .

What you're asking for is simply not real. The "main" thread for a Windows Forms application is the GUI thread, which, if it's busy with your long-running method, is not providing visual updates. If you believe otherwise, I suspect you misunderstand what BeginInvoke does: it launches a delegate on a separate thread. In fact, the example code you have included in your question to call Application.DoEvents between exec.BeginInvoke and exec.EndInvoke is redundant; you are actually calling Application.DoEvents repeatedly from the GUI thread, which would be updating anyway. (If you found otherwise, I suspect it's because you called exec.EndInvoke right away, which blocked the current thread until the method finished.)

So yes, the answer you're looking for is to use a BackgroundWorker.

You could use BeginInvoke, but instead of calling EndInvoke from the GUI thread (which will block it if the method isn't finished), pass an AsyncCallback parameter to your BeginInvoke call (instead of just passing null), and close the progress form in your callback. Be aware, however, that if you do that, you're going to have to invoke the method that closes the progress form from the GUI thread, since otherwise you'll be trying to close a form, which is a GUI function, from a non-GUI thread. But really, all the pitfalls of using BeginInvoke/EndInvoke have already been dealt with for you with the BackgroundWorker class, even if you think it's ".NET magic code" (to me, it's just an intuitive and useful tool).

How to check if an object implements an interface?

Use

if (gor instanceof Monster) {
    //...
}

Setting background images in JFrame

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

class BackgroundImageJFrame extends JFrame
{

    JButton b1;
    JLabel l1;

    public BackgroundImageJFrame() {

        setSize(400,400);
        setVisible(true);

        setLayout(new BorderLayout());

        JLabel background=new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful_design.png"));

        add(background);

        background.setLayout(new FlowLayout());

        l1=new JLabel("Here is a button");
        b1=new JButton("I am a button");

        background.add(l1);
        background.add(b1);
    }

    public static void main(String args[]) 
    {
        new BackgroundImageJFrame();
    }
}

check out the below link

http://java-demos.blogspot.in/2012/09/setting-background-image-in-jframe.html

Log4j2 configuration - No log4j2 configuration file found

In my case I had to put it in the bin folder of my project even the fact that my classpath is set to the src folder. I have no idea why, but it's worth a try.

Save PL/pgSQL output from PostgreSQL to a CSV file

In terminal (while connected to the db) set output to the cvs file

1) Set field seperator to ',':

\f ','

2) Set output format unaligned:

\a

3) Show only tuples:

\t

4) Set output:

\o '/tmp/yourOutputFile.csv'

5) Execute your query:

:select * from YOUR_TABLE

6) Output:

\o

You will then be able to find your csv file in this location:

cd /tmp

Copy it using the scp command or edit using nano:

nano /tmp/yourOutputFile.csv

What are the rules for casting pointers in C?

char c = '5'

A char (1 byte) is allocated on stack at address 0x12345678.

char *d = &c;

You obtain the address of c and store it in d, so d = 0x12345678.

int *e = (int*)d;

You force the compiler to assume that 0x12345678 points to an int, but an int is not just one byte (sizeof(char) != sizeof(int)). It may be 4 or 8 bytes according to the architecture or even other values.

So when you print the value of the pointer, the integer is considered by taking the first byte (that was c) and other consecutive bytes which are on stack and that are just garbage for your intent.

C fopen vs open

open() is a low-level os call. fdopen() converts an os-level file descriptor to the higher-level FILE-abstraction of the C language. fopen() calls open() in the background and gives you a FILE-pointer directly.

There are several advantages to using FILE-objects rather raw file descriptors, which includes greater ease of usage but also other technical advantages such as built-in buffering. Especially the buffering generally results in a sizeable performance advantage.

convert string array to string

I used this way to make my project faster:

RichTextBox rcbCatalyst = new RichTextBox()
{
    Lines = arrayString
};
string text = rcbCatalyst.Text;
rcbCatalyst.Dispose();

return text;

RichTextBox.Text will automatically convert your array to a multiline string!

Redirecting to a relative URL in JavaScript

try following js code

_x000D_
_x000D_
location = '..'
_x000D_
_x000D_
_x000D_

using nth-child in tables tr td

Current css version still doesn't support selector find by content. But there is a way, by using css selector find by attribute, but you have to put some identifier on all of the <td> that have $ inside. Example: using nth-child in tables tr td

html

<tr>
    <td>&nbsp;</td>
    <td data-rel='$'>$</td>
    <td>&nbsp;</td>
</tr>

css

table tr td[data-rel='$'] {
    background-color: #333;
    color: white;
}

Please try these example.

_x000D_
_x000D_
table tr td[data-content='$'] {_x000D_
    background-color: #333;_x000D_
    color: white;_x000D_
}
_x000D_
<table border="1">_x000D_
    <tr>_x000D_
        <td>A</td>_x000D_
        <td data-content='$'>$</td>_x000D_
        <td>B</td>_x000D_
        <td data-content='$'>$</td>_x000D_
        <td>C</td>_x000D_
        <td data-content='$'>$</td>_x000D_
        <td>D</td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

SQL Server 2005 Using CHARINDEX() To split a string

Here's a little function that will do "NATO encoding" for you:

CREATE FUNCTION dbo.NATOEncode (
   @String varchar(max)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN (
   WITH L1 (N) AS (SELECT 1 UNION ALL SELECT 1),
   L2 (N) AS (SELECT 1 FROM L1, L1 B),
   L3 (N) AS (SELECT 1 FROM L2, L2 B),
   L4 (N) AS (SELECT 1 FROM L3, L3 B),
   L5 (N) AS (SELECT 1 FROM L4, L4 C),
   L6 (N) AS (SELECT 1 FROM L5, L5 C),
   Nums (Num) AS (SELECT Row_Number() OVER (ORDER BY (SELECT 1)) FROM L6)
   SELECT
      NATOString = Substring((
         SELECT
            Convert(varchar(max), ' ' + D.Word)
         FROM
            Nums N
            INNER JOIN (VALUES
               ('A', 'Alpha'),
               ('B', 'Beta'),
               ('C', 'Charlie'),
               ('D', 'Delta'),
               ('E', 'Echo'),
               ('F', 'Foxtrot'),
               ('G', 'Golf'),
               ('H', 'Hotel'),
               ('I', 'India'),
               ('J', 'Juliet'),
               ('K', 'Kilo'),
               ('L', 'Lima'),
               ('M', 'Mike'),
               ('N', 'November'),
               ('O', 'Oscar'),
               ('P', 'Papa'),
               ('Q', 'Quebec'),
               ('R', 'Romeo'),
               ('S', 'Sierra'),
               ('T', 'Tango'),
               ('U', 'Uniform'),
               ('V', 'Victor'),
               ('W', 'Whiskey'),
               ('X', 'X-Ray'),
               ('Y', 'Yankee'),
               ('Z', 'Zulu'),
               ('0', 'Zero'),
               ('1', 'One'),
               ('2', 'Two'),
               ('3', 'Three'),
               ('4', 'Four'),
               ('5', 'Five'),
               ('6', 'Six'),
               ('7', 'Seven'),
               ('8', 'Eight'),
               ('9', 'Niner')
            ) D (Digit, Word)
               ON Substring(@String, N.Num, 1) = D.Digit
         WHERE
            N.Num <= Len(@String)
         FOR XML PATH(''), TYPE
      ).value('.[1]', 'varchar(max)'), 2, 2147483647)
);

This function will work on even very long strings, and performs pretty well (I ran it against a 100,000-character string and it returned in 589 ms). Here's an example of how to use it:

SELECT NATOString FROM dbo.NATOEncode('LD-23DSP-1430');
-- Output: Lima Delta Two Three Delta Sierra Papa One Four Three Zero

I intentionally made it a table-valued function so it could be inlined into a query if you run it against many rows at once, just use CROSS APPLY or wrap the above example in parentheses to use it as a value in the SELECT clause (you can put a column name in the function parameter position).

PHP array value passes to next row

Change the checkboxes so that the name includes the index inside the brackets:

<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>"> 

The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.

How do I run Python script using arguments in windows command line

I found this thread looking for information about dealing with parameters; this easy guide was so cool:

import argparse

parser = argparse.ArgumentParser(description='Script so useful.')
parser.add_argument("--opt1", type=int, default=1)
parser.add_argument("--opt2")

args = parser.parse_args()

opt1_value = args.opt1
opt2_value = args.opt2

run like:

python myScript.py --opt2 = 'hi'

Call parent method from child class c#

To follow up on the comment by suhendri to Rory McCrossan answer. Here is an Action delegate example:

In child add:

public Action UpdateProgress;  // In place of event handler declaration
                               // declare an Action delegate
.
.
.
private LoadData() {
    this.UpdateProgress();    // call to Action delegate - MyMethod in
                              // parent
}

In parent add:

// The 3 lines in the parent becomes:
ChildClass child = new ChildClass();
child.UpdateProgress = this.MyMethod;  // assigns MyMethod to child delegate

Fire event on enter key press for a textbox

Try this option.

update that coding part in Page_Load event before catching IsPostback

 TextBox1.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('ctl00_ContentPlaceHolder1_Button1').click();return false;}} else {return true}; ");

How can I apply a border only inside a table?

For ordinary table markup, here's a short solution that works on all devices/browsers on BrowserStack, except IE 7 and below:

table { border-collapse: collapse; }

td + td,
th + th { border-left: 1px solid; }
tr + tr { border-top: 1px solid; }

For IE 7 support, add this:

tr + tr > td,
tr + tr > th { border-top: 1px solid; }

A test case can be seen here: http://codepen.io/dalgard/pen/wmcdE

Hive: Convert String to Integer

If the value is between –2147483648 and 2147483647, cast(string_filed as int) will work. else cast(string_filed as bigint) will work

    hive> select cast('2147483647' as int);
    OK
    2147483647
    
    hive> select cast('2147483648' as int);
    OK
    NULL
    
    hive> select cast('2147483648' as bigint);
    OK
    2147483648

How can I format my grep output to show line numbers at the end of the line, and also the hit count?

-n returns line number.

-i is for ignore-case. Only to be used if case matching is not necessary

$ grep -in null myfile.txt

2:example two null,
4:example four null,

Combine with awk to print out the line number after the match:

$ grep -in null myfile.txt | awk -F: '{print $2" - Line number : "$1}'

example two null, - Line number : 2
example four null, - Line number : 4

Use command substitution to print out the total null count:

$ echo "Total null count :" $(grep -ic null myfile.txt)

Total null count : 2

Escaping Strings in JavaScript

A variation of the function provided by Paolo Bergantino that works directly on String:

String.prototype.addSlashes = function() 
{ 
   //no need to do (str+'') anymore because 'this' can only be a string
   return this.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
} 

By adding the code above in your library you will be able to do:

var test = "hello single ' double \" and slash \\ yippie";
alert(test.addSlashes());

EDIT:

Following suggestions in the comments, whoever is concerned about conflicts amongst JavaScript libraries can add the following code:

if(!String.prototype.addSlashes)
{
   String.prototype.addSlashes = function()... 
}
else
   alert("Warning: String.addSlashes has already been declared elsewhere.");

Check if a given time lies between two times regardless of date

Logically if you do the following you should always be ok granted we use military time...

if start time is greater than end time add 24 to end time else use times as is

compare current time to be inbetween start and end time.

How to turn off word wrapping in HTML?

This worked for me to stop silly work breaks from happening within Chrome textareas

word-break: keep-all;

CSV with comma or semicolon?

In Windows it is dependent on the "Regional and Language Options" customize screen where you find a List separator. This is the char Windows applications expect to be the CSV separator.

Of course this only has effect in Windows applications, for example Excel will not automatically split data into columns if the file is not using the above mentioned separator. All applications that use Windows regional settings will have this behavior.

If you are writing a program for Windows that will require importing the CSV in other applications and you know that the list separator set for your target machines is ,, then go for it, otherwise I prefer ; since it causes less problems with decimal points, digit grouping and does not appear in much text.

How to show Bootstrap table with sort icon

Use this icons with bootstrap (glyphicon):

<span class="glyphicon glyphicon-triangle-bottom"></span>
<span class="glyphicon glyphicon-triangle-top"></span>

http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_glyph_triangle-bottom&stacked=h

http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_glyph_triangle-bottom&stacked=h

Remove empty space before cells in UITableView

As long as UITableView is not the first subview of the view controller, the empty space will not appear.

Solution: Add a hidden/clear view object (views, labels, button, etc.) as the first subview of the view controller (at the same level as the UITableView but before it).

How to remove outliers from a dataset

OK, you should apply something like this to your dataset. Do not replace & save or you'll destroy your data! And, btw, you should (almost) never remove outliers from your data:

remove_outliers <- function(x, na.rm = TRUE, ...) {
  qnt <- quantile(x, probs=c(.25, .75), na.rm = na.rm, ...)
  H <- 1.5 * IQR(x, na.rm = na.rm)
  y <- x
  y[x < (qnt[1] - H)] <- NA
  y[x > (qnt[2] + H)] <- NA
  y
}

To see it in action:

set.seed(1)
x <- rnorm(100)
x <- c(-10, x, 10)
y <- remove_outliers(x)
## png()
par(mfrow = c(1, 2))
boxplot(x)
boxplot(y)
## dev.off()

And once again, you should never do this on your own, outliers are just meant to be! =)

EDIT: I added na.rm = TRUE as default.

EDIT2: Removed quantile function, added subscripting, hence made the function faster! =)

enter image description here

How do I export a project in the Android studio?

Follow this steps:

-Build
-Generate Signed Apk
-Create new

Then fill up "New Key Store" form. If you wand to change .jnk file destination then chick on destination and give a name to get Ok button. After finishing it you will get "Key store password", "Key alias", "Key password" Press next and change your the destination folder. Then press finish, thats all. :)

enter image description here

enter image description here enter image description here

enter image description here enter image description here

How to obtain the last index of a list?

all above answers is correct but however

a = [];
len(list1) - 1 # where 0 - 1 = -1

to be more precisely

a = [];
index = len(a) - 1 if a else None;

if index == None : raise Exception("Empty Array")

since arrays is starting with 0

How to hide image broken Icon using only CSS/HTML?

A basic and very simple way of doing this without any code required would be to just provide an empty alt statement. The browser will then return the image as blank. It would look just like if the image isn't there.

Example:

<img class="img_gal" alt="" src="awesome.jpg">

Try it out to see! ;)

How do I add a new column to a Spark DataFrame (using PySpark)?

For Spark 2.0

# assumes schema has 'age' column 
df.select('*', (df.age + 10).alias('agePlusTen'))

Why is char[] preferred over String for passwords?

I don't think this is a valid suggestion, but, I can at least guess at the reason.

I think the motivation is wanting to make sure that you can erase all trace of the password in memory promptly and with certainty after it is used. With a char[] you could overwrite each element of the array with a blank or something for sure. You can't edit the internal value of a String that way.

But that alone isn't a good answer; why not just make sure a reference to the char[] or String doesn't escape? Then there's no security issue. But the thing is that String objects can be intern()ed in theory and kept alive inside the constant pool. I suppose using char[] forbids this possibility.

How to submit form on change of dropdown list?

Simple JavaScript will do -

<form action="myservlet.do" method="POST">
    <select name="myselect" id="myselect" onchange="this.form.submit()">
        <option value="1">One</option>
        <option value="2">Two</option>
        <option value="3">Three</option>
        <option value="4">Four</option>
    </select>
</form>

Here is a link for a good javascript tutorial.

What does @media screen and (max-width: 1024px) mean in CSS?

In my case I wanted to center my logo on a website when the browser has 800px or less, then I did this by using the @media tag:

@media screen and (max-width: 800px) {
  #logo {
    float: none;
    margin: 0;
    text-align: center;
    display: block;
    width: auto;
  }
}

It worked for me, hope somebody find this solution useful. :) For more information see this.

How to retrieve records for last 30 minutes in MS SQL?

Remember that CURRENT_TIMESTAMP - (number) works fine, but that you need to understand what number it is looking for - it is floating-point number of days. So CURRENT_TIMESTAMP-1.0 is 1 day ago, CURRENT_TIMESTAMP-0.5 is 1/2 day ago. For 30 minutes, that is 1.0/48.0 (use radix so result is a floating point number) or 0.0208333333333333, so your query will work if re-written as

select * from
[Janus999DB].[dbo].[tblCustomerPlay]
where DatePlayed < CURRENT_TIMESTAMP
and DatePlayed >
CURRENT_TIMESTAMP-1.0/48.0

You could also use 1.0/24.0/2.0 if that looks more like 1/2 hour to you.

Extract file basename without path and extension in bash

Just an alternative that I came up with to extract an extension, using the posts in this thread with my own small knowledge base that was more familiar to me.

ext="$(rev <<< "$(cut -f "1" -d "." <<< "$(rev <<< "file.docx")")")"

Note: Please advise on my use of quotes; it worked for me but I might be missing something on their proper use (I probably use too many).

Split function in oracle to comma separated values with automatic sequence

This function returns the nth part of input string MYSTRING. Second input parameter is separator ie., SEPARATOR_OF_SUBSTR and the third parameter is Nth Part which is required.

Note: MYSTRING should end with the separator.

create or replace FUNCTION PK_GET_NTH_PART(MYSTRING VARCHAR2,SEPARATOR_OF_SUBSTR VARCHAR2,NTH_PART NUMBER)
RETURN VARCHAR2
IS
NTH_SUBSTR VARCHAR2(500);
POS1 NUMBER(4);
POS2 NUMBER(4);
BEGIN
IF NTH_PART=1 THEN
SELECT REGEXP_INSTR(MYSTRING,SEPARATOR_OF_SUBSTR, 1, 1)  INTO POS1 FROM DUAL; 
SELECT SUBSTR(MYSTRING,0,POS1-1) INTO NTH_SUBSTR FROM DUAL;
ELSE
SELECT REGEXP_INSTR(MYSTRING,SEPARATOR_OF_SUBSTR, 1, NTH_PART-1) INTO  POS1 FROM DUAL; 
SELECT REGEXP_INSTR(MYSTRING,SEPARATOR_OF_SUBSTR, 1, NTH_PART)  INTO POS2 FROM DUAL; 
SELECT SUBSTR(MYSTRING,POS1+1,(POS2-POS1-1)) INTO NTH_SUBSTR FROM DUAL;
END IF;
RETURN NTH_SUBSTR;
END;

Hope this helps some body, you can use this function like this in a loop to get all the values separated:

SELECT REGEXP_COUNT(MYSTRING, '~', 1, 'i') INTO NO_OF_RECORDS FROM DUAL;
WHILE NO_OF_RECORDS>0
LOOP
    PK_RECORD    :=PK_GET_NTH_PART(MYSTRING,'~',NO_OF_RECORDS);
    -- do some thing
    NO_OF_RECORDS  :=NO_OF_RECORDS-1;
END LOOP;

Here NO_OF_RECORDS,PK_RECORD are temp variables.

Hope this helps.

What is the difference between rb and r+b modes in file objects

r opens for reading, whereas r+ opens for reading and writing. The b is for binary.

This is spelled out in the documentation:

The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position). If mode is omitted, it defaults to 'r'. The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append 'b' to the mode value to open the file in binary mode, which will improve portability. (Appending 'b' is useful even on systems that don’t treat binary and text files differently, where it serves as documentation.) See below for more possible values of mode.

Modes 'r+', 'w+' and 'a+' open the file for updating (note that 'w+' truncates the file). Append 'b' to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don’t have this distinction, adding the 'b' has no effect.

POST request send json data java HttpUrlConnection

Your JSON is not correct. Instead of

JSONObject cred = new JSONObject();
JSONObject auth=new JSONObject();
JSONObject parent=new JSONObject();
cred.put("username","adm");
cred.put("password", "pwd");
auth.put("tenantName", "adm");
auth.put("passwordCredentials", cred.toString()); // <-- toString()
parent.put("auth", auth.toString());              // <-- toString()

OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());

write

JSONObject cred = new JSONObject();
JSONObject auth=new JSONObject();
JSONObject parent=new JSONObject();
cred.put("username","adm");
cred.put("password", "pwd");
auth.put("tenantName", "adm");
auth.put("passwordCredentials", cred);
parent.put("auth", auth);

OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());

So, the JSONObject.toString() should be called only once for the outer object.

Another thing (most probably not your problem, but I'd like to mention it):

To be sure not to run into encoding problems, you should specify the encoding, if it is not UTF-8:

con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("Accept", "application/json");

// ...

OutputStream os = con.getOutputStream();
os.write(parent.toString().getBytes("UTF-8"));
os.close();

batch file to check 64bit or 32bit OS

Here's a nice concise version:

set isX64=False && if /I "%PROCESSOR_ARCHITECTURE%"=="AMD64" ( set isX64=True ) else ( if /I "%PROCESSOR_ARCHITEW6432%"=="AMD64" ( set isX64=True ) )

echo %isX64%

Don't use the "Program Files (x86)" directory as evidence of anything: naughty software can easily create this directory on a 32-bit machine. Instead use the PROCESSOR_ARCHITECTURE and PROCESSOR_ARCHITEW6432 environment variables.

How to POST raw whole JSON in the body of a Retrofit request?

If you don't want to create extra classes or use JSONObject you can use a HashMap.

Retrofit interface:

@POST("/rest/registration/register")
fun signUp(@Body params: HashMap<String, String>): Call<ResponseBody>

Call:

val map = hashMapOf(
    "username" to username,
    "password" to password,
    "firstName" to firstName,
    "surname" to lastName
)

retrofit.create(TheApi::class.java)
     .signUp(map)
     .enqueue(callback)

Use CSS3 transitions with gradient backgrounds

For what it's worth, here's a Sass mixin:

Usage:

@include gradientAnimation(red, blue, .6s);

Mixin:

@mixin gradientAnimation( $start, $end, $transTime ){
    background-size: 100%;
    background-image: linear-gradient($start, $end);
    position: relative;
    z-index: 100;
    &:before {
        background-image: linear-gradient($end, $start);
        content: "";
        display: block;
        height: 100%;
        position: absolute;
        top: 0; left: 0;
        opacity: 0;
        width: 100%;
        z-index: -100;
        transition: opacity $transTime;
    }
    &:hover {
        &:before {
            opacity: 1;
        }
    }
}

Taken from this awesome post on Medium from Dave Lunny: https://medium.com/@dave_lunny/animating-css-gradients-using-only-css-d2fd7671e759

MySQL combine two columns and add into a new column

SELECT CONCAT (zipcode, ' - ', city, ', ', state) AS COMBINED FROM TABLE

Convert JSON String to JSON Object c#

This works for me using JsonConvert

var result = JsonConvert.DeserializeObject<Class>(responseString);

Editing dictionary values in a foreach loop

Disclaimer: I don't do much C#

You are trying to modify the DictionaryEntry object which is stored in the HashTable. The Hashtable only stores one object -- your instance of DictionaryEntry. Changing the Key or the Value is enough to change the HashTable and cause the enumerator to become invalid.

You can do it outside of the loop:

if(hashtable.Contains(key))
{
    hashtable[key] = value;
}

by first creating a list of all the keys of the values you wish to change and iterate through that list instead.

JSONException: Value of type java.lang.String cannot be converted to JSONObject

For me, I just needed to use getString() vs. getJSONObject() (the latter threw that error):

JSONObject jsonObject = new JSONObject(jsonString);
String valueIWanted = jsonObject.getString("access_token"))

Can't bind to 'ngForOf' since it isn't a known property of 'tr' (final release)

app.module.ts fixed and changed to: import the BrowserModule in your app module

import { BrowserModule } from '@angular/platform-browser';

@NgModule({
  declarations: [
    AppComponent    
  ],
  imports: [
    BrowserModule, 
  ],     
  providers: [],
  bootstrap: [AppComponent]
})

How to set the min and max height or width of a Frame?

There is no single magic function to force a frame to a minimum or fixed size. However, you can certainly force the size of a frame by giving the frame a width and height. You then have to do potentially two more things: when you put this window in a container you need to make sure the geometry manager doesn't shrink or expand the window. Two, if the frame is a container for other widget, turn grid or pack propagation off so that the frame doesn't shrink or expand to fit its own contents.

Note, however, that this won't prevent you from resizing a window to be smaller than an internal frame. In that case the frame will just be clipped.

import Tkinter as tk

root = tk.Tk()
frame1 = tk.Frame(root, width=100, height=100, background="bisque")
frame2 = tk.Frame(root, width=50, height = 50, background="#b22222")

frame1.pack(fill=None, expand=False)
frame2.place(relx=.5, rely=.5, anchor="c")

root.mainloop()

npm - "Can't find Python executable "python", you can set the PYTHON env variable."

The easiest way is to let NPM do everything for you,

npm --add-python-to-path='true' --debug install --global windows-build-tools

How to initialize log4j properly?

If we are using apache commons logging wrapper on top of log4j, then we need to have both the jars available in classpath. Also, commons-logging.properties and log4j.properties/xml should be available in classpath.

We can also pass implementation class and log4j.properties name as JAVA_OPTS either using -Dorg.apache.commons.logging.Log=<logging implementation class name> -Dlog4j.configuration=<file:location of log4j.properties/xml file>. Same can be done via setting JAVA_OPTS in case of app/web server.

It will help to externalize properties which can be changed in deployment.

Choosing bootstrap vs material design

As far as I know you can use all mentioned technologies separately or together. It's up to you. I think you look at the problem from the wrong angle. Material Design is just the way particular elements of the page are designed, behave and put together. Material Design provides great UI/UX, but it relies on the graphic layout (HTML/CSS) rather than JS (events, interactions).

On the other hand, AngularJS and Bootstrap are front-end frameworks that can speed up your development by saving you from writing tons of code. For example, you can build web app utilizing AngularJS, but without Material Design. Or You can build simple HTML5 web page with Material Design without AngularJS or Bootstrap. Finally you can build web app that uses AngularJS with Bootstrap and with Material Design. This is the best scenario. All technologies support each other.

  1. Bootstrap = responsive page
  2. AngularJS = MVC
  3. Material Design = great UI/UX

You can check awesome material design components for AngularJS:

https://material.angularjs.org


enter image description here

Demo: https://material.angularjs.org/latest/demo/ enter image description here

How to restart kubernetes nodes?

If a node is so unhealthy that the master can't get status from it -- Kubernetes may not be able to restart the node. And if health checks aren't working, what hope do you have of accessing the node by SSH?

In this case, you may have to hard-reboot -- or, if your hardware is in the cloud, let your provider do it.

For example, the AWS EC2 Dashboard allows you to right-click an instance to pull up an "Instance State" menu -- from which you can reboot/terminate an unresponsive node.

Before doing this, you might choose to kubectl cordon node for good measure. And you may find kubectl delete node to be an important part of the process for getting things back to normal -- if the node doesn't automatically rejoin the cluster after a reboot.


Why would a node become unresponsive? Probably some resource has been exhausted in a way that prevents the host operating system from handling new requests in a timely manner. This could be disk, or network -- but the more insidious case is out-of-memory (OOM), which Linux handles poorly.

To help Kubernetes manage node memory safely, it's a good idea to do both of the following:

  • Reserve some memory for the system.
  • Be very careful with (avoid) opportunistic memory specifications for your pods. In other words, don't allow different values of requests and limits for memory.

The idea here is to avoid the complications associated with memory overcommit, because memory is incompressible, and both Linux and Kubernetes' OOM killers may not trigger before the node has already become unhealthy and unreachable.

?: operator (the 'Elvis operator') in PHP

Yes, this is new in PHP 5.3. It returns either the value of the test expression if it is evaluated as TRUE, or the alternative value if it is evaluated as FALSE.

Log4j: How to configure simplest possible file logging?

Here's a simple one that I often use:

# Set up logging to include a file record of the output
# Note: the file is always created, even if there is 
# no actual output.
log4j.rootLogger=error, stdout, R

# Log format to standard out
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=   %5p\t[%d] [%t] (%F:%L)\n     \t%m%n\n

# File based log output
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=owls_conditions.log
log4j.appender.R.MaxFileSize=10000KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=   %5p\t[%d] [%t] (%F:%L)\n     \t%m%n\n

The format of the log is as follows:

ERROR   [2009-09-13 09:56:01,760] [main] (RDFDefaultErrorHandler.java:44)
        http://www.xfront.com/owl/ontologies/camera/#(line 1 column 1): Content is not allowed in prolog.

Such a format is defined by the string %5p\t[%d] [%t] (%F:%L)\n \t%m%n\n. You can read the meaning of conversion characters in log4j javadoc for PatternLayout.

Included comments should help in understanding what it does. Further notes:

  • it logs both to console and to file; in this case the file is named owls_conditions.log: change it according to your needs;
  • files are rotated when they reach 10000KB, and one back-up file is kept

Rotate a div using javascript

To rotate a DIV we can add some CSS that, well, rotates the DIV using CSS transform rotate.

To toggle the rotation we can keep a flag, a simple variable with a boolean value that tells us what way to rotate.

var rotated = false;

document.getElementById('button').onclick = function() {
    var div = document.getElementById('div'),
        deg = rotated ? 0 : 66;

    div.style.webkitTransform = 'rotate('+deg+'deg)'; 
    div.style.mozTransform    = 'rotate('+deg+'deg)'; 
    div.style.msTransform     = 'rotate('+deg+'deg)'; 
    div.style.oTransform      = 'rotate('+deg+'deg)'; 
    div.style.transform       = 'rotate('+deg+'deg)'; 

    rotated = !rotated;
}

_x000D_
_x000D_
var rotated = false;_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
    var div = document.getElementById('div'),_x000D_
        deg = rotated ? 0 : 66;_x000D_
_x000D_
    div.style.webkitTransform = 'rotate('+deg+'deg)'; _x000D_
    div.style.mozTransform    = 'rotate('+deg+'deg)'; _x000D_
    div.style.msTransform     = 'rotate('+deg+'deg)'; _x000D_
    div.style.oTransform      = 'rotate('+deg+'deg)'; _x000D_
    div.style.transform       = 'rotate('+deg+'deg)'; _x000D_
    _x000D_
    rotated = !rotated;_x000D_
}
_x000D_
#div {_x000D_
    position:relative; _x000D_
    height: 200px; _x000D_
    width: 200px; _x000D_
    margin: 30px;_x000D_
    background: red;_x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
_x000D_
_x000D_

To add some animation to the rotation all we have to do is add CSS transitions

div {
    -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in-out;
    -o-transition: all 0.5s ease-in-out;
    transition: all 0.5s ease-in-out;
}

_x000D_
_x000D_
var rotated = false;_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
    var div = document.getElementById('div'),_x000D_
        deg = rotated ? 0 : 66;_x000D_
_x000D_
    div.style.webkitTransform = 'rotate('+deg+'deg)'; _x000D_
    div.style.mozTransform    = 'rotate('+deg+'deg)'; _x000D_
    div.style.msTransform     = 'rotate('+deg+'deg)'; _x000D_
    div.style.oTransform      = 'rotate('+deg+'deg)'; _x000D_
    div.style.transform       = 'rotate('+deg+'deg)'; _x000D_
    _x000D_
    rotated = !rotated;_x000D_
}
_x000D_
#div {_x000D_
    position:relative; _x000D_
    height: 200px; _x000D_
    width: 200px; _x000D_
    margin: 30px;_x000D_
    background: red;_x000D_
    -webkit-transition: all 0.5s ease-in-out;_x000D_
    -moz-transition: all 0.5s ease-in-out;_x000D_
    -o-transition: all 0.5s ease-in-out;_x000D_
    transition: all 0.5s ease-in-out;_x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
_x000D_
_x000D_

Another way to do it is using classes, and setting all the styles in a stylesheet, thus keeping them out of the javascript

document.getElementById('button').onclick = function() {
    document.getElementById('div').classList.toggle('rotated');
}

_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
    document.getElementById('div').classList.toggle('rotated');_x000D_
}
_x000D_
#div {_x000D_
    position:relative; _x000D_
    height: 200px; _x000D_
    width: 200px; _x000D_
    margin: 30px;_x000D_
    background: red;_x000D_
    -webkit-transition: all 0.5s ease-in-out;_x000D_
    -moz-transition: all 0.5s ease-in-out;_x000D_
    -o-transition: all 0.5s ease-in-out;_x000D_
    transition: all 0.5s ease-in-out;_x000D_
}_x000D_
_x000D_
#div.rotated {_x000D_
    -webkit-transform : rotate(66deg); _x000D_
    -moz-transform : rotate(66deg); _x000D_
    -ms-transform : rotate(66deg); _x000D_
    -o-transform : rotate(66deg); _x000D_
    transform : rotate(66deg); _x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
_x000D_
_x000D_

How to compile makefile using MinGW?

You have to actively choose to install MSYS to get the make.exe. So you should always have at least (the native) mingw32-make.exe if MinGW was installed properly. And if you installed MSYS you will have make.exe (in the MSYS subfolder probably).

Note that many projects require first creating a makefile (e.g. using a configure script or automake .am file) and it is this step that requires MSYS or cygwin. Makes you wonder why they bothered to distribute the native make at all.

Once you have the makefile, it is unclear if the native executable requires a different path separator than the MSYS make (forward slashes vs backward slashes). Any autogenerated makefile is likely to have unix-style paths, assuming the native make can handle those, the compiled output should be the same.

What does it mean: The serializable class does not declare a static final serialVersionUID field?

The reasons for warning are documented here, and the simple fixes are to turn off the warning or put the following declaration in your code to supply the version UID. The actual value is not relevant, start with 999 if you like, but changing it when you make incompatible changes to the class is.

public class HelloWorldSwing extends JFrame {

        JTextArea m_resultArea = new JTextArea(6, 30);
        private static final long serialVersionUID = 1L;

MySQL SELECT DISTINCT multiple columns

Both your queries are correct and should give you the right answer.

I would suggest the following query to troubleshoot your problem.

SELECT DISTINCT a,b,c,d,count(*) Count FROM my_table GROUP BY a,b,c,d
order by count(*) desc

That is add count(*) field. This will give you idea how many rows were eliminated using the group command.

Laravel 5.2 not reading env file

Tried almost all of the above. Ended up doing

chmod 666 .env

which worked. This problem seems to keep cropping up on the app I inherited however, this most recent time was after adding a .env.testing. Running Laravel 5.8

Could not load file or assembly ... The parameter is incorrect

The problem relates to the .Net runtime version of a referenced class library (expaned references, select the library and check the "Runtime Version". I had a problem with Antlr3.Runtime, after upgrading my visual studio project to v4.5. I used NuGet to uninstall Microsoft ASP.NET Web Optimisation Framework (due to a chain of dependencies that prevented me from uninstalling Antlr3 directly)

I then used NuGet to reinstall the Microsoft ASP.NET Web Optimisation Framework. This reinstalled the correct runtime versions.

How does one represent the empty char?

To represent the fact that the value is not present you have two choices:

1) If the whole char range is meaningful and you cannot reserve any value, then use char* instead of char:

char** c = new char*[N];
c[0] = NULL; // no character
*c[1] = ' '; // ordinary character
*c[2] = 'a'; // ordinary character
*c[3] = '\0' // zero-code character

Then you'll have c[i] == NULL for when character is not present and otherwise *c[i] for ordinary characters.

2) If you don't need some values representable in char then reserve one for indicating that value is not present, for example the '\0' character.

char* c = new char[N];
c[0] = '\0'; // no character
c[1] = ' '; // ordinary character
c[2] = 'a'; // ordinary character

Then you'll have c[i] == '\0' for when character is not present and ordinary characters otherwise.

Excluding directory when creating a .tar.gz file

Yes, remove the trailing / and (at least in ubuntu 11.04) all the paths given must be relative or full path. You can't mix absolute and relative paths in the same command.

sudo tar -czvf 2011.10.24.tar.gz ./start-directory --exclude "home/user/start-directory/logs"

will not exclude logs directory but

sudo tar -czvf 2011.10.24.tar.gz ./start-directory --exclude "./start-directory/logs"

will work

Appending an id to a list if not already present in a string

Your list just contains a string. Convert it to integer IDs:

L = ['350882 348521 350166\r\n']

ids = [int(i) for i in L[0].strip().split()]
print(ids)
id = 348521
if id not in ids:
    ids.append(id)
print(ids)
id = 348522
if id not in ids:
    ids.append(id)
print(ids)
# Turn it back into your odd format
L = [' '.join(str(id) for id in ids) + '\r\n']
print(L)

Output:

[350882, 348521, 350166]
[350882, 348521, 350166]
[350882, 348521, 350166, 348522]
['350882 348521 350166 348522\r\n']

ASP.NET Web API session or something?

Well, REST by design is stateless. By adding session (or anything else of that kind) you are making it stateful and defeating any purpose of having a RESTful API.

The whole idea of RESTful service is that every resource is uniquely addressable using a universal syntax for use in hypermedia links and each HTTP request should carry enough information by itself for its recipient to process it to be in complete harmony with the stateless nature of HTTP".

So whatever you are trying to do with Web API here, should most likely be re-architectured if you wish to have a RESTful API.

With that said, if you are still willing to go down that route, there is a hacky way of adding session to Web API, and it's been posted by Imran here http://forums.asp.net/t/1780385.aspx/1

Code (though I wouldn't really recommend that):

public class MyHttpControllerHandler
  : HttpControllerHandler, IRequiresSessionState
{
    public MyHttpControllerHandler(RouteData routeData): base(routeData)
    { }
}

public class MyHttpControllerRouteHandler : HttpControllerRouteHandler
{
    protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        return new MyHttpControllerHandler(requestContext.RouteData);
    }
}

public class ValuesController : ApiController
{
   public string GET(string input)
   {
       var session = HttpContext.Current.Session;
       if (session != null)
       {
           if (session["Time"] == null)
           {
               session["Time"] = DateTime.Now;
           }
           return "Session Time: " + session["Time"] + input;
       }
       return "Session is not availabe" + input;
    }
}

and then add the HttpControllerHandler to your API route:

route.RouteHandler = new MyHttpControllerRouteHandler();

How to create an array containing 1...N

Let's share mine :p

Math.pow(2, 10).toString(2).split('').slice(1).map((_,j) => ++j)

google-services.json for different productFlavors

Simplifying what @Scotti said. You need to create Multiples apps with different package name for a particular Project depending on the product flavor.

Suppose your Project is ABC having different product flavors X,Y where X has a package name com.x and Y has a package name com.y then in the firebase console you need to create a project ABC in which you need to create 2 apps with the package names com.x and com.y. Then you need to download the google-services.json file in which there will be 2 client-info objects which will contain those pacakges and you will be good to go.

Snippet of the json would be something like this

{
  "client": [
    {
      "client_info": {
        "android_client_info": {
          "package_name": "com.x"
        }

    {
      "client_info": {
        "android_client_info": {
          "package_name": "com.y"
        }
      ]

    }

How do I get the Git commit count?

The following command prints the total number of commits on the current branch.

git shortlog -s -n  | awk '{ sum += $1; } END { print sum; }' "$@"

It is made up of two parts:

  1. Print the total logs number grouped by author (git shortlog -s -n)

    Example output

      1445  John C
      1398  Tom D
      1376  Chrsitopher P
       166  Justin T
       166  You
    
  2. Sum up the total commit number of each author, i.e. the first argument of each line, and print the result out (awk '{ sum += $1; } END { print sum; }' "$@")

    Using the same example as above it will sum up 1445 + 1398 + 1376 + 166 + 166. Therefore the output will be:

      4,551
    

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

Copied from the stacktrace:

BeanInstantiationException: Could not instantiate bean class [com.gestEtu.project.model.dao.CompteDAOHib]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.gestEtu.project.model.dao.CompteDAOHib.<init>()

By default, Spring will try to instantiate beans by calling a default (no-arg) constructor. The problem in your case is that the implementation of the CompteDAOHib has a constructor with a SessionFactory argument. By adding the @Autowired annotation to a constructor, Spring will attempt to find a bean of matching type, SessionFactory in your case, and provide it as a constructor argument, e.g.

@Autowired
public CompteDAOHib(SessionFactory sessionFactory) {
    // ...
}

How do I include image files in Django templates?

I do understand, that your question was about files stored in MEDIA_ROOT, but sometimes it can be possible to store content in static, when you are not planning to create content of that type anymore.
May be this is a rare case, but anyway - if you have a huge amount of "pictures of the day" for your site - and all these files are on your hard drive?

In that case I see no contra to store such a content in STATIC.
And all becomes really simple:

static

To link to static files that are saved in STATIC_ROOT Django ships with a static template tag. You can use this regardless if you're using RequestContext or not.

{% load static %} <img src="{% static "images/hi.jpg" %}" alt="Hi!" />

copied from Official django 1.4 documentation / Built-in template tags and filters

Python equivalent of a given wget command

There is also a nice Python module named wget that is pretty easy to use. Found here.

This demonstrates the simplicity of the design:

>>> import wget
>>> url = 'http://www.futurecrew.com/skaven/song_files/mp3/razorback.mp3'
>>> filename = wget.download(url)
100% [................................................] 3841532 / 3841532>
>> filename
'razorback.mp3'

Enjoy.

However, if wget doesn't work (I've had trouble with certain PDF files), try this solution.

Edit: You can also use the out parameter to use a custom output directory instead of current working directory.

>>> output_directory = <directory_name>
>>> filename = wget.download(url, out=output_directory)
>>> filename
'razorback.mp3'

How do I count a JavaScript object's attributes?

For those which will read this question/answers, here is a JavaScript implementation of Dictionary collection very similar as functionality as .NET one: JavaScript Dictionary

How can I loop over entries in JSON?

Actually, to query the team_name, just add it in brackets to the last line. Apart from that, it seems to work on Python 2.7.3 on command line.

from urllib2 import urlopen
import json

url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1'
response = urlopen(url)
json_obj = json.load(response)

for i in json_obj['team']:
    print i['team_name']

Get records with max value for each group of grouped SQL results

My solution works only if you need retrieve only one column, however for my needs was the best solution found in terms of performance (it use only one single query!):

SELECT SUBSTRING_INDEX(GROUP_CONCAT(column_x ORDER BY column_y),',',1) AS xyz,
   column_z
FROM table_name
GROUP BY column_z;

It use GROUP_CONCAT in order to create an ordered concat list and then I substring to only the first one.

Converting VS2012 Solution to VS2010

the simplest solution is.....open your website in vs2013 and go to Debug->WebsiteProperties (last option) a new window will open..

in this window go to "Build" option and change .net framework version from 4.5 to 4.0.....then select ok. [note: this step will only work if your project does not have dependencies with vs2013...]

Now open your website in vs2010

What good are SQL Server schemas?

Schemas logically group tables, procedures, views together. All employee-related objects in the employee schema, etc.

You can also give permissions to just one schema, so that users can only see the schema they have access to and nothing else.

Actionbar notification count icon (badge) like Google has

I found a very good solution here, I'm using it with kotlin.

First, in the drawable folder you have to create item_count.xml:

<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="8dp" />
<solid android:color="#f20000" />
<stroke
    android:width="2dip"
    android:color="#FFF" />
<padding
    android:bottom="5dp"
    android:left="5dp"
    android:right="5dp"
    android:top="5dp" />
</shape>

In your Activity_Main Layout some like:

<RelativeLayout
                    android:id="@+id/badgeLayout"
                    android:layout_width="40dp"
                    android:layout_height="40dp"
                    android:layout_toRightOf="@+id/badge_layout1"
                    android:layout_gravity="end|center_vertical"
                    android:layout_marginEnd="5dp">

                <RelativeLayout
                        android:id="@+id/relative_layout1"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content">

                    <Button
                            android:id="@+id/btnBadge"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:background="@mipmap/ic_notification" />

                </RelativeLayout>

                <TextView
                        android:id="@+id/txtBadge"
                        android:layout_width="18dp"
                        android:layout_height="18dp"
                        android:layout_alignRight="@id/relative_layout1"
                        android:background="@drawable/item_count"
                        android:text="22"
                        android:textColor="#FFF"
                        android:textSize="7sp"
                        android:textStyle="bold"
                        android:gravity="center"/>

            </RelativeLayout>

And you can modify like:

btnBadge.setOnClickListener { view ->
        Snackbar.make(view,"badge click", Snackbar.LENGTH_LONG) .setAction("Action", null).show()
        txtBadge.text = "0"
    }

200 PORT command successful. Consider using PASV. 425 Failed to establish connection

You need to use passive mode.

If you're using linux client, use pftp or ftp -p.

From man ftp:

-p    Use passive mode for data transfers. Allows use of ftp in environments where a firewall prevents connections from the outside world back to the client machine. Requires that the ftp server support the PASV command. This is the default if invoked as pftp.

How to use SQL LIKE condition with multiple values in PostgreSQL?

Using array or set comparisons:

create table t (str text);
insert into t values ('AAA'), ('BBB'), ('DDD999YYY'), ('DDD099YYY');

select str from t
where str like any ('{"AAA%", "BBB%", "CCC%"}');

select str from t
where str like any (values('AAA%'), ('BBB%'), ('CCC%'));

It is also possible to do an AND which would not be easy with a regex if it were to match any order:

select str from t
where str like all ('{"%999%", "DDD%"}');

select str from t
where str like all (values('%999%'), ('DDD%'));

Copy array items into another array

There are a number of answers talking about Array.prototype.push.apply. Here is a clear example:

_x000D_
_x000D_
var dataArray1 = [1, 2];_x000D_
var dataArray2 = [3, 4, 5];_x000D_
var newArray = [ ];_x000D_
Array.prototype.push.apply(newArray, dataArray1); // newArray = [1, 2]_x000D_
Array.prototype.push.apply(newArray, dataArray2); // newArray = [1, 2, 3, 4, 5]_x000D_
console.log(JSON.stringify(newArray)); // Outputs: [1, 2, 3, 4, 5]
_x000D_
_x000D_
_x000D_

If you have ES6 syntax:

_x000D_
_x000D_
var dataArray1 = [1, 2];_x000D_
var dataArray2 = [3, 4, 5];_x000D_
var newArray = [ ];_x000D_
newArray.push(...dataArray1); // newArray = [1, 2]_x000D_
newArray.push(...dataArray2); // newArray = [1, 2, 3, 4, 5]_x000D_
console.log(JSON.stringify(newArray)); // Outputs: [1, 2, 3, 4, 5]
_x000D_
_x000D_
_x000D_

Extract images from PDF without resampling, in python?

PikePDF can do this with very little code:

from pikepdf import Pdf, PdfImage

filename = "sample-in.pdf"
example = Pdf.open(filename)

for i, page in enumerate(example.pages):
    for j, (name, raw_image) in enumerate(page.images.items()):
        image = PdfImage(raw_image)
        out = image.extract_to(fileprefix=f"{filename}-page{i:03}-img{j:03}")

extract_to will automatically pick the file extension based on how the image is encoded in the PDF.

If you want, you could also print some detail about the images as they get extracted:

        # Optional: print info about image
        w = raw_image.stream_dict.Width
        h = raw_image.stream_dict.Height
        f = raw_image.stream_dict.Filter
        size = raw_image.stream_dict.Length

        print(f"Wrote {name} {w}x{h} {f} {size:,}B {image.colorspace} to {out}")

which can print something like

Wrote /Im1 150x150 /DCTDecode 5,952B /ICCBased to sample2.pdf-page000-img000.jpg
Wrote /Im10 32x32 /FlateDecode 36B /ICCBased to sample2.pdf-page000-img001.png
...

See the docs for more that you can do with images, including replacing them in the PDF file.

Expand div to max width when float:left is set

Hope I've understood you correctly, take a look at this: http://jsfiddle.net/EAEKc/

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="UTF-8" />_x000D_
  <title>Content with Menu</title>_x000D_
  <style>_x000D_
    .content .left {_x000D_
      float: left;_x000D_
      width: 100px;_x000D_
      background-color: green;_x000D_
    }_x000D_
    _x000D_
    .content .right {_x000D_
      margin-left: 100px;_x000D_
      background-color: red;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div class="content">_x000D_
    <div class="left">_x000D_
      <p>Hi, Flo!</p>_x000D_
    </div>_x000D_
    <div class="right">_x000D_
      <p>is</p>_x000D_
      <p>this</p>_x000D_
      <p>what</p>_x000D_
      <p>you are looking for?</p>_x000D_
    </div>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Doctrine 2: Update query with query builder

Let's say there is an administrator dashboard where users are listed with their id printed as a data attribute so it can be retrieved at some point via JavaScript.

An update could be executed this way …

class UserRepository extends \Doctrine\ORM\EntityRepository
{
    public function updateUserStatus($userId, $newStatus)
    {
        return $this->createQueryBuilder('u')
            ->update()
            ->set('u.isActive', '?1')
            ->setParameter(1, $qb->expr()->literal($newStatus))
            ->where('u.id = ?2')
            ->setParameter(2, $qb->expr()->literal($userId))
            ->getQuery()
            ->getSingleScalarResult()
        ;
    }

AJAX action handling:

# Post datas may be:
# handled with a specific custom formType — OR — retrieved from request object
$userId = (int)$request->request->get('userId');
$newStatus = (int)$request->request->get('newStatus');
$em = $this->getDoctrine()->getManager();
$r = $em->getRepository('NAMESPACE\User')
        ->updateUserStatus($userId, $newStatus);
if ( !empty($r) ){
    # Row updated
}

Working example using Doctrine 2.5 (on top of Symfony3).

How do I center a Bootstrap div with a 'spanX' class?

Update

As of BS3 there's a .center-block helper class. From the docs:

// Classes
.center-block {
  display: block;
  margin-left: auto;
  margin-right: auto;
}

// Usage as mixins
.element {
  .center-block();
}

There is hidden complexity in this seemingly simple problem. All the answers given have some issues.

1. Create a Custom Class (Major Gotcha)

Create .col-centred class, but there is a major gotcha.

.col-centred {
   float: none !important;
   margin: 0 auto;
}

<!-- Bootstrap 3 -->
<div class="col-lg-6 col-centred">
  Centred content.
</div>
<!-- Bootstrap 2 -->
<div class="span-6 col-centred">
  Centred content.
</div>

The Gotcha

Bootstrap requires columns add up to 12. If they do not they will overlap, which is a problem. In this case the centred column will overlap the column above it. Visually the page may look the same, but mouse events will not work on the column being overlapped (you can't hover or click links, for example). This is because mouse events are registering on the centred column that's overlapping the elements you try to click.

The Fixes

You can resolve this issue by using a clearfix element. Using z-index to bring the centred column to the bottom will not work because it will be overlapped itself, and consequently mouse events will work on it.

<div class="row">
  <div class="col-lg-12">
    I get overlapped by `col-lg-7 centered` unless there's a clearfix.
  </div>
  <div class="clearfix"></div>
  <div class="col-lg-7 centred">
  </div>
</div>

Or you can isolate the centred column in its own row.

<div class="row">
  <div class="col-lg-12">
  </div>
</div>
<div class="row">
  <div class="col-lg-7 centred">
    Look I am in my own row.
  </div>
</div>

2. Use col-lg-offset-x or spanx-offset (Major Gotcha)

<!-- Bootstrap 3 -->
<div class="col-lg-6 col-lg-offset-3">
  Centred content.
</div>
<!-- Bootstrap 2 -->
<div class="span-6 span-offset-3">
  Centred content.
</div>

The first problem is that your centred column must be an even number because the offset value must divide evenly by 2 for the layout to be centered (left/right).

Secondly, as some have commented, using offsets is a bad idea. This is because when the browser resizes the offset will turn into blank space, pushing the actual content down the page.

3. Create an Inner Centred Column

This is the best solution in my opinion. No hacking required and you don't mess around with the grid, which could cause unintended consequences, as per solutions 1 and 2.

.col-centred {
   margin: 0 auto;
}

<div class="row">
  <div class="col-lg-12">
    <div class="centred">
        Look I am in my own row.
    </div>
  </div>
</div>

How do I reference a local image in React?

import image from './img/one.jpg';

class Icons extends React.Component{
    render(){
      return(
        <img className='profile-image' alt='icon' src={image}/>
    );
    }
}
export default Icons;

CSS background opacity with rgba not working in IE 8

There are mostly all browser support RGBa code in CSS but only IE8 and below level does not support RGBa css code. For This here is solution. For The solution you must follow this code and it’s better to go with it’s sequence otherwise you will not get perfect output as you wish. This code is used by me and it’s mostly perfect. make comment if it’s perfect.

.class
 {
        /* Web browsers that does not support RGBa */
        background: rgb(0, 0, 0);
        /* IE9/FF/chrome/safari supported */
        background: rgba(0, 0, 0, 0.6);
        /* IE 8 suppoerted */
        /* Here some time problem for Hover than you can use background color/image */
        -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#88000000, endColorstr=#88000000)";
        /* Below IE7 supported */
        filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#88000000, endColorstr=#88000000);
 }

Angular2 Error: There is no directive with "exportAs" set to "ngForm"

I had this problem because I had a typo in my template near [(ngModel)]]. Extra bracket. Example:

<input id="descr" name="descr" type="text" required class="form-control width-half"
      [ngClass]="{'is-invalid': descr.dirty && !descr.valid}" maxlength="16" [(ngModel)]]="category.descr"
      [disabled]="isDescrReadOnly" #descr="ngModel">

Java substring: 'string index out of range'

itemdescription is shorter than 38 chars. Which is why the StringOutOfBoundsException is being thrown.

Checking .length() > 0 simply makes sure the String has some not-null value, what you need to do is check that the length is long enough. You could try:

if(itemdescription.length() > 38)
  ...

Remove Array Value By index in jquery

  1. Find the element in array and get its position
  2. Remove using the position

_x000D_
_x000D_
var array = new Array();_x000D_
  _x000D_
array.push('123');_x000D_
array.push('456');_x000D_
array.push('789');_x000D_
                 _x000D_
var _searchedIndex = $.inArray('456',array);_x000D_
alert(_searchedIndex );_x000D_
if(_searchedIndex >= 0){_x000D_
  array.splice(_searchedIndex,1);_x000D_
  alert(array );_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

  • inArray() - helps you to find the position.
  • splice() - helps you to remove the element in that position.

Check if a value is an object in JavaScript

The Ramda functional library has a wonderful function for detecting JavaScript types.

Paraphrasing the full function:

function type(val) {
  return val === null      ? 'Null'      :
         val === undefined ? 'Undefined' :
         Object.prototype.toString.call(val).slice(8, -1);
}

I had to laugh when I realized how simple and beautiful the solution was.

Example usage from Ramda documentation:

R.type({}); //=> "Object"
R.type(1); //=> "Number"
R.type(false); //=> "Boolean"
R.type('s'); //=> "String"
R.type(null); //=> "Null"
R.type([]); //=> "Array"
R.type(/[A-z]/); //=> "RegExp"
R.type(() => {}); //=> "Function"
R.type(undefined); //=> "Undefined"

CentOS 64 bit bad ELF interpreter

Just wanted to add a comment in BRPocock, but I don't have the sufficient privilegies.

So my contribution was for everyone trying to install IBM Integration Toolkit from IBM's Integration Bus bundle.

When you try to run "Installation Manager" command from folder /Integration_Toolkit/IM_Linux (the file to run is "install") you get the error showed in this post.

Further instructions to fix this problem you'll find in this IBM's web page: https://www-304.ibm.com/support/docview.wss?uid=swg21459143

Hope this helps for anybody trying to install that.

How to include a font .ttf using CSS?

You can use font face like this:

@font-face {
  font-family:"Name-Of-Font";
  src: url("yourfont.ttf") format("truetype");
}

How do I convert a C# List<string[]> to a Javascript array?

Many way to Json Parse but i have found most effective way to

 @model  List<string[]>

     <script>

         function DataParse() {
             var model = '@Html.Raw(Json.Encode(Model))';
             var data = JSON.parse(model);  

            for (i = 0; i < data.length; i++) {
            ......
             }

     </script>

How do I get the height and width of the Android Navigation Bar programmatically?

New answer in 2021 comes to the rescue


insipred from Egis's answer:

context.navigationBarHeight

where the extension getter is

val Context.navigationBarHeight: Int
get() {
    val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager

    return if (Build.VERSION.SDK_INT >= 30) {
        windowManager
                .currentWindowMetrics
                .windowInsets
                .getInsets(WindowInsets.Type.navigationBars())
                .bottom

    } else {
        val currentDisplay = try {
            display
        } catch (e: NoSuchMethodError) {
            windowManager.defaultDisplay
        }

        val appUsableSize = Point()
        val realScreenSize = Point()
        currentDisplay?.apply {
            getSize(appUsableSize)
            getRealSize(realScreenSize)
        }

        // navigation bar on the side
        if (appUsableSize.x < realScreenSize.x) {
            return realScreenSize.x - appUsableSize.x
        }

        // navigation bar at the bottom
        return if (appUsableSize.y < realScreenSize.y) {
            realScreenSize.y - appUsableSize.y
        } else 0
    }
}

tested on:

  • emulators with navigation bars
    • pixel 3a (api 30)
    • pixel 2 (api 28)
    • pixel 3 (api 25)
    • pixel 2 (api 21)
  • Xiaomi Poco f2 pro with & without navigation bar(full display)

Open an html page in default browser with VBA?

You can even say:

FollowHyperlink "www.google.com"

If you get Automation Error then use http://:

ThisWorkbook.FollowHyperlink("http://www.google.com")

Getting an "ambiguous redirect" error

put quotes around your variable. If it happens to have spaces, it will give you "ambiguous redirect" as well. also check your spelling

echo $AAAA"     "$DDDD"         "$MOL_TAG  >>  "${OUPUT_RESULTS}"

eg of ambiguous redirect

$ var="file with spaces"
$ echo $AAAA"     "$DDDD"         "$MOL_TAG >> ${var}
bash: ${var}: ambiguous redirect
$ echo $AAAA"     "$DDDD"         "$MOL_TAG >> "${var}"
$ cat file\ with\ spaces
aaaa     dddd         mol_tag

Get the Year/Month/Day from a datetime in php?

Try below code if you want to use php loop to display

<span>
  <select name="birth_month">
    <?php for( $m=1; $m<=12; ++$m ) { 
      $month_label = date('F', mktime(0, 0, 0, $m, 1));
    ?>
      <option value="<?php echo $month_label; ?>"><?php echo $month_label; ?></option>
    <?php } ?>
  </select> 
</span>
<span>
  <select name="birth_day">
    <?php 
      $start_date = 1;
      $end_date   = 31;
      for( $j=$start_date; $j<=$end_date; $j++ ) {
        echo '<option value='.$j.'>'.$j.'</option>';
      }
    ?>
  </select>
</span>
<span>
  <select name="birth_year">
    <?php 
      $year = date('Y');
      $min = $year - 60;
      $max = $year;
      for( $i=$max; $i>=$min; $i-- ) {
        echo '<option value='.$i.'>'.$i.'</option>';
      }
    ?>
  </select>
</span>

Sending a JSON HTTP POST request from Android

try some thing like blow:

SString otherParametersUrServiceNeed =  "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";

URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();   
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);

   JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

wr.writeBytes(jsonParam.toString());

wr.flush();
wr.close();

References :

  1. http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
  2. Java - sending HTTP parameters via POST method easily

jQuery $.cookie is not a function

Here are all the possible problems/solutions I have come across:

1. Download the cookie plugin

$.cookie is not a standard jQuery function and the plugin needs to be downloaded here. Make sure to include the appropriate <script> tag where necessary (see next).

2. Include jQuery before the cookie plugin

When including the cookie script, make sure to include jQuery FIRST, then the cookie plugin.

<script src="~/Scripts/jquery-2.0.3.js" type="text/javascript"></script>
<script src="~/Scripts/jquery_cookie.js" type="text/javascript"></script>

3. Don't include jQuery more than once

This was my problem. Make sure you aren't including jQuery more than once. If you are, it is possible that:

  1. jQuery loads correctly.
  2. The cookie plugin loads correctly.
  3. Your second inclusion of jQuery overwrites the first and destroys the cookie plugin.

For anyone using ASP.Net MVC projects, be careful with the default javascript bundle inclusions. My second inclusion of jQuery was within one of my global layout pages under the line @Scripts.Render("~/bundles/jquery").

4. Rename the plugin file to not include ".cookie"

In some rare cases, renaming the file to something that does NOT include ".cookie" has fixed this error, apparently due to web server issues. By default, the downloaded script is titled "jquery.cookie.js" but try renaming it to something like "jquery_cookie.js" as shown above. More details on this problem are here.

How to convert map to url query string?

Another 'one class'/no dependency way of doing it, handling single/multiple:

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class UrlQueryString {
  private static final String DEFAULT_ENCODING = "UTF-8";

  public static String buildQueryString(final LinkedHashMap<String, Object> map) {
    try {
      final Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
      final StringBuilder sb = new StringBuilder(map.size() * 8);
      while (it.hasNext()) {
        final Map.Entry<String, Object> entry = it.next();
        final String key = entry.getKey();
        if (key != null) {
          sb.append(URLEncoder.encode(key, DEFAULT_ENCODING));
          sb.append('=');
          final Object value = entry.getValue();
          final String valueAsString = value != null ? URLEncoder.encode(value.toString(), DEFAULT_ENCODING) : "";
          sb.append(valueAsString);
          if (it.hasNext()) {
            sb.append('&');
          }
        } else {
          // Do what you want...for example:
          assert false : String.format("Null key in query map: %s", map.entrySet());
        }
      }
      return sb.toString();
    } catch (final UnsupportedEncodingException e) {
      throw new UnsupportedOperationException(e);
    }
  }

  public static String buildQueryStringMulti(final LinkedHashMap<String, List<Object>> map) {
    try {
      final StringBuilder sb = new StringBuilder(map.size() * 8);
      for (final Iterator<Entry<String, List<Object>>> mapIterator = map.entrySet().iterator(); mapIterator.hasNext();) {
        final Entry<String, List<Object>> entry = mapIterator.next();
        final String key = entry.getKey();
        if (key != null) {
          final String keyEncoded = URLEncoder.encode(key, DEFAULT_ENCODING);
          final List<Object> values = entry.getValue();
          sb.append(keyEncoded);
          sb.append('=');
          if (values != null) {
            for (final Iterator<Object> listIt = values.iterator(); listIt.hasNext();) {
              final Object valueObject = listIt.next();
              sb.append(valueObject != null ? URLEncoder.encode(valueObject.toString(), DEFAULT_ENCODING) : "");
              if (listIt.hasNext()) {
                sb.append('&');
                sb.append(keyEncoded);
                sb.append('=');
              }
            }
          }
          if (mapIterator.hasNext()) {
            sb.append('&');
          }
        } else {
          // Do what you want...for example:
          assert false : String.format("Null key in query map: %s", map.entrySet());
        }
      }
      return sb.toString();
    } catch (final UnsupportedEncodingException e) {
      throw new UnsupportedOperationException(e);
    }
  }

  public static void main(final String[] args) {
    // Examples: could be turned into unit tests ...
    {
      final LinkedHashMap<String, Object> queryItems = new LinkedHashMap<String, Object>();
      queryItems.put("brand", "C&A");
      queryItems.put("count", null);
      queryItems.put("misc", 42);
      final String buildQueryString = buildQueryString(queryItems);
      System.out.println(buildQueryString);
    }
    {
      final LinkedHashMap<String, List<Object>> queryItems = new LinkedHashMap<String, List<Object>>();
      queryItems.put("usernames", new ArrayList<Object>(Arrays.asList(new String[] { "bob", "john" })));
      queryItems.put("nullValue", null);
      queryItems.put("misc", new ArrayList<Object>(Arrays.asList(new Integer[] { 1, 2, 3 })));
      final String buildQueryString = buildQueryStringMulti(queryItems);
      System.out.println(buildQueryString);
    }
  }
}

You may use either simple (easier to write in most cases) or multiple when required. Note that both can be combined by adding an ampersand... If you find any problems let me know in the comments.

How to center align the ActionBar title in Android?

Best and easiest way, specifically for those who just want text view with gravity center without any xml layout.

AppCompatTextView mTitleTextView = new AppCompatTextView(getApplicationContext());
        mTitleTextView.setSingleLine();
        ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
        layoutParams.gravity = Gravity.CENTER;
        actionBar.setCustomView(mTitleTextView, layoutParams);
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_HOME_AS_UP);
        mTitleTextView.setText(text);
        mTitleTextView.setTextAppearance(getApplicationContext(), android.R.style.TextAppearance_Medium);

C++ template constructor

template<class...>struct types{using type=types;};
template<class T>struct tag{using type=T;};
template<class Tag>using type_t=typename Tag::type;

the above helpers let you work with types as values.

class A {
  template<class T>
  A( tag<T> );
};

the tag<T> type is a variable with no state besides the type it caries. You can use this to pass a pure-type value into a template function and have the type be deduced by the template function:

auto a = A(tag<int>{});

You can pass in more than one type:

class A {
  template<class T, class U, class V>
  A( types<T,U,V> );
};
auto a = A(types<int,double,std::string>{});

Android overlay a view ontop of everything?

Simply use RelativeLayout or FrameLayout. The last child view will overlay everything else.

Android supports a pattern which Cocoa Touch SDK doesn't: Layout management.
Layout for iPhone means to position everything absolute (besides some strech factors). Layout in android means that children will be placed in relation to eachother.

Example (second EditText will completely cover the first one):

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/root_view">

    <EditText
        android:layout_width="fill_parent"
        android:id="@+id/editText1"
        android:layout_height="fill_parent">
    </EditText>

    <EditText
        android:layout_width="fill_parent"
        android:id="@+id/editText2"
        android:layout_height="fill_parent">
        <requestFocus></requestFocus>
    </EditText>

</FrameLayout>

FrameLayout is some kind of view stack. Made for special cases.

RelativeLayout is pretty powerful. You can define rules like View A has to align parent layout bottom, View B has to align A bottom to top, etc

Update based on comment

Usually you set the content with setContentView(R.layout.your_layout) in onCreate (it will inflate the layout for you). You can do that manually and call setContentView(inflatedView), there's no difference.

The view itself might be a single view (like TextView) or a complex layout hierarchy (nested layouts, since all layouts are views themselves).

After calling setContentView your activity knows what its content looks like and you can use (FrameLayout) findViewById(R.id.root_view) to retrieve any view int this hierarchy (General pattern (ClassOfTheViewWithThisId) findViewById(R.id.declared_id_of_view)).

Trigger to fire only if a condition is met in SQL Server

For triggers in general, you need to use a cursor to handle inserts or updates of multiple rows. For example:

DECLARE @Attribute;
DECLARE @ParameterValue;
DECLARE mycursor CURSOR FOR SELECT Attribute, ParameterValue FROM inserted;
OPEN mycursor;
FETCH NEXT FROM mycursor into @Attribute, @ParameterValue;
WHILE @@FETCH_STATUS = 0
BEGIN

If @Attribute LIKE 'NoHist_%'
      Begin
          Return
      End

etc.

FETCH NEXT FROM mycursor into @Attribute, @ParameterValue;
END

Triggers, at least in SQL Server, are a big pain and I avoid using them at all.

"Error 1067: The process terminated unexpectedly" when trying to start MySQL

Examine error log (start eventvwr.msc). MySQL typically writes something to the Application log.

In very rare cases it does not write anything (I'm only aware of one particular bug http://bugs.mysql.com/bug.php?id=56821, where services did not work at all). There is also error log file, normally named .err in the data directory that has the same info as written to windows error log.

C# Create New T()

Take a look at new Constraint

public class MyClass<T> where T : new()
{
    protected T GetObject()
    {
        return new T();
    }
}

T could be a class that does not have a default constructor: in this case new T() would be an invalid statement. The new() constraint says that T must have a default constructor, which makes new T() legal.

You can apply the same constraint to a generic method:

public static T GetObject<T>() where T : new()
{
    return new T();
}

If you need to pass parameters:

protected T GetObject(params object[] args)
{
    return (T)Activator.CreateInstance(typeof(T), args);
}

How to store arrays in MySQL?

Use database field type BLOB to store arrays.

Ref: http://us.php.net/manual/en/function.serialize.php

Return Values

Returns a string containing a byte-stream representation of value that can be stored anywhere.

Note that this is a binary string which may include null bytes, and needs to be stored and handled as such. For example, serialize() output should generally be stored in a BLOB field in a database, rather than a CHAR or TEXT field.

Representing Directory & File Structure in Markdown Syntax

There is an NPM module for this:

npm dree

It allows you to have a representation of a directory tree as a string or an object. Using it with the command line will allow you to save the representation in a txt file.

Example:

$ npm dree parse myDirectory --dest ./generated --name tree

Angular2 - Http POST request parameters

These answers are all outdated for those utilizing the HttpClient rather than Http. I was starting to go crazy thinking, "I have done the import of URLSearchParams but it still doesn't work without .toString() and the explicit header!"

With HttpClient, use HttpParams instead of URLSearchParams and note the body = body.append() syntax to achieve multiple params in the body since we are working with an immutable object:

login(userName: string, password: string): Promise<boolean> {
    if (!userName || !password) {
      return Promise.resolve(false);
    }

    let body: HttpParams = new HttpParams();
    body = body.append('grant_type', 'password');
    body = body.append('username', userName);
    body = body.append('password', password);

    return this.http.post(this.url, body)
      .map(res => {
        if (res) {          
          return true;
        }
        return false;
      })
      .toPromise();
  }

Strip spaces/tabs/newlines - python

Use str.split([sep[, maxsplit]]) with no sep or sep=None:

From docs:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

Demo:

>>> myString.split()
['I', 'want', 'to', 'Remove', 'all', 'white', 'spaces,', 'new', 'lines', 'and', 'tabs']

Use str.join on the returned list to get this output:

>>> ' '.join(myString.split())
'I want to Remove all white spaces, new lines and tabs'

How to change CSS using jQuery?

$(".radioValue").css({"background-color":"-webkit-linear-gradient(#e9e9e9,rgba(255, 255, 255, 0.43137254901960786),#e9e9e9)","color":"#454545", "padding": "8px"});

Difference between a user and a schema in Oracle?

Schema is an encapsulation of DB.objects about an idea/domain of intrest, and owned by ONE user. It then will be shared by other users/applications with suppressed roles. So users need not own a schema, but a schema needs to have an owner.

Email validation using jQuery

As others have mentioned you can use a regex to check if the email address matches a pattern. But you can still have emails that match the pattern but my still bounce or be fake spam emails.

checking with a regex

var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);

checking with a real email validation API

You can use an API which will check if the email address is real and currently active.

var emailAddress = "[email protected]"
response = $.get("https://isitarealemail.com/api/email/validate?email=" +
    emailAddress,
    function responseHandler(data) {
        if (data.status === 'valid') {
            // the email is valid and the mail box is active
        } else {
            // the email is incorrect or unable to be tested.
        }
    })

For more see https://isitarealemail.com or blog post

How to redirect page after click on Ok button on sweet alert?

Best and Simple solution, we can add more events as well!

swal({ title: "WOW!",
 text: "Message!",
 type: "success"}).then(okay => {
   if (okay) {
    window.location.href = "URL";
  }
});

How to select specific columns in laravel eloquent

you can also used findOrFail() method here it's good to used

if the exception is not caught, a 404 HTTP response is automatically sent back to the user. It is not necessary to write explicit checks to return 404 responses when using these method not give a 500 error..

ModelName::findOrFail($id, ['firstName', 'lastName']);

Android Eclipse - Could not find *.apk

None of these things worked for me. I'm trying to access native code through the jni, first with NDK samples. What I found was the build won't run if jarlist.cache is not present in the project bin directory. If I copy one from another project to that location (may need to refresh to see the folder in Eclipse), build works every time.

Imshow: extent and aspect

From plt.imshow() official guide, we know that aspect controls the aspect ratio of the axes. Well in my words, the aspect is exactly the ratio of x unit and y unit. Most of the time we want to keep it as 1 since we do not want to distort out figures unintentionally. However, there is indeed cases that we need to specify aspect a value other than 1. The questioner provided a good example that x and y axis may have different physical units. Let's assume that x is in km and y in m. Hence for a 10x10 data, the extent should be [0,10km,0,10m] = [0, 10000m, 0, 10m]. In such case, if we continue to use the default aspect=1, the quality of the figure is really bad. We can hence specify aspect = 1000 to optimize our figure. The following codes illustrate this method.

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
rng=np.random.RandomState(0)
data=rng.randn(10,10)
plt.imshow(data, origin = 'lower',  extent = [0, 10000, 0, 10], aspect = 1000)

enter image description here

Nevertheless, I think there is an alternative that can meet the questioner's demand. We can just set the extent as [0,10,0,10] and add additional xy axis labels to denote the units. Codes as follows.

plt.imshow(data, origin = 'lower',  extent = [0, 10, 0, 10])
plt.xlabel('km')
plt.ylabel('m')

enter image description here

To make a correct figure, we should always bear in mind that x_max-x_min = x_res * data.shape[1] and y_max - y_min = y_res * data.shape[0], where extent = [x_min, x_max, y_min, y_max]. By default, aspect = 1, meaning that the unit pixel is square. This default behavior also works fine for x_res and y_res that have different values. Extending the previous example, let's assume that x_res is 1.5 while y_res is 1. Hence extent should equal to [0,15,0,10]. Using the default aspect, we can have rectangular color pixels, whereas the unit pixel is still square!

plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10])
# Or we have similar x_max and y_max but different data.shape, leading to different color pixel res.
data=rng.randn(10,5)
plt.imshow(data, origin = 'lower',  extent = [0, 5, 0, 5])

enter image description here enter image description here

The aspect of color pixel is x_res / y_res. setting its aspect to the aspect of unit pixel (i.e. aspect = x_res / y_res = ((x_max - x_min) / data.shape[1]) / ((y_max - y_min) / data.shape[0])) would always give square color pixel. We can change aspect = 1.5 so that x-axis unit is 1.5 times y-axis unit, leading to a square color pixel and square whole figure but rectangular pixel unit. Apparently, it is not normally accepted.

data=rng.randn(10,10)
plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10], aspect = 1.5)

enter image description here

The most undesired case is that set aspect an arbitrary value, like 1.2, which will lead to neither square unit pixels nor square color pixels.

plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10], aspect = 1.2)

enter image description here

Long story short, it is always enough to set the correct extent and let the matplotlib do the remaining things for us (even though x_res!=y_res)! Change aspect only when it is a must.

Posting array from form

When you post that data, it is stored as an array in $_POST.

You could optionally do something like:

<input name="arrayname[item1]">
<input name="arrayname[item2]">
<input name="arrayname[item3]">

Then:

$item1 = $_POST['arrayname']['item1'];
$item2 = $_POST['arrayname']['item2'];
$item3 = $_POST['arrayname']['item3'];

But I fail to see the point.

Disable JavaScript error in WebBrowser control

I just found this :

 private static bool TrySetSuppressScriptErrors(WebBrowser webBrowser, bool value)
    {
        FieldInfo field = typeof(WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);
        if (field != null)
        {
            object axIWebBrowser2 = field.GetValue(webBrowser);
            if (axIWebBrowser2 != null)
            {
                axIWebBrowser2.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, axIWebBrowser2, new object[] { value });
                return true;
            }
        }

        return false;
    }

usage example to set webBrowser to silent : TrySetSuppressScriptErrors(webBrowser,true)

How to 'foreach' a column in a DataTable using C#?

You can do it like this:

DataTable dt = new DataTable("MyTable");

foreach (DataRow row in dt.Rows)
{
    foreach (DataColumn column in dt.Columns)
    {
        if (row[column] != null) // This will check the null values also (if you want to check).
        {
               // Do whatever you want.
        }
     }
}

A better way to check if a path exists or not in PowerShell

Another option is to use IO.FileInfo which gives you so much file info it make life easier just using this type:

PS > mkdir C:\Temp
PS > dir C:\Temp\
PS > [IO.FileInfo] $foo = 'C:\Temp\foo.txt'
PS > $foo.Exists
False
PS > New-TemporaryFile | Move-Item -Destination C:\Temp\foo.txt
PS > $foo.Refresh()
PS > $foo.Exists
True
PS > $foo | Select-Object *


Mode              : -a----
VersionInfo       : File:             C:\Temp\foo.txt
                    InternalName:
                    OriginalFilename:
                    FileVersion:
                    FileDescription:
                    Product:
                    ProductVersion:
                    Debug:            False
                    Patched:          False
                    PreRelease:       False
                    PrivateBuild:     False
                    SpecialBuild:     False
                    Language:

BaseName          : foo
Target            : {}
LinkType          :
Length            : 0
DirectoryName     : C:\Temp
Directory         : C:\Temp
IsReadOnly        : False
FullName          : C:\Temp\foo.txt
Extension         : .txt
Name              : foo.txt
Exists            : True
CreationTime      : 2/27/2019 8:57:33 AM
CreationTimeUtc   : 2/27/2019 1:57:33 PM
LastAccessTime    : 2/27/2019 8:57:33 AM
LastAccessTimeUtc : 2/27/2019 1:57:33 PM
LastWriteTime     : 2/27/2019 8:57:33 AM
LastWriteTimeUtc  : 2/27/2019 1:57:33 PM
Attributes        : Archive

More details on my blog.

Find the files that have been changed in last 24 hours

You can do that with

find . -mtime 0

From man find:

[The] time since each file was last modified is divided by 24 hours and any remainder is discarded. That means that to match -mtime 0, a file will have to have a modification in the past which is less than 24 hours ago.

Reporting (free || open source) Alternatives to Crystal Reports in Winforms

If you are using Sql Server (any edition, even express) then you can install Sql Server Reporting Services. This allows the creation of reports through a visual studio plugin, or through a browser control and can export the reports in a variety of formats, including PDF. You can view the reports through the winforms report viewer control which is included, or take advantage of all of the built in generated web content.

The learning curve is not very steep at all if you are used to using datasets in Visual Studio.

jQuery - Follow the cursor with a DIV

You can't follow the cursor with a DIV, but you can draw a DIV when moving the cursor!

$(document).on('mousemove', function(e){
    $('#your_div_id').css({
       left:  e.pageX,
       top:   e.pageY
    });
});

That div must be off the float, so position: absolute should be set.

What is the best way to seed a database in Rails?

Usually there are 2 types of seed data required.

  • Basic data upon which the core of your application may rely. I call this the common seeds.
  • Environmental data, for example to develop the app it is useful to have a bunch of data in a known state that us can use for working on the app locally (the Factory Girl answer above covers this kind of data).

In my experience I was always coming across the need for these two types of data. So I put together a small gem that extends Rails' seeds and lets you add multiple common seed files under db/seeds/ and any environmental seed data under db/seeds/ENV for example db/seeds/development.

I have found this approach is enough to give my seed data some structure and gives me the power to setup my development or staging environment in a known state just by running:

rake db:setup

Fixtures are fragile and flakey to maintain, as are regular sql dumps.

How do I convert uint to int in C#?

uint i = 10;
int j = (int)i;

or

int k = Convert.ToInt32(i)

How To Define a JPA Repository Query with a Join

You are experiencing this issue for two reasons.

  • The JPQL Query is not valid.
  • You have not created an association between your entities that the underlying JPQL query can utilize.

When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)

User.java

@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="iduser")
    private Long idUser;

    @Column(name="user_name")
    private String userName;

    @OneToOne()
    @JoinColumn(name="idarea")
    private Area area;

    public Long getIdUser() {
        return idUser;
    }

    public void setIdUser(Long idUser) {
        this.idUser = idUser;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Area getArea() {
        return area;
    }

    public void setArea(Area area) {
        this.area = area;
    }
}

Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:

@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")

While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.

Area.java

@Entity
@Table(name = "area")
public class Area {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="idarea")
    private Long idArea;

    @Column(name="area_name")
    private String areaName;

    @OneToOne(fetch=FetchType.LAZY, mappedBy="area")
    private User user;

    public Long getIdArea() {
        return idArea;
    }

    public void setIdArea(Long idArea) {
        this.idArea = idArea;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

C# Double - ToString() formatting with two decimal places but no rounding

Following can be used for display only which uses the property of String ..

double value = 123.456789;
String.Format("{0:0.00}", value);

No String-argument constructor/factory method to deserialize from String value ('')

Try setting mapper.configure(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)

or

mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

depending on your Jackson version.

C# Wait until condition is true

Ended up writing this today and seems to be ok. Your usage could be:

await TaskEx.WaitUntil(isExcelInteractive);

code (including the inverse operation)

public static class TaskEx
{
    /// <summary>
    /// Blocks while condition is true or timeout occurs.
    /// </summary>
    /// <param name="condition">The condition that will perpetuate the block.</param>
    /// <param name="frequency">The frequency at which the condition will be check, in milliseconds.</param>
    /// <param name="timeout">Timeout in milliseconds.</param>
    /// <exception cref="TimeoutException"></exception>
    /// <returns></returns>
    public static async Task WaitWhile(Func<bool> condition, int frequency = 25, int timeout = -1)
    {
        var waitTask = Task.Run(async () =>
        {
            while (condition()) await Task.Delay(frequency);
        });

        if(waitTask != await Task.WhenAny(waitTask, Task.Delay(timeout)))
            throw new TimeoutException();
    }

    /// <summary>
    /// Blocks until condition is true or timeout occurs.
    /// </summary>
    /// <param name="condition">The break condition.</param>
    /// <param name="frequency">The frequency at which the condition will be checked.</param>
    /// <param name="timeout">The timeout in milliseconds.</param>
    /// <returns></returns>
    public static async Task WaitUntil(Func<bool> condition, int frequency = 25, int timeout = -1)
    {
        var waitTask = Task.Run(async () =>
        {
            while (!condition()) await Task.Delay(frequency);
        });

        if (waitTask != await Task.WhenAny(waitTask, 
                Task.Delay(timeout))) 
            throw new TimeoutException();
    }
}

Example usage: https://dotnetfiddle.net/Vy8GbV

Send multipart/form-data files with angular using $http

Here's an updated answer for Angular 4 & 5. TransformRequest and angular.identity were dropped. I've also included the ability to combine files with JSON data in one request.

Angular 5 Solution:

import {HttpClient} from '@angular/common/http';

uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
  // Note that setting a content-type header
  // for mutlipart forms breaks some built in
  // request parsers like multer in express.
  const options = {} as any; // Set any options you like
  const formData = new FormData();

  // Append files to the virtual form.
  for (const file of files) {
    formData.append(file.name, file)
  }

  // Optional, append other kev:val rest data to the form.
  Object.keys(restObj).forEach(key => {
    formData.append(key, restObj[key]);
  });

  // Send it.
  return this.httpClient.post(uploadUrl, formData, options)
    .toPromise()
    .catch((e) => {
      // handle me
    });
}

Angular 4 Solution:

// Note that these imports below are deprecated in Angular 5
import {Http, RequestOptions} from '@angular/http';

uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
  // Note that setting a content-type header
  // for mutlipart forms breaks some built in
  // request parsers like multer in express.
  const options = new RequestOptions();
  const formData = new FormData();

  // Append files to the virtual form.
  for (const file of files) {
    formData.append(file.name, file)
  }

  // Optional, append other kev:val rest data to the form.
  Object.keys(restObj).forEach(key => {
    formData.append(key, restObj[key]);
  });

  // Send it.
  return this.http.post(uploadUrl, formData, options)
    .toPromise()
    .catch((e) => {
      // handle me
    });
}

Using "If cell contains" in VBA excel

Requirement:
Find a cell containing the word TOTAL then to enter a dash in the cell below it.

Solution: This solution uses the Find method of the Range object, as it seems appropriate to use it rather than brute force (For…Next loop). For explanation and details about the method see Range.Find method (Excel)

Implementation:
In order to provide flexibility the Find method is wrapped in this function:

Function Range_ƒFind_Action(sWhat As String, rTrg As Range) As Boolean

Where:
sWhat: contains the string to search for
rTrg: is the range to be searched

The function returns True if any match is found, otherwise it returns False

Additionally, every time the function finds a match it passes the resulting range to the procedure Range_Find_Action to execute the required action, (i.e. "enter a dash in the cell below it"). The "required action" is in a separated procedure to allow for customization and flexibility.

This is how the function is called:

This test is searching for "total" to show the effect of the MatchCase:=False. The match can be made case sensitive by changing it to MatchCase:=True

Sub Range_Find_Action_TEST()
Dim sWhat As String, rTrg As Range
Dim sMsgbdy As String
    sWhat = "total"                                             'String to search for (update as required)
    Rem Set rTrg = ThisWorkbook.Worksheets("Sht(0)").UsedRange  'Range to Search (use this to search all used cells)
    Set rTrg = ThisWorkbook.Worksheets("Sht(0)").Rows(6)        'Range to Search (update as required)
    sMsgbdy = IIf(Range_ƒFind_Action(sWhat, rTrg), _
        "Cells found were updated successfully", _
        "No cells were found.")
    MsgBox sMsgbdy, vbInformation, "Range_ƒFind_Action"
    End Sub

This is the Find function

Function Range_ƒFind_Action(sWhat As String, rTrg As Range) As Boolean
Dim rCll As Range, s1st As String
    With rTrg

        Rem Set First Cell Found
        Set rCll = .Find(What:=sWhat, After:=.Cells(1), _
            LookIn:=xlFormulas, LookAt:=xlPart, _
            SearchOrder:=xlByRows, SearchDirection:=xlNext, _
            MatchCase:=False, SearchFormat:=False)

        Rem Validate First Cell
        If rCll Is Nothing Then Exit Function
        s1st = rCll.Address

        Rem Perform Action
        Call Range_Find_Action(rCll)

        Do
            Rem Find Other Cells
            Set rCll = .FindNext(After:=rCll)
            Rem Validate Cell vs 1st Cell
            If rCll.Address <> s1st Then Call Range_Find_Action(rCll)

        Loop Until rCll.Address = s1st

    End With

    Rem Set Results
    Range_ƒFind_Action = True

    End Function

This is the Action procedure

Sub Range_Find_Action(rCll)
    rCll.Offset(1).Value2 = Chr(167)    'Update as required - Using `§` instead of "-" for visibilty purposes
    End Sub

enter image description here

How to subtract hours from a date in Oracle so it affects the day also

Try this:

SELECT to_char(sysdate - (2 / 24), 'MM-DD-YYYY HH24') FROM DUAL

To test it using a new date instance:

SELECT to_char(TO_DATE('11/06/2015 00:00','dd/mm/yyyy HH24:MI') - (2 / 24), 'MM-DD-YYYY HH24:MI') FROM DUAL

Output is: 06-10-2015 22:00, which is the previous day.

Synchronization vs Lock

Many answers here recommend using synchronized.

However, it depends on the usecase.

The synchronized keyword has naturally built in language support. This can mean the JIT can optimise synchronised blocks in ways it cannot with Locks. e.g. it can combine synchronized blocks. Only one thread is allowed to access only one method at any given point of time using a synchronized block. This is a very expensive operation.

Locks avoid this by allowing configuration of various locks for different purpose. One can have couple of methods synchronized under one lock and other methods under a different lock. This allows more concurrency and also increases overall performance.

So, for a smaller system which can do without concurrency and allowing one thread to execute an operation, synchronized can work. Otherwise, lock can be taken on the key.

How to disassemble a memory range with GDB?

If all that you want is to see the disassembly with the INTC call, use objdump -d as someone mentioned but use the -static option when compiling. Otherwise the fopen function is not compiled into the elf and is linked at runtime.

How do I stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?

You might want to check your CSS. In the example here: https://css-tricks.com/the-checkbox-hack/ there's position: absolute; top: -9999px;. This is particularly goofy on Chrome, as onclick="whatever" still jumps to the absolute position of the clicked element.

Removing position: absolute; top: -9999px;, for display: none; might help.

search in java ArrayList

You're missing the return statement because if your list size is 0, the for loop will never execute, thus the if will never run, and thus you will never return.

Move the if statement out of the loop.

Find a string by searching all tables in SQL Server Management Studio 2008

There's no need for nested looping (outer looping through tables and inner looping through all table columns). One can retrieve all (or arbitrary selected/filtered) table-column combinations from INFORMATION_SCHEMA.COLUMNS and in one loop simply pass through (search) all of them:

DECLARE @search VARCHAR(100), @table SYSNAME, @column SYSNAME

DECLARE curTabCol CURSOR FOR
    SELECT c.TABLE_SCHEMA + '.' + c.TABLE_NAME, c.COLUMN_NAME
    FROM INFORMATION_SCHEMA.COLUMNS c
    JOIN INFORMATION_SCHEMA.TABLES t 
      ON t.TABLE_NAME=c.TABLE_NAME AND t.TABLE_TYPE='BASE TABLE' -- avoid views
    WHERE c.DATA_TYPE IN ('varchar','nvarchar') -- searching only in these column types
    --AND c.COLUMN_NAME IN ('NAME','DESCRIPTION') -- searching only in these column names

SET @search='john'

OPEN curTabCol
FETCH NEXT FROM curTabCol INTO @table, @column

WHILE (@@FETCH_STATUS = 0)
BEGIN
    EXECUTE('IF EXISTS 
             (SELECT * FROM ' + @table + ' WHERE ' + @column + ' = ''' + @search + ''') 
             PRINT ''' + @table + '.' + @column + '''')
    FETCH NEXT FROM curTabCol INTO @table, @column
END

CLOSE curTabCol
DEALLOCATE curTabCol

Get cookie by name

function getCookie(name) {
    var pair = document.cookie.split('; ').find(x => x.startsWith(name+'='));
    if (pair)
       return pair.split('=')[1]
}

Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss

I was trying to format the date string received from a JSON response e.g. 2016-03-09T04:50:00-0800 to yyyy-MM-dd. So here's what I tried and it worked and helped me assign the formatted date string a calendar widget.

String DATE_FORMAT_I = "yyyy-MM-dd'T'HH:mm:ss";
String DATE_FORMAT_O = "yyyy-MM-dd";


SimpleDateFormat formatInput = new SimpleDateFormat(DATE_FORMAT_I);
SimpleDateFormat formatOutput = new SimpleDateFormat(DATE_FORMAT_O);

Date date = formatInput.parse(member.getString("date"));
String dateString = formatOutput.format(date);

This worked. Thanks.

Read specific columns from a csv file with csv module?

import csv
from collections import defaultdict

columns = defaultdict(list) # each value in each column is appended to a list

with open('file.txt') as f:
    reader = csv.DictReader(f) # read rows into a dictionary format
    for row in reader: # read a row as {column1: value1, column2: value2,...}
        for (k,v) in row.items(): # go over each column name and value 
            columns[k].append(v) # append the value into the appropriate list
                                 # based on column name k

print(columns['name'])
print(columns['phone'])
print(columns['street'])

With a file like

name,phone,street
Bob,0893,32 Silly
James,000,400 McHilly
Smithers,4442,23 Looped St.

Will output

>>> 
['Bob', 'James', 'Smithers']
['0893', '000', '4442']
['32 Silly', '400 McHilly', '23 Looped St.']

Or alternatively if you want numerical indexing for the columns:

with open('file.txt') as f:
    reader = csv.reader(f)
    reader.next()
    for row in reader:
        for (i,v) in enumerate(row):
            columns[i].append(v)
print(columns[0])

>>> 
['Bob', 'James', 'Smithers']

To change the deliminator add delimiter=" " to the appropriate instantiation, i.e reader = csv.reader(f,delimiter=" ")

Python: maximum recursion depth exceeded while calling a Python object

Python don't have a great support for recursion because of it's lack of TRE (Tail Recursion Elimination).

This means that each call to your recursive function will create a function call stack and because there is a limit of stack depth (by default is 1000) that you can check out by sys.getrecursionlimit (of course you can change it using sys.setrecursionlimit but it's not recommended) your program will end up by crashing when it hits this limit.

As other answer has already give you a much nicer way for how to solve this in your case (which is to replace recursion by simple loop) there is another solution if you still want to use recursion which is to use one of the many recipes of implementing TRE in python like this one.

N.B: My answer is meant to give you more insight on why you get the error, and I'm not advising you to use the TRE as i already explained because in your case a loop will be much better and easy to read.

"The semaphore timeout period has expired" error for USB connection

I had a similar problem which I solved by changing the Port Settings in the port driver (located in Ports in device manager) to fit the device I was using.

For me it was that wrong Bits per second value was set.

Define a global variable in a JavaScript function

It is very simple. Define the trailimage variable outside the function and set its value in the makeObj function. Now you can access its value from anywhere.

var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;
var trailimage;

function makeObj(address) {
    trailimage = [address, 50, 50];
    ...
}

Checking whether the pip is installed?

If you are on a linux machine running Python 2 you can run this commands:

1st make sure python 2 is installed:

python2 --version

2nd check to see if pip is installed:

pip --version

If you are running Python 3 you can run this command:

1st make sure python 3 is installed:

python3 --version

2nd check to see if pip3 is installed:

pip3 --version

If you do not have pip installed you can run these commands to install pip (it is recommended you install pip for Python 2 and Python 3):

Install pip for Python 2:

sudo apt install python-pip

Then verify if it is installed correctly:

pip --version

Install pip for Python 3:

sudo apt install python3-pip

Then verify if it is installed correctly:

pip3 --version

For more info see: https://itsfoss.com/install-pip-ubuntu/

UPDATE I would like to mention a few things. When working with Django I learned that my Linux install requires me to use python 2.7, so switching my default python version for the python and pip command alias's to python 3 with alias python=python3 is not recommended. Therefore I use the python3 and pip3 commands when installing software like Django 3.0, which works better with Python 3. And I keep their alias's pointed towards whatever Python 3 version I want like so alias python3=python3.8.

Keep In Mind When you are going to use your package in the future you will want to use the pip or pip3 command depending on which one you used to initially install the package. So for example if I wanted to change my change my Django package version I would use the pip3 command and not pip like so, pip3 install Django==3.0.11.

Notice When running checking the packages version for python: $ python -m django --version and python3: $ python3 -m django --version, two different versions of django will show because I installed django v3.0.11 with pip3 and django v1.11.29 with pip.

UUID max character length

Most databases have a native UUID type these days to make working with them easier. If yours doesn't, they're just 128-bit numbers, so you can use BINARY(16), and if you need the text format frequently, e.g. for troubleshooting, then add a calculated column to generate it automatically from the binary column. There is no good reason to store the (much larger) text form.

Docker: Multiple Dockerfiles in project

Add an abstraction layer, for example, a YAML file like in this project https://github.com/larytet/dockerfile-generator which looks like

centos7:
    base: centos:centos7
    packager: rpm
    install:
      - $build_essential_centos 
      - rpm-build
    run:
      - $get_release
    env:
      - $environment_vars

A short Python script/make can generate all Dockerfiles from the configuration file.

MIME types missing in IIS 7 for ASP.NET - 404.17

There are two reasons you might get this message:

  1. ASP.Net is not configured. For this run from Administrator command %FrameworkDir%\%FrameworkVersion%\aspnet_regiis -i. Read the message carefully. On Windows8/IIS8 it may say that this is no longer supported and you may have to use Turn Windows Features On/Off dialog in Install/Uninstall a Program in Control Panel.
  2. Another reason this may happen is because your App Pool is not configured correctly. For example, you created website for WordPress and you also want to throw in few aspx files in there, WordPress creates app pool that says don't run CLR stuff. To fix this just open up App Pool and enable CLR.

Configure cron job to run every 15 minutes on Jenkins

It should be,

*/15 * * * *  your_command_or_whatever

How can I parse a CSV string with JavaScript, which contains comma in data?

PEG(.js) grammar that handles RFC 4180 examples at http://en.wikipedia.org/wiki/Comma-separated_values:

start
  = [\n\r]* first:line rest:([\n\r]+ data:line { return data; })* [\n\r]* { rest.unshift(first); return rest; }

line
  = first:field rest:("," text:field { return text; })*
    & { return !!first || rest.length; } // ignore blank lines
    { rest.unshift(first); return rest; }

field
  = '"' text:char* '"' { return text.join(''); }
  / text:[^\n\r,]* { return text.join(''); }

char
  = '"' '"' { return '"'; }
  / [^"]

Test at http://jsfiddle.net/knvzk/10 or https://pegjs.org/online.

Download the generated parser at https://gist.github.com/3362830.

Match exact string

"^" For the begining of the line "$" for the end of it. Eg.:

var re = /^abc$/;

Would match "abc" but not "1abc" or "abc1". You can learn more at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Set port for php artisan.php serve

you can also add host as well with same command like :

php artisan serve --host=172.10.29.100 --port=8080

Deploying my application at the root in Tomcat

The fastest way.

  1. Make sure you don't have ROOT app deployed, undeploy if you have one

  2. Rename your war to ROOT.war, deploy, thats all, no configuration changes needed

Java, How to add library files in netbeans?

How to import a commons-library into netbeans.

  1. Evaluate the error message in NetBeans:

    java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
    
  2. NoClassDeffFoundError means somewhere under the hood in the code you used, a method called another method which invoked a class that cannot be found. So what that means is your code did this: MyFoobarClass foobar = new MyFoobarClass() and the compiler is confused because nowhere is defined this MyFoobarClass. This is why you get an error.

  3. To know what to do next, you have to look at the error message closely. The words 'org/apache/commons' lets you know that this is the codebase that provides the tools you need. You have a choice, either you can import EVERYTHING in apache commons, or you could import JUST the LogFactory class, or you could do something in between. Like for example just get the logging bit of apache commons.

  4. You'll want to go the middle of the road and get commons-logging. Excellent choice, fire up the google and search for apache commons-logging. The first link takes you to http://commons.apache.org/proper/commons-logging/. Go to downloads. There you will find the most up-to-date ones. If your project was compiled under ancient versions of commons-logging, then use those same ancient ones because if you use the newer ones, the code may fail because the newer versions are different.

  5. You're going to want to download the commons-logging-1.1.3-bin.zip or something to that effect. Read what the name is saying. The .zip means it's a compressed file. commons-logging means that this one should contain the LogFactory class you desire. the middle 1.1.3 means that is the version. if you are compiling for an old version, you'll need to match these up, or else you risk the code not compiling right due to changes due to upgrading.

  6. Download that zip. Unzip it. Search around for things that end in .jar. In netbeans right click your project, click properties, click libraries, click "add jar/folder" and import those jars. Save the project, and re-run, and the errors should be gone.

The binaries don't include the source code, so you won't be able to drill down and see what is happening when you debug. As programmers you should be downloading "the source" of apache commons and compiling from source, generating the jars yourself and importing those for experience. You should be smart enough to understand and correct the source code you are importing. These ancient versions of apache commons might have been compiled under an older version of Java, so if you go too far back, they may not even compile unless you compile them under an ancient version of java.

Counting inversions in an array

Here is one possible solution with variation of binary tree. It adds a field called rightSubTreeSize to each tree node. Keep on inserting number into binary tree in the order they appear in the array. If number goes lhs of node the inversion count for that element would be (1 + rightSubTreeSize). Since all those elements are greater than current element and they would have appeared earlier in the array. If element goes to rhs of a node, just increase its rightSubTreeSize. Following is the code.

Node { 
    int data;
    Node* left, *right;
    int rightSubTreeSize;

    Node(int data) { 
        rightSubTreeSize = 0;
    }   
};

Node* root = null;
int totCnt = 0;
for(i = 0; i < n; ++i) { 
    Node* p = new Node(a[i]);
    if(root == null) { 
        root = p;
        continue;
    } 

    Node* q = root;
    int curCnt = 0;
    while(q) { 
        if(p->data <= q->data) { 
            curCnt += 1 + q->rightSubTreeSize;
            if(q->left) { 
                q = q->left;
            } else { 
                q->left = p;
                break;
            }
        } else { 
            q->rightSubTreeSize++;
            if(q->right) { 
                q = q->right;
            } else { 
                q->right = p;
                break;
            }
        }
    }

    totCnt += curCnt;
  }
  return totCnt;

Parse an HTML string with JS

It's quite simple:

var parser = new DOMParser();
var htmlDoc = parser.parseFromString(txt, 'text/html');
// do whatever you want with htmlDoc.getElementsByTagName('a');

According to MDN, to do this in chrome you need to parse as XML like so:

var parser = new DOMParser();
var htmlDoc = parser.parseFromString(txt, 'text/xml');
// do whatever you want with htmlDoc.getElementsByTagName('a');

It is currently unsupported by webkit and you'd have to follow Florian's answer, and it is unknown to work in most cases on mobile browsers.

Edit: Now widely supported

How do I make a dictionary with multiple keys to one value?

I guess you mean this:

class Value:
    def __init__(self, v=None):
        self.v = v

v1 = Value(1)
v2 = Value(2)

d = {'a': v1, 'b': v1, 'c': v2, 'd': v2}
d['a'].v += 1

d['b'].v == 2 # True
  • Python's strings and numbers are immutable objects,
  • So, if you want d['a'] and d['b'] to point to the same value that "updates" as it changes, make the value refer to a mutable object (user-defined class like above, or a dict, list, set).
  • Then, when you modify the object at d['a'], d['b'] changes at same time because they both point to same object.

Server returned HTTP response code: 401 for URL: https

Try This. You need pass the authentication to let the server know its a valid user. You need to import these two packages and has to include a jersy jar. If you dont want to include jersy jar then import this package

import sun.misc.BASE64Encoder;

import com.sun.jersey.core.util.Base64;
import sun.net.www.protocol.http.HttpURLConnection;

and then,

String encodedAuthorizedUser = getAuthantication("username", "password");
URL url = new URL("Your Valid Jira URL");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty ("Authorization", "Basic " + encodedAuthorizedUser );

 public String getAuthantication(String username, String password) {
   String auth = new String(Base64.encode(username + ":" + password));
   return auth;
 }

Postman - How to see request with headers and body data with variables substituted

As of now, Postman comes with its own "Console." Click the terminal-like icon on the bottom left to open the console. Send a request, and you can inspect the request from within Postman's console.

enter image description here

How to remove single character from a String

For example if you want to calculate how many a's are there in the String, you can do it like this:

if (string.contains("a"))
{
    numberOf_a++;
    string = string.replaceFirst("a", "");
}

How to make a char string from a C macro's value?

He who is Shy* gave you the germ of an answer, but only the germ. The basic technique for converting a value into a string in the C pre-processor is indeed via the '#' operator, but a simple transliteration of the proposed solution gets a compilation error:

#define TEST_FUNC test_func
#define TEST_FUNC_NAME #TEST_FUNC

#include <stdio.h>
int main(void)
{
    puts(TEST_FUNC_NAME);
    return(0);
}

The syntax error is on the 'puts()' line - the problem is a 'stray #' in the source.

In section 6.10.3.2 of the C standard, 'The # operator', it says:

Each # preprocessing token in the replacement list for a function-like macro shall be followed by a parameter as the next preprocessing token in the replacement list.

The trouble is that you can convert macro arguments to strings -- but you can't convert random items that are not macro arguments.

So, to achieve the effect you are after, you most certainly have to do some extra work.

#define FUNCTION_NAME(name) #name
#define TEST_FUNC_NAME  FUNCTION_NAME(test_func)

#include <stdio.h>

int main(void)
{
    puts(TEST_FUNC_NAME);
    return(0);
}

I'm not completely clear on how you plan to use the macros, and how you plan to avoid repetition altogether. This slightly more elaborate example might be more informative. The use of a macro equivalent to STR_VALUE is an idiom that is necessary to get the desired result.

#define STR_VALUE(arg)      #arg
#define FUNCTION_NAME(name) STR_VALUE(name)

#define TEST_FUNC      test_func
#define TEST_FUNC_NAME FUNCTION_NAME(TEST_FUNC)

#include <stdio.h>

static void TEST_FUNC(void)
{
    printf("In function %s\n", TEST_FUNC_NAME);
}

int main(void)
{
    puts(TEST_FUNC_NAME);
    TEST_FUNC();
    return(0);
}

* At the time when this answer was first written, shoosh's name used 'Shy' as part of the name.

How to check if a div is visible state or not?

if (!$('#singlechatpanel-1').css('display') == 'none') {
   alert('visible');
}else{
   alert('hidden');
}

Javascript how to parse JSON array

This is my answer,

<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p>
First Name: <span id="fname"></span><br> 
Last Name: <span id="lname"></span><br> 
</p> 
<script>
var txt = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';

//var jsonData = eval ("(" + txt + ")");
var jsonData = JSON.parse(txt);
for (var i = 0; i < jsonData.employees.length; i++) {
    var counter = jsonData.employees[i];
    //console.log(counter.counter_name);
    alert(counter.firstName);
}

</script>
</body>
</html>

In Angular, What is 'pathmatch: full' and what effect does it have?

The path-matching strategy, one of 'prefix' or 'full'. Default is 'prefix'.

By default, the router checks URL elements from the left to see if the URL matches a given path, and stops when there is a match. For example, '/team/11/user' matches 'team/:id'.

The path-match strategy 'full' matches against the entire URL. It is important to do this when redirecting empty-path routes. Otherwise, because an empty path is a prefix of any URL, the router would apply the redirect even when navigating to the redirect destination, creating an endless loop.

Source : https://angular.io/api/router/Route#properties

ORA-01843 not a valid month- Comparing Dates

If you are using command line tools, then you can also set it in the shell.

On linux, with a sh type shell, you can do for example:

export NLS_TIMESTAMP_FORMAT='DD/MON/RR HH24:MI:SSXFF'

Then you can use the command line tools and it will use the specified format:

/path/to/dbhome_1/bin/sqlldr user/pass@host:port/service control=table.ctl direct=true

Youtube - downloading a playlist - youtube-dl

Removing the v=...& part from the url, and only keep the list=... part. The main problem being the special character &, interpreted by the shell.

You can also quote your 'url' in your command.

More information here (for instance) :

https://askubuntu.com/questions/564567/how-to-download-playlist-from-youtube-dl