Programs & Examples On #Memorystream

A memory stream is a kind of stream that has several methods to access and store data in memory.

How do you get a string from a MemoryStream?

Using a StreamReader to convert the MemoryStream to a String.

<Extension()> _
Public Function ReadAll(ByVal memStream As MemoryStream) As String
    ' Reset the stream otherwise you will just get an empty string.
    ' Remember the position so we can restore it later.
    Dim pos = memStream.Position
    memStream.Position = 0

    Dim reader As New StreamReader(memStream)
    Dim str = reader.ReadToEnd()

    ' Reset the position so that subsequent writes are correct.
    memStream.Position = pos

    Return str
End Function

How to get a MemoryStream from a Stream in .NET?

Use this:

var memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);

This will convert Stream to MemoryStream.

Attach a file from MemoryStream to a MailMessage in C#

Since I couldn't find confirmation of this anywhere, I tested if disposing of the MailMessage and/or the Attachment object would dispose of the stream loaded into them as I expected would happen.

It does appear with the following test that when the MailMessage is disposed, all streams used to create attachments will also be disposed. So as long as you dispose your MailMessage the streams that went into creating it do not need handling beyond that.

MailMessage mail = new MailMessage();
//Create a MemoryStream from a file for this test
MemoryStream ms = new MemoryStream(File.ReadAllBytes(@"C:\temp\test.gif"));

mail.Attachments.Add(new System.Net.Mail.Attachment(ms, "test.gif"));
if (mail.Attachments[0].ContentStream == ms) Console.WriteLine("Streams are referencing the same resource");
Console.WriteLine("Stream length: " + mail.Attachments[0].ContentStream.Length);

//Dispose the mail as you should after sending the email
mail.Dispose();
//--Or you can dispose the attachment itself
//mm.Attachments[0].Dispose();

Console.WriteLine("This will throw a 'Cannot access a closed Stream.' exception: " + ms.Length);

Serializing/deserializing with memory stream

BinaryFormatter may produce invalid output in some specific cases. For example it will omit unpaired surrogate characters. It may also have problems with values of interface types. Read this documentation page including community content.

If you find your error to be persistent you may want to consider using XML serializer like DataContractSerializer or XmlSerializer.

Save and load MemoryStream to/from a file

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;

namespace ImageWriterUtil
{
    public class ImageWaterMarkBuilder
    {
        //private ImageWaterMarkBuilder()
        //{
        //}
        Stream imageStream;
        string watermarkText = "©8Bytes.Technology";
        Font font = new System.Drawing.Font("Brush Script MT", 30, FontStyle.Bold, GraphicsUnit.Pixel);
        Brush brush = new SolidBrush(Color.Black);
        Point position;
        public ImageWaterMarkBuilder AddStream(Stream imageStream)
        {
            this.imageStream = imageStream;
            return this;
        }
        public ImageWaterMarkBuilder AddWaterMark(string watermarkText)
        {
            this.watermarkText = watermarkText;
            return this;
        }
        public ImageWaterMarkBuilder AddFont(Font font)
        {
            this.font = font;
            return this;
        }

        public ImageWaterMarkBuilder AddFontColour(Color color)
        {
            this.brush = new SolidBrush(color);
            return this;
        }
        public ImageWaterMarkBuilder AddPosition(Point position)
        {
            this.position = position;
            return this;
        }

        public void CompileAndSave(string filePath)
        {

            //Read the File into a Bitmap.
            using (Bitmap bmp = new Bitmap(this.imageStream, false))
            {
                using (Graphics grp = Graphics.FromImage(bmp))
                {


                    //Determine the size of the Watermark text.
                    SizeF textSize = new SizeF();
                    textSize = grp.MeasureString(watermarkText, font);

                    //Position the text and draw it on the image.
                    if (position == null)
                        position = new Point((bmp.Width - ((int)textSize.Width + 10)), (bmp.Height - ((int)textSize.Height + 10)));
                    grp.DrawString(watermarkText, font, brush, position);

                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        //Save the Watermarked image to the MemoryStream.
                        bmp.Save(memoryStream, ImageFormat.Png);
                        memoryStream.Position = 0;
                       // string fileName = Path.GetFileNameWithoutExtension(filePath);
                        // outPuthFilePath = Path.Combine(Path.GetDirectoryName(filePath), fileName + "_outputh.png");
                        using (FileStream file = new FileStream(filePath, FileMode.Create, System.IO.FileAccess.Write))
                        {
                            byte[] bytes = new byte[memoryStream.Length];
                            memoryStream.Read(bytes, 0, (int)memoryStream.Length);
                            file.Write(bytes, 0, bytes.Length);
                            memoryStream.Close();
                        }
                    }
                }
            }

        }
    }
}

Usage :-

ImageWaterMarkBuilder.AddStream(stream).AddWaterMark("").CompileAndSave(filePath);

Reading from memory stream to string

string result = System.Text.Encoding.UTF8.GetString(fs.ToArray());

Measuring execution time of a function in C++

In Scott Meyers book I found an example of universal generic lambda expression that can be used to measure function execution time. (C++14)

auto timeFuncInvocation = 
    [](auto&& func, auto&&... params) {
        // get time before function invocation
        const auto& start = std::chrono::high_resolution_clock::now();
        // function invocation using perfect forwarding
        std::forward<decltype(func)>(func)(std::forward<decltype(params)>(params)...);
        // get time after function invocation
        const auto& stop = std::chrono::high_resolution_clock::now();
        return stop - start;
     };

The problem is that you are measure only one execution so the results can be very differ. To get a reliable result you should measure a large number of execution. According to Andrei Alexandrescu lecture at code::dive 2015 conference - Writing Fast Code I:

Measured time: tm = t + tq + tn + to

where:

tm - measured (observed) time

t - the actual time of interest

tq - time added by quantization noise

tn - time added by various sources of noise

to - overhead time (measuring, looping, calling functions)

According to what he said later in the lecture, you should take a minimum of this large number of execution as your result. I encourage you to look at the lecture in which he explains why.

Also there is a very good library from google - https://github.com/google/benchmark. This library is very simple to use and powerful. You can checkout some lectures of Chandler Carruth on youtube where he is using this library in practice. For example CppCon 2017: Chandler Carruth “Going Nowhere Faster”;

Example usage:

#include <iostream>
#include <chrono>
#include <vector>
auto timeFuncInvocation = 
    [](auto&& func, auto&&... params) {
        // get time before function invocation
        const auto& start = high_resolution_clock::now();
        // function invocation using perfect forwarding
        for(auto i = 0; i < 100000/*largeNumber*/; ++i) {
            std::forward<decltype(func)>(func)(std::forward<decltype(params)>(params)...);
        }
        // get time after function invocation
        const auto& stop = high_resolution_clock::now();
        return (stop - start)/100000/*largeNumber*/;
     };

void f(std::vector<int>& vec) {
    vec.push_back(1);
}

void f2(std::vector<int>& vec) {
    vec.emplace_back(1);
}
int main()
{
    std::vector<int> vec;
    std::vector<int> vec2;
    std::cout << timeFuncInvocation(f, vec).count() << std::endl;
    std::cout << timeFuncInvocation(f2, vec2).count() << std::endl;
    std::vector<int> vec3;
    vec3.reserve(100000);
    std::vector<int> vec4;
    vec4.reserve(100000);
    std::cout << timeFuncInvocation(f, vec3).count() << std::endl;
    std::cout << timeFuncInvocation(f2, vec4).count() << std::endl;
    return 0;
}

EDIT: Ofcourse you always need to remember that your compiler can optimize something out or not. Tools like perf can be useful in such cases.

Stretch horizontal ul to fit width of div

inelegant (but effective) way: use percentages

#horizontal-style {
    width: 100%;
}

li {
    width: 20%;
}

This only works with the 5 <li> example. For more or less, modify your percentage accordingly. If you have other <li>s on your page, you can always assign these particular ones a class of "menu-li" so that only they are affected.

Responsive Image full screen and centered - maintain aspect ratio, not exceed window

After a lot of trial and error I found this solved my problems. This is used to display photos on TVs via a browser.

  • It Keeps the photos aspect ratio
  • Scales in vertical and horizontal
  • Centers vertically and horizontal
  • The only thing to watch for are really wide images. They do stretch to fill, but not by much, standard camera photos are not altered.

    Give it a try :)

*only tested in chrome so far

HTML:

<div class="frame">
  <img src="image.jpg"/>
</div>

CSS:

.frame {
  border: 1px solid red;

  min-height: 98%;
  max-height: 98%;
  min-width: 99%;
  max-width: 99%;

  text-align: center;
  margin: auto;
  position: absolute;
}
img {
  border: 1px solid blue;

  min-height: 98%;
  max-width: 99%;
  max-height: 98%;

  width: auto;
  height: auto;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}

How do I turn off the mysql password validation?

For mysql 8.0.7, Go to your mysql directory, and then use:

sudo bin/mysql_secure_installation

to configure the password option.

How do I launch the Android emulator from the command line?

Run the first emulator available:

~/Library/Android/sdk/tools/emulator -avd `~/Library/Android/sdk/tools/emulator -list-avds | awk '{print $1}'`

How to terminate a Python script

While you should generally prefer sys.exit because it is more "friendly" to other code, all it actually does is raise an exception.

If you are sure that you need to exit a process immediately, and you might be inside of some exception handler which would catch SystemExit, there is another function - os._exit - which terminates immediately at the C level and does not perform any of the normal tear-down of the interpreter; for example, hooks registered with the "atexit" module are not executed.

Swift's guard keyword

Simply put, it provides a way to validate fields prior to execution. This is a good programming style as it enhances readability. In other languages, it may look like this:

func doSomething() {
    if something == nil {
        // return, break, throw error, etc.
    }
    ...
}

But because Swift provides you with optionals, we can't check if it's nil and assign its value to a variable. In contrast, if let checks that it's not nil and assigns a variable to hold the actual value. This is where guard comes into play. It gives you a more concise way of exiting early using optionals.

How to fix Python indentation

On most UNIX-like systems, you can also run:

expand -t4 oldfilename.py > newfilename.py

from the command line, changing the number if you want to replace tabs with a number of spaces other than 4. You can easily write a shell script to do this with a bunch of files at once, retaining the original file names.

Create GUI using Eclipse (Java)

There are lot of GUI designers even like Eclipse plugins, just few of them could use both, Swing and SWT..

WindowBuilder Pro GUI Designer - eclipse marketplace

WindowBuilder Pro GUI Designer - Google code home page

and

Jigloo SWT/Swing GUI Builder - eclipse market place

Jigloo SWT/Swing GUI Builder - home page

The window builder is quite better tool..

But IMHO, GUIs created by those tools have really ugly and unmanageable code..

Finding the index of an item in a list

If performance is of concern:

It is mentioned in numerous answers that the built-in method of list.index(item) method is an O(n) algorithm. It is fine if you need to perform this once. But if you need to access the indices of elements a number of times, it makes more sense to first create a dictionary (O(n)) of item-index pairs, and then access the index at O(1) every time you need it.

If you are sure that the items in your list are never repeated, you can easily:

myList = ["foo", "bar", "baz"]

# Create the dictionary
myDict = dict((e,i) for i,e in enumerate(myList))

# Lookup
myDict["bar"] # Returns 1
# myDict.get("blah") if you don't want an error to be raised if element not found.

If you may have duplicate elements, and need to return all of their indices:

from collections import defaultdict as dd
myList = ["foo", "bar", "bar", "baz", "foo"]

# Create the dictionary
myDict = dd(list)
for i,e in enumerate(myList):
    myDict[e].append(i)

# Lookup
myDict["foo"] # Returns [0, 4]

How do I remove blank elements from an array?

In my project I use delete:

cities.delete("")

Encrypt and decrypt a String in java

Whether encrypted be the same when plain text is encrypted with the same key depends of algorithm and protocol. In cryptography there is initialization vector IV: http://en.wikipedia.org/wiki/Initialization_vector that used with various ciphers makes that the same plain text encrypted with the same key gives various cipher texts.

I advice you to read more about cryptography on Wikipedia, Bruce Schneier http://www.schneier.com/books.html and "Beginning Cryptography with Java" by David Hook. The last book is full of examples of usage of http://www.bouncycastle.org library.

If you are interested in cryptography the there is CrypTool: http://www.cryptool.org/ CrypTool is a free, open-source e-learning application, used worldwide in the implementation and analysis of cryptographic algorithms.

How do I insert non breaking space character &nbsp; in a JSF page?

You can use primefaces library

 <p:spacer width="10" />

Android Fragment onAttach() deprecated

Currently from the onAttach Fragment code, it is not clear if the Context is the current activity: Source Code

public void onAttach(Context context) {
    mCalled = true;
    final Activity hostActivity = mHost == null ? null : mHost.getActivity();
    if (hostActivity != null) {
        mCalled = false;
        onAttach(hostActivity);
    }
}

If you will take a look at getActivity you will see the same call

/**
 * Return the Activity this fragment is currently associated with.
 */
final public Activity getActivity() {
    return mHost == null ? null : mHost.getActivity();
}

So If you want to be sure that you are getting the Activity then use getActivity() (in onAttach in your Fragment) but don't forget to check for null because if mHost is null your activity will be null

Is there a way to cache GitHub credentials for pushing commits?

TLDR; Use an encrypted netrc file with Git 1.8.3+.

Saving a password for a Git repository HTTPS URL is possible with a ~/.netrc (Unix) or %HOME%/_netrc (note the _) on Windows.

But: That file would store your password in plain text.

Solution: Encrypt that file with GPG (GNU Privacy Guard), and make Git decrypt it each time it needs a password (for push/pull/fetch/clone operation).


Note: with Git 2.18 (Q2 2018), you now can customize the GPG used to decrypt the encrypted .netrc file.

See commit 786ef50, commit f07eeed (12 May 2018) by Luis Marsano (``).
(Merged by Junio C Hamano -- gitster -- in commit 017b7c5, 30 May 2018)

git-credential-netrc: accept gpg option

git-credential-netrc was hardcoded to decrypt with 'gpg' regardless of the gpg.program option.
This is a problem on distributions like Debian that call modern GnuPG something else, like 'gpg2'


Step-by-Step instructions for Windows

With Windows:

(Git has a gpg.exe in its distribution, but using a full GPG installation includes a gpg-agent.exe, which will memorize your passphrase associated to your GPG key.)

  • Install gpg4Win Lite, the minimum gnupg command-line interface (take the most recent gpg4win-vanilla-2.X.Y-betaZZ.exe), and complete your PATH with the GPG installation directory:

    set PATH=%PATH%:C:\path\to\gpg
    copy C:\path\to\gpg\gpg2.exe C:\path\to\gpg\gpg.exe
    

