Programs & Examples On #Congestion control

Congestion control concerns controlling traffic entry into a telecommunications network, so as to avoid congestive collapse by attempting to avoid oversubscription of any of the processing or link capabilities of the intermediate nodes and networks and taking resource reducing steps, such as reducing the rate of sending packets.

Create sequence of repeated values, in sequence?

For your example, Dirk's answer is perfect. If you instead had a data frame and wanted to add that sort of sequence as a column, you could also use group from groupdata2 (disclaimer: my package) to greedily divide the datapoints into groups.

# Attach groupdata2
library(groupdata2)
# Create a random data frame
df <- data.frame("x" = rnorm(27))
# Create groups with 5 members each (except last group)
group(df, n = 5, method = "greedy")
         x .groups
     <dbl> <fct>  
 1  0.891  1      
 2 -1.13   1      
 3 -0.500  1      
 4 -1.12   1      
 5 -0.0187 1      
 6  0.420  2      
 7 -0.449  2      
 8  0.365  2      
 9  0.526  2      
10  0.466  2      
# … with 17 more rows

There's a whole range of methods for creating this kind of grouping factor. E.g. by number of groups, a list of group sizes, or by having groups start when the value in some column differs from the value in the previous row (e.g. if a column is c("x","x","y","z","z") the grouping factor would be c(1,1,2,3,3).

How to use an arraylist as a prepared statement parameter

why making life hard-

PreparedStatement pstmt = conn.prepareStatement("select * from employee where id in ("+ StringUtils.join(arraylistParameter.iterator(),",") +)");

Finding the indices of matching elements in list in Python

if you're doing a lot of this kind of thing you should consider using numpy.

In [56]: import random, numpy

In [57]: lst = numpy.array([random.uniform(0, 5) for _ in range(1000)]) # example list

In [58]: a, b = 1, 3

In [59]: numpy.flatnonzero((lst > a) & (lst < b))[:10]
Out[59]: array([ 0, 12, 13, 15, 18, 19, 23, 24, 26, 29])

In response to Seanny123's question, I used this timing code:

import numpy, timeit, random

a, b = 1, 3

lst = numpy.array([random.uniform(0, 5) for _ in range(1000)])

def numpy_way():
    numpy.flatnonzero((lst > 1) & (lst < 3))[:10]

def list_comprehension():
    [e for e in lst if 1 < e < 3][:10]

print timeit.timeit(numpy_way)
print timeit.timeit(list_comprehension)

The numpy version is over 60 times faster.

Non-numeric Argument to Binary Operator Error in R

Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.

- is the 'binary operator' your error is referencing, and either CurrentDay or MA (or both) are non-numeric.

A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). + is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).

R only knows how to apply + (and other binary operators, such as -) to numeric arguments:

> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator

When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.

EDIT:

