Programs & Examples On #Msgsend

How to use HTTP GET in PowerShell?

Downloading Wget is not necessary; the .NET Framework has web client classes built in.

$wc = New-Object system.Net.WebClient;
$sms = Read-Host "Enter SMS text";
$sms = [System.Web.HttpUtility]::UrlEncode($sms);
$smsResult = $wc.downloadString("http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$sms&encoding=windows-1255")

Getting time and date from timestamp with php

You can try this:

For Date:

$date = new DateTime($from_date);
$date = $date->format('d-m-Y');

For Time:

$time = new DateTime($from_date);
$time = $time->format('H:i:s');

No Android SDK found - Android Studio

I just encountered and solve a similar problem.

First you should check the directory like other threads described. Then you can check whether the Build tool version matches your SDK version.

(e.g. for my project, in build.gradle file, you have:)

android { compileSdkVersion 21 buildToolsVersion "21.1.1" }

and then open you SDK manager, make sure you have the same version of sdk(21.1.1) installed in the selected directoriy:

If not, install it and restart Android Studio. It works for me.

I've also seen other guys saying run Android Studio as administrator would also help:

https://teamtreehouse.com/forum/i-am-getting-this-warning-message-rendering-problems-no-android-sdk-found-please-configure-an-android-sdk

PowerShell script to check the status of a URL

$request = [System.Net.WebRequest]::Create('http://stackoverflow.com/questions/20259251/powershell-script-to-check-the-status-of-a-url')

$response = $request.GetResponse()

$response.StatusCode

$response.Close()

How to read file from relative path in Java project? java.io.File cannot find the path specified

enter image description here

Assuming you want to read from resources directory in FileSystem class.

String file = "dummy.txt";
var path = Paths.get("src/com/company/fs/resources/", file);
System.out.println(path);

System.out.println(Files.readString(path));

Note: Leading . is not needed.

Plotting a fast Fourier transform in Python

I've built a function that deals with plotting FFT of real signals. The extra bonus in my function relative to the previous answers is that you get the actual amplitude of the signal.

Also, because of the assumption of a real signal, the FFT is symmetric, so we can plot only the positive side of the x-axis:

import matplotlib.pyplot as plt
import numpy as np
import warnings


def fftPlot(sig, dt=None, plot=True):
    # Here it's assumes analytic signal (real signal...) - so only half of the axis is required

    if dt is None:
        dt = 1
        t = np.arange(0, sig.shape[-1])
        xLabel = 'samples'
    else:
        t = np.arange(0, sig.shape[-1]) * dt
        xLabel = 'freq [Hz]'

    if sig.shape[0] % 2 != 0:
        warnings.warn("signal preferred to be even in size, autoFixing it...")
        t = t[0:-1]
        sig = sig[0:-1]

    sigFFT = np.fft.fft(sig) / t.shape[0]  # Divided by size t for coherent magnitude

    freq = np.fft.fftfreq(t.shape[0], d=dt)

    # Plot analytic signal - right half of frequence axis needed only...
    firstNegInd = np.argmax(freq < 0)
    freqAxisPos = freq[0:firstNegInd]
    sigFFTPos = 2 * sigFFT[0:firstNegInd]  # *2 because of magnitude of analytic signal

    if plot:
        plt.figure()
        plt.plot(freqAxisPos, np.abs(sigFFTPos))
        plt.xlabel(xLabel)
        plt.ylabel('mag')
        plt.title('Analytic FFT plot')
        plt.show()

    return sigFFTPos, freqAxisPos


if __name__ == "__main__":
    dt = 1 / 1000

    # Build a signal within Nyquist - the result will be the positive FFT with actual magnitude
    f0 = 200  # [Hz]
    t = np.arange(0, 1 + dt, dt)
    sig = 1 * np.sin(2 * np.pi * f0 * t) + \
        10 * np.sin(2 * np.pi * f0 / 2 * t) + \
        3 * np.sin(2 * np.pi * f0 / 4 * t) +\
        7.5 * np.sin(2 * np.pi * f0 / 5 * t)

    # Result in frequencies
    fftPlot(sig, dt=dt)
    # Result in samples (if the frequencies axis is unknown)
    fftPlot(sig)

Analytic FFT plot result

How to generate Class Diagram (UML) on Android Studio (IntelliJ Idea)

I have managed to to do it in a way. Perform all the steps as referenced by Michal Rowicki above.

  1. Open Visual Paradigm software.
  2. Create a new Project
  3. There would be an option on the Tools bar above that states Code and select Instant Reverse... from the drop down menu with Java language(or other)
  4. Select your application folder where your project is located and add it to the project(i have selected the complete folder application)
  5. The application should now appear on the left pane in Class Repository
  6. Then all you do is right click the project that you have added and select Reverse to new class diagram
  7. Select either you wish to have the packages included in the class diagram or just the class diagram of the project

Then it should appear on your screen and customize it as you wish

However i do not know if the plugin in Android Studio was necessary nevertheless it has worked in a way for me.

The condition has length > 1 and only the first element will be used

Like sgibb said it was an if problem, it had nothing to do with | or ||.

Here is another way to solve your problem:

for (i in 1:nrow(trip)) {
  if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='T'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='A') {
    trip[i, 'mutType'] <- "G:C to T:A"
  }
  else if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='C'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='G') {
    trip[i, 'mutType'] <- "G:C to C:G"
  }
  else if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='A'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='T') {
    trip[i, 'mutType'] <- "G:C to A:T"
  }
  else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='T'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='A') {
    trip[i, 'mutType'] <- "A:T to T:A"
  }
  else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='G'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='C') {
    trip[i, 'mutType'] <- "A:T to G:C"
  }
  else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='C'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='G') {
    trip[i, 'mutType'] <- "A:T to C:G"
  }
}

How to use Greek symbols in ggplot2?

You do not need the latex2exp package to do what you wanted to do. The following code would do the trick.

ggplot(smr, aes(Fuel.Rate, Eng.Speed.Ave., color=Eng.Speed.Max.)) + 
  geom_point() + 
  labs(title=expression("Fuel Efficiency"~(alpha*Omega)), 
color=expression(alpha*Omega), x=expression(Delta~price))

enter image description here

Also, some comments (unanswered as of this point) asked about putting an asterisk (*) after a Greek letter. expression(alpha~"*") works, so I suggest giving it a try.

More comments asked about getting ? Price and I find the most straightforward way to achieve that is expression(Delta~price)). If you need to add something before the Greek letter, you can also do this: expression(Indicative~Delta~price) which gets you:

enter image description here

How do I access previous promise results in a .then() chain?

I am not going to use this pattern in my own code since I'm not a big fan of using global variables. However, in a pinch it will work.

User is a promisified Mongoose model.

var globalVar = '';

User.findAsync({}).then(function(users){
  globalVar = users;
}).then(function(){
  console.log(globalVar);
});

Use CSS3 transitions with gradient backgrounds

As stated. Gradients aren't currently supported with CSS Transitions. But you could work around it in some cases by setting one of the colors to transparent, so that the background-color of some other wrapping element shines through, and transition that instead.

Postgresql - select something where date = "01/01/11"

I think you want to cast your dt to a date and fix the format of your date literal:

SELECT *
FROM table
WHERE dt::date = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD

Or the standard version:

SELECT *
FROM table
WHERE CAST(dt AS DATE) = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD

The extract function doesn't understand "date" and it returns a number.

How to detect if CMD is running as Administrator/has elevated privileges?

This trick only requires one command: type net session into the command prompt.

If you are NOT an admin, you get an access is denied message.

System error 5 has occurred.

Access is denied.

If you ARE an admin, you get a different message, the most common being:

There are no entries in the list.

From MS Technet:

Used without parameters, net session displays information about all sessions with the local computer.

Include another JSP file

At page translation time, the content of the file given in the include directive is ‘pasted’ as it is, in the place where the JSP include directive is used. Then the source JSP page is converted into a java servlet class. The included file can be a static resource or a JSP page. Generally, JSP include directive is used to include header banners and footers.

Syntax for include a jsp file:

<%@ include file="relative url">

Example

<%@include file="page_name.jsp" %>

Javascript counting number of objects in object

In recent browsers you can use:

Object.keys(obj.Data).length

See MDN

For older browsers, use the for-in loop in Michael Geary's answer.

Eclipse can't find / load main class

This worked for me finally : RUN -> RUN CONFIGURATIONS -> DELETE THE RUN CONFIGURATION CLOSE ECLIPSE REOPEN ECLIPSE CREATE RUN CONFIGURATION AGAIN.

Tadaaaa !! It works

Converting Array to List

Arrays.stream(ints).forEach(list::add);

This basically does 1 (iterate over the array) with 2 (using Java 8). (with 1 and 2 referring to your original question)

Asp.net - Add blank item at top of dropdownlist

After your databind:

drpList.Items.Insert(0, new ListItem(String.Empty, String.Empty));
drpList.SelectedIndex = 0;

No module named MySQLdb

...and remember there is no MySQLdb for python3.x

(I know the question is about python2.x but google rates this post quite high)


EDIT: As stated in the comments, there's a MySQLdb's fork that adds Python 3 support: github.com/PyMySQL/mysqlclient-python

HTML5 textarea placeholder not appearing

I had the same issue, only using a .pug file (similar to .jade). I realized that it was also a space issue, following the end of my closing parentheses. In my example, you need to highlight the text after (placeholder="YOUR MESSAGE") to see:

BEFORE:

form.form-horizontal(method='POST')
  .form-group
    textarea.form-control(placeholder="YOUR MESSAGE") 
  .form-group  
    button.btn.btn-primary(type='submit') SUBMIT

AFTER:

form.form-horizontal(method='POST')
  .form-group
    textarea.form-control(placeholder="YOUR MESSAGE")
  .form-group  
    button.btn.btn-primary(type='submit') SUBMIT

How to install an APK file on an Android phone?

If you dont have SDK or you are setting up 3rd party app here is another way:

  1. Copy the .APK file to your device.
  2. Use file manager to locate the file.
  3. Then click on it.
  4. Android App installer should be one of the options in pop-up.
  5. Select it and it installs.

MySQL Query to select data from last week?

SELECT id FROM table1
WHERE YEARWEEK(date) = YEARWEEK(NOW() - INTERVAL 1 WEEK)

I use the YEARWEEK function specifically to go back to the prior whole calendar week (as opposed to 7 days before today). YEARWEEK also allows a second argument that will set the start of the week or determine how the first/last week of the year are handled. YEARWEEK lets you to keep the number of weeks to go back/forward in a single variable, and will not include the same week number from prior/future years, and it's far shorter than most of the other answers on here.

LEFT JOIN only first row

@Matt Dodges answer put me on the right track. Thanks again for all the answers, which helped a lot of guys in the mean time. Got it working like this:

SELECT *
FROM feeds f
LEFT JOIN artists a ON a.artist_id = (
    SELECT artist_id
    FROM feeds_artists fa 
    WHERE fa.feed_id = f.id
    LIMIT 1
)
WHERE f.id = '13815'

How to set up a Web API controller for multipart/form-data

Perhaps it is late for the party. But there is an alternative solution for this is to use ApiMultipartFormFormatter plugin.

This plugin helps you to receive the multipart/formdata content as ASP.NET Core does.

In the github page, demo is already provided.

Forward declaring an enum in C++

Because the enum can be an integral size of varying size (the compiler decides which size a given enum has), the pointer to the enum can also have varying size, since it's an integral type (chars have pointers of a different size on some platforms for instance).

So the compiler can't even let you forward-declare the enum and user a pointer to it, because even there, it needs the size of the enum.

Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship

You will have to use the fluent API to do this.

Try adding the following to your DbContext:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{   
    modelBuilder.Entity<User>()
        .HasOptional(a => a.UserDetail)
        .WithOptionalDependent()
        .WillCascadeOnDelete(true);
}

How do I timestamp every ping result?

On macos you can do

ping --apple-time 127.0.0.1

The output looks like

16:07:11.315419 64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.064 ms
16:07:12.319933 64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.157 ms
16:07:13.322766 64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.066 ms
16:07:14.324649 64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.148 ms
16:07:15.328743 64 bytes from 127.0.0.1: icmp_seq=4 ttl=64 time=0.092 ms

How to open the second form?

If you need to show Form2 as a modal dialog, from within Form1 do:

var form2 = new Form2();
if (form2.ShowDialog() == DialogResult.OK) 
{
    // process results here
}

A modal dialog will retain focus while it is open; it will set the parent windows (Form1) "in the background" until it is closed, which is quite a common practice for settings windows.

How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

You can simply get it in the format you want.

String date = String.valueOf(android.text.format.DateFormat.format("dd-MM-yyyy", new java.util.Date()));

How to suppress Update Links warning?

