Programs & Examples On #Android wake lock

How to pass a Javascript Array via JQuery Post so that all its contents are accessible via the PHP $_POST array?

This is fairly straightforward. In your JS, all you would do is this or something similar:

var array = ["thing1", "thing2", "thing3"];

var parameters = {
  "array1[]": array,
  ...
};

$.post(
  'your/page.php',
  parameters
)
.done(function(data, statusText) {
    // This block is optional, fires when the ajax call is complete
});

In your php page, the values in array form will be available via $_POST['array1'].

references

Mongoose: Get full list of users

There was the very easy way to list your data :

server.get('/userlist' , function (req , res) {
 User.find({}).then(function (users) {
 res.send(users);
 });
});

Sending Multipart File as POST parameters with RestTemplate requests

I had this issue and found a much simpler solution than using a ByteArrayResource.

Simply do

public void loadInvoices(MultipartFile invoices, String channel) throws IOException {

    init();

    Resource invoicesResource = invoices.getResource();

    LinkedMultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
    parts.add("file", invoicesResource);

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
    httpHeaders.set("channel", channel);

    HttpEntity<LinkedMultiValueMap<String, Object>> httpEntity = new HttpEntity<>(parts, httpHeaders);

    String url = String.format("%s/rest/inbound/invoices/upload", baseUrl);

    restTemplate.postForEntity(url, httpEntity, JobData.class);
}

It works, and no messing around with the file system or byte arrays.

How can I use Html.Action?

first, create a class to hold your parameters:

public class PkRk {
    public int pk { get; set; }
    public int rk { get; set; }
}

then, use the Html.Action passing the parameters:

Html.Action("PkRkAction", new { pkrk = new PkRk { pk=400, rk=500} })

and use in Controller:

public ActionResult PkRkAction(PkRk pkrk) {
    return PartialView(pkrk);
}

Travel/Hotel API's?

Check out api.hotelsbase.org - its a free xml hotel api No images as of yet though

How do I combine 2 javascript variables into a string

Use the concatenation operator +, and the fact that numeric types will convert automatically into strings:

var a = 1;
var b = "bob";
var c = b + a;

Trigger event on body load complete js/jquery

$(document).ready( function() { YOUR CODE HERE } )

Auto-indent spaces with C in vim?

I wrote all about tabs in vim, which gives a few interesting things you didn't ask about. To automatically indent braces, use:

:set cindent

To indent two spaces (instead of one tab of eight spaces, the vim default):

:set shiftwidth=2

To keep vim from converting eight spaces into tabs:

:set expandtab

If you ever want to change the indentation of a block of text, use < and >. I usually use this in conjunction with block-select mode (v, select a block of text, < or >).

(I'd try to talk you out of using two-space indentation, since I (and most other people) find it hard to read, but that's another discussion.)

How to install PyQt4 in anaconda?

It looks like the latest version of anaconda forces install of pyqt5.6 over any pyqt build, which will be fatal for your applications. In a terminal, Try:

conda install -c anaconda pyqt=4.11.4

It will prompt to downgrade conda client. After that, it should be good.

UPDATE: If you want to know what pyqt versions are available for install, try:

conda search pyqt

UPDATE: The most recent version of conda installs anaconda-navigator. This depends on qt5, and should first be removed:

conda uninstall anaconda-navigator

Then install "newest" qt4:

conda install qt=4

display data from SQL database into php/ html table

refer to http://www.w3schools.com/php/php_mysql_select.asp . If you are a beginner and want to learn, w3schools is a good place.

<?php
    $con=mysqli_connect("localhost","root","YOUR_PHPMYADMIN_PASSWORD","hrmwaitrose");
    // Check connection
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }

    $result = mysqli_query($con,"SELECT * FROM employee");

    while($row = mysqli_fetch_array($result))
      {
      echo $row['FirstName'] . " " . $row['LastName']; //these are the fields that you have stored in your database table employee
      echo "<br />";
      }

    mysqli_close($con);
    ?>

You can similarly echo it inside your table

<?php
 echo "<table>";
 while($row = mysqli_fetch_array($result))
          {
          echo "<tr><td>" . $row['FirstName'] . "</td><td> " . $row['LastName'] . "</td></tr>"; //these are the fields that you have stored in your database table employee
          }
 echo "</table>";
 mysqli_close($con);
?>

port 8080 is already in use and no process using 8080 has been listed

Open eclipse go to Servers panel, right click or press F3 to open Overview window and go to Ports (Modify the server ports). You will get the following:

tomcat adminport
HTTP/1.1
AJP/1.3

You can change the port numbers (e.g. HTTP/1.1 port number 8080 to 8082).

Convert Pixels to Points

Actually it must be

points = pixels * 96 / 72

How to pass a value from one jsp to another jsp page?

Use below code for passing string from one jsp to another jsp

A.jsp

   <% String userid="Banda";%>
    <form action="B.jsp" method="post">
    <%
    session.setAttribute("userId", userid);
        %>
        <input type="submit"
                            value="Login">
    </form>

B.jsp

    <%String userid = session.getAttribute("userId").toString(); %>
    Hello<%=userid%>

Inserting Data into Hive Table

It's a limitation of hive.

1.You cannot update data after it is inserted

2.There is no "insert into table values ... " statement

3.You can only load data using bulk load

4.There is not "delete from " command

5.You can only do bulk delete

But you still want to insert record from hive console than you can do select from statck. refer this

Automatic exit from Bash shell script on error

One idiom is:

cd some_dir && ./configure --some-flags && make && make install

I realize that can get long, but for larger scripts you could break it into logical functions.

Threads vs Processes in Linux

For most cases i would prefer processes over threads. threads can be useful when you have a relatively smaller task (process overhead >> time taken by each divided task unit) and there is a need of memory sharing between them. Think a large array. Also (offtopic), note that if your CPU utilization is 100 percent or close to it, there is going to be no benefit out of multithreading or processing. (in fact it will worsen)

How to detect responsive breakpoints of Twitter Bootstrap 3 using JavaScript?

Detect responsive breakpoint of Twitter Bootstrap 4.1.x using JavaScript

The Bootstrap v.4.0.0 (and the latest version Bootstrap 4.1.x) introduced the updated grid options, so the old concept on detection may not directly be applied (see the migration instructions):

  • Added a new sm grid tier below 768px for more granular control. We now have xs, sm, md, lg, and xl;
  • xs grid classes have been modified to not require the infix.

I written the small utility function that respects an updated grid class names and a new grid tier:

/**
 * Detect the current active responsive breakpoint in Bootstrap
 * @returns {string}
 * @author farside {@link https://stackoverflow.com/users/4354249/farside}
 */
function getResponsiveBreakpoint() {
    var envs = {xs:"d-none", sm:"d-sm-none", md:"d-md-none", lg:"d-lg-none", xl:"d-xl-none"};
    var env = "";

    var $el = $("<div>");
    $el.appendTo($("body"));

    for (var i = Object.keys(envs).length - 1; i >= 0; i--) {
        env = Object.keys(envs)[i];
        $el.addClass(envs[env]);
        if ($el.is(":hidden")) {
            break; // env detected
        }
    }
    $el.remove();
    return env;
};

Detect responsive breakpoint of Bootstrap v4-beta using JavaScript

The Bootstrap v4-alpha and Bootstrap v4-beta had different approach on grid breakpoints, so here's the legacy way of achieving the same:

/**
 * Detect and return the current active responsive breakpoint in Bootstrap
 * @returns {string}
 * @author farside {@link https://stackoverflow.com/users/4354249/farside}
 */
function getResponsiveBreakpoint() {
    var envs = ["xs", "sm", "md", "lg"];
    var env = "";

    var $el = $("<div>");
    $el.appendTo($("body"));

    for (var i = envs.length - 1; i >= 0; i--) {
        env = envs[i];
        $el.addClass("d-" + env + "-none");;
        if ($el.is(":hidden")) {
            break; // env detected
        }
    }
    $el.remove();
    return env;
}

I think it would be useful, as it's easy to integrate to any project. It uses native responsive display classes of the Bootstrap itself.

How do I download the Android SDK without downloading Android Studio?

What worked for me on Windows:

  1. Downloaded command line tools from https://developer.android.com/studio/index.html
  2. Put the whole tools folder from the ZIP archive to C:\Program Files (x86)\Android SDK\
  3. Launched tools\android.bat as administrator, which opened the usual SDK Manager window
  4. Installed required components. The files were downloaded to ...\Android SDK\ directory (that is build-tools, platforms, platform-tools, etc. directories appeared alongside tools inside ...\Android SDK\)
  5. Opened the Android project in Intellij IDEA, navigated to File->Project Structure->SDKs, and added Android SDK by directing to ...\Android SDK\ directory

How do I fix MSB3073 error in my post-build event?

In my case, the dll I was creating by building the project was still in use in the background. I killed the application and then xcopy worked fine as expected.

Iterate through object properties

Also adding the recursive way:

function iterate(obj) {
    // watch for objects we've already iterated so we won't end in endless cycle
    // for cases like var foo = {}; foo.bar = foo; iterate(foo);
    var walked = [];
    var stack = [{obj: obj, stack: ''}];
    while(stack.length > 0)
    {
        var item = stack.pop();
        var obj = item.obj;
        for (var property in obj) {
            if (obj.hasOwnProperty(property)) {
                if (typeof obj[property] == "object") {
                  // check if we haven't iterated through the reference yet
                  var alreadyFound = false;
                  for(var i = 0; i < walked.length; i++)
                  {
                    if (walked[i] === obj[property])
                    {
                      alreadyFound = true;
                      break;
                    }
                  }
                  // new object reference
                  if (!alreadyFound)
                  {
                    walked.push(obj[property]);
                    stack.push({obj: obj[property], stack: item.stack + '.' + property});
                  }
                }
                else
                {
                    console.log(item.stack + '.' + property + "=" + obj[property]);
                }
            }
        }
    }
}

Usage:

iterate({ foo: "foo", bar: { foo: "foo"} }); 

Why is printing "B" dramatically slower than printing "#"?

I performed tests on Eclipse vs Netbeans 8.0.2, both with Java version 1.8; I used System.nanoTime() for measurements.

Eclipse:

I got the same time on both cases - around 1.564 seconds.

Netbeans:

  • Using "#": 1.536 seconds
  • Using "B": 44.164 seconds

So, it looks like Netbeans has bad performance on print to console.

