Programs & Examples On #Paramiko

Paramiko is a Python module that implements the SSH2 protocol.

How to ssh connect through python Paramiko with ppk public key

To create a valid DSA format private key supported by Paramiko in Puttygen.

Click on Conversions then Export OpenSSH Key

enter image description here

How to scp in Python?

Hmmm, perhaps another option would be to use something like sshfs (there an sshfs for Mac too). Once your router is mounted you can just copy the files outright. I'm not sure if that works for your particular application but it's a nice solution to keep handy.

Running interactive commands in Paramiko

The full paramiko distribution ships with a lot of good demos.

In the demos subdirectory, demo.py and interactive.py have full interactive TTY examples which would probably be overkill for your situation.

In your example above ssh_stdin acts like a standard Python file object, so ssh_stdin.write should work so long as the channel is still open.

I've never needed to write to stdin, but the docs suggest that a channel is closed as soon as a command exits, so using the standard stdin.write method to send a password up probably won't work. There are lower level paramiko commands on the channel itself that give you more control - see how the SSHClient.exec_command method is implemented for all the gory details.

Paramiko's SSHClient with SFTP

If you have a SSHClient, you can also use open_sftp():

import paramiko


# lets say you have SSH client...
client = paramiko.SSHClient()

sftp = client.open_sftp()

# then you can use upload & download as shown above
...

python paramiko ssh

There is something wrong with the accepted answer, it sometimes (randomly) brings a clipped response from server. I do not know why, I did not investigate the faulty cause of the accepted answer because this code worked perfectly for me:

import paramiko

ip='server ip'
port=22
username='username'
password='password'

cmd='some useful command' 

ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)

stdin,stdout,stderr=ssh.exec_command(cmd)
outlines=stdout.readlines()
resp=''.join(outlines)
print(resp)

stdin,stdout,stderr=ssh.exec_command('some really useful command')
outlines=stdout.readlines()
resp=''.join(outlines)
print(resp)

Jquery and HTML FormData returns "Uncaught TypeError: Illegal invocation"

Adding processData: false to the $.ajax options will fix this issue.

How to tell which commit a tag points to in Git?

I'd also like to know the "right" way, but in the meantime, you can do this:

git show mytag | head -1    

What column type/length should I use for storing a Bcrypt hashed password in a Database?

The modular crypt format for bcrypt consists of

  • $2$, $2a$ or $2y$ identifying the hashing algorithm and format
  • a two digit value denoting the cost parameter, followed by $
  • a 53 characters long base-64-encoded value (they use the alphabet ., /, 09, AZ, az that is different to the standard Base 64 Encoding alphabet) consisting of:
    • 22 characters of salt (effectively only 128 bits of the 132 decoded bits)
    • 31 characters of encrypted output (effectively only 184 bits of the 186 decoded bits)

Thus the total length is 59 or 60 bytes respectively.

As you use the 2a format, you’ll need 60 bytes. And thus for MySQL I’ll recommend to use the CHAR(60) BINARYor BINARY(60) (see The _bin and binary Collations for information about the difference).

CHAR is not binary safe and equality does not depend solely on the byte value but on the actual collation; in the worst case A is treated as equal to a. See The _bin and binary Collations for more information.

What does it mean to "program to an interface"?

An interface is like a contract, where you want your implementation class to implement methods written in the contract (interface). Since Java does not provide multiple inheritance, "programming to interface" is a good way to achieve multiple inheritance.

If you have a class A that is already extending some other class B, but you want that class A to also follow certain guidelines or implement a certain contract, then you can do so by the "programming to interface" strategy.

ImageView in android XML layout with layout_height="wrap_content" has padding top & bottom

I had a simular issue and resolved it using android:adjustViewBounds="true" on the ImageView.

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:contentDescription="@string/banner_alt"
    android:src="@drawable/banner_portrait" />

Make page to tell browser not to cache/preserve input values

From a Stack Overflow reference

It did not work with value="" if the browser already saves the value so you should add.

For an input tag there's the attribute autocomplete you can set:

<input type="text" autocomplete="off" />

You can use autocomplete for a form too.

Python - Dimension of Data Frame

df.shape, where df is your DataFrame.

How to install npm peer dependencies automatically?

The project npm-install-peers will detect peers and install them.

As of v1.0.1 it doesn't support writing back to the package.json automatically, which would essentially solve our need here.

Please add your support to issue in flight: https://github.com/spatie/npm-install-peers/issues/4

Is Java "pass-by-reference" or "pass-by-value"?

I have created a thread devoted to these kind of questions for any programming languages here.

Java is also mentioned. Here is the short summary:

  • Java passes it parameters by value
  • "by value" is the only way in java to pass a parameter to a method
  • using methods from the object given as parameter will alter the object as the references point to the original objects. (if that method itself alters some values)

how to install apk application from my pc to my mobile android

1.question answer-In your mobile having Developer Option in settings and enable that one. after In android studio project source file in bin--> apk file .just copy the apk file and paste in mobile memory in ur pc.. after all finished .you click that apk file in your mobile is automatically installed.

2.question answer-Your mobile is Samsung are just add Samsung Kies software in your pc..its helps to android code run in your mobile ...

ITextSharp HTML to PDF?

I came across the same question a few weeks ago and this is the result from what I found. This method does a quick dump of HTML to a PDF. The document will most likely need some format tweaking.

private MemoryStream createPDF(string html)
{
    MemoryStream msOutput = new MemoryStream();
    TextReader reader = new StringReader(html);

    // step 1: creation of a document-object
    Document document = new Document(PageSize.A4, 30, 30, 30, 30);

    // step 2:
    // we create a writer that listens to the document
    // and directs a XML-stream to a file
    PdfWriter writer = PdfWriter.GetInstance(document, msOutput);

    // step 3: we create a worker parse the document
    HTMLWorker worker = new HTMLWorker(document);

    // step 4: we open document and start the worker on the document
    document.Open();
    worker.StartDocument();

    // step 5: parse the html into the document
    worker.Parse(reader);

    // step 6: close the document and the worker
    worker.EndDocument();
    worker.Close();
    document.Close();

    return msOutput;
}

@RequestParam vs @PathVariable

If the URL http://localhost:8080/MyApp/user/1234/invoices?date=12-05-2013 gets the invoices for user 1234 on December 5th, 2013, the controller method would look like:

@RequestMapping(value="/user/{userId}/invoices", method = RequestMethod.GET)
public List<Invoice> listUsersInvoices(
            @PathVariable("userId") int user,
            @RequestParam(value = "date", required = false) Date dateOrNull) {
  ...
}

Also, request parameters can be optional, and as of Spring 4.3.3 path variables can be optional as well. Beware though, this might change the URL path hierarchy and introduce request mapping conflicts. For example, would /user/invoices provide the invoices for user null or details about a user with ID "invoices"?

ImportError: Couldn't import Django

If you are using python 3 use py in front of cmd code, like this

py manage.py runserver

How can I set the default value for an HTML <select> element?

I myself use it

<select selected=''>
    <option value=''></option>
    <option value='1'>ccc</option>
    <option value='2'>xxx</option>
    <option value='3'>zzz</option>
    <option value='4'>aaa</option>
    <option value='5'>qqq</option>
    <option value='6'>wwww</option>
</select>

Spring Boot - Cannot determine embedded database driver class for database type NONE

In my case , I put it a maven dependency for org.jasig.cas in my pom that triggered a hibernate dependency and that caused Spring Boot to look for a datasource to auto-configure hibernate persistence. I solved it by adding the com.h2database maven dependency as suggested by user672009. Thanks guys!

Allow 2 decimal places in <input type="number">

I found using jQuery was my best solution.

$( "#my_number_field" ).blur(function() {
    this.value = parseFloat(this.value).toFixed(2);
});

What's a redirect URI? how does it apply to iOS app for OAuth2.0?

If you are using Facebook SDK, you don't need to bother yourself to enter anything for redirect URI on the app management page of facebook. Just setup a URL scheme for your iOS app. The URL scheme of your app should be a value "fbxxxxxxxxxxx" where xxxxxxxxxxx is your app id as identified on facebook. To setup URL scheme for your iOS app, go to info tab of your app settings and add URL Type.

How do I insert an image in an activity with android studio?

copy the image that you want to show in android app and paste in drawable folder. given below code

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/image"
 />

Subtract a value from every number in a list in Python?

You can use map() function:

a = list(map(lambda x: x - 13, a))

I can’t find the Android keytool

Ok I did this in Windows 7 32-bit system.

step 1: go to - C:\Program Files\Java\jdk1.6.0_26\bin - and run jarsigner.exe first ( double click)

step2: locate debug.keystore, in my case it was - C:\Users\MyPcName\.android

step3: open command prompt and go to dir - C:\Program Files\Java\jdk1.6.0_26\bin and give the following command: keytool -list -keystore "C:\Users\MyPcName\.android\debug.keystore"

step4: it will ask for Keystore password now. ( which I am figuring out... :-? )