(I don't have enough rep points to add a comment, but I want to add some clarity on the answers here)

Application.AskToUpdateLinks = False is probably not what you want.

If set to False, then MS Excel will attempt to update the links automatically it just won't prompt the user beforehand, sorta counter-intuitive.

The correct solution, if you're looking to open a file without updating links should be:

Workbook.Open(UpdateLinks:=0)

Related link: Difference in AskToUpdateLinks=False and UpdateLinks:=0

GET URL parameter in PHP

$Query_String  = explode("&", explode("?", $_SERVER['REQUEST_URI'])[1] );
var_dump($Query_String)

Array ( [ 0] => link=www.google.com )

Get Country of IP Address with PHP

You can try the services of https://www.geoip-db.com They provide a JSON or JSONP-callback solution.

<?php

    $json = file_get_contents("https://www.geoip-db.com/json");
    $data = json_decode($json);

    print $data->country_code . "<br>";
    print $data->country_name . "<br>";
    print $data->state . "<br>";
    print $data->city . "<br>";
    print $data->postal . "<br>";
    print $data->latitude . "<br>";
    print $data->longitude . "<br>";
    print $data->IPv4 . "<br>";

?>

CSS selector for disabled input type="submit"

Does that work in IE6?

No, IE6 does not support attribute selectors at all, cf. CSS Compatibility and Internet Explorer.

You might find How to workaround: IE6 does not support CSS “attribute” selectors worth the read.


EDIT
If you are to ignore IE6, you could do (CSS2.1):

input[type=submit][disabled=disabled],
button[disabled=disabled] {
    ...
}

CSS3 (IE9+):

input[type=submit]:disabled,
button:disabled {
    ...
}

You can substitute [disabled=disabled] (attribute value) with [disabled] (attribute presence).

Get the current first responder without using a private API

Peter Steinberger just tweeted about the private notification UIWindowFirstResponderDidChangeNotification, which you can observe if you want to watch the firstResponder change.

How to kill MySQL connections

In MySQL Workbench:

Left-hand side navigator > Management > Client Connections

It gives you the option to kill queries and connections.

Note: this is not TOAD like the OP asked, but MySQL Workbench users like me may end up here

What's the difference between .NET Core, .NET Framework, and Xamarin?

.NET 5 will be a unified version of all .NET variants coming in November 2020, so there will be no need to choose between variants anymore. enter image description here

How is the default submit button on an HTML form determined?

EDIT: Sorry, when writing this answer I was thinking about submit buttons in the general sense. The answer below is not about multiple type="submit" buttons, as it leaves only one type="submit" and change the other to type="button". I leave the answer here as reference in case helps someone that can change the type in their form:

To determine what button is pressed when hitting enter, you can mark it up with type="submit", and the other buttons mark them with type="button". For example:

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

IntelliJ: Error:java: error: release version 5 not supported

In IntelliJ, the default maven compiler version is less than version 5, which is not supported, so we have to manually change the version of the maven compiler.

We have two ways to define version.

First way:

<properties>
  <maven.compiler.target>1.8</maven.compiler.target>
  <maven.compiler.source>1.8</maven.compiler.source>
</properties>

Second way:

<build>
  <plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
            <source>8</source>
            <target>8</target>
        </configuration>
    </plugin>
  </plugins>
</build>

Intercept a form submit in JavaScript and prevent normal submission

Use @Kristian Antonsen's answer, or you can use:

$('button').click(function() {
    preventDefault();
    captureForm();
});

Catch a thread's exception in the caller thread in Python

As a noobie to Threading, it took me a long time to understand how to implement Mateusz Kobos's code (above). Here's a clarified version to help understand how to use it.

#!/usr/bin/env python

import sys
import threading
import Queue

class ExThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.__status_queue = Queue.Queue()

    def run_with_exception(self):
        """This method should be overriden."""
        raise NotImplementedError

    def run(self):
        """This method should NOT be overriden."""
        try:
            self.run_with_exception()
        except Exception:
            self.__status_queue.put(sys.exc_info())
        self.__status_queue.put(None)

    def wait_for_exc_info(self):
        return self.__status_queue.get()

    def join_with_exception(self):
        ex_info = self.wait_for_exc_info()
        if ex_info is None:
            return
        else:
            raise ex_info[1]

class MyException(Exception):
    pass

class MyThread(ExThread):
    def __init__(self):
        ExThread.__init__(self)

    # This overrides the "run_with_exception" from class "ExThread"
    # Note, this is where the actual thread to be run lives. The thread
    # to be run could also call a method or be passed in as an object
    def run_with_exception(self):
        # Code will function until the int
        print "sleeping 5 seconds"
        import time
        for i in 1, 2, 3, 4, 5:
            print i
            time.sleep(1) 
        # Thread should break here
        int("str")
# I'm honestly not sure why these appear here? So, I removed them. 
# Perhaps Mateusz can clarify?        
#         thread_name = threading.current_thread().name
#         raise MyException("An error in thread '{}'.".format(thread_name))

if __name__ == '__main__':
    # The code lives in MyThread in this example. So creating the MyThread 
    # object set the code to be run (but does not start it yet)
    t = MyThread()
    # This actually starts the thread
    t.start()
    print
    print ("Notice 't.start()' is considered to have completed, although" 
           " the countdown continues in its new thread. So you code "
           "can tinue into new processing.")
    # Now that the thread is running, the join allows for monitoring of it
    try:
        t.join_with_exception()
    # should be able to be replace "Exception" with specific error (untested)
    except Exception, e: 
        print
        print "Exceptioon was caught and control passed back to the main thread"
        print "Do some handling here...or raise a custom exception "
        thread_name = threading.current_thread().name
        e = ("Caught a MyException in thread: '" + 
             str(thread_name) + 
             "' [" + str(e) + "]")
        raise Exception(e) # Or custom class of exception, such as MyException

Return a `struct` from a function in C

struct var e2 address pushed as arg to callee stack and values gets assigned there. In fact, get() returns e2's address in eax reg. This works like call by reference.

Android WebView style background-color:transparent ignored on android 2.2

  • After trying everything given above. I found it doesn't matter either you specify
    webView.setBackgroundColor(Color.TRANSPARENT) before or after loadUrl() /loadData().
  • The thing that matters is you should explicitly declare android:hardwareAccelerated="false" in the manifest.

Tested on IceCream Sandwich

Div with margin-left and width:100% overflowing on the right side

<div style="width:100%;">
    <div style="margin-left:45px;">
       <asp:TextBox ID="txtTitle" runat="server" Width="100%"></asp:TextBox><br />
    </div>
</div>

Simple way to encode a string according to a password?

As you explicitly state that you want obscurity not security, we'll avoid reprimanding you for the weakness of what you suggest :)

So, using PyCrypto:

import base64
from Crypto.Cipher import AES

msg_text = b'test some plain text here'.rjust(32)
secret_key = b'1234567890123456'

cipher = AES.new(secret_key,AES.MODE_ECB) # never use ECB in strong systems obviously
encoded = base64.b64encode(cipher.encrypt(msg_text))
print(encoded)
decoded = cipher.decrypt(base64.b64decode(encoded))
print(decoded)

If someone gets a hold of your database and your code base, they will be able to decode the encrypted data. Keep your secret_key safe!

using javascript to detect whether the url exists before display in iframe

I found this worked in my scenario.

The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

$.get("urlToCheck.com").done(function () {
  alert("success");
}).fail(function () {
   alert("failed.");
});

How to trim a string to N chars in Javascript?

Why not just use substring... string.substring(0, 7); The first argument (0) is the starting point. The second argument (7) is the ending point (exclusive). More info here.

var string = "this is a string";
var length = 7;
var trimmedString = string.substring(0, length);

onChange and onSelect in DropDownList

hmm. why don't you use onClick()

<select id="mySelect" onChange="enable();">
   <option onClick="disable();">No</option>
   <option onClick="enable();">Yes</option>
</select>

Load local javascript file in chrome for testing?

If you still need to do this, I ran across the same problem. Somehow, EDGE renders all the scripts even if they are not via HTTP, HTTPS etc... Open the html/js file directly from the filesystem with Edge, and it will work.

How can I parse String to Int in an Angular expression?

You can use javascript Number method to parse it to an number,

var num=Number (num_str);

(413) Request Entity Too Large | uploadReadAheadSize

For anyone else ever looking for an IIS WCF error 413 : Request entity to large and using a WCF service in Sharepoint, this is the information for you. The settings in the application host and web.config suggested in other sites/posts don't work in SharePoint if using the MultipleBaseAddressBasicHttpBindingServiceHostFactory. You can use SP Powershell to get the SPWebService.Content service, create a new SPWcvSettings object and update the settings as above for your service (they won't exist). Remember to just use the name of the service (e.g. [yourservice.svc]) when creating and adding the settings. See this site for more info https://robertsep.wordpress.com/2010/12/21/set-maximum-upload-filesize-sharepoint-wcf-service

How to undo the last commit in git

I think you haven't messed up yet. Try:

git reset HEAD^

This will bring the dir to state before you've made the commit, HEAD^ means the parent of the current commit (the one you don't want anymore), while keeping changes from it (unstaged).

Python list sort in descending order

You can simply do this:

timestamps.sort(reverse=True)

How to install pip3 on Windows?

On Windows pip3 should be in the Scripts path of your Python installation:

C:\path\to\python\Scripts\pip3

Use:

where python

to find out where your Python executable(s) is/are located. The result should look like this:

C:\path\to\python\python.exe

or:

C:\path\to\python\python3.exe

You can check if pip3 works with this absolute path:

C:\path\to\python\Scripts\pip3

if yes, add C:\path\to\python\Scripts to your environmental variable PATH .

Select records from today, this week, this month php mysql

Everybody seems to refer to date being a column in the table.
I dont think this is good practice. The word date might just be a keyword in some coding language (maybe Oracle) so please change the columnname date to maybe JDate.
So will the following work better:

SELECT * FROM jokes WHERE JDate >= CURRENT_DATE() ORDER BY JScore DESC;

So we have a table called Jokes with columns JScore and JDate.

How do you create a UIImage View Programmatically - Swift

Thanks, MEnnabah, just to add to your code where you are missing the = sign in the declaration statement:

let someImageView: UIImageView = {
   let theImageView = UIImageView()
   theImageView.image = UIImage(named: "yourImage.png")
   theImageView.translatesAutoresizingMaskIntoConstraints = false //You need to call this property so the image is added to your view
   return theImageView
}()

Everything else is, all perfect for Swift 3.

Include in SELECT a column that isn't actually in the database

You may want to use:

SELECT Name, 'Unpaid' AS Status FROM table;

The SELECT clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:

SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ] 
<select_list> 

Where the expression can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.

Make browser window blink in task Bar

function blinkTab() {
        const browserTitle = document.title;
        let timeoutId;
        let message = 'My New Title';

        const stopBlinking = () => {
            document.title = browserTitle;
            clearInterval(timeoutId);
        };

        const startBlinking = () => {
            document.title = document.title  === message ? browserTitle : message;
        };

        function registerEvents() {
            window.addEventListener("focus", function(event) { 
                stopBlinking();
            });

            window.addEventListener("blur", function(event) {
                const timeoutId = setInterval(startBlinking, 500);
            });
        };

        registerEvents();
    };


    blinkTab();

Can I call a constructor from another constructor (do constructor chaining) in C++?

I believe you can call a constructor from a constructor. It will compile and run. I recently saw someone do this and it ran on both Windows and Linux.

It just doesn't do what you want. The inner constructor will construct a temporary local object which gets deleted once the outer constructor returns. They would have to be different constructors as well or you would create a recursive call.

Ref: https://isocpp.org/wiki/faq/ctors#init-methods

How do I center align horizontal <UL> menu?

div {
     text-align: center;
}
div ul {
     display: inline-table;
}

ul as inline-table fixes the with issue. I used the parent div to align the text to center. this way it looks good even in other languages (translation, different width)

How schedule build in Jenkins?

In Jenkins , we have the format is as:

Minute(0-59) Hour(0-23) Day(1-7) Month(1-12) Day of the Week

How to get host name with port from a http or https request

You can use HttpServletRequest.getRequestURL and HttpServletRequest.getRequestURI.

StringBuffer url = request.getRequestURL();
String uri = request.getRequestURI();
int idx = (((uri != null) && (uri.length() > 0)) ? url.indexOf(uri) : url.length());
String host = url.substring(0, idx); //base url
idx = host.indexOf("://");
if(idx > 0) {
  host = host.substring(idx); //remove scheme if present
}

Scala: join an iterable of strings

How about mkString ?

theStrings.mkString(",")

A variant exists in which you can specify a prefix and suffix too.

See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.

Finding Android SDK on Mac and adding to PATH

  1. How do I find Android SDK on my machine? Or prove to myself it's not there?

When you install Android studio, it allows you to choose if you want to download SDK or not

  1. If it's not there how do I install it?

you can get SDK from here http://developer.android.com/sdk/index.html

  1. How do I change PATH to include Android SDK?

in Android Studio click in File >> Settings enter image description here

Adding multiple columns AFTER a specific column in MySQL

Try this

ALTER TABLE users
ADD COLUMN `count` SMALLINT(6) NOT NULL AFTER `lastname`,
ADD COLUMN `log` VARCHAR(12) NOT NULL AFTER `count`,
ADD COLUMN `status` INT(10) UNSIGNED NOT NULL AFTER `log`;

check the syntax

Change color when hover a font awesome icon?

use - !important - to override default black