After more research I realized that the problem is line-wrapping of the max buffer of Netbeans (it's not restricted to System.out.println command), demonstrated by this code:

for (int i = 0; i < 1000; i++) {
    long t1 = System.nanoTime();
    System.out.print("BBB......BBB"); \\<-contain 1000 "B"
    long t2 = System.nanoTime();
    System.out.println(t2-t1);
    System.out.println("");
}

The time results are less then 1 millisecond every iteration except every fifth iteration, when the time result is around 225 millisecond. Something like (in nanoseconds):

BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
.
.
.

And so on..

Summary:

  1. Eclipse works perfectly with "B"
  2. Netbeans has a line-wrapping problem that can be solved (because the problem does not occur in eclipse)(without adding space after B ("B ")).

"%%" and "%/%" for the remainder and the quotient

Have a look at the examples below for a clearer understanding of the differences between the different operators:

> # Floating Division:
> 5/2
[1] 2.5
> 
> # Integer Division:
> 5%/%2
[1] 2
> 
> # Remainder:
> 5%%2
[1] 1

How to get a random number in Ruby

Don't forget to seed the RNG with srand() first.

How to use if-else option in JSTL

There is no if-else, just if.

<c:if test="${user.age ge 40}">
 You are over the hill.
</c:if>

Optionally you can use choose-when:

<c:choose>
  <c:when test="${a boolean expr}">
    do something
  </c:when>
  <c:when test="${another boolean expr}">
    do something else
  </c:when>
  <c:otherwise>
    do this when nothing else is true
  </c:otherwise>
</c:choose>

Lock, mutex, semaphore... what's the difference?

A lock allows only one thread to enter the part that's locked and the lock is not shared with any other processes.

A mutex is the same as a lock but it can be system wide (shared by multiple processes).

A semaphore does the same as a mutex but allows x number of threads to enter, this can be used for example to limit the number of cpu, io or ram intensive tasks running at the same time.

For a more detailed post about the differences between mutex and semaphore read here.

You also have read/write locks that allows either unlimited number of readers or 1 writer at any given time.

Get folder name of the file in Python

You could get the full path as a string then split it into a list using your operating system's separator character. Then you get the program name, folder name etc by accessing the elements from the end of the list using negative indices.

Like this:

import os
strPath = os.path.realpath(__file__)
print( f"Full Path    :{strPath}" )
nmFolders = strPath.split( os.path.sep )
print( "List of Folders:", nmFolders )
print( f"Program Name :{nmFolders[-1]}" )
print( f"Folder Name  :{nmFolders[-2]}" )
print( f"Folder Parent:{nmFolders[-3]}" )

The output of the above was this:

Full Path    :C:\Users\terry\Documents\apps\environments\dev\app_02\app_02.py
List of Folders: ['C:', 'Users', 'terry', 'Documents', 'apps', 'environments', 'dev', 'app_02', 'app_02.py']
Program Name :app_02.py
Folder Name  :app_02
Folder Parent:dev

echo that outputs to stderr

Make a script

#!/bin/sh
echo $* 1>&2

that would be your tool.

Or make a function if you don't want to have a script in separate file.

Can't use SURF, SIFT in OpenCV

As per June 2020, I suppose this version (pip install -U opencv-contrib-python==3.4.2.16) is still working. so install it and enjoy.

How to automatically generate unique id in SQL like UID12345678?

CREATE TABLE dbo.tblUsers
(
    ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
    UserID AS 'UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED, 
    [Name] VARCHAR(50) NOT NULL,
)

marc_s's Answer Snap

marc_s's Answer Snap

How to skip a iteration/loop in while-loop

While you could use a continue, why not just inverse the logic in your if?

while(rs.next())
{
    if(!f.exists() || f.isDirectory()){
    //proceed
    }
}

You don't even need an else {continue;} as it will continue anyway if the if conditions are not satisfied.

Do I need a content-type header for HTTP GET requests?

GET requests can have "Accept" headers, which say which types of content the client understands. The server can then use that to decide which content type to send back.

They're optional though.

http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1

Git resolve conflict using --ours/--theirs for all files

You can -Xours or -Xtheirs with git merge as well. So:

  1. abort the current merge (for instance with git reset --hard HEAD)
  2. merge using the strategy you prefer (git merge -Xours or git merge -Xtheirs)

DISCLAIMER: of course you can choose only one option, either -Xours or -Xtheirs, do use different strategy you should of course go file by file.

I do not know if there is a way for checkout, but I do not honestly think it is terribly useful: selecting the strategy with the checkout command is useful if you want different solutions for different files, otherwise just go for the merge strategy approach.

What is the fastest/most efficient way to find the highest set bit (msb) in an integer in C?

Assuming you're on x86 and game for a bit of inline assembler, Intel provides a BSR instruction ("bit scan reverse"). It's fast on some x86s (microcoded on others). From the manual:

Searches the source operand for the most significant set bit (1 bit). If a most significant 1 bit is found, its bit index is stored in the destination operand. The source operand can be a register or a memory location; the destination operand is a register. The bit index is an unsigned offset from bit 0 of the source operand. If the content source operand is 0, the content of the destination operand is undefined.

(If you're on PowerPC there's a similar cntlz ("count leading zeros") instruction.)

Example code for gcc:

#include <iostream>

int main (int,char**)
{
  int n=1;
  for (;;++n) {
    int msb;
    asm("bsrl %1,%0" : "=r"(msb) : "r"(n));
    std::cout << n << " : " << msb << std::endl;
  }
  return 0;
}

See also this inline assembler tutorial, which shows (section 9.4) it being considerably faster than looping code.

JPA or JDBC, how are they different?

JDBC is the predecessor of JPA.

JDBC is a bridge between the Java world and the databases world. In JDBC you need to expose all dirty details needed for CRUD operations, such as table names, column names, while in JPA (which is using JDBC underneath), you also specify those details of database metadata, but with the use of Java annotations.

So JPA creates update queries for you and manages the entities that you looked up or created/updated (it does more as well).

If you want to do JPA without a Java EE container, then Spring and its libraries may be used with the very same Java annotations.

Max size of an iOS application

As of June 2019, if your user's are on iOS 13 the cellular download limit has been lifted. User's just get a warning now. Read here

In case the article is removed here are screen shots of it below

enter image description here

enter image description here

enter image description here

How to attach source or JavaDoc in eclipse for any jar file e.g. JavaFX?

To attach the Java source code with Eclipse,

When you install the JDK, you must have selected the option to install the Java source files too. This will copy the src.zip file in the installation directory. In Eclipse, go to Window -> Preferences -> Java -> Installed JREs -> Add and choose the JDK you have in your system. Eclipse will now list the JARs found in the dialog box. There, select the rt.jar and choose Source Attachment. By default, this will be pointing to the correct src.zip. If not, choose the src.zip file which you have in your java installation directory. java source attach in eclipse Similarly, if you have the javadoc downloaded in your machine, you can configure that too in this dialog box.

A regular expression to exclude a word/string

This should do it:

^/\b([a-z0-9]+)\b(?<!ignoreme|ignoreme2|ignoreme3)

You can add as much ignored words as you like, here is a simple PHP implementation:

$ignoredWords = array('ignoreme', 'ignoreme2', 'ignoreme...');

preg_match('~^/\b([a-z0-9]+)\b(?<!' . implode('|', array_map('preg_quote', $ignoredWords)) . ')~i', $string);

JavaScript, Node.js: is Array.forEach asynchronous?

Array.forEach is meant for computing stuff not waiting, and there is nothing to be gained making computations asynchronous in an event loop (webworkers add multiprocessing, if you need multi-core computation). If you want to wait for multiple tasks to end, use a counter, which you can wrap in a semaphore class.

Crystal Reports 13 And Asp.Net 3.5

I had this same problem and resolved it by making sure all references to the previous version of crystal from the Web Config file, the server, and the publishing workstation were removed. Other than the full trust basically everything that user707217 did, I did and it worked for my upgraded Web application

python dataframe pandas drop column using int

If there are multiple columns with identical names, the solutions given here so far will remove all of the columns, which may not be what one is looking for. This may be the case if one is trying to remove duplicate columns except one instance. The example below clarifies this situation:

# make a df with duplicate columns 'x'
df = pd.DataFrame({'x': range(5) , 'x':range(5), 'y':range(6, 11)}, columns = ['x', 'x', 'y']) 


df
Out[495]: 
   x  x   y
0  0  0   6
1  1  1   7
2  2  2   8
3  3  3   9
4  4  4  10

# attempting to drop the first column according to the solution offered so far     
df.drop(df.columns[0], axis = 1) 
   y
0  6
1  7
2  8
3  9
4  10

As you can see, both Xs columns were dropped. Alternative solution:

column_numbers = [x for x in range(df.shape[1])]  # list of columns' integer indices

column_numbers .remove(0) #removing column integer index 0
df.iloc[:, column_numbers] #return all columns except the 0th column

   x  y
0  0  6
1  1  7
2  2  8
3  3  9
4  4  10

As you can see, this truly removed only the 0th column (first 'x').

How to use custom font in a project written in Android Studio

  1. Create folder assets in Project -> app (or your app name) -> src -> main -> right click -> New -> Directory.
  2. Then create a new directory inside assets called "fonts".

To assign the font to the textView:

TextView textView = (TextView) findViewById(R.id.your_textView);

final Typeface font = Typeface.createFromAsset(context.getAssets(), "fonts/your_font_name");

your_font_name includes font extension.

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

Don't understand why UnboundLocalError occurs (closure)

try this

counter = 0

def increment():
  global counter
  counter += 1

increment()

How to use struct timeval to get the execution time?

You have two typing errors in your code:

 struct timeval,

should be

 struct timeval

and after the printf() parenthesis you need a semicolon.

Also, depending on the compiler, so simple a cycle might just be optimized out, giving you a time of 0 microseconds whatever you do.

Finally, the time calculation is wrong. You only take into accounts the seconds, ignoring the microseconds. You need to get the difference between seconds, multiply by one million, then add "after" tv_usec and subtract "before" tv_usec. You gain nothing by casting an integer number of seconds to a float.

I'd suggest checking out the man page for struct timeval.

This is the code:

#include <stdio.h>
#include <sys/time.h>

int main (int argc, char** argv) {
    struct timeval tvalBefore, tvalAfter;  // removed comma

    gettimeofday (&tvalBefore, NULL);
    int i =0;
    while ( i < 10000) {
        i ++;
    }

    gettimeofday (&tvalAfter, NULL);

    // Changed format to long int (%ld), changed time calculation

    printf("Time in microseconds: %ld microseconds\n",
            ((tvalAfter.tv_sec - tvalBefore.tv_sec)*1000000L
           +tvalAfter.tv_usec) - tvalBefore.tv_usec
          ); // Added semicolon
    return 0;
}

How do I output the results of a HiveQL query to CSV?

You can use INSERTDIRECTORY …, as in this example:

INSERT OVERWRITE LOCAL DIRECTORY '/tmp/ca_employees'
SELECT name, salary, address
FROM employees
WHERE se.state = 'CA';

OVERWRITE and LOCAL have the same interpretations as before and paths are interpreted following the usual rules. One or more files will be written to /tmp/ca_employees, depending on the number of reducers invoked.

How I can filter a Datatable?

You can use DataView.

DataView dv = new DataView(yourDatatable);
dv.RowFilter = "query"; // query example = "id = 10"


http://www.csharp-examples.net/dataview-rowfilter/

What is the regex pattern for datetime (2008-09-01 12:35:45 )?

Here is my solution:

[12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]) ([01][0-9]|2[0-3]):[0-5]\d

Regular expression visualization

Debuggex Demo

https://regex101.com/r/lbthaT/4

How do I install jmeter on a Mac?

Download last version (not 2.5.1 or other old ones) from jmeter.apache.org

Unzip file

Ensure you install a version of JAVA which is compatible, Java 6 or 7 for JMeter 2.11

In bin folder click on jmeter.sh not on jar or execute sh ./apache-jmeter-x.x.x/bin/jmeter in the terminal.

x.x.x is the version you use.

Finally, when started you may want to select System Look and feel for Mac OSX better integration. Menu > Options > Look and Feel > System

Get push notification while App in foreground iOS

According to apple documentation, Yes you can display notification while app is runningenter image description here

Converting video to HTML5 ogg / ogv and mpg4

MS Expression Encoder can do mp4/h.264. not sure about ogg though.

Fastest method of screen capturing on Windows

With Windows 8, Microsoft introduced the Windows Desktop Duplication API. That is the officially recommended way of doing it. One nice feature it has for screencasting is that it detects window movement, so you can transmit block deltas when windows get moved around, instead of raw pixels. Also, it tells you which rectangles have changed, from one frame to the next.

The Microsoft example code is pretty complex, but the API is actually simple and easy to use. I've put together an example project which is much simpler than the official example:

https://github.com/bmharper/WindowsDesktopDuplicationSample

Docs: https://docs.microsoft.com/en-gb/windows/desktop/direct3ddxgi/desktop-dup-api

Microsoft official example code: https://code.msdn.microsoft.com/windowsdesktop/Desktop-Duplication-Sample-da4c696a

Click a button programmatically

The best practice for this sort of situation is to create a method that hold all the logics, and call the method in both events, rather than calling an event from another event;

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

        LogicMethod()

End Sub

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

        LogicMethod()

End Sub

Private Sub LogicMethod()

     // All your logic goes here

End Sub

In case you need the properties of the EventArgs (e), you can easily pass it through parameters in your method, that will avoid errors if ever the sender is of different types. But that won't be a problem in your case, as both senders are of type Button.

Jquery open popup on button click for bootstrap

The answer is on the example link you provided:

http://getbootstrap.com/javascript/#modals-usage

i.e.

Call a modal with id myModal with a single line of JavaScript:

$('#myModal').modal('show');

Why do we need to install gulp globally and locally?

Just because I haven't seen it here, if you are on MacOS or Linux, I suggest you add this to your PATH (in your bashrc etc):

node_modules/.bin

With this relative path entry, if you are sitting in the root folder of any node project, you can run any command line tool (eslint, gulp, etc. etc.) without worrying about "global installs" or npm run etc.

Once I did this, I've never installed a module globally.

Setting timezone in Python

For windows you can use:

Running Windows command prompt commands in python.

import os
os.system('tzutil /s "Central Standard Time"')

In windows command prompt try:

This gives current timezone:

tzutil /g

This gives a list of timezones:

tzutil /l

This will set the timezone:

tzutil /s "Central America Standard Time"

For further reference: http://woshub.com/how-to-set-timezone-from-command-prompt-in-windows/

Closing WebSocket correctly (HTML5, Javascript)

By using close method of web socket, where you can write any function according to requirement.

var connection = new WebSocket('ws://127.0.0.1:1337');
    connection.onclose = () => {
            console.log('Web Socket Connection Closed');
        };

static files with express.js

If you have this setup

/app
   /public/index.html
   /media

Then this should get what you wanted

var express = require('express');
//var server = express.createServer();
// express.createServer()  is deprecated. 
var server = express(); // better instead
server.configure(function(){
  server.use('/media', express.static(__dirname + '/media'));
  server.use(express.static(__dirname + '/public'));
});

server.listen(3000);

The trick is leaving this line as last fallback

  server.use(express.static(__dirname + '/public'));

As for documentation, since Express uses connect middleware, I found it easier to just look at the connect source code directly.

For example this line shows that index.html is supported https://github.com/senchalabs/connect/blob/2.3.3/lib/middleware/static.js#L140

What does the servlet <load-on-startup> value signify

Resin 3.0 documents this behavior:

load-on-startup can specify an (optional) integer value. If the value is 0 or greater, it indicates an order for servlets to be loaded, servlets with higher numbers get loaded after servlets with lower numbers.

The JSP 3.1 spec (JSR 340) says this on page 14-160:

The element load-on-startup indicates that this servlet should be loaded (instantiated and have its init() called) on the startup of the Web application. The element content of this element must be an integer indicating the order in which the servlet should be loaded. If the value is a negative integer, or the element is not present, the container is free to load the servlet whenever it chooses. If the value is a positive integer or 0, the container must load and initialize the servlet as the application is deployed. The container must guarantee that servlets marked with lower integers are loaded before servlets marked with higher integers. The container may choose the order of loading of servlets with the same load-on-startup value.

You probably want to check not only the JSR, but also the documentation for your web container. There may be differences

Difference between WebStorm and PHPStorm

I couldn't find any major points on JetBrains' website and even Google didn't help that much.

You should train your search-fu twice as harder.


FROM: http://www.jetbrains.com/phpstorm/

NOTE: PhpStorm includes all the functionality of WebStorm (HTML/CSS Editor, JavaScript Editor) and adds full-fledged support for PHP and Databases/SQL.


Their forum also has quite few answers for such question.


Basically: PhpStorm = WebStorm + PHP + Database support

WebStorm comes with certain (mainly) JavaScript oriented plugins bundled by default while they need to be installed manually in PhpStorm (if necessary).

At the same time: plugins that require PHP support would not be able to install in WebStorm (for obvious reasons).