Your error lies in the use of [ instead of [[. Because Day is a list, subsetting with [ will return a list, not a numeric vector. [[, however, returns an object of the class of the item contained in the list:

> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator

> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3

Transaction, as you've defined it, returns a list of two vectors. Above, Day is a list contain one vector. Day2, however, is simply a vector.

Can you break from a Groovy "each" closure?

You could break by RETURN. For example

  def a = [1, 2, 3, 4, 5, 6, 7]
  def ret = 0
  a.each {def n ->
    if (n > 5) {
      ret = n
      return ret
    }
  }

It works for me!

RedirectToAction with parameter

//How to use RedirectToAction in MVC

return RedirectToAction("actionName", "ControllerName", routevalue);

example

return RedirectToAction("Index", "Home", new { id = 2});

Renaming files using node.js

  1. fs.readdir(path, callback)
  2. fs.rename(old,new,callback)

Go through http://nodejs.org/api/fs.html

One important thing - you can use sync functions also. (It will work like C program)

MySQL skip first 10 results

From the manual:

To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter. This statement retrieves all rows from the 96th row to the last:

SELECT * FROM tbl LIMIT 95,18446744073709551615;

Obviously, you should replace 95 by 10. The large number they use is 2^64 - 1, by the way.

Sockets: Discover port availability using Java

I have Tried something Like this and it worked really fine with me

            Socket Skt;
            String host = "localhost";
            int i = 8983; // port no.

                 try {
                    System.out.println("Looking for "+ i);
                    Skt = new Socket(host, i);
                    System.out.println("There is a Server on port "
                    + i + " of " + host);
                 }
                 catch (UnknownHostException e) {
                    System.out.println("Exception occured"+ e);

                 }
                 catch (IOException e) {
                     System.out.println("port is not used");

                 }

Merge / convert multiple PDF files into one PDF

Apache PDFBox http://pdfbox.apache.org/

PDFMerger This application will take a list of pdf documents and merge them, saving the result in a new document.

usage: java -jar pdfbox-app-x.y.z.jar PDFMerger "Source PDF files (2 ..n)" "Target PDF file"

How to encode URL to avoid special characters in Java?

If you don't want to do it manually use Apache Commons - Codec library. The class you are looking at is: org.apache.commons.codec.net.URLCodec

String final url = "http://www.google.com?...."
String final urlSafe = org.apache.commons.codec.net.URLCodec.encode(url);

Android Transparent TextView?

try to set the transparency with the android-studio designer in activity_main.xml. If you want it to be transparent, write it for example like this for white: White: #FFFFFF, with 50% transparency: #80FFFFFF This is for Kotlin tho, not sure if that will work the same way for basic android (java).

SELECT *, COUNT(*) in SQLite

If what you want is the total number of records in the table appended to each row you can do something like

SELECT *
  FROM my_table
  CROSS JOIN (SELECT COUNT(*) AS COUNT_OF_RECS_IN_MY_TABLE
                FROM MY_TABLE)

Get path from open file in Python

I had the exact same issue. If you are using a relative path os.path.dirname(path) will only return the relative path. os.path.realpath does the trick:

>>> import os
>>> f = open('file.txt')
>>> os.path.realpath(f.name)

Instance member cannot be used on type

Sometimes Xcode when overrides methods adds class func instead of just func. Then in static method you can't see instance properties. It is very easy to overlook it. That was my case.

enter image description here

How to make an element width: 100% minus padding?

This is why we have box-sizing in CSS.

I’ve edited your example, and now it works in Safari, Chrome, Firefox, and Opera. Check it out: http://jsfiddle.net/mathias/Bupr3/ All I added was this:

input {
  -webkit-box-sizing: border-box;
     -moz-box-sizing: border-box;
          box-sizing: border-box;
}

Unfortunately older browsers such as IE7 do not support this. If you’re looking for a solution that works in old IEs, check out the other answers.

Builder Pattern in Effective Java

You need to declare the Builder inner class as static.

Consult some documentation for both non-static inner classes and static inner classes.

Basically the non-static inner classes instances cannot exist without attached outer class instance.

Xcode5 "No matching provisioning profiles found issue" (but good at xcode4)

All of drop down lists disappeared in Build Settings after running the Fix Issue in Xcode 5. Spent several days trying to figure out what was wrong with my provisioning profiles and code signing. Found a link Xcode 4 missing drop down lists in Build Settings and sure enough I needed to re-enabled "Show Values" under the Editor menu. Hopefully this helps anyone else in this predicament.

Also, I had to clear my derived data, clean the solution and quit and reopen Xcode into for the code signing identities to correctly appear. My distribution provisioning profiles where showing up as signed by my developer certificate which was incorrect.

How do I fix the indentation of an entire file in Vi?

If you want to reindent the block you're in without having to type any chords, you can do:

[[=]]

How to check if a file exists from a url

    $headers = get_headers((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER[HTTP_HOST] . '/uploads/' . $MAIN['id'] . '.pdf');
    $fileExist = (stripos($headers[0], "200 OK") ? true : false);
    if ($fileExist) {
    ?>
    <a class="button" href="/uploads/<?= $MAIN['id'] ?>.pdf" download>???????</a> 
    <? }
    ?>

check if file exists on remote host with ssh

On CentOS machine, the oneliner bash that worked for me was:

if ssh <servername> "stat <filename> > /dev/null 2>&1"; then echo "file exists"; else echo "file doesnt exits"; fi

It needed I/O redirection (as the top answer) as well as quotes around the command to be run on remote.

Selecting only first-level elements in jquery

Once you have the initial ul, you can use the children() method, which will only consider the immediate children of the element. As @activa points out, one way to easily select the root element is to give it a class or an id. The following assumes you have a root ul with id root.

$('ul#root').children('li');

Git: which is the default configured remote for branch?

the command to get the effective push remote for the branch, e.g., master, is:

git config branch.master.pushRemote || git config remote.pushDefault || git config branch.master.remote

Here's why (from the "man git config" output):

branch.name.remote [...] tells git fetch and git push which remote to fetch from/push to [...] [for push] may be overridden with remote.pushDefault (for all branches) [and] for the current branch [..] further overridden by branch.name.pushRemote [...]

For some reason, "man git push" only tells about branch.name.remote (even though it has the least precedence of the three) + erroneously states that if it is not set, push defaults to origin - it does not, it's just that when you clone a repo, branch.name.remote is set to origin, but if you remove this setting, git push will fail, even though you still have the origin remote

Working copy XXX locked and cleanup failed in SVN

Had the same problem because I exported a folder under a version-controlled folder. Had to delete the folder from TortoiseSVN, then delete the folder from the filesystem (TortoiseSVN does not like unversioned subfolders ... why not???)

How do you know if Tomcat Server is installed on your PC

In case of Windows(in my case XP):-

  1. Check the directory where tomcat is installed.
  2. Open the directory called \conf in it.
  3. Then search file server.xml
  4. Open that file and check what is the connector port for HTTP,whre you will found something like 8009,8080 etc.
  5. Suppose it found 8009,use that port as "/localhost:8009/" in your web-browser with HTTP protocol. Hope this will work !

Proxy with express.js

Ok, here's a ready-to-copy-paste answer using the require('request') npm module and an environment variable *instead of an hardcoded proxy):

coffeescript

app.use (req, res, next) ->                                                 
  r = false
  method = req.method.toLowerCase().replace(/delete/, 'del')
  switch method
    when 'get', 'post', 'del', 'put'
      r = request[method](
        uri: process.env.PROXY_URL + req.url
        json: req.body)
    else
      return res.send('invalid method')
  req.pipe(r).pipe res

javascript:

app.use(function(req, res, next) {
  var method, r;
  method = req.method.toLowerCase().replace(/delete/,"del");
  switch (method) {
    case "get":
    case "post":
    case "del":
    case "put":
      r = request[method]({
        uri: process.env.PROXY_URL + req.url,
        json: req.body
      });
      break;
    default:
      return res.send("invalid method");
  }
  return req.pipe(r).pipe(res);
});

Delete ActionLink with confirm dialog

You can also try this for Html.ActionLink DeleteId

find all unchecked checkbox in jquery

Also it can be achieved with pure js in such a way:

var matches = document.querySelectorAll('input[type="checkbox"]:not(:checked)');

OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow

In these two lines:

mask = cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)

frame = cv2.circle(frame,(a, b),5,color[i].tolist(),-1)

try instead:

cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)

cv2.circle(frame,(a, b),5,color[i].tolist(),-1)

I had the same problem and the variables were being returned empty

Gradle DSL method not found: 'runProguard'

runProguard has been renamed to minifyEnabled in version 0.14.0 (2014/10/31) or more in Gradle.

To fix this, you need to change runProguard to minifyEnabled in the build.gradle file of your project.

enter image description here

http://localhost/ not working on Windows 7. What's the problem?

If you installed it on port 8080, you need to access it on port 8080:

http://localhost:8080 or http://127.0.0.1:8080

Creating a custom JButton in Java

You could always try the Synth look & feel. You provide an xml file that acts as a sort of stylesheet, along with any images you want to use. The code might look like this:

try {
    SynthLookAndFeel synth = new SynthLookAndFeel();
    Class aClass = MainFrame.class;
    InputStream stream = aClass.getResourceAsStream("\\default.xml");

    if (stream == null) {
        System.err.println("Missing configuration file");
        System.exit(-1);                
    }

    synth.load(stream, aClass);

    UIManager.setLookAndFeel(synth);
} catch (ParseException pe) {
    System.err.println("Bad configuration file");
    pe.printStackTrace();
    System.exit(-2);
} catch (UnsupportedLookAndFeelException ulfe) {
    System.err.println("Old JRE in use. Get a new one");
    System.exit(-3);
}

From there, go on and add your JButton like you normally would. The only change is that you use the setName(string) method to identify what the button should map to in the xml file.

The xml file might look like this:

<synth>
    <style id="button">
        <font name="DIALOG" size="12" style="BOLD"/>
        <state value="MOUSE_OVER">
            <imagePainter method="buttonBackground" path="dirt.png" sourceInsets="2 2 2 2"/>
            <insets top="2" botton="2" right="2" left="2"/>
        </state>
        <state value="ENABLED">
            <imagePainter method="buttonBackground" path="dirt.png" sourceInsets="2 2 2 2"/>
            <insets top="2" botton="2" right="2" left="2"/>
        </state>
    </style>
    <bind style="button" type="name" key="dirt"/>
</synth>

The bind element there specifies what to map to (in this example, it will apply that styling to any buttons whose name property has been set to "dirt").

And a couple of useful links:

http://javadesktop.org/articles/synth/

http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/synth.html

How to send email from Terminal?

Probably the simplest way is to use curl for this, there is no need to install any additional packages and it can be configured directly in a request.

Here is an example using gmail smtp server:

curl --url 'smtps://smtp.gmail.com:465' --ssl-reqd \
  --mail-from '[email protected]' \
  --mail-rcpt '[email protected]' \
  --user '[email protected]:YourPassword' \
  -T <(echo -e 'From: [email protected]\nTo: [email protected]\nSubject: Curl Test\n\nHello')

Shell script current directory?

You could do this yourself by checking the output from pwd when running it. This will print the directory you are currently in. Not the script.

If your script does not switch directories, it'll print the directory you ran it from.

CSS Printing: Avoiding cut-in-half DIVs between pages?

page-break-inside: avoid; gave me trouble using wkhtmltopdf.

To avoid breaks in the text add display: table; to the CSS of the text-containing div.

I hope this works for you too. Thanks JohnS.

How to automate drag & drop functionality using Selenium WebDriver Java

Selenium has pretty good documentation. Here is a link to the specific part of the API you are looking for.

WebElement element = driver.findElement(By.name("source")); 

WebElement target = driver.findElement(By.name("target"));

(new Actions(driver)).dragAndDrop(element, target).perform();

React Native Border Radius with background color

Apply the below line of code :

<TextInput
  style={{ height: 40, width: "95%", borderColor: 'gray', borderWidth: 2, borderRadius: 20,  marginBottom: 20, fontSize: 18, backgroundColor: '#68a0cf' }}
  // Adding hint in TextInput using Placeholder option.
  placeholder=" Enter Your First Name"
  // Making the Under line Transparent.
  underlineColorAndroid="transparent"
/>

Fork() function in C

First a link to some documentation of fork()

http://pubs.opengroup.org/onlinepubs/009695399/functions/fork.html

The pid is provided by the kernel. Every time the kernel create a new process it will increase the internal pid counter and assign the new process this new unique pid and also make sure there are no duplicates. Once the pid reaches some high number it will wrap and start over again.

So you never know what pid you will get from fork(), only that the parent will keep it's unique pid and that fork will make sure that the child process will have a new unique pid. This is stated in the documentation provided above.

If you continue reading the documentation you will see that fork() return 0 for the child process and the new unique pid of the child will be returned to the parent. If the child want to know it's own new pid you will have to query for it using getpid().

pid_t pid = fork()
if(pid == 0) {
    printf("this is a child: my new unique pid is %d\n", getpid());
} else {
    printf("this is the parent: my pid is %d and I have a child with pid %d \n", getpid(), pid);
}

and below is some inline comments on your code

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main() {
    pid_t pid1, pid2, pid3;
    pid1=0, pid2=0, pid3=0;
    pid1= fork(); /* A */
    if(pid1 == 0){
        /* This is child A */
        pid2=fork(); /* B */
        pid3=fork(); /* C */
    } else {
        /* This is parent A */
        /* Child B and C will never reach this code */
        pid3=fork(); /* D */
        if(pid3==0) {
            /* This is child D fork'ed from parent A */
            pid2=fork(); /* E */
        }
        if((pid1 == 0)&&(pid2 == 0)) {
            /* pid1 will never be 0 here so this is dead code */
            printf("Level 1\n");
        }
        if(pid1 !=0) {
            /* This is always true for both parent and child E */
            printf("Level 2\n");
        }
        if(pid2 !=0) {
           /* This is parent E (same as parent A) */
           printf("Level 3\n");
        }
        if(pid3 !=0) {
           /* This is parent D (same as parent A) */
           printf("Level 4\n");
        }
    }
    return 0;
}

Converting a PDF to PNG

My solution is much simpler and more direct. At least it works that way on my PC (with the following specs):

me@home: my.folder$ uname -a
Linux home 3.2.0-54-generic-pae #82-Ubuntu SMP Tue Sep 10 20:29:22 UTC 2013 i686 i686 i386 GNU/Linux

with

me@home: my.folder$ convert --version
Version: ImageMagick 6.6.9-7 2012-08-17 Q16 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2011 ImageMagick Studio LLC
Features: OpenMP

So, here's what I run on my file.pdf:

me@home: my.folder$ convert -density 300 -quality 100 file.pdf file.png

Has an event handler already been added?

i agree with alf's answer,but little modification to it is,, to use,

           try
            {
                control_name.Click -= event_Click;
                main_browser.Document.Click += Document_Click;
            }
            catch(Exception exce)
            {
                main_browser.Document.Click += Document_Click;
            }

How to skip to next iteration in jQuery.each() util?

Dont forget that you can sometimes just fall off the end of the block to get to the next iteration:

$(".row").each( function() {
    if ( ! leaveTheLoop ) {
        ... do stuff here ...
    }
});

Rather than actually returning like this:

$(".row").each( function() {
    if ( leaveTheLoop ) 
        return; //go to next iteration in .each()
    ... do stuff here ...
});

How do CSS triangles work?

CSS clip-path

This is something I feel this question has missed; clip-path

clip-path in a nutshell

Clipping, with the clip-path property, is akin to cutting a shape (like a circle or a pentagon) from a rectangular piece of paper. The property belongs to the “CSS Masking Module Level 1” specification. The spec states, “CSS masking provides two means for partially or fully hiding portions of visual elements: masking and clipping”.


clip-path will use the element itself rather than its borders to cut the shape you specify in its parameters. It uses a super simple percentage based co-ordinate system which makes editing it very easy and means you can pick it up and create weird and wonderful shapes in a matter of minutes.


Triangle Shape Example

_x000D_
_x000D_
div {_x000D_
  -webkit-clip-path: polygon(50% 0%, 0% 100%, 100% 100%);_x000D_
  clip-path: polygon(50% 0%, 0% 100%, 100% 100%);_x000D_
  background: red;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_


Downside

It does have a major downside at the moment, one being it's major lack of support, only really being covered within -webkit- browsers and having no support on IE and only very partial in FireFox.


Resources

Here are some useful resources and material to help better understand clip-path and also start creating your own.

Input type "number" won't resize

Rather than set the length, set the max and min values for the number input.

The input box then resizes to fit the longest valid value.

If you want to allow a 3-digit number then set 999 as the max

 <input type="number" name="quantity" min="0" max="999">

Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?

0000 0000 -> this is an 8-bit binary number. A digit represents a bit.

You count like so:

0000 0000 ? (0)

0000 0001 ? (1)

0000 0010 ? (2)

0000 0011 ? (3)

Each bit can be one of two values: on or off. The total highest number can be represented by multiplication:

2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 - 1 = 255

Or

2^8 - 1. 

We subtract one because the first number is 0.

255 can hold quite a bit (no pun intended) of values.

As we use more bits the max value goes up exponentially. Therefore for many purposes, adding more bits is overkill.

Bootstrap modal not displaying

If you're running Bootstrap 4, it may be due to ".fade:not(.show) { opacity: 0 }" in the Bootstrap css and your modal doesn't have class 'show'. And the reason it doesn't have class 'show' may be due to your page not loading jQuery, Popper, and Bootstrap Javascript files.

(The Bootstrap Javascript will add the class 'show' to your dialog automagically.)

Reference: https://getbootstrap.com/docs/4.3/getting-started/introduction/

How to return a result (startActivityForResult) from a TabHost Activity?

Oh, god! After spending several hours and downloading the Android sources, I have finally come to a solution.

If you look at the Activity class, you will see, that finish() method only sends back the result if there is a mParent property set to null. Otherwise the result is lost.

public void finish() {
    if (mParent == null) {
        int resultCode;
        Intent resultData;
        synchronized (this) {
            resultCode = mResultCode;
            resultData = mResultData;
        }
        if (Config.LOGV) Log.v(TAG, "Finishing self: token=" + mToken);
        try {
            if (ActivityManagerNative.getDefault()
                .finishActivity(mToken, resultCode, resultData)) {
                mFinished = true;
            }
        } catch (RemoteException e) {
            // Empty
        }
    } else {
        mParent.finishFromChild(this);
    }
}

So my solution is to set result to the parent activity if present, like that:

Intent data = new Intent();
 [...]
if (getParent() == null) {
    setResult(Activity.RESULT_OK, data);
} else {
    getParent().setResult(Activity.RESULT_OK, data);
}
finish();

I hope that will be helpful if someone looks for this problem workaround again.

numpy matrix vector multiplication

Simplest solution

Use numpy.dot or a.dot(b). See the documentation here.

>>> a = np.array([[ 5, 1 ,3], 
                  [ 1, 1 ,1], 
                  [ 1, 2 ,1]])
>>> b = np.array([1, 2, 3])
>>> print a.dot(b)
array([16, 6, 8])

This occurs because numpy arrays are not matrices, and the standard operations *, +, -, / work element-wise on arrays. Instead, you could try using numpy.matrix, and * will be treated like matrix multiplication.


Other Solutions

Also know there are other options:

  • As noted below, if using python3.5+ the @ operator works as you'd expect:

    >>> print(a @ b)
    array([16, 6, 8])
    
  • If you want overkill, you can use numpy.einsum. The documentation will give you a flavor for how it works, but honestly, I didn't fully understand how to use it until reading this answer and just playing around with it on my own.

    >>> np.einsum('ji,i->j', a, b)
    array([16, 6, 8])
    
  • As of mid 2016 (numpy 1.10.1), you can try the experimental numpy.matmul, which works like numpy.dot with two major exceptions: no scalar multiplication but it works with stacks of matrices.

    >>> np.matmul(a, b)
    array([16, 6, 8])
    
  • numpy.inner functions the same way as numpy.dot for matrix-vector multiplication but behaves differently for matrix-matrix and tensor multiplication (see Wikipedia regarding the differences between the inner product and dot product in general or see this SO answer regarding numpy's implementations).

    >>> np.inner(a, b)
    array([16, 6, 8])
    
    # Beware using for matrix-matrix multiplication though!
    >>> b = a.T
    >>> np.dot(a, b)
    array([[35,  9, 10],
           [ 9,  3,  4],
           [10,  4,  6]])
    >>> np.inner(a, b) 
    array([[29, 12, 19],
           [ 7,  4,  5],
           [ 8,  5,  6]])
    

Rarer options for edge cases

  • If you have tensors (arrays of dimension greater than or equal to one), you can use numpy.tensordot with the optional argument axes=1:

    >>> np.tensordot(a, b, axes=1)
    array([16,  6,  8])
    
  • Don't use numpy.vdot if you have a matrix of complex numbers, as the matrix will be flattened to a 1D array, then it will try to find the complex conjugate dot product between your flattened matrix and vector (which will fail due to a size mismatch n*m vs n).

How to compare two colors for similarity/difference

You'll need to convert any RGB colors into the Lab color space to be able to compare them in the way that humans see them. Otherwise you'll be getting RGB colors that 'match' in some very strange ways.

The wikipedia link on Color Differences gives you an intro into the various Lab color space difference algorithms that have been defined over the years. The simplest that just checks the Euclidian distance of two lab colours, works but has a few flaws.

Conveniently there's a Java implementation of the more sophisticated CIEDE2000 algorithm in the OpenIMAJ project. Provide it your two sets of Lab colours and it'll give you back single distance value.

Selenium IDE - Command to wait for 5 seconds

This will do what you are looking for in C# (WebDriver/Selenium 2.0)

var browser = new FirefoxDriver();
var overallTimeout = Timespan.FromSeconds(10);
var sleepCycle = TimeSpan.FromMiliseconds(50);
var wait = new WebDriverWait(new SystemClock(), browser, overallTimeout, sleepCycle);
var hasTimedOut = wait.Until(_ => /* here goes code that looks for the map */);

And never use Thread.Sleep because it makes your tests unreliable

Is it possible to install both 32bit and 64bit Java on Windows 7?

As stated by pnt you can have multiple versions of both 32bit and 64bit Java installed at the same time on the same machine.

Taking it further from there: Here's how it might be possible to set any runtime parameters for each of those installations:

You can run javacpl.exe or javacpl.cpl of the respective Java-version itself (bin-folder). The specific control panel opens fine. Adding parameters there is possible.

Python FileNotFound

try block should be around open. Not around prompt.

while True:
    prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
    try:
        sudoku = open(prompt, 'r').readlines()
    except FileNotFoundError:
        print("Wrong file or file path")
    else:
        break

CSS customized scroll bar in div

I thought it would be helpful to consolidate the latest information on scroll bars, CSS, and browser compatibility.

Scroll Bar CSS Support

Currently, there exists no cross-browser scroll bar CSS styling definitions. The W3C article I mention at the end has the following statement and was recently updated (10 Oct 2014):

Some browsers (IE, Konqueror) support the non-standard properties 'scrollbar-shadow-color', 'scrollbar-track-color' and others. These properties are illegal: they are neither defined in any CSS specification nor are they marked as proprietary (by prefixing them with "-vendor-")

Microsoft

As others have mentioned, Microsoft supports scroll bar styling, but only for IE8 and above.

Example:

<!-- language: lang-css -->

    .TA {
        scrollbar-3dlight-color:gold;
        scrollbar-arrow-color:blue;
        scrollbar-base-color:;
        scrollbar-darkshadow-color:blue;
        scrollbar-face-color:;
        scrollbar-highlight-color:;
        scrollbar-shadow-color:
    }

Chrome & Safari (WebKit)

Similarly, WebKit now has its own version:

Firefox (Gecko)

As of version 64 Firefox supports scrollbar styling through the properties scrollbar-color (partially, W3C draft) and scrollbar-width (W3C draft). Some good information about the implementation can be found in this answer.

Cross-browser Scroll Bar Styling

JavaScript libraries and plug-ins can provide a cross-browser solution. There are many options.

The list could go on. Your best bet is to search around, research, and test the available solutions. I am sure you will be able to find something that will fit your needs.

Prevent Illegal Scroll Bar Styling

Just in case you want to prevent scroll bar styling that hasn't been properly prefixed with "-vendor", this article over at W3C provides some basic instructions. Basically, you'll need to add the following CSS to a user style sheet associated with your browser. These definitions will override invalid scroll bar styling on any page you visit.

body, html {
  scrollbar-face-color: ThreeDFace !important;
  scrollbar-shadow-color: ThreeDDarkShadow !important;
  scrollbar-highlight-color: ThreeDHighlight !important;
  scrollbar-3dlight-color: ThreeDLightShadow !important;
  scrollbar-darkshadow-color: ThreeDDarkShadow !important;
  scrollbar-track-color: Scrollbar !important;
  scrollbar-arrow-color: ButtonText !important;
}

Duplicate or Similar Questions / Source Not Linked Above

Note: This answer contains information from various sources. If a source was used, then it is also linked in this answer.

java.net.ConnectException: failed to connect to /192.168.253.3 (port 2468): connect failed: ECONNREFUSED (Connection refused)

A common mistake during development of an android app running on a Virtual Device on your dev machine is to forget that the virtual device is not the same host as your dev machine. So if your server is running on your dev machine you cannot use a "http://localhost/..." url as that will look for the server endpoint on the virtual device not your dev machine.

case statement in where clause - SQL Server

You don't need case in the where statement, just use parentheses and or:

Select * From Times
WHERE StartDate <= @Date AND EndDate >= @Date
AND (
    (@day = 'Monday' AND Monday = 1)
    OR (@day = 'Tuesday' AND Tuesday = 1)
    OR Wednesday = 1
)

Additionally, your syntax is wrong for a case. It doesn't append things to the string--it returns a single value. You'd want something like this, if you were actually going to use a case statement (which you shouldn't):

Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date)
AND 1 = CASE WHEN @day = 'Monday' THEN Monday
             WHEN @day = 'Tuesday' THEN Tuesday
             ELSE Wednesday
        END 

And just for an extra umph, you can use the between operator for your date:

where @Date between StartDate and EndDate

Making your final query:

select
    * 
from 
    Times
where
    @Date between StartDate and EndDate
    and (
        (@day = 'Monday' and Monday = 1)
        or (@day = 'Tuesday' and Tuesday = 1)
        or Wednesday = 1
    )

Single controller with multiple GET methods in ASP.NET Web API

With the newer Web Api 2 it has become easier to have multiple get methods.

If the parameter passed to the GET methods are different enough for the attribute routing system to distinguish their types as is the case with ints and Guids you can specify the expected type in the [Route...] attribute

For example -

[RoutePrefix("api/values")]
public class ValuesController : ApiController
{

    // GET api/values/7
    [Route("{id:int}")]
    public string Get(int id)
    {
       return $"You entered an int - {id}";
    }

    // GET api/values/AAC1FB7B-978B-4C39-A90D-271A031BFE5D
    [Route("{id:Guid}")]
    public string Get(Guid id)
    {
       return $"You entered a GUID - {id}";
    }
} 

For more details about this approach, see here http://nodogmablog.bryanhogan.net/2017/02/web-api-2-controller-with-multiple-get-methods-part-2/

Another options is to give the GET methods different routes.

    [RoutePrefix("api/values")]
    public class ValuesController : ApiController
    {
        public string Get()
        {
            return "simple get";
        }

        [Route("geta")]
        public string GetA()
        {
            return "A";
        }

        [Route("getb")]
        public string GetB()
        {
            return "B";
        }
   }

See here for more details - http://nodogmablog.bryanhogan.net/2016/10/web-api-2-controller-with-multiple-get-methods/

Page scroll up or down in Selenium WebDriver (Selenium 2) using java

JavascriptExecutor is best to scroll down a web page window.scrollTo Function in JavascriptExecutor can do this

JavascriptExecutor js = ((JavascriptExecutor) driver);
js.executeScript("window.scrollTo(0,100"); 

Above code will scroll down by 100 y coordinates

file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?

php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data.

Source: http://php.net/manual/en/wrappers.php.php.

How do you convert a byte array to a hexadecimal string, and vice versa?

Either:

public static string ByteArrayToString(byte[] ba)
{
  StringBuilder hex = new StringBuilder(ba.Length * 2);
  foreach (byte b in ba)
    hex.AppendFormat("{0:x2}", b);
  return hex.ToString();
}

or:

public static string ByteArrayToString(byte[] ba)
{
  return BitConverter.ToString(ba).Replace("-","");
}

There are even more variants of doing it, for example here.

The reverse conversion would go like this:

public static byte[] StringToByteArray(String hex)
{
  int NumberChars = hex.Length;
  byte[] bytes = new byte[NumberChars / 2];
  for (int i = 0; i < NumberChars; i += 2)
    bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
  return bytes;
}

Using Substring is the best option in combination with Convert.ToByte. See this answer for more information. If you need better performance, you must avoid Convert.ToByte before you can drop SubString.

Greyscale Background Css Images

Here you go:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>bluantinoo CSS Grayscale Bg Image Sample</title>
<style type="text/css">
    div {
        border: 1px solid black;
        padding: 5px;
        margin: 5px;
        width: 600px;
        height: 600px;
        float: left;
        color: white;
    }
     .grayscale {
         background: url(yourimagehere.jpg);
         -moz-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
         -o-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
         -webkit-filter: grayscale(100%);
         filter: gray;
         filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
     }

    .nongrayscale {
        background: url(yourimagehere.jpg);
    }
</style>
</head>
<body>
    <div class="nongrayscale">
        this is a non-grayscale of the bg image
    </div>
    <div class="grayscale">
        this is a grayscale of the bg image
    </div>
</body>
</html>

Tested it in FireFox, Chrome and IE. I've also attached an image to show my results of my implementation of this.Grayscale Background Image in DIV Sample

EDIT: Also, if you want the image to just toggle back and forth with jQuery, here's the page source for that...I've included the web link to jQuery and and image that's online so you should just be able to copy/paste to test it out:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>bluantinoo CSS Grayscale Bg Image Sample</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<style type="text/css">
    div {
        border: 1px solid black;
        padding: 5px;
        margin: 5px;
        width: 600px;
        height: 600px;
        float: left;
        color: white;
    }
     .grayscale {
         background: url(http://www.polyrootstattoo.com/images/Artists/Buda/40.jpg);
         -moz-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
         -o-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
         -webkit-filter: grayscale(100%);
         filter: gray;
         filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
     }

    .nongrayscale {
        background: url(http://www.polyrootstattoo.com/images/Artists/Buda/40.jpg);
    }
</style>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#image").mouseover(function () {
                $(".nongrayscale").removeClass().fadeTo(400,0.8).addClass("grayscale").fadeTo(400, 1);
            });
            $("#image").mouseout(function () {
                $(".grayscale").removeClass().fadeTo(400, 0.8).addClass("nongrayscale").fadeTo(400, 1);
            });
        });
</script>
</head>
<body>
    <div id="image" class="nongrayscale">
        rollover this image to toggle grayscale
    </div>
</body>
</html>

EDIT 2 (For IE10-11 Users): The solution above will not work with the changes Microsoft has made to the browser as of late, so here's an updated solution that will allow you to grayscale (or desaturate) your images.

_x000D_
_x000D_
<svg>_x000D_
  <defs>_x000D_
    <filter xmlns="http://www.w3.org/2000/svg" id="desaturate">_x000D_
      <feColorMatrix type="saturate" values="0" />_x000D_
    </filter>_x000D_
  </defs>_x000D_
  <image xlink:href="http://www.polyrootstattoo.com/images/Artists/Buda/40.jpg" width="600" height="600" filter="url(#desaturate)" />_x000D_
</svg>
_x000D_
_x000D_
_x000D_

Everytime I run gulp anything, I get a assertion error. - Task function must be specified

Try replacing your last line of gulpfile.js

gulp.task('default', ['server', 'watch']);

with

gulp.task('default', gulp.series('server', 'watch'));

When to use extern in C++

It is useful when you share a variable between a few modules. You define it in one module, and use extern in the others.

For example:

in file1.cpp:

int global_int = 1;

in file2.cpp:

extern int global_int;
//in some function
cout << "global_int = " << global_int;

Java JTable getting the data of the selected row

http://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html

You will find these methods in it:

getValueAt(int row, int column)
getSelectedRow()
getSelectedColumn()

Use a mix of these to achieve your result.

How do you do a limit query in JPQL or HQL?

You can use below query

NativeQuery<Object[]> query = session.createNativeQuery(select * from employee limit ?)
query.setparameter(1,1);

Escape sequence \f - form feed - what exactly is it?

It skips to the start of the next page. (Applies mostly to terminals where the output device is a printer rather than a VDU.)

Definition of int64_t

int64_t is typedef you can find that in <stdint.h> in C

Convert row names into first column

Alternatively, you can create a new dataframe (or overwrite the current one, as the example below) so you do not need to use of any external package. However this way may not be efficient with huge dataframes.

df <- data.frame(names = row.names(df), df)

How to make use of SQL (Oracle) to count the size of a string?

you need length() function

select length(customer_name) from ar.ra_customers

HTML form input tag name element array with JavaScript

document.form.p_id.length ... not count().

You really should give your form an id

<form id="myform">

Then refer to it using:

var theForm = document.getElementById("myform");

Then refer to the elements like:

for(var i = 0; i < theForm.p_id.length; i++){

Send email by using codeigniter library via localhost

Please check my working code.

function sendMail()
{
    $config = Array(
  'protocol' => 'smtp',
  'smtp_host' => 'ssl://smtp.googlemail.com',
  'smtp_port' => 465,
  'smtp_user' => '[email protected]', // change it to yours
  'smtp_pass' => 'xxx', // change it to yours
  'mailtype' => 'html',
  'charset' => 'iso-8859-1',
  'wordwrap' => TRUE
);

        $message = '';
        $this->load->library('email', $config);
      $this->email->set_newline("\r\n");
      $this->email->from('[email protected]'); // change it to yours
      $this->email->to('[email protected]');// change it to yours
      $this->email->subject('Resume from JobsBuddy for your Job posting');
      $this->email->message($message);
      if($this->email->send())
     {
      echo 'Email sent.';
     }
     else
    {
     show_error($this->email->print_debugger());
    }

}

How to echo text during SQL script execution in SQLPLUS

You can change the name of the column, therefore instead of "COUNT(*)" you would have something meaningful. You will have to update your "RowCount.sql" script for that.

For example:

SQL> select count(*) as RecordCountFromTableOne from TableOne;

Will be displayed as:

RecordCountFromTableOne
-----------------------
           0

If you want to have space in the title, you need to enclose it in double quotes

SQL> select count(*) as "Record Count From Table One" from TableOne;

Will be displayed as:

Record Count From Table One
---------------------------
            0

How do I convert from int to Long in Java?

use

new Long(your_integer);

or

Long.valueOf(your_integer);

How do I list all files of a directory?

Getting Full File Paths From a Directory and All Its Subdirectories

import os

def get_filepaths(directory):
    """
    This function will generate the file names in a directory 
    tree by walking the tree either top-down or bottom-up. For each 
    directory in the tree rooted at directory top (including top itself), 
    it yields a 3-tuple (dirpath, dirnames, filenames).
    """
    file_paths = []  # List which will store all of the full filepaths.

    # Walk the tree.
    for root, directories, files in os.walk(directory):
        for filename in files:
            # Join the two strings in order to form the full filepath.
            filepath = os.path.join(root, filename)
            file_paths.append(filepath)  # Add it to the list.

    return file_paths  # Self-explanatory.

# Run the above function and store its results in a variable.   
full_file_paths = get_filepaths("/Users/johnny/Desktop/TEST")

  • The path I provided in the above function contained 3 files— two of them in the root directory, and another in a subfolder called "SUBFOLDER." You can now do things like:
  • print full_file_paths which will print the list:

    • ['/Users/johnny/Desktop/TEST/file1.txt', '/Users/johnny/Desktop/TEST/file2.txt', '/Users/johnny/Desktop/TEST/SUBFOLDER/file3.dat']

If you'd like, you can open and read the contents, or focus only on files with the extension ".dat" like in the code below:

for f in full_file_paths:
  if f.endswith(".dat"):
    print f

/Users/johnny/Desktop/TEST/SUBFOLDER/file3.dat

Add a user control to a wpf window

Make sure there is an namespace definition (xmlns) for the namespace your control belong to.

xmlns:myControls="clr-namespace:YourCustomNamespace.Controls;assembly=YourAssemblyName"
<myControls:thecontrol/>

How to use dashes in HTML-5 data-* attributes in ASP.NET MVC

You can use it like this:

In Mvc:

@Html.TextBoxFor(x=>x.Id,new{@data_val_number="10"});

In Html:

<input type="text" name="Id" data_val_number="10"/>

Reload child component when variables on parent component changes. Angular2

On Angular to update a component including its template, there is a straight forward solution to this, having an @Input property on your ChildComponent and add to your @Component decorator changeDetection: ChangeDetectionStrategy.OnPush as follows:

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

@Component({
    selector: 'master',
    templateUrl: templateUrl,
    styleUrls:[styleUrl1],
    changeDetection: ChangeDetectionStrategy.OnPush    
})

export class ChildComponent{
  @Input() data: MyData;
}

This will do all the work of check if Input data have changed and re-render the component

How to normalize an array in NumPy to a unit vector?

If you work with multidimensional array following fast solution is possible.

Say we have 2D array, which we want to normalize by last axis, while some rows have zero norm.

import numpy as np
arr = np.array([
    [1, 2, 3], 
    [0, 0, 0],
    [5, 6, 7]
], dtype=np.float)

lengths = np.linalg.norm(arr, axis=-1)
print(lengths)  # [ 3.74165739  0.         10.48808848]
arr[lengths > 0] = arr[lengths > 0] / lengths[lengths > 0][:, np.newaxis]
print(arr)
# [[0.26726124 0.53452248 0.80178373]
# [0.         0.         0.        ]
# [0.47673129 0.57207755 0.66742381]]

Delete all the records

I can see the that the others answers shown above are right, but I'll make your life easy.

I even created an example for you. I added some rows and want delete them.

You have to right click on the table and as shown in the figure Script Table a> Delete to> New query Editor widows:

enter image description here

Then another window will open with a script. Delete the line of "where", because you want to delete all rows. Then click Execute.

enter image description here

To make sure you did it right right click over the table and click in "Select Top 1000 rows". Then you can see that the query is empty.

What is the point of WORKDIR on Dockerfile?

You can think of WORKDIR like a cd inside the container (it affects commands that come later in the Dockerfile, like the RUN command). If you removed WORKDIR in your example above, RUN npm install wouldn't work because you would not be in the /usr/src/app directory inside your container.

I don't see how this would be related to where you put your Dockerfile (since your Dockerfile location on the host machine has nothing to do with the pwd inside the container). You can put the Dockerfile wherever you'd like in your project. However, the first argument to COPY is a relative path, so if you move your Dockerfile you may need to update those COPY commands.

Animate change of view background color on Android

You can use ArgbEvaluatorCompat class above API 11.

implementation 'com.google.android.material:material:1.0.0' 


ValueAnimator colorAnim = ValueAnimator.ofObject(new ArgbEvaluatorCompat(), startColor, endColor);
colorAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            mTargetColor = (int) animation.getAnimatedValue();
        }
    });
colorAnim.start();

Error message "Strict standards: Only variables should be passed by reference"

The second snippet doesn't work either and that's why.

array_shift is a modifier function, that changes its argument. Therefore it expects its parameter to be a reference, and you cannot reference something that is not a variable. See Rasmus' explanations here: Strict standards: Only variables should be passed by reference

Creating an IFRAME using JavaScript

It is better to process HTML as a template than to build nodes via JavaScript (HTML is not XML after all.) You can keep your IFRAME's HTML syntax clean by using a template and then appending the template's contents into another DIV.

<div id="placeholder"></div>

<script id="iframeTemplate" type="text/html">
    <iframe src="...">
        <!-- replace this line with alternate content -->
    </iframe>
</script>

<script type="text/javascript">
var element,
    html,
    template;

element = document.getElementById("placeholder");
template = document.getElementById("iframeTemplate");
html = template.innerHTML;

element.innerHTML = html;
</script>

Simple Pivot Table to Count Unique Values

Step 1. Add a column

Step 2. Use the formula =IF(COUNTIF(C2:$C$2410,C2)>1,0,1) in 1st record

Step 3. Drag it to all the records

Step 4. Filter '1' in the column with formula

SQL set values of one column equal to values of another column in the same table

I don't think that other example is what you're looking for. If you're just updating one column from another column in the same table you should be able to use something like this.

update some_table set null_column = not_null_column where null_column is null

static constructors in C++? I need to initialize private static objects

The concept of static constructors was introduced in Java after they learned from the problems in C++. So we have no direct equivalent.

The best solution is to use POD types that can be initialised explicitly.
Or make your static members a specific type that has its own constructor that will initialize it correctly.

//header

class A
{
    // Make sure this is private so that nobody can missues the fact that
    // you are overriding std::vector. Just doing it here as a quicky example
    // don't take it as a recomendation for deriving from vector.
    class MyInitedVar: public std::vector<char>
    {
        public:
        MyInitedVar()
        {
           // Pre-Initialize the vector.
           for(char c = 'a';c <= 'z';++c)
           {
               push_back(c);
           }
        }
    };
    static int          count;
    static MyInitedVar  var1;

};


//source
int            A::count = 0;
A::MyInitedVar A::var1;

Drawing an SVG file on a HTML5 canvas

EDIT Dec 16th, 2019

Path2D is supported by all major browsers now

EDIT November 5th, 2014

You can now use ctx.drawImage to draw HTMLImageElements that have a .svg source in some but not all browsers. Chrome, IE11, and Safari work, Firefox works with some bugs (but nightly has fixed them).

var img = new Image();
img.onload = function() {
    ctx.drawImage(img, 0, 0);
}
img.src = "http://upload.wikimedia.org/wikipedia/commons/d/d2/Svg_example_square.svg";

Live example here. You should see a green square in the canvas. The second green square on the page is the same <svg> element inserted into the DOM for reference.

You can also use the new Path2D objects to draw SVG (string) paths. In other words, you can write:

var path = new Path2D('M 100,100 h 50 v 50 h 50');
ctx.stroke(path);

Live example of that here.


Old posterity answer:

There's nothing native that allows you to natively use SVG paths in canvas. You must convert yourself or use a library to do it for you.

I'd suggest looking in to canvg:

http://code.google.com/p/canvg/

http://canvg.googlecode.com/svn/trunk/examples/index.htm

How do I get class name in PHP?

Since PHP 5.5 you can use class name resolution via ClassName::class.

See new features of PHP5.5.

<?php

namespace Name\Space;

class ClassName {}

echo ClassName::class;

?>

If you want to use this feature in your class method use static::class:

<?php

namespace Name\Space;

class ClassName {
   /**
    * @return string
    */
   public function getNameOfClass()
   {
      return static::class;
   }
}

$obj = new ClassName();
echo $obj->getNameOfClass();

?>

For older versions of PHP, you can use get_class().

How to get a key in a JavaScript object by its value?

http://jsfiddle.net/rTazZ/2/

var a = new Array(); 
    a.push({"1": "apple", "2": "banana"}); 
    a.push({"3": "coconut", "4": "mango"});

    GetIndexByValue(a, "coconut");

    function GetIndexByValue(arrayName, value) {  
    var keyName = "";
    var index = -1;
    for (var i = 0; i < arrayName.length; i++) { 
       var obj = arrayName[i]; 
            for (var key in obj) {          
                if (obj[key] == value) { 
                    keyName = key; 
                    index = i;
                } 
            } 
        }
        //console.log(index); 
        return index;
    } 

I can't access http://localhost/phpmyadmin/

I am using Linux Mint : After installing LAMP along with PhpMyAdmin, I linked both the configuration files of Apache and PhpMyAdmin. It did the trick. Following are the commands.

sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf.d/phpmyadmin.conf

sudo /etc/init.d/apache2 reload

How to edit .csproj file

Since the question is not directly mentioning Visual Studio, I will post how to do this in JetBrains Rider.

From context menu

  1. Right-click your project
  2. Go to edit
  3. Edit '{project-name.csproj}'

enter image description here

With shortcut

  1. Select project
  2. Press F4

How To Launch Git Bash from DOS Command Line?

If you want to launch from a batch file:

  • for x86

    start "" "%SYSTEMDRIVE%\Program Files (x86)\Git\bin\sh.exe" --login
    
  • for x64

    start "" "%PROGRAMFILES%\Git\bin\sh.exe" --login
    

Why do people hate SQL cursors so much?

Cursors make people overly apply a procedural mindset to a set-based environment.

And they are SLOW!!!

From SQLTeam:

Please note that cursors are the SLOWEST way to access data inside SQL Server. The should only be used when you truly need to access one row at a time. The only reason I can think of for that is to call a stored procedure on each row. In the Cursor Performance article I discovered that cursors are over thirty times slower than set based alternatives.

Can I open a dropdownlist using jQuery

No you can't.

You can change the size to make it larger... similar to Dreas idea, but it is the size you need to change.

<select id="countries" size="6">
  <option value="1">Country 1</option>
  <option value="2">Country 2</option>
  <option value="3">Country 3</option>
  <option value="4">Country 4</option>
  <option value="5">Country 5</option>
  <option value="6">Country 6</option>
</select>

How can I compare two lists in python and return matches

A quick performance test showing Lutz's solution is the best:

import time

def speed_test(func):
    def wrapper(*args, **kwargs):
        t1 = time.time()
        for x in xrange(5000):
            results = func(*args, **kwargs)
        t2 = time.time()
        print '%s took %0.3f ms' % (func.func_name, (t2-t1)*1000.0)
        return results
    return wrapper

@speed_test
def compare_bitwise(x, y):
    set_x = frozenset(x)
    set_y = frozenset(y)
    return set_x & set_y

@speed_test
def compare_listcomp(x, y):
    return [i for i, j in zip(x, y) if i == j]

@speed_test
def compare_intersect(x, y):
    return frozenset(x).intersection(y)

# Comparing short lists
a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
compare_bitwise(a, b)
compare_listcomp(a, b)
compare_intersect(a, b)

# Comparing longer lists
import random
a = random.sample(xrange(100000), 10000)
b = random.sample(xrange(100000), 10000)
compare_bitwise(a, b)
compare_listcomp(a, b)
compare_intersect(a, b)

These are the results on my machine:

# Short list:
compare_bitwise took 10.145 ms
compare_listcomp took 11.157 ms
compare_intersect took 7.461 ms

# Long list:
compare_bitwise took 11203.709 ms
compare_listcomp took 17361.736 ms
compare_intersect took 6833.768 ms

Obviously, any artificial performance test should be taken with a grain of salt, but since the set().intersection() answer is at least as fast as the other solutions, and also the most readable, it should be the standard solution for this common problem.

Change the mouse cursor on mouse over to anchor-like style

Assuming your div has an id="myDiv", add the following to your CSS. The cursor: pointer specifies that the cursor should be the same hand icon that is use for anchors (hyperlinks):

CSS to Add

#myDiv
{
    cursor: pointer;
}

You can simply add the cursor style to your div's HTML like this:

<div style="cursor: pointer">

</div>

EDIT:

If you are determined to use jQuery for this, then add the following line to your $(document).ready() or body onload: (replace myClass with whatever class all of your divs share)

$('.myClass').css('cursor', 'pointer');

How to display the current time and date in C#

You'd need to set the label's text property to DateTime.Now:

labelName.Text = DateTime.Now.ToString();

You can format it in a variety of ways by handing ToString() a format string in the form of "MM/DD/YYYY" and the like. (Google Date-format strings).

@POST in RESTful web service

REST webservice: (http://localhost:8080/your-app/rest/data/post)

package com.yourorg.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.MediaType; 
import javax.ws.rs.core.Response;

    @Path("/data")
public class JSONService {

    @POST
    @Path("/post")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createDataInJSON(String data) { 

        String result = "Data post: "+data;

        return Response.status(201).entity(result).build(); 
    }

Client send a post:

package com.yourorg.client;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JerseyClientPost {

  public static void main(String[] args) {

    try {

        Client client = Client.create();

        WebResource webResource = client.resource("http://localhost:8080/your-app/rest/data/post");

        String input = "{\"message\":\"Hello\"}";

        ClientResponse response = webResource.type("application/json")
           .post(ClientResponse.class, input);

        if (response.getStatus() != 201) {
            throw new RuntimeException("Failed : HTTP error code : "
                 + response.getStatus());
        }

        System.out.println("Output from Server .... \n");
        String output = response.getEntity(String.class);
        System.out.println(output);

      } catch (Exception e) {

        e.printStackTrace();

      }

    }
}

link with target="_blank" does not open in new tab in Chrome

For Some reason it is not working so we can do this by another way

just remove the line and add this :-

<a onclick="window.open ('http://www.foracure.org.au', ''); return false" href="javascript:void(0);"></a>

Good luck.

Regular expression [Any number]

You can use the following function to find the biggest [number] in any string.

It returns the value of the biggest [number] as an Integer.

var biggestNumber = function(str) {
    var pattern = /\[([0-9]+)\]/g, match, biggest = 0;

    while ((match = pattern.exec(str)) !== null) {
        if (match.index === pattern.lastIndex) {
            pattern.lastIndex++;
        }
        match[1] = parseInt(match[1]);
        if(biggest < match[1]) {
            biggest = match[1];
        }
    }
    return biggest;
}

DEMO

The following demo calculates the biggest number in your textarea every time you click the button.

It allows you to play around with the textarea and re-test the function with a different text.

_x000D_
_x000D_
var biggestNumber = function(str) {_x000D_
    var pattern = /\[([0-9]+)\]/g, match, biggest = 0;_x000D_
_x000D_
    while ((match = pattern.exec(str)) !== null) {_x000D_
        if (match.index === pattern.lastIndex) {_x000D_
            pattern.lastIndex++;_x000D_
        }_x000D_
        match[1] = parseInt(match[1]);_x000D_
        if(biggest < match[1]) {_x000D_
            biggest = match[1];_x000D_
        }_x000D_
    }_x000D_
    return biggest;_x000D_
}_x000D_
_x000D_
document.getElementById("myButton").addEventListener("click", function() {_x000D_
    alert(biggestNumber(document.getElementById("myTextArea").value));_x000D_
});
_x000D_
<div>_x000D_
    <textarea rows="6" cols="50" id="myTextArea">_x000D_
this is a test [1] also this [2] is a test_x000D_
and again [18] this is a test. _x000D_
items[14].items[29].firstname too is a test!_x000D_
items[4].firstname too is a test!_x000D_
    </textarea>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
   <button id="myButton">Try me</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

See also this Fiddle!

check if command was successful in a batch file

You can use

if errorlevel 1 echo Unsuccessful

in some cases. This depends on the last command returning a proper exit code. You won't be able to tell that there is anything wrong if your program returns normally even if there was an abnormal condition.

Caution with programs like Robocopy, which require a more nuanced approach, as the error level returned from that is a bitmask which contains more than just a boolean information and the actual success code is, AFAIK, 3.

How to parse JSON boolean value?

You can cast this value to a Boolean in a very simple manner: by comparing it with integer value 1, like this:

boolean multipleContacts = new Integer(1).equals(jsonObject.get("MultipleContacts"))

If it is a String, you could do this:

boolean multipleContacts = "1".equals(jsonObject.get("MultipleContacts"))

How can I move HEAD back to a previous location? (Detached head) & Undo commits

The question can be read as:

I was in detached-state with HEAD at 23b6772 and typed git reset origin/master (because I wanted to squash). Now I've changed my mind, how do I go back to HEAD being at 23b6772?

The straightforward answer being: git reset 23b6772

But I hit this question because I got sick of typing (copy & pasting) commit hashes or its abbreviation each time I wanted to reference the previous HEAD and was Googling to see if there were any kind of shorthand.

It turns out there is!

git reset - (or in my case git cherry-pick -)

Which incidentally was the same as cd - to return to the previous current directory in *nix! So hurrah, I learned two things with one stone.

How do I get IntelliJ to recognize common Python modules?

My problem was similar to @Toddarooski 's, except that the module I had, under the "Dependencies" tab, had no SDK listed. I right clicked on 'SDK', picked edit from the drop down menu, and selected my Python SDK. That did the trick.

Could not load file or assembly 'EntityFramework' after downgrading EF 5.0.0.0 --> 4.3.1.0

After failed attempts to find references to EntityFramework in repositories.config and elsewhere, I stumbled upon a reference in Web.config as I was editing it to help with my diagnosis.

The bindingRedirect referenced 5.0.0.0 which was no longer installed and this appeared to be the source of the exception. Honestly, I did not add this reference to Web.config and, after trying to duplicate the error in a separate project, discovered that it is not added by the NuGet package installer so, I don't know why it was there but something added it.

<dependentAssembly>
  <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
  <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>

I decided to replace this with the equivalent element from a working project. NB the references to 5.0.0.0 are replaced with 4.3.1.0 in the following:

<dependentAssembly>
  <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
  <bindingRedirect oldVersion="0.0.0.0-4.3.1.0" newVersion="4.3.1.0" />
</dependentAssembly>

This worked!

I then decided to remove the dependentAssembly reference for the EntityFramework in its entirety.

It still worked!

So, I'm posting this here as a self-answered question in the hope that it helps someone else. If anyone can explain to me:

  • What added the dependentAssembly for EntityFramework to my Web.config
  • Any consequence(s) of removing these references

I'd be interested to learn.

Hide Spinner in Input Number - Firefox 29

According to this blog post, you need to set -moz-appearance:textfield; on the input.

_x000D_
_x000D_
input[type=number]::-webkit-outer-spin-button,_x000D_
input[type=number]::-webkit-inner-spin-button {_x000D_
    -webkit-appearance: none;_x000D_
    margin: 0;_x000D_
}_x000D_
_x000D_
input[type=number] {_x000D_
    -moz-appearance:textfield;_x000D_
}
_x000D_
<input type="number" step="0.01"/>
_x000D_
_x000D_
_x000D_

How to see local history changes in Visual Studio Code?

Basic Functionality

  • Automatically saved local edit history is available with the Local History extension.
  • Manually saved local edit history is available with the Checkpoints extension (this is the IntelliJ equivalent to adding tags to the local history).

Advanced Functionality

  • None of the extensions mentioned above support edit history when a file is moved or renamed.
  • The extensions above only support edit history. They do not support move/delete history, for example, like IntelliJ does.

Open Request

If you'd like to see this feature added natively, along with all of the advanced functionality, I'd suggest upvoting the open GitHub issue here.

jQuery Scroll to Div

It is often required to move both body and html objects together.

$('html,body').animate({
   scrollTop: $("#divToBeScrolledTo").offset().top
});

ShiftyThomas is right:

$("#divToBeScrolledTo").offset().top + 10 // +10 (pixels) reduces the margin.

So to increase the margin use:

$("#divToBeScrolledTo").offset().top - 10 // -10 (pixels) would increase the margin between the top of your window and your element.

Java 8 lambda Void argument

You can create a sub-interface for that special case:

interface Command extends Action<Void, Void> {
  default Void execute(Void v) {
    execute();
    return null;
  }
  void execute();
}

It uses a default method to override the inherited parameterized method Void execute(Void), delegating the call to the simpler method void execute().

The result is that it's much simpler to use:

Command c = () -> System.out.println("Do nothing!");

How to download source in ZIP format from GitHub?

For people using Windows and struggling to download repo as zip from terminal:

url -L http://github.com/GorvGoyl/Notion-Boost-browser-extension/archive/master.zip --output master.zip

Add image in title bar

you should be searching about how to add favicon.ico . You can try adding favicon.ico directly in your html pages like this

<link rel="shortcut icon" href="/favicon.png" type="image/png">
<link rel="shortcut icon" type="image/png" href="http://www.example.com/favicon.png" />

Or you can update that in your webserver. It is advised to add in your webserver as you don't need to add this in each of your html pages (assuming no includes).

To add in your apache place the favicon.ico in your root website director and add this in httpd.conf

AddType image/x-icon .ico

php exec command (or similar) to not wait for result

"exec nohup setsid your_command"

the nohup allows your_command to continue even though the process that launched may terminate first. If it does, the the SIGNUP signal will be sent to your_command causing it to terminate (unless it catches that signal and ignores it).

notifyDataSetChange not working from custom adapter

If adapter is set to AutoCompleteTextView then notifyDataSetChanged() doesn't work.

Need this to update adapter:

myAutoCompleteAdapter = new ArrayAdapter<String>(MainActivity.this, 
        android.R.layout.simple_dropdown_item_1line, myList);

myAutoComplete.setAdapter(myAutoCompleteAdapter);

Refer: http://android-er.blogspot.in/2012/10/autocompletetextview-with-dynamic.html

How do you get the string length in a batch file?

You can try this code. Fast, you can also include special characters

@echo off
set "str=[string]"
echo %str% > "%tmp%\STR"
for %%P in ("%TMP%\STR") do (set /a strlen=%%~zP-3)
echo String lenght: %strlen%

jQuery: value.attr is not a function

Contents of that jQuery object are plain DOM elements, which doesn't respond to jQuery methods (e.g. .attr). You need to wrap the value by $() to turn it into a jQuery object to use it.

    console.info("cat_id: ", $(value).attr('cat_id'));

or just use the DOM method directly

    console.info("cat_id: ", value.getAttribute('cat_id'));

Basic HTTP and Bearer Token Authentication

Try this one to push basic authentication at url:

curl -i http://username:[email protected]/api/users -H "Authorization: Bearer mytoken123"
               ^^^^^^^^^^^^^^^^^^

If above one doesn't work, then you have nothing to do with it. So try the following alternates.

You can pass the token under another name. Because you are handling the authorization from your Application. So you can easily use this flexibility for this special purpose.

curl -i http://dev.myapp.com/api/users \
  -H "Authorization: Basic Ym9zY236Ym9zY28=" \
  -H "Application-Authorization: mytoken123"

Notice I have changed the header into Application-Authorization. So from your application catch the token under that header and process what you need to do.

Another thing you can do is, to pass the token through the POST parameters and grab the parameter's value from the Server side. For example passing token with curl post parameter:

-d "auth-token=mytoken123"

How do you set autocommit in an SQL Server session?

I wanted a more permanent and quicker way. Because I tend to forget to add extra lines before writing my actual Update/Insert queries.

I did it by checking SET IMPLICIT_TRANSACTIONS check-box from Options. To navigate to Options Select Tools>Options>Query Execution>SQL Server>ANSI in your Microsoft SQL Server Management Studio.

Just make sure to execute commit or rollback after you are done executing your queries. Otherwise, the table you would have run the query will be locked for others.

Does Java have an exponential operator?

There is no operator, but there is a method.

Math.pow(2, 3) // 8.0

Math.pow(3, 2) // 9.0

FYI, a common mistake is to assume 2 ^ 3 is 2 to the 3rd power. It is not. The caret is a valid operator in Java (and similar languages), but it is binary xor.

iPhone 5 CSS media query

Just a very quick addition as I have been testing a few options and missed this along the way. Make sure your page has:

<meta name="viewport" content="initial-scale=1.0">

Javascript validation: Block special characters

Try this one, this function allows alphanumeric and spaces:

function alpha(e) {
    var k;
    document.all ? k = e.keyCode : k = e.which;
    return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
}

in your html:

<input type="text" name="name"  onkeypress="return alpha(event)"/>

Making TextView scrollable on Android

For a vertically or horizontally scrollable TextView some of the other answers help, but I needed to be able to scroll both ways.

What finally worked is a ScrollView with a HorizontalScrollView inside of it, and a TextView inside the HSV. It's very smooth and can easily go side to side or top to bottom in one swipe. It also only allows scrolling in one direction at a time so there's none of the jumping side to side while scrolling up or down.

An EditText with editing and cursor disabled works, but it feels terrible. Each attempt to scroll moves the cursor and it requires many swipes to go top to bottom or side to side in even a ~100-line file.

Using setHorizontallyScrolling(true) can work, but there's no similar method to allow vertical scrolling, and it doesn't work inside of a ScrollView as far as I can tell (just learning though, could be wrong).

JAXB: how to marshall map into <key>value</key>

There may be a valid reason why you want to do this, but generating this kind of XML is generally best avoided. Why? Because it means that the XML elements of your map are dependent on the runtime contents of your map. And since XML is usually used as an external interface or interface layer this is not desirable. Let me explain.

The Xml Schema (xsd) defines the interface contract of your XML documents. In addition to being able to generate code from the XSD, JAXB can also generate the XML schema for you from the code. This allows you to restrict the data exchanged over the interface to the pre-agreed structures defined in the XSD.

In the default case for a Map<String, String>, the generated XSD will restrict the map element to contain multiple entry elements each of which must contain one xs:string key and one xs:string value. That's a pretty clear interface contract.

What you describe is that you want the xml map to contain elements whose name will be determined by the content of the map at runtime. Then the generated XSD can only specify that the map must contain a list of elements whose type is unknown at compile time. This is something that you should generally avoid when defining an interface contract.

To achieve a strict contract in this case, you should use an enumerated type as the key of the map instead of a String. E.g.

public enum KeyType {
 KEY, KEY2;
}

@XmlJavaTypeAdapter(MapAdapter.class)
Map<KeyType , String> mapProperty;

That way the keys which you want to become elements in XML are known at compile time so JAXB should be able to generate a schema that would restrict the elements of map to elements using one of the predefined keys KEY or KEY2.

On the other hand, if you wish to simplify the default generated structure

<map>
    <entry>
        <key>KEY</key>
        <value>VALUE</value>
    </entry>
    <entry>
        <key>KEY2</key>
        <value>VALUE2</value>
    </entry>
</map>

To something simpler like this

<map>
    <item key="KEY" value="VALUE"/>
    <item key="KEY2" value="VALUE2"/>
</map>

You can use a MapAdapter that converts the Map to an array of MapElements as follows:

class MapElements {
    @XmlAttribute
    public String key;
    @XmlAttribute
    public String value;

    private MapElements() {
    } //Required by JAXB

    public MapElements(String key, String value) {
        this.key = key;
        this.value = value;
    }
}


public class MapAdapter extends XmlAdapter<MapElements[], Map<String, String>> {
    public MapAdapter() {
    }

    public MapElements[] marshal(Map<String, String> arg0) throws Exception {
        MapElements[] mapElements = new MapElements[arg0.size()];
        int i = 0;
        for (Map.Entry<String, String> entry : arg0.entrySet())
            mapElements[i++] = new MapElements(entry.getKey(), entry.getValue());

        return mapElements;
    }

    public Map<String, String> unmarshal(MapElements[] arg0) throws Exception {
        Map<String, String> r = new TreeMap<String, String>();
        for (MapElements mapelement : arg0)
            r.put(mapelement.key, mapelement.value);
        return r;
    }
}

How open PowerShell as administrator from the run window

Windows 10 appears to have a keyboard shortcut. According to How to open elevated command prompt in Windows 10 you can press ctrl + shift + enter from the search or start menu after typing cmd for the search term.

image of win 10 start menu
(source: winaero.com)

SQL Inner join more than two tables

A possible solution:

SELECT Company.Company_Id,Company.Company_Name,
    Invoice_Details.Invoice_No, Product_Details.Price
  FROM Company inner join Invoice_Details
    ON Company.Company_Id=Invoice_Details.Company_Id
 INNER JOIN Product_Details
        ON Invoice_Details.Invoice_No= Product_Details.Invoice_No
 WHERE Price='60000';

-- tets changes

how to change directory using Windows command line

cd /driveName driveName:\pathNamw

jQuery checkbox change and click event

Well .. just for the sake of saving a headache (its past midnight here), I could come up with:

$('#checkbox1').click(function() {
  if (!$(this).is(':checked')) {
    var ans = confirm("Are you sure?");
     $('#textbox1').val(ans);
  }
});

Hope it helps

How do I concatenate strings with variables in PowerShell?

You could use the PowerShell equivalent of String.Format - it's usually the easiest way to build up a string. Place {0}, {1}, etc. where you want the variables in the string, put a -f immediately after the string and then the list of variables separated by commas.

Get-ChildItem c:\code|%{'{0}\{1}\{2}.dll' -f $_.fullname,$buildconfig,$_.name}

(I've also taken the dash out of the $buildconfig variable name as I have seen that causes issues before too.)

Accessing localhost:port from Android emulator

localhost seemed to be working fine in my emulator at start and then i started getting connection refused exception i used 127.0.2.2 from the emulator browser and it worked and when i used this in my android app in emulator it again started showing the connection refused problem.

then i did ifconfig and i used the ip 192.168.2.2 and it worked perfectly

How to split a dos path into its components in Python

For a somewhat more concise solution, consider the following:

def split_path(p):
    a,b = os.path.split(p)
    return (split_path(a) if len(a) and len(b) else []) + [b]

Using Spring RestTemplate in generic method with generic parameter

My own implementation of generic restTemplate call:

private <REQ, RES> RES queryRemoteService(String url, HttpMethod method, REQ req, Class reqClass) {
    RES result = null;
    try {
        long startMillis = System.currentTimeMillis();

        // Set the Content-Type header
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(new MediaType("application","json"));            

        // Set the request entity
        HttpEntity<REQ> requestEntity = new HttpEntity<>(req, requestHeaders);

        // Create a new RestTemplate instance
        RestTemplate restTemplate = new RestTemplate();

        // Add the Jackson and String message converters
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

        // Make the HTTP POST request, marshaling the request to JSON, and the response to a String
        ResponseEntity<RES> responseEntity = restTemplate.exchange(url, method, requestEntity, reqClass);
        result = responseEntity.getBody();
        long stopMillis = System.currentTimeMillis() - startMillis;

        Log.d(TAG, method + ":" + url + " took " + stopMillis + " ms");
    } catch (Exception e) {
         Log.e(TAG, e.getMessage());
    }
    return result;
}

To add some context, I'm consuming RESTful service with this, hence all requests and responses are wrapped into small POJO like this:

public class ValidateRequest {
  User user;
  User checkedUser;
  Vehicle vehicle;
}

and

public class UserResponse {
  User user;
  RequestResult requestResult;
}

Method which calls this is the following:

public User checkUser(User user, String checkedUserName) {
    String url = urlBuilder()
            .add(USER)
            .add(USER_CHECK)
            .build();

    ValidateRequest request = new ValidateRequest();
    request.setUser(user);
    request.setCheckedUser(new User(checkedUserName));

    UserResponse response = queryRemoteService(url, HttpMethod.POST, request, UserResponse.class);
    return response.getUser();
}

And yes, there's a List dto-s as well.

How to get file path from OpenFileDialog and FolderBrowserDialog?

Your choofdlog holds a FileName and FileNames (for multi-selection) containing the file paths, after the ShowDialog() returns.

What is the difference between null and undefined in JavaScript?

For the undefined type, there is one and only one value: undefined.

For the null type, there is one and only one value: null.

So for both of them, the label is both its type and its value.

The difference between them. For example:

  • null is an empty value
  • undefined is a missing value

Or:

  • undefined hasn't had a value yet
  • null had a value and doesn't anymore

Actually, null is a special keyword, not an identifier, and thus you cannot treat it as a variable to assign to.

However, undefined is an identifier. In both non-strict mode and strict mode, however, you can create a local variable of the name undefined. But this is one terrible idea!

function foo() {
    undefined = 2; // bad idea!
}

foo();

function foo() {
    "use strict";
    undefined = 2; // TypeError!
}

foo();

.gitignore for Visual Studio Projects and Solutions

If you are using a dbproj in your solution you will want to add the following:

#Visual Studio DB Project
*.dbmdl
[Ss]ql/

Source: http://blogs.msdn.com/b/bahill/archive/2009/07/31/come-visit-revisit-the-beer-house-continuous-integration.aspx

check if file exists in php

You can also use PHP get_headers() function.

Example:

function check_file_exists_here($url){
   $result=get_headers($url);
   return stripos($result[0],"200 OK")?true:false; //check if $result[0] has 200 OK
}

if(check_file_exists_here("http://www.mywebsite.com/file.pdf"))
   echo "This file exists";
else
   echo "This file does not exist";

Show div on scrollDown after 800px

You can also, do this.

$(window).on("scroll", function () {
   if ($(this).scrollTop() > 800) {
      #code here
   } else {
      #code here
   }
});

JQUERY: Uncaught Error: Syntax error, unrecognized expression

The "double quote" + 'single quote' combo is not needed

console.log( $('#'+d) ); // single quotes only
console.log( $("#"+d) ); // double quotes only

Your selector results like this, which is overkill with the quotes:

$('"#abc"') // -> it'll try to find  <div id='"#abc"'>

// In css, this would be the equivalent:
"#abc"{ /* Wrong */ } // instead of:
#abc{ /* Right */ }

How to change onClick handler dynamically?

If you want to pass variables from the current function, another way to do this is, for example:

document.getElementById("space1").onclick = new Function("lrgWithInfo('"+myVar+"')");

If you don't need to pass information from this function, it's just:

document.getElementById("space1").onclick = new Function("lrgWithInfo('13')");

How to change a <select> value from JavaScript

I found that doing document.getElementById("select").value = "defaultValue" wont work.

You must be experiencing a separate bug, as this works fine in this live demo.

And here's the full working code in case you are interested:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>Demo</title>
    <script type="text/javascript">
        var selectFunction = function() {
            document.getElementById("select").value = "defaultValue";
        };
    </script>
</head>
<body>
    <select id="select">
        <option value="defaultValue">Default</option>
        <option value="Option1">Option1</option>
        <option value="Option2">Option2</option>    
    </select>
    <input type="button" value="CHANGE" onclick="selectFunction()" />
</body>
</html>

How to backup a local Git repository?

You can backup the git repo with git-copy . git-copy saved new project as a bare repo, it means minimum storage cost.

git copy /path/to/project /backup/project.backup

Then you can restore your project with git clone

git clone /backup/project.backup project

Node.js - Find home directory in platform agnostic way

As mentioned in a more recent answer, the preferred way is now simply:

const homedir = require('os').homedir();

[Original Answer]: Why not use the USERPROFILE environment variable on win32?

function getUserHome() {
  return process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
}

Change New Google Recaptcha (v2) Width

No, currently you can not. It was only possible with the old recaptcha, but I'm sure you will be able to do that in the future.

I have no solution but a suggestion. I had the same problem, so I centered the recaptcha div (margin: 0 auto;display: table), I think it looks much better than a left-aligned div.

How to escape strings in SQL Server using PHP?

Warning: This function was REMOVED in PHP 7.0.0.

http://php.net/manual/en/function.mssql-query.php

For anyone still using these mssql_* functions, keep in mind that they have been removed from PHP as of v7.0.0. So, that means you eventually have to rewrite your model code to either use the PDO library, sqlsrv_* etc. If you're looking for something with a "quoting/escaping" method, I would recommend PDO.

Alternatives to this function include: PDO::query(), sqlsrv_query() and odbc_exec()

Disallow Twitter Bootstrap modal window from closing

If you want to conditionally disable the backdrop click closing feature. You can use the following line to set the backdrop option to static during runtime.

Bootstrap v3.xx

jQuery('#MyModal').data('bs.modal').options.backdrop = 'static';

Bootstrap v2.xx

jQuery('#MyModal').data('modal').options.backdrop = 'static';

This will prevent an already instantiated model with backdrop option set to false (the default behavior), from closing.

Uncaught (in promise) TypeError: Failed to fetch and Cors error

Adding mode:'no-cors' to the request header guarantees that no response will be available in the response

Adding a "non standard" header, line 'access-control-allow-origin' will trigger a OPTIONS preflight request, which your server must handle correctly in order for the POST request to even be sent

You're also doing fetch wrong ... fetch returns a "promise" for a Response object which has promise creators for json, text, etc. depending on the content type...

In short, if your server side handles CORS correctly (which from your comment suggests it does) the following should work

function send(){
    var myVar = {"id" : 1};
    console.log("tuleb siia", document.getElementById('saada').value);
    fetch("http://localhost:3000", {
        method: "POST",
        headers: {
            "Content-Type": "text/plain"
        },
        body: JSON.stringify(myVar)
    }).then(function(response) {
        return response.json();
    }).then(function(muutuja){
        document.getElementById('väljund').innerHTML = JSON.stringify(muutuja);
    });
}

however, since your code isn't really interested in JSON (it stringifies the object after all) - it's simpler to do

function send(){
    var myVar = {"id" : 1};
    console.log("tuleb siia", document.getElementById('saada').value);
    fetch("http://localhost:3000", {
        method: "POST",
        headers: {
            "Content-Type": "text/plain"
        },
        body: JSON.stringify(myVar)
    }).then(function(response) {
        return response.text();
    }).then(function(muutuja){
        document.getElementById('väljund').innerHTML = muutuja;
    });
}

Why should we NOT use sys.setdefaultencoding("utf-8") in a py script?

As per the documentation: This allows you to switch from the default ASCII to other encodings such as UTF-8, which the Python runtime will use whenever it has to decode a string buffer to unicode.

This function is only available at Python start-up time, when Python scans the environment. It has to be called in a system-wide module, sitecustomize.py, After this module has been evaluated, the setdefaultencoding() function is removed from the sys module.

The only way to actually use it is with a reload hack that brings the attribute back.

Also, the use of sys.setdefaultencoding() has always been discouraged, and it has become a no-op in py3k. The encoding of py3k is hard-wired to "utf-8" and changing it raises an error.

I suggest some pointers for reading:

Bootstrap date and time picker

If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:

The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.

numpy array TypeError: only integer scalar arrays can be converted to a scalar index

This could be unrelated to this specific problem, but I ran into a similar issue where I used NumPy indexing on a Python list and got the same exact error message:

# incorrect
weights = list(range(1, 129)) + list(range(128, 0, -1))
mapped_image = weights[image[:, :, band]] # image.shape = [800, 600, 3]
# TypeError: only integer scalar arrays can be converted to a scalar index

It turns out I needed to turn weights, a 1D Python list, into a NumPy array before I could apply multi-dimensional NumPy indexing. The code below works:

# correct
weights = np.array(list(range(1, 129)) + list(range(128, 0, -1)))
mapped_image = weights[image[:, :, band]] # image.shape = [800, 600, 3]

SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable

I just faced the issue when I cloned my repo from Github and ran ./gradlew clean assembleDebug. I confirm I have ANDROID_HOME in my .bashrc file.

So, I imported the project into Android Studio. Noticed that extension of my settings.gradle file is .kts, settings.gradle.kts. When I am done with import then I ran ./gradlew clean assembleDebug and didn't get any issue.

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

I had same problem and it solved by defining kotlin gradle plugin version in build.gradle file.

change this

 classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

to

 classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.50{or latest version}"

Can I store images in MySQL

You'll need to save as a blob, LONGBLOB datatype in mysql will work.

Ex:

CREATE TABLE 'test'.'pic' (
    'idpic' INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
    'caption' VARCHAR(45) NOT NULL,
    'img' LONGBLOB NOT NULL,
  PRIMARY KEY ('idpic')
)

As others have said, its a bad practice but it can be done. Not sure if this code would scale well, though.

When to Redis? When to MongoDB?

Redis and MongoDB are both non-relational databases but they're of different categories.

Redis is a Key/Value database, and it's using In-memory storage which makes it super fast. It's a good candidate for caching stuff and temporary data storage(in memory) and as the most of cloud platforms (such as Azure,AWS) support it, it's memory usage is scalable.But if you're gonna use it on your machines with limited resources, consider it's memory usage.

MongoDB on the other hand, is a document database. It's a good option for keeping large texts, images, videos, etc and almost anything you do with databases except transactions.For example if you wanna develop a blog or social network, MongoDB is a proper choice. It's scalable with scale-out strategy. It uses disk as storage media, so data would be persisted.

Why do python lists have pop() but not push()

Probably because the original version of Python (CPython) was written in C, not C++.

The idea that a list is formed by pushing things onto the back of something is probably not as well-known as the thought of appending them.

How to avoid .pyc files?

I have several test cases in a test suite and before I was running the test suite in the Mac Terminal like this:

python LoginSuite.py

Running the command this way my directory was being populated with .pyc files. I tried the below stated method and it solved the issue:

python -B LoginSuite.py

This method works if you are importing test cases into the test suite and running the suite on the command line.

Redirect using AngularJS

Assuming you're not using html5 routing, try $location.path("route"). This will redirect your browser to #/route which might be what you want.

Create 3D array using Python

"""
Create 3D array for given dimensions - (x, y, z)

@author: Naimish Agarwal
"""


def three_d_array(value, *dim):
    """
    Create 3D-array
    :param dim: a tuple of dimensions - (x, y, z)
    :param value: value with which 3D-array is to be filled
    :return: 3D-array
    """

    return [[[value for _ in xrange(dim[2])] for _ in xrange(dim[1])] for _ in xrange(dim[0])]

if __name__ == "__main__":
    array = three_d_array(False, *(2, 3, 1))
    x = len(array)
    y = len(array[0])
    z = len(array[0][0])
    print x, y, z

    array[0][0][0] = True
    array[1][1][0] = True

    print array

Prefer to use numpy.ndarray for multi-dimensional arrays.

Change Twitter Bootstrap Tooltip content on click

You can just change the data-original-title using the following code:

$(element).attr('data-original-title', newValue);

How to get the nth element of a python list or a default if not available

try:
   a = b[n]
except IndexError:
   a = default

Edit: I removed the check for TypeError - probably better to let the caller handle this.

Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?

I used file_get_contents using stream_create_context and it works fine:

$postdataStr = http_build_query($postdataArr);

$context_options = array (
        'http' => array (    <blink> // this will allways be http!!!</blink>
            'method' => 'POST',
            'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
                . "Content-Length: " . strlen($postdataArr) . "\r\n"
                . "Cookie: " . $cookies."\r\n"
            'content' => $postdataStr
            )
        );

$context = stream_context_create($context_options);
$HTTPSReq = file_get_contents('https://www.example.com/', false, $context);

Java keytool easy way to add server cert from url/port

You can export a certificate using Firefox, this site has instructions. Then you use keytool to add the certificate.

How to view the roles and permissions granted to any database user in Azure SQL server instance?

if you want to find about object name e.g. table name and stored procedure on which particular user has permission, use the following query:

SELECT pr.principal_id, pr.name, pr.type_desc, 
    pr.authentication_type_desc, pe.state_desc, pe.permission_name, OBJECT_NAME(major_id) objectName
FROM sys.database_principals AS pr
JOIN sys.database_permissions AS pe ON pe.grantee_principal_id = pr.principal_id
--INNER JOIN sys.schemas AS s ON s.principal_id =  sys.database_role_members.role_principal_id 
     where pr.name in ('youruser1','youruser2') 

Retrieve a single file from a repository

I use this

$ cat ~/.wgetrc
check_certificate = off

$ wget https://raw.github.com/jquery/jquery/master/grunt.js
HTTP request sent, awaiting response... 200 OK
Length: 11339 (11K) [text/plain]
Saving to: `grunt.js'

Java Enum return Int

Simply call the ordinal() method on an enum value, to retrieve its corresponding number. There's no need to declare an addition attribute with its value, each enumerated value gets its own number by default, assigned starting from zero, incrementing by one for each value in the same order they were declared.

You shouldn't depend on the int value of an enum, only on its actual value. Enums in Java are a different kind of monster and are not like enums in C, where you depend on their integer code.

Regarding the example you provided in the question, Font.PLAIN works because that's just an integer constant of the Font class. If you absolutely need a (possibly changing) numeric code, then an enum is not the right tool for the job, better stick to numeric constants.

SQL Query To Obtain Value that Occurs more than once

For MySQL:

SELECT lastname AS ln 
    FROM 
    (SELECT lastname, count(*) as Counter 
     FROM `students` 
     GROUP BY `lastname`) AS tbl WHERE Counter > 2

C# "must declare a body because it is not marked abstract, extern, or partial"

You can just use the keywork value to accomplish this.

public int Hour {
    get{
        // Do some logic if you want
        //return some custom stuff based on logic

        // or just return the value
        return value;
    }; set { 
        // Do some logic stuff 
        if(value < MINVALUE){
            this.Hour = 0;
        } else {
            // Or just set the value
            this.Hour = value;
        }
    }
}

insert data into database using servlet and jsp in eclipse

I had a similar issue and was able to resolve it by identifying which JDBC driver I intended to use. In my case, I was connecting to an Oracle database. I placed the following statement, prior to creating the connection variable.

DriverManager.registerDriver( new oracle.jdbc.driver.OracleDriver());

Getting "conflicting types for function" in C, why?

When you don't give a prototype for the function before using it, C assumes that it takes any number of parameters and returns an int. So when you first try to use do_something, that's the type of function the compiler is looking for. Doing this should produce a warning about an "implicit function declaration".

So in your case, when you actually do declare the function later on, C doesn't allow function overloading, so it gets pissy because to it you've declared two functions with different prototypes but with the same name.

Short answer: declare the function before trying to use it.

"Specified argument was out of the range of valid values"

try this.

if (ViewState["CurrentTable"] != null)
            {
                DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
                DataRow drCurrentRow = null;
                if (dtCurrentTable.Rows.Count > 0)
                {
                    for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                    {
                        //extract the TextBox values
                        TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("txt_type");
                        TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("txt_total");
                        TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("txt_max");
                        TextBox box4 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("txt_min");
                        TextBox box5 = (TextBox)Gridview1.Rows[i].Cells[5].FindControl("txt_rate");

                        drCurrentRow = dtCurrentTable.NewRow();
                        drCurrentRow["RowNumber"] = i + 1;

                        dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
                        dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
                        dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
                        dtCurrentTable.Rows[i - 1]["Column4"] = box4.Text;
                        dtCurrentTable.Rows[i - 1]["Column5"] = box5.Text;

                        rowIndex++;
                    }
                    dtCurrentTable.Rows.Add(drCurrentRow);
                    ViewState["CurrentTable"] = dtCurrentTable;

                    Gridview1.DataSource = dtCurrentTable;
                    Gridview1.DataBind();
                }
            }
            else
            {
                Response.Write("ViewState is null");
            }

How to empty a list?

You could try:

alist[:] = []

Which means: Splice in the list [] (0 elements) at the location [:] (all indexes from start to finish)

The [:] is the slice operator. See this question for more information.

https connection using CURL from command line

For me, I just wanted to test a website that had an automatic http->https redirect. I think I had some certs installed already, so this alone works for me on Ubuntu 16.04 running curl 7.47.0 (x86_64-pc-linux-gnu) libcurl/7.47.0 GnuTLS/3.4.10 zlib/1.2.8 libidn/1.32 librtmp/2.3

curl --proto-default https <target>

Sleep function Visual Basic

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

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

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

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

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

Linux Script to check if process is running and act on the result

In case you're looking for a more modern way to check to see if a service is running (this will not work for just any old process), then systemctl might be what you're looking for.

Here's the basic command:

systemctl show --property=ActiveState your_service_here

Which will yield very simple output (one of the following two lines will appear depending on whether the service is running or not running):

ActiveState=active
ActiveState=inactive

And if you'd like to know all of the properties you can get:

systemctl show --all your_service_here

If you prefer that alphabetized:

systemctl show --all your_service_here | sort

And the full code to act on it:

service=$1
result=`systemctl show --property=ActiveState $service`
if [[ "$result" == 'ActiveState=active' ]]; then
    echo "$service is running" # Do something here
else
    echo "$service is not running" # Do something else here
fi 

Angular CLI Error: The serve command requires to be run in an Angular project, but a project definition could not be found

In your Package Manager Console run the command

PM> cd NameofApp 

then you can try to run the command there.For instance

PM > ng generate component Home

Query to display all tablespaces in a database and datafiles

In oracle, generally speaking, there are number of facts that I will mention in following section:

  • Each database can have many Schema/User (Logical division).
  • Each database can have many tablespaces (Logical division).
  • A schema is the set of objects (tables, indexes, views, etc) that belong to a user.
  • In Oracle, a user can be considered the same as a schema.
  • A database is divided into logical storage units called tablespaces, which group related logical structures together. For example, tablespaces commonly group all of an application’s objects to simplify some administrative operations. You may have a tablespace for application data and an additional one for application indexes.

Therefore, your question, "to see all tablespaces and datafiles belong to SCOTT" is s bit wrong.

However, there are some DBA views encompass information about all database objects, regardless of the owner. Only users with DBA privileges can access these views: DBA_DATA_FILES, DBA_TABLESPACES, DBA_FREE_SPACE, DBA_SEGMENTS.

So, connect to your DB as sysdba and run query through these helpful views. For example this query can help you to find all tablespaces and their data files that objects of your user are located:

SELECT DISTINCT sgm.TABLESPACE_NAME , dtf.FILE_NAME
FROM DBA_SEGMENTS sgm
JOIN DBA_DATA_FILES dtf ON (sgm.TABLESPACE_NAME = dtf.TABLESPACE_NAME)
WHERE sgm.OWNER = 'SCOTT'

Sending JWT token in the headers with Postman

Somehow postman didn't work for me. I had to use a chrome extension called RESTED which did work.

Why is processing a sorted array faster than processing an unsorted array?

This question has already been answered excellently many times over. Still I'd like to draw the group's attention to yet another interesting analysis.

Recently this example (modified very slightly) was also used as a way to demonstrate how a piece of code can be profiled within the program itself on Windows. Along the way, the author also shows how to use the results to determine where the code is spending most of its time in both the sorted & unsorted case. Finally the piece also shows how to use a little known feature of the HAL (Hardware Abstraction Layer) to determine just how much branch misprediction is happening in the unsorted case.

The link is here: A Demonstration of Self-Profiling

How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator

Swift5

(Java's substring method):

extension String {
    func subString(from: Int, to: Int) -> String {
       let startIndex = self.index(self.startIndex, offsetBy: from)
       let endIndex = self.index(self.startIndex, offsetBy: to)
       return String(self[startIndex..<endIndex])
    }
}

Usage:

var str = "Hello, Nick Michaels"
print(str.subString(from:7,to:20))
// print Nick Michaels

Error: 'int' object is not subscriptable - Python

x is already integer(x=0) and again you trying to make x again integer and also you gave indexing which is beyound the limit because x already has only one indexing (0) and you are trying to give indexing same as age so thats why you get this error. use this simple code

name1 = input("What's your name? ")
age1 = int(input ("how old are you?" ))
x=0
twentyone = str(21-age1)
print("Hi, " +name1+ " you will be 21 in: " + twentyone + " years.")

python: restarting a loop

a = ['1', '2', '3']
ls = []
count = False

while ls != a :
    print(a[count])
    if a[count] != a[-1] :
        count = count + 1
    else :
        count = False

Restart while loop.

Is there a CSS selector for elements containing certain text?

You could set content as data attribute and then use attribute selectors, as shown here:

_x000D_
_x000D_
/* Select every cell containing word "male" */
td[data-content="male"] {
  color: red;
}

/* Select every cell starting on "p" case insensitive */
td[data-content^="p" i] {
  color: blue;
}

/* Select every cell containing "4" */
td[data-content*="4"] {
  color: green;
}
_x000D_
<table>
  <tr>
    <td data-content="Peter">Peter</td>
    <td data-content="male">male</td>
    <td data-content="34">34</td>
  </tr>
  <tr>
    <td data-content="Susanne">Susanne</td>
    <td data-content="female">female</td>
    <td data-content="14">14</td>
  </tr>
</table>
_x000D_
_x000D_
_x000D_

You can also use jQuery to easily set the data-content attributes:

$(function(){
  $("td").each(function(){
    var $this = $(this);
    $this.attr("data-content", $this.text());
  });
});

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

Since iOS 11, you can use the native framework called PDFKit for displaying and manipulating PDFs.

After importing PDFKit, you should initialize a PDFView with a local or a remote URL and display it in your view.

if let url = Bundle.main.url(forResource: "example", withExtension: "pdf") {
    let pdfView = PDFView(frame: view.frame)
    pdfView.document = PDFDocument(url: url)
    view.addSubview(pdfView)
}

Read more about PDFKit in the Apple Developer documentation.

Why can't radio buttons be "readonly"?

What about capturing an "On_click()" event in JS and checking it like here?:

http://www.dynamicdrive.com/forums/showthread.php?t=33043

How to have jQuery restrict file types on upload?

For the front-end it is pretty convenient to put 'accept' attribute if you are using a file field.

Example:

<input id="file" type="file" name="file" size="30" 
       accept="image/jpg,image/png,image/jpeg,image/gif" 
/>

A couple of important notes:

How do I get an animated gif to work in WPF?

Small improvement of GifImage.Initialize() method, which reads proper frame timing from GIF metadata.

    private void Initialize()
    {
        _gifDecoder = new GifBitmapDecoder(new Uri("pack://application:,,," + this.GifSource), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

        int duration=0;
        _animation = new Int32AnimationUsingKeyFrames();
        _animation.KeyFrames.Add(new DiscreteInt32KeyFrame(0, KeyTime.FromTimeSpan(new TimeSpan(0))));
        foreach (BitmapFrame frame in _gifDecoder.Frames)
        {
            BitmapMetadata btmd = (BitmapMetadata)frame.Metadata;
            duration += (ushort)btmd.GetQuery("/grctlext/Delay");
            _animation.KeyFrames.Add(new DiscreteInt32KeyFrame(_gifDecoder.Frames.IndexOf(frame)+1, KeyTime.FromTimeSpan(new TimeSpan(duration*100000))));
        }            
         _animation.RepeatBehavior = RepeatBehavior.Forever;
        this.Source = _gifDecoder.Frames[0];            
        _isInitialized = true;
    }

Access to build environment variables from a groovy script in a Jenkins build step (Windows)

build and listener objects are presenting during system groovy execution. You can do this:

def myVar = build.getEnvironment(listener).get('myVar')

Environment variables for java installation

I am going to explain here by pictures for Windows 7.

Please follow the following steps:

Step 1: Go to "Start" and get into the "My Computer" properties

enter image description here

Step 2: Go to "Advance System Setting" and click on it.

enter image description here

Step 3: Go to "Start" and get into the "My Computer" properties

enter image description here

Step 4: The dialog for Environment variable will open like this:

enter image description here

Step 5: Go to path and click on edit.

enter image description here

Step 6: Put the path of your JDK wherever it resides up to bin like you can see in the picture. Also add path from your sdk of Android up to the Platform Tools:

enter image description here

How to split a line into words separated by one or more spaces in bash?

echo $line | tr " " "\n"

gives the output similar to those of most of the answers above; without using loops.


In your case, you also mention ll=<...output...>,
so, (given that I don't know much python and assuming you need to assign output to a variable),

ll=`echo $line | tr " " "\n"`

should suffice (remember to echo "$ll" instead of echo $ll)

C++, How to determine if a Windows Process is running?

#include <cstdio>
#include <windows.h>
#include <tlhelp32.h>

/*!
\brief Check if a process is running
\param [in] processName Name of process to check if is running
\returns \c True if the process is running, or \c False if the process is not running
*/
bool IsProcessRunning(const wchar_t *processName)
{
    bool exists = false;
    PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);

    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);

    if (Process32First(snapshot, &entry))
        while (Process32Next(snapshot, &entry))
            if (!wcsicmp(entry.szExeFile, processName))
                exists = true;

    CloseHandle(snapshot);
    return exists;
}

How can I toggle word wrap in Visual Studio?

Following https://docs.microsoft.com/en-gb/visualstudio/ide/reference/how-to-manage-word-wrap-in-the-editor

When viewing a document: Edit / Advanced / Word Wrap (Ctrl+E, Ctrl+W)

General settings: Tools / Options / Text Editor / All Languages / Word wrap

Or search for 'word wrap' in the Quick Launch box.


Known issues:

If you're familiar with word wrap in Notepad++, Sublime Text, or Visual Studio Code, be aware of the following issues where Visual Studio behaves differently to other editors:

  1. Triple click doesn't select whole line
  2. Cut command doesn't delete whole line
  3. Pressing End key twice does not move cursor to end of line

Unfortunately these bugs have been closed "lower priority". If you'd like these bugs fixed, please vote for the feature request Fix known issues with word wrap.

How to align center the text in html table row?

<td align="center"valign="center">textgoeshere</td>

more on valign

A url resource that is a dot (%2E)

It's actually not really clearly stated in the standard (RFC 3986) whether a percent-encoded version of . or .. is supposed to have the same this-folder/up-a-folder meaning as the unescaped version. Section 3.3 only talks about “The path segments . and ..”, without clarifying whether they match . and .. before or after pct-encoding.

Personally I find Firefox's interpretation that %2E does not mean . most practical, but unfortunately all the other browsers disagree. This would mean that you can't have a path component containing only . or ...

I think the only possible suggestion is “don't do that”! There are other path components that are troublesome too, typically due to server limitations: %2F, %00 and %5C sequences in paths may also be blocked by some web servers, and the empty path segment can also cause problems. So in general it's not possible to fit all possible byte sequences into a path component.

Setting the character encoding in form submit for Internet Explorer

It seems that this can't be done, not at least with current versions of IE (6 and 7).

IE supports form attribute accept-charset, but only if its value is 'utf-8'.

The solution is to modify server A to produce encoding 'ISO-8859-1' for page that contains the form.

Background thread with QThread in PyQt

PySide2 Solution:

Unlike in PyQt5, in PySide2 the QThread.started signal is received/handled on the original thread, not the worker thread! Luckily it still receives all other signals on the worker thread.

In order to match PyQt5's behavior, you have to create the started signal yourself.

Here is an easy solution:

# Use this class instead of QThread
class QThread2(QThread):
    # Use this signal instead of "started"
    started2 = Signal()

    def __init__(self):
        QThread.__init__(self)
        self.started.connect(self.onStarted)

    def onStarted(self):
        self.started2.emit()

Replacing Spaces with Underscores

I used like this

$option = trim($option);
$option = str_replace(' ', '_', $option);

How to define static constant in a class in swift

Some might want certain class constants public while others private.

private keyword can be used to limit the scope of constants within the same swift file.

class MyClass {

struct Constants {

    static let testStr = "test"
    static let testStrLen = testStr.characters.count

    //testInt will not be accessable by other classes in different swift files
    private static let testInt = 1
}

func ownFunction()
{

    var newInt = Constants.testInt + 1

    print("Print testStr=\(Constants.testStr)")
}

}

Other classes will be able to access your class constants like below

class MyClass2
{

func accessOtherConstants()
{
    print("MyClass's testStr=\(MyClass.Constants.testStr)")
}

} 

How to convert object array to string array in Java

For your idea, actually you are approaching the success, but if you do like this should be fine:

for (int i=0;i<String_Array.length;i++) String_Array[i]=(String)Object_Array[i];

BTW, using the Arrays utility method is quite good and make the code elegant.

How to send data with angularjs $http.delete() request?

My suggestion:

$http({
    method: 'DELETE',
    url: '/roles/' + roleid,
    data: {
        user: userId
    },
    headers: {
        'Content-type': 'application/json;charset=utf-8'
    }
})
.then(function(response) {
    console.log(response.data);
}, function(rejection) {
    console.log(rejection.data);
});

What are the different usecases of PNG vs. GIF vs. JPEG vs. SVG?

GIF has 8 bit (256 color) palette where PNG as upto 24 bit color palette. So, PNG can support more color and of course the algorithm support compression

Create a text file for download on-the-fly

Check out this SO question's accepted solution. Substitute your own filename for basename($File) and change filesize($File) to strlen($your_string). (You may want to use mb_strlen just in case the string contains multibyte characters.)

Disabling submit button until all fields have values

This works well since all the inputs have to meet the condition of not null.

$(function () {
    $('#submits').attr('disabled', true);
    $('#input_5').change(function () {
        if ($('#input_1').val() != '' && $('#input_2').val() != '' && $('#input_3').val() != '' && $('#input_4').val() != '' && $('#input_5').val() != '') {
            $('#submit').attr('disabled', false);
        } else {
            $('#submit').attr('disabled', true);
        }
     });
 });

Property '...' has no initializer and is not definitely assigned in the constructor

If you want to initialize an object based on an interface you can initialize it empty with following statement.

myObj: IMyObject = {} as IMyObject;

Refreshing data in RecyclerView and keeping its scroll position

EDIT: To restore the exact same apparent position, as in, make it look exactly like it did, we need to do something a bit different (See below how to restore the exact scrollY value):

Save the position and offset like this:

LinearLayoutManager manager = (LinearLayoutManager) mRecycler.getLayoutManager();
int firstItem = manager.findFirstVisibleItemPosition();
View firstItemView = manager.findViewByPosition(firstItem);
float topOffset = firstItemView.getTop();

outState.putInt(ARGS_SCROLL_POS, firstItem);
outState.putFloat(ARGS_SCROLL_OFFSET, topOffset);

And then restore the scroll like this:

LinearLayoutManager manager = (LinearLayoutManager) mRecycler.getLayoutManager();
manager.scrollToPositionWithOffset(mStatePos, (int) mStateOffset);

This restores the list to its exact apparent position. Apparent because it will look the same to the user, but it will not have the same scrollY value (because of possible differences in landscape/portrait layout dimensions).

Note that this only works with LinearLayoutManager.

--- Below how to restore the exact scrollY, which will likely make the list look different ---

  1. Apply an OnScrollListener like so:

    private int mScrollY;
    private RecyclerView.OnScrollListener mTotalScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            mScrollY += dy;
        }
    };
    

This will store the exact scroll position at all times in mScrollY.

  1. Store this variable in your Bundle, and restore it in state restoration to a different variable, we'll call it mStateScrollY.

  2. After state restoration and after your RecyclerView has reset all its data reset the scroll with this:

    mRecyclerView.scrollBy(0, mStateScrollY);
    

That's it.

Beware, that you restore the scroll to a different variable, this is important, because the OnScrollListener will be called with .scrollBy() and subsequently will set mScrollY to the value stored in mStateScrollY. If you do not do this mScrollY will have double the scroll value (because the OnScrollListener works with deltas, not absolute scrolls).

State saving in activities can be achieved like this:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt(ARGS_SCROLL_Y, mScrollY);
}

And to restore call this in your onCreate():

if(savedState != null){
    mStateScrollY = savedState.getInt(ARGS_SCROLL_Y, 0);
}

State saving in fragments works in a similar way, but the actual state saving needs a bit of extra work, but there are plenty of articles dealing with that, so you shouldn't have a problem finding out how, the principles of saving the scrollY and restoring it remain the same.