_x000D_
_x000D_
.fa-heart:hover{_x000D_
   color:red !important;_x000D_
}_x000D_
.fa-heart-o:hover{_x000D_
   color:red !important;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">_x000D_
_x000D_
<i class="fa fa-heart fa-2x"></i>_x000D_
<i class="fa fa-heart-o fa-2x"></i>
_x000D_
_x000D_
_x000D_

Re-sign IPA (iPhone)

In 2020, I did it with Fastlane -

Here is the command I used

$ fastlane run resign ipa:"/Users/my_user/path/to/app.ipa" signing_identity:"iPhone Distribution: MY Company (XXXXXXXX)" provisioning_profile:"/Users/my_user/path/to/profile.mobileprovision" bundle_id:com.company.new.bundle.name

Full docs here - https://docs.fastlane.tools/actions/resign/

Efficient way to return a std::vector in c++

A common pre-C++11 idiom is to pass a reference to the object being filled.

Then there is no copying of the vector.

void f( std::vector & result )
{
  /*
    Insert elements into result
  */
} 

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

Not sure if MySQL has row_number function. If so you can use it to get the desired result. On SQL Server you can do something similar to:

CREATE TABLE p
(
 person NVARCHAR(10),
 gp INT,
 age INT
);
GO
INSERT  INTO p
VALUES  ('Bob', 1, 32);
INSERT  INTO p
VALUES  ('Jill', 1, 34);
INSERT  INTO p
VALUES  ('Shawn', 1, 42);
INSERT  INTO p
VALUES  ('Jake', 2, 29);
INSERT  INTO p
VALUES  ('Paul', 2, 36);
INSERT  INTO p
VALUES  ('Laura', 2, 39);
GO

SELECT  t.person, t.gp, t.age
FROM    (
         SELECT *,
                ROW_NUMBER() OVER (PARTITION BY gp ORDER BY age DESC) row
         FROM   p
        ) t
WHERE   t.row = 1;

What does <T> (angle brackets) mean in Java?

It is related to generics in java. If I mentioned ArrayList<String> that means I can add only String type object to that ArrayList.

The two major benefits of generics in Java are:

  1. Reducing the number of casts in your program, thus reducing the number of potential bugs in your program.
  2. Improving code clarity

Difference Between ViewResult() and ActionResult()

It's for the same reason you don't write every method of every class to return "object". You should be as specific as you can. This is especially valuable if you're planning to write unit tests. No more testing return types and/or casting the result.

How to change color of SVG image using CSS (jQuery SVG image replacement)?

If we have a greater number of such svg images we can also take the help of font-files.
Sites like https://glyphter.com/ can get us a font file from our svgs.


E.g.

@font-face {
    font-family: 'iconFont';
    src: url('iconFont.eot');
}
#target{
    color: white;
    font-size:96px;
    font-family:iconFont;
}

psql - save results of command to a file

Use the below query to store the result in a CSV file

\copy (your query) to 'file path' csv header;

Example

\copy (select name,date_order from purchase_order) to '/home/ankit/Desktop/result.csv' cvs header;

Hope this helps you.

Android Studio: Unable to start the daemon process

I have solve this problem by just deleting .gradle folder within my application project..

Delete folder .gradle from your project no need to delete main .gradle folder which is located at C:\Users\<username>

close fxml window by code, javafx

I'm not sure if this is the best way (or if it works), but you could try:

private void on_btnClose_clicked(ActionEvent actionEvent) {

        Window window = getScene().getWindow();   

        if (window instanceof Stage){
            ((Stage) window).close();
        }
}

(Assuming your controller is a Node. Otherwise you have to get the node first (getScene() is a method of Node)

How to find nth occurrence of character in a string?

If your project already depends on Apache Commons you can use StringUtils.ordinalIndexOf, otherwise, here's an implementation:

public static int ordinalIndexOf(String str, String substr, int n) {
    int pos = str.indexOf(substr);
    while (--n > 0 && pos != -1)
        pos = str.indexOf(substr, pos + 1);
    return pos;
}

This post has been rewritten as an article here.

PHP code is not being executed, instead code shows on the page

For fresh setup of LAMP running php 7 edit the file /etc/httpd/conf/httpd.conf Note: make sure to make backup for it before changing anything.

Paste this at the very bottom of the file:

<IfModule php7_module>
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
<IfModule dir_module>
    DirectoryIndex index.html index.php
</IfModule>

Then, search for LoadModule and paste the following line:

LoadModule php7_module modules/libphp7.so

This line will simply ask httpd to load the php 7 module

Then restart httpd

AltGr key not working, instead I have to use Ctrl+AltGr

I found a solution for my problem while writing my question !

Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)

I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)

So it seems the problem comes from the use of RDP (windows7 and 8)

Update 2017: Problem occurs on Windows 10 aswell.

Change drive in git bash for windows

In order to navigate to a different drive just use

cd /E/Study/Codes

It will solve your problem.

.htaccess file to allow access to images folder to view pictures?

<Directory /uploads>
   Options +Indexes
</Directory>

How can I get the executing assembly version?

I finally settled on typeof(MyClass).GetTypeInfo().Assembly.GetName().Version for a netstandard1.6 app. All of the other proposed answers presented a partial solution. This is the only thing that got me exactly what I needed.

Sourced from a combination of places:

https://msdn.microsoft.com/en-us/library/x4cw969y(v=vs.110).aspx

https://msdn.microsoft.com/en-us/library/2exyydhb(v=vs.110).aspx

Android: Test Push Notification online (Google Cloud Messaging)

POSTMAN : A google chrome extension

Use postman to send message instead of server. Postman settings are as follows :

Request Type: POST

URL: https://android.googleapis.com/gcm/send

Header
  Authorization  : key=your key //Google API KEY
  Content-Type : application/json

JSON (raw) :
{       
  "registration_ids":["yours"],
  "data": {
    "Hello" : "World"
  } 
}

on success you will get

Response :
{
  "multicast_id": 6506103988515583000,
  "success": 1,
  "failure": 0,
  "canonical_ids": 0,
  "results": [
    {
      "message_id": "0:1432811719975865%54f79db3f9fd7ecd"
    }
  ]
}

HTML-encoding lost when attribute read from input field

I had a similar problem and solve it using the function encodeURIComponent from JavaScript (documentation)

For example, in your case if you use:

<input id='hiddenId' type='hidden' value='chalk & cheese' />

and

encodeURIComponent($('#hiddenId').attr('value'))

you will get chalk%20%26%20cheese. Even spaces are kept.

In my case, I had to encode one backslash and this code works perfectly

encodeURIComponent('name/surname')

and I got name%2Fsurname

Difference between null and empty string

String s1 = ""; means that the empty String is assigned to s1. In this case, s1.length() is the same as "".length(), which will yield 0 as expected.

String s2 = null; means that (null) or "no value at all" is assigned to s2. So this one, s2.length() is the same as null.length(), which will yield a NullPointerException as you can't call methods on null variables (pointers, sort of) in Java.

Also, a point, the statement

String s1;

Actually has the same effect as:

String s1 = null;

Whereas

String s1 = "";

Is, as said, a different thing.

React JS - Uncaught TypeError: this.props.data.map is not a function

You don't need an array to do it.

var ItemNode = this.state.data.map(function(itemData) {
return (
   <ComponentName title={itemData.title} key={itemData.id} number={itemData.id}/>
 );
});

Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH

In my case I was modifying the request to append a header (using Fiddler) to an https request, but I did not configure it to decrypt https traffic. You can export a manually-created certificate from Fiddler, so you can trust/import the certificate by your browsers. See above link for details, some steps include:

  1. Click Tools > Fiddler Options.
  2. Click the HTTPS tab. Ensure the Decrypt HTTPS traffic checkbox is checked.
  3. Click the Export Fiddler Root Certificate to Desktop button.

Renaming a branch in GitHub

The following commands worked for me:

git push origin :old-name-of-branch-on-github
git branch -m old-name-of-branch-on-github new-name-for-branch-you-want
git push origin new-name-for-branch-you-want

127 Return code from $?

It has no special meaning, other than that the last process to exit did so with an exit status of 127.