P.S. Since WebStorm has different release cycle than PhpStorm, it can have new JS/CSS/HTML oriented features faster than PhpStorm (it's all about platform builds used).

For example: latest stable PhpStorm is v7.1.4 while WebStorm is already on v8.x. But, PhpStorm v8 will be released in approximately 1 month (accordingly to their road map), which means that stable version of PhpStorm will include some of the features that will only be available in WebStorm v9 (quite few months from now, lets say 2-3-5) -- if using/comparing stable versions ONLY.

UPDATE (2016-12-13): Since 2016.1 version PhpStorm and WebStorm use the same version/build numbers .. so there is no longer difference between the same versions: functionality present in WebStorm 2016.3 is the same as in PhpStorm 2016.3 (if the same plugins are installed, of course).


Everything that I know atm. is that PHPStorm doesn't support JS part like Webstorm

That's not correct (your wording). Missing "extra" technology in PhpStorm (for example: node, angularjs) does not mean that basic JavaScript support has missing functionality. Any "extras" can be easily installed (or deactivated, if not required).


UPDATE (2016-12-13): Here is the list of plugins that are bundled with WebStorm 2016.3 but require manual installation in PhpStorm 2016.3 (if you need them, of course):

  • Cucumber.js
  • Dart
  • EditorConfig
  • EJS
  • Handelbars/Mustache
  • Java Server Pages (JSP) Integration
  • Karma
  • LiveEdit
  • Meteor
  • PhoneGap/Cordova Plugin
  • Polymer & Web Components
  • Pug (ex-Jade)
  • Spy-js
  • Stylus support
  • Yeoman

Explaining Python's '__enter__' and '__exit__'

This is called context manager and I just want to add that similar approaches exist for other programming languages. Comparing them could be helpful in understanding the context manager in python. Basically, a context manager is used when we are dealing with some resources (file, network, database) that need to be initialized and at some point, tear downed (disposed). In Java 7 and above we have automatic resource management that takes the form of:

//Java code
try (Session session = new Session())
{
  // do stuff
}

Note that Session needs to implement AutoClosable or one of its (many) sub-interfaces.

In C#, we have using statements for managing resources that takes the form of:

//C# code
using(Session session = new Session())
{
  ... do stuff.
}

In which Session should implement IDisposable.

In python, the class that we use should implement __enter__ and __exit__. So it takes the form of:

#Python code
with Session() as session:
    #do stuff

And as others pointed out, you can always use try/finally statement in all the languages to implement the same mechanism. This is just syntactic sugar.

Show ProgressDialog Android

You should not execute resource intensive tasks in the main thread. It will make the UI unresponsive and you will get an ANR. It seems like you will be doing resource intensive stuff and want the user to see the ProgressDialog. You can take a look at http://developer.android.com/reference/android/os/AsyncTask.html to do resource intensive tasks. It also shows you how to use a ProgressDialog.

js window.open then print()

As most of browsers has been updated, So print and close do not any more as It worked before. So you should add onafterprint event listener in order to close print window.

    var printWindow = window.open('https://stackoverflow.com/');
    printWindow.print();

    //Close window once print is finished
    printWindow.onafterprint = function(){
       printWindow.close()
    };

Javascript : natural sort of alphanumerical strings

If you have a array of objects you can do like this:

myArrayObjects = myArrayObjects.sort(function(a, b) {
  return a.name.localeCompare(b.name, undefined, {
    numeric: true,
    sensitivity: 'base'
  });
});

_x000D_
_x000D_
var myArrayObjects = [{_x000D_
    "id": 1,_x000D_
    "name": "1 example"_x000D_
  },_x000D_
  {_x000D_
    "id": 2,_x000D_
    "name": "100 example"_x000D_
  },_x000D_
  {_x000D_
    "id": 3,_x000D_
    "name": "12 example"_x000D_
  },_x000D_
  {_x000D_
    "id": 4,_x000D_
    "name": "5 example"_x000D_
  },_x000D_
_x000D_
]_x000D_
_x000D_
myArrayObjects = myArrayObjects.sort(function(a, b) {_x000D_
  return a.name.localeCompare(b.name, undefined, {_x000D_
    numeric: true,_x000D_
    sensitivity: 'base'_x000D_
  });_x000D_
});_x000D_
console.log(myArrayObjects);
_x000D_
_x000D_
_x000D_

bash: Bad Substitution

I have found that this issue is either caused by the marked answer or you have a line or space before the bash declaration

How to print spaces in Python?

Sometimes, pprint() in pprint module works wonder, especially for dict variables.

Count the number of items in my array list

Outside of your loop create an int:

int numberOfItemIds = 0;
for (int i = 0; i < key.length; i++) {

Then in the loop, increment it:

itemId = p.getItemId();
numberOfItemIds++;

How to do a join in linq to sql with method syntax?

var result = from sc in enumerableOfSomeClass
             join soc in enumerableOfSomeOtherClass
             on sc.Property1 equals soc.Property2
             select new { SomeClass = sc, SomeOtherClass = soc };

Would be equivalent to:

var result = enumerableOfSomeClass
    .Join(enumerableOfSomeOtherClass,
          sc => sc.Property1,
          soc => soc.Property2,
          (sc, soc) => new
                       {
                           SomeClass = sc,
                           SomeOtherClass = soc
                       });

As you can see, when it comes to joins, query syntax is usually much more readable than lambda syntax.

How to rotate a div using jQuery

EDIT: Updated for jQuery 1.8

Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: Added code to make it a jQuery function.

For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
                 '-moz-transform' : 'rotate('+ degrees +'deg)',
                 '-ms-transform' : 'rotate('+ degrees +'deg)',
                 'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.


Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.

Here is a jsFiddle.

If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.

HTML

<div class="rotate">
    <h1>Rotatey text</h1>
</div>

CSS

/* Totally for style */
.rotate {
    background: #F02311;
    color: #FFF;
    width: 200px;
    height: 200px;
    text-align: center;
    font: normal 1em Arial;
    position: relative;
    top: 50px;
    left: 50px;
}

/* The real code */
.rotated {
    -webkit-transform: rotate(45deg);  /* Chrome, Safari 3.1+ */
    -moz-transform: rotate(45deg);  /* Firefox 3.5-15 */
    -ms-transform: rotate(45deg);  /* IE 9 */
    -o-transform: rotate(45deg);  /* Opera 10.50-12.00 */
    transform: rotate(45deg);  /* Firefox 16+, IE 10+, Opera 12.10+ */
}

jQuery

Make sure these are wrapped in $(document).ready

$('.rotate').click(function() {
    $(this).toggleClass('rotated');
});

Custom intervals

var rotation = 0;
$('.rotate').click(function() {
    rotation += 5;
    $(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
                 '-moz-transform' : 'rotate('+ rotation +'deg)',
                 '-ms-transform' : 'rotate('+ rotation +'deg)',
                 'transform' : 'rotate('+ rotation +'deg)'});
});

How do I delete unpushed git commits?

Delete the most recent commit, keeping the work you've done:

git reset --soft HEAD~1

Delete the most recent commit, destroying the work you've done:

git reset --hard HEAD~1

How to get json key and value in javascript?

You can use the following solution to get a JSON key and value in JavaScript:

var dt = JSON.stringify(data).replace('[', '').replace(']', '');
if (dt) {
  var result = jQuery.parseJSON(dt);
  var val = result.YOUR_OBJECT_NAME;
}

python pandas: Remove duplicates by columns A, keeping the row with the highest value in column B

The top answer is doing too much work and looks to be very slow for larger data sets. apply is slow and should be avoided if possible. ix is deprecated and should be avoided as well.

df.sort_values('B', ascending=False).drop_duplicates('A').sort_index()

   A   B
1  1  20
3  2  40
4  3  10

Or simply group by all the other columns and take the max of the column you need. df.groupby('A', as_index=False).max()

SQL Server: Error converting data type nvarchar to numeric

You might need to revise the data in the column, but anyway you can do one of the following:-

1- check if it is numeric then convert it else put another value like 0

Select COLUMNA AS COLUMNA_s, CASE WHEN Isnumeric(COLUMNA) = 1
THEN CONVERT(DECIMAL(18,2),COLUMNA) 
ELSE 0 END AS COLUMNA

2- select only numeric values from the column

SELECT COLUMNA AS COLUMNA_s ,CONVERT(DECIMAL(18,2),COLUMNA) AS COLUMNA
where Isnumeric(COLUMNA) = 1

Implement division with bit-wise operator

The below method is the implementation of binary divide considering both numbers are positive. If subtraction is a concern we can implement that as well using binary operators.

Code

-(int)binaryDivide:(int)numerator with:(int)denominator
{
    if (numerator == 0 || denominator == 1) {
        return numerator;
    }

    if (denominator == 0) {

        #ifdef DEBUG
            NSAssert(denominator == 0, @"denominator should be greater then 0");
        #endif
        return INFINITY;
    }

    // if (numerator <0) {
    //     numerator = abs(numerator);
    // }

    int maxBitDenom = [self getMaxBit:denominator];
    int maxBitNumerator = [self getMaxBit:numerator];
    int msbNumber = [self getMSB:maxBitDenom ofNumber:numerator];

    int qoutient = 0;

    int subResult = 0;

    int remainingBits = maxBitNumerator-maxBitDenom;

    if (msbNumber >= denominator) {
        qoutient |=1;
        subResult = msbNumber - denominator;
    }
    else {
        subResult = msbNumber;
    }

    while (remainingBits>0) {
        int msbBit = (numerator & (1 << (remainingBits-1)))>0 ? 1 : 0;
        subResult = (subResult << 1) |msbBit;
        if (subResult >= denominator) {
            subResult = subResult-denominator;
            qoutient = (qoutient << 1) | 1;
        }
        else {
            qoutient = qoutient << 1;
        }
        remainingBits--;
    }
    return qoutient;
}


-(int)getMaxBit:(int)inputNumber
{
    int maxBit =0;
    BOOL isMaxBitSet = NO;
    for (int i=0; i<sizeof(inputNumber)*8; i++) {
        if (inputNumber & (1 << i) ) {
            maxBit = i;
            isMaxBitSet=YES;
        }
    }
    if (isMaxBitSet) {
        maxBit += 1;
    }
    return maxBit;
}


-(int)getMSB:(int)bits ofNumber:(int)number
{
    int numbeMaxBit = [self getMaxBit:number];
    return number >> (numbeMaxBit -bits);
}

What are the undocumented features and limitations of the Windows FINDSTR command?

Preface
Much of the information in this answer has been gathered based on experiments run on a Vista machine. Unless explicitly stated otherwise, I have not confirmed whether the information applies to other Windows versions.

FINDSTR output
The documentation never bothers to explain the output of FINDSTR. It alludes to the fact that matching lines are printed, but nothing more.

The format of matching line output is as follows:

filename:lineNumber:lineOffset:text

where

fileName: = The name of the file containing the matching line. The file name is not printed if the request was explicitly for a single file, or if searching piped input or redirected input. When printed, the fileName will always include any path information provided. Additional path information will be added if the /S option is used. The printed path is always relative to the provided path, or relative to the current directory if none provided.

Note - The filename prefix can be avoided when searching multiple files by using the non-standard (and poorly documented) wildcards < and >. The exact rules for how these wildcards work can be found here. Finally, you can look at this example of how the non-standard wildcards work with FINDSTR.

lineNumber: = The line number of the matching line represented as a decimal value with 1 representing the 1st line of the input. Only printed if /N option is specified.

lineOffset: = The decimal byte offset of the start of the matching line, with 0 representing the 1st character of the 1st line. Only printed if /O option is specified. This is not the offset of the match within the line. It is the number of bytes from the beginning of the file to the beginning of the line.

text = The binary representation of the matching line, including any <CR> and/or <LF>. Nothing is left out of the binary output, such that this example that matches all lines will produce an exact binary copy of the original file.

FINDSTR "^" FILE >FILE_COPY

The /A option sets the color of the fileName:, lineNumber:, and lineOffset: output only. The text of the matching line is always output with the current console color. The /A option only has effect when output is displayed directly to the console. The /A option has no effect if the output is redirected to a file or piped. See the 2018-08-18 edit in Aacini's answer for a description of the buggy behavior when output is redirected to CON.

Most control characters and many extended ASCII characters display as dots on XP
FINDSTR on XP displays most non-printable control characters from matching lines as dots (periods) on the screen. The following control characters are exceptions; they display as themselves: 0x09 Tab, 0x0A LineFeed, 0x0B Vertical Tab, 0x0C Form Feed, 0x0D Carriage Return.

XP FINDSTR also converts a number of extended ASCII characters to dots as well. The extended ASCII characters that display as dots on XP are the same as those that are transformed when supplied on the command line. See the "Character limits for command line parameters - Extended ASCII transformation" section, later in this post

Control characters and extended ASCII are not converted to dots on XP if the output is piped, redirected to a file, or within a FOR IN() clause.

Vista and Windows 7 always display all characters as themselves, never as dots.

Return Codes (ERRORLEVEL)

  • 0 (success)
    • Match was found in at least one line of at least one file.
  • 1 (failure)
    • No match was found in any line of any file.
    • Invalid color specified by /A:xx option
  • 2 (error)
    • Incompatible options /L and /R both specified
    • Missing argument after /A:, /F:, /C:, /D:, or /G:
    • File specified by /F:file or /G:file not found
  • 255 (error)

Source of data to search (Updated based on tests with Windows 7)
Findstr can search data from only one of the following sources:

  • filenames specified as arguments and/or using the /F:file option.

  • stdin via redirection findstr "searchString" <file

  • data stream from a pipe type file | findstr "searchString"

Arguments/options take precedence over redirection, which takes precedence over piped data.

File name arguments and /F:file may be combined. Multiple file name arguments may be used. If multiple /F:file options are specified, then only the last one is used. Wild cards are allowed in filename arguments, but not within the file pointed to by /F:file.

Source of search strings (Updated based on tests with Windows 7)
The /G:file and /C:string options may be combined. Multiple /C:string options may be specified. If multiple /G:file options are specified, then only the last one is used. If either /G:file or /C:string is used, then all non-option arguments are assumed to be files to search. If neither /G:file nor /C:string is used, then the first non-option argument is treated as a space delimited list of search terms.

File names must not be quoted within the file when using the /F:FILE option.
File names may contain spaces and other special characters. Most commands require that such file names are quoted. But the FINDSTR /F:files.txt option requires that filenames within files.txt must NOT be quoted. The file will not be found if the name is quoted.

BUG - Short 8.3 filenames can break the /D and /S options
As with all Windows commands, FINDSTR will attempt to match both the long name and the short 8.3 name when looking for files to search. Assume the current folder contains the following non-empty files:

b1.txt
b.txt2
c.txt

The following command will successfully find all 3 files:

findstr /m "^" *.txt

b.txt2 matches because the corresponding short name B9F64~1.TXT matches. This is consistent with the behavior of all other Windows commands.

But a bug with the /D and /S options causes the following commands to only find b1.txt

findstr /m /d:. "^" *.txt
findstr /m /s "^" *.txt

The bug prevents b.txt2 from being found, as well as all file names that sort after b.txt2 within the same directory. Additional files that sort before, like a.txt, are found. Additional files that sort later, like d.txt, are missed once the bug has been triggered.

Each directory searched is treated independently. For example, the /S option would successfully begin searching in a child folder after failing to find files in the parent, but once the bug causes a short file name to be missed in the child, then all subsequent files in that child folder would also be missed.

The commands work bug free if the same file names are created on a machine that has NTFS 8.3 name generation disabled. Of course b.txt2 would not be found, but c.txt would be found properly.

Not all short names trigger the bug. All instances of bugged behavior I have seen involve an extension that is longer than 3 characters with a short 8.3 name that begins the same as a normal name that does not require an 8.3 name.

The bug has been confirmed on XP, Vista, and Windows 7.

Non-Printable characters and the /P option
The /P option causes FINDSTR to skip any file that contains any of the following decimal byte codes:
0-7, 14-25, 27-31.

Put another way, the /P option will only skip files that contain non-printable control characters. Control characters are codes less than or equal to 31 (0x1F). FINDSTR treats the following control characters as printable:

 8  0x08  backspace
 9  0x09  horizontal tab
10  0x0A  line feed
11  0x0B  vertical tab
12  0x0C  form feed
13  0x0D  carriage return
26  0x1A  substitute (end of text)

All other control characters are treated as non-printable, the presence of which causes the /P option to skip the file.

Piped and Redirected input may have <CR><LF> appended
If the input is piped in and the last character of the stream is not <LF>, then FINDSTR will automatically append <CR><LF> to the input. This has been confirmed on XP, Vista and Windows 7. (I used to think that the Windows pipe was responsible for modifying the input, but I have since discovered that FINDSTR is actually doing the modification.)

The same is true for redirected input on Vista. If the last character of a file used as redirected input is not <LF>, then FINDSTR will automatically append <CR><LF> to the input. However, XP and Windows 7 do not alter redirected input.

FINDSTR hangs on XP and Windows 7 if redirected input does not end with <LF>
This is a nasty "feature" on XP and Windows 7. If the last character of a file used as redirected input does not end with <LF>, then FINDSTR will hang indefinitely once it reaches the end of the redirected file.

Last line of Piped data may be ignored if it consists of a single character
If the input is piped in and the last line consists of a single character that is not followed by <LF>, then FINDSTR completely ignores the last line.

Example - The first command with a single character and no <LF> fails to match, but the second command with 2 characters works fine, as does the third command that has one character with terminating newline.

> set /p "=x" <nul | findstr "^"

> set /p "=xx" <nul | findstr "^"
xx

> echo x| findstr "^"
x

Reported by DosTips user Sponge Belly at new findstr bug. Confirmed on XP, Windows 7 and Windows 8. Haven't heard about Vista yet. (I no longer have Vista to test).

Option syntax
Option letters are not case sensitive, so /i and /I are equivalent.

Options can be prefixed with either / or - Options may be concatenated after a single / or -. However, the concatenated option list may contain at most one multicharacter option such as OFF or F:, and the multi-character option must be the last option in the list.

The following are all equivalent ways of expressing a case insensitive regex search for any line that contains both "hello" and "goodbye" in any order

  • /i /r /c:"hello.*goodbye" /c:"goodbye.*hello"

  • -i -r -c:"hello.*goodbye" /c:"goodbye.*hello"

  • /irc:"hello.*goodbye" /c:"goodbye.*hello"

Options may also be quoted. So /i, -i, "/i" and "-i" are all equivalent. Likewise, /c:string, "/c":string, "/c:"string and "/c:string" are all equivalent.

If a search string begins with a / or - literal, then the /C or /G option must be used. Thanks to Stephan for reporting this in a comment (since deleted).

Search String length limits
On Vista the maximum allowed length for a single search string is 511 bytes. If any search string exceeds 511 then the result is a FINDSTR: Search string too long. error with ERRORLEVEL 2.

When doing a regular expression search, the maximum search string length is 254. A regular expression with length between 255 and 511 will result in a FINDSTR: Out of memory error with ERRORLEVEL 2. A regular expression length >511 results in the FINDSTR: Search string too long. error.

On Windows XP the search string length is apparently shorter. Findstr error: "Search string too long": How to extract and match substring in "for" loop? The XP limit is 127 bytes for both literal and regex searches.

Line Length limits
Files specified as a command line argument or via the /F:FILE option have no known line length limit. Searches were successfully run against a 128MB file that did not contain a single <LF>.

Piped data and Redirected input is limited to 8191 bytes per line. This limit is a "feature" of FINDSTR. It is not inherent to pipes or redirection. FINDSTR using redirected stdin or piped input will never match any line that is >=8k bytes. Lines >= 8k generate an error message to stderr, but ERRORLEVEL is still 0 if the search string is found in at least one line of at least one file.

Default type of search: Literal vs Regular Expression
/C:"string" - The default is /L literal. Explicitly combining the /L option with /C:"string" certainly works but is redundant.

"string argument" - The default depends on the content of the very first search string. (Remember that <space> is used to delimit search strings.) If the first search string is a valid regular expression that contains at least one un-escaped meta-character, then all search strings are treated as regular expressions. Otherwise all search strings are treated as literals. For example, "51.4 200" will be treated as two regular expressions because the first string contains an un-escaped dot, whereas "200 51.4" will be treated as two literals because the first string does not contain any meta-characters.

/G:file - The default depends on the content of the first non-empty line in the file. If the first search string is a valid regular expression that contains at least one un-escaped meta-character, then all search strings are treated as regular expressions. Otherwise all search strings are treated as literals.

Recommendation - Always explicitly specify /L literal option or /R regular expression option when using "string argument" or /G:file.

BUG - Specifying multiple literal search strings can give unreliable results

The following simple FINDSTR example fails to find a match, even though it should.

echo ffffaaa|findstr /l "ffffaaa faffaffddd"

This bug has been confirmed on Windows Server 2003, Windows XP, Vista, and Windows 7.

Based on experiments, FINDSTR may fail if all of the following conditions are met:

  • The search is using multiple literal search strings
  • The search strings are of different lengths
  • A short search string has some amount of overlap with a longer search string
  • The search is case sensitive (no /I option)

In every failure I have seen, it is always one of the shorter search strings that fails.

For more info see Why doesn't this FINDSTR example with multiple literal search strings find a match?

Quotes and backslahses within command line arguments
Note - User MC ND's comments reflect the actual horrifically complicated rules for this section. There are 3 distinct parsing phases involved:

  • First cmd.exe may require some quotes to be escaped as ^" (really nothing to do with FINDSTR)
  • Next FINDSTR uses the pre 2008 MS C/C++ argument parser, which has special rules for " and \
  • After the argument parser finishes, FINDSTR additionally treats \ followed by an alpha-numeric character as literal, but \ followed by non-alpha-numeric character as an escape character

The remainder of this highlighted section is not 100% correct. It can serve as a guide for many situations, but the above rules are required for total understanding.

Escaping Quote within command line search strings
Quotes within command line search strings must be escaped with backslash like \". This is true for both literal and regex search strings. This information has been confirmed on XP, Vista, and Windows 7.

Note: The quote may also need to be escaped for the CMD.EXE parser, but this has nothing to do with FINDSTR. For example, to search for a single quote you could use:

FINDSTR \^" file && echo found || echo not found

Escaping Backslash within command line literal search strings
Backslash in a literal search string can normally be represented as \ or as \\. They are typically equivalent. (There may be unusual cases in Vista where the backslash must always be escaped, but I no longer have a Vista machine to test).

But there are some special cases:

When searching for consecutive backslashes, all but the last must be escaped. The last backslash may optionally be escaped.

  • \\ can be coded as \\\ or \\\\
  • \\\ can be coded as \\\\\ or \\\\\\

Searching for one or more backslashes before a quote is bizarre. Logic would suggest that the quote must be escaped, and each of the leading backslashes would need to be escaped, but this does not work! Instead, each of the leading backslashes must be double escaped, and the quote is escaped normally:

  • \" must be coded as \\\\\"
  • \\" must be coded as \\\\\\\\\"

As previously noted, one or more escaped quotes may also require escaping with ^ for the CMD parser

The info in this section has been confirmed on XP and Windows 7.

Escaping Backslash within command line regex search strings

  • Vista only: Backslash in a regex must be either double escaped like \\\\, or else single escaped within a character class set like [\\]

  • XP and Windows 7: Backslash in a regex can always be represented as [\\]. It can normally be represented as \\. But this never works if the backslash precedes an escaped quote.

    One or more backslashes before an escaped quote must either be double escaped, or else coded as [\\]

    • \" may be coded as \\\\\" or [\\]\"
    • \\" may be coded as \\\\\\\\\" or [\\][\\]\" or \\[\\]\"

Escaping Quote and Backslash within /G:FILE literal search strings
Standalone quotes and backslashes within a literal search string file specified by /G:file need not be escaped, but they can be.

" and \" are equivalent.

\ and \\ are equivalent.

If the intent is to find \\, then at least the leading backslash must be escaped. Both \\\ and \\\\ work.

If the intent is to find ", then at least the leading backslash must be escaped. Both \\" and \\\" work.

Escaping Quote and Backslash within /G:FILE regex search strings
This is the one case where the escape sequences work as expected based on the documentation. Quote is not a regex metacharacter, so it need not be escaped (but can be). Backslash is a regex metacharacter, so it must be escaped.

Character limits for command line parameters - Extended ASCII transformation
The null character (0x00) cannot appear in any string on the command line. Any other single byte character can appear in the string (0x01 - 0xFF). However, FINDSTR converts many extended ASCII characters it finds within command line parameters into other characters. This has a major impact in two ways:

  1. Many extended ASCII characters will not match themselves if used as a search string on the command line. This limitation is the same for literal and regex searches. If a search string must contain extended ASCII, then the /G:FILE option should be used instead.

  2. FINDSTR may fail to find a file if the name contains extended ASCII characters and the file name is specified on the command line. If a file to be searched contains extended ASCII in the name, then the /F:FILE option should be used instead.

Here is a complete list of extended ASCII character transformations that FINDSTR performs on command line strings. Each character is represented as the decimal byte code value. The first code represents the character as supplied on the command line, and the second code represents the character it is transformed into. Note - this list was compiled on a U.S machine. I do not know what impact other languages may have on this list.

158 treated as 080     199 treated as 221     226 treated as 071
169 treated as 170     200 treated as 043     227 treated as 112
176 treated as 221     201 treated as 043     228 treated as 083
177 treated as 221     202 treated as 045     229 treated as 115
178 treated as 221     203 treated as 045     231 treated as 116
179 treated as 221     204 treated as 221     232 treated as 070
180 treated as 221     205 treated as 045     233 treated as 084
181 treated as 221     206 treated as 043     234 treated as 079
182 treated as 221     207 treated as 045     235 treated as 100
183 treated as 043     208 treated as 045     236 treated as 056
184 treated as 043     209 treated as 045     237 treated as 102
185 treated as 221     210 treated as 045     238 treated as 101
186 treated as 221     211 treated as 043     239 treated as 110
187 treated as 043     212 treated as 043     240 treated as 061
188 treated as 043     213 treated as 043     242 treated as 061
189 treated as 043     214 treated as 043     243 treated as 061
190 treated as 043     215 treated as 043     244 treated as 040
191 treated as 043     216 treated as 043     245 treated as 041
192 treated as 043     217 treated as 043     247 treated as 126
193 treated as 045     218 treated as 043     249 treated as 250
194 treated as 045     219 treated as 221     251 treated as 118
195 treated as 043     220 treated as 095     252 treated as 110
196 treated as 045     222 treated as 221     254 treated as 221
197 treated as 043     223 treated as 095
198 treated as 221     224 treated as 097

Any character >0 not in the list above is treated as itself, including <CR> and <LF>. The easiest way to include odd characters like <CR> and <LF> is to get them into an environment variable and use delayed expansion within the command line argument.

Character limits for strings found in files specified by /G:FILE and /F:FILE options
The nul (0x00) character can appear in the file, but it functions like the C string terminator. Any characters after a nul character are treated as a different string as if they were on another line.

The <CR> and <LF> characters are treated as line terminators that terminate a string, and are not included in the string.

All other single byte characters are included perfectly within a string.

Searching Unicode files
FINDSTR cannot properly search most Unicode (UTF-16, UTF-16LE, UTF-16BE, UTF-32) because it cannot search for nul bytes and Unicode typically contains many nul bytes.

However, the TYPE command converts UTF-16LE with BOM to a single byte character set, so a command like the following will work with UTF-16LE with BOM.

type unicode.txt|findstr "search"

Note that Unicode code points that are not supported by your active code page will be converted to ? characters.

It is possible to search UTF-8 as long as your search string contains only ASCII. However, the console output of any multi-byte UTF-8 characters will not be correct. But if you redirect the output to a file, then the result will be correctly encoded UTF-8. Note that if the UTF-8 file contains a BOM, then the BOM will be considered as part of the first line, which could throw off a search that matches the beginning of a line.

It is possible to search multi-byte UTF-8 characters if you put your search string in a UTF-8 encoded search file (without BOM), and use the /G option.

End Of Line
FINDSTR breaks lines immediately after every <LF>. The presence or absence of <CR> has no impact on line breaks.

Searching across line breaks
As expected, the . regex metacharacter will not match <CR> or <LF>. But it is possible to search across a line break using a command line search string. Both the <CR> and <LF> characters must be matched explicitly. If a multi-line match is found, only the 1st line of the match is printed. FINDSTR then doubles back to the 2nd line in the source and begins the search all over again - sort of a "look ahead" type feature.

Assume TEXT.TXT has these contents (could be Unix or Windows style)

A
A
A
B
A
A

Then this script

@echo off
setlocal
::Define LF variable containing a linefeed (0x0A)
set LF=^


::Above 2 blank lines are critical - do not remove

::Define CR variable containing a carriage return (0x0D)
for /f %%a in ('copy /Z "%~dpf0" nul') do set "CR=%%a"

setlocal enableDelayedExpansion
::regex "!CR!*!LF!" will match both Unix and Windows style End-Of-Line
findstr /n /r /c:"A!CR!*!LF!A" TEST.TXT

gives these results

1:A
2:A
5:A

Searching across line breaks using the /G:FILE option is imprecise because the only way to match <CR> or <LF> is via a regex character class range expression that sandwiches the EOL characters.

  • [<TAB>-<0x0B>] matches <LF>, but it also matches <TAB> and <0x0B>

  • [<0x0C>-!] matches <CR>, but it also matches <0x0C> and !

Note - the above are symbolic representations of the regex byte stream since I can't graphically represent the characters.

Answer continued in part 2 below...

"Full screen" <iframe>

You can use this piece of code:

  <iframe src="http://example.com" frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0%;left:0px;right:0px;bottom:0px" height="100%" width="100%"></iframe>

Configure Flask dev server to be visible across the network

go to project path set FLASK_APP=ABC.py SET FLASK_ENV=development

flask run -h [yourIP] -p 8080 you will following o/p on CMD:- * Serving Flask app "expirement.py" (lazy loading) * Environment: development * Debug mode: on * Restarting with stat * Debugger is active! * Debugger PIN: 199-519-700 * Running on http://[yourIP]:8080/ (Press CTRL+C to quit)

Could not load file or assembly "Oracle.DataAccess" or one of its dependencies

I needed a 64-bit version of oracle.dataaccess.dll but this caused problems with other libraries I was using.

[BadImageFormatException: Could not load file or assembly 'Oracle.DataAccess' or one of its dependencies. An attempt was made to load a program with an incorrect format.]

I followed several steps above. Going to advance settings on the projects pool to toggle allow 32bit worked but I wasn't content to leave it like that so i turned it back on.

My project also had references that relied on Elmah and log4net references. I downloaded the latest version of these and my project was able to build and run fine without messing with the pools's allow 32bit setting.

$(document).ready(function(){ Uncaught ReferenceError: $ is not defined

$ is a function provided by the jQuery library, it won't be available unless you have loaded the jQuery library.

You need to add jQuery (typically with a <script> element which can point at a local copy of the library or one hosted on a CDN). Make sure you are using a current and supported version: Many answers on this question recommend using 1.x or 2.x versions of jQuery which are no longer supported and have known security issues.

<script src="/path/to/jquery.js"></script>

Make sure you load jQuery before you run any script which depends on it.

The jQuery homepage will have a link to download the current version of the library (at the time of writing it is 3.5.1 but that may change by the time you read this).

Further down the page you will find a section on using jQuery with a CDN which links to a number of places that will host the library for you.


(NB: Some other libraries provide a $ function, and browsers have native $ variables which are only available in the Developer Tools Console, but this question isn't about those).

Best way to alphanumeric check in JavaScript

In a tight loop, it's probably better to avoid regex and hardcode your characters:

const CHARS = new Set("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
function isAlphanumeric(char) {
    return CHARS.has(char);
}

How should I escape strings in JSON?

org.json.JSONObject quote(String data) method does the job

import org.json.JSONObject;
String jsonEncodedString = JSONObject.quote(data);

Extract from the documentation:

Encodes data as a JSON string. This applies quotes and any necessary character escaping. [...] Null will be interpreted as an empty string

How does it work - requestLocationUpdates() + LocationRequest/Listener

I use this one:

LocationManager.requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)

For example, using a 1s interval:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);

the time is in milliseconds, the distance is in meters.

This automatically calls:

public void onLocationChanged(Location location) {
    //Code here, location.getAccuracy(), location.getLongitude() etc...
}

I also had these included in the script but didnt actually use them:

public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}

In short:

public class GPSClass implements LocationListener {

    public void onLocationChanged(Location location) {
        // Called when a new location is found by the network location provider.
        Log.i("Message: ","Location changed, " + location.getAccuracy() + " , " + location.getLatitude()+ "," + location.getLongitude());
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {}
    public void onProviderEnabled(String provider) {}
    public void onProviderDisabled(String provider) {}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
    }
}

Access VBA | How to replace parts of a string with another string

Use Access's VBA function Replace(text, find, replacement):

Dim result As String

result = Replace("Some sentence containing Avenue in it.", "Avenue", "Ave")

What does the variable $this mean in PHP?

It is the way to reference an instance of a class from within itself, the same as many other object oriented languages.

From the PHP docs:

The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).

Get timezone from DateTime

There is a public domain TimeZone library for .NET. Really useful. It will answer your needs.

Solving the general-case timezone problem is harder than you think.

How can I scale the content of an iframe?

If you want the iframe and its contents to scale when the window resizes, you can set the following to the window's resize event as well as the iframes onload event.

function()
{
    var _wrapWidth=$('#wrap').width();
    var _frameWidth=$($('#frame')[0].contentDocument).width();

    if(!this.contentLoaded)
      this.initialWidth=_frameWidth;
    this.contentLoaded=true;
    var frame=$('#frame')[0];

    var percent=_wrapWidth/this.initialWidth;

    frame.style.width=100.0/percent+"%";
    frame.style.height=100.0/percent+"%";

    frame.style.zoom=percent;
    frame.style.webkitTransform='scale('+percent+')';
    frame.style.webkitTransformOrigin='top left';
    frame.style.MozTransform='scale('+percent+')';
    frame.style.MozTransformOrigin='top left';
    frame.style.oTransform='scale('+percent+')';
    frame.style.oTransformOrigin='top left';
  };

This will make the iframe and its content scale to 100% width of the wrap div (or whatever percent you want). As an added bonus, you don't have to set the css of the frame to hard coded values since they'll all be set dynamically, you'll just need to worry about how you want the wrap div to display.

I've tested this and it works on chrome, IE11, and firefox.

onclick event function in JavaScript

Check you are calling same function or not.

<script>function greeting(){document.write("hi");}</script>

<input type="button" value="Click Here" onclick="greeting();"/>

How do I read the file content from the Internal storage - Android App

Take a look this how to use storages in android http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

To read data from internal storage you need your app files folder and read content from here

String yourFilePath = context.getFilesDir() + "/" + "hello.txt";
File yourFile = new File( yourFilePath );

Also you can use this approach

FileInputStream fis = context.openFileInput("hello.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
    sb.append(line);
}

How to submit form on change of dropdown list?

To those in the answer above. It's definitely JavaScript. It's just inline.

BTW the jQuery equivalent if you want to apply to all selects:

$('form select').on('change', function(){
    $(this).closest('form').submit();
});

Table cell widths - fixing width, wrapping/truncating long words

Stack Overflow has solved a similar problem with long lines of code by using a DIV and having overflow-x:auto. CSS can't break up words for you.

PHP: Show yes/no confirmation dialog

What I usually do is create a delete page that shows a confirmation form if the request method is "GET" and deletes the data if the method was "POST" and the user chose the "Yes" option.

Then, in the page with the delete link, I add an onclick function (or just use the jQuery confirm plugin) that uses AJAX to post to the link, bypassing the confirmation page.

Here's the idea in pseudo code:

delete.php:

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if ($_POST['confirm'] == 'Yes') {
        delete_record($_REQUEST['id']); // From GET or POST variables
    }
    redirect($_POST['referer']);
}
?>