update: OK in my case password was ´ android ´. - (I am using Eclipse for android, so I found it here) Follow the steps in eclipse: Windows>preferences>android>build>..
( Look in `default Debug Keystore´ field.)



Command to change the keystore password (look here): Keystore change passwords



Difference between clean, gradlew clean

You can also use

./gradlew clean build (Mac and Linux) -With ./

gradlew clean build (Windows) -Without ./

it removes build folder, as well configure your modules and then build your project.

i use it before release any new app on playstore.

What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim?

I think the Vim documentation should've explained the meaning behind the naming of these commands. Just telling you what they do doesn't help you remember the names.

map is the "root" of all recursive mapping commands. The root form applies to "normal", "visual+select", and "operator-pending" modes. (I'm using the term "root" as in linguistics.)

noremap is the "root" of all non-recursive mapping commands. The root form applies to the same modes as map. (Think of the nore prefix to mean "non-recursive".)

(Note that there are also the ! modes like map! that apply to insert & command-line.)

See below for what "recursive" means in this context.

Prepending a mode letter like n modify the modes the mapping works in. It can choose a subset of the list of applicable modes (e.g. only "visual"), or choose other modes that map wouldn't apply to (e.g. "insert").

Use help map-modes will show you a few tables that explain how to control which modes the mapping applies to.

Mode letters:

  • n: normal only
  • v: visual and select
  • o: operator-pending
  • x: visual only
  • s: select only
  • i: insert
  • c: command-line
  • l: insert, command-line, regexp-search (and others. Collectively called "Lang-Arg" pseudo-mode)

"Recursive" means that the mapping is expanded to a result, then the result is expanded to another result, and so on.

The expansion stops when one of these is true:

  1. the result is no longer mapped to anything else.
  2. a non-recursive mapping has been applied (i.e. the "noremap" [or one of its ilk] is the final expansion).

At that point, Vim's default "meaning" of the final result is applied/executed.

"Non-recursive" means the mapping is only expanded once, and that result is applied/executed.

Example:

 nmap K H
 nnoremap H G
 nnoremap G gg

The above causes K to expand to H, then H to expand to G and stop. It stops because of the nnoremap, which expands and stops immediately. The meaning of G will be executed (i.e. "jump to last line"). At most one non-recursive mapping will ever be applied in an expansion chain (it would be the last expansion to happen).

The mapping of G to gg only applies if you press G, but not if you press K. This mapping doesn't affect pressing K regardless of whether G was mapped recursively or not, since it's line 2 that causes the expansion of K to stop, so line 3 wouldn't be used.

Changing background color of selected cell?

Here is a quick way to do this right in Interface Builder (within a Storyboard). Drag a simple UIView to the top of your UITableView as in UIView Next connect your cell's selectedBackgroundView Outlet to this view. You can even connect multiple cells' outlets to this one view. Cell's outlet

How to deal with page breaks when printing a large HTML table

I've tried all suggestions given above and found simple and working cross browser solution for this issue. There is no styles or page break needed for this solution. For the solution, the format of the table should be like:

<table>
    <thead>  <!-- there should be <thead> tag-->
        <td>Heading</td> <!--//inside <thead> should be <td> it should not be <th>-->
    </thead>
    <tbody><!---<tbody>also must-->
        <tr>
            <td>data</td>
        </tr>
        <!--100 more rows-->
    </tbody>
</table>

Above format tested and working in cross browsers

Python xml ElementTree from a string source?

You need the xml.etree.ElementTree.fromstring(text)

from xml.etree.ElementTree import XML, fromstring
myxml = fromstring(text)

HttpClient won't import in Android Studio

For android API 28 and higher in Manifest.xml inside application tag

    <application
    .
    .
    .

    <uses-library android:name="org.apache.http.legacy" android:required="false"/>

PHP exec() vs system() vs passthru()

It really all comes down to how you want to handle output that the command might return and whether you want your PHP script to wait for the callee program to finish or not.

  • exec executes a command and passes output to the caller (or returns it in an optional variable).

  • passthru is similar to the exec() function in that it executes a command . This function should be used in place of exec() or system() when the output from the Unix command is binary data which needs to be passed directly back to the browser.

  • system executes an external program and displays the output, but only the last line.

If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

Generate PDF from HTML using pdfMake in Angularjs

Okay, I figured this out.

  1. You will need html2canvas and pdfmake. You do NOT need to do any injection in your app.js to either, just include in your script tags

  2. On the div that you want to create the PDF of, add an ID name like below:

     <div id="exportthis">
    
  3. In your Angular controller use the id of the div in your call to html2canvas:

  4. change the canvas to an image using toDataURL()

  5. Then in your docDefinition for pdfmake assign the image to the content.

  6. The completed code in your controller will look like this:

           html2canvas(document.getElementById('exportthis'), {
                onrendered: function (canvas) {
                    var data = canvas.toDataURL();
                    var docDefinition = {
                        content: [{
                            image: data,
                            width: 500,
                        }]
                    };
                    pdfMake.createPdf(docDefinition).download("Score_Details.pdf");
                }
            });
    

I hope this helps someone else. Happy coding!

Getting next element while cycling through a list

while running:
    lenli = len(li)
    for i, elem in enumerate(li):
        thiselem = elem
        nextelem = li[(i+1)%lenli]

Disable text input history

<input type="text" autocomplete="off"/>

Should work. Alternatively, use:

<form autocomplete="off" … >

for the entire form (see this related question).

How to convert a structure to a byte array in C#?

I've come up with a different approach that could convert any struct without the hassle of fixing length, however the resulting byte array would have a little bit more overhead.

Here is a sample struct:

[StructLayout(LayoutKind.Sequential)]
public class HelloWorld
{
    public MyEnum enumvalue;
    public string reqtimestamp;
    public string resptimestamp;
    public string message;
    public byte[] rawresp;
}

As you can see, all those structures would require adding the fixed length attributes. Which could often ended up taking up more space than required. Note that the LayoutKind.Sequential is required, as we want reflection to always gives us the same order when pulling for FieldInfo. My inspiration is from TLV Type-Length-Value. Let's have a look at the code:

public static byte[] StructToByteArray<T>(T obj)
{
    using (MemoryStream ms = new MemoryStream())
    {
        FieldInfo[] infos = typeof(T).GetFields(BindingFlags.Public | BindingFlags.Instance);
        foreach (FieldInfo info in infos)
        {
            BinaryFormatter bf = new BinaryFormatter();
            using (MemoryStream inms = new MemoryStream()) {

                bf.Serialize(inms, info.GetValue(obj));
                byte[] ba = inms.ToArray();
                // for length
                ms.Write(BitConverter.GetBytes(ba.Length), 0, sizeof(int));

                // for value
                ms.Write(ba, 0, ba.Length);
            }
        }

        return ms.ToArray();
    }
}

The above function simply uses the BinaryFormatter to serialize the unknown size raw object, and I simply keep track of the size as well and store it inside the output MemoryStream too.

public static void ByteArrayToStruct<T>(byte[] data, out T output)
{
    output = (T) Activator.CreateInstance(typeof(T), null);
    using (MemoryStream ms = new MemoryStream(data))
    {
        byte[] ba = null;
        FieldInfo[] infos = typeof(T).GetFields(BindingFlags.Public | BindingFlags.Instance);
        foreach (FieldInfo info in infos)
        {
            // for length
            ba = new byte[sizeof(int)];
            ms.Read(ba, 0, sizeof(int));

            // for value
            int sz = BitConverter.ToInt32(ba, 0);
            ba = new byte[sz];
            ms.Read(ba, 0, sz);

            BinaryFormatter bf = new BinaryFormatter();
            using (MemoryStream inms = new MemoryStream(ba))
            {
                info.SetValue(output, bf.Deserialize(inms));
            }
        }
    }
}

When we want to convert it back to its original struct we simply read the length back and directly dump it back into the BinaryFormatter which in turn dump it back into the struct.

These 2 functions are generic and should work with any struct, I've tested the above code in my C# project where I have a server and a client, connected and communicate via NamedPipeStream and I forward my struct as byte array from one and to another and converted it back.

I believe my approach might be better, since it doesn't fix length on the struct itself and the only overhead is just an int for every fields you have in your struct. There are also some tiny bit overhead inside the byte array generated by BinaryFormatter, but other than that, is not much.

Eclipse won't compile/run java file

right click somewhere on the file or in project explorer and choose 'run as'->'java application'

How to remove an element from the flow?

Try to use this:

position: relative;
clear: both;

I use it when I can't use absolute position, for example in printing when you use page-break-after: always; works fine only with position:relative.

How do we change the URL of a working GitLab install?

You did everything correctly!

You might also change the email configuration, depending on if the email server is also the same server. The email configuration is in gitlab.yml for the mails sent by GitLab and also the admin-email.

Why do you need to invoke an anonymous function on the same line?

The code you show,

(function (msg){alert(msg)});
('SO');

consist of two statements. The first is an expression which yields a function object (which will then be garbage collected because it is not saved). The second is an expression which yields a string. To apply the function to the string, you either need to pass the string as an argument to the function when it is created (which you also show above), or you will need to actually store the function in a variable, so that you can apply it at a later time, at your leisure. Like so:

var f = (function (msg){alert(msg)});
f('SO');

Note that by storing an anonymous function (a lambda function) in a variable, your are effectively giving it a name. Hence you may just as well define a regular function:

function f(msg) {alert(msg)};
f('SO');

HTML tag <a> want to add both href and onclick working

To achieve this use following html:

<a href="www.mysite.com" onclick="make(event)">Item</a>

<script>
    function make(e) {
        // ...  your function code
        // e.preventDefault();   // use this to NOT go to href site
    }
</script>

Here is working example.

SSL error SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

The problem is in new PHP Version in macOS Sierra

Please add

stream_context_set_option($ctx, 'ssl', 'verify_peer', false);

Using jQuery To Get Size of Viewport

To get size of viewport on load and on resize (based on SimaWB response):

function getViewport() {
    var viewportWidth = $(window).width();
    var viewportHeight = $(window).height();
    $('#viewport').html('Viewport: '+viewportWidth+' x '+viewportHeight+' px');
}

getViewport();

$(window).resize(function() {
    getViewport()
});

How to use executables from a package installed locally in node_modules?

Use npm-run.

From the readme:

npm-run

Find & run local executables from node_modules

Any executable available to an npm lifecycle script is available to npm-run.

Usage

$ npm install mocha # mocha installed in ./node_modules
$ npm-run mocha test/* # uses locally installed mocha executable 

Installation

$ npm install -g npm-run

When should I use the Visitor Design Pattern?

The reason for your confusion is probably that the Visitor is a fatal misnomer. Many (prominent1!) programmers have stumbled over this problem. What it actually does is implement double dispatching in languages that don't support it natively (most of them don't).


1) My favourite example is Scott Meyers, acclaimed author of “Effective C++”, who called this one of his most important C++ aha! moments ever.

Is the ternary operator faster than an "if" condition in Java

Ternary Operator example:

int a = (i == 0) ? 10 : 5;

You can't do assignment with if/else like this:

// invalid:
int a = if (i == 0) 10; else 5;

This is a good reason to use the ternary operator. If you don't have an assignment:

(i == 0) ? foo () : bar ();

an if/else isn't that much more code:

if (i == 0) foo (); else bar ();

In performance critical cases: measure it. Measure it with the target machine, the target JVM, with typical data, if there is a bottleneck. Else go for readability.

Embedded in context, the short form is sometimes very handy:

System.out.println ("Good morning " + (p.female ? "Miss " : "Mister ") + p.getName ()); 

Get a filtered list of files in a directory

use os.walk to recursively list your files

import os
root = "/home"
pattern = "145992"
alist_filter = ['jpg','bmp','png','gif'] 
path=os.path.join(root,"mydir_to_scan")
for r,d,f in os.walk(path):
    for file in f:
        if file[-3:] in alist_filter and pattern in file:
            print os.path.join(root,file)

Call a function on click event in Angular 2

This worked for me: :)

<button (click)="updatePendingApprovals(''+pendingApproval.personId, ''+pendingApproval.personId)">Approve</button>
updatePendingApprovals(planId: string, participantId: string) : void {
  alert('PlanId:' + planId + '    ParticipantId:' + participantId);
}

R barplot Y-axis scale too short

I see you try to set ylim but you give bad values. This will change the scale of the plot (like a zoom). For example see this:

par(mfrow=c(2,1))
tN <- table(Ni <- stats::rpois(100, lambda = 5))
r <- barplot(tN, col = rainbow(20),ylim=c(0,50),main='long y-axis')
r <- barplot(tN, col = rainbow(20),main='short y axis')

enter image description here Another option is to plot without axes and set them manually using axis and usr:

require(grDevices) # for colours
par(mfrow=c(1,1))
r <- barplot(tN, col = rainbow(20),main='short y axis',ann=FALSE,axes=FALSE)
usr <- par("usr")
par(usr=c(usr[1:2], 0, 20))
axis(2,at=seq(0,20,5))

enter image description here

Simplest way to detect a pinch

You want to use the gesturestart, gesturechange, and gestureend events. These get triggered any time 2 or more fingers touch the screen.

Depending on what you need to do with the pinch gesture, your approach will need to be adjusted. The scale multiplier can be examined to determine how dramatic the user's pinch gesture was. See Apple's TouchEvent documentation for details about how the scale property will behave.

node.addEventListener('gestureend', function(e) {
    if (e.scale < 1.0) {
        // User moved fingers closer together
    } else if (e.scale > 1.0) {
        // User moved fingers further apart
    }
}, false);

You could also intercept the gesturechange event to detect a pinch as it happens if you need it to make your app feel more responsive.

How to delete a localStorage item when the browser window/tab is closed?

There is a very specific use case in which any suggestion to use sessionStorage instead of localStorage does not really help. The use-case would be something as simple as having something stored while you have at least one tab opened, but invalidate it if you close the last tab remaining. If you need your values to be saved cross-tab and window, sessionStorage does not help you unless you complicate your life with listeners, like I have tried. In the meantime localStorage would be perfect for this, but it does the job 'too well', since your data will be waiting there even after a restart of the browser. I ended up using a custom code and logic that takes advantage of both.

I'd rather explain then give code. First store what you need to in localStorage, then also in localStorage create a counter that will contain the number of tabs that you have opened. This will be increased every time the page loads and decreased every time the page unloads. You can have your pick here of the events to use, I'd suggest 'load' and 'unload'. At the time you unload, you need to do the cleanup tasks that you'd like to when the counter reaches 0, meaning you're closing the last tab. Here comes the tricky part: I haven't found a reliable and generic way to tell the difference between a page reload or navigation inside the page and the closing of the tab. So If the data you store is not something that you can rebuild on load after checking that this is your first tab, then you cannot remove it at every refresh. Instead you need to store a flag in sessionStorage at every load before increasing the tab counter. Before storing this value, you can make a check to see if it already has a value and if it doesn't, this means you're loading into this session for the first time, meaning that you can do the cleanup at load if this value is not set and the counter is 0.

Get string character by index - Java

A hybrid approach combining charAt with your requirement of not getting char could be

newstring = String.valueOf("foo".charAt(0));

But that's not really "neater" than substring() to be honest.

Is it possible to change the package name of an Android app on Google Play?

Never, you can't do it since package name is the unique name Identifier for your app.....

Create a GUID in Java

It depends what kind of UUID you want.

  • The standard Java UUID class generates Version 4 (random) UUIDs. (UPDATE - Version 3 (name) UUIDs can also be generated.) It can also handle other variants, though it cannot generate them. (In this case, "handle" means construct UUID instances from long, byte[] or String representations, and provide some appropriate accessors.)

  • The Java UUID Generator (JUG) implementation purports to support "all 3 'official' types of UUID as defined by RFC-4122" ... though the RFC actually defines 4 types and mentions a 5th type.

For more information on UUID types and variants, there is a good summary in Wikipedia, and the gory details are in RFC 4122 and the other specifications.

Android fade in and fade out with ImageView

I wanted to achieve the same goal as you, so I wrote the following method which does exactly that if you pass it an ImageView and a list of references to image drawables.

ImageView demoImage = (ImageView) findViewById(R.id.DemoImage);
int imagesToShow[] = { R.drawable.image1, R.drawable.image2,R.drawable.image3 };

animate(demoImage, imagesToShow, 0,false);  



  private void animate(final ImageView imageView, final int images[], final int imageIndex, final boolean forever) {

  //imageView <-- The View which displays the images
  //images[] <-- Holds R references to the images to display
  //imageIndex <-- index of the first image to show in images[] 
  //forever <-- If equals true then after the last image it starts all over again with the first image resulting in an infinite loop. You have been warned.

    int fadeInDuration = 500; // Configure time values here
    int timeBetween = 3000;
    int fadeOutDuration = 1000;

    imageView.setVisibility(View.INVISIBLE);    //Visible or invisible by default - this will apply when the animation ends
    imageView.setImageResource(images[imageIndex]);

    Animation fadeIn = new AlphaAnimation(0, 1);
    fadeIn.setInterpolator(new DecelerateInterpolator()); // add this
    fadeIn.setDuration(fadeInDuration);

    Animation fadeOut = new AlphaAnimation(1, 0);
    fadeOut.setInterpolator(new AccelerateInterpolator()); // and this
    fadeOut.setStartOffset(fadeInDuration + timeBetween);
    fadeOut.setDuration(fadeOutDuration);

    AnimationSet animation = new AnimationSet(false); // change to false
    animation.addAnimation(fadeIn);
    animation.addAnimation(fadeOut);
    animation.setRepeatCount(1);
    imageView.setAnimation(animation);

    animation.setAnimationListener(new AnimationListener() {
        public void onAnimationEnd(Animation animation) {
            if (images.length - 1 > imageIndex) {
                animate(imageView, images, imageIndex + 1,forever); //Calls itself until it gets to the end of the array
            }
            else {
                if (forever){
                animate(imageView, images, 0,forever);  //Calls itself to start the animation all over again in a loop if forever = true
                }
            }
        }
        public void onAnimationRepeat(Animation animation) {
            // TODO Auto-generated method stub
        }
        public void onAnimationStart(Animation animation) {
            // TODO Auto-generated method stub
        }
    });
}

Httpd returning 503 Service Unavailable with mod_proxy for Tomcat 8

On CentOS Linux release 7.5.1804, we were able to make this work by editing /etc/selinux/config and changing the setting of SELINUX like so:

SELINUX=disabled

Loop through an array of strings in Bash?

None of those answers include a counter...

#!/bin/bash
## declare an array variable
declare -a array=("one" "two" "three")

# get length of an array
arraylength=${#array[@]}

# use for loop to read all values and indexes
for (( i=1; i<${arraylength}+1; i++ ));
do
  echo $i " / " ${arraylength} " : " ${array[$i-1]}
done

Output:

1  /  3  :  one
2  /  3  :  two
3  /  3  :  three

Uri not Absolute exception getting while calling Restful Webservice

Maybe the problem only in your IDE encoding settings. Try to set UTF-8 everywhere:

enter image description here

How do I remove link underlining in my HTML email?

I copied my html page and pasted to word. Edited the signature in word deleting the spaces where the underline is placed and make my own "padding" presssing space bar. Copied again and pasted to Outlook 2013. Worked fine for me.

7-Zip command to create and extract a password-protected ZIP file on Windows?

General Syntax:

7z a archive_name target parameters

Check your 7-Zip dir. Depending on the release you have, 7z may be replaced with 7za in the syntax.

Parameters:

  • -p encrypt and prompt for PW.
  • -pPUT_PASSWORD_HERE (this replaces -p) if you want to preset the PW with no prompt.
  • -mhe=on to hide file structure, otherwise file structure and names will be visible by default.

Eg. This will prompt for a PW and hide file structures:

7z a archive_name target -p -mhe=on

Eg. No prompt, visible file structure:

7z a archive_name target -pPUT_PASSWORD_HERE

And so on. If you leave target blank, 7z will assume * in current directory and it will recurs directories by default.

Remove all of x axis labels in ggplot

You have to set to element_blank() in theme() elements you need to remove

ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

How can I capitalize the first letter of each word in a string using JavaScript?

Or it can be done using replace(), and replace each word's first letter with its "upperCase".

function titleCase(str) {
    return str.toLowerCase().split(' ').map(function(word) {
               return word.replace(word[0], word[0].toUpperCase());
           }).join(' ');
}

titleCase("I'm a little tea pot");

Reading large text files with streams in C#

For binary files, the fastest way of reading them I have found is this.

 MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file);
 MemoryMappedViewStream mms = mmf.CreateViewStream();
 using (BinaryReader b = new BinaryReader(mms))
 {
 }

In my tests it's hundreds of times faster.

Android App Not Install. An existing package by the same name with a conflicting signature is already installed

If you don't want to bother with the keystore file, then just remove the package altogether for all users.

Connect your device with Mac/PC and run adb uninstall <package>

Worked for me.

Ref: https://android.stackexchange.com/questions/92025/how-to-completely-uninstall-an-app-on-android-lollipop

jQuery: Return data after ajax call success

See jquery docs example: http://api.jquery.com/jQuery.ajax/ (about 2/3 the page)

You may be looking for following code:

    $.ajax({
     url: 'ajax/test.html',
     success: function(data) {
     $('.result').html(data);
     alert('Load was performed.');
   }
});

Same page...lower down.

Python Requests - No connection adapters

You need to include the protocol scheme:

'http://192.168.1.61:8080/api/call'

Without the http:// part, requests has no idea how to connect to the remote server.

Note that the protocol scheme must be all lowercase; if your URL starts with HTTP:// for example, it won’t find the http:// connection adapter either.

How to get item's position in a list?

Just to illustrate complete example along with the input_list which has searies1 (example: input_list[0]) in which you want to do a lookup of series2 (example: input_list[1]) and get indexes of series2 if it exists in series1.

Note: Your certain condition will go in lambda expression if conditions are simple

input_list = [[1,2,3,4,5,6,7],[1,3,7]]
series1 = input_list[0]
series2 = input_list[1]
idx_list = list(map(lambda item: series1.index(item) if item in series1 else None, series2))
print(idx_list)

output:

[0, 2, 6]

Access parent DataContext from DataTemplate

You can use RelativeSource to find the parent element, like this -

Binding="{Binding Path=DataContext.CurveSpeedMustBeSpecified, 
RelativeSource={RelativeSource AncestorType={x:Type local:YourParentElementType}}}"

See this SO question for more details about RelativeSource.

Javascript Drag and drop for touch devices

You can use the Jquery UI for drag and drop with an additional library that translates mouse events into touch which is what you need, the library I recommend is https://github.com/furf/jquery-ui-touch-punch, with this your drag and drop from Jquery UI should work on touch devises

or you can use this code which I am using, it also converts mouse events into touch and it works like magic.

function touchHandler(event) {
    var touch = event.changedTouches[0];

    var simulatedEvent = document.createEvent("MouseEvent");
        simulatedEvent.initMouseEvent({
        touchstart: "mousedown",
        touchmove: "mousemove",
        touchend: "mouseup"
    }[event.type], true, true, window, 1,
        touch.screenX, touch.screenY,
        touch.clientX, touch.clientY, false,
        false, false, false, 0, null);

    touch.target.dispatchEvent(simulatedEvent);
    event.preventDefault();
}

function init() {
    document.addEventListener("touchstart", touchHandler, true);
    document.addEventListener("touchmove", touchHandler, true);
    document.addEventListener("touchend", touchHandler, true);
    document.addEventListener("touchcancel", touchHandler, true);
}

And in your document.ready just call the init() function

code found from Here

How to read a text file into a string variable and strip newlines?

Regular expression works too:

import re
with open("depression.txt") as f:
     l = re.split(' ', re.sub('\n',' ', f.read()))[:-1]

print (l)

['I', 'feel', 'empty', 'and', 'dead', 'inside']

CSS border less than 1px

try giving border in % for exapmle 0.1% according to your need.

Is It Possible to NSLog C Structs (Like CGRect or CGPoint)?

I use the following macro to help me out with NSRect:

#define LogRect(RECT) NSLog(@"%s: (%0.0f, %0.0f) %0.0f x %0.0f",
    #RECT, RECT.origin.x, RECT.origin.y, RECT.size.width, RECT.size.height)

You could do something similar for CGPoint:

@define LogCGPoint(POINT) NSLog(@"%s: (%0.0f, %0.0f)",
    #POINT POINT.x, POINT.y);

Using it as follows:

LogCGPoint(cgPoint);

Would produce the following:

cgPoint: (100, 200)

How to get table cells evenly spaced?

You can use CSS. One way is to set table-layout to fixed, which stops the table and it's children from sizing according to their content. You can then set a fixed width on the relevant td elements. This should do the trick:

table.PerformanceTable {
    table-layout: fixed;
    width: 500px;
}
    table.PerformanceTable td.PerformanceCell {
        width: 75px;
    }

Suggestions for for tidying up? You don't need the cellpadding or cellspacing attributes, or the TableRow and TableHeader classes. You can cover those off in CSS:

table {
    /* cellspacing */
    border-collapse: collapse;
    border-spacing: 0;
}
th {
    /* This covers the th elements */
}
tr {
    /* This covers the tr elements */
}
th, td {
    /* cellpadding */
    padding: 0;
}

You should use a heading (e.g. <h2>) instead of <span class="Emphasis"> and a <p> or a table <caption> instead of the Source <span>. You wouldn't need the <br> elements either, because you'd be using proper block level elements.

How to select the last column of dataframe

Somewhat similar to your original attempt, but more Pythonic, is to use Python's standard negative-indexing convention to count backwards from the end:

df[df.columns[-1]]

Close Bootstrap modal on form submit

Use that Code

 $('#button').submit(function(e) {
    e.preventDefault();
    // Coding
    $('#IDModal').modal('toggle'); //or  $('#IDModal').modal('hide');
    return false;
});

How to remove leading and trailing spaces from a string

You can use:

  • String.TrimStart - Removes all leading occurrences of a set of characters specified in an array from the current String object.
  • String.TrimEnd - Removes all trailing occurrences of a set of characters specified in an array from the current String object.
  • String.Trim - combination of the two functions above

Usage:

string txt = "                   i am a string                                    ";
char[] charsToTrim = { ' ' };    
txt = txt.Trim(charsToTrim)); // txt = "i am a string"

EDIT:

txt = txt.Replace(" ", ""); // txt = "iamastring"   

How do I disable form fields using CSS?

first time answering something, and seemingly just a bit late...

I agree to do it by javascript, if you're already using it.

For a composite structure, like I usually use, I've made a css pseudo after element to block the elements from user interaction, and allow styling without having to manipulate the entire structure.

For Example:

<div id=test class=stdInput>
    <label class=stdInputLabel for=selecterthingy>A label for this input</label>
    <label class=selectWrapper>
         <select id=selecterthingy>
             <option selected disabled>Placeholder</option>
             <option value=1>Option 1</option>
             <option value=2>Option 2</option>
         </select>
    </label>
</div>

I can place a disabled class on the wrapping div

.disabled { 
    position : relative; 
    color    : grey;
}
.disabled:after {
    position :absolute;
    left     : 0;
    top      : 0;
    width    : 100%;
    height   : 100%;
    content  :' ';
}

This would grey text within the div and make it unusable to the user.

My example JSFiddle

How to programmatically click a button in WPF?

this.PowerButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));

Twig for loop for arrays with keys

I found the answer :

{% for key,value in array_path %}
    Key : {{ key }}
    Value : {{ value }}
{% endfor %}

How to find the UpgradeCode and ProductCode of an installed application in Windows 7

If you don't have the msi and you need the upgrade code, rather than the product code then the answer is here: How can I find the upgrade code for an installed application in C#?

jQuery Validation plugin: validate check box

You had several issues with your code.

1) Missing a closing brace, }, within your rules.

2) In this case, there is no reason to use a function for the required rule. By default, the plugin can handle checkbox and radio inputs just fine, so using true is enough. However, this will simply do the same logic as in your original function and verify that at least one is checked.

3) If you also want only a maximum of two to be checked, then you'll need to apply the maxlength rule.

4) The messages option was missing the rule specification. It will work, but the one custom message would apply to all rules on the same field.

5) If a name attribute contains brackets, you must enclose it within quotes.

DEMO: http://jsfiddle.net/K6Wvk/

$(document).ready(function () {

    $('#formid').validate({ // initialize the plugin
        rules: {
            'test[]': {
                required: true,
                maxlength: 2
            }
        },
        messages: {
            'test[]': {
                required: "You must check at least 1 box",
                maxlength: "Check no more than {0} boxes"
            }
        }
    });

});

How do I start PowerShell from Windows Explorer?

Another option are the excellent Elevation PowerToys by Michael Murgolo on TechNet at http://technet.microsoft.com/en-us/magazine/2008.06.elevation.aspx.

They include PowerShell Prompt Here and PowerShell Prompt Here as Administrator.

What is the largest possible heap size with a 64-bit JVM?

For a 64-bit JVM running in a 64-bit OS on a 64-bit machine, is there any limit besides the theoretical limit of 2^64 bytes or 16 exabytes?

You also have to take hardware limits into account. While pointers may be 64bit current CPUs can only address a less than 2^64 bytes worth of virtual memory.

With uncompressed pointers the hotspot JVM needs a continuous chunk of virtual address space for its heap. So the second hurdle after hardware is the operating system providing such a large chunk, not all OSes support this.

And the third one is practicality. Even if you can have that much virtual memory it does not mean the CPUs support that much physical memory, and without physical memory you will end up swapping, which will adversely affect the performance of the JVM because the GCs generally have to touch a large fraction of the heap.

As other answers mention compressed oops: By bumping the object alignment higher than 8 bytes the limits with compressed oops can be increased beyond 32GB

Android Dialog: Removing title bar

**write this before adding view to dialog.**

dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);

Validate phone number using javascript

JavaScript to validate the phone number:

_x000D_
_x000D_
function phonenumber(inputtxt) {_x000D_
  var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;_x000D_
  if(inputtxt.value.match(phoneno)) {_x000D_
    return true;_x000D_
  }_x000D_
  else {_x000D_
    alert("message");_x000D_
    return false;_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

The above script matches:

XXX-XXX-XXXX
XXX.XXX.XXXX
XXX XXX XXXX

If you want to use a + sign before the number in the following way
+XX-XXXX-XXXX
+XX.XXXX.XXXX
+XX XXXX XXXX
use the following code:

function phonenumber(inputtxt) {
  var phoneno = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
  if(inputtxt.value.match(phoneno)) {
    return true;
  }  
  else {  
    alert("message");
    return false;
  }
}

Is it possible to set async:false to $.getJSON call

In my case, Jay D is right. I have to add this before the call.

$.ajaxSetup({
    async: false
});

In my previous code, I have this:

var jsonData= (function() {
    var result;
    $.ajax({
        type:'GET',
        url:'data.txt',
        dataType:'json',
        async:false,
        success:function(data){
            result = data;
        }
    });
    return result;
})();
alert(JSON.stringify(jsonData));

It works find. Then I change to

var jsonData= (function() {
    var result;
    $.getJSON('data.txt', {}, function(data){
      result = data;
    });
    return result;
})();
alert(JSON.stringify(jsonData));

The alert is undefined.

If I add those three lines, the alert shows the data again.

$.ajaxSetup({
    async: false
});
var jsonData= (function() {
    var result;
    $.getJSON('data.txt', {}, function(data){
      result = data;
    });
    return result;
})();
alert(JSON.stringify(jsonData));

Converting Swagger specification JSON to HTML documentation

I spent a lot of time and tried a lot of different solutions - in the end I did it this way :

<html>
    <head>    
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/swagger-ui.css">
        <script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script>
        <script>

            function render() {
                var ui = SwaggerUIBundle({
                    url:  `path/to/my/swagger.yaml`,
                    dom_id: '#swagger-ui',
                    presets: [
                        SwaggerUIBundle.presets.apis,
                        SwaggerUIBundle.SwaggerUIStandalonePreset
                    ]
                });
            }

        </script>
    </head>

    <body onload="render()">
        <div id="swagger-ui"></div>
    </body>
</html>

You just need to have path/to/my/swagger.yaml served from the same location.
(or use CORS headers)

How to make clang compile to llvm IR

Given some C/C++ file foo.c:

> clang -S -emit-llvm foo.c

Produces foo.ll which is an LLVM IR file.

The -emit-llvm option can also be passed to the compiler front-end directly, and not the driver by means of -cc1:

> clang -cc1 foo.c -emit-llvm

Produces foo.ll with the IR. -cc1 adds some cool options like -ast-print. Check out -cc1 --help for more details.


To compile LLVM IR further to assembly, use the llc tool:

> llc foo.ll

Produces foo.s with assembly (defaulting to the machine architecture you run it on). llc is one of the LLVM tools - here is its documentation.

How can I match a string with a regex in Bash?

To match regexes you need to use the =~ operator.

Try this:

[[ sed-4.2.2.tar.bz2 =~ tar.bz2$ ]] && echo matched

Alternatively, you can use wildcards (instead of regexes) with the == operator:

[[ sed-4.2.2.tar.bz2 == *tar.bz2 ]] && echo matched

If portability is not a concern, I recommend using [[ instead of [ or test as it is safer and more powerful. See What is the difference between test, [ and [[ ? for details.

How to revert a "git rm -r ."?

undo git rm

git rm file             # delete file & update index
git checkout HEAD file  # restore file & index from HEAD

undo git rm -r

git rm -r dir          # delete tracked files in dir & update index
git checkout HEAD dir  # restore file & index from HEAD

undo git rm -rf

git rm -r dir          # delete tracked files & delete uncommitted changes
not possible           # `uncommitted changes` can not be restored.

Uncommitted changes includes not staged changes, staged changes but not committed.

Change onClick attribute with javascript

You are not actually changing the function.

onClick is assigned to a function (Which is a reference to something, a function pointer in this case). The values passed to it don't matter and cannot be utilised in any manner.

Another problem is your variable color seems out of nowhere.

Ideally, inside the function you should put this logic and let it figure out what to write. (on/off etc etc)

Querying data by joining two tables in two database on different servers

If the database link option is not available, another route you could take is to link the tables via ODBC to something such as MS Access or Crystal reports and do the join there.

CentOS 64 bit bad ELF interpreter

Try

$ yum provides ld-linux.so.2
$ yum update
$ yum install glibc.i686 libfreetype.so.6 libfontconfig.so.1 libstdc++.so.6

Hope this clears out.

What are all possible pos tags of NLTK?

The book has a note how to find help on tag sets, e.g.:

nltk.help.upenn_tagset()

Others are probably similar. (Note: Maybe you first have to download tagsets from the download helper's Models section for this)

C# Form.Close vs Form.Dispose

As a general rule, I'd always advocate explicitly calling the Dispose method for any class that offers it, either by calling the method directly or wrapping in a "using" block.

Most often, classes that implement IDisposible do so because they wrap some unmanaged resource that needs to be freed. While these classes should have finalizers that act as a safeguard, calling Dispose will help free that memory earlier and with lower overhead.

In the case of the Form object, as the link fro Kyra noted, the Close method is documented to invoke Dispose on your behalf so you need not do so explicitly. However, to me, that has always felt like relying on an implementaion detail. I prefer to always call both Close and Dispose for classes that implement them, to guard against implementation changes/errors and for the sake of being clear. A properly implemented Dispose method should be safe to invoke multiple times.

How to apply bold text style for an entire row using Apache POI?

This should work fine.

    Workbook wb = new XSSFWorkbook("myWorkbook.xlsx");
    Row row=sheet.getRow(0);
    CellStyle style=null;

    XSSFFont defaultFont= wb.createFont();
    defaultFont.setFontHeightInPoints((short)10);
    defaultFont.setFontName("Arial");
    defaultFont.setColor(IndexedColors.BLACK.getIndex());
    defaultFont.setBold(false);
    defaultFont.setItalic(false);

    XSSFFont font= wb.createFont();
    font.setFontHeightInPoints((short)10);
    font.setFontName("Arial");
    font.setColor(IndexedColors.WHITE.getIndex());
    font.setBold(true);
    font.setItalic(false);

    style=row.getRowStyle();
    style.setFillBackgroundColor(IndexedColors.DARK_BLUE.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setFont(font);

If you do not create defaultFont all your workbook will be using the other one as default.

docker run <IMAGE> <MULTIPLE COMMANDS>

For anyone else who came here looking to do the same with docker-compose you just need to prepend bash -c and enclose multiple commands in quotes, joined together with &&.

So in the OPs example docker-compose run image bash -c "cd /path/to/somewhere && python a.py"

Jackson with JSON: Unrecognized field, not marked as ignorable

In my case it was simple: the REST-service JSON Object was updated (a property was added), but the REST-client JSON Object wasn't. As soon as i've updated JSON client object the 'Unrecognized field ...' exception has vanished.

Finding moving average from data points in Python

A moving average is a convolution, and numpy will be faster than most pure python operations. This will give you the 10 point moving average.

import numpy as np
smoothed = np.convolve(data, np.ones(10)/10)

I would also strongly suggest using the great pandas package if you are working with timeseries data. There are some nice moving average operations built in.

How to send a "multipart/form-data" with requests in python?

Here is the python snippet you need to upload one large single file as multipart formdata. With NodeJs Multer middleware running on the server side.

import requests
latest_file = 'path/to/file'
url = "http://httpbin.org/apiToUpload"
files = {'fieldName': open(latest_file, 'rb')}
r = requests.put(url, files=files)

For the server side please check the multer documentation at: https://github.com/expressjs/multer here the field single('fieldName') is used to accept one single file, as in:

var upload = multer().single('fieldName');

"An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

Ok, so very important to realize the implications here.

Docs say that SSL over 465 is NOT supported in SmtpClient.

Seems like you have no choice but to use STARTTLS which may not be supported by your mail host. You may have to use a different library if your host requires use of SSL over 465.

Quoted from http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.enablessl(v=vs.110).aspx

The SmtpClient class only supports the SMTP Service Extension for Secure SMTP over Transport Layer Security as defined in RFC 3207. In this mode, the SMTP session begins on an unencrypted channel, then a STARTTLS command is issued by the client to the server to switch to secure communication using SSL. See RFC 3207 published by the Internet Engineering Task Force (IETF) for more information.

An alternate connection method is where an SSL session is established up front before any protocol commands are sent. This connection method is sometimes called SMTP/SSL, SMTP over SSL, or SMTPS and by default uses port 465. This alternate connection method using SSL is not currently supported.

How do I sort a VARCHAR column in SQL server that contains numbers?

 SELECT *,
       ROW_NUMBER()OVER(ORDER BY CASE WHEN ISNUMERIC (ID)=1 THEN CONVERT(NUMERIC(20,2),SUBSTRING(Id, PATINDEX('%[0-9]%', Id), LEN(Id)))END DESC)Rn ---- numerical
        FROM
            (

        SELECT '1'Id UNION ALL
        SELECT '25.20' Id UNION ALL

    SELECT 'A115' Id UNION ALL
    SELECT '2541' Id UNION ALL
    SELECT '571.50' Id UNION ALL
    SELECT '67' Id UNION ALL
    SELECT 'B48' Id UNION ALL
    SELECT '500' Id UNION ALL
    SELECT '147.54' Id UNION ALL
    SELECT 'A-100' Id
    )A

    ORDER BY 
    CASE WHEN ISNUMERIC (ID)=0                                /* alphabetical sort */ 
         THEN CASE WHEN PATINDEX('%[0-9]%', Id)=0
                   THEN LEFT(Id,PATINDEX('%[0-9]%',Id))
                   ELSE LEFT(Id,PATINDEX('%[0-9]%',Id)-1)
              END
    END DESC

How to get the nth occurrence in a string?

a simple solution just add string, character and idx:

function getCharIdx(str,char,n){
  let r = 0
  for (let i = 0; i<str.length; i++){
    if (str[i] === char){
      r++
      if (r === n){
        return i
      }

    }
   
  }
}

How to show Bootstrap table with sort icon

You could try using FontAwesome. It contains a sort-icon (http://fontawesome.io/icon/sort/).

To do so, you would

  1. need to include fontawesome:

    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
    
  2. and then simply use the fontawesome-icon instead of the default-bootstrap-icons in your th's:

    <th><b>#</b> <i class="fa fa-fw fa-sort"></i></th>
    

Hope that helps.

Make a number a percentage

Most answers suggest appending '%' at the end. I would rather prefer Intl.NumberFormat() with { style: 'percent'}

_x000D_
_x000D_
var num = 25;_x000D_
_x000D_
var option = {_x000D_
  style: 'percent'_x000D_
_x000D_
};_x000D_
var formatter = new Intl.NumberFormat("en-US", option);_x000D_
var percentFormat = formatter.format(num / 100);_x000D_
console.log(percentFormat);
_x000D_
_x000D_
_x000D_

How to make bootstrap column height to 100% row height?

@Alan's answer will do what you're looking for, but this solution fails when you use the responsive capabilities of Bootstrap. In your case, you're using the xs sizes so you won't notice, but if you used anything else (e.g. col-sm, col-md, etc), you'd understand.

Another approach is to play with margins and padding. See the updated fiddle: http://jsfiddle.net/jz8j247x/1/

.left-side {
  background-color: blue;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.something {
  height: 100%;
  background-color: red;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.row {
  background-color: green;
  overflow: hidden;
}

How to set a default Value of a UIPickerView

In normal case, you can do something like this in viewDidLoad method;

[_picker selectRow:1 inComponent:0 animated:YES];

In my case, I'd like to fetch data from api server and display them onto UIPickerView then I want the picker to select the first item by default.

The UIPickerView will look like it selected the first item after it was created, but when you try to get the selected index by using selectedRowInComponent, you will get NSNull. That's because it detected nothing changed by the user (select 0 from 0 ).

Following is my solution (in viewWillAppear, after I fetched the data)

[_picker selectRow:1 inComponent:0 animated:NO];
[_picker selectRow:0 inComponent:0 animated:NO];

Its a bit dirty, but dont worry, the UI rendering in iOS is very fast ;)

How to check if $_GET is empty?

Just to provide some variation here: You could check for

if ($_SERVER["QUERY_STRING"] == null)

it is completely identical to testing $_GET.

Squash the first two commits in Git?

I've reworked VonC's script to do everything automatically and not ask me for anything. You give it two commit SHA1s and it will squash everything between them into one commit named "squashed history":

#!/bin/sh
# Go back to the last commit that we want
# to form the initial commit (detach HEAD)
git checkout $2

# reset the branch pointer to the initial commit (= $1),
# but leaving the index and working tree intact.
git reset --soft $1

# amend the initial tree using the tree from $2
git commit --amend -m "squashed history"

# remember the new commit sha1
TARGET=`git rev-list HEAD --max-count=1`

# go back to the original branch (assume master for this example)
git checkout master

# Replay all the commits after $2 onto the new initial commit
git rebase --onto $TARGET $2

Equivalent of LIMIT and OFFSET for SQL Server?

Another sample :

declare @limit int 
declare @offset int 
set @offset = 2;
set @limit = 20;
declare @count int
declare @idxini int 
declare @idxfim int 
select @idxfim = @offset * @limit
select @idxini = @idxfim - (@limit-1);
WITH paging AS
    (
        SELECT 
             ROW_NUMBER() OVER (order by object_id) AS rowid, *
        FROM 
            sys.objects 
    )
select *
    from 
        (select COUNT(1) as rowqtd from paging) qtd, 
            paging 
    where 
        rowid between @idxini and @idxfim
    order by 
        rowid;

PHP - check if variable is undefined

You can use -

$isTouch = isset($variable);

It will return true if the $variable is defined. if the variable is not defined it will return false.

Note : Returns TRUE if var exists and has value other than NULL, FALSE otherwise.

If you want to check for false, 0 etc You can then use empty() -

$isTouch = empty($variable);

empty() works for -

  • "" (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • $var; (a variable declared, but without a value)

Typescript - multidimensional array initialization

Beware of the use of push method, if you don't use indexes, it won't work!

var main2dArray: Things[][] = []

main2dArray.push(someTmp1dArray)
main2dArray.push(someOtherTmp1dArray)

gives only a 1 line array!

use

main2dArray[0] = someTmp1dArray
main2dArray[1] = someOtherTmp1dArray

to get your 2d array working!!!

Other beware! foreach doesn't seem to work with 2d arrays!

How to use radio buttons in ReactJS?

I also got confused in radio, checkbox implementation. What we need is, listen change event of the radio, and then set the state. I have made small example of gender selection.

_x000D_
_x000D_
/*_x000D_
 * A simple React component_x000D_
 */_x000D_
class App extends React.Component {_x000D_
  constructor(params) {_x000D_
     super(params) _x000D_
     // initial gender state set from props_x000D_
     this.state = {_x000D_
       gender: this.props.gender_x000D_
     }_x000D_
     this.setGender = this.setGender.bind(this)_x000D_
  }_x000D_
  _x000D_
  setGender(e) {_x000D_
    this.setState({_x000D_
      gender: e.target.value_x000D_
    })_x000D_
  }_x000D_
  _x000D_
  render() {_x000D_
    const {gender} = this.state_x000D_
    return  <div>_x000D_
        Gender:_x000D_
        <div>_x000D_
          <input type="radio" checked={gender == "male"} _x000D_
onClick={this.setGender} value="male" /> Male_x000D_
          <input type="radio" checked={gender == "female"} _x000D_
onClick={this.setGender} value="female"  /> Female_x000D_
        </div>_x000D_
        { "Select Gender: " } {gender}_x000D_
      </div>;_x000D_
  }_x000D_
}_x000D_
_x000D_
/*_x000D_
 * Render the above component into the div#app_x000D_
 */_x000D_
ReactDOM.render(<App gender="male" />, document.getElementById('app'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

How to create a file in Ruby

data = 'data you want inside the file'.

You can use File.write('name of file here', data)

Counting the number of option tags in a select tag in jQuery

In a multi-select option box, you can use $('#input1 :selected').length; to get the number of selected options. This can be useful to disable buttons if a certain minimum number of options aren't met.

function refreshButtons () {
    if ($('#input :selected').length == 0)
    {
        $('#submit').attr ('disabled', 'disabled');
    }
    else
    {
        $('#submit').removeAttr ('disabled');
    }
}

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

In gradle-wrapper.properties I changed back from gradle-5.1.1 to distributionUrl=https://services.gradle.org/distributions/gradle-4.10.3-all.zip

How to use GROUP_CONCAT in a CONCAT in MySQL

IF OBJECT_ID('master..test') is not null Drop table test

CREATE TABLE test (ID INTEGER, NAME VARCHAR (50), VALUE INTEGER );
INSERT INTO test VALUES (1, 'A', 4);
INSERT INTO test VALUES (1, 'A', 5);
INSERT INTO test VALUES (1, 'B', 8);
INSERT INTO test VALUES (2, 'C', 9);

select distinct NAME , LIST = Replace(Replace(Stuff((select ',', +Value from test where name = _a.name for xml path('')), 1,1,''),'<Value>', ''),'</Value>','') from test _a order by 1 desc

My table name is test , and for concatination I use the For XML Path('') syntax. The stuff function inserts a string into another string. It deletes a specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.

STUFF functions looks like this : STUFF (character_expression , start , length ,character_expression )

character_expression Is an expression of character data. character_expression can be a constant, variable, or column of either character or binary data.

start Is an integer value that specifies the location to start deletion and insertion. If start or length is negative, a null string is returned. If start is longer than the first character_expression, a null string is returned. start can be of type bigint.

length Is an integer that specifies the number of characters to delete. If length is longer than the first character_expression, deletion occurs up to the last character in the last character_expression. length can be of type bigint.

Column "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"

The consequence of this is that you may need a rather insane-looking query, e. g.,

SELECT [dbo].[tblTimeSheetExportFiles].[lngRecordID]            AS lngRecordID
          ,[dbo].[tblTimeSheetExportFiles].[vcrSourceWorkbookName]  AS vcrSourceWorkbookName
          ,[dbo].[tblTimeSheetExportFiles].[vcrImportFileName]      AS vcrImportFileName
          ,[dbo].[tblTimeSheetExportFiles].[dtmLastWriteTime]       AS dtmLastWriteTime
          ,[dbo].[tblTimeSheetExportFiles].[lngNRecords]            AS lngNRecords
          ,[dbo].[tblTimeSheetExportFiles].[lngSizeOnDisk]          AS lngSizeOnDisk
          ,[dbo].[tblTimeSheetExportFiles].[lngLastIdentity]        AS lngLastIdentity
          ,[dbo].[tblTimeSheetExportFiles].[dtmImportCompletedTime] AS dtmImportCompletedTime
          ,MIN ( [tblTimeRecords].[dtmActivity_Date] )              AS dtmPeriodFirstWorkDate
          ,MAX ( [tblTimeRecords].[dtmActivity_Date] )              AS dtmPeriodLastWorkDate
          ,SUM ( [tblTimeRecords].[decMan_Hours_Actual] )           AS decHoursWorked
          ,SUM ( [tblTimeRecords].[decAdjusted_Hours] )             AS decHoursBilled
      FROM [dbo].[tblTimeSheetExportFiles]
      LEFT JOIN   [dbo].[tblTimeRecords]
              ON  [dbo].[tblTimeSheetExportFiles].[lngRecordID] = [dbo].[tblTimeRecords].[lngTimeSheetExportFile]
        GROUP BY  [dbo].[tblTimeSheetExportFiles].[lngRecordID]
                 ,[dbo].[tblTimeSheetExportFiles].[vcrSourceWorkbookName]
                 ,[dbo].[tblTimeSheetExportFiles].[vcrImportFileName]
                 ,[dbo].[tblTimeSheetExportFiles].[dtmLastWriteTime]
                 ,[dbo].[tblTimeSheetExportFiles].[lngNRecords]
                 ,[dbo].[tblTimeSheetExportFiles].[lngSizeOnDisk]
                 ,[dbo].[tblTimeSheetExportFiles].[lngLastIdentity]
                 ,[dbo].[tblTimeSheetExportFiles].[dtmImportCompletedTime]

Since the primary table is a summary table, its primary key handles the only grouping or ordering that is truly necessary. Hence, the GROUP BY clause exists solely to satisfy the query parser.

Passing an integer by reference in Python

class Obj:
  def __init__(self,a):
    self.value = a
  def sum(self, a):
    self.value += a
    
a = Obj(1)
b = a
a.sum(1)
print(a.value, b.value)// 2 2

Can you get the column names from a SqlDataReader?

I use the GetSchemaTable method, which is exposed via the IDataReader interface.

Batch - If, ElseIf, Else

@echo off
title Test

echo Select a language. (de/en)
set /p language=

IF /i "%language%"=="de" goto languageDE
IF /i "%language%"=="en" goto languageEN

echo Not found.
goto commonexit

:languageDE
echo German
goto commonexit

:languageEN
echo English
goto commonexit

:commonexit
pause

The point is that batch simply continues through instructions, line by line until it reaches a goto, exit or end-of-file. It has no concept of sections to control flow.

Hence, entering de would jump to :languagede then simply continue executing instructions until the file ends, showing de then en then not found.

How get the base URL via context path in JSF?

URLs are not resolved based on the file structure in the server side. URLs are resolved based on the real public web addresses of the resources in question. It's namely the webbrowser who has got to invoke them, not the webserver.

There are several ways to soften the pain:

JSF EL offers a shorthand to ${pageContext.request} in flavor of #{request}:

<li><a href="#{request.contextPath}/index.xhtml">Home</a></li>
<li><a href="#{request.contextPath}/about_us.xhtml">About us</a></li>

You can if necessary use <c:set> tag to make it yet shorter. Put it somewhere in the master template, it'll be available to all pages:

<c:set var="root" value="#{request.contextPath}/" />
...
<li><a href="#{root}index.xhtml">Home</a></li>
<li><a href="#{root}about_us.xhtml">About us</a></li>

JSF 2.x offers the <h:link> which can take a view ID relative to the context root in outcome and it will append the context path and FacesServlet mapping automatically:

<li><h:link value="Home" outcome="index" /></li>
<li><h:link value="About us" outcome="about_us" /></li>

HTML offers the <base> tag which makes all relative URLs in the document relative to this base. You could make use of it. Put it in the <h:head>.

<base href="#{request.requestURL.substring(0, request.requestURL.length() - request.requestURI.length())}#{request.contextPath}/" />
...
<li><a href="index.xhtml">Home</a></li>
<li><a href="about_us.xhtml">About us</a></li>

(note: this requires EL 2.2, otherwise you'd better use JSTL fn:substring(), see also this answer)

This should end up in the generated HTML something like as

<base href="http://example.com/webname/" />

Note that the <base> tag has a caveat: it makes all jump anchors in the page like <a href="#top"> relative to it as well! See also Is it recommended to use the <base> html tag? In JSF you could solve it like <a href="#{request.requestURI}#top">top</a> or <h:link value="top" fragment="top" />.

How to add font-awesome to Angular 2 + CLI project

You can use Angular Font Awesome package

npm install --save font-awesome angular-font-awesome

and then import in your module:

import { AngularFontAwesomeModule } from 'angular-font-awesome';
     @NgModule({
       //...
      imports: [
        //...
        AngularFontAwesomeModule
      ],
      //...
    })
    export class AppModule { }

and import the style in angular-cli file:

   "styles": [
        "styles.css",
        "../node_modules/font-awesome/css/font-awesome.css"
    ],

see more details about the package in npm library:

https://www.npmjs.com/package/angular-font-awesome

and then use it like this:

<i class="fa fa-coffee"></i>

Visual Studio 2010 - recommended extensions

JScript Editor Extensions

Bundles the following extensions for the Visual Studio 2010 JScript editor

Brace Matching

Adds support for automatically highlighting the matching opening or closing brace to the one currently at the cursor. Supports matching parenthesis: (), square brackets: [], and curly braces: {}. Braces in strings, comments and regular expression literals are ignored.

Outlining / Cold-folding

Adds support for automatically creating outlining regions for JScript blocks. Blocks are detected via opening and closing curly braces. Braces in strings, comments and regular expression literals are ignored.

Current Word Highlighting

Adds support for highlighting all instances of the word currently at the cursor.

IntelliSense Doc-Comments Support

Adds support for the element in JScript IntelliSense doc-comments to allow display of new lines in IntelliSense tooltips.

Amazon S3 - HTTPS/SSL - Is it possible?

This is a response I got from their Premium Services

Hello,

This is actually a issue with the way SSL validates names containing a period, '.', > character. We've documented this behavior here:

http://docs.amazonwebservices.com/AmazonS3/latest/dev/BucketRestrictions.html

The only straight-forward fix for this is to use a bucket name that does not contain that character. You might instead use a bucket named 'furniture-retailcatalog-us'. This would allow you use HTTPS with

https://furniture-retailcatalog-us.s3.amazonaws.com/

You could, of course, put a CNAME DNS record to make that more friendly. For example,

images-furniture.retailcatalog.us IN CNAME furniture-retailcatalog-us.s3.amazonaws.com.

Hope that helps. Let us know if you have any other questions.

Amazon Web Services

Unfortunately your "friendly" CNAME will cause host name mismatch when validating the certificate, therefore you cannot really use it for a secure connection. A big missing feature of S3 is accepting custom certificates for your domains.


UPDATE 10/2/2012

From @mpoisot:

The link Amazon provided no longer says anything about https. I poked around in the S3 docs and finally found a small note about it on the Virtual Hosting page: http://docs.amazonwebservices.com/AmazonS3/latest/dev/VirtualHosting.html


UPDATE 6/17/2013

From @Joseph Lust:

Just got it! Check it out and sign up for an invite: http://aws.amazon.com/cloudfront/custom-ssl-domains

When should I really use noexcept?

There are many examples of functions that I know will never throw, but for which the compiler cannot determine so on its own. Should I append noexcept to the function declaration in all such cases?

When you say "I know [they] will never throw", you mean by examining the implementation of the function you know that the function will not throw. I think that approach is inside out.

It is better to consider whether a function may throw exceptions to be part of the design of the function: as important as the argument list and whether a method is a mutator (... const). Declaring that "this function never throws exceptions" is a constraint on the implementation. Omitting it does not mean the function might throw exceptions; it means that the current version of the function and all future versions may throw exceptions. It is a constraint that makes the implementation harder. But some methods must have the constraint to be practically useful; most importantly, so they can be called from destructors, but also for implementation of "roll-back" code in methods that provide the strong exception guarantee.

Get the decimal part from a double

It is very simple

       float moveWater =  Mathf.PingPong(theTime * speed, 100) * .015f;
       int    m = (int)(moveWater);
       float decimalPart= moveWater -m ;

       Debug.Log(decimalPart);

How to select last two characters of a string

You can pass a negative index to .slice(). That will indicate an offset from the end of the set.

var member = "my name is Mate";

var last2 = member.slice(-2);

alert(last2); // "te"

How to make java delay for a few seconds?

You need to use the Thread.sleep() method.

This is used to pause the execution of current thread for specified time in milliseconds. The argument value for milliseconds can’t be negative, else it throws IllegalArgumentException.

FYI (Summary taken from here)

Java Thread Sleep important points

  • It always pause the current thread execution.
  • Thread sleep doesn’t lose any monitors or locks current thread has acquired.
  • Any other thread can interrupt the current thread in sleep, in that case InterruptedException is thrown.

How can I write a regex which matches non greedy?

The non-greedy ? works perfectly fine. It's just that you need to select dot matches all option in the regex engines (regexpal, the engine you used, also has this option) you are testing with. This is because, regex engines generally don't match line breaks when you use .. You need to tell them explicitly that you want to match line-breaks too with .

For example,

<img\s.*?>

works fine!

Check the results here.

Also, read about how dot behaves in various regex flavours.

" app-release.apk" how to change this default generated apk name

Not renaming it, but perhaps generating the name correctly in the first place would help? Change apk name with Gradle

base64 encoded images in email signatures

Recently I had the same problem to include QR image/png in email. The QR image is a byte array which is generated using ZXing. We do not want to save it to a file because saving/reading from a file is too expensive (slow). So both of the answers above do not work for me. Here's what I did to solve this problem:

import javax.mail.util.ByteArrayDataSource;
import org.apache.commons.mail.ImageHtmlEmail;
...
ImageHtmlEmail email = new ImageHtmlEmail();
byte[] qrImageBytes = createQRCode(); // get your image byte array
ByteArrayDataSource qrImageDataSource = new ByteArrayDataSource(qrImageBytes, "image/png");
String contentId = email.embed(qrImageDataSource, "QR Image");

Let's say the contentId is "111122223333", then your HTML part should have this:

<img src="cid: 111122223333">

There's no need to convert the byte array to Base64 because Commons Mail does the conversion for you automatically. Hope this helps.

How to escape a JSON string to have it in a URL?

encodeURIComponent(JSON.stringify(object_to_be_serialised))

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

JaredPar is right in that you can't know if the process is running. You can only know if the process was running at the moment you checked. It might have died in the mean time.

You also have to be aware the PIDs can be recycled pretty quickly. So just because there's a process out there with your PID, it doesn't mean that it's your process.

Have the processes share a GUID. (Process 1 could generate the GUID and pass it to Process 2 on the command line.) Process 2 should create a named mutex with that GUID. When Process 1 wants to check, it can do a WaitForSingleObject on the mutex with a 0 timeout. If Process 2 is gone, the return code will tell you that the mutex was abandoned, otherwise you'll get a timeout.

SQL Query Where Date = Today Minus 7 Days

DECLARE @Daysforward int
SELECT @Daysforward = 25 (no of days required)
Select * from table name

where CAST( columnDate AS date) < DATEADD(day,1+@Daysforward,CAST(GETDATE() AS date))

one line if statement in php

Use ternary operator:

echo (($test == '') ? $redText : '');
echo $test == '' ? $redText : ''; //removed parenthesis

But in this case you can't use shorter reversed version because it will return bool(true) in first condition.

echo (($test != '') ?: $redText); //this will not work properly for this case

'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel

First thing Correctly specify all settings in the .ENV file for Mail.

I LOST 6 HOURS FOR THIS

Example

MAIL_DRIVER=smtp
MAIL_MAILER=smtp
MAIL_HOST=smtp.yandex.ru
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=password //Create password for Apps in settings. NOT PASTE YOUR REAL MAIL PASSWORD
MAIL_ENCRYPTION=SSL
[email protected]
MAIL_FROM_NAME="${APP_NAME}"

How do I get user IP address in django?

You can use django-ipware which supports Python 2 & 3 and handles IPv4 & IPv6.

Install:

pip install django-ipware

Simple Usage:

# In a view or a middleware where the `request` object is available

from ipware import get_client_ip
ip, is_routable = get_client_ip(request)
if ip is None:
    # Unable to get the client's IP address
else:
    # We got the client's IP address
    if is_routable:
        # The client's IP address is publicly routable on the Internet
    else:
        # The client's IP address is private

# Order of precedence is (Public, Private, Loopback, None)

Advanced Usage:

  • Custom Header - Custom request header for ipware to look at:

    i, r = get_client_ip(request, request_header_order=['X_FORWARDED_FOR'])
    i, r = get_client_ip(request, request_header_order=['X_FORWARDED_FOR', 'REMOTE_ADDR'])
    
  • Proxy Count - Django server is behind a fixed number of proxies:

    i, r = get_client_ip(request, proxy_count=1)
    
  • Trusted Proxies - Django server is behind one or more known & trusted proxies:

    i, r = get_client_ip(request, proxy_trusted_ips=('177.2.2.2'))
    
    # For multiple proxies, simply add them to the list
    i, r = get_client_ip(request, proxy_trusted_ips=('177.2.2.2', '177.3.3.3'))
    
    # For proxies with fixed sub-domain and dynamic IP addresses, use partial pattern
    i, r = get_client_ip(request, proxy_trusted_ips=('177.2.', '177.3.'))
    

Note: read this notice.

use regular expression in if-condition in bash

Adding this solution with grep and basic sh builtins for those interested in a more portable solution (independent of bash version; also works with plain old sh, on non-Linux platforms etc.)

# GLOB matching
gg=svm-grid-ch    
case "$gg" in
   *grid*) echo $gg ;;
esac

# REGEXP    
if echo "$gg" | grep '^....grid*' >/dev/null ; then echo $gg ; fi    
if echo "$gg" | grep '....grid*' >/dev/null ; then echo $gg ; fi    
if echo "$gg" | grep 's...grid*' >/dev/null ; then echo $gg ; fi    

# Extended REGEXP
if echo "$gg" | egrep '(^....grid*|....grid*|s...grid*)' >/dev/null ; then
  echo $gg
fi    

Some grep incarnations also support the -q (quiet) option as an alternative to redirecting to /dev/null, but the redirect is again the most portable.

loop through json array jquery

you could also change from the .get() method to the .getJSON() method, jQuery will then parse the string returned as data to a javascript object and/or array that you can then reference like any other javascript object/array.

using your code above, if you changed .get to .getJSON, you should get an alert of [object Object] for each element in the array. If you changed the alert to alert(item.name) you will get the names.

How to make external HTTP requests with Node.js

You can use node.js http module to do that. You could check the documentation at Node.js HTTP.

You would need to pass the query string as well to the other HTTP Server. You should have that in ServerRequest.url.

Once you have those info, you could pass in the backend HTTP Server and port in the options that you will provide in the http.request()

Convert a string to an enum in C#

You can extend the accepted answer with a default value to avoid exceptions:

public static T ParseEnum<T>(string value, T defaultValue) where T : struct
{
    try
    {
        T enumValue;
        if (!Enum.TryParse(value, true, out enumValue))
        {
            return defaultValue;
        }
        return enumValue;
    }
    catch (Exception)
    {
        return defaultValue;
    }
}

Then you call it like:

StatusEnum MyStatus = EnumUtil.ParseEnum("Active", StatusEnum.None);

If the default value is not an enum the Enum.TryParse would fail and throw an exception which is catched.

After years of using this function in our code on many places maybe it's good to add the information that this operation costs performance!

Turning off eslint rule for a specific line

You can add the files which give error to .eslintignore file in your project.Like for all the .vue files just add /*.vue

accessing a docker container from another container

You will have to access db through the ip of host machine, or if you want to access it via localhost:1521, then run webserver like -

docker run --net=host --name oracle-wls wls-image:latest

See here

convert xml to java object using jaxb (unmarshal)

Tests

On the Tests class we will add an @XmlRootElement annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData property differs from the default mapping we will use the @XmlElement annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted

package forum11221136;

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Tests {

    TestData testData;

    @XmlElement(name="test-data")
    public TestData getTestData() {
        return testData;
    }

    public void setTestData(TestData testData) {
        this.testData = testData;
    }

}

TestData

On this class I used the @XmlType annotation to specify the order in which the elements should be ordered in. I added a testData property that appeared to be missing. I also used an @XmlElement annotation for the same reason as in the Tests class.

package forum11221136;

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
    String title;
    String book;
    String count;
    List<TestData> testData;

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getBook() {
        return book;
    }
    public void setBook(String book) {
        this.book = book;
    }
    public String getCount() {
        return count;
    }
    public void setCount(String count) {
        this.count = count;
    }
    @XmlElement(name="test-data")
    public List<TestData> getTestData() {
        return testData;
    }
    public void setTestData(List<TestData> testData) {
        this.testData = testData;
    }
}

Demo

Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.

package forum11221136;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Tests.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum11221136/input.xml");
        Tests tests = (Tests) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(tests, System.out);
    }

}

Converting a sentence string to a string array of words in Java

The easiest and best answer I can think of is to use the following method defined on the java string -

String[] split(String regex)

And just do "This is a sample sentence".split(" "). Because it takes a regex, you can do more complicated splits as well, which can include removing unwanted punctuation and other such characters.

How to compile for Windows on Linux with gcc/g++?

From: https://fedoraproject.org/wiki/MinGW/Tutorial

As of Fedora 17 it is possible to easily build (cross-compile) binaries for the win32 and win64 targets. This is realized using the mingw-w64 toolchain: http://mingw-w64.sf.net/. Using this toolchain allows you to build binaries for the following programming languages: C, C++, Objective-C, Objective-C++ and Fortran.

"Tips and tricks for using the Windows cross-compiler": https://fedoraproject.org/wiki/MinGW/Tips

UIView Infinite 360 degree rotation animation?

let val = CGFloat(M_PI_2)

UIView.animate(withDuration: 1, delay: 0, options: [.repeat, .curveLinear], animations: {
        self.viewToRotate.transform = self.viewToRotate.transform.rotated(by: val)
})

Extract a substring according to a pattern

Here is another simple answer

gsub("^.*:","", string)

Error converting data types when importing from Excel to SQL Server 2008

When Excel finds mixed data types in same column it guesses what is the right format for the column (the majority of the values determines the type of the column) and dismisses all other values by inserting NULLs. But Excel does it far badly (e.g. if a column is considered text and Excel finds a number then decides that the number is a mistake and insert a NULL instead, or if some cells containing numbers are "text" formatted, one may get NULL values into an integer column of the database).

Solution:

  1. Create a new excel sheet with the name of the columns in the first row
  2. Format the columns as text
  3. Paste the rows without format (use CVS format or copy/paste in Notepad to get only text)

Note that formatting the columns on an existing Excel sheet is not enough.

How to set cookie in node js using express framework?

Set Cookie?

res.cookie('cookieName', 'cookieValue')

Read Cookie?

req.cookies

Demo

const express('express')
    , cookieParser = require('cookie-parser'); // in order to read cookie sent from client

app.get('/', (req,res)=>{

    // read cookies
    console.log(req.cookies) 

    let options = {
        maxAge: 1000 * 60 * 15, // would expire after 15 minutes
        httpOnly: true, // The cookie only accessible by the web server
        signed: true // Indicates if the cookie should be signed
    }

    // Set cookie
    res.cookie('cookieName', 'cookieValue', options) // options is optional
    res.send('')

})

Access PHP variable in JavaScript

metrobalderas is partially right. Partially, because the PHP variable's value may contain some special characters, which are metacharacters in JavaScript. To avoid such problem, use the code below:

<script type="text/javascript">
var something=<?php echo json_encode($a); ?>;
</script>

How to enter a formula into a cell using VBA?

I would do it like this:

Worksheets("EmployeeCosts").Range("B" & var1a).Formula = _
Replace("=SUM(H5:H{SOME_VAR})","{SOME_VAR}",var1a)

In case you have some more complex formula it will be handy

How do I PHP-unserialize a jQuery-serialized form?

I don't know which version of Jquery you are using, but this works for me in jquery 1.3:

$.ajax({
    type: 'POST', 
    url: your url,
    data: $('#'+form_id).serialize(), 
    success: function(data) {
        $('#debug').html(data);
  }
});

Then you can access POST array keys as you would normally do in php. Just try with a print_r().

I think you're wrapping serialized form value in an object's property, which is useless as far as i know.

Hope this helps!

How to set a primary key in MongoDB?

If you thinking like RDBMS, you can't create primary key. Default primary key is _id. But you can create Unique Index. Example is bellow.

db.members.createIndex( { "user_id": 1 }, { unique: true } )

db.members.insert({'user_id':1,'name':'nanhe'})

db.members.insert({'name':'kumar'})

db.members.find();

Output is bellow.

{ "_id" : ObjectId("577f9cecd71d71fa1fb6f43a"), "user_id" : 1, "name" : "nanhe" }

{ "_id" : ObjectId("577f9d02d71d71fa1fb6f43b"), "name" : "kumar" }

When you try to insert same user_id mongodb throws a write error.

db.members.insert({'user_id':1,'name':'aarush'})

WriteResult({ "nInserted" : 0, "writeError" : { "code" : 11000, "errmsg" : "E11000 duplicate key error collection: student.members index: user_id_1 dup key: { : 1.0 }" } })

WPF Binding to parent DataContext

I dont know about XamGrid but that's what i'll do with a standard wpf DataGrid:

<DataGrid>
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
            <DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellEditingTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

Since the TextBlock and the TextBox specified in the cell templates will be part of the visual tree, you can walk up and find whatever control you need.

Check if value exists in dataTable?

You can use LINQ-to-DataSet with Enumerable.Any:

String author = "John Grisham";
bool contains = tbl.AsEnumerable().Any(row => author == row.Field<String>("Author"));

Another approach is to use DataTable.Select:

DataRow[] foundAuthors = tbl.Select("Author = '" + searchAuthor + "'");
if(foundAuthors.Length != 0)
{
    // do something...
}

Q: what if we do not know the columns Headers and we want to find if any cell value PEPSI exist in any rows'c columns? I can loop it all to find out but is there a better way? –

Yes, you can use this query:

DataColumn[] columns = tbl.Columns.Cast<DataColumn>().ToArray();
bool anyFieldContainsPepsi = tbl.AsEnumerable()
    .Any(row => columns.Any(col => row[col].ToString() == "PEPSI"));

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

It took me ages to work this one out, so for the benefit of searchers:

I had a bizarre issue whereby the application worked in debug, but gave the XamlParseException once released.

After fixing the x86/x64 issue as detailed by Katjoek, the issue remained.

The issue was that a CEF tutorial said to bring down System.Windows.Interactivity from NuGet (even thought it's in the Extensions section of references in .NET) and bringing down from NuGet sets specific version to true.

Once deployed, a different version of System.Windows.Interactivity was being packed by a different application.

It's refusal to use a different version of the dll caused the whole application to crash with XamlParseException.

jQuery UI DatePicker to show month year only

Made a couple of refinements to BrianS's nearly perfect response above:

  1. I've regexed the value set on show because I think it does actually make it slightly more readable in this case (although note I'm using a slightly different format)

  2. My client wanted no calendar so I've added an on show / hide class addition to do that without affecting any other datepickers. The removal of the class is on a timer to avoid the table flashing back up as the datepicker fades out, which seems to be very noticeable in IE.

EDIT: One problem left to solve with this is that there is no way to empty the datepicker - clear the field and click away and it repopulates with the selected date.

EDIT2: I have not managed to solve this nicely (i.e. without adding a separate Clear button next to the input), so ended up just using this: https://github.com/thebrowser/jquery.ui.monthpicker - if anyone can get the standard UI one to do it that would be amazing.

    $('.typeof__monthpicker').datepicker({
        dateFormat: 'mm/yy',
        showButtonPanel:true,
        beforeShow: 
            function(input, dpicker)
            {                           
                if(/^(\d\d)\/(\d\d\d\d)$/.exec($(this).val()))
                {
                    var d = new Date(RegExp.$2, parseInt(RegExp.$1, 10) - 1, 1);

                    $(this).datepicker('option', 'defaultDate', d);
                    $(this).datepicker('setDate', d);
                }

                $('#ui-datepicker-div').addClass('month_only');
            },
        onClose: 
            function(dt, dpicker)
            {
                setTimeout(function() { $('#ui-datepicker-div').removeClass('month_only') }, 250);

                var m = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
                var y = $("#ui-datepicker-div .ui-datepicker-year :selected").val();

                $(this).datepicker('setDate', new Date(y, m, 1));
            }
    });

You also need this style rule:

#ui-datepicker-div.month_only .ui-datepicker-calendar {
display:none
}

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

So simple. In Nuget Package Manager Console:

Update-Package Microsoft.AspNet.Mvc -Reinstall

How to read text files with ANSI encoding and non-English letters?

You get the question-mark-diamond characters when your textfile uses high-ANSI encoding -- meaning it uses characters between 127 and 255. Those characters have the eighth (i.e. the most significant) bit set. When ASP.NET reads the textfile it assumes UTF-8 encoding, and that most significant bit has a special meaning.

You must force ASP.NET to interpret the textfile as high-ANSI encoding, by telling it the codepage is 1252:

String textFilePhysicalPath = System.Web.HttpContext.Current.Server.MapPath("~/textfiles/MyInputFile.txt");
String contents = File.ReadAllText(textFilePhysicalPath, System.Text.Encoding.GetEncoding(1252));
lblContents.Text = contents.Replace("\n", "<br />");  // change linebreaks to HTML

How to replace negative numbers in Pandas Data Frame by zero

If you are dealing with a large df (40m x 700 in my case) it works much faster and memory savvy through iteration on columns with something like.

for col in df.columns:
    df[col][df[col] < 0] = 0

No default constructor found; nested exception is java.lang.NoSuchMethodException with Spring MVC?

If your environment is using both Guice and Spring and using the constructor @Inject, for example, with Play Framework, you will also run into this issue if you have mistakenly auto-completed the import with an incorrect choice of:

import com.google.inject.Inject;

Then you get the same missing default constructor error even though the rest of your source with @Inject looks exactly the same way as other working components in your project and compile without an error.

Correct that with:

import javax.inject.Inject;

Do not write a default constructor with construction time injection.

How to call a REST web service API from JavaScript?

Usual way is to go with PHP and ajax. But for your requirement, below will work fine.

<body>

https://www.google.com/controller/Add/2/2<br>
https://www.google.com/controller/Sub/5/2<br>
https://www.google.com/controller/Multi/3/2<br><br>

<input type="text" id="url" placeholder="RESTful URL" />
<input type="button" id="sub" value="Answer" />
<p>
<div id="display"></div>
</body>

<script type="text/javascript">

document.getElementById('sub').onclick = function(){

var url = document.getElementById('url').value;
var controller = null; 
var method = null; 
var parm = []; 

//validating URLs
function URLValidation(url){
if (url.indexOf("http://") == 0 || url.indexOf("https://") == 0) {
var x = url.split('/');
controller = x[3];
method = x[4]; 
parm[0] = x[5]; 
parm[1] = x[6];
 }
}

//Calculations
function Add(a,b){
return Number(a)+ Number(b);
}
function Sub(a,b){
return Number(a)/Number(b);
}
function Multi(a,b){
return Number(a)*Number(b);
}  

//JSON Response
function ResponseRequest(status,res){
var res = {status: status, response: res};
document.getElementById('display').innerHTML = JSON.stringify(res);
}


//Process
function ProcessRequest(){

if(method=="Add"){
    ResponseRequest("200",Add(parm[0],parm[1]));
}else if(method=="Sub"){
    ResponseRequest("200",Sub(parm[0],parm[1]));
}else if(method=="Multi"){
   ResponseRequest("200",Multi(parm[0],parm[1]));
}else {
    ResponseRequest("404","Not Found");
 }

}

URLValidation(url);
ProcessRequest();

};
</script>

How do I display a text file content in CMD?

tail -3 d:\text_file.txt

tail -1 d:\text_file.txt

I assume this was added to Windows cmd.exe at some point.

How do I query between two dates using MySQL?

As extension to the answer from @sabin and a hint if one wants to compare the date part only (without the time):

If the field to compare is from type datetime and only dates are specified for comparison, then these dates are internally converted to datetime values. This means that the following query

SELECT * FROM `objects` WHERE (date_time_field BETWEEN '2010-01-30' AND '2010-09-29')

will be converted to

SELECT * FROM `objects` WHERE (date_time_field BETWEEN '2010-01-30 00:00:00' AND '2010-09-29 00:00:00')

internally.

This in turn leads to a result that does not include the objects from 2010-09-29 with a time value greater than 00:00:00!

Thus, if all objects with date 2010-09-29 should be included too, the field to compare has to be converted to a date:

SELECT * FROM `objects` WHERE (DATE(date_time_field) BETWEEN '2010-01-30' AND '2010-09-29')

How to specify non-default shared-library path in GCC Linux? Getting "error while loading shared libraries" when running

Should it be LIBRARY_PATH instead of LD_LIBRARY_PATH. gcc checks for LIBRARY_PATH which can be seen with -v option

What is dynamic programming?

I am also very much new to Dynamic Programming (a powerful algorithm for particular type of problems)

In most simple words, just think dynamic programming as a recursive approach with using the previous knowledge

Previous knowledge is what matters here the most, Keep track of the solution of the sub-problems you already have.

Consider this, most basic example for dp from Wikipedia

Finding the fibonacci sequence

function fib(n)   // naive implementation
    if n <=1 return n
    return fib(n - 1) + fib(n - 2)

Lets break down the function call with say n = 5

fib(5)
fib(4) + fib(3)
(fib(3) + fib(2)) + (fib(2) + fib(1))
((fib(2) + fib(1)) + (fib(1) + fib(0))) + ((fib(1) + fib(0)) + fib(1))
(((fib(1) + fib(0)) + fib(1)) + (fib(1) + fib(0))) + ((fib(1) + fib(0)) + fib(1))

In particular, fib(2) was calculated three times from scratch. In larger examples, many more values of fib, or sub-problems, are recalculated, leading to an exponential time algorithm.

Now, lets try it by storing the value we already found out in a data-structure say a Map

var m := map(0 ? 0, 1 ? 1)
function fib(n)
    if key n is not in map m 
        m[n] := fib(n - 1) + fib(n - 2)
    return m[n]

Here we are saving the solution of sub-problems in the map, if we don't have it already. This technique of saving values which we already had calculated is termed as Memoization.

At last, For a problem, first try to find the states (possible sub-problems and try to think of the better recursion approach so that you can use the solution of previous sub-problem into further ones).

How to use WebRequest to POST some data and read response?

From MSDN

// Create a request using a URL that can receive a post. 
WebRequest request = WebRequest.Create ("http://contoso.com/PostAccepter.aspx ");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream ();
// Write the data to the request stream.
dataStream.Write (byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close ();
// Get the response.
WebResponse response = request.GetResponse ();
// Display the status.
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
// Display the content.
Console.WriteLine (responseFromServer);
// Clean up the streams.
reader.Close ();
dataStream.Close ();
response.Close ();

Take into account that the information must be sent in the format key1=value1&key2=value2

How to add a Try/Catch to SQL Stored Procedure

Create Proc[usp_mquestions]  
( 
 @title  nvarchar(500),   --0
 @tags  nvarchar(max),   --1
 @category  nvarchar(200),   --2
 @ispoll  char(1),   --3
 @descriptions  nvarchar(max),   --4
)              
 AS  
 BEGIN TRY




BEGIN
DECLARE @message varchar(1000); 
DECLARE @tempid bigint; 

IF((SELECT count(id) from  [xyz] WHERE title=@title)>0)
BEGIN
SELECT 'record already existed.';
END
ELSE
BEGIN               


if @id=0 
begin 
select @tempid =id from [xyz] where id=@id;

if @tempid is null 
BEGIN 
        INSERT INTO xyz
        (entrydate,updatedate)
        VALUES
        (GETDATE(),GETDATE())

        SET @tempid=@@IDENTITY;
 END 
END 
ELSE 
BEGIN 
set @tempid=@id 
END 
if @tempid>0 
BEGIN 

    -- Updation of table begin--


UPDATE  tab_questions
set title=@title, --0 
 tags=@tags, --1 
 category=@category, --2 
 ispoll=@ispoll, --3 
 descriptions=@descriptions, --4 
 status=@status, --5

WHERE id=@tempid ; --9 ;


IF @id=0 
BEGIN 
SET @message= 'success:Record added successfully:'+ convert(varchar(10), @tempid)
END 
ELSE 
BEGIN 
SET @message= 'success:Record updated successfully.:'+ convert(varchar(10), @tempid)

END 
END 
ELSE 
BEGIN 
SET @message= 'failed:invalid request:'+convert(varchar(10), @tempid)
END 

END
END

END TRY
BEGIN CATCH
    SET @message='failed:'+ ERROR_MESSAGE();
END CATCH
SELECT @message;

How do I run PHP code when a user clicks on a link?

I know this post is old but I just wanted to add my answer!

You said to log a user out WITHOUT directing... this method DOES redirect but it returns the user to the page they were on! here's my implementation:

// every page with logout button
<?php
        // get the full url of current page
        $page = $_SERVER['PHP_SELF'];
        // find position of the last '/'
        $file_name_begin_pos = strripos($page, "/");
        // get substring from position to end 
        $file_name = substr($page, ++$fileNamePos);
    }
?>

// the logout link in your html
<a href="logout.php?redirect_to=<?=$file_name?>">Log Out</a>

// logout.php page
<?php
    session_start();
    $_SESSION = array();
    session_destroy();
    $page = "index.php";
    if(isset($_GET["redirect_to"])){
        $file = $_GET["redirect_to"];
        if ($file == "user.php"){
            // if redirect to is a restricted page, redirect to index
            $file = "index.php";
        }
    }
    header("Location: $file");
?>

and there we go!

the code that gets the file name from the full url isn't bug proof. for example if query strings are involved with un-escaped '/' in them, it will fail.

However there are many scripts out there to get the filename from url!

Happy Coding!

Alex

Compare data of two Excel Columns A & B, and show data of Column A that do not exist in B

All values of column A that are not present in column B will have a red background. Hope that it helps as starting point.

Sub highlight_missings()
Dim i As Long, lastA As Long, lastB As Long
Dim compare As Variant
Range("A:A").ClearFormats
lastA = Range("A65536").End(xlUp).Row
lastB = Range("B65536").End(xlUp).Row

For i = 2 To lastA
    compare = Application.Match(Range("a" & i), Range("B2:B" & lastB), 0)
        If IsError(compare) Then
            Range("A" & i).Interior.ColorIndex = 3
        End If
Next i
End Sub

Unsafe JavaScript attempt to access frame with URL

From a child document of different origin you are not allowed access to the top window's location.hash property, but you are allowed to set the location property itself.

This means that given that the top windows location is http://example.com/page/, instead of doing

parent.location.hash = "#foobar";

you do need to know the parents location and do

parent.location = "http://example.com/page/#foobar";

Since the resource is not navigated this will work as expected, only changing the hash part of the url.

If you are using this for cross-domain communication, then I would recommend using easyXDM instead.

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

delay does not work on none queue functions, so we should use setTimeout().

And you don't need to separate things. All you need to do is including everything in a setTimeOut method:

setTimeout(function () {
    $("#div").addClass("error").delay(1000).removeClass("error");
}, 1000);

Check if a temporary table exists and delete if it exists before creating a temporary table

My code uses a Source table that changes, and a Destination table that must match those changes.

-- 
-- Sample SQL to update only rows in a "Destination" Table
--  based on only rows that have changed in a "Source" table
--


--
-- Drop and Create a Temp Table to use as the "Source" Table
--
IF OBJECT_ID('tempdb..#tSource') IS NOT NULL drop table #tSource
create table #tSource (Col1 int, Col2 int, Col3 int, Col4 int)

--
-- Insert some values into the source
--
Insert #tSource (Col1, Col2, Col3, Col4) Values(1,1,1,1)
Insert #tSource (Col1, Col2, Col3, Col4) Values(2,1,1,2)
Insert #tSource (Col1, Col2, Col3, Col4) Values(3,1,1,3)
Insert #tSource (Col1, Col2, Col3, Col4) Values(4,1,1,4)
Insert #tSource (Col1, Col2, Col3, Col4) Values(5,1,1,5)
Insert #tSource (Col1, Col2, Col3, Col4) Values(6,1,1,6)

--
-- Drop and Create a Temp Table to use as the "Destination" Table
--
IF OBJECT_ID('tempdb..#tDest') IS NOT NULL drop Table #tDest
create table #tDest (Col1 int, Col2 int, Col3 int, Col4 int)

--
-- Add all Rows from the Source to the Destination
--
Insert #tDest
Select Col1, Col2, Col3, Col4 from #tSource


--
-- Look at both tables to see that they are the same
--
select *
from #tSource
Select *
from #tDest

--
-- Make some changes to the Source
--
update #tSource
    Set Col3=19
    Where Col1=1
update #tSource
    Set Col3=29
    Where Col1=2
update #tSource
    Set Col2=38
    Where Col1=3
update #tSource
    Set Col2=48
    Where Col1=4

--
-- Look at the Differences
-- Note: Only 4 rows are different. 2 Rows have remained the same.
--
Select Col1, Col2, Col3, Col4
from #tSource
except
Select Col1, Col2, Col3, Col4
from #tDest

--
-- Update only the rows that have changed
-- Note: I am using Col1 like an ID column
--
Update #tDest
    Set Col2=S.Col2,
        Col3=S.Col3,
        Col4=S.Col4
From    (   Select Col1, Col2, Col3, Col4
            from #tSource
            except
            Select Col1, Col2, Col3, Col4
            from #tDest
        ) S
Where #tDest.Col1=S.Col1 

--
-- Look at the tables again to see that
--  the destination table has changed to match
--  the source table.

select *
from #tSource
Select *
from #tDest

--
-- Clean Up
--
drop table #tSource
drop table #tDest

How to add number of days in postgresql datetime

For me I had to put the whole interval in single quotes not just the value of the interval.

select id,  
   title,
   created_at + interval '1 day' * claim_window as deadline from projects   

Instead of

select id,  
   title,
   created_at + interval '1' day * claim_window as deadline from projects   

Postgres Date/Time Functions

Remove title in Toolbar in appcompat-v7

if your using default toolbar then you can add this line of code

Objects.requireNonNull(getSupportActionBar()).setDisplayShowTitleEnabled(false);

Angular 2.0 router not working on reloading the browser

The error you are seeing is because you are requesting http://localhost/route which doesn't exist. According to Simon.

When using html5 routing you need to map all routes in your app(currently 404) to index.html in your server side. Here are some options for you:

  1. using live-server: https://www.npmjs.com/package/live-server

    $live-server --entry-file=index.html`
    
  2. using nginx: http://nginx.org/en/docs/beginners_guide.html

    error_page 404 /index.html
    
  3. Tomcat - configuration of web.xml. From Kunin's comment

    <error-page>
          <error-code>404</error-code>
          <location>/index.html</location>
    </error-page>
    

The specified child already has a parent. You must call removeView() on the child's parent first

in ActivitySaludo, this line,

    setContentView(txtCambiado);

you must set the content view for the activity only once.

How to execute the start script with Nodemon

Add this to script object from your project's package.json file


    "start":"nodemon index.js"

It should be like this


    "scripts": {
        "start":"nodemon index.js"
    }

Google Maps JS API v3 - Simple Multiple Marker Example

This is the working example map image

var arr = new Array();
    function initialize() { 
        var i;  
        var Locations = [
                {
                  lat:48.856614, 
                  lon:2.3522219000000177, 
                  address:'Paris',
                  gval:'25.5',
                  aType:'Non-Commodity',
                  title:'Paris',
                  descr:'Paris'           
                },        
                    {
                  lat: 55.7512419, 
                  lon: 37.6184217,
                  address:'Moscow',
                  gval:'11.5',
                  aType:'Non-Commodity',
                  title:'Moscow',
                  descr:'Moscow Airport'              
                },     

                {
              lat:-9.481553000000002, 
              lon:147.190242, 
              address:'Port Moresby',
              gval:'1',
              aType:'Oil',
              title:'Papua New Guinea',
              descr:'Papua New Guinea 123123123'              
            },
            {
           lat:20.5200,
           lon:77.7500,
           address:'Indore',
            gval:'1',
            aType:'Oil',
            title:'Indore, India',
            descr:'Airport India'
        }
    ];

    var myOptions = {
        zoom: 2,
        center: new google.maps.LatLng(51.9000,8.4731),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById("map"), myOptions);

    var infowindow =  new google.maps.InfoWindow({
        content: ''
    });

    for (i = 0; i < Locations.length; i++) {
            size=15;        
            var img=new google.maps.MarkerImage('marker.png',           
                new google.maps.Size(size, size),
                new google.maps.Point(0,0),
                new google.maps.Point(size/2, size/2)
           );

        var marker = new google.maps.Marker({
            map: map,
            title: Locations[i].title,
            position: new google.maps.LatLng(Locations[i].lat, Locations[i].lon),           
                icon: img
        });

        bindInfoWindow(marker, map, infowindow, "<p>" + Locations[i].descr + "</p>",Locations[i].title);  

    }

}

function bindInfoWindow(marker, map, infowindow, html, Ltitle) { 
    google.maps.event.addListener(marker, 'mouseover', function() {
            infowindow.setContent(html); 
            infowindow.open(map, marker); 

    });
    google.maps.event.addListener(marker, 'mouseout', function() {
        infowindow.close();

    }); 
} 

Full working example. You can just copy, paste and use.

How can I make a JUnit test wait?

You can use java.util.concurrent.TimeUnit library which internally uses Thread.sleep. The syntax should look like this :

@Test
public void testExipres(){
    SomeCacheObject sco = new SomeCacheObject();
    sco.putWithExipration("foo", 1000);

    TimeUnit.MINUTES.sleep(2);

    assertNull(sco.getIfNotExipred("foo"));
}

This library provides more clear interpretation for time unit. You can use 'HOURS'/'MINUTES'/'SECONDS'.

Change WPF window background image in C# code

The problem is the way you are using it in code. Just try the below code

public partial class MainView : Window
{
    public MainView()
    {
        InitializeComponent();

        ImageBrush myBrush = new ImageBrush();
        myBrush.ImageSource =
            new BitmapImage(new Uri("pack://application:,,,/icon.jpg", UriKind.Absolute));
        this.Background = myBrush;
    }
}

You can find more details regarding this in
http://msdn.microsoft.com/en-us/library/aa970069.aspx

How to produce a range with step n in bash? (generate a sequence of numbers with increments)

Bash 4's brace expansion has a step feature:

for {0..10..2}; do
  ..
done

No matter if Bash 2/3 (C-style for loop, see answers above) or Bash 4, I would prefer anything over the 'seq' command.

Marker in leaflet, click event

Additional relevant info: A common need is to pass the ID of the object represented by the marker to some ajax call for the purpose of fetching more info from the server.

It seems that when we do:

marker.on('click', function(e) {...

The e points to a MouseEvent, which does not let us get to the marker object. But there is a built-in this object which strangely, requires us to use this.options to get to the options object which let us pass anything we need. In the above case, we can pass some ID in an option, let's say objid then within the function above, we can get the value by invoking: this.options.objid

Android Studio-No Module

Go to Project setting enter image description here

CHECK if the project setting is like this,if the module that you want is show in here enter image description here

IF the module that you want or "Module SDK" is not show or not correct.

then go to the module's build.gradle file to check if the CompileSdkVersion has installed in your computer.

or modifier the CompileSdkVersion to the version that has been installed in your computer.

In my case:I just installed sdk version 29 in my computer but in the module build.gradle file ,I'm setting the CompilerSdkVersion 28

Both are not matched.

Modifier the build.gradle file CompilerSdkVersion 29 which I installed in my computer

It's working!!!

enter image description here enter image description here

Spring - @Transactional - What happens in background?

As a visual person, I like to weigh in with a sequence diagram of the proxy pattern. If you don't know how to read the arrows, I read the first one like this: Client executes Proxy.method().

  1. The client calls a method on the target from his perspective, and is silently intercepted by the proxy
  2. If a before aspect is defined, the proxy will execute it
  3. Then, the actual method (target) is executed
  4. After-returning and after-throwing are optional aspects that are executed after the method returns and/or if the method throws an exception
  5. After that, the proxy executes the after aspect (if defined)
  6. Finally the proxy returns to the calling client

Proxy Pattern Sequence Diagram (I was allowed to post the photo on condition that I mentioned its origins. Author: Noel Vaes, website: www.noelvaes.eu)

How to get coordinates of an svg element?

You can use the function getBBox() to get the bounding box for the path. This will give you the position and size of the tightest rectangle that could contain the rendered path.

An advantage of using this method over reading the x and y values is that it will work with all graphical objects. There are more objects than paths that do not have x and y, for example circles that have cx and cy instead.

TypeError: ObjectId('') is not JSON serializable

If you will not be needing the _id of the records I will recommend unsetting it when querying the DB which will enable you to print the returned records directly e.g

To unset the _id when querying and then print data in a loop you write something like this

records = mycollection.find(query, {'_id': 0}) #second argument {'_id':0} unsets the id from the query
for record in records:
    print(record)

JPA: How to get entity based on field value other than ID?

Write a custom method like this:

public Object findByYourField(Class entityClass, String yourFieldValue)
{
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery(entityClass);
    Root<Object> root = criteriaQuery.from(entityClass);
    criteriaQuery.select(root);

    ParameterExpression<String> params = criteriaBuilder.parameter(String.class);
    criteriaQuery.where(criteriaBuilder.equal(root.get("yourField"), params));

    TypedQuery<Object> query = entityManager.createQuery(criteriaQuery);
    query.setParameter(params, yourFieldValue);

    List<Object> queryResult = query.getResultList();

    Object returnObject = null;

    if (CollectionUtils.isNotEmpty(queryResult)) {
        returnObject = queryResult.get(0);
    }

    return returnObject;
}

How add class='active' to html menu with php

seperate your page from nav bar.

pageOne.php:

$page="one";
include("navigation.php");

navigation.php

if($page=="one"){$oneIsActive = 'class="active"';}else{ $oneIsActive=""; }
if($page=="two"){$twoIsActive = 'class="active"';}else{ $twoIsActive=""; }
if($page=="three"){$threeIsActive = 'class="active"';}else{ $threeIsActive=""; }

<ul class="nav">
  <li <?php echo $oneIsActive; ?>><a href="pageOne.php">One</a></li>
  <li <?php echo $twoIsActive; ?>><a href="pageTwo.php"><a href="#">Page 2</a></li>
  <li <?php echo $threeIsActive; ?>><a href="pageThree.php"><a href="#">Page 3</a></li>
</ul>

I found that I could also set the title of my pages with this method as well.

 $page="one";
 $title="This is page one."
 include("navigation.php");

and just grab the $title var and put it in between the "title" tags. Though I am sending it to my header page above my nav bar.

StringUtils.isBlank() vs String.isEmpty()

StringUtils.isBlank also returns true for just whitespace:

isBlank(String str)

Checks if a String is whitespace, empty ("") or null.

Add Favicon with React and Webpack

This worked for me:

Add this in index.html (inside src folder along with favicon.ico)

**<link rel="icon" href="/src/favicon.ico" type="image/x-icon" />**

webpack.config.js is like:

 plugins: [new HtmlWebpackPlugin({`enter code here`
        template: './src/index.html'
    })],

java.net.ConnectException :connection timed out: connect?

Number (1): The IP was incorrect - is the correct answer. The /etc/hosts file (a.k.a. C:\Windows\system32\drivers\etc\hosts ) had an incorrect entry for the local machine name. Corrected the 'hosts' file and Camel runs very well. Thanks for the pointer.

javascript onclick increment number

Simple HTML + Thymeleaf version. Code with Controller

<form action="/" method="post">
                <input type="hidden" th:value="${post.getId_post()}" name="id_post">
                <input type="hidden" th:value="-1" name="valueForChange">
                <input type="submit" value="-">
</form>

This is how it looks - look of buttons you can change with style. https://i.stack.imgur.com/b97N1.png

How to make in CSS an overlay over an image?

A bit late for this, but this thread comes up in Google as a top result when searching for an overlay method.

You could simply use a background-blend-mode

.foo {
    background-image: url(images/image1.png), url(images/image2.png);
    background-color: violet;
    background-blend-mode: screen multiply;
}

What this does is it takes the second image, and it blends it with the background colour by using the multiply blend mode, and then it blends the first image with the second image and the background colour by using the screen blend mode. There are 16 different blend modes that you could use to achieve any overlay.

multiply, screen, overlay, darken, lighten, color-dodge, color-burn, hard-light, soft-light, difference, exclusion, hue, saturation, color and luminosity.

Combine two OR-queries with AND in Mongoose

It's probably easiest to create your query object directly as:

  Test.find({
      $and: [
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ]
  }, function (err, results) {
      ...
  }

But you can also use the Query#and helper that's available in recent 3.x Mongoose releases:

  Test.find()
      .and([
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ])
      .exec(function (err, results) {
          ...
      });

What is PECS (Producer Extends Consumer Super)?

In a nutshell, three easy rules to remember PECS:

  1. Use the <? extends T> wildcard if you need to retrieve object of type T from a collection.
  2. Use the <? super T> wildcard if you need to put objects of type T in a collection.
  3. If you need to satisfy both things, well, don’t use any wildcard. As simple as that.

How to disable a particular checkstyle rule for a particular line of code?

I had difficulty with the answers above, potentially because I set the checkStyle warnings to be errors. What did work was SuppressionFilter: http://checkstyle.sourceforge.net/config_filters.html#SuppressionFilter

The drawback of this is that the line range is stored in a separate suppresssions.xml file, so an unfamiliar developer may not immediately make the connection.

Scanner vs. StringTokenizer vs. String.Split

I recently did some experiments about the bad performance of String.split() in highly performance sensitive situations. You may find this useful.

http://eblog.chrononsystems.com/hidden-evils-of-javas-stringsplit-and-stringr

The gist is that String.split() compiles a Regular Expression pattern each time and can thus slow down your program, compared to if you use a precompiled Pattern object and use it directly to operate on a String.

React eslint error missing in props validation

It seems that the problem is in eslint-plugin-react.

It can not correctly detect what props were mentioned in propTypes if you have annotated named objects via destructuring anywhere in the class.

There was similar problem in the past

Server.UrlEncode vs. HttpUtility.UrlEncode

Fast-forward almost 9 years since this was first asked, and in the world of .NET Core and .NET Standard, it seems the most common options we have for URL-encoding are WebUtility.UrlEncode (under System.Net) and Uri.EscapeDataString. Judging by the most popular answer here and elsewhere, Uri.EscapeDataString appears to be preferable. But is it? I did some analysis to understand the differences and here's what I came up with:

  • WebUtility.UrlEncode encodes space as +; Uri.EscapeDataString encodes it as %20.
  • Uri.EscapeDataString percent-encodes !, (, ), and *; WebUtility.UrlEncode does not.
  • WebUtility.UrlEncode percent-encodes ~; Uri.EscapeDataString does not.
  • Uri.EscapeDataString throws a UriFormatException on strings longer than 65,520 characters; WebUtility.UrlEncode does not. (A more common problem than you might think, particularly when dealing with URL-encoded form data.)
  • Uri.EscapeDataString throws a UriFormatException on the high surrogate characters; WebUtility.UrlEncode does not. (That's a UTF-16 thing, probably a lot less common.)

For URL-encoding purposes, characters fit into one of 3 categories: unreserved (legal in a URL); reserved (legal in but has special meaning, so you might want to encode it); and everything else (must always be encoded).

According to the RFC, the reserved characters are: :/?#[]@!$&'()*+,;=

And the unreserved characters are alphanumeric and -._~

The Verdict

Uri.EscapeDataString clearly defines its mission: %-encode all reserved and illegal characters. WebUtility.UrlEncode is more ambiguous in both definition and implementation. Oddly, it encodes some reserved characters but not others (why parentheses and not brackets??), and stranger still it encodes that innocently unreserved ~ character.

Therefore, I concur with the popular advice - use Uri.EscapeDataString when possible, and understand that reserved characters like / and ? will get encoded. If you need to deal with potentially large strings, particularly with URL-encoded form content, you'll need to either fall back on WebUtility.UrlEncode and accept its quirks, or otherwise work around the problem.


EDIT: I've attempted to rectify ALL of the quirks mentioned above in Flurl via the Url.Encode, Url.EncodeIllegalCharacters, and Url.Decode static methods. These are in the core package (which is tiny and doesn't include all the HTTP stuff), or feel free to rip them from the source. I welcome any comments/feedback you have on these.


Here's the code I used to discover which characters are encoded differently:

var diffs =
    from i in Enumerable.Range(0, char.MaxValue + 1)
    let c = (char)i
    where !char.IsHighSurrogate(c)
    let diff = new {
        Original = c,
        UrlEncode = WebUtility.UrlEncode(c.ToString()),
        EscapeDataString = Uri.EscapeDataString(c.ToString()),
    }
    where diff.UrlEncode != diff.EscapeDataString
    select diff;

foreach (var diff in diffs)
    Console.WriteLine($"{diff.Original}\t{diff.UrlEncode}\t{diff.EscapeDataString}");

Why does 'git commit' not save my changes?

Maybe an obvious thing, but...

If you have problem with the index, use git-gui. You get a very good view how the index (staging area) actually works.

Another source of information that helped me understand the index was Scott Chacons "Getting Git" page 259 and forward.

I started off using the command line because most documentation only showed that...

I think git-gui and gitk actually make me work faster, and I got rid of bad habits like "git pull" for example... Now I always fetch first... See what the new changes really are before I merge.

Angular checkbox and ng-click

cardeal's answer was really helpful. Took it a little further and figured it may help others some where down the line. Here is the fiddle:

https://jsfiddle.net/vtL5x0wh/

And the code:

<body ng-app="checkboxExample">
  <script>
  angular.module('checkboxExample', [])
    .controller('ExampleController', ['$scope', function($scope) {

    $scope.value0 = "none";
    $scope.value1 = "none";
    $scope.value2 = "none";
    $scope.value3 = "none";

    $scope.checkboxModel = {
        critical1: {selected: true, id: 'C1', error:'critical' , score:20},
        critical2: {selected: false, id: 'C2', error:'critical' , score:30},
        critical3: {selected: false, id: 'C3', error:'critical' , score:40},

       myClick : function($event) { 
          $scope.value0 = $event.selected;
          $scope.value1 = $event.id;
          $scope.value2 = $event.error;
          $scope.value3 = $event.score;
        }
    };

   }]);
</script>
<form name="myForm" ng-controller="ExampleController">
  <label>


    Value1:
    <input type="checkbox" ng-model="checkboxModel.critical1.selected" ng-change="checkboxModel.myClick(checkboxModel.critical1)">
  </label><br/>
  <label>Value2:
    <input type="checkbox" ng-model="checkboxModel.critical2.selected" ng-change="checkboxModel.myClick(checkboxModel.critical2)">
   </label><br/>
     <label>Value3:
    <input type="checkbox" ng-model="checkboxModel.critical3.selected" ng-change="checkboxModel.myClick(checkboxModel.critical3)">
   </label><br/><br/><br/><br/>
  <tt>selected = {{value0}}</tt><br/>
  <tt>id = {{value1}}</tt><br/>
  <tt>error = {{value2}}</tt><br/>
  <tt>score = {{value3}}</tt><br/>
 </form>