However, it is also used by bash (assuming you're using bash as a shell) to tell you that the command you tried to execute couldn't be executed (i.e. it couldn't be found). It's unfortunately not immediately deducible though, if the process exited with status 127, or if it couldn't found.

EDIT:
Not immediately deducible, except for the output on the console, but this is stack overflow, so I assume you're doing this in a script.

How to suppress "unused parameter" warnings in C?

Labelling the attribute is ideal way. MACRO leads to sometime confusion. and by using void(x),we are adding an overhead in processing.

If not using input argument, use

void foo(int __attribute__((unused))key)
{
}

If not using the variable defined inside the function

void foo(int key)
{
   int hash = 0;
   int bkt __attribute__((unused)) = 0;

   api_call(x, hash, bkt);
}

Now later using the hash variable for your logic but doesn’t need bkt. define bkt as unused, otherwise compiler says'bkt set bt not used".

NOTE: This is just to suppress the warning not for optimization.

Java: how can I split an ArrayList in multiple small ArrayLists?

This works for me

/**
* Returns List of the List argument passed to this function with size = chunkSize
* 
* @param largeList input list to be portioned
* @param chunkSize maximum size of each partition
* @param <T> Generic type of the List
* @return A list of Lists which is portioned from the original list 
*/
public static  <T> List<List<T>> chunkList(List<T> list, int chunkSize) {
    if (chunkSize <= 0) {
        throw new IllegalArgumentException("Invalid chunk size: " + chunkSize);
    }
    List<List<T>> chunkList = new ArrayList<>(list.size() / chunkSize);
    for (int i = 0; i < list.size(); i += chunkSize) {
        chunkList.add(list.subList(i, i + chunkSize >= list.size() ? list.size()-1 : i + chunkSize));
    }
    return chunkList;
}

Eg :

List<Integer> stringList = new ArrayList<>();
stringList.add(0);
stringList.add(1);
stringList.add(2);
stringList.add(3);
stringList.add(4);
stringList.add(5);
stringList.add(6);
stringList.add(7);
stringList.add(8);
stringList.add(9);

List<List<Integer>> chunkList = getChunkList1(stringList, 2);

Java - Check if input is a positive integer, negative integer, natural number and so on.

(You should you as Else-If statement to check the for the three different state (positive, negative, 0)

Here is a simple example (excludes the possibility of non-integer values)

  import java.util.Scanner;

  public class Compare {

   public static void main(String[] args) { 

    Scanner input = new Scanner(System.in);

    System.out.print("Enter a number: ");
    int number = input.nextInt();

    if( number == 0)
    { System.out.println("Number is equal to zero"); }
    else if (number > 0)
    { System.out.println("Number is positive"); }
    else 
    { System.out.println("Number is negative"); }


  }
 }

How can I get the list of files in a directory using C or C++?

One function is enough, you don't need to use any 3rd-party library (for Windows).

#include <Windows.h>

vector<string> get_all_files_names_within_folder(string folder)
{
    vector<string> names;
    string search_path = folder + "/*.*";
    WIN32_FIND_DATA fd; 
    HANDLE hFind = ::FindFirstFile(search_path.c_str(), &fd); 
    if(hFind != INVALID_HANDLE_VALUE) { 
        do { 
            // read all (real) files in current folder
            // , delete '!' read other 2 default folder . and ..
            if(! (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) {
                names.push_back(fd.cFileName);
            }
        }while(::FindNextFile(hFind, &fd)); 
        ::FindClose(hFind); 
    } 
    return names;
}

PS: as mentioned by @Sebastian, you could change *.* to *.ext in order to get only the EXT-files (i.e. of a specific type) in that directory.

Redirect stderr and stdout in Bash

Curiously, this works:

yourcommand &> filename

But this gives a syntax error:

yourcommand &>> filename
syntax error near unexpected token `>'

You have to use:

yourcommand 1>> filename 2>&1

Asus Zenfone 5 not detected by computer

Try a different usb cable. My cable was bad. Charging was ok but did not attach the phone.

Swapping pointers in C (char, int)

void intSwap (int *pa, int *pb){
    int temp = *pa;
    *pa = *pb;
    *pb = temp;
}

You need to know the following -

int a = 5; // an integer, contains value
int *p; // an integer pointer, contains address
p = &a; // &a means address of a
a = *p; // *p means value stored in that address, here 5

void charSwap(char* a, char* b){
    char temp = *a;
    *a = *b;
    *b = temp;
}

So, when you swap like this. Only the value will be swapped. So, for a char* only their first char will swap.

Now, if you understand char* (string) clearly, then you should know that, you only need to exchange the pointer. It'll be easier to understand if you think it as an array instead of string.

void stringSwap(char** a, char** b){
    char *temp = *a;
    *a = *b;
    *b = temp;
}

So, here you are passing double pointer because starting of an array itself is a pointer.

Include an SVG (hosted on GitHub) in MarkDown

The purpose of raw.github.com is to allow users to view the contents of a file, so for text based files this means (for certain content types) you can get the wrong headers and things break in the browser.

When this question was asked (in 2012) SVGs didn't work. Since then Github has implemented various improvements. Now (at least for SVG), the correct Content-Type headers are sent.

Examples

All of the ways stated below will work.

I copied the SVG image from the question to a repo on github in order to create the examples below

Linking to files using relative paths (Works, but obviously only on github.com / github.io)

Code

![Alt text](./controllers_brief.svg)
<img src="./controllers_brief.svg">

Result

See the working example on github.com.

Linking to RAW files

Code

![Alt text](https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg)
<img src="https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg">

Result

Alt text

Linking to RAW files using ?sanitize=true

Code

![Alt text](https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg?sanitize=true)
<img src="https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg?sanitize=true">

Result

Alt text

Linking to files hosted on github.io

Code

![Alt text](https://potherca-blog.github.io/StackOverflow/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg)
<img src="https://potherca-blog.github.io/StackOverflow/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg">

Result

Alt text


Some comments regarding changes that happened along the way:

  • Github has implemented a feature which makes it possible for SVG's to be used with the Markdown image syntax. The SVG image will be sanitized and displayed with the correct HTTP header. Certain tags (like <script>) are removed.

    To view the sanitized SVG or to achieve this effect from other places (i.e. from markdown files not hosted in repos on http://github.com/) simply append ?sanitize=true to the SVG's raw URL.

  • As stated by AdamKatz in the comments, using a source other than github.io can introduce potentially privacy and security risks. See the answer by CiroSantilli and the answer by DavidChambers for more details.

  • The issue to resolve this was opened on Github on October 13th 2015 and was resolved on August 31th 2017

Div height 100% and expands to fit content

Even you can do like this

display:block;
overflow:auto;
height: 100%;

This will include your each dynamic div as per the content. Suppose if you have a common div with class it will increase height of each dynamic div according to the content

What replaces cellpadding, cellspacing, valign, and align in HTML5 tables?

This should solve your problem:

td {
    /* <http://www.w3.org/wiki/CSS/Properties/text-align>
     * left, right, center, justify, inherit
     */
    text-align: center;
    /* <http://www.w3.org/wiki/CSS/Properties/vertical-align>
     * baseline, sub, super, top, text-top, middle,
     * bottom, text-bottom, length, or a value in percentage
     */
    vertical-align: top;
}

How can we redirect a Java program console output to multiple files?

We can do this by setting out variable of System class in the following way

System.setOut(new PrintStream(new FileOutputStream("Path to output file"))). Also You need to close or flush 'out'(System.out.close() or System.out.flush()) variable so that you don't end up missing some output.

Source : http://xmodulo.com/how-to-save-console-output-to-file-in-eclipse.html

To prevent a memory leak, the JDBC Driver has been forcibly unregistered

I see this issue come up a lot. Yes, Tomcat 7 does automatically deregister it, but it that REALLY taking control of your code and a good coding practice? Surely YOU want to know that you have all the correct code in place to close all your objects, shut down database connection pool threads, and get rid of all warnings. I certainly do.

This is how I do it.

Step 1: Register a Listener

web.xml

<listener>
    <listener-class>com.mysite.MySpecialListener</listener-class>
</listener>

Step 2: Implement the Listener

com.mysite.MySpecialListener.java

public class MySpecialListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // On Application Startup, please…

        // Usually I'll make a singleton in here, set up my pool, etc.
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // On Application Shutdown, please…

        // 1. Go fetch that DataSource
        Context initContext = new InitialContext();
        Context envContext  = (Context)initContext.lookup("java:/comp/env");
        DataSource datasource = (DataSource)envContext.lookup("jdbc/database");

        // 2. Deregister Driver
        try {
            java.sql.Driver mySqlDriver = DriverManager.getDriver("jdbc:mysql://localhost:3306/");
            DriverManager.deregisterDriver(mySqlDriver);
        } catch (SQLException ex) {
            logger.info("Could not deregister driver:".concat(ex.getMessage()));
        } 

        // 3. For added safety, remove the reference to dataSource for GC to enjoy.
        dataSource = null;
    }

}

Please feel free to comment and/or add...

How to install ia32-libs in Ubuntu 14.04 LTS (Trusty Tahr)

Simply install the 32-bit version of the program, instead of the 64-bit version.

This is much safer than installing packages that are not intended for the distribution at hand.

I got this suggestion from the Google Earth installation instructions for Ubuntu 14.04. Google Earth used to employ ia32-libs under 64-bit Ubuntu 12.04.

Quoting webupd8.org:

The ia32-libs package is no longer available in Ubuntu, starting with Ubuntu 13.10. The package was superseded by multiarch support so you don't need it any more, but some 64bit packages (which are actually 32bit applications) still depend on this package and because of this, they can't be installed in Ubuntu 14.04 or 13.10, 64bit. [...]

The "fix" or more specifically the correct way of installing these apps which depend on ia32-libs is to simply install the 32bit package on Ubuntu 64bit. Of course, that will install quite a few 32bit packages, but that's how multiarch works.

The problem with some programs (like Google Earth) is that the 32-bit package does not support multiarch. Consequently, some 32-bit dependencies need to be installed manually to make the 32-bit version of the program run on Ubuntu 64-bit.

sudo dpkg --add-architecture i386 # only needed once
sudo apt-get update
sudo apt-get install libfontconfig1:i386 libx11-6:i386 libxrender1:i386 libxext6:i386 libgl1-mesa-glx:i386 libglu1-mesa:i386 libglib2.0-0:i386 libsm6:i386

Calculate a Running Total in SQL Server

SELECT TOP 25   amount, 
    (SELECT SUM(amount) 
    FROM time_detail b 
    WHERE b.time_detail_id <= a.time_detail_id) AS Total FROM time_detail a

You can also use the ROW_NUMBER() function and a temp table to create an arbitrary column to use in the comparison on the inner SELECT statement.

CSS3 equivalent to jQuery slideUp and slideDown?

you can't make easisly a slideup slidedown with css3 tha's why I've turned JensT script into a plugin with javascript fallback and callback.

in this way if you have a modern brwowser you can use the css3 csstransition. if your browser does not support it gracefuly use the old fashioned slideUp slideDown.

 /* css */
.csstransitions .mosneslide {
  -webkit-transition: height .4s ease-in-out;
  -moz-transition: height .4s ease-in-out;
  -ms-transition: height .4s ease-in-out;
  -o-transition: height .4s ease-in-out;
  transition: height .4s ease-in-out;
  max-height: 9999px;
  overflow: hidden;
  height: 0;
}

the plugin

(function ($) {
$.fn.mosne_slide = function (
    options) {
    // set default option values
    defaults = {
        delay: 750,
        before: function () {}, // before  callback
        after: function () {} // after callback;
    }
    // Extend default settings
    var settings = $.extend({},
        defaults, options);
    return this.each(function () {
        var $this = $(this);
        //on after
        settings.before.apply(
            $this);
        var height = $this.height();
        var width = $this.width();
        if (Modernizr.csstransitions) {
            // modern browsers
            if (height > 0) {
                $this.css(
                    'height',
                    '0')
                    .addClass(
                        "mosne_hidden"
                );
            } else {
                var clone =
                    $this.clone()
                    .css({
                        'position': 'absolute',
                        'visibility': 'hidden',
                        'height': 'auto',
                        'width': width
                    })
                    .addClass(
                        'mosne_slideClone'
                )
                    .appendTo(
                        'body'
                );
                var newHeight =
                    $(
                        ".mosne_slideClone"
                )
                    .height();
                $(
                    ".mosne_slideClone"
                )
                    .remove();
                $this.css(
                    'height',
                    newHeight +
                    'px')
                    .removeClass(
                        "mosne_hidden"
                );
            }
        } else {
            //fallback
            if ($this.is(
                ":visible"
            )) {
                $this.slideUp()
                    .addClass(
                        "mosne_hidden"
                );
            } else {
                $this.hide()
                    .slideDown()
                    .removeClass(
                        "mosne_hidden"
                );
            }
        }
        //on after
        setTimeout(function () {
            settings.after
                .apply(
                    $this
            );
        }, settings.delay);
    });
}
})(jQuery);;

how to use it

/* jQuery */
$(".mosneslide").mosne_slide({
    delay:400,
    before:function(){console.log("start");},
    after:function(){console.log("done");}
});

you can find a demo page here http://www.mosne.it/playground/mosne_slide_up_down/

python global name 'self' is not defined

In Python self is the conventional name given to the first argument of instance methods of classes, which is always the instance the method was called on:

class A(object):
  def f(self):
    print self

a = A()
a.f()

Will give you something like

<__main__.A object at 0x02A9ACF0>

How to remove the bottom border of a box with CSS

Just add in: border-bottom: none;

#index-03 {
    position:absolute;
    border: .1px solid #900;
    border-bottom: none;
    left:0px;
    top:102px;
    width:900px;
    height:27px;
}

How to play a notification sound on websites?

As of 2016, the following will suffice (you don't even need to embed):

let src = 'https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3';
let audio = new Audio(src);
audio.play();

See more here.

How to select bottom most rows?

The problem with ordering the other way is that it often does not make good use of indices. It is also not very extendable if you ever need to select a number of rows that are not at the start or the end. An alternative way is as follows.

DECLARE @NumberOfRows int;
SET @NumberOfRows = (SELECT COUNT(*) FROM TheTable);

SELECT col1, col2,...
FROM (
    SELECT col1, col2,..., ROW_NUMBER() OVER (ORDER BY col1) AS intRow
    FROM TheTable
) AS T
WHERE intRow > @NumberOfRows - 20;

How to check if a windows form is already open, and close it if it is?

* Hope This will work for u

System.Windows.Forms.Form f1 = System.Windows.Forms.Application.OpenForms["Order"];
if(((Order)f1)!=null)
{
//open Form
}
else
{
//not open
}

Equivalent of LIMIT for DB2

Using FETCH FIRST [n] ROWS ONLY:

http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/index.jsp?topic=/com.ibm.db29.doc.perf/db2z_fetchfirstnrows.htm

SELECT LASTNAME, FIRSTNAME, EMPNO, SALARY
  FROM EMP
  ORDER BY SALARY DESC
  FETCH FIRST 20 ROWS ONLY;

To get ranges, you'd have to use ROW_NUMBER() (since v5r4) and use that within the WHERE clause: (stolen from here: http://www.justskins.com/forums/db2-select-how-to-123209.html)

SELECT code, name, address
FROM ( 
  SELECT row_number() OVER ( ORDER BY code ) AS rid, code, name, address
  FROM contacts
  WHERE name LIKE '%Bob%' 
  ) AS t
WHERE t.rid BETWEEN 20 AND 25;

Run two async tasks in parallel and collect results in .NET 4.5

This article helped explain a lot of things. It's in FAQ style.

Async/Await FAQ

This part explains why Thread.Sleep runs on the same original thread - leading to my initial confusion.

Does the “async” keyword cause the invocation of a method to queue to the ThreadPool? To create a new thread? To launch a rocket ship to Mars?

No. No. And no. See the previous questions. The “async” keyword indicates to the compiler that “await” may be used inside of the method, such that the method may suspend at an await point and have its execution resumed asynchronously when the awaited instance completes. This is why the compiler issues a warning if there are no “awaits” inside of a method marked as “async”.

Submitting a form on 'Enter' with jQuery?

Return false to prevent the keystroke from continuing.

Object spread vs. Object.assign

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

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

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

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

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

Understanding ASP.NET Eval() and Bind()

The question was answered perfectly by Darin Dimitrov, but since ASP.NET 4.5, there is now a better way to set up these bindings to replace* Eval() and Bind(), taking advantage of the strongly-typed bindings.

*Note: this will only work if you're not using a SqlDataSource or an anonymous object. It requires a Strongly-typed object (from an EF model or any other class).

This code snippet shows how Eval and Bind would be used for a ListView control (InsertItem needs Bind, as explained by Darin Dimitrov above, and ItemTemplate is read-only (hence they're labels), so just needs an Eval):

<asp:ListView ID="ListView1" runat="server" DataKeyNames="Id" InsertItemPosition="LastItem" SelectMethod="ListView1_GetData" InsertMethod="ListView1_InsertItem" DeleteMethod="ListView1_DeleteItem">
    <InsertItemTemplate>
        <li>
            Title: <asp:TextBox ID="Title" runat="server" Text='<%# Bind("Title") %>'/><br />         
            Description: <asp:TextBox ID="Description" runat="server" TextMode="MultiLine" Text='<%# Bind("Description") %>' /><br />        
            <asp:Button ID="InsertButton" runat="server" Text="Insert" CommandName="Insert" />        
        </li>
    </InsertItemTemplate>
    <ItemTemplate>
        <li>
            Title: <asp:Label ID="Title" runat="server" Text='<%#  Eval("Title") %>' /><br />
            Description: <asp:Label ID="Description" runat="server" Text='<%# Eval("Description") %>' /><br />        
            <asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" CausesValidation="false"/>
        </li>
      </ItemTemplate>

From ASP.NET 4.5+, data-bound controls have been extended with a new property ItemType, which points to the type of object you're assigning to its data source.

<asp:ListView ItemType="Picture" ID="ListView1" runat="server" ...>

Picture is the strongly type object (from EF model). We then replace:

Bind(property) -> BindItem.property
Eval(property) -> Item.property

So this:

<%# Bind("Title") %>      
<%# Bind("Description") %>         
<%#  Eval("Title") %> 
<%# Eval("Description") %>

Would become this:

<%# BindItem.Title %>         
<%# BindItem.Description %>
<%# Item.Title %>
<%# Item.Description %>

Advantages over Eval & Bind:

  • IntelliSense can find the correct property of the object your're working withenter image description here
  • If property is renamed/deleted, you will get an error before page is viewed in browser
  • External tools (requires full versions of VS) will correctly rename item in markup when you rename a property on your object

Source: from this excellent book

TypeError: got multiple values for argument

I had the same problem that is really easy to make, but took me a while to see through.

I had copied the declaration to where I was using it and had left the 'self' argument there, but it took me ages to realise that.

I had

self.myFunction(self, a, b, c='123')

but it should have been

self.myFunction(a, b, c='123')

SQL Server add auto increment primary key to existing table

ALTER TABLE table_name ADD COLUMN ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT ; This could be useful

How do I horizontally center a span element inside a div

only css div you can center content

div{
       display:table;
       margin:0 auto;
    }

http://jsfiddle.net/4q2r69te/1/

How do I get a background location update every n minutes in my iOS application?

It seems that stopUpdatingLocation is what triggers the background watchdog timer, so I replaced it in didUpdateLocation with:

     [self.locationManager setDesiredAccuracy:kCLLocationAccuracyThreeKilometers];
     [self.locationManager setDistanceFilter:99999];

which appears to effectively power down the GPS. The selector for the background NSTimer then becomes:

- (void) changeAccuracy {
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[self.locationManager setDistanceFilter:kCLDistanceFilterNone];
}

All I'm doing is periodically toggling the accuracy to get a high-accuracy coordinate every few minutes and because the locationManager hasn't been stopped, backgroundTimeRemaining stays at its maximum value. This reduced battery consumption from ~10% per hour (with constant kCLLocationAccuracyBest in the background) to ~2% per hour on my device

Better way to get type of a Javascript variable?

A reasonably good type capture function is the one used by YUI3:

var TYPES = {
    'undefined'        : 'undefined',
    'number'           : 'number',
    'boolean'          : 'boolean',
    'string'           : 'string',
    '[object Function]': 'function',
    '[object RegExp]'  : 'regexp',
    '[object Array]'   : 'array',
    '[object Date]'    : 'date',
    '[object Error]'   : 'error'
},
TOSTRING = Object.prototype.toString;

function type(o) {
    return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null');
};

This captures many of the primitives provided by javascript, but you can always add more by modifying the TYPES object. Note that typeof HTMLElementCollection in Safari will report function, but type(HTMLElementCollection) will return object

Extract the maximum value within each group in a dataframe

There are many possibilities to do this in R. Here are some of them:

df <- read.table(header = TRUE, text = 'Gene   Value
A      12
A      10
B      3
B      5
B      6
C      1
D      3
D      4')

# aggregate
aggregate(df$Value, by = list(df$Gene), max)
aggregate(Value ~ Gene, data = df, max)

# tapply
tapply(df$Value, df$Gene, max)

# split + lapply
lapply(split(df, df$Gene), function(y) max(y$Value))

# plyr
require(plyr)
ddply(df, .(Gene), summarise, Value = max(Value))

# dplyr
require(dplyr)
df %>% group_by(Gene) %>% summarise(Value = max(Value))

# data.table
require(data.table)
dt <- data.table(df)
dt[ , max(Value), by = Gene]

# doBy
require(doBy)
summaryBy(Value~Gene, data = df, FUN = max)

# sqldf
require(sqldf)
sqldf("select Gene, max(Value) as Value from df group by Gene", drv = 'SQLite')

# ave
df[as.logical(ave(df$Value, df$Gene, FUN = function(x) x == max(x))),]

Processing Symbol Files in Xcode

In my case symbolicating was take forever. I force restart my phone with both of on/off and home button. Now quickly finished symbolicating and I am starting run my app via xcode.

How to make <input type="date"> supported on all browsers? Any alternatives?

Any browser that does not support the input type date will default to the standard type, which is text, so all you have to do is check the type property (not the attribute), if it's not date, the date input is not supported by the browser, and you add your own datepicker:

if ( $('[type="date"]').prop('type') != 'date' ) {
    $('[type="date"]').datepicker();
}

FIDDLE

You can of course use any datepicker you want, jQuery UI's datepicker is probably the one most commonly used, but it does add quite a bit of javascript if you're not using the UI library for anything else, but there are hundreds of alternative datepickers to choose from.

The type attribute never changes, the browser will only fall back to the default text type for the property, so one has to check the property.
The attribute can still be used as a selector, as in the example above.

"Keep Me Logged In" - the best approach

OK, let me put this bluntly: if you're putting user data, or anything derived from user data into a cookie for this purpose, you're doing something wrong.

There. I said it. Now we can move on to the actual answer.

What's wrong with hashing user data, you ask? Well, it comes down to exposure surface and security through obscurity.

Imagine for a second that you're an attacker. You see a cryptographic cookie set for the remember-me on your session. It's 32 characters wide. Gee. That may be an MD5...

Let's also imagine for a second that they know the algorithm that you used. For example:

md5(salt+username+ip+salt)

Now, all an attacker needs to do is brute force the "salt" (which isn't really a salt, but more on that later), and he can now generate all the fake tokens he wants with any username for his IP address! But brute-forcing a salt is hard, right? Absolutely. But modern day GPUs are exceedingly good at it. And unless you use sufficient randomness in it (make it large enough), it's going to fall quickly, and with it the keys to your castle.

In short, the only thing protecting you is the salt, which isn't really protecting you as much as you think.

But Wait!

All of that was predicated that the attacker knows the algorithm! If it's secret and confusing, then you're safe, right? WRONG. That line of thinking has a name: Security Through Obscurity, which should NEVER be relied upon.

The Better Way

The better way is to never let a user's information leave the server, except for the id.

When the user logs in, generate a large (128 to 256 bit) random token. Add that to a database table which maps the token to the userid, and then send it to the client in the cookie.

What if the attacker guesses the random token of another user?

Well, let's do some math here. We're generating a 128 bit random token. That means that there are:

possibilities = 2^128
possibilities = 3.4 * 10^38

Now, to show how absurdly large that number is, let's imagine every server on the internet (let's say 50,000,000 today) trying to brute-force that number at a rate of 1,000,000,000 per second each. In reality your servers would melt under such load, but let's play this out.

guesses_per_second = servers * guesses
guesses_per_second = 50,000,000 * 1,000,000,000
guesses_per_second = 50,000,000,000,000,000

So 50 quadrillion guesses per second. That's fast! Right?

time_to_guess = possibilities / guesses_per_second
time_to_guess = 3.4e38 / 50,000,000,000,000,000
time_to_guess = 6,800,000,000,000,000,000,000

So 6.8 sextillion seconds...

Let's try to bring that down to more friendly numbers.

215,626,585,489,599 years

Or even better:

47917 times the age of the universe

Yes, that's 47917 times the age of the universe...

Basically, it's not going to be cracked.

So to sum up:

The better approach that I recommend is to store the cookie with three parts.

function onLogin($user) {
    $token = GenerateRandomToken(); // generate a token, should be 128 - 256 bit
    storeTokenForUser($user, $token);
    $cookie = $user . ':' . $token;
    $mac = hash_hmac('sha256', $cookie, SECRET_KEY);
    $cookie .= ':' . $mac;
    setcookie('rememberme', $cookie);
}

Then, to validate:

function rememberMe() {
    $cookie = isset($_COOKIE['rememberme']) ? $_COOKIE['rememberme'] : '';
    if ($cookie) {
        list ($user, $token, $mac) = explode(':', $cookie);
        if (!hash_equals(hash_hmac('sha256', $user . ':' . $token, SECRET_KEY), $mac)) {
            return false;
        }
        $usertoken = fetchTokenByUserName($user);
        if (hash_equals($usertoken, $token)) {
            logUserIn($user);
        }
    }
}

Note: Do not use the token or combination of user and token to lookup a record in your database. Always be sure to fetch a record based on the user and use a timing-safe comparison function to compare the fetched token afterwards. More about timing attacks.

Now, it's very important that the SECRET_KEY be a cryptographic secret (generated by something like /dev/urandom and/or derived from a high-entropy input). Also, GenerateRandomToken() needs to be a strong random source (mt_rand() is not nearly strong enough. Use a library, such as RandomLib or random_compat, or mcrypt_create_iv() with DEV_URANDOM)...

The hash_equals() is to prevent timing attacks. If you use a PHP version below PHP 5.6 the function hash_equals() is not supported. In this case you can replace hash_equals() with the timingSafeCompare function:

/**
 * A timing safe equals comparison
 *
 * To prevent leaking length information, it is important
 * that user input is always used as the second parameter.
 *
 * @param string $safe The internal (safe) value to be checked
 * @param string $user The user submitted (unsafe) value
 *
 * @return boolean True if the two strings are identical.
 */
function timingSafeCompare($safe, $user) {
    if (function_exists('hash_equals')) {
        return hash_equals($safe, $user); // PHP 5.6
    }
    // Prevent issues if string length is 0
    $safe .= chr(0);
    $user .= chr(0);

    // mbstring.func_overload can make strlen() return invalid numbers
    // when operating on raw binary strings; force an 8bit charset here:
    if (function_exists('mb_strlen')) {
        $safeLen = mb_strlen($safe, '8bit');
        $userLen = mb_strlen($user, '8bit');
    } else {
        $safeLen = strlen($safe);
        $userLen = strlen($user);
    }

    // Set the result to the difference between the lengths
    $result = $safeLen - $userLen;

    // Note that we ALWAYS iterate over the user-supplied length
    // This is to prevent leaking length information
    for ($i = 0; $i < $userLen; $i++) {
        // Using % here is a trick to prevent notices
        // It's safe, since if the lengths are different
        // $result is already non-0
        $result |= (ord($safe[$i % $safeLen]) ^ ord($user[$i]));
    }

    // They are only identical strings if $result is exactly 0...
    return $result === 0;
}

How to compile multiple java source files in command line

Here is another example, for compiling a java file in a nested directory.

I was trying to build this from the command line. This is an example from 'gradle', which has dependency 'commons-collection.jar'. For more info, please see 'gradle: java quickstart' example. -- of course, you would use the 'gradle' tools to build it. But i thought to extend this example, for a nested java project, with a dependent jar.

Note: You need the 'gradle binary or source' distribution for this, example code is in: 'samples/java/quickstart'

% mkdir -p temp/classes
% curl --get \
    http://central.maven.org/maven2/commons-collections/commons-collections/3.2.2/commons-collections-3.2.2.jar \
        --output commons-collections-3.2.2.jar

% javac -g -classpath commons-collections-3.2.2.jar \
     -sourcepath src/main/java -d temp/classes \
      src/main/java/org/gradle/Person.java 

% jar cf my_example.jar -C temp/classes org/gradle/Person.class
% jar tvf my_example.jar
   0 Wed Jun 07 14:11:56 CEST 2017 META-INF/
  69 Wed Jun 07 14:11:56 CEST 2017 META-INF/MANIFEST.MF
 519 Wed Jun 07 13:58:06 CEST 2017 org/gradle/Person.class

Using reflection in Java to create a new instance with the reference variable type set to the new instance class name?

//====Single Class Reference used to retrieve object for fields and initial values. Performance enhancing only====          
Class<?>    reference           =   vector.get(0).getClass();
Object      obj                 =   reference.newInstance();
Field[]     objFields           =   obj.getClass().getFields(); 

Where does error CS0433 "Type 'X' already exists in both A.dll and B.dll " come from?

Look at the Inherits tag of all your aspx pages and master pages. Chances are there are two partial classes that have the same name. Change one and recompile.

Here is some more info:

http://blogs.msdn.com/b/carloc/archive/2007/06/12/compiler-error-message-cs0433-in-asp-net-2-0.aspx

How to copy a huge table data into another table in SQL Server

I have been working with our DBA to copy an audit table with 240M rows to another database.

Using a simple select/insert created a huge tempdb file.

Using a the Import/Export wizard worked but copied 8M rows in 10min

Creating a custom SSIS package and adjusting settings copied 30M rows in 10Min

The SSIS package turned out to be the fastest and most efficent for our purposes

Earl

R solve:system is exactly singular

I guess your code uses somewhere in the second case a singular matrix (i.e. not invertible), and the solve function needs to invert it. This has nothing to do with the size but with the fact that some of your vectors are (probably) colinear.

How to kill a child process by the parent process?

Send a SIGTERM or a SIGKILL to it:

http://en.wikipedia.org/wiki/SIGKILL

http://en.wikipedia.org/wiki/SIGTERM

SIGTERM is polite and lets the process clean up before it goes, whereas, SIGKILL is for when it won't listen >:)

Example from the shell (man page: http://unixhelp.ed.ac.uk/CGI/man-cgi?kill )

kill -9 pid

In C, you can do the same thing using the kill syscall:

kill(pid, SIGKILL);

See the following man page: http://linux.die.net/man/2/kill

Check if a String contains numbers Java

The code below is enough for "Check if a String contains numbers in Java"

Pattern p = Pattern.compile("([0-9])");
Matcher m = p.matcher("Here is ur string");

if(m.find()){
    System.out.println("Hello "+m.find());
}

#1214 - The used table type doesn't support FULLTEXT indexes

Before MySQL 5.6 Full-Text Search is supported only with MyISAM Engine.

Therefore either change the engine for your table to MyISAM

CREATE TABLE gamemech_chat (
  id bigint(20) unsigned NOT NULL auto_increment,
  from_userid varchar(50) NOT NULL default '0',
  to_userid varchar(50) NOT NULL default '0',
  text text NOT NULL,
  systemtext text NOT NULL,
  timestamp datetime NOT NULL default '0000-00-00 00:00:00',
  chatroom bigint(20) NOT NULL default '0',
  PRIMARY KEY  (id),
  KEY from_userid (from_userid),
  FULLTEXT KEY from_userid_2 (from_userid),
  KEY chatroom (chatroom),
  KEY timestamp (timestamp)
) ENGINE=MyISAM;

Here is SQLFiddle demo

or upgrade to 5.6 and use InnoDB Full-Text Search.

How to use ArgumentCaptor for stubbing?

Assuming the following method to test:

public boolean doSomething(SomeClass arg);

Mockito documentation says that you should not use captor in this way:

when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
assertThat(argumentCaptor.getValue(), equalTo(expected));

Because you can just use matcher during stubbing:

when(someObject.doSomething(eq(expected))).thenReturn(true);

But verification is a different story. If your test needs to ensure that this method was called with a specific argument, use ArgumentCaptor and this is the case for which it is designed:

ArgumentCaptor<SomeClass> argumentCaptor = ArgumentCaptor.forClass(SomeClass.class);
verify(someObject).doSomething(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), equalTo(expected));

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

That method was added in Servlet 2.5.

So this problem can have at least 3 causes:

  1. The servlet container does not support Servlet 2.5.
  2. The web.xml is not declared conform Servlet 2.5 or newer.
  3. The webapp's runtime classpath is littered with servlet container specific JAR files of a different servlet container make/version which does not support Servlet 2.5.

To solve it,

  1. Make sure that your servlet container supports at least Servlet 2.5. That are at least Tomcat 6, Glassfish 2, JBoss AS 4.1, etcetera. Tomcat 5.5 for example supports at highest Servlet 2.4. If you can't upgrade Tomcat, then you'd need to downgrade Spring to a Servlet 2.4 compatible version.
  2. Make sure that the root declaration of web.xml complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.
  3. Make sure that you don't have any servlet container specific libraries like servlet-api.jar or j2ee.jar in /WEB-INF/lib or even worse, the JRE/lib or JRE/lib/ext. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.

How to make a page redirect using JavaScript?

You can call a JavaScript function and use window.location = 'url';:

http://www.pageresource.com/jscript/jredir.htm

Copying data from one SQLite database to another

You'll have to attach Database X with Database Y using the ATTACH command, then run the appropriate Insert Into commands for the tables you want to transfer.

INSERT INTO X.TABLE SELECT * FROM Y.TABLE;

Or, if the columns are not matched up in order:

INSERT INTO X.TABLE(fieldname1, fieldname2) SELECT fieldname1, fieldname2 FROM Y.TABLE;

HttpURLConnection timeout settings

If the HTTP Connection doesn't timeout, You can implement the timeout checker in the background thread itself (AsyncTask, Service, etc), the following class is an example for Customize AsyncTask which timeout after certain period

public abstract class AsyncTaskWithTimer<Params, Progress, Result> extends
    AsyncTask<Params, Progress, Result> {

private static final int HTTP_REQUEST_TIMEOUT = 30000;

@Override
protected Result doInBackground(Params... params) {
    createTimeoutListener();
    return doInBackgroundImpl(params);
}

private void createTimeoutListener() {
    Thread timeout = new Thread() {
        public void run() {
            Looper.prepare();

            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {

                    if (AsyncTaskWithTimer.this != null
                            && AsyncTaskWithTimer.this.getStatus() != Status.FINISHED)
                        AsyncTaskWithTimer.this.cancel(true);
                    handler.removeCallbacks(this);
                    Looper.myLooper().quit();
                }
            }, HTTP_REQUEST_TIMEOUT);

            Looper.loop();
        }
    };
    timeout.start();
}

abstract protected Result doInBackgroundImpl(Params... params);
}

A Sample for this

public class AsyncTaskWithTimerSample extends AsyncTaskWithTimer<Void, Void, Void> {

    @Override
    protected void onCancelled(Void void) {
        Log.d(TAG, "Async Task onCancelled With Result");
        super.onCancelled(result);
    }

    @Override
    protected void onCancelled() {
        Log.d(TAG, "Async Task onCancelled");
        super.onCancelled();
    }

    @Override
    protected Void doInBackgroundImpl(Void... params) {
        // Do background work
        return null;
    };
 }

PIL image to array (numpy array to array) - Python

I highly recommend you use the tobytes function of the Image object. After some timing checks this is much more efficient.

def jpg_image_to_array(image_path):
  """
  Loads JPEG image into 3D Numpy array of shape 
  (width, height, channels)
  """
  with Image.open(image_path) as image:         
    im_arr = np.fromstring(image.tobytes(), dtype=np.uint8)
    im_arr = im_arr.reshape((image.size[1], image.size[0], 3))                                   
  return im_arr

The timings I ran on my laptop show

In [76]: %timeit np.fromstring(im.tobytes(), dtype=np.uint8)
1000 loops, best of 3: 230 µs per loop

In [77]: %timeit np.array(im.getdata(), dtype=np.uint8)
10 loops, best of 3: 114 ms per loop

```

Storing a file in a database as opposed to the file system?

Have a look at this answer:

Storing Images in DB - Yea or Nay?

Essentially, the space and performance hit can be quite big, depending on the number of users. Also, keep in mind that Web servers are cheap and you can easily add more to balance the load, whereas the database is the most expensive and hardest to scale part of a web architecture usually.

There are some opposite examples (e.g., Microsoft Sharepoint), but usually, storing files in the database is not a good idea.

Unless possibly you write desktop apps and/or know roughly how many users you will ever have, but on something as random and unexpectable like a public web site, you may pay a high price for storing files in the database.

Python: Finding differences between elements of a list

Ok. I think I found the proper solution:

v = [x[0]-x[1] for x in zip(t[1:],t[:-1])]

How can I use grep to show just filenames on Linux?

Your question How can I just get the file-names (with paths)

Your syntax example find . -iname "*php" -exec grep -H myString {} \;

My Command suggestion

sudo find /home -name *.php

The output from this command on my Linux OS:

compose-sample-3/html/mail/contact_me.php

As you require the filename with path, enjoy!

python filter list of dictionaries based on key value

Use filter, or if the number of dictionaries in exampleSet is too high, use ifilter of the itertools module. It would return an iterator, instead of filling up your system's memory with the entire list at once:

from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
    print elem

How to use SharedPreferences in Android to store, fetch and edit values

Setting values in Preference:

// MY_PREFS_NAME - a static String variable like: 
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
 editor.putString("name", "Elena");
 editor.putInt("idName", 12);
 editor.commit();

Retrieve data from preference:

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
  String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
  int idName = prefs.getInt("idName", 0); //0 is the default value.
}

more info:

Using Shared Preferences

Shared Preferences

How to open a link in new tab using angular?

In the app-routing.modules.ts file:

{
    path: 'hero/:id', component: HeroComponent
}

In the component.html file:

target="_blank" [routerLink]="['/hero', '/sachin']"

How to dynamically add a class to manual class names?

If you need style names which should appear according to the state condition, I prefer to use this construction:

<div className={'wrapper searchDiv' + (this.state.something === "a" ? " anotherClass" : "")'}>

AngularJS - add HTML element to dom in directive without jQuery

Why not to try simple (but powerful) html() method:

iElement.html('<svg width="600" height="100" class="svg"></svg>');

Or append as an alternative:

iElement.append('<svg width="600" height="100" class="svg"></svg>');

And , of course , more cleaner way:

 var svg = angular.element('<svg width="600" height="100" class="svg"></svg>');
 iElement.append(svg);

Fiddle: http://jsfiddle.net/cherniv/AgGwK/

How do I extract a substring from a string until the second space is encountered?

I was thinking about this problem for my own code and even though I probably will end up using something simpler/faster, here's another Linq solution that's similar to one that @Francisco added.

I just like it because it reads the most like what you actually want to do: "Take chars while the resulting substring has fewer than 2 spaces."

string input = "o1 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467";
var substring = input.TakeWhile((c0, index) => 
                                input.Substring(0, index + 1).Count(c => c == ' ') < 2);
string result = new String(substring.ToArray());

Spring Data JPA and Exists query

You can use Case expression for returning a boolean in your select query like below.

@Query("SELECT CASE WHEN count(e) > 0 THEN true ELSE false END FROM MyEntity e where e.my_column = ?1")

How to get the connection String from a database

On connectionstrings.com you can find the connection string for every DB provider. A connection string is built up with certain attributes/properties and their values. For SQL server 2008, it looks like this (standard, which is what you'll need here):

Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;

on myServerAddress, write the name of your installed instance (by default it's .\SQLEXPRESS for SQL Server Express edition). Initial catalog = your database name, you'll see it in SSMS on the left after connecting. The rest speaks for itself.

edit

You will need to omit username and password for windows authentication and add Integrated Security=SSPI.

How to change value of object which is inside an array using JavaScript or jQuery?

Here i am using angular js. In javascript you can use for loop to find.

    if($scope.bechval>0 &&$scope.bechval!=undefined)
    {

                angular.forEach($scope.model.benhmarkghamlest, function (val, key) {
                $scope.model.benhmarkghamlest[key].bechval = $scope.bechval;

            });
    }
    else {
        alert("Please sepecify Bechmark value");
    }

Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using pure JS version

Unfortunately, All the above answers are only half right.. Took a long time to figure this out..

Mongoose bson install via npm throws warning and causes the error...

npm install -g node-gyp

git clone https://github.com/mongodb/js-bson.git
cd js-bson
npm install
node-gyp rebuild

This works like magic!!

Increasing the timeout value in a WCF service

Are you referring to the server side or the client side?

For a client, you would want to adjust the sendTimeout attribute of a binding element. For a service, you would want to adjust the receiveTimeout attribute of a binding elemnent.

<system.serviceModel>
  <bindings>
    <netTcpBinding>
      <binding name="longTimeoutBinding"
        receiveTimeout="00:10:00" sendTimeout="00:10:00">
        <security mode="None"/>
      </binding>
    </netTcpBinding>
  </bindings>

  <services>
    <service name="longTimeoutService"
      behaviorConfiguration="longTimeoutBehavior">
      <endpoint address="net.tcp://localhost/longtimeout/"
        binding="netTcpBinding" bindingConfiguration="longTimeoutBinding" />
    </service>
....

Of course, you have to map your desired endpoint to that particular binding.

How do I print the percent sign(%) in c

Try printing out this way

printf("%%");

How to find index position of an element in a list when contains returns true

int indexOf(Object o) This method returns the index in this list of the first occurrence of the specified element, or -1 if this list does not contain this element.

How to load a resource bundle from a file resource in Java?

From the JavaDocs for ResourceBundle.getBundle(String baseName):

baseName - the base name of the resource bundle, a fully qualified class name

What this means in plain English is that the resource bundle must be on the classpath and that baseName should be the package containing the bundle plus the bundle name, mybundle in your case.

Leave off the extension and any locale that forms part of the bundle name, the JVM will sort that for you according to default locale - see the docs on java.util.ResourceBundle for more info.

com.apple.WebKit.WebContent drops 113 error: Could not find specified service

Perhaps the below method could be the cause if you've set it to

func webView(_ webView: WebView!,decidePolicyForNavigationAction actionInformation: [AnyHashable : Any]!, request: URLRequest!, frame: WebFrame!, decisionListener listener: WebPolicyDecisionListener!) 

ends with

decisionHandler(.cancel)

for the default navigationAction.request.url

Hope it works!

Hibernate JPA Sequence (non-Id)

If you are using postgresql
And i'm using in spring boot 1.5.6

@Column(columnDefinition = "serial")
@Generated(GenerationTime.INSERT)
private Integer orderID;

Creating a blocking Queue<T> in .NET?

You can use the BlockingCollection and ConcurrentQueue in the System.Collections.Concurrent Namespace

 public class ProducerConsumerQueue<T> : BlockingCollection<T>
{
    /// <summary>
    /// Initializes a new instance of the ProducerConsumerQueue, Use Add and TryAdd for Enqueue and TryEnqueue and Take and TryTake for Dequeue and TryDequeue functionality
    /// </summary>
    public ProducerConsumerQueue()  
        : base(new ConcurrentQueue<T>())
    {
    }

  /// <summary>
  /// Initializes a new instance of the ProducerConsumerQueue, Use Add and TryAdd for Enqueue and TryEnqueue and Take and TryTake for Dequeue and TryDequeue functionality
  /// </summary>
  /// <param name="maxSize"></param>
    public ProducerConsumerQueue(int maxSize)
        : base(new ConcurrentQueue<T>(), maxSize)
    {
    }



}

How to sort an array of objects by multiple fields?

Sorting on two date fields and a numeric field example:

var generic_date =  new Date(2070, 1, 1);
checkDate = function(date) {
  return Date.parse(date) ? new Date(date): generic_date;
}

function sortData() {  
  data.sort(function(a,b){
    var deltaEnd = checkDate(b.end) - checkDate(a.end);
    if(deltaEnd) return deltaEnd;

    var deltaRank = a.rank - b.rank;
    if (deltaRank) return deltaRank;

    var deltaStart = checkDate(b.start) - checkDate(a.start);
    if(deltaStart) return deltaStart;

    return 0;
  });
}

http://jsfiddle.net/hcWgf/57/

How does one make random number between range for arc4random_uniform()?

I've made an Int type extension. tested it in playground, hope this is useful. It also accepts negative ranges:

extension Int
{
    static func random(range: Range<Int> ) -> Int
    {
        var offset = 0

        if range.startIndex < 0   // allow negative ranges
        {
            offset = abs(range.startIndex)
        }

        let mini = UInt32(range.startIndex + offset)
        let maxi = UInt32(range.endIndex   + offset)

        return Int(mini + arc4random_uniform(maxi - mini)) - offset
    }
}

use like

var aRandomInt = Int.random(-500...100)  // returns a random number within the given range.

or define it as a Range extension as property like this:

extension Range
{
    var randomInt: Int
    {
        get
        {
            var offset = 0

            if (startIndex as Int) < 0   // allow negative ranges
            {
                offset = abs(startIndex as Int)
            }

            let mini = UInt32(startIndex as Int + offset)
            let maxi = UInt32(endIndex   as Int + offset)

            return Int(mini + arc4random_uniform(maxi - mini)) - offset
        }
    }
}

// usage example: get an Int within the given Range:
let nr = (-1000 ... 1100).randomInt

Why would an Enum implement an Interface?

The post above that mentioned strategies didn't stress enough what a nice lightweight implementation of the strategy pattern using enums gets you:

public enum Strategy {

  A {
    @Override
    void execute() {
      System.out.print("Executing strategy A");
    }
  },

  B {
    @Override
    void execute() {
      System.out.print("Executing strategy B");
    }
  };

  abstract void execute();
}

You can have all your strategies in one place without needing a separate compilation unit for each. You get a nice dynamic dispatch just with:

Strategy.valueOf("A").execute();

Makes java read almost like a nice loosely typed language!

New lines (\r\n) are not working in email body

Using <BR> is not allways enough. MS Outlook 2007 will ignore this if you dont tell outlook that it is a selfclosing html tag by using

 <BR />

Relative imports in Python 3

TLDR; Append Script path to the System Path by adding following in the entry point of your python script.

import os.path
import sys
PACKAGE_PARENT = '..'
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))

Thats it now you can run your project in PyCharma as well as from Terminal!!

Easy way to turn JavaScript array into comma-separated list?

There are many methods to convert an array to comma separated list

1. Using array#join

From MDN

The join() method joins all elements of an array (or an array-like object) into a string.

The code

var arr = ["this","is","a","comma","separated","list"];
arr = arr.join(",");

Snippet

_x000D_
_x000D_
var arr = ["this", "is", "a", "comma", "separated", "list"];_x000D_
arr = arr.join(",");_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

2. Using array#toString

From MDN

The toString() method returns a string representing the specified array and its elements.

The code

var arr = ["this","is","a","comma","separated","list"];
arr = arr.toString();

Snippet

_x000D_
_x000D_
var arr = ["this", "is", "a", "comma", "separated", "list"];_x000D_
arr = arr.toString();_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

3. Add []+ before array or +[] after an array

The []+ or +[] will convert it into a string

Proof

([]+[] === [].toString())

will output true

_x000D_
_x000D_
console.log([]+[] === [].toString());
_x000D_
_x000D_
_x000D_

var arr = ["this","is","a","comma","separated","list"];
arr = []+arr;

Snippet

_x000D_
_x000D_
var arr = ["this", "is", "a", "comma", "separated", "list"];_x000D_
arr = []+arr;_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

Also

var arr = ["this","is","a","comma","separated","list"];
arr = arr+[];

_x000D_
_x000D_
var arr = ["this", "is", "a", "comma", "separated", "list"];_x000D_
arr = arr + [];_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

Android custom Row Item for ListView

Step 1:Create a XML File

 <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">


        <ListView
            android:id="@+id/lvItems"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            />
    </LinearLayout>

Step 2:Studnet.java

package com.scancode.acutesoft.telephonymanagerapp;


public class Student
{
    String email,phone,address;

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

Step 3:MainActivity.java

 package com.scancode.acutesoft.telephonymanagerapp;

    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.ListView;

    import java.util.ArrayList;

    public class MainActivity extends Activity  {

        ListView lvItems;
        ArrayList<Student> studentArrayList ;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            lvItems = (ListView) findViewById(R.id.lvItems);
            studentArrayList = new ArrayList<Student>();
            dataSaving();
            CustomAdapter adapter = new CustomAdapter(MainActivity.this,studentArrayList);
            lvItems.setAdapter(adapter);
        }

        private void dataSaving() {

            Student student = new Student();
            student.setEmail("[email protected]");
            student.setPhone("1234567890");
            student.setAddress("Hyderabad");
            studentArrayList.add(student);


            student = new Student();
            student.setEmail("[email protected]");
            student.setPhone("1234567890");
            student.setAddress("Banglore");
            studentArrayList.add(student);

            student = new Student();
            student.setEmail("[email protected]");
            student.setPhone("1234567890");
            student.setAddress("Banglore");
            studentArrayList.add(student);

            student = new Student();
            student.setEmail("[email protected]");
            student.setPhone("1234567890");
            student.setAddress("Banglore");
            studentArrayList.add(student);
        }


    }

Step 4:CustomAdapter.java

  package com.scancode.acutesoft.telephonymanagerapp;

    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.TextView;

    import java.util.ArrayList;


    public class CustomAdapter extends BaseAdapter
    {
        ArrayList<Student> studentList;
        Context mContext;


        public CustomAdapter(Context context, ArrayList<Student> studentArrayList) {
            this.mContext = context;
            this.studentList = studentArrayList;

        }

        @Override
        public int getCount() {
            return studentList.size();
        }
        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            Student student = studentList.get(position);
            convertView = LayoutInflater.from(mContext).inflate(R.layout.student_row,null);

            TextView tvStudEmail = (TextView) convertView.findViewById(R.id.tvStudEmail);
            TextView tvStudPhone = (TextView) convertView.findViewById(R.id.tvStudPhone);
            TextView tvStudAddress = (TextView) convertView.findViewById(R.id.tvStudAddress);

            tvStudEmail.setText(student.getEmail());
            tvStudPhone.setText(student.getPhone());
            tvStudAddress.setText(student.getAddress());


            return convertView;
        }
    }

How to add footnotes to GitHub-flavoured Markdown?

Although I am not aware if it's officially documented anywhere, you can do footer notes in Github.

  1. Mark the place where you want to insert footer link with a number enclosed in square brackets, I.E. [1]

  2. On the bottom of the post, make a reference of the numbered marker and followed by a colon and the link, I.E. [1]: http://www.example.com/link1

And once you preview it, it will be rendered as numbered links in the body of the post.

How to take screenshot of a div with JavaScript?

If you wish to have "Save as" dialog, just pass image into php script, which adds appropriate headers

Example "all-in-one" script script.php

<?php if(isset($_GET['image'])):
    $image = $_GET['image'];

    if(preg_match('#^data:image/(.*);base64,(.*)$#s', $image, $match)){
        $base64 = $match[2];
        $imageBody = base64_decode($base64);
        $imageFormat = $match[1];

        header('Content-type: application/octet-stream');
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private", false); // required for certain browsers
        header("Content-Disposition: attachment; filename=\"file.".$imageFormat."\";" ); //png is default for toDataURL
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: ".strlen($imageBody));
        echo $imageBody;
    }
    exit();
endif;?>

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js?ver=1.7.2'></script>
<canvas id="canvas" width="300" height="150"></canvas>
<button id="btn">Save</button>
<script>
    $(document).ready(function(){
        var canvas = document.getElementById('canvas');
        var oCtx = canvas.getContext("2d");
        oCtx.beginPath();
        oCtx.moveTo(0,0);
        oCtx.lineTo(300,150);
        oCtx.stroke();

        $('#btn').on('click', function(){
            // opens dialog but location doesnt change due to SaveAs Dialog
            document.location.href = '/script.php?image=' + canvas.toDataURL();
        });
    });
</script>

How to skip the first n rows in sql query

In order to do this in SQL Server, you must order the query by a column, so you can specify the rows you want.

Example:

select * from table order by [some_column] 
offset 10 rows
FETCH NEXT 10 rows only

How to reset (clear) form through JavaScript?

You can simply do:

$("#client.frm").trigger('reset')

Directory index forbidden by Options directive

Adding this in conf.d fixed this issue for me.

Options +Indexes +FollowSymLinks

Has been compiled by a more recent version of the Java Runtime (class file version 57.0)

The problem is that you compiled the code with java 13 (class file 57), and the java runtime is set to java 8 (class file 52).

Assuming you have the JRE 13 installed in your local system, you could change your runtime from 52 to 57. That you can do with the plugin Choose Runtime. To install it go to File/Settings/Plugins

enter image description here

Once installed go to Help/Find Action, type "runtime" and select the jre 13 from the dropdown menu.

enter image description here

Right way to reverse a pandas DataFrame?

data.reindex(index=data.index[::-1])

or simply:

data.iloc[::-1]

will reverse your data frame, if you want to have a for loop which goes from down to up you may do:

for idx in reversed(data.index):
    print(idx, data.loc[idx, 'Even'], data.loc[idx, 'Odd'])

or

for idx in reversed(data.index):
    print(idx, data.Even[idx], data.Odd[idx])

You are getting an error because reversed first calls data.__len__() which returns 6. Then it tries to call data[j - 1] for j in range(6, 0, -1), and the first call would be data[5]; but in pandas dataframe data[5] means column 5, and there is no column 5 so it will throw an exception. ( see docs )

Move cursor to end of file in vim

No need to explicitly go to the end of line before doing a, use A;
Append text at the end of line [count] times

<ESC>GA

sort files by date in PHP

You need to put the files into an array in order to sort and find the last modified file.

$files = array();
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
           $files[filemtime($file)] = $file;
        }
    }
    closedir($handle);

    // sort
    ksort($files);
    // find the last modification
    $reallyLastModified = end($files);

    foreach($files as $file) {
        $lastModified = date('F d Y, H:i:s',filemtime($file));
        if(strlen($file)-strpos($file,".swf")== 4){
           if ($file == $reallyLastModified) {
             // do stuff for the real last modified file
           }
           echo "<tr><td><input type=\"checkbox\" name=\"box[]\"></td><td><a href=\"$file\" target=\"_blank\">$file</a></td><td>$lastModified</td></tr>";
        }
    }
}