<form action="delete.php" method="post">
    Are you sure?
    <input type="submit" name="confirm" value="Yes">
    <input type="submit" name="confirm" value="No">

    <input type="hidden" name="id" value="<?php echo $_GET['id']; ?>">
    <input type="hidden" name="referer" value="<?php echo $_SERVER['HTTP_REFERER']; ?>">
</form>

Page with delete link:

<script>
    function confirmDelete(link) {
        if (confirm("Are you sure?")) {
            doAjax(link.href, "POST"); // doAjax needs to send the "confirm" field
        }
        return false;
    }
</script>

<a href="delete.php?id=1234" onclick="return confirmDelete(this);">Delete record</a>

How to restore default perspective settings in Eclipse IDE

Alt+w-->or click on window tab -->ResetPerspective

What is the difference between a 'closure' and a 'lambda'?

This question is old and got many answers.
Now with Java 8 and Official Lambda that are unofficial closure projects, it revives the question.

The answer in Java context (via Lambdas and closures — what’s the difference?):

"A closure is a lambda expression paired with an environment that binds each of its free variables to a value. In Java, lambda expressions will be implemented by means of closures, so the two terms have come to be used interchangeably in the community."

Changing website favicon dynamically

I use favico.js in my projects.

It allows to change the favicon to a range of predefined shapes and also custom ones.