(Note the 'copy' command: Git will need a Bash script to execute the command 'gpg'. Since gpg4win-vanilla-2 comes with gpg2.exe, you need to duplicate it.)

  • Create or import a GPG key, and trust it:

    gpgp --import aKey
    # or
    gpg --gen-key
    

(Make sure to put a passphrase to that key.)

  • Trust that key

  • Install the credential helper script in a directory within your %PATH%:

    cd c:\a\fodler\in\your\path
    curl -o c:\prgs\bin\git-credential-netrc https://raw.githubusercontent.com/git/git/master/contrib/credential/netrc/git-credential-netrc.perl
    

(Beware: the script is renamed in Git 2.25.x/2.26, see below)

(Yes, this is a Bash script, but it will work on Windows since it will be called by Git.)

  • Make a _netrc file in clear text

    machine a_server.corp.com
    login a_login
    password a_password
    protocol https
    
    machine a_server2.corp.com
    login a_login2
    password a_password2
    protocol https
    

(Don't forget the 'protocol' part: 'http' or 'https' depending on the URL you will use.)

  • Encrypt that file:

    gpg -e -r a_recipient _netrc
    

(You now can delete the _netrc file, keeping only the _netrc.gpg encrypted one.)

  • Use that encrypted file:

    git config --local credential.helper "netrc -f C:/path/to/_netrc.gpg -v"
    

(Note the '/': C:\path\to... wouldn't work at all.) (You can use at first -v -d to see what is going on.)

From now on, any Git command using an HTTP(S) URL which requires authentication will decrypt that _netrc.gpg file and use the login/password associated to the server you are contacting. The first time, GPG will ask you for the passphrase of your GPG key, to decrypt the file. The other times, the gpg-agent launched automatically by the first GPG call will provide that passphrase for you.

That way, you can memorize several URLs/logins/passwords in one file, and have it stored on your disk encrypted.
I find it more convenient than a "cache" helper", where you need to remember and type (once per session) a different password for each of your remote services, for said password to be cached in memory.


With Git 2.26 (Q1 2020), the sample credential helper for using .netrc has been updated to work out of the box. See patch/discussion.

See commit 6579d93, commit 1c78c78 (20 Dec 2019) by Denton Liu (Denton-L).
(Merged by Junio C Hamano -- gitster -- in commit 1fd27f8, 25 Dec 2019)

contrib/credential/netrc: make PERL_PATH configurable

Signed-off-by: Denton Liu

The shebang path for the Perl interpreter in git-credential-netrc was hardcoded.
However, some users may have it located at a different location and thus, would have had to manually edit the script.

Add a .perl prefix to the script to denote it as a template and ignore the generated version.
Augment the Makefile so that it generates git-credential-netrc from git-credential-netrc.perl, just like other Perl scripts.

The Makefile recipes were shamelessly stolen from contrib/mw-to-git/Makefile.

And:

With 2.26 (Q1 2020), Sample credential helper for using .netrc has been updated to work out of the box.

See commit 6579d93, commit 1c78c78 (20 Dec 2019) by Denton Liu (Denton-L).
(Merged by Junio C Hamano -- gitster -- in commit 1fd27f8, 25 Dec 2019)

contrib/credential/netrc: work outside a repo

Signed-off-by: Denton Liu

Currently, git-credential-netrc does not work outside of a git repository. It fails with the following error:

fatal: Not a git repository: . at /usr/share/perl5/Git.pm line 214.

There is no real reason why need to be within a repository, though. Credential helpers should be able to work just fine outside the repository as well.

Call the non-self version of config() so that git-credential-netrc no longer needs to be run within a repository.

Jeff King (peff) adds:

I assume you're using a gpg-encrypted netrc (if not, you should probably just use credential-store).
For "read-only" password access, I find the combination of pass with config like this is a bit nicer:

[credential "https://github.com"]
  username = peff
  helper = "!f() { test $1 = get && echo password=`pass github/oauth`; }; f"

Calculate RSA key fingerprint

$ ssh-add -l 

will also work on Mac OS X v10.8 (Mountain Lion) - v10.10 (Yosemite).

It also supports the option -E to specify the fingerprint format so in case MD5 is needed (it's often used, e.g. by GitHub), just add -E md5 to the command.

font-family is inherit. How to find out the font-family in chrome developer pane?

The inherit value, when used, means that the value of the property is set to the value of the same property of the parent element. For the root element (in HTML documents, for the html element) there is no parent element; by definition, the value used is the initial value of the property. The initial value is defined for each property in CSS specifications.

The font-family property is special in the sense that the initial value is not fixed in the specification but defined to be browser-dependent. This means that the browser’s default font family is used. This value can be set by the user.

If there is a continuous chain of elements (in the sense of parent-child relationships) from the root element to the current element, all with font-family set to inherit or not set at all in any style sheet (which also causes inheritance), then the font is the browser default.

This is rather uninteresting, though. If you don’t set fonts at all, browsers defaults will be used. Your real problem might be different – you seem to be looking at the part of style sheets that constitute a browser style sheet. There are probably other, more interesting style sheets that affect the situation.

Fatal error: [] operator not supported for strings

this was available in php 5.6 in php 7+ you should declare the array first

$users = array(); // not $users = ";
$users[] = "762";

Convert time in HH:MM:SS format to seconds only?

Simple

function timeToSeconds($time)
{
     $timeExploded = explode(':', $time);
     if (isset($timeExploded[2])) {
         return $timeExploded[0] * 3600 + $timeExploded[1] * 60 + $timeExploded[2];
     }
     return $timeExploded[0] * 3600 + $timeExploded[1] * 60;
}

How to access shared folder without giving username and password

I found one way to access the shared folder without giving the username and password.

We need to change the share folder protect settings in the machine where the folder has been shared.

Go to Control Panel > Network and sharing center > Change advanced sharing settings > Enable Turn Off password protect sharing option.

By doing the above settings we can access the shared folder without any username/password.

How can a web application send push notifications to iOS devices?

ACTUALLY.. This is brand new mind you.. On the newest version of OS X (Mavericks) you CAN send push notifications from a webpage to the desktop. But according to the documentation, NOT iPhones:

Note: This document pertains to OS X only. Notifications for websites do not appear on iOS.

Currently Apple has plans to allow 2 kinds of push notifications: OS X Website Push Notifications and Local Notifications.

The obvious hurdle here is that this will not work on PCs, nor will it allow you to do android push notifications.

Furthermore, you actually can with versions as old as Snow Leapord, send push notifications from a website as long as said website is open and active. The new Mavericks OS will allow push notifications even if the site isnt opened, assuming you have already given permission to said site to send push notifications.

From the mouth of Apple:

In OS X v10.9 and later, you can dispatch OS X Website Push Notifications from your web server directly to OS X users by using the Apple Push Notification service (APNs). Not to be confused with local notifications, push notifications can reach your users regardless of whether your website or their web browser is open…

To integrate push notifications in your website, you first present an interface that allows the user to opt in to receive notifications. If the user consents, Safari contacts your website requesting its credentials in the form of a file called a push package. The push package also contains notification assets used throughout OS X and data used to communicate to a web service you configure. If the push package is valid, you receive a unique identifier for the user on the device known as a device token. The user receives the notification when you send the combination of this device token and your message, or payload, to APNs.

Upon receiving the notification, the user can click on it to open a webpage of your choosing in the user’s default browser.

Note: If you need a refresher on APNs, read the “Apple Push Notification Service” chapter in Local and Push Notification Programming Guide. Although the document is specific to iOS and OS X push notifications, paradigms of the push notification service still apply.

Java Garbage Collection Log messages

I just wanted to mention that one can get the detailed GC log with the

-XX:+PrintGCDetails 

parameter. Then you see the PSYoungGen or PSPermGen output like in the answer.

Also -Xloggc:gc.log seems to generate the same output like -verbose:gc but you can specify an output file in the first.

Example usage:

java -Xloggc:./memory.log -XX:+PrintGCDetails Memory

To visualize the data better you can try gcviewer (a more recent version can be found on github).

Take care to write the parameters correctly, I forgot the "+" and my JBoss would not start up, without any error message!

T-SQL stored procedure that accepts multiple Id values

Erland Sommarskog has maintained the authoritative answer to this question for the last 16 years: Arrays and Lists in SQL Server.

There are at least a dozen ways to pass an array or list to a query; each has their own unique pros and cons.

I really can't recommend enough to read the article to learn about the tradeoffs among all these options.

DateTime fields from SQL Server display incorrectly in Excel

I had the same problem as Andre. There does not seem to be a direct solution, but a CAST in the query that generates the data fixes the problem as long as you can live within the restrictions of SMALLDATETIME. In the following query, the first column does not format correctly in Excel, the second does.

SELECT GETDATE(), CAST(GETDATE() AS SMALLDATETIME)

Perhaps the fractional part of the seconds in DATETIME and DATETIME2 confuses Excel.

Open a facebook link by native Facebook app on iOS

To add yonix’s comment as an answer, the old fb://page/… URL no longer works. Apparently it was replaced by fb://profile/…, even though a page is not a profile.

VB.NET Switch Statement GoTo Case

I'm not sure it's a good idea to use a GoTo but if you do want to use it, you can do something like this:

Select Case parameter 
    Case "userID"
        ' does something here.
    Case "packageID"
        ' does something here.
    Case "mvrType" 
        If otherFactor Then 
            ' does something here. 
        Else 
            GoTo caseElse
        End If 
    Case Else
caseElse:
        ' does some processing... 
End Select

As I said, although it works, GoTo is not good practice, so here are some alternative solutions:

Using elseif...

If parameter = "userID" Then
    ' does something here.
ElseIf parameter = "packageID" Then
    ' does something here.
ElseIf parameter = "mvrType" AndAlso otherFactor Then
    ' does something here.
Else
    'does some processing...
End If

Using a boolean value...

Dim doSomething As Boolean

Select Case parameter
Case "userID"
     ' does something here.
Case "packageID"
     ' does something here.
Case "mvrType"
     If otherFactor Then
          ' does something here. 
     Else
          doSomething = True
     End If
Case Else
     doSomething = True
End Select

If doSomething Then
     ' does some processing... 
End If

Instead of setting a boolean variable you could also call a method directly in both cases...

Javascript + Regex = Nothing to repeat error?

For Google travelers: this stupidly unhelpful error message is also presented when you make a type and double up the + regex operator:

Okay:

\w+

Not okay:

\w++

Update GCC on OSX

I'm just dropping in to say that using a soft link to accomplish this is a terrible, no-good, horrible idea.

One of the key things about writing software is reproduceability - you want to be able to get the same results every time. These systems are so complex that you want to reduce all invisible sources of error.

Having a soft link is an invisible source of error. It's the sort of thing you'll forget in a month, then move to a different machine, and wonder why you are getting different results - or, you'll try to upgrade your system, and you'll get weird errors because it's not expecting a softlink there.

Moreover, this isn't guaranteed to work - in particular, it's not clear that you will get the correct system include files, which have certainly changed between iterations of gcc.

gcc_select is a systematic way of doing the same thing which will work predictably, or in the very worst case you can file a bug report and get an eventual fix or fix it yourself.

Unfortunately :-( gcc_select does not affect which compiler XCode uses so it's not the way to go if you need to work in XCode (which I do). I still don't know what that way might be.

Rendering raw html with reactjs

I used this library called Parser. It worked for what I needed.

import React, { Component } from 'react';    
import Parser from 'html-react-parser';

class MyComponent extends Component {
  render() {
    <div>{Parser(this.state.message)}</div>
  }
};

Display QImage with QtGui

Thanks All, I found how to do it, which is the same as Dave and Sergey:

I am using QT Creator:

In the main GUI window create using the drag drop GUI and create label (e.g. "myLabel")

In the callback of the button (clicked) do the following using the (*ui) pointer to the user interface window:

void MainWindow::on_pushButton_clicked()
{
     QImage imageObject;
     imageObject.load(imagePath);
     ui->myLabel->setPixmap(QPixmap::fromImage(imageObject));

     //OR use the other way by setting the Pixmap directly

     QPixmap pixmapObject(imagePath");
     ui->myLabel2->setPixmap(pixmapObject);
}

Not equal to != and !== in PHP

!== should match the value and data type

!= just match the value ignoring the data type

$num = '1';
$num2 = 1;

$num == $num2; // returns true    
$num === $num2; // returns false because $num is a string and $num2 is an integer

change directory in batch file using variable

The set statement doesn't treat spaces the way you expect; your variable is really named Pathname[space] and is equal to [space]C:\Program Files.

Remove the spaces from both sides of the = sign, and put the value in double quotes:

set Pathname="C:\Program Files"

Also, if your command prompt is not open to C:\, then using cd alone can't change drives.

Use

cd /d %Pathname%

or

pushd %Pathname%

instead.

How to print a dictionary line by line in Python?

Check the following one-liner:

print('\n'.join("%s\n%s" % (key1,('\n'.join("%s : %r" % (key2,val2) for (key2,val2) in val1.items()))) for (key1,val1) in cars.items()))

Output:

A
speed : 70
color : 2
B
speed : 60
color : 3

How to convert (transliterate) a string from utf8 to ASCII (single byte) in c#?

I was able to figure it out. In case someone wants to know below the code that worked for me:

ASCIIEncoding ascii = new ASCIIEncoding();
byte[] byteArray = Encoding.UTF8.GetBytes(sOriginal);
byte[] asciiArray = Encoding.Convert(Encoding.UTF8, Encoding.ASCII, byteArray);
string finalString = ascii.GetString(asciiArray);

Let me know if there is a simpler way o doing it.

Invert "if" statement to reduce nesting

In my opinion early return is fine if you are just returning void (or some useless return code you're never gonna check) and it might improve readability because you avoid nesting and at the same time you make explicit that your function is done.

If you are actually returning a returnValue - nesting is usually a better way to go cause you return your returnValue just in one place (at the end - duh), and it might make your code more maintainable in a whole lot of cases.

How to remove outliers from a dataset

Outliers are quite similar to peaks, so a peak detector can be useful for identifying outliers. The method described here has quite good performance using z-scores. The animation part way down the page illustrates the method signaling on outliers, or peaks.

Peaks are not always the same as outliers, but they're similar frequently.

An example is shown here: This dataset is read from a sensor via serial communications. Occasional serial communication errors, sensor error or both lead to repeated, clearly erroneous data points. There is no statistical value in these point. They are arguably not outliers, they are errors. The z-score peak detector was able to signal on spurious data points and generated a clean resulting dataset: enter image description here

Strange Characters in database text: Ã, Ã, ¢, â‚ €,

The error usually gets introduced while creation of CSV. Try using Linux for saving the CSV as a TextCSV. Libre Office in Ubuntu can enforce the encoding to be UTF-8, worked for me. I wasted a lot of time trying this on Mac OS. Linux is the key. I've tested on Ubuntu.

Good Luck

Python: How exactly can you take a string, split it, reverse it and join it back together again?

>>> tmp = "a,b,cde"
>>> tmp2 = tmp.split(',')
>>> tmp2.reverse()
>>> "".join(tmp2)
'cdeba'

or simpler:

>>> tmp = "a,b,cde"
>>> ''.join(tmp.split(',')[::-1])
'cdeba'

The important parts here are the split function and the join function. To reverse the list you can use reverse(), which reverses the list in place or the slicing syntax [::-1] which returns a new, reversed list.

Function to clear the console in R and RStudio

If you are using the default R console CTRL + L

RStudio - CTRL + L

Java get last element of a collection

A Collection is not a necessarily ordered set of elements so there may not be a concept of the "last" element. If you want something that's ordered, you can use a SortedSet which has a last() method. Or you can use a List and call mylist.get(mylist.size()-1);

If you really need the last element you should use a List or a SortedSet. But if all you have is a Collection and you really, really, really need the last element, you could use toArray() or you could use an Iterator and iterate to the end of the list.

For example:

public Object getLastElement(final Collection c) {
    final Iterator itr = c.iterator();
    Object lastElement = itr.next();
    while(itr.hasNext()) {
        lastElement = itr.next();
    }
    return lastElement;
}

Including non-Python files with setup.py

Step 1: create a MANIFEST.in file in the same folder with setup.py

Step 2: include the relative path to the files you want to add in MANIFEST.in

include README.rst
include docs/*.txt
include funniest/data.json

Step 3: set include_package_data=True in the setup() function to copy these files to site-package

Reference is here.

ExecuteNonQuery: Connection property has not been initialized.

just try this..

you need to open the connection using connection.open() on the SqlCommand.Connection object before executing ExecuteNonQuery()

Inline labels in Matplotlib

Update: User cphyc has kindly created a Github repository for the code in this answer (see here), and bundled the code into a package which may be installed using pip install matplotlib-label-lines.


Pretty Picture:

semi-automatic plot-labeling

In matplotlib it's pretty easy to label contour plots (either automatically or by manually placing labels with mouse clicks). There does not (yet) appear to be any equivalent capability to label data series in this fashion! There may be some semantic reason for not including this feature which I am missing.

Regardless, I have written the following module which takes any allows for semi-automatic plot labelling. It requires only numpy and a couple of functions from the standard math library.

Description

The default behaviour of the labelLines function is to space the labels evenly along the x axis (automatically placing at the correct y-value of course). If you want you can just pass an array of the x co-ordinates of each of the labels. You can even tweak the location of one label (as shown in the bottom right plot) and space the rest evenly if you like.

In addition, the label_lines function does not account for the lines which have not had a label assigned in the plot command (or more accurately if the label contains '_line').

Keyword arguments passed to labelLines or labelLine are passed on to the text function call (some keyword arguments are set if the calling code chooses not to specify).

Issues

  • Annotation bounding boxes sometimes interfere undesirably with other curves. As shown by the 1 and 10 annotations in the top left plot. I'm not even sure this can be avoided.
  • It would be nice to specify a y position instead sometimes.
  • It's still an iterative process to get annotations in the right location
  • It only works when the x-axis values are floats

Gotchas

  • By default, the labelLines function assumes that all data series span the range specified by the axis limits. Take a look at the blue curve in the top left plot of the pretty picture. If there were only data available for the x range 0.5-1 then then we couldn't possibly place a label at the desired location (which is a little less than 0.2). See this question for a particularly nasty example. Right now, the code does not intelligently identify this scenario and re-arrange the labels, however there is a reasonable workaround. The labelLines function takes the xvals argument; a list of x-values specified by the user instead of the default linear distribution across the width. So the user can decide which x-values to use for the label placement of each data series.

Also, I believe this is the first answer to complete the bonus objective of aligning the labels with the curve they're on. :)

label_lines.py:

from math import atan2,degrees
import numpy as np

#Label line with line2D label data
def labelLine(line,x,label=None,align=True,**kwargs):

    ax = line.axes
    xdata = line.get_xdata()
    ydata = line.get_ydata()

    if (x < xdata[0]) or (x > xdata[-1]):
        print('x label location is outside data range!')
        return

    #Find corresponding y co-ordinate and angle of the line
    ip = 1
    for i in range(len(xdata)):
        if x < xdata[i]:
            ip = i
            break

    y = ydata[ip-1] + (ydata[ip]-ydata[ip-1])*(x-xdata[ip-1])/(xdata[ip]-xdata[ip-1])

    if not label:
        label = line.get_label()

    if align:
        #Compute the slope
        dx = xdata[ip] - xdata[ip-1]
        dy = ydata[ip] - ydata[ip-1]
        ang = degrees(atan2(dy,dx))

        #Transform to screen co-ordinates
        pt = np.array([x,y]).reshape((1,2))
        trans_angle = ax.transData.transform_angles(np.array((ang,)),pt)[0]

    else:
        trans_angle = 0

    #Set a bunch of keyword arguments
    if 'color' not in kwargs:
        kwargs['color'] = line.get_color()

    if ('horizontalalignment' not in kwargs) and ('ha' not in kwargs):
        kwargs['ha'] = 'center'

    if ('verticalalignment' not in kwargs) and ('va' not in kwargs):
        kwargs['va'] = 'center'

    if 'backgroundcolor' not in kwargs:
        kwargs['backgroundcolor'] = ax.get_facecolor()

    if 'clip_on' not in kwargs:
        kwargs['clip_on'] = True

    if 'zorder' not in kwargs:
        kwargs['zorder'] = 2.5

    ax.text(x,y,label,rotation=trans_angle,**kwargs)

def labelLines(lines,align=True,xvals=None,**kwargs):

    ax = lines[0].axes
    labLines = []
    labels = []

    #Take only the lines which have labels other than the default ones
    for line in lines:
        label = line.get_label()
        if "_line" not in label:
            labLines.append(line)
            labels.append(label)

    if xvals is None:
        xmin,xmax = ax.get_xlim()
        xvals = np.linspace(xmin,xmax,len(labLines)+2)[1:-1]

    for line,x,label in zip(labLines,xvals,labels):
        labelLine(line,x,label,align,**kwargs)

Test code to generate the pretty picture above:

from matplotlib import pyplot as plt
from scipy.stats import loglaplace,chi2

from labellines import *

X = np.linspace(0,1,500)
A = [1,2,5,10,20]
funcs = [np.arctan,np.sin,loglaplace(4).pdf,chi2(5).pdf]

plt.subplot(221)
for a in A:
    plt.plot(X,np.arctan(a*X),label=str(a))

labelLines(plt.gca().get_lines(),zorder=2.5)

plt.subplot(222)
for a in A:
    plt.plot(X,np.sin(a*X),label=str(a))

labelLines(plt.gca().get_lines(),align=False,fontsize=14)

plt.subplot(223)
for a in A:
    plt.plot(X,loglaplace(4).pdf(a*X),label=str(a))

xvals = [0.8,0.55,0.22,0.104,0.045]
labelLines(plt.gca().get_lines(),align=False,xvals=xvals,color='k')

plt.subplot(224)
for a in A:
    plt.plot(X,chi2(5).pdf(a*X),label=str(a))

lines = plt.gca().get_lines()
l1=lines[-1]
labelLine(l1,0.6,label=r'$Re=${}'.format(l1.get_label()),ha='left',va='bottom',align = False)
labelLines(lines[:-1],align=False)

plt.show()

Can I get image from canvas element and use it in img src tag?

I´ve found two problems with your Fiddle, one of the problems is first in Zeta´s answer.

the method is not toDataUrl(); is toDataURL(); and you forgot to store the canvas in your variable.

So the Fiddle now works fine http://jsfiddle.net/gfyWK/12/

I hope this helps!

How to get full path of a file?

In a similar scenario, I'm launching a cshell script from some other location. For setting the correct absolute path of the script so that it runs in the designated directory only, I'm using the following code:

set script_dir = `pwd`/`dirname $0`

$0 stores the exact string how the script was executed.

For e.g. if the script was launched like this: $> ../../test/test.csh, $script_dir will contain /home/abc/sandbox/v1/../../test

Get restaurants near my location

Is this what you are looking for?

https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant

types is optional

Difference between Activity Context and Application Context

The reason I think is that ProgressDialog is attached to the activity that props up the ProgressDialog as the dialog cannot remain after the activity gets destroyed so it needs to be passed this(ActivityContext) that also gets destroyed with the activity whereas the ApplicationContext remains even after the activity gets destroyed.

How to make cross domain request

If you're willing to transmit some data and that you don't need to be secured (any public infos) you can use a CORS proxy, it's very easy, you'll not have to change anything in your code or in server side (especially of it's not your server like the Yahoo API or OpenWeather). I've used it to fetch JSON files with an XMLHttpRequest and it worked fine.

How to set default value for form field in Symfony2?

A general solution for any case/approach, mainly by using a form without a class or when we need access to any services to set the default value:

// src/Form/Extension/DefaultFormTypeExtension.php

class DefaultFormTypeExtension extends AbstractTypeExtension
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if (null !== $options['default']) {
            $builder->addEventListener(
                FormEvents::PRE_SET_DATA,
                function (FormEvent $event) use ($options) {
                    if (null === $event->getData()) {
                        $event->setData($options['default']);
                    }
                }
            );
        }
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefault('default', null);
    }

    public function getExtendedType()
    {
        return FormType::class;
    }
}

and register the form extension:

app.form_type_extension:
    class: App\Form\Extension\DefaultFormTypeExtension
    tags:
        - { name: form.type_extension, extended_type: Symfony\Component\Form\Extension\Core\Type\FormType }

After that, we can use default option in any form field:

$formBuilder->add('user', null, array('default' => $this->getUser()));
$formBuilder->add('foo', null, array('default' => 'bar'));

How to read the value of a private field from a different class in Java?

Use the Soot Java Optimization framework to directly modify the bytecode. http://www.sable.mcgill.ca/soot/

Soot is completely written in Java and works with new Java versions.

How can I represent 'Authorization: Bearer <token>' in a Swagger Spec (swagger.json)

By using the requestInterceptor, it worked for me:

const ui = SwaggerUIBundle({
  ...
  requestInterceptor: (req) => {
    req.headers.Authorization = "Bearer " + req.headers.Authorization;
    return req;
  },
  ...
});

ASP.NET MVC passing an ID in an ActionLink to the controller

Don't put the @ before the id

new { id = "1" }

The framework "translate" it in ?Lenght when there is a mismatch in the parameter/route

Retrieving the COM class factory for component failed

For IIS 8 I did basically the same thing as Monic. Im running my application as its own app pool on an x64 machine 1.In DCOMCNFG, right click on the My Computer and select properties.

2.Choose the COM Securities tab.

3.In Access Permissions, click Edit Defaults and add iis apppool\myapp to it and give it Allow local access permission. Do the same for iis apppool\myapp

4.In launch and Activation Permissions, click Edit Defaults and add iis apppool\myapp to it and give it Local launch and Local Activation permission. Do the same for iis apppool\myapp.

additionally I had to make the folders outlined under C:\Windows\SysWOW64\config\systemprofile\Desktop and give read \ write permissions to iis apppool\myapp also

How to display a json array in table format?

var data = [
    {
        id : "001",
        name : "apple",
        category : "fruit",
        color : "red"
    },
    {
        id : "002",
        name : "melon",
        category : "fruit",
        color : "green"
    },
    {
        id : "003",
        name : "banana",
        category : "fruit",
        color : "yellow"
    }
];

for(var i = 0, len = data.length; i < length; i++) {
    var temp = '<tr><td>' + data[i].id + '</td>';
    temp+= '<td>' + data[i].name+ '</td>';
    temp+= '<td>' + data[i].category + '</td>';
    temp+= '<td>' + data[i].color + '</td></tr>';
    $('table tbody').append(temp));
}

How to check if a file exists in the Documents directory in Swift?

This works fine for me in swift4:

func existingFile(fileName: String) -> Bool {

    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
    let url = NSURL(fileURLWithPath: path)
    if let pathComponent = url.appendingPathComponent("\(fileName)") {
        let filePath = pathComponent.path
        let fileManager = FileManager.default
        if fileManager.fileExists(atPath: filePath) 

       {

        return true

        } else {

        return false

        }

    } else {

        return false

        }


}

You can check with this call:

   if existingFile(fileName: "yourfilename") == true {

            // your code if file exists

           } else {

           // your code if file does not exist

           }

I hope it is useful for someone. @;-]

"Integer number too large" error message for 600851475143

The java compiler tries to interpret 600851475143 as a constant value of type int by default. This causes an error since 600851475143 can not be represented with an int.

To tell the compiler that you want the number interpretet as a long you have to add either l or L after it. Your number should then look like this 600851475143L.

Since some Fonts make it hard to distinguish "1" and lower case "l" from each other you should always use the upper case "L".

How to decompile a whole Jar file?

Something like:

jar -xf foo.jar && find . -iname "*.class" | xargs /opt/local/bin/jad -r

maybe?

Python - Convert a bytes array into JSON format

Python 3.5 + Use io module

import json
import io

my_bytes_value = b'[{\'Date\': \'2016-05-21T21:35:40Z\', \'CreationDate\': \'2012-05-05\', \'LogoType\': \'png\', \'Ref\': 164611595, \'Classe\': [\'Email addresses\', \'Passwords\'],\'Link\':\'http://some_link.com\'}]'

fix_bytes_value = my_bytes_value.replace(b"'", b'"')

my_json = json.load(io.BytesIO(fix_bytes_value))  

How to make a WPF window be on top of all other windows of my app (not system wide)?

I too faced the same problem and followed Google to this question. Recently I found the following worked for me.

CustomWindow cw = new CustomWindow();
cw.Owner = this;
cw.ShowDialog();

Secure FTP using Windows batch script

The built in FTP command doesn't have a facility for security. Use cUrl instead. It's scriptable, far more robust and has FTP security.

Py_Initialize fails - unable to load the file system codec

For me this happened when I updated Python 64 bit from 3.6.4 to 3.6.5. It threw some error like "unable to extract python.dll. Do you have permissions."

Pycharm also failed to load interpreter, even though I reloaded it in settings. Running python command gave same error, with and without administrator mode.

Reason

There was error in installation of Python, include folder in python installation directory C:\Users\USERNAME\AppData\Local\Programs\Python\Python36 was missing

Reinstalling Python also dint solve the issue.(Not removal and install)

Solution

Uninstall Python and Install of Python again.

Because running installer was just extracting same files excluding include folder

How to include "zero" / "0" results in COUNT aggregate?

USE join to get 0 count in the result using GROUP BY.

simply 'join' does Inner join in MS SQL so , Go for left or right join.

If the table which contains the primary key is mentioned first in the QUERY then use LEFT join else RIGHT join.

EG:

select WARDNO,count(WARDCODE) from MAIPADH 
right join  MSWARDH on MSWARDH.WARDNO= MAIPADH.WARDCODE
group by WARDNO

.

select WARDNO,count(WARDCODE) from MSWARDH
left join  MAIPADH on MSWARDH.WARDNO= MAIPADH.WARDCODE group by WARDNO

Take group by from the table which has Primary key and count from the another table which has actual entries/details.

How to disable the parent form when a child form is active?

Form1 frmnew = new Form1();
frmnew.ShowDialog();

Ajax success function

It is because Ajax is asynchronous, the success or the error function will be called later, when the server answer the client. So, just move parts depending on the result into your success function like that :

jQuery.ajax({

            type:"post",
            dataType:"json",
            url: myAjax.ajaxurl,
            data: {action: 'submit_data', info: info},
            success: function(data) {
                successmessage = 'Data was succesfully captured';
                $("label#successmessage").text(successmessage);
            },
            error: function(data) {
                successmessage = 'Error';
                $("label#successmessage").text(successmessage);
            },
        });

        $(":input").val('');
        return false;

DOUBLE vs DECIMAL in MySQL

We have just been going through this same issue, but the other way around. That is, we store dollar amounts as DECIMAL, but now we're finding that, for example, MySQL was calculating a value of 4.389999999993, but when storing this into the DECIMAL field, it was storing it as 4.38 instead of 4.39 like we wanted it to. So, though DOUBLE may cause rounding issues, it seems that DECIMAL can cause some truncating issues as well.

Sorting an IList in C#

Is this a valid solution?

        IList<string> ilist = new List<string>();
        ilist.Add("B");
        ilist.Add("A");
        ilist.Add("C");

        Console.WriteLine("IList");
        foreach (string val in ilist)
            Console.WriteLine(val);
        Console.WriteLine();

        List<string> list = (List<string>)ilist;
        list.Sort();
        Console.WriteLine("List");
        foreach (string val in list)
            Console.WriteLine(val);
        Console.WriteLine();

        list = null;

        Console.WriteLine("IList again");
        foreach (string val in ilist)
            Console.WriteLine(val);
        Console.WriteLine();

The result was: IList B A C

List A B C

IList again A B C

Is it possible to add an array or object to SharedPreferences on Android

To write,

SharedPreferences prefs = PreferenceManager
        .getDefaultSharedPreferences(this);
JSONArray jsonArray = new JSONArray();
jsonArray.put(1);
jsonArray.put(2);
Editor editor = prefs.edit();
editor.putString("key", jsonArray.toString());
System.out.println(jsonArray.toString());
editor.commit();

To Read,

try {
    JSONArray jsonArray2 = new JSONArray(prefs.getString("key", "[]"));
    for (int i = 0; i < jsonArray2.length(); i++) {
         Log.d("your JSON Array", jsonArray2.getInt(i)+"");
    }
} catch (Exception e) {
    e.printStackTrace();
}

Other way to do same:

//Retrieve the values
Gson gson = new Gson();
String jsonText = Prefs.getString("key", null);
String[] text = gson.fromJson(jsonText, String[].class);  //EDIT: gso to gson


//Set the values
Gson gson = new Gson();
List<String> textList = new ArrayList<String>(data);
String jsonText = gson.toJson(textList);
prefsEditor.putString("key", jsonText);
prefsEditor.apply();

Using GSON in Java:

public void saveArrayList(ArrayList<String> list, String key){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
    SharedPreferences.Editor editor = prefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(list);
    editor.putString(key, json);
    editor.apply();    

}

public ArrayList<String> getArrayList(String key){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
    Gson gson = new Gson();
    String json = prefs.getString(key, null);
    Type type = new TypeToken<ArrayList<String>>() {}.getType();
    return gson.fromJson(json, type);
}

Using GSON in Kotlin

fun saveArrayList(list: java.util.ArrayList<String?>?, key: String?) {
    val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)
    val editor: Editor = prefs.edit()
    val gson = Gson()
    val json: String = gson.toJson(list)
    editor.putString(key, json)
    editor.apply()
}

fun getArrayList(key: String?): java.util.ArrayList<String?>? {
    val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)
    val gson = Gson()
    val json: String = prefs.getString(key, null)
    val type: Type = object : TypeToken<java.util.ArrayList<String?>?>() {}.getType()
    return gson.fromJson(json, type)
}

How to get the sign, mantissa and exponent of a floating point number

Cast a pointer to the floating point variable as something like an unsigned int. Then you can shift and mask the bits to get each component.

float foo;
unsigned int ival, mantissa, exponent, sign;

foo = -21.4f;
ival = *((unsigned int *)&foo);
mantissa = ( ival & 0x7FFFFF);
ival = ival >> 23;
exponent = ( ival  & 0xFF );
ival = ival >> 8;
sign = ( ival & 0x01 );

Obviously you probably wouldn't use unsigned ints for the exponent and sign bits but this should at least give you the idea.

set gvim font in .vimrc file

I am trying to set this in .vimrc file like below

For GUI specific settings use the .gvimrc instead of .vimrc, which on Windows is either $HOME\_gvimrc or $VIM\_gvimrc.

Check the :help .gvimrc for details. In essence, on start-up VIM reads the .vimrc. After that, if GUI is activated, it also reads the .gvimrc. IOW, all VIM general settings should be kept in .vimrc, all GUI specific things in .gvimrc. (But if you do no use console VIM then you can simply forget about the .vimrc.)

set guifont=Consolas\ 10

The syntax is wrong. After :set guifont=* you can always check the proper syntax for the font using :set guifont?. VIM Windows syntax is :set guifont=Consolas:h10. I do not see precise specification for that, though it is mentioned in the :help win32-faq.

How can I load webpage content into a div on page load?

With jQuery, it is possible, however not using ajax.

function LoadPage(){
  $.get('http://a_site.com/a_page.html', function(data) {
    $('#siteloader').html(data);
  });
}

And then place onload="LoadPage()" in the body tag.

Although if you follow this route, a php version might be better:

echo htmlspecialchars(file_get_contents("some URL"));

What and where are the stack and heap?

From WikiAnwser.

Stack

When a function or a method calls another function which in turns calls another function, etc., the execution of all those functions remains suspended until the very last function returns its value.

This chain of suspended function calls is the stack, because elements in the stack (function calls) depend on each other.

The stack is important to consider in exception handling and thread executions.

Heap

The heap is simply the memory used by programs to store variables. Element of the heap (variables) have no dependencies with each other and can always be accessed randomly at any time.

How to change current working directory using a batch file

Just use cd /d %root% to switch driver letters and change directories.

Alternatively, use pushd %root% to switch drive letters when changing directories as well as storing the previous directory on a stack so you can use popd to switch back.

Note that pushd will also allow you to change directories to a network share. It will actually map a network drive for you, then unmap it when you execute the popd for that directory.

Place input box at the center of div

Here's a rather unconventional way of doing it:

#inputcontainer
{
    display:table-cell; //display like a <td> to make the vertical-align work
    text-align:center; //centre the input horizontally
    vertical-align:middle; //centre the input vertically


    width:200px; //widen the div for demo purposes
    height:200px; //make the div taller for demo purposes
    background:green; //change the background of the div for demo purposes
}

It might not be the best way to do it, and margin? won't work, but it does the job. If you need to use margin, then you could wrap the div that displays as a table cell in another 'normal' div.

JSFiddle: http://jsfiddle.net/qw4QW/

Flutter Circle Design

Try This!

demo

I have added 5 circles you can add more. And instead of RaisedButton use InkResponse.

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(home: new ExampleWidget()));
}

class ExampleWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Widget bigCircle = new Container(
      width: 300.0,
      height: 300.0,
      decoration: new BoxDecoration(
        color: Colors.orange,
        shape: BoxShape.circle,
      ),
    );

    return new Material(
      color: Colors.black,
      child: new Center(
        child: new Stack(
          children: <Widget>[
            bigCircle,
            new Positioned(
              child: new CircleButton(onTap: () => print("Cool"), iconData: Icons.favorite_border),
              top: 10.0,
              left: 130.0,
            ),
            new Positioned(
              child: new CircleButton(onTap: () => print("Cool"), iconData: Icons.timer),
              top: 120.0,
              left: 10.0,
            ),
            new Positioned(
              child: new CircleButton(onTap: () => print("Cool"), iconData: Icons.place),
              top: 120.0,
              right: 10.0,
            ),
            new Positioned(
              child: new CircleButton(onTap: () => print("Cool"), iconData: Icons.local_pizza),
              top: 240.0,
              left: 130.0,
            ),
            new Positioned(
              child: new CircleButton(onTap: () => print("Cool"), iconData: Icons.satellite),
              top: 120.0,
              left: 130.0,
            ),
          ],
        ),
      ),
    );
  }
}

class CircleButton extends StatelessWidget {
  final GestureTapCallback onTap;
  final IconData iconData;

  const CircleButton({Key key, this.onTap, this.iconData}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    double size = 50.0;

    return new InkResponse(
      onTap: onTap,
      child: new Container(
        width: size,
        height: size,
        decoration: new BoxDecoration(
          color: Colors.white,
          shape: BoxShape.circle,
        ),
        child: new Icon(
          iconData,
          color: Colors.black,
        ),
      ),
    );
  }
}

How to suppress warnings globally in an R Script

You could use

options(warn=-1)

But note that turning off warning messages globally might not be a good idea.

To turn warnings back on, use

options(warn=0)

(or whatever your default is for warn, see this answer)

Remove .php extension with .htaccess

I found 100% working Concept for me:

# Options is required by Many Hosting
Options +MultiViews

RewriteEngine on

# For .php & .html URL's:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
RewriteRule ^([^\.]+)$ $1.html [NC,L]

Use this code in Root of your website .htaccess file like :

offline - wamp\www\YourWebDir

online - public_html/

If it doesn't work correct, then change the settings of your Wamp Server: 1) Left click WAMP icon 2) Apache 3) Apache Modules 4) Left click rewrite_module

Remove last item from array

I would consider .pop() to be the most 'correct' solution, however, sometimes it might not work since you need to use array without the last element right there...

In such a case you might want to use the following, it will return [1,2,3]

_x000D_
_x000D_
var arr = [1,2,3,4];_x000D_
console.log(arr.splice(0,arr.length-1));
_x000D_
_x000D_
_x000D_

while .pop() would return 4:

_x000D_
_x000D_
var arr = [1,2,3,4];_x000D_
console.log(arr.pop());
_x000D_
_x000D_
_x000D_

which might not be desirable...

Hope this saves you some time.

How to redirect DNS to different ports

You can use SRV records:

_service._proto.name. TTL class SRV priority weight port target.

Service: the symbolic name of the desired service.

Proto: the transport protocol of the desired service; this is usually either TCP or UDP.

Name: the domain name for which this record is valid, ending in a dot.

TTL: standard DNS time to live field.

Class: standard DNS class field (this is always IN).

Priority: the priority of the target host, lower value means more preferred.

Weight: A relative weight for records with the same priority.

Port: the TCP or UDP port on which the service is to be found.

Target: the canonical hostname of the machine providing the service, ending in a dot.

Example:

_sip._tcp.example.com. 86400 IN SRV 0 5 5060 sipserver.example.com.

So what I think you're looking for is to add something like this to your DNS hosts file:

_sip._tcp.arboristal.com. 86400 IN SRV 10 40 25565 mc.arboristal.com.
_sip._tcp.arboristal.com. 86400 IN SRV 10 30 25566 tekkit.arboristal.com.
_sip._tcp.arboristal.com. 86400 IN SRV 10 30 25567 pvp.arboristal.com.

On a side note, I highly recommend you go with a hosting company rather than hosting the servers yourself. It's just asking for trouble with your home connection (DDoS and Bandwidth/Connection Speed), but it's up to you.

How to create a property for a List<T>

Simple and effective alternative:

public class ClassName
{
    public List<dynamic> MyProperty { get; set; }
}

or

public class ClassName
{
    public List<object> MyProperty { get; set; }
}

For differences see this post: List<Object> vs List<dynamic>

How do I prevent people from doing XSS in Spring MVC?

When you are trying to prevent XSS, it's important to think of the context. As an example how and what to escape is very different if you are ouputting data inside a variable in a javascript snippet as opposed to outputting data in an HTML tag or an HTML attribute.

I have an example of this here: http://erlend.oftedal.no/blog/?blogid=91

Also checkout the OWASP XSS Prevention Cheat Sheet: http://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet

So the short answer is, make sure you escape output like suggested by Tendayi Mawushe, but take special care when you are outputting data in HTML attributes or javascript.

Method to find string inside of the text file. Then getting the following lines up to a certain limit

Here is a java 8 method to find a string in a text file:

for (String toFindUrl : urlsToTest) {
        streamService(toFindUrl);
    }

private void streamService(String item) {
        try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
           stream.filter(lines -> lines.contains(item))
                       .forEach(System.out::println);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

How to delete a cookie?

To delete a cookie I set it again with an empty value and expiring in 1 second. In details, I always use one of the following flavours (I tend to prefer the second one):

1.

    function setCookie(key, value, expireDays, expireHours, expireMinutes, expireSeconds) {
        var expireDate = new Date();
        if (expireDays) {
            expireDate.setDate(expireDate.getDate() + expireDays);
        }
        if (expireHours) {
            expireDate.setHours(expireDate.getHours() + expireHours);
        }
        if (expireMinutes) {
            expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
        }
        if (expireSeconds) {
            expireDate.setSeconds(expireDate.getSeconds() + expireSeconds);
        }
        document.cookie = key +"="+ escape(value) +
            ";domain="+ window.location.hostname +
            ";path=/"+
            ";expires="+expireDate.toUTCString();
    }

    function deleteCookie(name) {
        setCookie(name, "", null , null , null, 1);
    }

Usage:

setCookie("reminder", "buyCoffee", null, null, 20);
deleteCookie("reminder");

2

    function setCookie(params) {
        var name            = params.name,
            value           = params.value,
            expireDays      = params.days,
            expireHours     = params.hours,
            expireMinutes   = params.minutes,
            expireSeconds   = params.seconds;

        var expireDate = new Date();
        if (expireDays) {
            expireDate.setDate(expireDate.getDate() + expireDays);
        }
        if (expireHours) {
            expireDate.setHours(expireDate.getHours() + expireHours);
        }
        if (expireMinutes) {
            expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
        }
        if (expireSeconds) {
            expireDate.setSeconds(expireDate.getSeconds() + expireSeconds);
        }

        document.cookie = name +"="+ escape(value) +
            ";domain="+ window.location.hostname +
            ";path=/"+
            ";expires="+expireDate.toUTCString();
    }

    function deleteCookie(name) {
        setCookie({name: name, value: "", seconds: 1});
    }

Usage:

setCookie({name: "reminder", value: "buyCoffee", minutes: 20});
deleteCookie("reminder");

How to fix request failed on channel 0

shell request failed on channel 0

mean you don't have shell or remote commands access, fix your user permission on server to have shell access or if you just want tunneling use -N and -T options

How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

Put in head link to google styles

<link href="https://fonts.googleapis.com/icon?family=Material+Icons+Outlined" rel="stylesheet">

and in body something like this

<i class="material-icons-outlined">bookmarks</i>

How to store a large (10 digits) integer?

A primitive long or its java.lang.Long wrapper can also store ten digits.

Does SVG support embedding of bitmap images?

It is also possible to include bitmaps. I think you also can use transformations on that.

Reading an image file into bitmap from sdcard, why am I getting a NullPointerException?

I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:

String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
    fis = new FileInputStream(imagefile);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
}

Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);    
byte[] b = baos.toByteArray(); 
encImage = Base64.encodeToString(b, Base64.DEFAULT);

Factorial using Recursion in Java

result is a local variable of the fact method. So each time the fact method is called, the result is stored in a different variable than the previous fact invocation.

So when fact is invoked with 3 as argument, you can imagine that its result is

 result3 = fact(2) * 3
 result3 = result2 * 3
 result3 = 1 * 2 * 3

Finding Key associated with max Value in a Java Map

This is going to return the keys with max value in a Map<Integer, Integer>

public Set<Integer> getMaxKeys(Map<Integer, Integer> map) { 

        if (map.isEmpty()) {
            return Collections.emptySet();
        }

        return map
        .entrySet()
        .stream()
        .collect(
            groupingBy(
                Map.Entry::getValue, TreeMap::new, mapping(Map.Entry::getKey, toSet())
            )
         )
         .lastEntry()
         .getValue();
    }

jQuery Mobile Page refresh mechanism

Please take a good look here: http://jquerymobile.com/test/docs/api/methods.html

$.mobile.changePage() is to change from one page to another, and the parameter can be a url or a page object. ( only #result will also work )

$.mobile.page() isn't recommended anymore, please use .trigger( "create"), see also: JQuery Mobile .page() function causes infinite loop?

Important: Create vs. refresh: An important distinction

Note that there is an important difference between the create event and refresh method that some widgets have. The create event is suited for enhancing raw markup that contains one or more widgets. The refresh method that some widgets have should be used on existing (already enhanced) widgets that have been manipulated programmatically and need the UI be updated to match.

For example, if you had a page where you dynamically appended a new unordered list with data-role=listview attribute after page creation, triggering create on a parent element of that list would transform it into a listview styled widget. If more list items were then programmatically added, calling the listview’s refresh method would update just those new list items to the enhanced state and leave the existing list items untouched.

$.mobile.refresh() doesn't exist i guess

So what are you using for your results? A listview? Then you can update it by doing:

$('ul').listview('refresh');

Example: http://operationmobile.com/dont-forget-to-call-refresh-when-adding-items-to-your-jquery-mobile-list/

Otherwise you can do:

$('#result').live("pageinit", function(){ // or pageshow
    // your dom manipulations here
});

Difference between Statement and PreparedStatement

Advantages of a PreparedStatement:

  • Precompilation and DB-side caching of the SQL statement leads to overall faster execution and the ability to reuse the same SQL statement in batches.

  • Automatic prevention of SQL injection attacks by builtin escaping of quotes and other special characters. Note that this requires that you use any of the PreparedStatement setXxx() methods to set the values

    preparedStatement = connection.prepareStatement("INSERT INTO Person (name, email, birthdate, photo) VALUES (?, ?, ?, ?)");
    preparedStatement.setString(1, person.getName());
    preparedStatement.setString(2, person.getEmail());
    preparedStatement.setTimestamp(3, new Timestamp(person.getBirthdate().getTime()));
    preparedStatement.setBinaryStream(4, person.getPhoto());
    preparedStatement.executeUpdate();
    

    and thus don't inline the values in the SQL string by string-concatenating.

    preparedStatement = connection.prepareStatement("INSERT INTO Person (name, email) VALUES ('" + person.getName() + "', '" + person.getEmail() + "'");
    preparedStatement.executeUpdate();
    
  • Eases setting of non-standard Java objects in a SQL string, e.g. Date, Time, Timestamp, BigDecimal, InputStream (Blob) and Reader (Clob). On most of those types you can't "just" do a toString() as you would do in a simple Statement. You could even refactor it all to using PreparedStatement#setObject() inside a loop as demonstrated in the utility method below:

    public static void setValues(PreparedStatement preparedStatement, Object... values) throws SQLException {
        for (int i = 0; i < values.length; i++) {
            preparedStatement.setObject(i + 1, values[i]);
        }
    }
    

    Which can be used as below:

    preparedStatement = connection.prepareStatement("INSERT INTO Person (name, email, birthdate, photo) VALUES (?, ?, ?, ?)");
    setValues(preparedStatement, person.getName(), person.getEmail(), new Timestamp(person.getBirthdate().getTime()), person.getPhoto());
    preparedStatement.executeUpdate();
    

Read all worksheets in an Excel workbook into an R list with data.frames

I tried the above and had issues with the amount of data that my 20MB Excel I needed to convert consisted of; therefore the above did not work for me.

After more research I stumbled upon openxlsx and this one finally did the trick (and fast) Importing a big xlsx file into R?

https://cran.r-project.org/web/packages/openxlsx/openxlsx.pdf

HTTP 404 when accessing .svc file in IIS

In my case Win 10. the file applicationHost.config is corrupted by VS 2012. And you can get the copy the history of this file under C:\inetpub\history. Then restart IIS and it works properly.

How to remove underline from a name on hover

You can use CSS under legend.green-color a:hover to do it.

legend.green-color a:hover {
    color:green;
    text-decoration:none;
}

How to load image files with webpack file-loader

webpack.config.js

{
    test: /\.(png|jpe?g|gif)$/i,
    loader: 'file-loader',
    options: {
        name: '[name].[ext]',
    },
}

anyfile.html

<img src={image_name.jpg} />

Reversing a String with Recursion in Java

AFAIK, there 2 thing in every recursion function :

  1. There is always a stop condition which is :

    if ((null == str) || (str.length() <= 1)) { return str; }

  2. Recursion use the stack memory which use LIFO mechanism that's why the revert happen.

Invoke-Command error "Parameter set cannot be resolved using the specified named parameters"

The error you have is because -credential without -computername can't exist.

You can try this way:

Invoke-Command -Credential $migratorCreds  -ScriptBlock ${function:Get-LocalUsers} -ArgumentList $xmlPRE,$migratorCreds -computername YOURCOMPUTERNAME

Address already in use: JVM_Bind java

I was having this problem too. For me, I couldn't start/stop openfire (it said it was stopped, but everything was still running)

sudo /etc/init.d/openfire stop
sudo /etc/init.d/openfire start

Also, restarting apache did not help either

sudo /etc/init.d/apache2 restart

The errors were inside:

/opt/openfire/logs/stderror.log
Error creating server listener on port 5269: Address already in use
Error creating server listener on port 5222: Address already in use

The way I fixed this, I had to actually turn off the server inside the admin area for my host.

htaccess - How to force the client's browser to clear the cache?

The most straight forward is to add filetime to the request. eg

myfile.txt?2014-10-30-13:12:33

versioning by date.

How to set a header for a HTTP GET request, and trigger file download?

i want to post my solution here which was done AngularJS, ASP.NET MVC. The code illustrates how to download file with authentication.

WebApi method along with helper class:

[RoutePrefix("filess")]
class FileController: ApiController
{
    [HttpGet]
    [Route("download-file")]
    [Authorize(Roles = "admin")]
    public HttpResponseMessage DownloadDocument([FromUri] int fileId)
    {
        var file = "someFile.docx"// asking storage service to get file path with id
        return Request.ReturnFile(file);
    }
}

static class DownloadFIleFromServerHelper
{
    public static HttpResponseMessage ReturnFile(this HttpRequestMessage request, string file)
    {
        var result = request.CreateResponse(HttpStatusCode.OK);

        result.Content = new StreamContent(new FileStream(file, FileMode.Open, FileAccess.Read));
        result.Content.Headers.Add("x-filename", Path.GetFileName(file)); // letters of header names will be lowercased anyway in JS.
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = Path.GetFileName(file)
        };

        return result;
    }
}

Web.config file changes to allow sending file name in custom header.

<configuration>
    <system.webServer>
        <httpProtocol>
            <customHeaders>
                <add name="Access-Control-Allow-Methods" value="POST,GET,PUT,PATCH,DELETE,OPTIONS" />
                <add name="Access-Control-Allow-Headers" value="Authorization,Content-Type,x-filename" />
                <add name="Access-Control-Expose-Headers" value="Authorization,Content-Type,x-filename" />
                <add name="Access-Control-Allow-Origin" value="*" />

Angular JS Service Part:

function proposalService($http, $cookies, config, FileSaver) {
        return {
                downloadDocument: downloadDocument
        };

    function downloadFile(documentId, errorCallback) {
    $http({
        url: config.apiUrl + "files/download-file?documentId=" + documentId,
        method: "GET",
        headers: {
            "Content-type": "application/json; charset=utf-8",
            "Authorization": "Bearer " + $cookies.get("api_key")
        },
        responseType: "arraybuffer"  
        })
    .success( function(data, status, headers) {
        var filename = headers()['x-filename'];

        var blob = new Blob([data], { type: "application/octet-binary" });
        FileSaver.saveAs(blob, filename);
    })
    .error(function(data, status) {
        console.log("Request failed with status: " + status);
        errorCallback(data, status);
    });
};
};

Module dependency for FileUpload: angular-file-download (gulp install angular-file-download --save). Registration looks like below.

var app = angular.module('cool',
[
    ...
    require('angular-file-saver'),
])
. // other staff.

webpack is not recognized as a internal or external command,operable program or batch file

We also experienced this problem and I like all the answers that suggest using a script defined in package.json.

For our solutions we often use the following sequence:

  1. npm install --save-dev webpack-cli (if you're using webpack v4 or later, otherwise use npm install --save-dev webpack, see webpack installation, retrieved 19 Jan 2019)
  2. npx webpack

Step 1 is a one-off. Step 2 also checks ./node_modules/.bin. You can add the second step as a npm script to package.json as well, for example:

{
   ...
   "scripts": {
      ...
      "build": "npx webpack --mode development",
      ...
   },
   ...
}

and then use npm run build to execute this script.

Tested this solution with npm version 6.5.0, webpack version 4.28.4 and webpack-cli version 3.2.1 on Windows 10, executing all commands inside of a PowerShell window. My nodejs version is/was 10.14.2. I also tested this on Ubuntu Linux version 18.04.

I'd advise against installing webpack globally, in particular if you are working with a lot of different projects each of which may require a different version of webpack. Installing webpack globally locks you down to a particular version across all projects on the same machine.

How to convert an XML file to nice pandas dataframe?

You can also convert by creating a dictionary of elements and then directly converting to a data frame:

import xml.etree.ElementTree as ET
import pandas as pd

# Contents of test.xml
# <?xml version="1.0" encoding="utf-8"?> <tags>   <row Id="1" TagName="bayesian" Count="4699" ExcerptPostId="20258" WikiPostId="20257" />   <row Id="2" TagName="prior" Count="598" ExcerptPostId="62158" WikiPostId="62157" />   <row Id="3" TagName="elicitation" Count="10" />   <row Id="5" TagName="open-source" Count="16" /> </tags>

root = ET.parse('test.xml').getroot()

tags = {"tags":[]}
for elem in root:
    tag = {}
    tag["Id"] = elem.attrib['Id']
    tag["TagName"] = elem.attrib['TagName']
    tag["Count"] = elem.attrib['Count']
    tags["tags"]. append(tag)

df_users = pd.DataFrame(tags["tags"])
df_users.head()

How to remove list elements in a for loop in Python?

You are not permitted to remove elements from the list while iterating over it using a for loop.

The best way to rewrite the code depends on what it is you're trying to do.

For example, your code is equivalent to:

for item in a:
  print item
a[:] = []

Alternatively, you could use a while loop:

while a:
  print a.pop(0)

I'm trying to remove items if they match a condition. Then I go to next item.

You could copy every element that doesn't match the condition into a second list:

result = []
for item in a:
  if condition is False:
    result.append(item)
a = result

Alternatively, you could use filter or a list comprehension and assign the result back to a:

a = filter(lambda item:... , a)

or

a = [item for item in a if ...]

where ... stands for the condition that you need to check.

How is Pythons glob.glob ordered?

If you're wondering about what glob.glob has done on your system in the past and cannot add a sorted call, the ordering will be consistent on Mac HFS+ filesystems and will be traversal order on other Unix systems. So it will likely have been deterministic unless the underlying filesystem was reorganized which can happen if files were added, removed, renamed, deleted, moved, etc...

How to find the remainder of a division in C?

You can use the % operator to find the remainder of a division, and compare the result with 0.

Example:

if (number % divisor == 0)
{
    //code for perfect divisor
}
else
{
    //the number doesn't divide perfectly by divisor
}

Controlling Maven final name of jar artifact

This works for me

mvn jar:jar -Djar.finalName=custom-jar-name

Is there a way to add a gif to a Markdown file?

From the Markdown Cheatsheet:

You can add it to your repo and reference it with an image tag:

Inline-style: 
![alt text](https://github.com/adam-p/markdown-here/raw/master/src/common/images/icon48.png "Logo Title Text 1")

Reference-style: 
![alt text][logo]

[logo]: https://github.com/adam-p/markdown-here/raw/master/src/common/images/icon48.png "Logo Title Text 2"

Inline-style: alt text

Reference-style: alt text


Alternatively you can use the url directly:

![](http://www.reactiongifs.us/wp-content/uploads/2013/10/nuh_uh_conan_obrien.gif)

How to convert String into Hashmap in java

String value = "{first_name = naresh,last_name = kumar,gender = male}"

Let's start

  1. Remove { and } from the String>>first_name = naresh,last_name = kumar,gender = male
  2. Split the String from ,>> array of 3 element
  3. Now you have an array with 3 element
  4. Iterate the array and split each element by =
  5. Create a Map<String,String> put each part separated by =. first part as Key and second part as Value

Installation of SQL Server Business Intelligence Development Studio

http://msdn.microsoft.com/en-us/library/ms173767.aspx

Business Intelligence Development Studio is Microsoft Visual Studio 2008 with additional project types that are specific to SQL Server business intelligence. Business Intelligence Development Studio is the primary environment that you will use to develop business solutions that include Analysis Services, Integration Services, and Reporting Services projects. Each project type supplies templates for creating the objects required for business intelligence solutions, and provides a variety of designers, tools, and wizards to work with the objects.

If you already have Visual Studio installed, the new project types will be installed along with SQL Server.

More Information

Set default option in mat-select

I was able to set the default value or whatever value using the following:

Template:
          <mat-form-field>
              <mat-label>Holiday Destination</mat-label>
              <mat-select [(ngModel)]="selectedCity" formControlName="cityHoliday">
                <mat-option [value]="nyc">New York</mat-option>
                <mat-option [value]="london">London</mat-option>
                <mat-option [value]="india">Delhi</mat-option>
                <mat-option [value]="Oslo">Oslo</mat-option>
              </mat-select>
          </mat-form-field>

Component:

export class WhateverComponent implements OnInit{

selectedCity: string;    

}

ngOnInit() {
    this.selectedCity = 'london';
} 

}

How to find files recursively by file type and copy them to a directory while in ssh?

Something like this should work.

ssh [email protected] 'find -type f -name "*.pdf" -exec cp {} ./pdfsfolder \;'

Select count(*) from result query

select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)

should works

Fragments onResume from back stack

This is the correct answer you can call onResume() providing the fragment is attached to the activity. Alternatively you can use onAttach and onDetach

Proper use of const for defining functions in JavaScript

There are some very important benefits to the use of const and some would say it should be used wherever possible because of how deliberate and indicative it is.

It is, as far as I can tell, the most indicative and predictable declaration of variables in JavaScript, and one of the most useful, BECAUSE of how constrained it is. Why? Because it eliminates some possibilities available to var and let declarations.

What can you infer when you read a const? You know all of the following just by reading the const declaration statement, AND without scanning for other references to that variable:

  • the value is bound to that variable (although its underlying object is not deeply immutable)
  • it can’t be accessed outside of its immediately containing block
  • the binding is never accessed before declaration, because of Temporal Dead Zone (TDZ) rules.

The following quote is from an article arguing the benefits of let and const. It also more directly answers your question about the keyword's constraints/limits:

Constraints such as those offered by let and const are a powerful way of making code easier to understand. Try to accrue as many of these constraints as possible in the code you write. The more declarative constraints that limit what a piece of code could mean, the easier and faster it is for humans to read, parse, and understand a piece of code in the future.

Granted, there’s more rules to a const declaration than to a var declaration: block-scoped, TDZ, assign at declaration, no reassignment. Whereas var statements only signal function scoping. Rule-counting, however, doesn’t offer a lot of insight. It is better to weigh these rules in terms of complexity: does the rule add or subtract complexity? In the case of const, block scoping means a narrower scope than function scoping, TDZ means that we don’t need to scan the scope backwards from the declaration in order to spot usage before declaration, and assignment rules mean that the binding will always preserve the same reference.

The more constrained statements are, the simpler a piece of code becomes. As we add constraints to what a statement might mean, code becomes less unpredictable. This is one of the biggest reasons why statically typed programs are generally easier to read than dynamically typed ones. Static typing places a big constraint on the program writer, but it also places a big constraint on how the program can be interpreted, making its code easier to understand.

With these arguments in mind, it is recommended that you use const where possible, as it’s the statement that gives us the least possibilities to think about.

Source: https://ponyfoo.com/articles/var-let-const

combining two string variables

you need to take out the quotes:

soda = a + b

(You want to refer to the variables a and b, not the strings "a" and "b")

How to do something to each file in a directory with a batch script

Alternatively, use:

forfiles /s /m *.png /c "cmd /c echo @path"

The forfiles command is available in Windows Vista and up.

What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

As all of the other answers have already said, it's part of ES2015 arrow function syntax. More specifically, it's not an operator, it's a punctuator token that separates the parameters from the body: ArrowFunction : ArrowParameters => ConciseBody. E.g. (params) => { /* body */ }.

VBoxManage: error: Failed to create the host-only adapter

If you are on Linux:

sudo service virtualbox restart

Align Bootstrap Navigation to Center

Try this css

.clearfix:before, .clearfix:after, .container:before, .container:after, .container-fluid:before, .container-fluid:after, .row:before, .row:after, .form-horizontal .form-group:before, .form-horizontal .form-group:after, .btn-toolbar:before, .btn-toolbar:after, .btn-group-vertical > .btn-group:before, .btn-group-vertical > .btn-group:after, .nav:before, .nav:after, .navbar:before, .navbar:after, .navbar-header:before, .navbar-header:after, .navbar-collapse:before, .navbar-collapse:after, .pager:before, .pager:after, .panel-body:before, .panel-body:after, .modal-footer:before, .modal-footer:after {
    content: " ";
    display: table-cell;
}

ul.nav {
    float: none;
    margin-bottom: 0;
    margin-left: auto;
    margin-right: auto;
    margin-top: 0;
    width: 240px;
}

Convert a object into JSON in REST service by Spring MVC

You can always add the @Produces("application/json") above your web method or specify produces="application/json" to return json. Then on top of the Student class you can add @XmlRootElement from javax.xml.bind.annotation package.

Please note, it might not be a good idea to directly return model classes. Just a suggestion.

HTH.

Why do I need 'b' to encode a string with Base64?

If the string is Unicode the easiest way is:

import base64                                                        

a = base64.b64encode(bytes(u'complex string: ñáéíóúÑ', "utf-8"))

# a: b'Y29tcGxleCBzdHJpbmc6IMOxw6HDqcOtw7PDusOR'

b = base64.b64decode(a).decode("utf-8", "ignore")                    

print(b)
# b :complex string: ñáéíóúÑ

How to write a caption under an image?

For responsive images. You can add the picture and source tags within the figure tag.

<figure>
  <picture>
    <source media="(min-width: 750px)" srcset="images/image_2x.jpg"/>
    <source media="(min-width: 500px)" srcset="images/image.jpg" />
    <img src="images.jpg" alt="An image">
  </picture>
  <figcaption>Caption goes here</figcaption>
</figure>

How to insert pandas dataframe via mysqldb into database?

This should do the trick:

import pandas as pd
import pymysql
pymysql.install_as_MySQLdb()
from sqlalchemy import create_engine

# Create engine
engine = create_engine('mysql://USER_NAME_HERE:PASS_HERE@HOST_ADRESS_HERE/DB_NAME_HERE')

# Create the connection and close it(whether successed of failed)
with engine.begin() as connection:
  df.to_sql(name='INSERT_TABLE_NAME_HERE/INSERT_NEW_TABLE_NAME', con=connection, if_exists='append', index=False)

How to add conditional attribute in Angular 2?

null removes it:

[attr.checked]="value ? '' : null"

or

[attr.checked]="value ? 'checked' : null"

Hint:

Attribute vs property

When the HTML element where you add this binding does not have a property with the name used in the binding (checked in this case) and also no Angular component or directive is applied to the same element that has an @Input() checked;, then [xxx]="..." can not be used.

See also What is the difference between properties and attributes in HTML?

What to bind to when there is no such property

Alternatives are [style.xxx]="...", [attr.xxx]="...", [class.xxx]="..." depending on what you try to accomplish.

Because <input> only has a checked attribute, but no checked property [attr.checked]="..." is the right way for this specific case.

Attributes can only handle string values

A common pitfall is also that for [attr.xxx]="..." bindings the value (...) is always stringified. Only properties and @Input()s can receive other value types like boolean, number, object, ...

Most properties and attributes of elements are connected and have the same name.

Property-attribute connection

When bound to the attribute the property also only receives the stringified value from the attribute.
When bound to the property the property receives the value bound to it (boolean, number, object, ...) and the attribute again the stringified value.

Two cases where attribute and property names do not match.

Angular was changed since then and knows about these special cases and handles them so that you can bind to <label [for]=" even though no such property exists (same for colspan)

Get Line Number of certain phrase in file Python

for n,line in enumerate(open("file")):
    if "pattern" in line: print n+1

How can I interrupt a running code in R with a keyboard command?

Try out Ctrl + z But it will kill the process, not suspend it.

How do I get the current year using SQL on Oracle?

Use extract(datetime) function it's so easy, simple.

It returns year, month, day, minute, second

Example:

select extract(year from sysdate) from dual;

How to ensure that there is a delay before a service is started in systemd?

This answer on super user I think is a better answer. From https://superuser.com/a/573761/67952

"But since you asked for a way without using Before and After, you can use:

Type=idle

which as man systemd.service explains

Behavior of idle is very similar to simple; however, actual execution of the service program is delayed until all active jobs are dispatched. This may be used to avoid interleaving of output of shell services with the status output on the console. Note that this type is useful only to improve console output, it is not useful as a general unit ordering tool, and the effect of this service type is subject to a 5s time-out, after which the service program is invoked anyway. "

What is an unsigned char?

char and unsigned char aren't guaranteed to be 8-bit types on all platforms—they are guaranteed to be 8-bit or larger. Some platforms have 9-bit, 32-bit, or 64-bit bytes. However, the most common platforms today (Windows, Mac, Linux x86, etc.) have 8-bit bytes.

Disabling Chrome cache for website development

Using Ctrl+Shift+R to refresh was nice but didn't get everything I needed. still some things wouldn't refresh, such as data stored in js and css. found a solution: a toolbar of google for chrome web developers. After you install the toolbar select options and "reset page".

Case insensitive access for generic dictionary

Its not very elegant but in case you cant change the creation of dictionary, and all you need is a dirty hack, how about this:

var item = MyDictionary.Where(x => x.Key.ToLower() == MyIndex.ToLower()).FirstOrDefault();
    if (item != null)
    {
        TheValue = item.Value;
    }

Absolute position of an element on the screen using jQuery

See .offset() here in the jQuery doc. It gives the position relative to the document, not to the parent. You perhaps have .offset() and .position() confused. If you want the position in the window instead of the position in the document, you can subtract off the .scrollTop() and .scrollLeft() values to account for the scrolled position.

Here's an excerpt from the doc:

The .offset() method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent. When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop), .offset() is the more useful.

To combine these:

var offset = $("selector").offset();
var posY = offset.top - $(window).scrollTop();
var posX = offset.left - $(window).scrollLeft(); 

You can try it here (scroll to see the numbers change): http://jsfiddle.net/jfriend00/hxRPQ/

Python map object is not subscriptable

map() doesn't return a list, it returns a map object.

You need to call list(map) if you want it to be a list again.

Even better,

from itertools import imap
payIntList = list(imap(int, payList))

Won't take up a bunch of memory creating an intermediate object, it will just pass the ints out as it creates them.

Also, you can do if choice.lower() == 'n': so you don't have to do it twice.

Python supports +=: you can do payIntList[i] += 1000 and numElements += 1 if you want.

If you really want to be tricky:

from itertools import count
for numElements in count(1):
    payList.append(raw_input("Enter the pay amount: "))
    if raw_input("Do you wish to continue(y/n)?").lower() == 'n':
         break

and / or

for payInt in payIntList:
    payInt += 1000
    print payInt

Also, four spaces is the standard indent amount in Python.

Eclipse error "ADB server didn't ACK, failed to start daemon"

Command prompt (cmd.exe):

netstat -aon | findstr 5037

Find the process id of 0.0.0.0:

Enter image description here

Make sure it's adb.exe:

tasklist | findstr 1980

Enter image description here

Kill this process:

taskkill /f /t /im adb.exe

Enter image description here

Get ADB back to normal:

Enter image description here

Credit: blog post *Android ADB server didn't ACK failed to start daemon*

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

This is a typical bidirectional consistency problem. It is well discussed in this link as well as this link.

As per the articles in the previous 2 links you need to fix your setters in both sides of the bidirectional relationship. An example setter for the One side is in this link.

An example setter for the Many side is in this link.

After you correct your setters you want to declare the Entity access type to be "Property". Best practice to declare "Property" access type is to move ALL the annotations from the member properties to the corresponding getters. A big word of caution is not to mix "Field" and "Property" access types within the entity class otherwise the behavior is undefined by the JSR-317 specifications.

How to access parent scope from within a custom directive *with own scope* in AngularJS?

 scope: false
 transclude: false

and you will have the same scope(with parent element)

$scope.$watch(...

There are a lot of ways how to access parent scope depending on this two options scope& transclude.

How can I concatenate a string within a loop in JSTL/JSP?

Is JSTL's join(), what you searched for?

<c:set var="myVar" value="${fn:join(myParams.items, ' ')}" />

Visual Studio window which shows list of methods

Do you mean the class view window (View->Class View, or Ctrl+W,C)?

You also have the intellisence popup-window

Parse date without timezone javascript

I have the same issue. I get a date as a String, for example: '2016-08-25T00:00:00', but I need to have Date object with correct time. To convert String into object, I use getTimezoneOffset:

var date = new Date('2016-08-25T00:00:00')
var userTimezoneOffset = date.getTimezoneOffset() * 60000;
new Date(date.getTime() - userTimezoneOffset);

getTimezoneOffset() will return ether negative or positive value. This must be subtracted to work in every location in world.

linking jquery in html

<script
 src="CDN">
</script>

for change the CDN check this website.

the first one is JQuery

How to set timeout for a line of c# code

I use something like this (you should add code to deal with the various fails):

    var response = RunTaskWithTimeout<ReturnType>(
        (Func<ReturnType>)delegate { return SomeMethod(someInput); }, 30);


    /// <summary>
    /// Generic method to run a task on a background thread with a specific timeout, if the task fails,
    /// notifies a user
    /// </summary>
    /// <typeparam name="T">Return type of function</typeparam>
    /// <param name="TaskAction">Function delegate for task to perform</param>
    /// <param name="TimeoutSeconds">Time to allow before task times out</param>
    /// <returns></returns>
    private T RunTaskWithTimeout<T>(Func<T> TaskAction, int TimeoutSeconds)
    {
        Task<T> backgroundTask;

        try
        {
            backgroundTask = Task.Factory.StartNew(TaskAction);
            backgroundTask.Wait(new TimeSpan(0, 0, TimeoutSeconds));
        }
        catch (AggregateException ex)
        {
            // task failed
            var failMessage = ex.Flatten().InnerException.Message);
            return default(T);
        }
        catch (Exception ex)
        {
            // task failed
            var failMessage = ex.Message;
            return default(T);
        }

        if (!backgroundTask.IsCompleted)
        {
            // task timed out
            return default(T);
        }

        // task succeeded
        return backgroundTask.Result;
    }

Powershell script to check if service is started, if not then start it

I think you may have over-complicated your code: If you are just checking to see if a service is running and, if not, run it and then stop re-evaluating, the following should suffice:

Good point on the refresh.

$ServiceName = 'Serenade'
$arrService = Get-Service -Name $ServiceName

while ($arrService.Status -ne 'Running')
{

    Start-Service $ServiceName
    write-host $arrService.status
    write-host 'Service starting'
    Start-Sleep -seconds 60
    $arrService.Refresh()
    if ($arrService.Status -eq 'Running')
    {
        Write-Host 'Service is now Running'
    }

}

svn : how to create a branch from certain revision of trunk

Try below one:

svn copy http://svn.example.com/repos/calc/trunk@rev-no 
       http://svn.example.com/repos/calc/branches/my-calc-branch 
  -m "Creating a private branch of /calc/trunk."  --parents

No slash "\" between the svn URLs.

Create a List of primitive int?

In Java the type of any variable is either a primitive type or a reference type. Generic type arguments must be reference types. Since primitives do not extend Object they cannot be used as generic type arguments for a parametrized type.

Instead use the Integer class which is a wrapper for int:

List<Integer> list = new ArrayList<Integer>();

If your using Java 7 you can simplify this declaration using the diamond operator:

List<Integer> list = new ArrayList<>();

With autoboxing in Java the primitive type int will become an Integer when necessary.

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.

So the following is valid:

int myInt = 1;
List<Integer> list = new ArrayList<Integer>();
list.add(myInt);

System.out.println(list.get(0)); //prints 1

deleting rows in numpy array

The simplest way to delete rows and columns from arrays is the numpy.delete method.

Suppose I have the following array x:

x = array([[1,2,3],
        [4,5,6],
        [7,8,9]])

To delete the first row, do this:

x = numpy.delete(x, (0), axis=0)

To delete the third column, do this:

x = numpy.delete(x,(2), axis=1)

So you could find the indices of the rows which have a 0 in them, put them in a list or a tuple and pass this as the second argument of the function.

jQuery get values of checked checkboxes into array

Needed the form elements named in the HTML as an array to be an array in the javascript object, as if the form was actually submitted.

If there is a form with multiple checkboxes such as:

<input name='breath[0]' type='checkbox' value='presence0'/>
<input name='breath[1]' type='checkbox' value='presence1'/>
<input name='breath[2]' type='checkbox' value='presence2'/>
<input name='serenity'  type='text' value='Is within the breath.'/>
...

The result is an object with:

data = {
   'breath':['presence0','presence1','presence2'],
   'serenity':'Is within the breath.'
}


var $form = $(this),
    data  = {};

$form.find("input").map(function()
{
    var $el  = $(this),
        name = $el.attr("name");

    if (/radio|checkbox/i.test($el.attr('type')) && !$el.prop('checked'))return;

    if(name.indexOf('[') > -1)
    {
        var name_ar = name.split(']').join('').split('['),
            name    = name_ar[0],
            index   = name_ar[1];

        data[name]  = data[name] || [];
        data[name][index] = $el.val();
    }
    else data[name] = $el.val();
});

And there are tons of answers here which helped improve my code, but they were either too complex or didn't do exactly want I wanted: Convert form data to JavaScript object with jQuery

Works but can be improved: only works on one-dimensional arrays and the resulting indexes may not be sequential. The length property of an array returns the next index number as the length of the array, not the actually length.

Hope this helped. Namaste!

How can I one hot encode in Python?

pandas as has inbuilt function "get_dummies" to get one hot encoding of that particular column/s.

one line code for one-hot-encoding:

df=pd.concat([df,pd.get_dummies(df['column name'],prefix='column name')],axis=1).drop(['column name'],axis=1)

Stopword removal with NLTK

There is an in-built stopword list in NLTK made up of 2,400 stopwords for 11 languages (Porter et al), see http://nltk.org/book/ch02.html

>>> from nltk import word_tokenize
>>> from nltk.corpus import stopwords
>>> stop = set(stopwords.words('english'))
>>> sentence = "this is a foo bar sentence"
>>> print([i for i in sentence.lower().split() if i not in stop])
['foo', 'bar', 'sentence']
>>> [i for i in word_tokenize(sentence.lower()) if i not in stop] 
['foo', 'bar', 'sentence']

I recommend looking at using tf-idf to remove stopwords, see Effects of Stemming on the term frequency?

C++ - struct vs. class

POD classes are Plain-Old data classes that have only data members and nothing else. There are a few questions on stackoverflow about the same. Find one here.

Also, you can have functions as members of structs in C++ but not in C. You need to have pointers to functions as members in structs in C.

read subprocess stdout line by line

A function that allows iterating over both stdout and stderr concurrently, in realtime, line by line

In case you need to get the output stream for both stdout and stderr at the same time, you can use the following function.

The function uses Queues to merge both Popen pipes into a single iterator.

Here we create the function read_popen_pipes():

from queue import Queue, Empty
from concurrent.futures import ThreadPoolExecutor


def enqueue_output(file, queue):
    for line in iter(file.readline, ''):
        queue.put(line)
    file.close()


def read_popen_pipes(p):

    with ThreadPoolExecutor(2) as pool:
        q_stdout, q_stderr = Queue(), Queue()

        pool.submit(enqueue_output, p.stdout, q_stdout)
        pool.submit(enqueue_output, p.stderr, q_stderr)

        while True:

            if p.poll() is not None and q_stdout.empty() and q_stderr.empty():
                break

            out_line = err_line = ''

            try:
                out_line = q_stdout.get_nowait()
            except Empty:
                pass
            try:
                err_line = q_stderr.get_nowait()
            except Empty:
                pass

            yield (out_line, err_line)

read_popen_pipes() in use:

import subprocess as sp


with sp.Popen(my_cmd, stdout=sp.PIPE, stderr=sp.PIPE, text=True) as p:

    for out_line, err_line in read_popen_pipes(p):

        # Do stuff with each line, e.g.:
        print(out_line, end='')
        print(err_line, end='')

    return p.poll() # return status-code

How do I commit only some files?

If you have already staged files, simply unstage them:

git reset HEAD [file-name-A.ext] [file-name-B.ext]

Then add them bit by bit back in.

How to get Rails.logger printing to the console/stdout when running rspec?

You can define a method in spec_helper.rb that sends a message both to Rails.logger.info and to puts and use that for debugging:

def log_test(message)
    Rails.logger.info(message)
    puts message
end

Format number as percent in MS SQL Server

SELECT cast( cast(round(37.0/38.0,2) AS DECIMAL(18,2)) as varchar(100)) + ' %'

RESULT:  0.97 %

Formatting a double to two decimal places

Since you are working in currency why not simply do this:

Console.Writeline("Earnings this week: {0:c}", answer);

This will format answer as currency, so on my machine (UK) it will come out as:

Earnings this week: £209.00

How do I get bootstrap-datepicker to work with Bootstrap 3?

For anyone else who runs into this...

Version 1.2.0 of this plugin (current as of this post) doesn't quite work in all cases as documented with Bootstrap 3.0, but it does with a minor workaround.

Specifically, if using an input with icon, the HTML markup is of course slightly different as class names have changed:

<div class="input-group" data-datepicker="true">
    <input name="date" type="text" class="form-control" />
    <span class="input-group-addon"><i class="icon-calendar"></i></span>
</div>

It seems because of this, you need to use a selector that points directly to the input element itself NOT the parent container (which is what the auto generated HTML on the demo page suggests).

$('*[data-datepicker="true"] input[type="text"]').datepicker({
    todayBtn: true,
    orientation: "top left",
    autoclose: true,
    todayHighlight: true
});

Having done this you will probably also want to add a listener for clicking/tapping on the icon so it sets focus on the text input when clicked (which is the behaviour when using this plugin with TB 2.x by default).

$(document).on('touch click', '*[data-datepicker="true"] .input-group-addon', function(e){
    $('input[type="text"]', $(this).parent()).focus();
});

NB: I just use a data-datepicker boolean attribute because the class name 'datepicker' is reserved by the plugin and I already use 'date' for styling elements.

Get a list of resources from classpath directory

So in terms of the PathMatchingResourcePatternResolver this is what is needed in the code:

@Autowired
ResourcePatternResolver resourceResolver;

public void getResources() {
  resourceResolver.getResources("classpath:config/*.xml");
}

Security of REST authentication schemes

A previous answer only mentioned SSL in the context of data transfer and didn't actually cover authentication.

You're really asking about securely authenticating REST API clients. Unless you're using TLS client authentication, SSL alone is NOT a viable authentication mechanism for a REST API. SSL without client authc only authenticates the server, which is irrelevant for most REST APIs because you really want to authenticate the client.

If you don't use TLS client authentication, you'll need to use something like a digest-based authentication scheme (like Amazon Web Service's custom scheme) or OAuth 1.0a or even HTTP Basic authentication (but over SSL only).

These schemes authenticate that the request was sent by someone expected. TLS (SSL) (without client authentication) ensures that the data sent over the wire remains untampered. They are separate - but complementary - concerns.

For those interested, I've expanded on an SO question about HTTP Authentication Schemes and how they work.

How to call servlet through a JSP page

Why would you want to do this? You shouldn't be executing controller code in the view, and most certainly shouldn't be trying to pull code inside of another servlet into the view either.

Do all of your processing and refactoring of the application first, then just pass off the results to a view. Make the view as dumb as possible and you won't even run into these problems.

If this kind of design is hard for you, try Freemarker or even something like Velocity (although I don't recommend it) to FORCE you to do this. You never have to do this sort of thing ever.

To put it more accurately, the problem you are trying to solve is just a symptom of a greater problem - your architecture/design of your servlets.

Why do I always get the same sequence of random numbers with rand()?

None of you guys are answering his question.

with this code i get the same sequance everytime the code but it generates random sequences if i add srand(/somevalue/) before the for loop . can someone explain why ?

From what my professor has told me, it is used if you want to make sure your code is running properly and to see if there is something wrong or if you can change something.

Change font size of UISegmentedControl

I ran into the same issue. This code sets the font size for the entire segmented control. Something similar might work for setting the font type. Note that this is only available for iOS5+

Obj C:

UIFont *font = [UIFont boldSystemFontOfSize:12.0f];
NSDictionary *attributes = [NSDictionary dictionaryWithObject:font
                                                       forKey:NSFontAttributeName];
[segmentedControl setTitleTextAttributes:attributes 
                                forState:UIControlStateNormal];

EDIT: UITextAttributeFont has been deprecated - use NSFontAttributeName instead.

EDIT #2: For Swift 4 NSFontAttributeName has been changed to NSAttributedStringKey.font.

Swift 5:

let font = UIFont.systemFont(ofSize: 16)
segmentedControl.setTitleTextAttributes([NSAttributedString.Key.font: font], for: .normal)

Swift 4:

let font = UIFont.systemFont(ofSize: 16)
segmentedControl.setTitleTextAttributes([NSAttributedStringKey.font: font],
                                        for: .normal)

Swift 3:

let font = UIFont.systemFont(ofSize: 16)
segmentedControl.setTitleTextAttributes([NSFontAttributeName: font],
                                        for: .normal)

Swift 2.2:

let font = UIFont.systemFontOfSize(16)
segmentedControl.setTitleTextAttributes([NSFontAttributeName: font], 
    forState: UIControlState.Normal)

Thanks to the Swift implementations from @audrey-gordeev

Get Date in YYYYMMDD format in windows batch file

If, after reading the other questions and viewing the links mentioned in the comment sections, you still can't figure it out, read on.

First of all, where you're going wrong is the offset.

It should look more like this...

set mydate=%date:~10,4%%date:~6,2%/%date:~4,2%
echo %mydate%

If the date was Tue 12/02/2013 then it would display it as 2013/02/12.

To remove the slashes, the code would look more like

set mydate=%date:~10,4%%date:~7,2%%date:~4,2%
echo %mydate%

which would output 20130212

And a hint for doing it in the future, if mydate equals something like %date:~10,4%%date:~7,2% or the like, you probably forgot a tilde (~).

Get age from Birthdate

function getAge(birthday) {
    var today = new Date();
    var thisYear = 0;
    if (today.getMonth() < birthday.getMonth()) {
        thisYear = 1;
    } else if ((today.getMonth() == birthday.getMonth()) && today.getDate() < birthday.getDate()) {
        thisYear = 1;
    }
    var age = today.getFullYear() - birthday.getFullYear() - thisYear;
    return age;
}

JSFiddle

Insert new item in array on any position in PHP

A function that can insert at both integer and string positions:

/**
 * @param array      $array
 * @param int|string $position
 * @param mixed      $insert
 */
function array_insert(&$array, $position, $insert)
{
    if (is_int($position)) {
        array_splice($array, $position, 0, $insert);
    } else {
        $pos   = array_search($position, array_keys($array));
        $array = array_merge(
            array_slice($array, 0, $pos),
            $insert,
            array_slice($array, $pos)
        );
    }
}

Integer usage:

$arr = ["one", "two", "three"];
array_insert(
    $arr,
    1,
    "one-half"
);
// ->
array (
  0 => 'one',
  1 => 'one-half',
  2 => 'two',
  3 => 'three',
)

String Usage:

$arr = [
    "name"  => [
        "type"      => "string",
        "maxlength" => "30",
    ],
    "email" => [
        "type"      => "email",
        "maxlength" => "150",
    ],
];

array_insert(
    $arr,
    "email",
    [
        "phone" => [
            "type"   => "string",
            "format" => "phone",
        ],
    ]
);
// ->
array (
  'name' =>
  array (
    'type' => 'string',
    'maxlength' => '30',
  ),
  'phone' =>
  array (
    'type' => 'string',
    'format' => 'phone',
  ),
  'email' =>
  array (
    'type' => 'email',
    'maxlength' => '150',
  ),
)

Swift: Determine iOS Screen size

In Swift 3.0

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

In older swift: Do something like this:

let screenSize: CGRect = UIScreen.mainScreen().bounds

then you can access the width and height like this:

let screenWidth = screenSize.width
let screenHeight = screenSize.height

if you want 75% of your screen's width you can go:

let screenWidth = screenSize.width * 0.75

Swift 4.0

// Screen width.
public var screenWidth: CGFloat {
    return UIScreen.main.bounds.width
}

// Screen height.
public var screenHeight: CGFloat {
    return UIScreen.main.bounds.height
}

In Swift 5.0

let screenSize: CGRect = UIScreen.main.bounds

Express.js - app.listen vs server.listen

Express is basically a wrapper of http module that is created for the ease of the developers in such a way that..

  1. They can set up middlewares to respond to HTTP Requests (easily) using express.
  2. They can dynamically render HTML Pages based on passing arguments to templates using express.
  3. They can also define routing easily using express.

How can I check if mysql is installed on ubuntu?

Multiple ways of searching for the program.

Type mysql in your terminal, see the result.

Search the /usr/bin, /bin directories for the binary.

Type apt-cache show mysql to see if it is installed

locate mysql

Windows: XAMPP vs WampServer vs EasyPHP vs alternative

After years of using XAMPP finally I've given up, and started looking for alternatives. XAMPP has not received any updates for quite a while and it kept breaking down once every two weeks.

The one I've just found and I could absolutely recommend is The Uniform Server

It's really frequently updated, has much more emphasis on security and looks like a much more mature project compared to XAMPP.

They have a wiki where they list all the latest versions of packages. As the time of writing, their newest release is only 4 days old!

Versions in Uniform Server as of today:

  • Apache 2.4.2
  • MySQL 5.5.23-community
  • PHP 5.4.1
  • phpMyAdmin 3.5.0

Versions in XAMPP as of today:

  • Apache 2.2.21
  • MySQL 5.5.16
  • PHP 5.3.8
  • phpMyAdmin 3.4.5

Comparing boxed Long values 127 and 128

Comparing non-primitives (aka Objects) in Java with == compares their reference instead of their values. Long is a class and thus Long values are Objects.

The problem is that the Java Developers wanted people to use Long like they used long to provide compatibility, which led to the concept of autoboxing, which is essentially the feature, that long-values will be changed to Long-Objects and vice versa as needed. The behaviour of autoboxing is not exactly predictable all the time though, as it is not completely specified.

So to be safe and to have predictable results always use .equals() to compare objects and do not rely on autoboxing in this case:

Long num1 = 127, num2 = 127;
if(num1.equals(num2)) { iWillBeExecutedAlways(); }

Does Python SciPy need BLAS?

Try using

sudo apt-get install python3-scipy

ADB Shell Input Events

By the way, if you are trying to find a way to send double quotes to the device, try the following:

adb shell input text '\"'

I'm not sure why there's no event code for quotes, but this workaround does the job. Also, if you're using MonkeyDevice (or ChimpChat) you should test each caracter before invoking monkeyDevice.type, otherwise you get nothing when you try to send "

Use own username/password with git and bitbucket

I had to merge some of those good answers here! This works for me:

git remote set-url origin 'https://bitbucket.org/teamName/repo.git'

In the end, it will always prompt anyone who wants to pull from it

Java: how do I check if a Date is within a certain range?

  public class TestDate {

    public static void main(String[] args) {
    // TODO Auto-generated method stub

    String fromDate = "18-FEB-2018";
    String toDate = "20-FEB-2018";

    String requestDate = "19/02/2018";  
    System.out.println(checkBetween(requestDate,fromDate, toDate));
}

public static boolean checkBetween(String dateToCheck, String startDate, String endDate) {
    boolean res = false;
    SimpleDateFormat fmt1 = new SimpleDateFormat("dd-MMM-yyyy"); //22-05-2013
    SimpleDateFormat fmt2 = new SimpleDateFormat("dd/MM/yyyy"); //22-05-2013
    try {
     Date requestDate = fmt2.parse(dateToCheck);
     Date fromDate = fmt1.parse(startDate);
     Date toDate = fmt1.parse(endDate);
     res = requestDate.compareTo(fromDate) >= 0 && requestDate.compareTo(toDate) <=0;
    }catch(ParseException pex){
        pex.printStackTrace();
    }
    return res;
   }
 }

My Routes are Returning a 404, How can I Fix Them?

If you're using Vagrant though Homestead, it's possible there was an error mounting the shared folder. It looks like Vagrant takes your files from that folder and swaps out the files that are actually on the host machine on boot, so if there was an error, you're essentially trying to access your Laravel installation from when you first made it (which is why you're only getting "home"- that was generated during installation).

You can easily check this by sshing into your vm and checking the routes/web.php file to see if it's actually your file. If it isn't, exit out and vagrant halt, vagrant up, and look for errors on boot.

PHP, Get tomorrows date from date

$date = '2013-01-22';
$time = strtotime($date) + 86400;
echo date('Y-m-d', $time);

Where 86400 is the # of seconds in a day.

Create a new txt file using VB.NET

Here is a single line that will create (or overwrite) the file:

File.Create("C:\my files\2010\SomeFileName.txt").Dispose()

Note: calling Dispose() ensures that the reference to the file is closed.

Javascript Get Element by Id and set the value

For each element type, you can use specific attribute to set value. E.g.:

<div id="theValue1"></div>
window.document.getElementById("theValue1").innerText = "value div";

<input id="theValue2"></input>
window.document.getElementById("theValue2").value = "value input";

You can try example here!

Impact of Xcode build options "Enable bitcode" Yes/No

Bitcode makes crash reporting harder. Here is a quote from HockeyApp (which also true for any other crash reporting solutions):

When uploading an app to the App Store and leaving the "Bitcode" checkbox enabled, Apple will use that Bitcode build and re-compile it on their end before distributing it to devices. This will result in the binary getting a new UUID and there is an option to download a corresponding dSYM through Xcode.

Note: the answer was edited on Jan 2016 to reflect most recent changes

How to enable PHP short tags?

Set the asp_tags = On and short_open_tag = On in both the files \apache\Apache2.2.21\bin\php.ini and \bin\php\php5.3.8\php.ini and then restart the apache server.

How to npm install to a specified directory?

As of npm version 3.8.6, you can use

npm install --prefix ./install/here <package>

to install in the specified directory. NPM automatically creates node_modules folder even when a node_modules directory already exists in the higher up hierarchy. You can also have a package.json in the current directory and then install it in the specified directory using --prefix option:

npm install --prefix ./install/here

As of npm 6.0.0, you can use

npm install --prefix ./install/here ./

to install the package.json in current directory to "./install/here" directory. There is one thing that I have noticed on Mac that it creates a symlink to parent folder inside the node_modules directory. But, it still works.

NOTE: NPM honours the path that you've specified through the --prefix option. It resolves as per npm documentation on folders, only when npm install is used without the --prefix option.

ImportError: No module named PyQt4.QtCore

I had the "No module named PyQt4.QtCore" error and installing the python-qt4 package fixed it only partially: I could run

from PyQt4.QtCore import SIGNAL

from a python interpreter but only without activating my virtualenv.

The only solution I've found till now to use a virtualenv is to copy the PyQt4 folder and the sip.so file into my virtualenv as explained here: Is it possible to add PyQt4/PySide packages on a Virtualenv sandbox?

How to hide the border for specified rows of a table?

Use the CSS property border on the <td>s following the <tr>s you do not want to have the border.

In my example I made a class noBorder that I gave to one <tr>. Then I use a simple selector tr.noBorder td to make the border go away for all the <td>s that are inside of <tr>s with the noBorder class by assigning border: 0.

Note that you do not need to provide the unit (i.e. px) if you set something to 0 as it does not matter anyway. Zero is just zero.

_x000D_
_x000D_
table, tr, td {_x000D_
  border: 3px solid red;_x000D_
}_x000D_
tr.noBorder td {_x000D_
  border: 0;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>A1</td>_x000D_
    <td>B1</td>_x000D_
    <td>C1</td>_x000D_
  </tr>_x000D_
  <tr class="noBorder">_x000D_
    <td>A2</td>_x000D_
    <td>B2</td>_x000D_
    <td>C2</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>A3</td>_x000D_
    <td>A3</td>_x000D_
    <td>A3</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Here's the output as an image:

Output from HTML

How to save and load numpy.array() data properly?

np.fromfile() has a sep= keyword argument:

Separator between items if file is a text file. Empty (“”) separator means the file should be treated as binary. Spaces (” ”) in the separator match zero or more whitespace characters. A separator consisting only of spaces must match at least one whitespace.

The default value of sep="" means that np.fromfile() tries to read it as a binary file rather than a space-separated text file, so you get nonsense values back. If you use np.fromfile('markers.txt', sep=" ") you will get the result you are looking for.

However, as others have pointed out, np.loadtxt() is the preferred way to convert text files to numpy arrays, and unless the file needs to be human-readable it is usually better to use binary formats instead (e.g. np.load()/np.save()).

Most popular screen sizes/resolutions on Android phones

Another alternative to see popular android resolutions or aspect ratios is Unity statistics:

LATEST UNITY STATISTICS (on 2019.06 return http503) web arhive

Top on 2017-01:

Display Resolutions:

  • 1280 x 720: 28.9%
  • 1920 x 1080: 21.4%
  • 800 x 480: 10.3%
  • 854 x 480: 9.7%
  • 960 x 540: 8.9%
  • 1024 x 600: 7.8%
  • 1280 x 800: 5.0%
  • 2560 x 1440: 2.4%
  • 480 x 320: 1.2%
  • 1920 x 1200: 0.8%
  • 1024 x 768: 0.8%

Display Aspect Ratios:

  • 16:9: 72.4%
  • 5:3: 18.2%
  • 16:10: 6.2%
  • 4:3: 1.7%
  • 3:2: 1.2%
  • 5:4: 0.1%

Exit a Script On Error

exit 1 is all you need. The 1 is a return code, so you can change it if you want, say, 1 to mean a successful run and -1 to mean a failure or something like that.

CSS-moving text from left to right

Somehow I got it to work by using margin-right, and setting it to move from right to left. http://jsfiddle.net/gXdMc/

Don't know why for this case, margin-right 100% doesn't go off the screen. :D (tested on chrome 18)

EDIT: now left to right works too http://jsfiddle.net/6LhvL/

'was not declared in this scope' error

Here

{int y=((year-1)%100);int c=(year-1)/100;}

you declare and initialize the variables y, c, but you don't used them at all before they run out of scope. That's why you get the unused message.

Later in the function, y, c are undeclared, because the declarations you made only hold inside the block they were made in (the block between the braces {...}).

Using number as "index" (JSON)

Probably you need an array?

var Game = {

    status: [
        ["val", "val","val"],
        ["val", "val", "val"]
    ]
}

alert(Game.status[0][0]);

Why did I get the compile error "Use of unassigned local variable"?

Local variables are not automatically initialized. That only happens with instance-level variables.

You need to explicitly initialize local variables if you want them to be initialized. In this case, (as the linked documentation explains) either by setting the value of 0 or using the new operator.

The code you've shown does indeed attempt to use the value of the variable tmpCnt before it is initialized to anything, and the compiler rightly warns about it.

Getting results between two dates in PostgreSQL

To have a query working in any locale settings, consider formatting the date yourself:

SELECT * 
  FROM testbed 
 WHERE start_date >= to_date('2012-01-01','YYYY-MM-DD')
   AND end_date <= to_date('2012-04-13','YYYY-MM-DD');

How to create an empty file with Ansible?

The documentation of the file module says

If state=file, the file will NOT be created if it does not exist, see the copy or template module if you want that behavior.

So we use the copy module, using force=no to create a new empty file only when the file does not yet exist (if the file exists, its content is preserved).

- name: ensure file exists
  copy:
    content: ""
    dest: /etc/nologin
    force: no
    group: sys
    owner: root
    mode: 0555

This is a declarative and elegant solution.

Installation failed with message Invalid File

follow some steps:

Clean Project
Rebuild Project
Invalidate Caches / Restart

Now run your project. Hope it will work.

It's work for me.

Step-by-step debugging with IPython

You can start IPython session from pudb and go back to the debugging session as you like.

BTW, ipdb is using IPython behind the scenes and you can actually use IPython functionality such as TAB completion and magic commands (the one starts with %). If you are OK with ipdb you can start it from IPython using commands such as %run and %debug. ipdb session is actually better than plain IPython one in the sense you can go up and down in the stack trace etc. What is missing in ipdb for "object inspection"?

Also, python.el bundled with Emacs >= 24.3 has nice ipdb support.

Convert date to day name e.g. Mon, Tue, Wed

echo date('D', strtotime($date));
echo date('l', strtotime($date));

Result

Tue
Tuesday

How to randomly select rows in SQL?

SELECT TOP 5 Id, Name FROM customerNames ORDER BY NEWID()

lists and arrays in VBA

You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.

Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String

'Assign data to first item in array
compArray(1) = "asdf"

'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"

'Prints "ErrorState"
Debug.Print Computers("Computer Name")

Collections cannot be sorted so if you need to sort data you will probably want to use an array.

Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx

Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx

Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!

Edit:

Sub ArrayExample()
    Dim subject As String
    Dim TestArray() As String
    Dim counter As Long

    subject = "Example"
    counter = Len(subject)

    ReDim TestArray(1 To counter) As String

    For counter = 1 To Len(subject)
        TestArray(counter) = Right(Left(subject, counter), 1)
    Next
End Sub

CSS - Overflow: Scroll; - Always show vertical scroll bar?

Try the following code to display scroll bar always on your page,

::-webkit-scrollbar {
  -webkit-appearance: none;
  width: 10px;
}

::-webkit-scrollbar-thumb {
  border-radius: 5px;
  background-color: rgba(0,0,0,.5);
  -webkit-box-shadow: 0 0 1px rgba(255,255,255,.5);
}

this will always show the vertical and horizontal scroll bar on your page. If you need only a vertical scroll bar then put overflow-x: hidden

Android: ScrollView vs NestedScrollView

Other than the advantages listed in the answers given, one more advantage of NestedScrollView over ScrollView is its compatibility with CoordinatorLayout. The ScrollView does not cooperate with the CoordinatorLayout. You have to use NestedScrollView to get "scroll off-screen" behaviour for the toolbar.

Toolbar will not collapse with Scrollview as child of CoordinatorLayout

iPad Safari scrolling causes HTML elements to disappear and reappear with a delay

I faced this problem in a Framework7 & Cordova project. I tried all the solutions above. They did not solve my problem.

In my case, I was using 10+ css animations on the same page with infinite rotation (transform). I had to remove the animations. It is ok now with the lack of some visual features.

If the solutions above do not help you, you may start eliminating some animations.