Not tested, but that's how to do it.

Calculating arithmetic mean (one type of average) in Python

The proper answer to your question is to use statistics.mean. But for fun, here is a version of mean that does not use the len() function, so it (like statistics.mean) can be used on generators, which do not support len():

from functools import reduce
from operator import truediv
def ave(seq):
    return truediv(*reduce(lambda a, b: (a[0] + b[1], b[0]), 
                           enumerate(seq, start=1), 
                           (0, 0)))

What does "static" mean in C?

Static variables in C have the lifetime of the program.

If defined in a function, they have local scope, i.e. they can be accessed only inside those functions. The value of static variables is preserved between function calls.

For example:

void function()
{
    static int var = 1;
    var++;
    printf("%d", var);
}

int main()
{
    function(); // Call 1
    function(); // Call 2
}

In the above program, var is stored in the data segment. Its lifetime is the whole C program.

After function call 1, var becomes 2. After function call 2, var becomes 3.

The value of var is not destroyed between functions calls.

If var had between non static and local variable, it would be stored in the stack segment in the C program. Since the stack frame of the function is destroyed after the function returns, the value of var is also destroyed.

Initialized static variables are stored in the data segment of the C program whereas uninitialized ones are stored in the BSS segment.

Another information about static: If a variable is global and static, it has the life time of the C program, but it has file scope. It is visible only in that file.