Internally it uses canvas for rendering and base64 data URL for icon encoding.

The library also has nice features: icon badges and animations; purportedly, you can even stream the webcam video into the icon :)

Difference between ApiController and Controller in ASP.NET MVC

I love the fact that ASP.NET Core's MVC6 merged the two patterns into one because I often need to support both worlds. While it's true that you can tweak any standard MVC Controller (and/or develop your own ActionResult classes) to act & behave just like an ApiController, it can be very hard to maintain and to test: on top of that, having Controllers methods returning ActionResult mixed with others returning raw/serialized/IHttpActionResult data can be very confusing from a developer perspective, expecially if you're not working alone and need to bring other developers to speed with that hybrid approach.

The best technique I've come so far to minimize that issue in ASP.NET non-Core web applications is to import (and properly configure) the Web API package into the MVC-based Web Application, so I can have the best of both worlds: Controllers for Views, ApiControllers for data.

In order to do that, you need to do the following:

  • Install the following Web API packages using NuGet: Microsoft.AspNet.WebApi.Core and Microsoft.AspNet.WebApi.WebHost.
  • Add one or more ApiControllers to your /Controllers/ folder.
  • Add the following WebApiConfig.cs file to your /App_Config/ folder:

using System.Web.Http;

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Finally, you'll need to register the above class to your Startup class (either Startup.cs or Global.asax.cs, depending if you're using OWIN Startup template or not).

Startup.cs

 public void Configuration(IAppBuilder app)
 {
    // Register Web API routing support before anything else
    GlobalConfiguration.Configure(WebApiConfig.Register);

    // The rest of your file goes there
    // ...
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    ConfigureAuth(app);
    // ...
}

Global.asax.cs

protected void Application_Start()
{
    // Register Web API routing support before anything else
    GlobalConfiguration.Configure(WebApiConfig.Register);

    // The rest of your file goes there
    // ...
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    // ...
}

This approach - together with its pros and cons - is further explained in this post I wrote on my blog.

How to re-sync the Mysql DB if Master and slave have different database incase of Mysql replication?

Rebuilding the slave using LVM

Here is the method we use to rebuild MySQL slaves using Linux LVM. This guarantees a consistent snapshot while requiring very minimal downtime on your master.

Set innodb max dirty pages percent to zero on the master MySQL server. This will force MySQL to write all the pages to the disk which will significantly speed up the restart.

set global innodb_max_dirty_pages_pct = 0;

To monitor the number of dirty pages run the command

mysqladmin ext -i10 | grep dirty

Once the number stop decreasing you have reach the point to continue. Next reset the master to clear the old bin logs / relay logs:

RESET MASTER;

Execute lvdisplay to get LV Path

lvdisplay

Output will look like this

--- Logical volume ---
LV Path                /dev/vg_mysql/lv_data
LV Name                lv_data
VG Name                vg_mysql

Shutdown the master database with command

service mysql stop

Next take a snaphot, mysql_snapshot will be the new logical volume name. If binlogs are place on the OS drive those need to be snapshot as well.

lvcreate --size 10G --snapshot --name mysql_snapshot /dev/vg_mysql/lv_data

Start master again with command

service mysql start

Restore dirty pages setting to the default

set global innodb_max_dirty_pages_pct = 75;

Run lvdisplay again to make sure the snapshot is there and visible

lvdisplay

Output:

--- Logical volume ---
LV Path                /dev/vg_mysql/mysql_snapshot
LV Name                mysql_snapshot
VG Name                vg_mysql

Mount the snapshot

mkdir /mnt/mysql_snapshot
mount /dev/vg_mysql/mysql_snapshot /mnt/mysql_snapshot

If you have an existing MySQL slave running you need to stop it

service mysql stop

Next you need to clear MySQL data folder

cd /var/lib/mysql
rm -fr *

Back to master. Now rsync the snapshot to the MySQL slave

rsync --progress -harz /mnt/mysql_snapshot/ targethostname:/var/lib/mysql/

Once rsync has completed you may unmount and remove the snapshot

umount /mnt/mysql_snapshot
lvremove -f /dev/vg_mysql/mysql_snapshot

Create replication user on the master if the old replication user doesn't exist or password is unknown

GRANT REPLICATION SLAVE on *.* to 'replication'@'[SLAVE IP]' identified by 'YourPass';

Verify that /var/lib/mysql data files are owned by the mysql user, if so you can omit the following command:

chown -R mysql:mysql /var/lib/mysql

Next record the binlog position

ls -laF | grep mysql-bin

You will see something like

..
-rw-rw----     1 mysql mysql  1073750329 Aug 28 03:33 mysql-bin.000017
-rw-rw----     1 mysql mysql  1073741932 Aug 28 08:32 mysql-bin.000018
-rw-rw----     1 mysql mysql   963333441 Aug 28 15:37 mysql-bin.000019
-rw-rw----     1 mysql mysql    65657162 Aug 28 16:44 mysql-bin.000020

Here the master log file is the highest file number in sequence and bin log position is the file size. Record these values:

master_log_file=mysql-bin.000020
master_log_post=65657162

Next start the slave MySQL

service mysql start

Execute change master command on the slave by executing the following:

CHANGE MASTER TO 
master_host="10.0.0.12", 
master_user="replication", 
master_password="YourPass", 
master_log_file="mysql-bin.000020", 
master_log_pos=65657162; 

Finally start the slave

SLAVE START;

Check slave status:

SHOW SLAVE STATUS;

Make sure Slave IO is running and there are no connection errors. Good luck!

BR, Juha Vehnia

I recently wrote this on my blog which is found here... There are few more details there but the story is the same.

http://www.juhavehnia.com/2015/05/rebuilding-mysql-slave-using-linux-lvm.html

"Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project

One of the possible reasons is when you load jQuery TWICE ,like:

<script src='..../jquery.js'></script>
....
....
....
....
....
<script src='......./jquery.js'></script>

So, check your source code and remove duplicate jQuery load.

How can I force component to re-render with hooks in React?

You should preferably only have your component depend on state and props and it will work as expected, but if you really need a function to force the component to re-render, you could use the useState hook and call the function when needed.

Example

_x000D_
_x000D_
const { useState, useEffect } = React;_x000D_
_x000D_
function Foo() {_x000D_
  const [, forceUpdate] = useState();_x000D_
_x000D_
  useEffect(() => {_x000D_
    setTimeout(forceUpdate, 2000);_x000D_
  }, []);_x000D_
_x000D_
  return <div>{Date.now()}</div>;_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Foo />, document.getElementById("root"));
_x000D_
<script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>_x000D_
<script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>_x000D_
_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

Provide password to ssh command inside bash script, Without the usage of public keys and Expect

For security reasons you must avoid providing password on a command line otherwise anyone running ps command can see your password. Better to use sshpass utility like this:

#!/bin/bash

export SSHPASS="your-password"
sshpass -e ssh -oBatchMode=no sshUser@remoteHost

You might be interested in How to run the sftp command with a password from Bash script?

move a virtual machine from one vCenter to another vCenter

I've figure it out the solution to my problem:

  • Step 1: from within the vSphere client, while connected to vCenter1, select the VM and then from "File" menu select "Export"->"Export OVF Template" (Note: make sure the VM is Powered Off otherwise this feature is not available - it will be gray). This action will allow you to save on your machine/laptop the VM (as an .vmdk, .ovf and a .mf file).
  • Step 2: Connect to the vCenter2 with your vSphere client and from "File" menu select "Deploy OVF Template..." and then select the location where the VM was saved in the previous step.

That was all!
Thanks!

Git Checkout warning: unable to unlink files, permission denied

In my first encounter with this error my user had rights to "write" to the file but not the containing directory. Check the permissions of the directory containing the file.

Launching Spring application Address already in use

This only worked for me by setting additional properties and using available arbitrary port numbers, like this:

  • YML

/src/main/resources/application.yml

server:
  port: 18181
management:
  port: 9191
tomcat:
  jvmroute: 5478
  ajp:
    port: 4512
    redirectPort: 1236
  • Properties

/src/main/resources/application.properties

server.port=18181
management.port=9191
tomcat.jvmroute=5478
tomcat.ajp.port=4512
tomcat.ajp.redirectPort=1236     

Cookies on localhost with explicit domain

I had much better luck testing locally using 127.0.0.1 as the domain. I'm not sure why, but I had mixed results with localhost and .localhost, etc.

Applying a single font to an entire website with CSS

*{font-family:Algerian;}

this html worked for me. Added to canvas settings in wordpress.

Looks cool - thanks !

converting list to json format - quick and easy way

why reinvent the wheel? use microsoft's json serialize or a 3rd party library such as json.NET

Sum the digits of a number

Doing some Codecademy challenges I resolved this like:

def digit_sum(n):
    digits = []
    nstr = str(n)
    for x in nstr:
        digits.append(int(x))
    return sum(digits)

How to debug stored procedures with print statements?

try using:

RAISERROR('your message here!!!',0,1) WITH NOWAIT

you could also try switching to "Results to Text" it is just a few icons to the right of "Execute" on the default tool bar.

With both of the above in place, and you still you do not see the messages, make sure you are running the same server/database/owner version of the procedure that you are editing. Make sure you are hitting the RAISERROR command, make it the first command inside the procedure.

If all else fails, you could create a table:

create table temp_log (RowID int identity(1,1) primary key not null
                      , MessageValue varchar(255))

then:

INSERT INTO temp_log VALUES ('Your message here')

then after running the procedure (provided no rollbacks) just select the table.

Ternary operator in AngularJS templates

For texts in angular template (userType is property of $scope, like $scope.userType):

<span>
  {{userType=='admin' ? 'Edit' : 'Show'}}
</span>

How to loop in excel without VBA or macros?

You could create a table somewhere on a calculation spreadsheet which performs this operation for each pair of cells, and use auto-fill to fill it up.

Aggregate the results from that table into a results cell.

The 200 so cells which reference the results could then reference the cell that holds the aggregation results. In the newest versions of excel you can name the result cell and reference it that way, for ease of reading.

Error related to only_full_group_by when executing a query in MySql

I would just add group_id to the GROUP BY.

When SELECTing a column that is not part of the GROUP BY there could be multiple values for that column within the groups, but there will only be space for a single value in the results. So, the database usually needs to be told exactly how to make those multiple values into one value. Commonly, this is done with an aggregate function like COUNT(), SUM(), MAX() etc... I say usually because most other popular database systems insist on this. However, in MySQL prior to version 5.7 the default behaviour has been more forgiving because it will not complain and then arbitrarily choose any value! It also has an ANY_VALUE() function that could be used as another solution to this question if you really needed the same behaviour as before. This flexibility comes at a cost because it is non-deterministic, so I would not recommend it unless you have a very good reason for needing it. MySQL are now turning on the only_full_group_by setting by default for good reasons, so it's best to get used to it and make your queries comply with it.

So why my simple answer above? I've made a couple of assumptions:

1) the group_id is unique. Seems reasonable, it is an 'ID' after all.

2) the group_name is also unique. This may not be such a reasonable assumption. If this is not the case and you have some duplicate group_names and you then follow my advice to add group_id to the GROUP BY, you may find that you now get more results than before because the groups with the same name will now have separate rows in the results. To me, this would be better than having these duplicate groups hidden because the database has quietly selected a value arbitrarily!

It's also good practice to qualify all the columns with their table name or alias when there's more than one table involved...

SELECT 
  g.group_id AS 'value', 
  g.group_name AS 'text' 
FROM mod_users_groups g
LEFT JOIN mod_users_data d ON g.group_id = d.group_id 
WHERE g.active = 1 
  AND g.department_id = 1 
  AND g.manage_work_orders = 1 
  AND g.group_name != 'root' 
  AND g.group_name != 'superuser' 
GROUP BY 
  g.group_name, 
  g.group_id 
HAVING COUNT(d.user_id) > 0 
ORDER BY g.group_name

How to select bottom most rows?

I've come up with a solution to this that doesn't require you to know the number of row returned.

For example, if you want to get all the locations logged in a table, except the latest 1 (or 2, or 5, or 34)

SELECT * 
FROM
    (SELECT ROW_NUMBER() OVER (ORDER BY CreatedDate) AS Row, * 
    FROM Locations
    WHERE UserId = 12345) AS SubQuery
WHERE Row > 1 -- or 2, or 5, or 34

React Native android build failed. SDK location not found

Check out in your local.properties file:

sdk.dir=C\:\\Users\\USERNAME\\AppData\\Local\\Android\\sdk

if the format is proper or not

How to create string with multiple spaces in JavaScript

var a = 'something' + Array(10).fill('\xa0').join('') + 'something'

number inside Array(10) can be changed to needed number of spaces

Convert string into integer in bash script - "Leading Zero" number error

How about sed?

hour=`echo $hour|sed -e "s/^0*//g"`

Return sql rows where field contains ONLY non-alphanumeric characters

If you have short strings you should be able to create a few LIKE patterns ('[^a-zA-Z0-9]', '[^a-zA-Z0-9][^a-zA-Z0-9]', ...) to match strings of different length. Otherwise you should use CLR user defined function and a proper regular expression - Regular Expressions Make Pattern Matching And Data Extraction Easier.

Reliable way to convert a file to a byte[]

Not to repeat what everyone already have said but keep the following cheat sheet handly for File manipulations:

  1. System.IO.File.ReadAllBytes(filename);
  2. File.Exists(filename)
  3. Path.Combine(folderName, resOfThePath);
  4. Path.GetFullPath(path); // converts a relative path to absolute one
  5. Path.GetExtension(path);

Changing .gitconfig location on Windows

I have solved this problem using a slightly different approach that I have seen work for other configuration files. Git Config supports includes that allows you to point to a configuration file in another location. That alternate location is then imported and expanded in place as if it was part of .gitconfig file. So now I just have a single entry in .gitconfig:

[include]
   path = c:\\path\\to\\my.config

Any updates written by Git to the .gitconfig file will not overwrite my include path. It does mean that occasionally I may need to move values from .gitconfig to my.config.

How to distinguish between left and right mouse click with jQuery

You can easily tell which mouse button was pressed by checking the which property of the event object on mouse events:

/*
  1 = Left   mouse button
  2 = Centre mouse button
  3 = Right  mouse button
*/

$([selector]).mousedown(function(e) {
    if (e.which === 3) {
        /* Right mouse button was clicked! */
    }
});

How to programmatically set the layout_align_parent_right attribute of a Button in Relative Layout?

  1. you need to create and id for the buttons you need to refference: btn1.setId(1);
  2. you can use the params variable to add parameters to your layout, i think the method is addRule(), check out the android java docs for this LayoutParams object.

How to get first and last element in an array in java?

I think there is only one intuitive solution and it is:

int[] someArray = {1,2,3,4,5};
int first = someArray[0];
int last = someArray[someArray.length - 1];
System.out.println("First: " + first + "\n" + "Last: " + last);

Output:

First: 1
Last: 5

Printing the value of a variable in SQL Developer

select View-->DBMS Output in menu and

C++ getters/setters coding style

Avoid public variables, except for classes that are essentially C-style structs. It's just not a good practice to get into.

Once you've defined the class interface, you might never be able to change it (other than adding to it), because people will build on it and rely on it. Making a variable public means that you need to have that variable, and you need to make sure it has what the user needs.

Now, if you use a getter, you're promising to supply some information, which is currently kept in that variable. If the situation changes, and you'd rather not maintain that variable all the time, you can change the access. If the requirements change (and I've seen some pretty odd requirements changes), and you mostly need the name that's in this variable but sometimes the one in that variable, you can just change the getter. If you made the variable public, you'd be stuck with it.

This won't always happen, but I find it a lot easier just to write a quick getter than to analyze the situation to see if I'd regret making the variable public (and risk being wrong later).

Making member variables private is a good habit to get into. Any shop that has code standards is probably going to forbid making the occasional member variable public, and any shop with code reviews is likely to criticize you for it.

Whenever it really doesn't matter for ease of writing, get into the safer habit.

How to kill a child process after a given timeout in Bash?

Here's the third answer I've submitted here. This one handles signal interrupts and cleans up background processes when SIGINT is received. It uses the $BASHPID and exec trick used in the top answer to get the PID of a process (in this case $$ in a sh invocation). It uses a FIFO to communicate with a subshell that is responsible for killing and cleanup. (This is like the pipe in my second answer, but having a named pipe means that the signal handler can write into it too.)

run_with_timeout ()
{
  t=$1 ; shift

  trap cleanup 2

  F=$$.fifo ; rm -f $F ; mkfifo $F

  # first, run main process in background
  "$@" & pid=$!

  # sleeper process to time out
  ( sh -c "echo \$\$ >$F ; exec sleep $t" ; echo timeout >$F ) &
  read sleeper <$F

  # control shell. read from fifo.
  # final input is "finished".  after that
  # we clean up.  we can get a timeout or a
  # signal first.
  ( exec 0<$F
    while : ; do
      read input
      case $input in
        finished)
          test $sleeper != 0 && kill $sleeper
          rm -f $F
          exit 0
          ;;
        timeout)
          test $pid != 0 && kill $pid
          sleeper=0
          ;;
        signal)
          test $pid != 0 && kill $pid
          ;;
      esac
    done
  ) &

  # wait for process to end
  wait $pid
  status=$?
  echo finished >$F
  return $status
}

cleanup ()
{
  echo signal >$$.fifo
}

I've tried to avoid race conditions as far as I can. However, one source of error I couldn't remove is when the process ends near the same time as the timeout. For example, run_with_timeout 2 sleep 2 or run_with_timeout 0 sleep 0. For me, the latter gives an error:

timeout.sh: line 250: kill: (23248) - No such process

as it is trying to kill a process that has already exited by itself.

Remove all whitespaces from NSString

This for me is the best way SWIFT

        let myString = "  ciao   \n              ciao     "
        var finalString = myString as NSString

        for character in myString{
        if character == " "{

            finalString = finalString.stringByReplacingOccurrencesOfString(" ", withString: "")

        }else{
            finalString = finalString.stringByReplacingOccurrencesOfString("\n", withString: "")

        }

    }
     println(finalString)

and the result is : ciaociao

But the trick is this!

 extension String {

    var NoWhiteSpace : String {

    var miaStringa = self as NSString

    if miaStringa.containsString(" "){

      miaStringa =  miaStringa.stringByReplacingOccurrencesOfString(" ", withString: "")
    }
        return miaStringa as String

    }
}

let myString = "Ciao   Ciao       Ciao".NoWhiteSpace  //CiaoCiaoCiao

Adding a month to a date in T SQL

Use DATEADD:

DATEADD(month, 1, reference_dt)

Multiple arguments to function called by pthread_create()?

Use:

struct arg_struct *args = malloc(sizeof(struct arg_struct));

And pass this arguments like this:

pthread_create(&tr, NULL, print_the_arguments, (void *)args);

Don't forget free args! ;)

Shortcut key for commenting out lines of Python code in Spyder

  • Single line comment

    Ctrl + 1

  • Multi-line comment select the lines to be commented

    Ctrl + 4

  • Unblock Multi-line comment

    Ctrl + 5

How do I tell if a regular file does not exist in Bash?

I prefer to do the following one-liner, in POSIX shell compatible format:

$ [ -f "/$DIR/$FILE" ] || echo "$FILE NOT FOUND"

$ [ -f "/$DIR/$FILE" ] && echo "$FILE FOUND"

For a couple of commands, like I would do in a script:

$  [ -f "/$DIR/$FILE" ] || { echo "$FILE NOT FOUND" ; exit 1 ;}

Once I started doing this, I rarely use the fully typed syntax anymore!!

Python, compute list difference

The above examples trivialized the problem of calculating differences. Assuming sorting or de-duplication definitely make it easier to compute the difference, but if your comparison cannot afford those assumptions then you'll need a non-trivial implementation of a diff algorithm. See difflib in the python standard library.

#! /usr/bin/python2
from difflib import SequenceMatcher

A = [1,2,3,4]
B = [2,5]

squeeze=SequenceMatcher( None, A, B )

print "A - B = [%s]"%( reduce( lambda p,q: p+q,
                               map( lambda t: squeeze.a[t[1]:t[2]],
                                    filter(lambda x:x[0]!='equal',
                                           squeeze.get_opcodes() ) ) ) )

Or Python3...

#! /usr/bin/python3
from difflib import SequenceMatcher
from functools import reduce

A = [1,2,3,4]
B = [2,5]

squeeze=SequenceMatcher( None, A, B )

print( "A - B = [%s]"%( reduce( lambda p,q: p+q,
                               map( lambda t: squeeze.a[t[1]:t[2]],
                                    filter(lambda x:x[0]!='equal',
                                           squeeze.get_opcodes() ) ) ) ) )

Output:

A - B = [[1, 3, 4]]

Popup window in winform c#

"But the thing is I also want to be able to add textboxes etc in this popup window thru the form designer."

It's unclear from your description at what stage in the development process you're in. If you haven't already figured it out, to create a new Form you click on Project --> Add Windows Form, then type in a name for the form and hit the "Add" button. Now you can add controls to your form as you'd expect.

When it comes time to display it, follow the advice of the other posts to create an instance and call Show() or ShowDialog() as appropriate.

Stop handler.postDelayed()

You can define a boolean and change it to false when you want to stop handler. Like this..

boolean stop = false;

handler.postDelayed(new Runnable() {
    @Override
    public void run() {

        //do your work here..

        if (!stop) {
            handler.postDelayed(this, delay);
        }
    }
}, delay);

Raw SQL Query without DbSet - Entity Framework Core

You can also use QueryFirst. Like Dapper, this is totally outside EF. Unlike Dapper (or EF), you don't need to maintain the POCO, you edit your sql SQL in a real environment, and it's continually revalidated against the DB. Disclaimer: I'm the author of QueryFirst.

C# using Sendkey function to send a key to another application

If notepad is already started, you should write:

// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);

//...

Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
    IntPtr h = p.MainWindowHandle;
    SetForegroundWindow(h);
    SendKeys.SendWait("k");
}

GetProcessesByName returns an array of processes, so you should get the first one (or find the one you want).

If you want to start notepad and send the key, you should write:

Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");

The only situation in which the code may not work is when notepad is started as Administrator and your application is not.

How to import existing *.sql files in PostgreSQL 8.4?

Well, the shortest way I know of, is following:

psql -U {user_name} -d {database_name} -f {file_path} -h {host_name}

database_name: Which database should you insert your file data in.

file_path: Absolute path to the file through which you want to perform the importing.

host_name: The name of the host. For development purposes, it is mostly localhost.

Upon entering this command in console, you will be prompted to enter your password.

Downloading all maven dependencies to a directory NOT in repository?

I found the next command

mvn dependency:copy-dependencies -Dclassifier=sources

here maven.apache.org

How to access parent Iframe from JavaScript

// just in case some one is searching for a solution
function get_parent_frame_dom_element(win)
{
    win = (win || window);
    var parentJQuery = window.parent.jQuery;
    var ifrms = parentJQuery("iframe.upload_iframe");
    for (var i = 0; i < ifrms.length; i++)
    {
        if (ifrms[i].contentDocument === win.document)
            return ifrms[i];
    }
    return null;
}

Javascript loop through object array?

It appears you may just have missed the "messages" property in the data, so the loop is likely iterating the root Object rather than the Array:

for (var key in data.messages) {
    var obj = data.messages[key];
    // ...
}

Unless data was set to messages before the given snippet.

Though, you should consider changing that to a normal for loop for the Array:

for (var i = 0, l = data.messages.length; i < l; i++) {
    var obj = data.messages[i];
    // ...
}

When to use 'raise NotImplementedError'?

Consider if instead it was:

class RectangularRoom(object):
    def __init__(self, width, height):
        pass

    def cleanTileAtPosition(self, pos):
        pass

    def isTileCleaned(self, m, n):
        pass

and you subclass and forget to tell it how to isTileCleaned() or, perhaps more likely, typo it as isTileCLeaned(). Then in your code, you'll get a None when you call it.

  • Will you get the overridden function you wanted? Definitely not.
  • Is None valid output? Who knows.
  • Is that intended behavior? Almost certainly not.
  • Will you get an error? It depends.

raise NotImplmentedError forces you to implement it, as it will throw an exception when you try to run it until you do so. This removes a lot of silent errors. It's similar to why a bare except is almost never a good idea: because people make mistakes and this makes sure they aren't swept under the rug.

Note: Using an abstract base class, as other answers have mentioned, is better still, as then the errors are frontloaded and the program won't run until you implement them (with NotImplementedError, it will only throw an exception if actually called).

CSS get height of screen resolution

You could use viewport-percentage lenghts.

See: http://stanhub.com/how-to-make-div-element-100-height-of-browser-window-using-css-only/

It works like this:

.element{
    height: 100vh; /* For 100% screen height */
    width:  100vw; /* For 100% screen width */
}

More info also available through Mozilla Developer Network and W3C.

biggest integer that can be stored in a double

Wikipedia has this to say in the same context with a link to IEEE 754:

On a typical computer system, a 'double precision' (64-bit) binary floating-point number has a coefficient of 53 bits (one of which is implied), an exponent of 11 bits, and one sign bit.

2^53 is just over 9 * 10^15.

Return rows in random order

SELECT * FROM table
ORDER BY NEWID()

Upgrading PHP on CentOS 6.5 (Final)

  1. Verify current version of PHP Type in the following to see the current PHP version:

    php -v

    Should output something like:

    PHP 5.3.3 (cli) (built: Jul 9 2015 17:39:00) Copyright (c) 1997-2010 The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies

  2. Install the Remi and EPEL RPM repositories

If you haven’t already done so, install the Remi and EPEL repositories

wget https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm && rpm -Uvh epel-release-latest-6.noarch.rpm



wget http://rpms.famillecollet.com/enterprise/remi-release-6.rpm && rpm -Uvh remi-release-6*.rpm

Enable the REMI repository globally:

nano /etc/yum.repos.d/remi.repo

Under the section that looks like [remi] make the following changes:

[remi]
name=Remi's RPM repository for Enterprise Linux 6 - $basearch
#baseurl=http://rpms.remirepo.net/enterprise/6/remi/$basearch/
mirrorlist=http://rpms.remirepo.net/enterprise/6/remi/mirror
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-remi

Also, under the section that looks like [remi-php55] make the following changes:

[remi-php56]
name=Remi's PHP 5.6 RPM repository for Enterprise Linux 6 - $basearch
#baseurl=http://rpms.remirepo.net/enterprise/6/php56/$basearch/
mirrorlist=http://rpms.remirepo.net/enterprise/6/php56/mirror
# WARNING: If you enable this repository, you must also enable "remi"
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-remi

Type CTRL-O to save and CTRL-X to close the editor

  1. Upgrade PHP 5.3 to PHP 5.6 Now we can upgrade PHP. Simply type in the following command:

    yum -y upgrade php*

Once the update has completed, let’s verify that you have PHP 5.6 installed:

php -v

Should see output similar to the following:

PHP 5.6.14 (cli) (built: Sep 30 2015 14:07:43) 
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies

Simple timeout in java

Nowadays you can use

try {
    String s = CompletableFuture.supplyAsync(() -> br.readLine())
                                .get(1, TimeUnit.SECONDS);
} catch (TimeoutException e) {
    System.out.println("Time out has occurred");
} catch (InterruptedException | ExecutionException e) {
    // Handle
}

Object Required Error in excel VBA

The Set statement is only used for object variables (like Range, Cell or Worksheet in Excel), while the simple equal sign '=' is used for elementary datatypes like Integer. You can find a good explanation for when to use set here.

The other problem is, that your variable g1val isn't actually declared as Integer, but has the type Variant. This is because the Dim statement doesn't work the way you would expect it, here (see example below). The variable has to be followed by its type right away, otherwise its type will default to Variant. You can only shorten your Dim statement this way:

Dim intColumn As Integer, intRow As Integer  'This creates two integers

For this reason, you will see the "Empty" instead of the expected "0" in the Watches window.

Try this example to understand the difference:

Sub Dimming()

  Dim thisBecomesVariant, thisIsAnInteger As Integer
  Dim integerOne As Integer, integerTwo As Integer

  MsgBox TypeName(thisBecomesVariant)  'Will display "Empty"
  MsgBox TypeName(thisIsAnInteger )  'Will display "Integer"
  MsgBox TypeName(integerOne )  'Will display "Integer"
  MsgBox TypeName(integerTwo )  'Will display "Integer"

  'By assigning an Integer value to a Variant it becomes Integer, too
  thisBecomesVariant = 0
  MsgBox TypeName(thisBecomesVariant)  'Will display "Integer"

End Sub

Two further notices on your code:

First remark: Instead of writing