To try this:

file1.c

static int x;

int main()
{
    printf("Accessing in same file%d", x):
}

file2.c

    extern int x;
    func()
    {
        printf("accessing in different file %d",x); // Not allowed, x has the file scope of file1.c
    }

run gcc -c file1.c

gcc -c file2.c

Now try to link them using:

gcc -o output file1.o file2.o

It would give a linker error as x has the file scope of file1.c and the linker would not be able to resolve the reference to variable x used in file2.c.

References:

  1. http://en.wikipedia.org/wiki/Translation_unit_(programming)
  2. http://en.wikipedia.org/wiki/Call_stack

from list of integers, get number closest to a given value

>>> takeClosest = lambda num,collection:min(collection,key=lambda x:abs(x-num))
>>> takeClosest(5,[4,1,88,44,3])
4

A lambda is a special way of writing an "anonymous" function (a function that doesn't have a name). You can assign it any name you want because a lambda is an expression.

The "long" way of writing the the above would be:

def takeClosest(num,collection):
   return min(collection,key=lambda x:abs(x-num))

JDK on OSX 10.7 Lion

You can download the 10.7 Lion JDK from http://connect.apple.com.

  1. Sign in and click the java section on the right.

  2. The jdk is installed into a different location then previous. This will result in IDEs (such as Eclipse) being unable to locate source code and javadocs.

  3. At the time of writing the JDK ended up here:

    /Library/Java/JavaVirtualMachines/1.6.0_26-b03-383.jdk/Contents/Home

  4. Open up eclipse preferences and go to Java --> Installed JREs page

  5. Rather than use the "JVM Contents (MacOS X Default) we will need to use the JDK location

  6. At the time of writing Search is not aware of the new JDK location; we we will need to click on the Add button

  7. From the Add JRE wizard choose "MacOS X VM" for the JRE Type

  8. For the JRE Definition Page we need to fill in the following:

    • JRE Home: /Library/Java/JavaVirtualMachines/1.6.0_26-b03-383.jdk/Contents/Home
  9. The other fields will now auto fill, with the default JRE name being "Home". You can quickly correct this to something more meaningful:

    • JRE name: System JDK
  10. Finish the wizard and return to the Installed JREs page

  11. Choose "System JDK" from the list

  12. You can now develop normally with:

    • javadocs correctly shown for base classes
    • source code correctly shown when debugging

What is the meaning of the word logits in TensorFlow?

Personal understanding, in TensorFlow domain, logits are the values to be used as input to softmax. I came to this understanding based on this tensorflow tutorial.

https://www.tensorflow.org/tutorials/layers


Although it is true that logit is a function in maths(especially in statistics), I don't think that's the same 'logit' you are looking at. In the book Deep Learning by Ian Goodfellow, he mentioned,

The function s-1(x) is called the logit in statistics, but this term is more rarely used in machine learning. s-1(x) stands for the inverse function of logistic sigmoid function.

In TensorFlow, it is frequently seen as the name of last layer. In Chapter 10 of the book Hands-on Machine Learning with Scikit-learn and TensorFLow by Aurélien Géron, I came across this paragraph, which stated logits layer clearly.

note that logits is the output of the neural network before going through the softmax activation function: for optimization reasons, we will handle the softmax computation later.

That is to say, although we use softmax as the activation function in the last layer in our design, for ease of computation, we take out logits separately. This is because it is more efficient to calculate softmax and cross-entropy loss together. Remember that cross-entropy is a cost function, not used in forward propagation.

Suppress console output in PowerShell

Try redirecting the output to Out-Null. Like so,

$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose | out-null

How to round the double value to 2 decimal points?

This would do it.

     public static void main(String[] args) {
        double d = 12.349678;
        int r = (int) Math.round(d*100);
        double f = r / 100.0;
       System.out.println(f);
     }

You can short this method, it's easy to understand that's why I have written like this.

How to load assemblies in PowerShell?

Make sure you have below features are installed in order

  1. Microsoft System CLR Types for SQL Server
  2. Microsoft SQL Server Shared Management Objects
  3. Microsoft Windows PowerShell Extensions

Also you may need to load

Add-Type -Path "C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies\Microsoft.SqlServer.Smo.dll"
Add-Type -Path "C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies\Microsoft.SqlServer.SqlWmiManagement.dll"

What is the difference between declarations, providers, and import in NgModule?

Components are declared, Modules are imported, and Services are provided. An example I'm working with:

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


import { AppComponent } from './app.component';
import {FormsModule} from '@angular/forms';
import { UserComponent } from './components/user/user.component';
import { StateService } from './services/state.service';    

@NgModule({
  declarations: [
    AppComponent,
    UserComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [ StateService ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

Returning value from Thread

Using Future described in above answers does the job, but a bit less significantly as f.get(), blocks the thread until it gets the result, which violates concurrency.

Best solution is to use Guava's ListenableFuture. An example :

    ListenableFuture<Void> future = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(1, new NamedThreadFactory).submit(new Callable<Void>()
    {
        @Override
        public Void call() throws Exception
        {
            someBackgroundTask();
        }
    });
    Futures.addCallback(future, new FutureCallback<Long>()
    {
        @Override
        public void onSuccess(Long result)
        {
            doSomething();
        }

        @Override
        public void onFailure(Throwable t)
        {

        }
    };

How to insert a row between two rows in an existing excel with HSSF (Apache POI)

Referencing Qwerty's answer, if the destRow isnot null, sheet.shiftRows() will change the destRow's reference to the next row; so we should always create a new row:

if (destRow != null) {
  sheet.shiftRows(destination, sheet.getLastRowNum(), 1);
}
destRow = sheet.createRow(destination);

Android: upgrading DB version and adding new table

Your code looks correct. My suggestion is that the database already thinks it's upgraded. If you executed the project after incrementing the version number, but before adding the execSQL call, the database on your test device/emulator may already believe it's at version 2.

A quick way to verify this would be to change the version number to 3 -- if it upgrades after that, you know it was just because your device believed it was already upgraded.

Blur or dim background when Android PopupWindow active

Another trick is to use 2 popup windows instead of one. The 1st popup window will simply be a dummy view with translucent background which provides the dim effect. The 2nd popup window is your intended popup window.

Sequence while creating pop up windows: Show the dummy pop up window 1st and then the intended popup window.

Sequence while destroying: Dismiss the intended pop up window and then the dummy pop up window.

The best way to link these two is to add an OnDismissListener and override the onDismiss() method of the intended to dimiss the dummy popup window from their.

Code for the dummy popup window:

fadepopup.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
    android:id="@+id/fadePopup"
    android:background="#AA000000">
</LinearLayout>

Show fade popup to dim the background

private PopupWindow dimBackground() {

    LayoutInflater inflater = (LayoutInflater) EPGGRIDActivity.this
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View layout = inflater.inflate(R.layout.fadepopup,
            (ViewGroup) findViewById(R.id.fadePopup));
    PopupWindow fadePopup = new PopupWindow(layout, windowWidth, windowHeight, false);
    fadePopup.showAtLocation(layout, Gravity.NO_GRAVITY, 0, 0);
    return fadePopup;
}

There has been an error processing your request, Error log record number

I encountered a problem like this and it turns out that I accidentally changed the permission of the var/cache folder. Just delete the cache folder so magento could automatically create the folder with the right permissions.

rm -rf root/var/cache

How to distinguish between left and right mouse click with jQuery

$.event.special.rightclick = {
    bindType: "contextmenu",
    delegateType: "contextmenu"
};

$(document).on("rightclick", "div", function() {
    console.log("hello");
    return false;
});

http://jsfiddle.net/SRX3y/8/

How to get multiple counts with one SQL query?

Based on Bluefeet's accepted response with an added nuance using OVER():

SELECT distributor_id,
    COUNT(*) total,
    SUM(case when level = 'exec' then 1 else 0 end) OVER() ExecCount,
    SUM(case when level = 'personal' then 1 else 0 end) OVER () PersonalCount
FROM yourtable
GROUP BY distributor_id

Using OVER() with nothing in the () will give you the total count for the whole dataset.

How to post data using HttpClient?

You need to use:

await client.PostAsync(uri, content);

Something like that:

var comment = "hello world";
var questionId = 1;

var formContent = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("comment", comment), 
    new KeyValuePair<string, string>("questionId", questionId) 
});

var myHttpClient = new HttpClient();
var response = await myHttpClient.PostAsync(uri.ToString(), formContent);

And if you need to get the response after post, you should use:

var stringContent = await response.Content.ReadAsStringAsync();

Hope it helps ;)

reading from app.config file

Just for the future reference, you just need to add System.Configuration to your references library:

enter image description here

Getting "file not found" in Bridging Header when importing Objective-C frameworks into Swift project

If using cocoapods, try reinstalling the pods by running the following command.

pod install

How to increase font size in a plot in R?

In case you want to increase the font of the labels of the histogram when setting labels=TRUE

bp=hist(values, labels = FALSE, 
 main='Histogram',
 xlab='xlab',ylab='ylab',  cex.main=2, cex.lab=2,cex.axis=2)

text(x=bp$mids, y=bp$counts, labels=bp$counts ,cex=2,pos=3)

how to print an exception using logger?

Use: LOGGER.log(Level.INFO, "Got an exception.", e);
or LOGGER.info("Got an exception. " + e.getMessage());

Select first 10 distinct rows in mysql

SELECT * 
FROM people 
WHERE names ='SMITH'
ORDER BY names asc
limit 10

If you need add group by clause. If you search Smith you would have to sort on something else.

Update row values where certain condition is met in pandas

You can do the same with .ix, like this:

In [1]: df = pd.DataFrame(np.random.randn(5,4), columns=list('abcd'))

In [2]: df
Out[2]: 
          a         b         c         d
0 -0.323772  0.839542  0.173414 -1.341793
1 -1.001287  0.676910  0.465536  0.229544
2  0.963484 -0.905302 -0.435821  1.934512
3  0.266113 -0.034305 -0.110272 -0.720599
4 -0.522134 -0.913792  1.862832  0.314315

In [3]: df.ix[df.a>0, ['b','c']] = 0

In [4]: df
Out[4]: 
          a         b         c         d
0 -0.323772  0.839542  0.173414 -1.341793
1 -1.001287  0.676910  0.465536  0.229544
2  0.963484  0.000000  0.000000  1.934512
3  0.266113  0.000000  0.000000 -0.720599
4 -0.522134 -0.913792  1.862832  0.314315

EDIT

After the extra information, the following will return all columns - where some condition is met - with halved values:

>> condition = df.a > 0
>> df[condition][[i for i in df.columns.values if i not in ['a']]].apply(lambda x: x/2)

I hope this helps!

Getting the client IP address: REMOTE_ADDR, HTTP_X_FORWARDED_FOR, what else could be useful?

Call the Below Action Method from your JS file (To get the ipv4 ip address).

    [HttpGet]
    public string GetIP()
    {
        IPAddress[] ipv4Addresses = Array.FindAll(
            Dns.GetHostEntry(string.Empty).AddressList,
            a => a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
        return ipv4Addresses.ToString();
    }

Check after keeping Breakpoint, and use as per your requirement. Its working fine for me.

Changing datagridview cell color dynamically

Implement your own extension of DataGridViewTextBoxCell and override Paint method like this:

class MyDataGridViewTextBoxCell : DataGridViewTextBoxCell
{
    protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex,
        DataGridViewElementStates cellState, object value, object formattedValue, string errorText,
        DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
    {
        if (value != null)
        {
            if ((bool) value)
            {
                cellStyle.BackColor = Color.LightGreen;
            }
            else
            {
                cellStyle.BackColor = Color.OrangeRed;
            }
        }
        base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value,
            formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
}

}

Then in the code set CellTemplate property of your column to instance of your class

columns.Add(new DataGridViewTextBoxColumn() {CellTemplate = new MyDataGridViewTextBoxCell()});

AngularJS : Factory and Service?

$provide service

They are technically the same thing, it's actually a different notation of using the provider function of the $provide service.

  • If you're using a class: you could use the service notation.
  • If you're using an object: you could use the factory notation.

The only difference between the service and the factory notation is that the service is new-ed and the factory is not. But for everything else they both look, smell and behave the same. Again, it's just a shorthand for the $provide.provider function.

// Factory

angular.module('myApp').factory('myFactory', function() {

  var _myPrivateValue = 123;

  return {
    privateValue: function() { return _myPrivateValue; }
  };

});

// Service

function MyService() {
  this._myPrivateValue = 123;
}

MyService.prototype.privateValue = function() {
  return this._myPrivateValue;
};

angular.module('myApp').service('MyService', MyService);

Java HttpRequest JSON & Response Handling

The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc

A set of simple examples:

Using Gson:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Gson {

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

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);
            String json = EntityUtils.toString(result.getEntity(), "UTF-8");

            com.google.gson.Gson gson = new com.google.gson.Gson();
            Response respuesta = gson.fromJson(json, Response.class);

            System.out.println(respuesta.getExample());
            System.out.println(respuesta.getFr());

        } catch (IOException ex) {
        }
        return null;
    }

    public class Response{

        private String example;
        private String fr;

        public String getExample() {
            return example;
        }
        public void setExample(String example) {
            this.example = example;
        }
        public String getFr() {
            return fr;
        }
        public void setFr(String fr) {
            this.fr = fr;
        }
    }
}

Using json-simple:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JsonSimple {

    public static void main(String[] args) {

    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);

            String json = EntityUtils.toString(result.getEntity(), "UTF-8");
            try {
                JSONParser parser = new JSONParser();
                Object resultObject = parser.parse(json);

                if (resultObject instanceof JSONArray) {
                    JSONArray array=(JSONArray)resultObject;
                    for (Object object : array) {
                        JSONObject obj =(JSONObject)object;
                        System.out.println(obj.get("example"));
                        System.out.println(obj.get("fr"));
                    }

                }else if (resultObject instanceof JSONObject) {
                    JSONObject obj =(JSONObject)resultObject;
                    System.out.println(obj.get("example"));
                    System.out.println(obj.get("fr"));
                }

            } catch (Exception e) {
                // TODO: handle exception
            }

        } catch (IOException ex) {
        }
        return null;
    }
}

etc...