'If g1val is bigger than the value in the current cell
If g1val > Cells(33, i).Value Then
  g1val = g1val   'Don't change g1val
Else
  g1val = Cells(33, i).Value  'Otherwise set g1val to the cell's value
End If

you could simply write

'If g1val is smaller or equal than the value in the current cell
If g1val <= Cells(33, i).Value Then
  g1val = Cells(33, i).Value  'Set g1val to the cell's value 
End If

Since you don't want to change g1val in the other case.

Second remark: I encourage you to use Option Explicit when programming, to prevent typos in your program. You will then have to declare all variables and the compiler will give you a warning if a variable is unknown.

When to favor ng-if vs. ng-show/ng-hide?

If you use ng-show or ng-hide the content (eg. thumbnails from server) will be loaded irrespective of the value of expression but will be displayed based on the value of the expression.

If you use ng-if the content will be loaded only if the expression of the ng-if evaluates to truthy.

Using ng-if is a good idea in a situation where you are going to load data or images from the server and show those only depending on users interaction. This way your page load will not be blocked by unnecessary nw intensive tasks.

Warning as error - How to get rid of these

View -> Error list -> Right click on specific Error/Warning.

You can change Severity as You want.

I have never set any passwords to my keystore and alias, so how are they created?

Signing in Debug Mode

The Android build tools provide a debug signing mode that makes it easier for you to develop and debug your application, while still meeting the Android system requirement for signing your APK. When using debug mode to build your app, the SDK tools invoke Keytool to automatically create a debug keystore and key. This debug key is then used to automatically sign the APK, so you do not need to sign the package with your own key.

The SDK tools create the debug keystore/key with predetermined names/passwords:

Keystore name: "debug.keystore"
Keystore password: "android"
Key alias: "androiddebugkey"
Key password: "android"
CN: "CN=Android Debug,O=Android,C=US"

If necessary, you can change the location/name of the debug keystore/key or supply a custom debug keystore/key to use. However, any custom debug keystore/key must use the same keystore/key names and passwords as the default debug key (as described above). (To do so in Eclipse/ADT, go to Windows > Preferences > Android > Build.)

Caution: You cannot release your application to the public when signed with the debug certificate.

Source: Developer.Android

Finding the 'type' of an input element

If you want to check the type of input within form, use the following code:

<script>
    function getFind(obj) {
    for (i = 0; i < obj.childNodes.length; i++) {
        if (obj.childNodes[i].tagName == "INPUT") {
            if (obj.childNodes[i].type == "text") {
                alert("this is Text Box.")
            }
            if (obj.childNodes[i].type == "checkbox") {
                alert("this is CheckBox.")
            }
            if (obj.childNodes[i].type == "radio") {
                alert("this is Radio.")
            }
        }
        if (obj.childNodes[i].tagName == "SELECT") {
            alert("this is Select")
        }
    }
}
</script>     

<script>    
    getFind(document.myform);  
</script>

What are the differences between a multidimensional array and an array of arrays in C#?

Simply put multidimensional arrays are similar to a table in DBMS.
Array of Array (jagged array) lets you have each element hold another array of the same type of variable length.

So, if you are sure that the structure of data looks like a table (fixed rows/columns), you can use a multi-dimensional array. Jagged array are fixed elements & each element can hold an array of variable length

E.g. Psuedocode:

int[,] data = new int[2,2];
data[0,0] = 1;
data[0,1] = 2;
data[1,0] = 3;
data[1,1] = 4;

Think of the above as a 2x2 table:

1 | 2
3 | 4
int[][] jagged = new int[3][]; 
jagged[0] = new int[4] {  1,  2,  3,  4 }; 
jagged[1] = new int[2] { 11, 12 }; 
jagged[2] = new int[3] { 21, 22, 23 }; 

Think of the above as each row having variable number of columns:

 1 |  2 |  3 | 4
11 | 12
21 | 22 | 23

What is the PostgreSQL equivalent for ISNULL()

Create the following function

CREATE OR REPLACE FUNCTION isnull(text, text) RETURNS text AS 'SELECT (CASE (SELECT $1 "
    "is null) WHEN true THEN $2 ELSE $1 END) AS RESULT' LANGUAGE 'sql'

And it'll work.

You may to create different versions with different parameter types.

Get the last element of a std::string

You probably want to check the length of the string first and do something like this:

if (!myStr.empty())
{
    char lastChar = *myStr.rbegin();
}

Eclipse Generate Javadoc Wizard: what is "Javadoc Command"?

You may need to add a JDK (Java Development Kit) to the installed JRE's within Eclipse

Go to Window->Preferences->Java->Installed JRE's

In the Name column if you do not have a JDK as your default, then you will need to add it.

Click the "Add" Button and locate the JDK on your machine. You may find it in this location: C:\Program Files\Java\jdk1.x.y
Where x and y are numbers.

If there are no JDK's installed on your machine then download and install the Java SE (Standard Edition) from the Oracle website.

Then do the steps above again. Be sure that it is set as the default JRE to use.

Then go back to the Projects->Generate Javadoc... dialog

Now it should work.

Good Luck.

C++ Loop through Map

Try the following

for ( const auto &p : table )
{
   std::cout << p.first << '\t' << p.second << std::endl;
} 

The same can be written using an ordinary for loop

for ( auto it = table.begin(); it != table.end(); ++it  )
{
   std::cout << it->first << '\t' << it->second << std::endl;
} 

Take into account that value_type for std::map is defined the following way

typedef pair<const Key, T> value_type

Thus in my example p is a const reference to the value_type where Key is std::string and T is int

Also it would be better if the function would be declared as

void output( const map<string, int> &table );

How do I use Node.js Crypto to create a HMAC-SHA1 hash?

Documentation for crypto: http://nodejs.org/api/crypto.html

const crypto = require('crypto')

const text = 'I love cupcakes'
const key = 'abcdeg'

crypto.createHmac('sha1', key)
  .update(text)
  .digest('hex')

Get a list of distinct values in List

public class KeyNote
{
    public long KeyNoteId { get; set; }
    public long CourseId { get; set; }
    public string CourseName { get; set; }
    public string Note { get; set; }
    public DateTime CreatedDate { get; set; }
}

public List<KeyNote> KeyNotes { get; set; }
public List<RefCourse> GetCourses { get; set; }    

List<RefCourse> courses = KeyNotes.Select(x => new RefCourse { CourseId = x.CourseId, Name = x.CourseName }).Distinct().ToList();

By using the above logic, we can get the unique Courses.

HTML5 Canvas 100% Width Height of Viewport?

I'll answer the more general question of how to have a canvas dynamically adapt in size upon window resize. The accepted answer appropriately handles the case where width and height are both supposed to be 100%, which is what was asked for, but which also will change the aspect ratio of the canvas. Many users will want the canvas to resize on window resize, but while keeping the aspect ratio untouched. It's not the exact question, but it "fits in", just putting the question into a slightly more general context.

The window will have some aspect ratio (width / height), and so will the canvas object. How you want these two aspect ratios to relate to each other is one thing you'll have to be clear about, there is no "one size fits all" answer to that question - I'll go through some common cases of what you might want.

Most important thing you have to be clear about: the html canvas object has a width attribute and a height attribute; and then, the css of the same object also has a width and a height attribute. Those two widths and heights are different, both are useful for different things.

Changing the width and height attributes is one method with which you can always change the size of your canvas, but then you'll have to repaint everything, which will take time and is not always necessary, because some amount of size change you can accomplish via the css attributes, in which case you do not redraw the canvas.

I see 4 cases of what you might want to happen on window resize (all starting with a full screen canvas)

1: you want the width to remain 100%, and you want the aspect ratio to stay as it was. In that case, you do not need to redraw the canvas; you don't even need a window resize handler. All you need is

$(ctx.canvas).css("width", "100%");

where ctx is your canvas context. fiddle: resizeByWidth

2: you want width and height to both stay 100%, and you want the resulting change in aspect ratio to have the effect of a stretched-out image. Now, you still don't need to redraw the canvas, but you need a window resize handler. In the handler, you do

$(ctx.canvas).css("height", window.innerHeight);

fiddle: messWithAspectratio

3: you want width and height to both stay 100%, but the answer to the change in aspect ratio is something different from stretching the image. Then you need to redraw, and do it the way that is outlined in the accepted answer.

fiddle: redraw

4: you want the width and height to be 100% on page load, but stay constant thereafter (no reaction to window resize.

fiddle: fixed

All fiddles have identical code, except for line 63 where the mode is set. You can also copy the fiddle code to run on your local machine, in which case you can select the mode via a querystring argument, as ?mode=redraw

Links not going back a directory?

You need to give a relative file path of <a href="../index.html">Home</a>

Alternately you can specify a link from the root of your site with <a href="/pages/en/index.html">Home</a>

.. and . have special meanings in file paths, .. means up one directory and . means current directory.

so <a href="index.html">Home</a> is the same as <a href="./index.html">Home</a>

MySQL: #1075 - Incorrect table definition; autoincrement vs another key?

First create table without auto_increment,

CREATE TABLE `members`(
    `id` int(11) NOT NULL,
    `memberid` VARCHAR( 30 ) NOT NULL ,
    `Time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
    `firstname` VARCHAR( 50 ) NULL ,
    `lastname` VARCHAR( 50 ) NULL
    PRIMARY KEY (memberid) 
) ENGINE = MYISAM;

after set id as index,

ALTER TABLE `members` ADD INDEX(`id`);

after set id as auto_increment,

ALTER TABLE `members` CHANGE `id` `id` INT(11) NOT NULL AUTO_INCREMENT;

Or

CREATE TABLE IF NOT EXISTS `members` (
    `id` int(11) NOT NULL,
    `memberid` VARCHAR( 30 ) NOT NULL ,
    `Time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
    `firstname` VARCHAR( 50 ) NULL ,
    `lastname` VARCHAR( 50 ) NULL,
      PRIMARY KEY (`memberid`),
      KEY `id` (`id`)
) ENGINE=MYISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

git push says "everything up-to-date" even though I have local changes

Maybe you're pushing a new local branch?

A new local branch must be pushed explicitly:

git push origin your-new-branch-name

Just one of those things about git... You clone a repo, make a branch, commit some changes, push... "Everything is up to date". I understand why it happens, but this workflow is extremely unfriendly to newcomers.

How can I run an EXE program from a Windows Service using C#?

i have tried this article Code Project, it is working fine for me. I have used the code too. article is excellent in explanation with screenshot.

I am adding necessary explanation to this scenario

You have just booted up your computer and are about to log on. When you log on, the system assigns you a unique Session ID. In Windows Vista, the first User to log on to the computer is assigned a Session ID of 1 by the OS. The next User to log on will be assigned a Session ID of 2. And so on and so forth. You can view the Session ID assigned to each logged on User from the Users tab in Task Manager. enter image description here

But your windows service is brought under session ID of 0. This session is isolated from other sessions. This ultimately prevent the windows service to invoke the application running under user session's like 1 or 2.

In order to invoke the application from windows service you need to copy the control from winlogon.exe which acts as present logged user as shown in below screenshot. enter image description here

Important codes

// obtain the process id of the winlogon process that 
// is running within the currently active session
Process[] processes = Process.GetProcessesByName("winlogon");
foreach (Process p in processes)
{
    if ((uint)p.SessionId == dwSessionId)
    {
        winlogonPid = (uint)p.Id;
    }
}

// obtain a handle to the winlogon process
hProcess = OpenProcess(MAXIMUM_ALLOWED, false, winlogonPid);

// obtain a handle to the access token of the winlogon process
if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE, ref hPToken))
{
    CloseHandle(hProcess);
    return false;
}

// Security attibute structure used in DuplicateTokenEx and   CreateProcessAsUser
// I would prefer to not have to use a security attribute variable and to just 
// simply pass null and inherit (by default) the security attributes
// of the existing token. However, in C# structures are value types and   therefore
// cannot be assigned the null value.
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
sa.Length = Marshal.SizeOf(sa);

// copy the access token of the winlogon process; 
// the newly created token will be a primary token
if (!DuplicateTokenEx(hPToken, MAXIMUM_ALLOWED, ref sa, 
    (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, 
    (int)TOKEN_TYPE.TokenPrimary, ref hUserTokenDup))
    {
      CloseHandle(hProcess);
      CloseHandle(hPToken);
      return false;
    }

 STARTUPINFO si = new STARTUPINFO();
 si.cb = (int)Marshal.SizeOf(si);

// interactive window station parameter; basically this indicates 
// that the process created can display a GUI on the desktop
si.lpDesktop = @"winsta0\default";

// flags that specify the priority and creation method of the process
int dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE;

// create a new process in the current User's logon session
 bool result = CreateProcessAsUser(hUserTokenDup,  // client's access token
                            null,             // file to execute
                            applicationName,  // command line
                            ref sa,           // pointer to process    SECURITY_ATTRIBUTES
                            ref sa,           // pointer to thread SECURITY_ATTRIBUTES
                            false,            // handles are not inheritable
                            dwCreationFlags,  // creation flags
                            IntPtr.Zero,      // pointer to new environment block 
                            null,             // name of current directory 
                            ref si,           // pointer to STARTUPINFO structure
                            out procInfo      // receives information about new process
                            );

recursively use scp but excluding some folders

This one works fine for me as the directories structure is not important for me.

scp -r USER@HOSTNAME:~/bench1/?cpu/p_?/image/ .

Assuming /bench1 is in the home directory of the current user. Also, change USER and HOSTNAME to the real values.

Convert pandas timezone-aware DateTimeIndex to naive timestamp, but in certain timezone

Late contribution but just came across something similar in Python datetime and pandas give different timestamps for the same date.

If you have timezone-aware datetime in pandas, technically, tz_localize(None) changes the POSIX timestamp (that is used internally) as if the local time from the timestamp was UTC. Local in this context means local in the specified timezone. Ex:

import pandas as pd

t = pd.date_range(start="2013-05-18 12:00:00", periods=2, freq='H', tz="US/Central")
# DatetimeIndex(['2013-05-18 12:00:00-05:00', '2013-05-18 13:00:00-05:00'], dtype='datetime64[ns, US/Central]', freq='H')

t_loc = t.tz_localize(None)
# DatetimeIndex(['2013-05-18 12:00:00', '2013-05-18 13:00:00'], dtype='datetime64[ns]', freq='H')

# offset in seconds according to timezone:
(t_loc.values-t.values)//1e9
# array([-18000, -18000], dtype='timedelta64[ns]')

Note that this will leave you with strange things during DST transitions, e.g.

t = pd.date_range(start="2020-03-08 01:00:00", periods=2, freq='H', tz="US/Central")
(t.values[1]-t.values[0])//1e9
# numpy.timedelta64(3600,'ns')

t_loc = t.tz_localize(None)
(t_loc.values[1]-t_loc.values[0])//1e9
# numpy.timedelta64(7200,'ns')

In contrast, tz_convert(None) does not modify the internal timestamp, it just removes the tzinfo.

t_utc = t.tz_convert(None)
(t_utc.values-t.values)//1e9
# array([0, 0], dtype='timedelta64[ns]')

My bottom line would be: stick with timezone-aware datetime if you can or only use t.tz_convert(None) which doesn't modify the underlying POSIX timestamp. Just keep in mind that you're practically working with UTC then.

(Python 3.8.2 x64 on Windows 10, pandas v1.0.5.)

TypeScript: Creating an empty typed container array

Okay you got the syntax wrong here, correct way to do this is:

var arr: Criminal[] = [];

I'm assuming you are using var so that means declaring it somewhere inside the func(),my suggestion would be use let instead of var.

If declaring it as c class property usse acces modifiers like private, public, protected.

How to get current foreground activity context in android?

For backwards compatibility:

ComponentName cn;
ActivityManager am = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
    cn = am.getAppTasks().get(0).getTaskInfo().topActivity;
} else {
    //noinspection deprecation
    cn = am.getRunningTasks(1).get(0).topActivity;
}

Div vertical scrollbar show

What browser are you testing in?

What DOCType have you set?

How exactly are you declaring your CSS?

Are you sure you haven't missed a ; before/after the overflow-y: scroll?

I've just tested the following in IE7 and Firefox and it works fine

_x000D_
_x000D_
<!-- Scroll bar present but disabled when less content -->_x000D_
<div style="width: 200px; height: 100px; overflow-y: scroll;">_x000D_
  test_x000D_
</div>_x000D_
_x000D_
<!-- Scroll bar present and enabled when more contents -->        _x000D_
<div style="width: 200px; height: 100px; overflow-y: scroll;">_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Injection of autowired dependencies failed;

The error shows that com.bd.service.ArticleService is not a registered bean. Add the packages in which you have beans that will be autowired in your application context:

<context:component-scan base-package="com.bd.service"/>
<context:component-scan base-package="com.bd.controleur"/>

Alternatively, if you want to include all subpackages in com.bd:

<context:component-scan base-package="com.bd">
     <context:include-filter type="aspectj" expression="com.bd.*" />
</context:component-scan>

As a side note, if you're using Spring 3.1 or later, you can take advantage of the @ComponentScan annotation, so that you don't have to use any xml configuration regarding component-scan. Use it in conjunction with @Configuration.

@Controller
@RequestMapping("/Article/GererArticle")
@Configuration
@ComponentScan("com.bd.service") // No need to include component-scan in xml
public class ArticleControleur {

    @Autowired
    ArticleService articleService;
    ...
}

You might find this Spring in depth section on Autowiring useful.

DLL and LIB files - what and why?

One important reason for creating a DLL/LIB rather than just compiling the code into an executable is reuse and relocation. The average Java or .NET application (for example) will most likely use several 3rd party (or framework) libraries. It is much easier and faster to just compile against a pre-built library, rather than having to compile all of the 3rd party code into your application. Compiling your code into libraries also encourages good design practices, e.g. designing your classes to be used in different types of applications.

How can I pass a list as a command-line argument with argparse?

Additionally to nargs, you might want to use choices if you know the list in advance:

>>> parser = argparse.ArgumentParser(prog='game.py')
>>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
>>> parser.parse_args(['rock'])
Namespace(move='rock')
>>> parser.parse_args(['fire'])
usage: game.py [-h] {rock,paper,scissors}
game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
'paper', 'scissors')

How to create a HTTP server in Android?

Consider this one: https://github.com/NanoHttpd/nanohttpd. Very small, written in Java. I used it without any problem.

Set margins in a LinearLayout programmatically

Here is a little code to accomplish it:

LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
     LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

layoutParams.setMargins(30, 20, 30, 0);

Button okButton=new Button(this);
okButton.setText("some text");
ll.addView(okButton, layoutParams);

How to sort a list of strings numerically?

I approached the same problem yesterday and found a module called [natsort][1], which solves your problem. Use:

from natsort import natsorted # pip install natsort

# Example list of strings
a = ['1', '10', '2', '3', '11']

[In]  sorted(a)
[Out] ['1', '10', '11', '2', '3']

[In]  natsorted(a)
[Out] ['1', '2', '3', '10', '11']

# Your array may contain strings
[In]  natsorted(['string11', 'string3', 'string1', 'string10', 'string100'])
[Out] ['string1', 'string3', 'string10', 'string11', 'string100']

It also works for dictionaries as an equivalent of sorted. [1]: https://pypi.org/project/natsort/

How do I install SciPy on 64 bit Windows?

I was getting this same error on a 32-bit machine. I fixed it by registering my Python installation, using the script at:

http://effbot.org/zone/python-register.htm

It's possible that the script would also make the 64-bit superpack installers work.

best OCR (Optical character recognition) example in android

Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.

Let me explain using step-by-step guidance.

First, download the source code from https://github.com/rmtheis/tess-two.

Import all three projects. After importing you will get an error. To solve the error you have to create a res folder in the tess-two project

enter image description here

First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"

After doing this in all three project the error should be gone.

Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.

Now you just need to import it into your workspace, but first you have to download android-ndk from this site:

http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file

Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable

Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture

enter image description here

done it

Now open cmd and go to on D:\Android Workspace\tess-two like below

enter image description here

If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:

Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest

enter image description here

Import test-two in this and run OCRTest and run it; you will get the best example of OCR.

Vector erase iterator

The following also seems to work :

for (vector<int>::iterator it = res.begin(); it != res.end(); it++)
{
  res.erase(it--);
}

Not sure if there's any flaw in this ?

jQuery Loop through each div

You're right that it involves a loop, but this is, at least, made simple by use of the each() method:

$('.target').each(
    function(){
        // iterate through each of the `.target` elements, and do stuff in here
        // `this` and `$(this)` refer to the current `.target` element
        var images = $(this).find('img'),
            imageWidth = images.width(); // returns the width of the _first_ image
            numImages = images.length;
        $(this).css('width', (imageWidth*numImages));

    });

References:

Assembly Language - How to do Modulo?

If you don't care too much about performance and want to use the straightforward way, you can use either DIV or IDIV.

DIV or IDIV takes only one operand where it divides a certain register with this operand, the operand can be register or memory location only.

When operand is a byte: AL = AL / operand, AH = remainder (modulus).

Ex:

MOV AL,31h ; Al = 31h

DIV BL ; Al (quotient)= 08h, Ah(remainder)= 01h

when operand is a word: AX = (AX) / operand, DX = remainder (modulus).

Ex:

MOV AX,9031h ; Ax = 9031h

DIV BX ; Ax=1808h & Dx(remainder)= 01h

Convert an enum to List<string>

Use Enum's static method, GetNames. It returns a string[], like so:

Enum.GetNames(typeof(DataSourceTypes))

If you want to create a method that does only this for only one type of enum, and also converts that array to a List, you can write something like this:

public List<string> GetDataSourceTypes()
{
    return Enum.GetNames(typeof(DataSourceTypes)).ToList();
}

You will need Using System.Linq; at the top of your class to use .ToList()

How to schedule a task to run when shutting down windows

One workaround might be to write a simple batch file to run the program then shutdown the computer.

You can shut down from the command line -- so your script could be fairly simple:

c:\directory\myProgram.exe
C:\WINDOWS\system32\shutdown.exe -s -f -t 0

Circle-Rectangle collision detection (intersection)

Assuming you have the four edges of the rectangle check the distance from the edges to the center of the circle, if its less then the radius, then the shapes are intersecting.

if sqrt((rectangleRight.x - circleCenter.x)^2 +
        (rectangleBottom.y - circleCenter.y)^2) < radius
// then they intersect

if sqrt((rectangleRight.x - circleCenter.x)^2 +
        (rectangleTop.y - circleCenter.y)^2) < radius
// then they intersect

if sqrt((rectangleLeft.x - circleCenter.x)^2 +
        (rectangleTop.y - circleCenter.y)^2) < radius
// then they intersect

if sqrt((rectangleLeft.x - circleCenter.x)^2 +
        (rectangleBottom.y - circleCenter.y)^2) < radius
// then they intersect

How to escape double quotes in JSON

To escape backslashes that cause problems for JSON data I use this function.

//escape backslash to avoid errors
var escapeJSON = function(str) {
    return str.replace(/\\/g,'\\');
};

What's a standard way to do a no-op in python?

If you need a function that behaves as a nop, try

nop = lambda *a, **k: None
nop()

Sometimes I do stuff like this when I'm making dependencies optional:

try:
    import foo
    bar=foo.bar
    baz=foo.baz
except:
    bar=nop
    baz=nop

# Doesn't break when foo is missing:
bar()
baz()

Return content with IHttpActionResult for non-OK response

You can use HttpRequestMessagesExtensions.CreateErrorResponse (System.Net.Http namespace), like so:

public IHttpActionResult Get()
{
   return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Message describing the error here"));
}

It is preferable to create responses based on the request to take advantage of Web API's content negotiation.

How to fix Cannot find module 'typescript' in Angular 4?

If you don't have particular needs, I suggest to install Typescript locally.

NPM Installation Method

npm install --global typescript # Global installation
npm install --save-dev typescript # Local installation

Yarn Installation Method

yarn global add typescript # Global installation
yarn add --dev typescript # Local installation

python plot normal distribution

If you prefer to use a step by step approach you could consider a solution like follows

import numpy as np
import matplotlib.pyplot as plt

mean = 0; std = 1; variance = np.square(std)
x = np.arange(-5,5,.01)
f = np.exp(-np.square(x-mean)/2*variance)/(np.sqrt(2*np.pi*variance))

plt.plot(x,f)
plt.ylabel('gaussian distribution')
plt.show()

Filter by process/PID in Wireshark

Use strace is more suitable for this situation.

strace -f -e trace=network -s 10000 -p <PID>;

options -f to also trace all forked processes, -e trace=netwrok to only filter network system-call and -s to display string length up to 10000 char.

You can also only trace certain calls like send,recv, read operations.

strace -f -e trace=send,recv,read -s 10000 -p <PID>;

How can I make setInterval also work when a tab is inactive in Chrome?

For me it's not important to play audio in the background like for others here, my problem was that I had some animations and they acted like crazy when you were in other tabs and coming back to them. My solution was putting these animations inside if that is preventing inactive tab:

if (!document.hidden){ //your animation code here }

thanks to that my animation was running only if tab was active. I hope this will help someone with my case.

Download a file from HTTPS using download.file()

Had exactly the same problem as UseR (original question), I'm also using windows 7. I tried all proposed solutions and they didn't work.

I resolved the problem doing as follows:

  1. Using RStudio instead of R console.

  2. Actualising the version of R (from 3.1.0 to 3.1.1) so that the library RCurl runs OK on it. (I'm using now R3.1.1 32bit although my system is 64bit).

  3. I typed the URL address as https (secure connection) and with / instead of backslashes \\.

  4. Setting method = "auto".

It works for me now. You should see the message:

Content type 'text/csv; charset=utf-8' length 9294 bytes
opened URL
downloaded 9294 by

Make a DIV fill an entire table cell

Try this:

<td style="position:relative;">
    <div style="position:absolute;top:0;bottom:0;width:100%;"></div>
</td>

How to check object is nil or not in swift?

Swift 4.2

func isValid(_ object:AnyObject!) -> Bool
{
    if let _:AnyObject = object
    {
        return true
    }

    return false
}

Usage

if isValid(selectedPost)
{
    savePost()
}

jquery input select all on focus

Works great with the native JavaScript select().

$("input[type=text]").focus(function(event) {
   event.currentTarget.select();
});

or in general:

$("input[type=text]")[0].select()

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

I had this issue while working at the local Starbucks and I remembered that when I initially set up my database through Mongo Atlas. I set my IP address to be able to access the database. After looking through several threads, I changed my IP address on Atlas and the issue went away. Hope this helps someone.

How to repair a serialized string which has been corrupted by an incorrect byte count length?

You can fix broken serialize string using following function, with multibyte character handling.

function repairSerializeString($value)
{

    $regex = '/s:([0-9]+):"(.*?)"/';

    return preg_replace_callback(
        $regex, function($match) {
            return "s:".mb_strlen($match[2]).":\"".$match[2]."\""; 
        },
        $value
    );
}

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.

How to get complete current url for Cakephp

Use Html helper

<?php echo $this->Html->url($this->here, true); ?> 

It'll produce the full url which'll started from http or https

Fitting a density curve to a histogram in R

If I understand your question correctly, then you probably want a density estimate along with the histogram:

X <- c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4))
hist(X, prob=TRUE)            # prob=TRUE for probabilities not counts
lines(density(X))             # add a density estimate with defaults
lines(density(X, adjust=2), lty="dotted")   # add another "smoother" density

Edit a long while later:

Here is a slightly more dressed-up version:

X <- c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4))
hist(X, prob=TRUE, col="grey")# prob=TRUE for probabilities not counts
lines(density(X), col="blue", lwd=2) # add a density estimate with defaults
lines(density(X, adjust=2), lty="dotted", col="darkgreen", lwd=2) 

along with the graph it produces:

enter image description here

How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"

Use modern java.time classes if you use java 8 or newer.

String s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());

Basil Bourque's answer is pretty good. But it's too long. Many people would have no patience to read it. Top 3 answers are too old and may mislead Java new bee .So I provide this short and modern answer for new coming devs. Hope this answer can reduce usage of terrible SimpleDateFormat.

Go to first line in a file in vim?

In command mode (press Esc if you are not sure) you can use:

  • gg,
  • :1,
  • 1G,
  • or 1gg.

Parsing JSON using Json.net

/*
     * This method takes in JSON in the form returned by javascript's
     * JSON.stringify(Object) and returns a string->string dictionary.
     * This method may be of use when the format of the json is unknown.
     * You can modify the delimiters, etc pretty easily in the source
     * (sorry I didn't abstract it--I have a very specific use).
     */ 
    public static Dictionary<string, string> jsonParse(string rawjson)
    {
        Dictionary<string, string> outdict = new Dictionary<string, string>();
        StringBuilder keybufferbuilder = new StringBuilder();
        StringBuilder valuebufferbuilder = new StringBuilder();
        StringReader bufferreader = new StringReader(rawjson);

        int s = 0;
        bool reading = false;
        bool inside_string = false;
        bool reading_value = false;
        //break at end (returns -1)
        while (s >= 0)
        {
            s = bufferreader.Read();
            //opening of json
            if (!reading)
            {
                if ((char)s == '{' && !inside_string && !reading) reading = true;
                continue;
            }
            else
            {
                //if we find a quote and we are not yet inside a string, advance and get inside
                if (!inside_string)
                {
                    //read past the quote
                    if ((char)s == '\"') inside_string = true;
                    continue;
                }
                if (inside_string)
                {
                    //if we reached the end of the string
                    if ((char)s == '\"')
                    {
                        inside_string = false;
                        s = bufferreader.Read(); //advance pointer
                        if ((char)s == ':')
                        {
                            reading_value = true;
                            continue;
                        }
                        if (reading_value && (char)s == ',')
                        {
                            //we know we just ended the line, so put itin our dictionary
                            if (!outdict.ContainsKey(keybufferbuilder.ToString())) outdict.Add(keybufferbuilder.ToString(), valuebufferbuilder.ToString());
                            //and clear the buffers
                            keybufferbuilder.Clear();
                            valuebufferbuilder.Clear();
                            reading_value = false;
                        }
                        if (reading_value && (char)s == '}')
                        {
                            //we know we just ended the line, so put itin our dictionary
                            if (!outdict.ContainsKey(keybufferbuilder.ToString())) outdict.Add(keybufferbuilder.ToString(), valuebufferbuilder.ToString());
                            //and clear the buffers
                            keybufferbuilder.Clear();
                            valuebufferbuilder.Clear();
                            reading_value = false;
                            reading = false;
                            break;
                        }
                    }
                    else
                    {
                        if (reading_value)
                        {
                            valuebufferbuilder.Append((char)s);
                            continue;
                        }
                        else
                        {
                            keybufferbuilder.Append((char)s);
                            continue;
                        }
                    }
                }
                else
                {
                    switch ((char)s)
                    {
                        case ':':
                            reading_value = true;
                            break;
                        default:
                            if (reading_value)
                            {
                                valuebufferbuilder.Append((char)s);
                            }
                            else
                            {
                                keybufferbuilder.Append((char)s);
                            }
                            break;
                    }
                }
            }
        }
        return outdict;
    }