Programs & Examples On #Waf

Waf is a Python-based framework for configuring, compiling and installing applications. It derives from the concepts of other build tools such as Scons, Autotools, CMake or Ant.

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

For the Collatz problem, you can get a significant boost in performance by caching the "tails". This is a time/memory trade-off. See: memoization (https://en.wikipedia.org/wiki/Memoization). You could also look into dynamic programming solutions for other time/memory trade-offs.

Example python implementation:

import sys

inner_loop = 0

def collatz_sequence(N, cache):
    global inner_loop

    l = [ ]
    stop = False
    n = N

    tails = [ ]

    while not stop:
        inner_loop += 1
        tmp = n
        l.append(n)
        if n <= 1:
            stop = True  
        elif n in cache:
            stop = True
        elif n % 2:
            n = 3*n + 1
        else:
            n = n // 2
        tails.append((tmp, len(l)))

    for key, offset in tails:
        if not key in cache:
            cache[key] = l[offset:]

    return l

def gen_sequence(l, cache):
    for elem in l:
        yield elem
        if elem in cache:
            yield from gen_sequence(cache[elem], cache)
            raise StopIteration

if __name__ == "__main__":
    le_cache = {}

    for n in range(1, 4711, 5):
        l = collatz_sequence(n, le_cache)
        print("{}: {}".format(n, len(list(gen_sequence(l, le_cache)))))

    print("inner_loop = {}".format(inner_loop))

Android Error Building Signed APK: keystore.jks not found for signing config 'externalOverride'

This is a problem that can arise from writing down a "filename" instead of a path, while generating the .jks file. Generate a new one, put it on the Desktop (or any other real path) and re-generate APK.

How to use Visual Studio C++ Compiler?

In Visual Studio, you can't just open a .cpp file and expect it to run. You must create a project first, or open the .cpp in some existing project.

In your case, there is no project, so there is no project to build.

Go to File --> New --> Project --> Visual C++ --> Win32 Console Application. You can uncheck "create a directory for solution". On the next page, be sure to check "Empty project".

Then, You can add .cpp files you created outside the Visual Studio by right clicking in the Solution explorer on folder icon "Source" and Add->Existing Item.

Obviously You can create new .cpp this way too (Add --> New). The .cpp file will be created in your project directory.

Then you can press ctrl+F5 to compile without debugging and can see output on console window.

npm ERR cb() never called

For anyone who has upgraded recently from 6.x to 6.7.0.

Deleting the /Users/{YOUR USERNAME}/.npm folder solved my issues with npm install.

I also, ran some of these commands suggested by https://npm.community/t/crash-npm-err-cb-never-called/858/93?u=jasonfoglia

sudo npm cache clean -f
sudo npm install -g n

But I'm not sure which actually worked until I deleted the folder. So if you experience this issue and just delete the .npm folder fixing your issue please note that in the comments.

How do I use checkboxes in an IF-THEN statement in Excel VBA 2010?

If Sheets("Sheet1").OLEObjects("CheckBox1").Object.Value = True Then

I believe Tim is right. You have a Form Control. For that you have to use this

If ActiveSheet.Shapes("Check Box 1").ControlFormat.Value = 1 Then

Opening a CHM file produces: "navigation to the webpage was canceled"

Win 8 x64:

just move it to another folder or rename your folder (in my case: my folder was "c#"). avoid to use symbol on folder name. name it with letter.

done.

Adding a new line/break tag in XML

You are probably using Windows, so new line is CR + LF (carriage return + line feed). So solution would be:

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="dummy.xsl"?>
  <item>
     <summary>Tootsie roll tiramisu macaroon wafer carrot cake.&#13;&#10;Danish topping sugar plum tart bonbon caramels cake.
     </summary>
  </item>

For Linux there is only LF and for Mac OS only CR.

In question there showed Linux way.

Scroll part of content in fixed position container

What worked for me :

div#scrollable {
    overflow-y: scroll;
    max-height: 100vh;
}

JPA mapping: "QuerySyntaxException: foobar is not mapped..."

I got the same error while using other one entity, He was annotating the class wrongly by using the table name inside the @Entity annotation without using the @Table annotation

The correct format should be

@Entity //default name similar to class name 'FooBar' OR @Entity( name = "foobar" ) for differnt entity name
@Table( name = "foobar" ) // Table name 
public class FooBar{

fork() and wait() with two child processes

It looks to me as though the basic problem is that you have one wait() call rather than a loop that waits until there are no more children. You also only wait if the last fork() is successful rather than if at least one fork() is successful.

You should only use _exit() if you don't want normal cleanup operations - such as flushing open file streams including stdout. There are occasions to use _exit(); this is not one of them. (In this example, you could also, of course, simply have the children return instead of calling exit() directly because returning from main() is equivalent to exiting with the returned status. However, most often you would be doing the forking and so on in a function other than main(), and then exit() is often appropriate.)


Hacked, simplified version of your code that gives the diagnostics I'd want. Note that your for loop skipped the first element of the array (mine doesn't).

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int main(void)
{
    pid_t child_pid, wpid;
    int status = 0;
    int i;
    int a[3] = {1, 2, 1};

    printf("parent_pid = %d\n", getpid());
    for (i = 0; i < 3; i++)
    {
        printf("i = %d\n", i);
        if ((child_pid = fork()) == 0)
        {
            printf("In child process (pid = %d)\n", getpid());
            if (a[i] < 2)
            {
                printf("Should be accept\n");
                exit(1);
            }
            else
            {
                printf("Should be reject\n");
                exit(0);
            }
            /*NOTREACHED*/
        }
    }

    while ((wpid = wait(&status)) > 0)
    {
        printf("Exit status of %d was %d (%s)\n", (int)wpid, status,
               (status > 0) ? "accept" : "reject");
    }
    return 0;
}

Example output (MacOS X 10.6.3):

parent_pid = 15820
i = 0
i = 1
In child process (pid = 15821)
Should be accept
i = 2
In child process (pid = 15822)
Should be reject
In child process (pid = 15823)
Should be accept
Exit status of 15823 was 256 (accept)
Exit status of 15822 was 0 (reject)
Exit status of 15821 was 256 (accept)

How to pass an array into a function, and return the results with an array

You are not able to return 'multiple values' in PHP. You can return a single value, which might be an array.

function foo($test1, $test2, $test3)
{
    return array($test1, $test2, $test3);
}
$test1 = "1";
$test2 = "2";
$test3 = "3";

$arr = foo($test1, $test2, $test3);

$test1 = $arr[0];
$test2 = $arr[1];
$test3 = $arr[2];

Get selected row item in DataGrid WPF

If you're using the MVVM pattern you can bind a SelectedRecord property of your VM with SelectedItem of the DataGrid, this way you always have the SelectedValue in you VM. Otherwise you should use the SelectedIndex property of the DataGrid.

CURLOPT_RETURNTRANSFER set to true doesnt work on hosting server

If you set CURLOPT_RETURNTRANSFER to true or 1 then the return value from curl_exec will be the actual result from the successful operation. In other words it will not return TRUE on success. Although it will return FALSE on failure.

As described in the Return Values section of curl-exec PHP manual page: http://php.net/manual/function.curl-exec.php

You should enable the CURLOPT_FOLLOWLOCATION option for redirects but this would be a problem if your server is in safe_mode and/or open_basedir is in effect which can cause issues with curl as well.

Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

I want to give a different view of MONEY vs. NUMERICAL, largely based my own expertise and experience... My point of view here is MONEY, because I have worked with it for a considerable long time and never really used NUMERICAL much...

MONEY Pro:

  • Native Data Type. It uses a native data type (integer) as the same as a CPU register (32 or 64 bit), so the calculation doesn't need unnecessary overhead so it's smaller and faster... MONEY needs 8 bytes and NUMERICAL(19, 4) needs 9 bytes (12.5% bigger)...

    MONEY is faster as long as it is used for it was meant to be (as money). How fast? My simple SUM test on 1 million data shows that MONEY is 275 ms and NUMERIC 517 ms... That is almost twice as fast... Why SUM test? See next Pro point

  • Best for Money. MONEY is best for storing money and do operations, for example, in accounting. A single report can run millions of additions (SUM) and a few multiplications after the SUM operation is done. For very big accounting applications it is almost twice as fast, and it is extremely significant...
  • Low Precision of Money. Money in real life doesn't need to be very precise. I mean, many people may care about 1 cent USD, but how about 0.01 cent USD? In fact, in my country, banks no longer care about cents (digit after decimal comma); I don't know about US bank or other country...

MONEY Con:

  • Limited Precision. MONEY only has four digits (after the comma) precision, so it has to be converted before doing operations such as division... But then again money doesn't need to be so precise and is meant to be used as money, not just a number...

But... Big, but here is even your application involved real-money, but do not use it in lots of SUM operations, like in accounting. If you use lots of divisions and multiplications instead then you should not use MONEY...

UTF-8 encoding problem in Spring MVC

in your dispatcher servlet context xml, you have to add a propertie "<property name="contentType" value="text/html;charset=UTF-8" />" on your viewResolver bean. we are using freemarker for views.

it looks something like this:

<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
       ...
       <property name="contentType" value="text/html;charset=UTF-8" />
       ...
</bean>

Python: print a generator expression?

Unlike a list or a dictionary, a generator can be infinite. Doing this wouldn't work:

def gen():
    x = 0
    while True:
        yield x
        x += 1
g1 = gen()
list(g1)   # never ends

Also, reading a generator changes it, so there's not a perfect way to view it. To see a sample of the generator's output, you could do

g1 = gen()
[g1.next() for i in range(10)]

Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling

Assuming you're looking for a quick tactical fix, what you need to do is make sure the cell image is initialized and also that the cell's row is still visible, e.g:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    cell.poster.image = nil; // or cell.poster.image = [UIImage imageNamed:@"placeholder.png"];

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://myurl.com/%@.jpg", self.myJson[indexPath.row][@"movieId"]]];

    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            UIImage *image = [UIImage imageWithData:data];
            if (image) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    MyCell *updateCell = (id)[tableView cellForRowAtIndexPath:indexPath];
                    if (updateCell)
                        updateCell.poster.image = image;
                });
            }
        }
    }];
    [task resume];

    return cell;
}

The above code addresses a few problems stemming from the fact that the cell is reused:

  1. You're not initializing the cell image before initiating the background request (meaning that the last image for the dequeued cell will still be visible while the new image is downloading). Make sure to nil the image property of any image views or else you'll see the flickering of images.

  2. A more subtle issue is that on a really slow network, your asynchronous request might not finish before the cell scrolls off the screen. You can use the UITableView method cellForRowAtIndexPath: (not to be confused with the similarly named UITableViewDataSource method tableView:cellForRowAtIndexPath:) to see if the cell for that row is still visible. This method will return nil if the cell is not visible.

    The issue is that the cell has scrolled off by the time your async method has completed, and, worse, the cell has been reused for another row of the table. By checking to see if the row is still visible, you'll ensure that you don't accidentally update the image with the image for a row that has since scrolled off the screen.

  3. Somewhat unrelated to the question at hand, I still felt compelled to update this to leverage modern conventions and API, notably:

    • Use NSURLSession rather than dispatching -[NSData contentsOfURL:] to a background queue;

    • Use dequeueReusableCellWithIdentifier:forIndexPath: rather than dequeueReusableCellWithIdentifier: (but make sure to use cell prototype or register class or NIB for that identifier); and

    • I used a class name that conforms to Cocoa naming conventions (i.e. start with the uppercase letter).

Even with these corrections, there are issues:

  1. The above code is not caching the downloaded images. That means that if you scroll an image off screen and back on screen, the app may try to retrieve the image again. Perhaps you'll be lucky enough that your server response headers will permit the fairly transparent caching offered by NSURLSession and NSURLCache, but if not, you'll be making unnecessary server requests and offering a much slower UX.

  2. We're not canceling requests for cells that scroll off screen. Thus, if you rapidly scroll to the 100th row, the image for that row could be backlogged behind requests for the previous 99 rows that aren't even visible anymore. You always want to make sure you prioritize requests for visible cells for the best UX.

The simplest fix that addresses these issues is to use a UIImageView category, such as is provided with SDWebImage or AFNetworking. If you want, you can write your own code to deal with the above issues, but it's a lot of work, and the above UIImageView categories have already done this for you.

What is difference between functional and imperative programming languages?

I know this question is older and others already explained it well, I would like to give an example problem which explains the same in simple terms.

Problem: Writing the 1's table.

Solution: -

By Imperative style: =>

    1*1=1
    1*2=2
    1*3=3
    .
    .
    .
    1*n=n 

By Functional style: =>

    1
    2
    3
    .
    .
    .
    n

Explanation in Imperative style we write the instructions more explicitly and which can be called as in more simplified manner.

Where as in Functional style, things which are self-explanatory will be ignored.

How to use jQuery to select a dropdown option?

Try this:

$('#mySelectElement option')[0].selected = true;

Regards!

Custom exception type

You could implement your own exceptions and their handling for example like here:

// define exceptions "classes" 
function NotNumberException() {}
function NotPositiveNumberException() {}

// try some code
try {
    // some function/code that can throw
    if (isNaN(value))
        throw new NotNumberException();
    else
    if (value < 0)
        throw new NotPositiveNumberException();
}
catch (e) {
    if (e instanceof NotNumberException) {
        alert("not a number");
    }
    else
    if (e instanceof NotPositiveNumberException) {
        alert("not a positive number");
    }
}

There is another syntax for catching a typed exception, although this won't work in every browser (for example not in IE):

// define exceptions "classes" 
function NotNumberException() {}
function NotPositiveNumberException() {}

// try some code
try {
    // some function/code that can throw
    if (isNaN(value))
        throw new NotNumberException();
    else
    if (value < 0)
        throw new NotPositiveNumberException();
}
catch (e if e instanceof NotNumberException) {
    alert("not a number");
}
catch (e if e instanceof NotPositiveNumberException) {
    alert("not a positive number");
}

Easy way to add drop down menu with 1 - 100 without doing 100 different options?

Not with pure HTML as far as I know.

But with JS or PHP or another scripting language such as JSP, you can do it very easily with a for loop.

Example in PHP:

<select>
<?php
    for ($i=1; $i<=100; $i++)
    {
        ?>
            <option value="<?php echo $i;?>"><?php echo $i;?></option>
        <?php
    }
?>
</select>

Running a cron every 30 seconds

write one shell script create .sh file

nano every30second.sh

and write script

#!/bin/bash
For  (( i=1; i <= 2; i++ ))
do
    write Command here
    sleep 30
done

then set cron for this script crontab -e

(* * * * * /home/username/every30second.sh)

this cron call .sh file in every 1 min & in the .sh file command is run 2 times in 1 min

if you want run script for 5 seconds then replace 30 by 5 and change for loop like this: For (( i=1; i <= 12; i++ ))

when you select for any second then calculate 60/your second and write in For loop

How can I add new dimensions to a Numpy array?

There is no structure in numpy that allows you to append more data later.

Instead, numpy puts all of your data into a contiguous chunk of numbers (basically; a C array), and any resize requires allocating a new chunk of memory to hold it. Numpy's speed comes from being able to keep all the data in a numpy array in the same chunk of memory; e.g. mathematical operations can be parallelized for speed and you get less cache misses.

So you will have two kinds of solutions:

  1. Pre-allocate the memory for the numpy array and fill in the values, like in JoshAdel's answer, or
  2. Keep your data in a normal python list until it's actually needed to put them all together (see below)

images = []
for i in range(100):
    new_image = # pull image from somewhere
    images.append(new_image)
images = np.stack(images, axis=3)

Note that there is no need to expand the dimensions of the individual image arrays first, nor do you need to know how many images you expect ahead of time.

Adding a splash screen to Flutter apps

Flutter actually gives a simpler way to add Splash Screen to our application. We first need to design a basic page as we design other app screens. You need to make it a StatefulWidget since the state of this will change in a few seconds.

import 'dart:async';
import 'package:flutter/material.dart';
import 'home.dart';

class SplashScreen extends StatefulWidget {
  @override
  _SplashScreenState createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  @override
  void initState() {
    super.initState();
    Timer(
        Duration(seconds: 3),
        () => Navigator.of(context).pushReplacement(MaterialPageRoute(
            builder: (BuildContext context) => HomeScreen())));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Center(
        child: Image.asset('assets/splash.png'),
      ),
    );
  }
}

Logic Inside the initState(), call a Timer() with the duration, as you wish, I made it 3 seconds, once done push the navigator to Home Screen of our application.

Note: The application should show the splash screen only once, the user should not go back to it again on back button press. For this, we use Navigator.pushReplacement(), It will move to a new screen and remove the previous screen from the navigation history stack.

For a better understanding, visit Flutter: Design your own Splash Screen

SQL - How to find the highest number in a column?

If you're talking MS SQL, here's the most efficient way. This retrieves the current identity seed from a table based on whatever column is the identity.

select IDENT_CURRENT('TableName') as LastIdentity

Using MAX(id) is more generic, but for example I have an table with 400 million rows that takes 2 minutes to get the MAX(id). IDENT_CURRENT is nearly instantaneous...

How to concatenate items in a list to a single string?

If you have mixed content list. And want to stringify it. Here is one way:

Consider this list:

>>> aa
[None, 10, 'hello']

Convert it to string:

>>> st = ', '.join(map(str, map(lambda x: f'"{x}"' if isinstance(x, str) else x, aa)))
>>> st = '[' + st + ']'
>>> st
'[None, 10, "hello"]'

If required, convert back to list:

>>> ast.literal_eval(st)
[None, 10, 'hello']

Add numpy array as column to Pandas data frame

Consider using a higher dimensional datastructure (a Panel), rather than storing an array in your column:

In [11]: p = pd.Panel({'df': df, 'csc': csc})

In [12]: p.df
Out[12]: 
   0  1  2
0  1  2  3
1  4  5  6
2  7  8  9

In [13]: p.csc
Out[13]: 
   0  1  2
0  0  1  0
1  0  0  1
2  1  0  0

Look at cross-sections etc, etc, etc.

In [14]: p.xs(0)
Out[14]: 
   csc  df
0    0   1
1    1   2
2    0   3

See the docs for more on Panels.

Remove git mapping in Visual Studio 2015

Removing .git hidden folder worked for me.

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

Put this in C2 and copy down

=IF(ISNA(VLOOKUP(A2,$B$2:$B$65535,1,FALSE)),"not in B","")

Then if the value in A isn't in B the cell in column C will say "not in B".

How do I set ANDROID_SDK_HOME environment variable?

Android SDK

Installing the Android SDK is also necessary. The Android SDK provides you the API libraries and developer tools necessary to build, test, and debug apps for Android.

Cordova requires the ANDROID_HOME environment variable to be set. This should point to the [ANDROID_SDK_DIR]\android-sdk directory (for example c:\android\android-sdk).

Next, update your PATH to include the tools/ and platform-tools/ folder in that folder. So, using ANDROID_HOME, you would add both %ANDROID_HOME%\tools and %ANDROID_HOME%\platform-tools.

Reference : http://ionicframework.com/docs/v1/guide/installation.html

Double.TryParse or Convert.ToDouble - which is faster and safer?

This is an interesting old question. I'm adding an answer because nobody noticed a couple of things with the original question.

Which is faster: Convert.ToDouble or Double.TryParse? Which is safer: Convert.ToDouble or Double.TryParse?

I'm going to answer both these questions (I'll update the answer later), in detail, but first:

For safety, the thing every programmer missed in this question is the line (emphasis mine):

It adds only data that are numbers with a few digits (1000 1000,2 1000,34 - comma is a delimiter in Russian standards).

Followed by this code example:

Convert.ToDouble(regionData, CultureInfo.CurrentCulture);

What's interesting here is that if the spreadsheets are in Russian number format but Excel has not correctly typed the cell fields, what is the correct interpretation of the values coming in from Excel?

Here is another interesting thing about the two examples, regarding speed:

catch (InvalidCastException)
{
    // is not a number
}

This is likely going to generate MSIL that looks like this:

catch [mscorlib]System.InvalidCastException 
{
  IL_0023:  stloc.0
  IL_0024:  nop
  IL_0025:  ldloc.0
  IL_0026:  nop
  IL_002b:  nop
  IL_002c:  nop
  IL_002d:  leave.s    IL_002f
}  // end handler
IL_002f: nop
IL_0030: return

In this sense, we can probably compare the total number of MSIL instructions carried out by each program - more on that later as I update this post.

I believe code should be Correct, Clear, and Fast... In that order!

How to get the filename without the extension in Java?

Simplest way to get name from relative path or full path is using

import org.apache.commons.io.FilenameUtils; FilenameUtils.getBaseName(definitionFilePath)

How to remove unused imports from Eclipse

Remove all unused import in eclipse:

Right click on the desired package then Source->Organize Imports. Or You can direct use the shortcut by pressing Ctrl+Shift+O

Work perfectly.

Java: Converting String to and from ByteBuffer and associated problems

Check out the CharsetEncoder and CharsetDecoder API descriptions - You should follow a specific sequence of method calls to avoid this problem. For example, for CharsetEncoder:

  1. Reset the encoder via the reset method, unless it has not been used before;
  2. Invoke the encode method zero or more times, as long as additional input may be available, passing false for the endOfInput argument and filling the input buffer and flushing the output buffer between invocations;
  3. Invoke the encode method one final time, passing true for the endOfInput argument; and then
  4. Invoke the flush method so that the encoder can flush any internal state to the output buffer.

By the way, this is the same approach I am using for NIO although some of my colleagues are converting each char directly to a byte in the knowledge they are only using ASCII, which I can imagine is probably faster.

How to git-cherry-pick only changes to certain files?

Merge a branch into new one (squash) and remove the files not needed:

git checkout master
git checkout -b <branch>
git merge --squash <source-branch-with-many-commits>
git reset HEAD <not-needed-file-1>
git checkout -- <not-needed-file-1>
git reset HEAD <not-needed-file-2>
git checkout -- <not-needed-file-2>
git commit

How to use ADB Shell when Multiple Devices are connected? Fails with "error: more than one device and emulator"

adb -d shell (or adb -e shell).

This command will help you in most of the cases, if you are too lazy to type the full ID.

From http://developer.android.com/tools/help/adb.html#commandsummary:

-d - Direct an adb command to the only attached USB device. Returns an error when more than one USB device is attached.

-e - Direct an adb command to the only running emulator. Returns an error when more than one emulator is running.

How to enable copy paste from between host machine and virtual machine in vmware, virtual machine is ubuntu

This worked for me. Might want to try editing virtual machine settings:

Click on Edit virtual machine settings

Switch to Always Enabled in Options, Shared Folders

set the iframe height automatically

If the sites are on separate domains, the calling page can't access the height of the iframe due to cross-browser domain restrictions. If you have access to both sites, you may be able to use the [document domain hack].1 Then anroesti's links should help.

Error: Cannot find module 'ejs'

Ensure all dependencies are installed. npm install

I was making a quick app for myself and I had forgotten to add express. Threw the above error.

How to set a tkinter window to a constant size

If you want a window as a whole to have a specific size, you can just give it the size you want with the geometry command. That's really all you need to do.

For example:

mw.geometry("500x500")

Though, you'll also want to make sure that the widgets inside the window resize properly, so change how you add the frame to this:

back.pack(fill="both", expand=True)

Restoring MySQL database from physical files

Yes it is! Just add them to your database-folder ( depending on the OS ) and run a command such as "MySQL Fix Permissions". This re-stored the database. See too it that the correct permissions are set on the files aswell.

REST API - file (ie images) processing - best practices

There are several decisions to make:

  1. The first about resource path:

    • Model the image as a resource on its own:

      • Nested in user (/user/:id/image): the relationship between the user and the image is made implicitly

      • In the root path (/image):

        • The client is held responsible for establishing the relationship between the image and the user, or;

        • If a security context is being provided with the POST request used to create an image, the server can implicitly establish a relationship between the authenticated user and the image.

    • Embed the image as part of the user

  2. The second decision is about how to represent the image resource:

    • As Base 64 encoded JSON payload
    • As a multipart payload

This would be my decision track:

  • I usually favor design over performance unless there is a strong case for it. It makes the system more maintainable and can be more easily understood by integrators.
  • So my first thought is to go for a Base64 representation of the image resource because it lets you keep everything JSON. If you chose this option you can model the resource path as you like.
    • If the relationship between user and image is 1 to 1 I'd favor to model the image as an attribute specially if both data sets are updated at the same time. In any other case you can freely choose to model the image either as an attribute, updating the it via PUT or PATCH, or as a separate resource.
  • If you choose multipart payload I'd feel compelled to model the image as a resource on is own, so that other resources, in our case, the user resource, is not impacted by the decision of using a binary representation for the image.

Then comes the question: Is there any performance impact about choosing base64 vs multipart?. We could think that exchanging data in multipart format should be more efficient. But this article shows how little do both representations differ in terms of size.

My choice Base64:

  • Consistent design decision
  • Negligible performance impact
  • As browsers understand data URIs (base64 encoded images), there is no need to transform these if the client is a browser
  • I won't cast a vote on whether to have it as an attribute or standalone resource, it depends on your problem domain (which I don't know) and your personal preference.

Set a border around a StackPanel.

What about this one :

<DockPanel Margin="8">
    <Border CornerRadius="6" BorderBrush="Gray" Background="LightGray" BorderThickness="2" DockPanel.Dock="Top">
        <StackPanel Orientation="Horizontal">
            <TextBlock FontSize="14" Padding="0 0 8 0" HorizontalAlignment="Center" VerticalAlignment="Center">Search:</TextBlock>
            <TextBox x:Name="txtSearchTerm" HorizontalAlignment="Center" VerticalAlignment="Center" />
            <Image Source="lock.png" Width="32" Height="32" HorizontalAlignment="Center" VerticalAlignment="Center" />            
        </StackPanel>
    </Border>
    <StackPanel Orientation="Horizontal" DockPanel.Dock="Bottom" Height="25" />
</DockPanel>

How to handle windows file upload using Selenium WebDriver?

Find the element (must be an input element with type="file" attribute) and send the path to the file.

WebElement fileInput = driver.findElement(By.id("uploadFile"));
fileInput.sendKeys("/path/to/file.jpg");

NOTE: If you're using a RemoteWebDriver, you will also have to set a file detector. The default is UselessFileDetector

WebElement fileInput = driver.findElement(By.id("uploadFile"));
driver.setFileDetector(new LocalFileDetector());
fileInput.sendKeys("/path/to/file.jpg");

Regex Letters, Numbers, Dashes, and Underscores

Depending on your regex variant, you might be able to do simply this:

([\w-]+)

Also, you probably don't need the parentheses unless this is part of a larger expression.

How to Retrieve value from JTextField in Java Swing?

How do we retrieve a value from a text field?

mytestField.getText();

ActionListner example:

mytextField.addActionListener(this);

public void actionPerformed(ActionEvent evt) {
    String text = textField.getText();
    textArea.append(text + newline);
    textField.selectAll();
}

Beginner Python Practice?

You could also try CheckIO which is kind of a quest where you have to post solutions in Python 2.7 or 3.3 to move up in the game. Fun and has quite a big community for questions and support.

From their Main Wiki Page:

Welcome to CheckIO – a service that has united all levels of Python developers – from beginners up to the real experts!

Here you can learn Python coding, try yourself in solving various kinds of problems and share your ideas with others. Moreover, you can consider original solutions of other users, exchange opinions and find new friends.

If you are just starting with Python – CheckIO is a great chance for you to learn the basics and get a rich practice in solving different tasks. If you’re an experienced coder, here you’ll find an exciting opportunity to perfect your skills and learn new alternative logics from others. On CheckIO you can not only resolve the existing tasks, but also provide your own ones and even get points for them. Enjoy the possibility of playing logical games, participating in exciting competitions and share your success with friends in CheckIO.org!

How to view DB2 Table structure

I am using Aquadata Studio 12.0.23, which is several versions short of the newest. So your experience may be better than mine. I found that the best way to get an overview was to use the ERD generator. It took a couple of hours, since normalization was not a concept used in the design of this database almost 30 years ago. I was able to get definitions for all of the objects in a few hours, with a file for each.

Including a css file in a blade template?

in your main layout put this in the head at the bottom of everything

@stack('styles')

and in your view put this

@push('styles')

    <link rel="stylesheet" href="{{ asset('css/app.css') }}">

@endpush

basically a placeholder so the links will appear on your main layout, and you can see custom css files on different pages

How to rotate a 3D object on axis three.js?

In Three.js R66, this is what I use (CoffeeScript version):

THREE.Object3D.prototype.rotateAroundWorldAxis = (axis, radians) ->
  rotWorldMatrix = new THREE.Matrix4()
  rotWorldMatrix.makeRotationAxis axis.normalize(), radians
  rotWorldMatrix.multiply this.matrix
  this.matrix = rotWorldMatrix
  this.rotation.setFromRotationMatrix this.matrix

Structs in Javascript

I use objects JSON style for dumb structs (no member functions).

Limiting the output of PHP's echo to 200 characters

It gives out a string of max 200 characters OR 200 normal characters OR 200 characters followed by '...'

$ur_str= (strlen($ur_str) > 200) ? substr($ur_str,0,200).'...' :$ur_str;

Python POST binary data

This has nothing to do with a malformed upload. The HTTP error clearly specifies 401 unauthorized, and tells you the CSRF token is invalid. Try sending a valid CSRF token with the upload.

More about csrf tokens here:

What is a CSRF token ? What is its importance and how does it work?

Visual Studio - How to change a project's folder name and solution name without breaking the solution

You could open the SLN file in any text editor (Notepad, etc.) and simply change the project path there.

How to get the previous page URL using JavaScript?

You can use the following to get the previous URL.

var oldURL = document.referrer;
alert(oldURL);

Excel add one hour

This may help you as well. This is a conditional statement that will fill the cell with a default date if it is empty but will subtract one hour if it is a valid date/time and put it into the cell.

=IF((Sheet1!C4)="",DATE(1999,1,1),Sheet1!C4-TIME(1,0,0))

You can also substitute TIME with DATE to add or subtract a date or time.

How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest

Setting CSS width to 1% or 100% of an element according to all specs I could find out is related to the parent. Although Blink Rendering Engine (Chrome) and Gecko (Firefox) at the moment of writing seems to handle that 1% or 100% (make a columns shrink or a column to fill available space) well, it is not guaranteed according to all CSS specifications I could find to render it properly.

One option is to replace table with CSS4 flex divs:

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

That works in new browsers i.e. IE11+ see table at the bottom of the article.

Numpy array dimensions

First:

By convention, in Python world, the shortcut for numpy is np, so:

In [1]: import numpy as np

In [2]: a = np.array([[1,2],[3,4]])

Second:

In Numpy, dimension, axis/axes, shape are related and sometimes similar concepts:

dimension

In Mathematics/Physics, dimension or dimensionality is informally defined as the minimum number of coordinates needed to specify any point within a space. But in Numpy, according to the numpy doc, it's the same as axis/axes:

In Numpy dimensions are called axes. The number of axes is rank.

In [3]: a.ndim  # num of dimensions/axes, *Mathematics definition of dimension*
Out[3]: 2

axis/axes

the nth coordinate to index an array in Numpy. And multidimensional arrays can have one index per axis.

In [4]: a[1,0]  # to index `a`, we specific 1 at the first axis and 0 at the second axis.
Out[4]: 3  # which results in 3 (locate at the row 1 and column 0, 0-based index)

shape

describes how many data (or the range) along each available axis.

In [5]: a.shape
Out[5]: (2, 2)  # both the first and second axis have 2 (columns/rows/pages/blocks/...) data

custom facebook share button

You can use facebook javascript sdk. First add FB Js SDK to your code (please refer to https://developers.facebook.com/docs/javascript)

window.fbAsyncInit = function(){
FB.init({
    appId: 'xxxxx', status: true, cookie: true, xfbml: true }); 
};
(function(d, debug){var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
    if(d.getElementById(id)) {return;}
    js = d.createElement('script'); js.id = id; 
    js.async = true;js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";
    ref.parentNode.insertBefore(js, ref);}(document, /*debug*/ false));
function postToFeed(title, desc, url, image){
var obj = {method: 'feed',link: url, picture: 'http://www.url.com/images/'+image,name: title,description: desc};
function callback(response){}
FB.ui(obj, callback);
}

So when you want to share something

<a href="someurl.com/some-article" data-image="article-1.jpg" data-title="Article Title" data-desc="Some description for this article" class="btnShare">Share</a>

And finally JS to handle click:

$('.btnShare').click(function(){
elem = $(this);
postToFeed(elem.data('title'), elem.data('desc'), elem.prop('href'), elem.data('image'));

return false;
});

Bootstrap 3.0 Sliding Menu from left

I believe that although javascript is an option here, you have a smoother animation through forcing hardware accelerate with CSS3. You can achieve this by setting the following CSS3 properties on the moving div:

div.hardware-accelarate {
     -webkit-transform: translate3d(0,0,0);
        -moz-transform: translate3d(0,0,0);
         -ms-transform: translate3d(0,0,0);
          -o-transform: translate3d(0,0,0);
             transform: translate3d(0,0,0);
}

I've made a plunkr setup for ya'll to test and tweak...

Is there a way to make AngularJS load partials in the beginning and not at when needed?

You can pass $state to your controller and then when the page loads and calls the getter in the controller you call $state.go('index') or whatever partial you want to load. Done.

How to set label size in Bootstrap

if you have

<span class="label label-default">New</span>

just add the style="font-size:XXpx;", ej.

<span class="label label-default" style="font-size:15px;">New</span>

How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?

You can write a PL/SQL function to return that cursor (or you could put that function in a package if you have more code related to this):

CREATE OR REPLACE FUNCTION get_allitems
  RETURN SYS_REFCURSOR
AS
  my_cursor SYS_REFCURSOR;
BEGIN
  OPEN my_cursor FOR SELECT * FROM allitems;
  RETURN my_cursor;
END get_allitems;

This will return the cursor.

Make sure not to put your SELECT-String into quotes in PL/SQL when possible. Putting it in strings means that it can not be checked at compile time, and that it has to be parsed whenever you use it.


If you really need to use dynamic SQL you can put your query in single quotes:

  OPEN my_cursor FOR 'SELECT * FROM allitems';

This string has to be parsed whenever the function is called, which will usually be slower and hides errors in your query until runtime.

Make sure to use bind-variables where possible to avoid hard parses:

  OPEN my_cursor FOR 'SELECT * FROM allitems WHERE id = :id' USING my_id;

Passing parameters to a JDBC PreparedStatement

You should use the setString() method to set the userID. This both ensures that the statement is formatted properly, and prevents SQL injection:

statement =con.prepareStatement("SELECT * from employee WHERE  userID = ?");
statement.setString(1, userID);

There is a nice tutorial on how to use PreparedStatements properly in the Java Tutorials.

How to catch a specific SqlException error?

It is better to use error codes, you don't have to parse.

try
{
}
catch (SqlException exception)
{
    if (exception.Number == 208)
    {

    }
    else
        throw;
}

How to find out that 208 should be used:

select message_id
from sys.messages
where text like 'Invalid object name%'

JQuery find first parent element with specific class prefix

Jquery later allowed you to to find the parents with the .parents() method.

Hence I recommend using:

var $div = $('#divid').parents('div[class^="div-a"]');

This gives all parent nodes matching the selector. To get the first parent matching the selector use:

var $div = $('#divid').parents('div[class^="div-a"]').eq(0);

For other such DOM traversal queries, check out the documentation on traversing the DOM.

How can I pause setInterval() functions?

The following code, provides a precision way to pause resume a timer.

How it works:

When the timer is resumed after a pause, it generates a correction cycle using a single timeout, that will consider the pause offset (exact time when the timer was paused between cycles). After the correction cycle finishes, it schedules the following cycles with a regular setInteval, and continues normally the cycle execution.

This allows to pause/resume the timer, without losing the sync.

Code :

_x000D_
_x000D_
function Timer(_fn_callback_ , _timer_freq_){_x000D_
    let RESUME_CORRECTION_RATE = 2;_x000D_
_x000D_
    let _timer_statusCode_;_x000D_
    let _timer_clockRef_;_x000D_
_x000D_
    let _time_ellapsed_;        // will store the total time ellapsed_x000D_
    let _time_pause_;           // stores the time when timer is paused_x000D_
    let _time_lastCycle_;       // stores the time of the last cycle_x000D_
_x000D_
    let _isCorrectionCycle_;_x000D_
 _x000D_
    /**_x000D_
     * execute in each clock cycle_x000D_
     */_x000D_
    const nextCycle = function(){_x000D_
        // calculate deltaTime_x000D_
        let _time_delta_        = new Date() - _time_lastCycle_;_x000D_
        _time_lastCycle_    = new Date();_x000D_
        _time_ellapsed_   += _time_delta_;_x000D_
_x000D_
        // if its a correction cicle (caused by a pause,_x000D_
        // destroy the temporary timeout and generate a definitive interval_x000D_
        if( _isCorrectionCycle_ ){_x000D_
            clearTimeout( _timer_clockRef_ );_x000D_
            clearInterval( _timer_clockRef_ );_x000D_
            _timer_clockRef_    = setInterval(  nextCycle , _timer_freq_  );_x000D_
            _isCorrectionCycle_ = false;_x000D_
        }_x000D_
        // execute callback_x000D_
        _fn_callback_.apply( timer, [ timer ] );_x000D_
    };_x000D_
_x000D_
    // initialize timer_x000D_
    _time_ellapsed_     = 0;_x000D_
    _time_lastCycle_     = new Date();_x000D_
    _timer_statusCode_   = 1;_x000D_
    _timer_clockRef_     = setInterval(  nextCycle , _timer_freq_  );_x000D_
_x000D_
_x000D_
    // timer public API_x000D_
    const timer = {_x000D_
        get statusCode(){ return _timer_statusCode_ },_x000D_
        get timestamp(){_x000D_
            let abstime;_x000D_
            if( _timer_statusCode_=== 1 ) abstime = _time_ellapsed_ + ( new Date() - _time_lastCycle_ );_x000D_
            else if( _timer_statusCode_=== 2 ) abstime = _time_ellapsed_ + ( _time_pause_ - _time_lastCycle_ );_x000D_
            return abstime || 0;_x000D_
        },_x000D_
_x000D_
        pause : function(){_x000D_
            if( _timer_statusCode_ !== 1 ) return this;_x000D_
            // stop timers_x000D_
            clearTimeout( _timer_clockRef_ );_x000D_
            clearInterval( _timer_clockRef_ );_x000D_
            // set new status and store current time, it will be used on_x000D_
            // resume to calculate how much time is left for next cycle_x000D_
            // to be triggered_x000D_
            _timer_statusCode_ = 2;_x000D_
            _time_pause_       = new Date();_x000D_
            return this;_x000D_
        },_x000D_
_x000D_
        resume: function(){_x000D_
            if( _timer_statusCode_ !== 2 ) return this;_x000D_
            _timer_statusCode_  = 1;_x000D_
            _isCorrectionCycle_ = true;_x000D_
            const delayEllapsedTime = _time_pause_ - _time_lastCycle_;_x000D_
            _time_lastCycle_    = new Date( new Date() - (_time_pause_ - _time_lastCycle_) );_x000D_
_x000D_
            _timer_clockRef_ = setTimeout(  nextCycle , _timer_freq_ - delayEllapsedTime - RESUME_CORRECTION_RATE);_x000D_
_x000D_
            return this;_x000D_
        } _x000D_
    };_x000D_
    return timer;_x000D_
};_x000D_
_x000D_
_x000D_
let myTimer = Timer( x=> console.log(x.timestamp), 1000);
_x000D_
<input type="button" onclick="myTimer.pause()" value="pause">_x000D_
<input type="button" onclick="myTimer.resume()" value="resume">
_x000D_
_x000D_
_x000D_

Code source :

This Timer is a modified and simplified version of advanced-timer, a js library created by myself, with many more functionalities.

The full library and documentation is available in NPM and GITHUB

Attach a file from MemoryStream to a MailMessage in C#

I landed on this question because I needed to attach an Excel file I generate through code and is available as MemoryStream. I could attach it to the mail message but it was sent as 64Bytes file instead of a ~6KB as it was meant. So, the solution that worked for me was this:

MailMessage mailMessage = new MailMessage();
Attachment attachment = new Attachment(myMemorySteam, new ContentType(MediaTypeNames.Application.Octet));

attachment.ContentDisposition.FileName = "myFile.xlsx";
attachment.ContentDisposition.Size = attachment.Length;

mailMessage.Attachments.Add(attachment);

Setting the value of attachment.ContentDisposition.Size let me send messages with the correct size of attachment.

How to Convert date into MM/DD/YY format in C#

Look into using the ToString() method with a specified format.

Javascript to export html table to Excel

For UTF 8 Conversion and Currency Symbol Export Use this:

var tableToExcel = (function() {
  var uri = 'data:application/vnd.ms-excel;base64,'
    , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><?xml version="1.0" encoding="UTF-8" standalone="yes"?><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
    , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
    , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
  return function(table, name) {
      if (!table.nodeType) table = document.getElementById(table)
      var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
    window.location.href = uri + base64(format(template, ctx))
  }
})()

Storing WPF Image Resources

In code to load a resource in the executing assembly where my image Freq.png was in the folder Icons and defined as Resource:

this.Icon = new BitmapImage(new Uri(@"pack://application:,,,/" 
    + Assembly.GetExecutingAssembly().GetName().Name 
    + ";component/" 
    + "Icons/Freq.png", UriKind.Absolute)); 

I also made a function:

/// <summary>
/// Load a resource WPF-BitmapImage (png, bmp, ...) from embedded resource defined as 'Resource' not as 'Embedded resource'.
/// </summary>
/// <param name="pathInApplication">Path without starting slash</param>
/// <param name="assembly">Usually 'Assembly.GetExecutingAssembly()'. If not mentionned, I will use the calling assembly</param>
/// <returns></returns>
public static BitmapImage LoadBitmapFromResource(string pathInApplication, Assembly assembly = null)
{
    if (assembly == null)
    {
        assembly = Assembly.GetCallingAssembly();
    }

    if (pathInApplication[0] == '/')
    {
        pathInApplication = pathInApplication.Substring(1);
    }
    return new BitmapImage(new Uri(@"pack://application:,,,/" + assembly.GetName().Name + ";component/" + pathInApplication, UriKind.Absolute)); 
}

Usage (assumption you put the function in a ResourceHelper class):

this.Icon = ResourceHelper.LoadBitmapFromResource("Icons/Freq.png");

Note: see MSDN Pack URIs in WPF:
pack://application:,,,/ReferencedAssembly;component/Subfolder/ResourceFile.xaml

Original purpose of <input type="hidden">?

basically hidden fields will be more useful and advantages to use with multi step form. we can use hidden fields to pass one step information to next step using hidden and keep it forwarding till the end step.

  1. CSRF tokens.

Cross-site request forgery is a very common website vulnerability. Requiring a secret, user-specific token in all form submissions will prevent CSRF attacks since attack sites cannot guess what the proper token is and any form submissions they perform on the behalf of the user will always fail.

  1. Save state in multi-page forms.

If you need to store what step in a multi-page form the user is currently on, use hidden input fields. The user doesn't need to see this information, so hide it in a hidden input field.

General rule: Use the field to store anything that the user doesn't need to see, but that you want to send to the server on form submission.

Adding hours to JavaScript Date object?

For a simple add/subtract hour/minute function in javascript, try this:

function getTime (addHour, addMin){
    addHour = (addHour?addHour:0);
    addMin = (addMin?addMin:0);
    var time = new Date(new Date().getTime());
    var AM = true;
    var ndble = 0;
    var hours, newHour, overHour, newMin, overMin;
    //change form 24 to 12 hour clock
    if(time.getHours() >= 13){
        hours = time.getHours() - 12;
        AM = (hours>=12?true:false);
    }else{
        hours = time.getHours();
        AM = (hours>=12?false:true);
    }
    //get the current minutes
    var minutes = time.getMinutes();
    // set minute
    if((minutes+addMin) >= 60 || (minutes+addMin)<0){
        overMin = (minutes+addMin)%60;
        overHour = Math.floor((minutes+addMin-Math.abs(overMin))/60);
        if(overMin<0){
            overMin = overMin+60;
            overHour = overHour-Math.floor(overMin/60);
        }
        newMin = String((overMin<10?'0':'')+overMin);
        addHour = addHour+overHour;
    }else{
        newMin = minutes+addMin;
        newMin = String((newMin<10?'0':'')+newMin);
    }
    //set hour
    if(( hours+addHour>=13 )||( hours+addHour<=0 )){
        overHour = (hours+addHour)%12;
        ndble = Math.floor(Math.abs((hours+addHour)/12));
        if(overHour<=0){
            newHour = overHour+12;
            if(overHour == 0){
                ndble++;
            }
        }else{
            if(overHour ==0 ){
                newHour = 12;
                ndble++;
            }else{
                ndble++;
                newHour = overHour;
            }
        }
        newHour = (newHour<10?'0':'')+String(newHour);
        AM = ((ndble+1)%2===0)?AM:!AM;
    }else{
        AM = (hours+addHour==12?!AM:AM);
        newHour = String((Number(hours)+addHour<10?'0':'')+(hours+addHour));
    }
    var am = (AM)?'AM':'PM';
    return new Array(newHour, newMin, am);
};

This can be used without parameters to get the current time

getTime();

or with parameters to get the time with the added minutes/hours

getTime(1,30); // adds 1.5 hours to current time
getTime(2);    // adds 2 hours to current time
getTime(0,120); // same as above

even negative time works

getTime(-1, -30); // subtracts 1.5 hours from current time

this function returns an array of

array([Hour], [Minute], [Meridian])

Progress Bar with HTML and CSS

Create an element which shows the left part of the bar (the round part), also create an element for the right part. For the actual progress bar, create a third element with a repeating background and a width which depends on the actual progress. Put it all on top of the background image (containing the empty progress bar).

But I suppose you already knew that...

Edit: When creating a progress bar which do not use textual backgrounds. You can use the border-radius to get the round effect, as shown by Rikudo Sennin and RoToRa!

SQL DROP TABLE foreign key constraint

No, this will not drop your table if there are indeed foreign keys referencing it.

To get all foreign key relationships referencing your table, you could use this SQL (if you're on SQL Server 2005 and up):

SELECT * 
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('Student')

and if there are any, with this statement here, you could create SQL statements to actually drop those FK relations:

SELECT 
    'ALTER TABLE [' +  OBJECT_SCHEMA_NAME(parent_object_id) +
    '].[' + OBJECT_NAME(parent_object_id) + 
    '] DROP CONSTRAINT [' + name + ']'
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('Student')

PostgreSQL: ERROR: operator does not exist: integer = character varying

I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).

If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::.

Something along these lines:

create view view1
as 
select table1.col1,table2.col1,table3.col3
from table1 
inner join
table2 
inner join 
table3
on 
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;

Notice the varchar typecasting on the table1.col4.

Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.

Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).

How to make a machine trust a self-signed Java application

SERIOUS DISCLAIMER

This solution has a serious security flaw. Please use at your own risk.
Have a look at the comments on this post, and look at all the answers to this question.


OK, I had to go to the customer premises and found a solution. I:

  • Exported the keystore that holds the signing keys in PKCS #12 format
  • Opened control panel Java -> Security tab
  • Clicked Manage certificates
  • Imported this new keystore as a secure site CA

Then I opened the JAWS application without any warning. This is a little bit cumbersome, but much cheaper than buying a signed certificate!

PHP pass variable to include

In regards to the OP's question, specifically "The variable needs to be set and evaluated from the calling first file (it's actually '$_SERVER['PHP_SELF']', and needs to return the path of that file, not the included second.php)."

This will tell you what file included the file. Place this in the included file.

$includer = debug_backtrace();
echo $includer[0]['file'];

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

I’ve found a solution. I had to clear fragment’s parent from views before destroying and I’ve used the next peace of code for this:

in Java

public void onDestroyView() {
        if (rootView != null){
            ViewGroup viewGroup = (ViewGroup)rootView.getParent();
            if (viewGroup != null){
                viewGroup.removeAllViews();
            }
        }
        super.onDestroyView();
    }

in Kotlin

override fun onDestroyView() {
    if (rootView != null) {
        val viewGroup = rootView.parent as ViewGroup?
        viewGroup?.removeAllViews();
    }
    super.onDestroyView()
}

Razor view engine - How can I add Partial Views

If you don't want to duplicate code, and like me you just want to show stats, in your view model, you could just pass in the models you want to get data from like so:

public class GameViewModel
{
    public virtual Ship Ship { get; set; }
    public virtual GamePlayer GamePlayer { get; set; }     
}

Then, in your controller just run your queries on the respective models, pass them to the view model and return it, example:

GameViewModel PlayerStats = new GameViewModel();

GamePlayer currentPlayer = (from c in db.GamePlayer [more queries]).FirstOrDefault();

[code to check if results]

//pass current player into custom view model
PlayerStats.GamePlayer = currentPlayer;

Like I said, you should only really do this if you want to display stats from the relevant tables, and there's no other part of the CRUD process happening, for security reasons other people have mentioned above.

Disable a textbox using CSS

**just copy paste this code and run you can see the textbox disabled **

<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title> 

<style>.container{float:left;width:200px;height:25px;position:relative;}
       .container input{float:left;width:200px;height:25px;}
       .overlay{display:block;width:208px;position:absolute;top:0px;left:0px;height:32px;} 
</style>
 </head>
<body>
      <div class="container">
       <input type="text" value="[email protected]" />
       <div class="overlay">
        </div>
       </div> 
</body>
</html>

asp.net: Invalid postback or callback argument

You can also fill you data in the prerender event. This way you can keep your validation and stay secure. Here is an example using a repeater.

protected void Page_PreRender(object sender, EventArgs e)
     {
        List<Objects.User> users = Application.User.GetAllUsers();

        Repeater1.DataSource = users;
        Repeater1.DataBind();
      }

Remove all padding and margin table HTML and CSS

Try using tag body to remove all margin and padding like that you want.

<body style="margin: 0;padding: 0">
    <table border="1" width="100%" cellpadding="0" cellspacing="0" bgcolor=green>
        <tr>
            <td >&nbsp;</td>
            <td>&nbsp;</td>
        </tr>
        <tr>
            <td >&nbsp;</td>
            <td>&nbsp;</td>
        </tr>
        <tr>
            <td >&nbsp;</td>
            <td>&nbsp;</td>
        </tr>
    </table>
</body>

Python if-else short-hand

The most readable way is

x = 10 if a > b else 11

but you can use and and or, too:

x = a > b and 10 or 11

The "Zen of Python" says that "readability counts", though, so go for the first way.

Also, the and-or trick will fail if you put a variable instead of 10 and it evaluates to False.

However, if more than the assignment depends on this condition, it will be more readable to write it as you have:

if A[i] > B[j]:
  x = A[i]
  i += 1
else:
  x = A[j]
  j += 1

unless you put i and j in a container. But if you show us why you need it, it may well turn out that you don't.

How to make a simple image upload using Javascript/HTML

Try this, It supports multi file uploading,

$('#multi_file_upload').change(function(e) {
    var file_id = e.target.id;

    var file_name_arr = new Array();
    var process_path = site_url + 'public/uploads/';

    for (i = 0; i < $("#" + file_id).prop("files").length; i++) {

        var form_data = new FormData();
        var file_data = $("#" + file_id).prop("files")[i];
        form_data.append("file_name", file_data);

        if (check_multifile_logo($("#" + file_id).prop("files")[i]['name'])) {
            $.ajax({
                //url         :   site_url + "inc/upload_image.php?width=96&height=60&show_small=1",
                url: site_url + "inc/upload_contact_info.php",
                cache: false,
                contentType: false,
                processData: false,
                async: false,
                data: form_data,
                type: 'post',
                success: function(data) {
                    // display image
                }
            });
        } else {
            $("#" + html_div).html('');
            alert('We only accept JPG, JPEG, PNG, GIF and BMP files');
        }

    }
});

function check_multifile_logo(file) {
    var extension = file.substr((file.lastIndexOf('.') + 1))
    if (extension === 'jpg' || extension === 'jpeg' || extension === 'gif' || extension === 'png' || extension === 'bmp') {
        return true;
    } else {
        return false;
    }
}

Here #multi_file_upload is the ID of image upload field.

Invalidating JSON Web Tokens

This is primarily a long comment supporting and building on the answer by @mattway

Given:

Some of the other proposed solutions on this page advocate hitting the datastore on every request. If you hit the main datastore to validate every authentication request, then I see less reason to use JWT instead of other established token authentication mechanisms. You've essentially made JWT stateful, instead of stateless if you go to the datastore each time.

(If your site receives a high volume of unauthorized requests, then JWT would deny them without hitting the datastore, which is helpful. There are probably other use cases like that.)

Given:

Truly stateless JWT authentication cannot be achieved for a typical, real world web app because stateless JWT does not have a way to provide immediate and secure support for the following important use cases:

User's account is deleted/blocked/suspended.

User's password is changed.

User's roles or permissions are changed.

User is logged out by admin.

Any other application critical data in the JWT token is changed by the site admin.

You cannot wait for token expiration in these cases. The token invalidation must occur immediately. Also, you cannot trust the client not to keep and use a copy of the old token, whether with malicious intent or not.

Therefore: I think the answer from @matt-way, #2 TokenBlackList, would be most efficient way to add the required state to JWT based authentication.

You have a blacklist that holds these tokens until their expiration date is hit. The list of tokens will be quite small compared to the total number of users, since it only has to keep blacklisted tokens until their expiration. I'd implement by putting invalidated tokens in redis, memcached or another in-memory datastore that supports setting an expiration time on a key.

You still have to make a call to your in-memory db for every authentication request that passes initial JWT auth, but you don't have to store keys for your entire set of users in there. (Which may or may not be a big deal for a given site.)

Select first 4 rows of a data.frame in R

Use head:

dnow <- data.frame(x=rnorm(100), y=runif(100))
head(dnow,4) ## default is 6

How does HTTP file upload work?

An HTTP message may have a body of data sent after the header lines. In a response, this is where the requested resource is returned to the client (the most common use of the message body), or perhaps explanatory text if there's an error. In a request, this is where user-entered data or uploaded files are sent to the server.

http://www.tutorialspoint.com/http/http_messages.htm

Find all packages installed with easy_install/pip?

At least for Ubuntu (maybe also others) works this (inspired by a previous post in this thread):

printf "Installed with pip:";
pip list 2>/dev/null | gawk '{print $1;}' | while read; do pip show "${REPLY}" 2>/dev/null | grep 'Location: /usr/local/lib/python2.7/dist-packages' >/dev/null; if (( $? == 0 )); then printf " ${REPLY}"; fi; done; echo

How to unsubscribe to a broadcast event in angularJS. How to remove function registered via $on

Looking at most of the replies, they seem overly complicated. Angular has built in mechanisms to unregister.

Use the deregistration function returned by $on :

// Register and get a handle to the listener
var listener = $scope.$on('someMessage', function () {
    $log.log("Message received");
});

// Unregister
$scope.$on('$destroy', function () {
    $log.log("Unregistering listener");
    listener();
});

What is the most efficient way to store tags in a database?

Items should have an "ID" field, and Tags should have an "ID" field (Primary Key, Clustered).

Then make an intermediate table of ItemID/TagID and put the "Perfect Index" on there.

Which is better: <script type="text/javascript">...</script> or <script>...</script>

<script type="text/javascript"></script> because its the right way and compatible with all browsers

Set the space between Elements in Row Flutter

You can use Spacers if all you want is a little bit of spacing between items in a row. The example below centers 2 Text widgets within a row with some spacing between them.

Spacer creates an adjustable, empty spacer that can be used to tune the spacing between widgets in a Flex container, like Row or Column.

In a row, if we want to put space between two widgets such that it occupies all remaining space.

    widget = Row (
    children: <Widget>[
      Spacer(flex: 20),
      Text(
        "Item #1",
      ),
      Spacer(),  // Defaults to flex: 1
      Text(
        "Item #2",
      ),
      Spacer(flex: 20),
    ]
  );

Property getters and setters

Try using this:

var x:Int!

var xTimesTwo:Int {
    get {
        return x * 2
    }
    set {
        x = newValue / 2
    }
}

This is basically Jack Wu's answer, but the difference is that in Jack Wu's answer his x variable is var x: Int, in mine, my x variable is like this: var x: Int!, so all I did was make it an optional type.

The object 'DF__*' is dependent on column '*' - Changing int to double

While dropping the columns from multiple tables, I faced following default constraints error. Similar issue appears if you need to change the datatype of column.

The object 'DF_TableName_ColumnName' is dependent on column 'ColumnName'.

To resolve this, I have to drop all those constraints first, by using following query

DECLARE @sql NVARCHAR(max)=''     
SELECT @SQL += 'Alter table ' + Quotename(tbl.name) + '  DROP constraint ' + Quotename(cons.name) + ';'
 FROM SYS.DEFAULT_CONSTRAINTS cons 
 JOIN   SYS.COLUMNS col ON col.default_object_id = cons.object_id
 JOIN   SYS.TABLES tbl ON tbl.object_id = col.object_id
 WHERE  col.[name] IN ('Column1','Column2')

--PRINT @sql
EXEC Sp_executesql @sql 

After that, I dropped all those columns (my requirement, not mentioned in this question)

DECLARE @sql NVARCHAR(max)='' 
SELECT @SQL += 'Alter table ' + Quotename(table_catalog)+ '.' + Quotename(table_schema) + '.'+ Quotename(TABLE_NAME) 
               + '  DROP column ' + Quotename(column_name) + ';'
FROM   information_schema.columns where COLUMN_NAME IN ('Column1','Column2')  
--PRINT @sql
EXEC Sp_executesql @sql 

I posted here in case someone find the same issue.

Happy Coding!

C++ Pass A String

Well, std::string is a class, const char * is a pointer. Those are two different things. It's easy to get from string to a pointer (since it typically contains one that it can just return), but for the other way, you need to create an object of type std::string.

My recommendation: Functions that take constant strings and don't modify them should always take const char * as an argument. That way, they will always work - with string literals as well as with std::string (via an implicit c_str()).

Print DIV content by JQuery

There is a way to use this with a hidden div but you have to work abit more with the printElement() function and css.

Css:

#SelectorToPrint{
     display: none;
}

Script:

  $("#SelectorToPrint").printElement({ printBodyOptions:{styleToAdd:'padding:10px;margin:10px;display:block', classNameToAdd:'WhatYouWant'}})

This will override the display: none in the new window you open and the content will be displayed on the print-preview page and the div on you site remains hidden.

How to delete/unset the properties of a javascript object?

To blank it:

myObject["myVar"]=null;

To remove it:

delete myObject["myVar"]

as you can see in duplicate answers

Plot a horizontal line using matplotlib

You can use plt.grid to draw a horizontal line.

import numpy as np
from matplotlib import pyplot as plt
from scipy.interpolate import UnivariateSpline
from matplotlib.ticker import LinearLocator

# your data here
annual = np.arange(1,21,1)
l = np.random.random(20)
spl = UnivariateSpline(annual,l)
xs = np.linspace(1,21,200)

# plot your data
plt.plot(xs,spl(xs),'b')

# horizental line?
ax = plt.axes()
# three ticks:
ax.yaxis.set_major_locator(LinearLocator(3))
# plot grids only on y axis on major locations
plt.grid(True, which='major', axis='y')

# show
plt.show()

random data plot example

How to select from subquery using Laravel Query Builder?

Laravel v5.6.12 (2018-03-14) added fromSub() and fromRaw() methods to query builder (#23476).

The accepted answer is correct but can be simplified into:

DB::query()->fromSub(function ($query) {
    $query->from('abc')->groupBy('col1');
}, 'a')->count();

The above snippet produces the following SQL:

select count(*) as aggregate from (select * from `abc` group by `col1`) as `a`

X11/Xlib.h not found in Ubuntu

Why not try find /usr/include/X11 -name Xlib.h

If there is a hit, you have Xlib.h

If not install it using sudo apt-get install libx11-dev

and you are good to go :)

JavaScript private methods

Personally, I prefer the following pattern for creating classes in JavaScript :

var myClass = (function() {
    // Private class properties go here

    var blueprint = function() {
        // Private instance properties go here
        ...
    };

    blueprint.prototype = { 
        // Public class properties go here
        ...
    };

    return  {
         // Public class properties go here
        create : function() { return new blueprint(); }
        ...
    };
})();

As you can see, it allows you to define both class properties and instance properties, each of which can be public and private.


Demo

_x000D_
_x000D_
var Restaurant = function() {
    var totalfoodcount = 0;        // Private class property
    var totalrestroomcount  = 0;   // Private class property
    
    var Restaurant = function(name){
        var foodcount = 0;         // Private instance property
        var restroomcount  = 0;    // Private instance property
        
        this.name = name
        
        this.incrementFoodCount = function() {
            foodcount++;
            totalfoodcount++;
            this.printStatus();
        };
        this.incrementRestroomCount = function() {
            restroomcount++;
            totalrestroomcount++;
            this.printStatus();
        };
        this.getRestroomCount = function() {
            return restroomcount;
        },
        this.getFoodCount = function() {
            return foodcount;
        }
    };
   
    Restaurant.prototype = {
        name : '',
        buy_food : function(){
           this.incrementFoodCount();
        },
        use_restroom : function(){
           this.incrementRestroomCount();
        },
        getTotalRestroomCount : function() {
            return totalrestroomcount;
        },
        getTotalFoodCount : function() {
            return totalfoodcount;
        },
        printStatus : function() {
           document.body.innerHTML
               += '<h3>Buying food at '+this.name+'</h3>'
               + '<ul>' 
               + '<li>Restroom count at ' + this.name + ' : '+ this.getRestroomCount() + '</li>'
               + '<li>Food count at ' + this.name + ' : ' + this.getFoodCount() + '</li>'
               + '<li>Total restroom count : '+ this.getTotalRestroomCount() + '</li>'
               + '<li>Total food count : '+ this.getTotalFoodCount() + '</li>'
               + '</ul>';
        }
    };

    return  { // Singleton public properties
        create : function(name) {
            return new Restaurant(name);
        },
        printStatus : function() {
          document.body.innerHTML
              += '<hr />'
              + '<h3>Overview</h3>'
              + '<ul>' 
              + '<li>Total restroom count : '+ Restaurant.prototype.getTotalRestroomCount() + '</li>'
              + '<li>Total food count : '+ Restaurant.prototype.getTotalFoodCount() + '</li>'
              + '</ul>'
              + '<hr />';
        }
    };
}();

var Wendys = Restaurant.create("Wendy's");
var McDonalds = Restaurant.create("McDonald's");
var KFC = Restaurant.create("KFC");
var BurgerKing = Restaurant.create("Burger King");

Restaurant.printStatus();

Wendys.buy_food();
Wendys.use_restroom();
KFC.use_restroom();
KFC.use_restroom();
Wendys.use_restroom();
McDonalds.buy_food();
BurgerKing.buy_food();

Restaurant.printStatus();

BurgerKing.buy_food();
Wendys.use_restroom();
McDonalds.buy_food();
KFC.buy_food();
Wendys.buy_food();
BurgerKing.buy_food();
McDonalds.buy_food();

Restaurant.printStatus();
_x000D_
_x000D_
_x000D_

See also this Fiddle.

Angular 5 Scroll to top on every Route click

If you face this problem in Angular 6, you can fix it by adding the parameter scrollPositionRestoration: 'enabled' to app-routing.module.ts 's RouterModule:

@NgModule({
  imports: [RouterModule.forRoot(routes,{
    scrollPositionRestoration: 'enabled'
  })],
  exports: [RouterModule]
})

WiX tricks and tips

Set the DISABLEADVTSHORTCUTS property to force all advertised shortcuts in your installer to become regular shortcuts, and you don't need to include a dummy reg key to be used as the keypath.

<Property Id="DISABLEADVTSHORTCUTS" Value="1"/>

I think Windows Installer 4.0 or higher is a requirement.

How to remove old Docker containers

To get rid of your stopped container you can use:

docker rm <cointainer_id>

You can also use the name of the container:

docker rm <name>

If you want to get rid of all the stopped containers you can use the:

docker container prune

Or you can also use:

docker rm $(docker ps -aq -f status=exited)

You can use -v argument to delete any docker managed volumes that are not referenced any further

docker rm -v $(docker ps -aq -f status=exited)

You can also use --rm with the docker run. This will delete the container and the associated files when the container exists.

How can I symlink a file in Linux?

ln -s target linkName

You can have a look at the man page here:

http://linux.die.net/man/1/ln

How Can I Set the Default Value of a Timestamp Column to the Current Timestamp with Laravel Migrations?

As additional possibility for future googlers

I find it more useful to have null in the updated_at column when the record is been created but has never been modified. It reduces the db size (ok, just a little) and its possible to see it at the first sight that the data has never been modified.

As of this I use:

$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->default(DB::raw('NULL ON UPDATE CURRENT_TIMESTAMP'))->nullable();

(In Laravel 7 with mysql 8).

How do I get today's date in C# in mm/dd/yyyy format?

Or without the year:

DateTime.Now.ToString("M/dd")

JMS Topic vs Queues

A JMS topic is the type of destination in a 1-to-many model of distribution. The same published message is received by all consuming subscribers. You can also call this the 'broadcast' model. You can think of a topic as the equivalent of a Subject in an Observer design pattern for distributed computing. Some JMS providers efficiently choose to implement this as UDP instead of TCP. For topic's the message delivery is 'fire-and-forget' - if no one listens, the message just disappears. If that's not what you want, you can use 'durable subscriptions'.

A JMS queue is a 1-to-1 destination of messages. The message is received by only one of the consuming receivers (please note: consistently using subscribers for 'topic client's and receivers for queue client's avoids confusion). Messages sent to a queue are stored on disk or memory until someone picks it up or it expires. So queues (and durable subscriptions) need some active storage management, you need to think about slow consumers.

In most environments, I would argue, topics are the better choice because you can always add additional components without having to change the architecture. Added components could be monitoring, logging, analytics, etc. You never know at the beginning of the project what the requirements will be like in 1 year, 5 years, 10 years. Change is inevitable, embrace it :-)

Multiple queries executed in java in single statement

I think this is the easiest way for multy selection/update/insert/delete. You can run as many update/insert/delete as u want after select (you have to make a select first(a dummy if needed)) with executeUpdate(str) (just use new int(count1,count2,...)) and if u need a new selection close 'statement' and 'connection' and make new for next select. Like example:

String str1 = "select * from users";
String str9 = "INSERT INTO `port`(device_id, potition, port_type, di_p_pt) VALUE ('"+value1+"', '"+value2+"', '"+value3+"', '"+value4+"')";
String str2 = "Select port_id from port where device_id = '"+value1+"' and potition = '"+value2+"' and port_type = '"+value3+"' ";
try{  
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    theConnection=(Connection) DriverManager.getConnection(dbURL,dbuser,dbpassword);  
    theStatement = theConnection.prepareStatement(str1);
    ResultSet theResult = theStatement.executeQuery();
    int count8 = theStatement.executeUpdate(str9);
    theStatement.close();
    theConnection.close();
    theConnection=DriverManager.getConnection(dbURL,dbuser,dbpassword);
    theStatement = theConnection.prepareStatement(str2);
    theResult = theStatement.executeQuery();

    ArrayList<Port> portList = new ArrayList<Port>();
    while (theResult.next()) {
        Port port = new Port();
        port.setPort_id(theResult.getInt("port_id"));

        portList.add(port);
    }

I hope it helps

OTP (token) should be automatically read from the message

I will recommend you not to use any third party libraries for auto fetch OTP from SMS Inbox. This can be done easily if you have basic understanding of Broadcast Receiver and how it works. Just Try following approach :

Step 1) Create single interface i.e SmsListner

package com.wnrcorp.reba;
public interface SmsListener{
public void messageReceived(String messageText);}

Step 2) Create single Broadcast Receiver i.e SmsReceiver

package com.wnrcorp.reba;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
public class SmsReceiver extends BroadcastReceiver {
private static SmsListener mListener;
Boolean b;
String abcd,xyz;
@Override
public void onReceive(Context context, Intent intent) {
Bundle data  = intent.getExtras();
Object[] pdus = (Object[]) data.get("pdus");
    for(int i=0;i<pdus.length;i++){
        SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
        String sender = smsMessage.getDisplayOriginatingAddress();
       // b=sender.endsWith("WNRCRP");  //Just to fetch otp sent from WNRCRP
        String messageBody = smsMessage.getMessageBody();
       abcd=messageBody.replaceAll("[^0-9]","");   // here abcd contains otp 
        which is in number format
        //Pass on the text to our listener.
        if(b==true) {
            mListener.messageReceived(abcd);  // attach value to interface 
  object
        }
        else
        {
        }
    }
}
public static void bindListener(SmsListener listener) {
    mListener = listener;
}
}

Step 3) Add Listener i.e broadcast receiver in android manifest file

<receiver android:name=".SmsReceiver">    
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
        </intent-filter>
</receiver>

and add permission

<uses-permission android:name="android.permission.RECEIVE_SMS"/>

Final Step 4) The activity where you going to auto fetch otp when it is received in inbox. In my case I'm fetching otp and setting on edittext field.

public class OtpVerificationActivity extends AppCompatActivity {
EditText ed;
TextView tv;
String otp_generated,contactNo,id1;
GlobalData gd = new GlobalData();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_otp_verification);
    ed=(EditText)findViewById(R.id.otp);
    tv=(TextView) findViewById(R.id.verify_otp); 
    /*This is important because this will be called every time you receive 
     any sms */            
 SmsReceiver.bindListener(new SmsListener() {
        @Override
        public void messageReceived(String messageText) {
            ed.setText(messageText);     
        }
    });
    tv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try
            {
                InputMethodManager imm=
  (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);                    
  imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),0);
            }
            catch(Exception e)
            {}           
            if (ed.getText().toString().equals(otp_generated))
            {
                Toast.makeText(OtpVerificationActivity.this, "OTP Verified 
       Successfully !", Toast.LENGTH_SHORT).show();           
             }
    });
   }
}

Layout File for OtpVerificationActivity

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_otp_verification"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.wnrcorp.reba.OtpVerificationActivity">
<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/firstcard"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    card_view:cardCornerRadius="10dp"
    >
   <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="@android:color/white">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="OTP Confirmation"
            android:textSize="18sp"
            android:textStyle="bold"
            android:id="@+id/dialogTitle"
            android:layout_margin="5dp"
            android:layout_gravity="center"
            />
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/otp"
            android:layout_margin="5dp"
            android:hint="OTP Here"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Verify"
            android:textSize="18sp"
            android:id="@+id/verify_otp"
            android:gravity="center"
            android:padding="10dp"
            android:layout_gravity="center"
            android:visibility="visible"
            android:layout_margin="5dp"
            android:background="@color/colorPrimary"
            android:textColor="#ffffff"
            />
        </LinearLayout>
        </android.support.v7.widget.CardView>
        </RelativeLayout>

Screenshots for OTP Verification Activity where you fetch OTP as soons as messages received enter image description here

jquery ajax function not working

I am doing a code like this

_x000D_
_x000D_
<!-- Optional JavaScript -->_x000D_
<!-- jQuery first, then Popper.js, then Bootstrap JS -->_x000D_
<script_x000D_
    src="http://code.jquery.com/jquery-3.3.1.min.js"_x000D_
    integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="_x000D_
    crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>_x000D_
<script>_x000D_
    $(document).ready(function () {_x000D_
_x000D_
        $(".work-category a").click(function (e) {_x000D_
            e.preventDefault();_x000D_
            var id = $(this).attr('data-id');_x000D_
            $.ajax({_x000D_
                url: 'process.php',_x000D_
                method: 'POST',_x000D_
                data: {_x000D_
                    clickCategoryID : id_x000D_
                },_x000D_
                dataType: 'JSON',_x000D_
                success: function (data) {_x000D_
                    $("#content-area").html(data.Content);_x000D_
                    $(".container-area").animate({top: '100px'}, 1000);_x000D_
                    $(".single-content").animate({opacity:1}, 1000);_x000D_
                }_x000D_
            });_x000D_
        });_x000D_
_x000D_
    });_x000D_
</script>
_x000D_
_x000D_
_x000D_

But the code is not running and the console saya process.php not found though I have the code on it.

Curl not recognized as an internal or external command, operable program or batch file

Steps to install curl in windows

Install cURL on Windows

There are 4 steps to follow to get cURL installed on Windows.

Step 1 and Step 2 is to install SSL library. Step 3 is to install cURL. Step 4 is to install a recent certificate

Step One: Install Visual C++ 2008 Redistributables

From https://www.microsoft.com/en-za/download/details.aspx?id=29 For 64bit systems Visual C++ 2008 Redistributables (x64) For 32bit systems Visual C++ 2008 Redistributables (x32)

Step Two: Install Win(32/64) OpenSSL v1.0.0k Light

From http://www.shininglightpro.com/products/Win32OpenSSL.html For 64bit systems Win64 OpenSSL v1.0.0k Light For 32bit systems Win32 OpenSSL v1.0.0k Light

Step Three: Install cURL

Depending on if your system is 32 or 64 bit, download the corresponding** curl.exe.** For example, go to the Win64 - Generic section and download the Win64 binary with SSL support (the one where SSL is not crossed out). Visit http://curl.haxx.se/download.html

Copy curl.exe to C:\Windows\System32

Step Four: Install Recent Certificates

Do not skip this step. Download a recent copy of valid CERT files from https://curl.haxx.se/ca/cacert.pem Copy it to the same folder as you placed curl.exe (C:\Windows\System32) and rename it as curl-ca-bundle.crt

If you have already installed curl or after doing the above steps, add the directory where it's installed to the windows path:

1 - From the Desktop, right-click My Computer and click Properties.
2 - Click Advanced System Settings .
3 - In the System Properties window click the Environment Variables button.
4 - Select Path and click Edit.
5 - Append ;c:\path to curl directory at the end.
5 - Click OK.
6 - Close and re-open the command prompt

CSS3 opacity gradient?

I think the "messy" second method, which is linked from another question here may be the only pure CSS solution.

If you're thinking about using JavaScript, then this was my solution to the problem:

demo: using a canvas element to fade text against an animated background

The idea is that your element with the text and the canvas element are one on top of the other. You keep the text in your element (in order to allow text selection, which isn't possible with canvas text), but make it completely transparent (with rgba(0,0,0,0), in order to have the text visible in IE8 and older - that's because you have no RGBa support and no canvas support in IE8 and older).

You then read the text inside your element and write it on the canvas with the same font properties so that each letter you write on the canvas is over the corresponding letter in the element with the text.

The canvas element does not support multi-line text, so you'll have to break the text into words and then keep adding words on a test line which you then measure. If the width taken by the test line is bigger than the maximum allowed width you can have for a line (you get that maximum allowed width by reading the computed width of the element with the text), then you write it on the canvas without the last word added, you reset the test line to be that last word, and you increase the y coordinate at which to write the next line by one line height (which you also get from the computed styles of your element with the text). With each line that you write, you also decrease the opacity of the text with an appropriate step (this step being inversely proportional to the average number of characters per line).

What you cannot do easily in this case is to justify text. It can be done, but it gets a bit more complicated, meaning that you would have to compute how wide should each step be and write the text word by word rather than line by line.

Also, keep in mind that if your text container changes width as you resize the window, then you'll have to clear the canvas and redraw the text on it on each resize.

OK, the code:

HTML:

<article>
  <h1>Interacting Spiral Galaxies NGC 2207/ IC 2163</h1>
  <em class='timestamp'>February 4, 2004 09:00 AM</em>
  <section class='article-content' id='art-cntnt'>
    <canvas id='c' class='c'></canvas>In the direction of <!--and so on-->  
  </section>
</article>

CSS:

html {
  background: url(moving.jpg) 0 0;
  background-size: 200%;
  font: 100%/1.3 Verdana, sans-serif;
  animation: ani 4s infinite linear;
}
article {
  width: 50em; /* tweak this ;) */
  padding: .5em;
  margin: 0 auto;
}
.article-content {
  position: relative;
  color: rgba(0,0,0,0);
  /* add slash at the end to check they superimpose *
  color: rgba(255,0,0,.5);/**/
}
.c {
  position: absolute;
  z-index: -1;
  top: 0; left: 0;
}
@keyframes ani { to { background-position: 100% 0; } }

JavaScript:

var wrapText = function(ctxt, s, x, y, maxWidth, lineHeight) {
  var words = s.split(' '), line = '', 
      testLine, metrics, testWidth, alpha = 1, 
      step = .8*maxWidth/ctxt.measureText(s).width;

  for(var n = 0; n < words.length; n++) {
    testLine = line + words[n] + ' ';
    metrics = ctxt.measureText(testLine);
    testWidth = metrics.width;
    if(testWidth > maxWidth) {
      ctxt.fillStyle = 'rgba(0,0,0,'+alpha+')';
      alpha  -= step;
      ctxt.fillText(line, x, y);
      line = words[n] + ' ';
      y += lineHeight;
    }
    else line = testLine;
  }
  ctxt.fillStyle = 'rgba(0,0,0,'+alpha+')';
  alpha  -= step;
  ctxt.fillText(line, x, y);
  return y + lineHeight;
}

window.onload = function() {
  var c = document.getElementById('c'), 
      ac = document.getElementById('art-cntnt'), 
      /* use currentStyle for IE9 */
      styles = window.getComputedStyle(ac),
      ctxt = c.getContext('2d'), 
      w = parseInt(styles.width.split('px')[0], 10),
      h = parseInt(styles.height.split('px')[0], 10),
      maxWidth = w, 
      lineHeight = parseInt(styles.lineHeight.split('px')[0], 10), 
      x = 0, 
      y = parseInt(styles.fontSize.split('px')[0], 10), 
      text = ac.innerHTML.split('</canvas>')[1];

  c.width = w;
  c.height = h;
  ctxt.font = '1em Verdana, sans-serif';
  wrapText(ctxt, text, x, y, maxWidth, lineHeight);
};

Error: could not find function ... in R

This error can occur even if the name of the function is valid if some mandatory arguments are missing (i.e you did not provide enough arguments).
I got this in an Rcpp context, where I wrote a C++ function with optionnal arguments, and did not provided those arguments in R. It appeared that optionnal arguments from the C++ were seen as mandatory by R. As a result, R could not find a matching function for the correct name but an incorrect number of arguments.

Rcpp Function : SEXP RcppFunction(arg1, arg2=0) {}
R Calls :
RcppFunction(0) raises the error
RcppFunction(0, 0) does not

Entity Framework change connection at runtime

The created class is 'partial'!

public partial class Database1Entities1 : DbContext
{
    public Database1Entities1()
        : base("name=Database1Entities1")
    {
    }

... and you call it like this:

using (var ctx = new Database1Entities1())
      {
        #if DEBUG
        ctx.Database.Log = Console.Write;
        #endif

so, you need only create a partial own class file for original auto-generated class (with same class name!) and add a new constructor with connection string parameter, like Moho's answer before.

After it you able to use parametrized constructor against original. :-)

example:

using (var ctx = new Database1Entities1(myOwnConnectionString))
      {
        #if DEBUG
        ctx.Database.Log = Console.Write;
        #endif

How to get everything after last slash in a URL?

First extract the path element from the URL:

from urllib.parse import urlparse
parsed= urlparse('https://www.dummy.example/this/is/PATH?q=/a/b&r=5#asx')

and then you can extract the last segment with string functions:

parsed.path.rpartition('/')[2]

(example resulting to 'PATH')

How to display an activity indicator with text on iOS 8 with Swift?

For activity indicator, its better you create one custom class.

Instead of creating UIActivityIndicator in each UIViewController.Subclass UIView and use from any UIViewController.

Updated for Swift 5.0:

import UIKit
import Foundation
class ProgressIndicator: UIView {

var indicatorColor:UIColor
var loadingViewColor:UIColor
var loadingMessage:String
var messageFrame = UIView()
var activityIndicator = UIActivityIndicatorView()

init(inview:UIView,loadingViewColor:UIColor,indicatorColor:UIColor,msg:String){

    self.indicatorColor = indicatorColor
    self.loadingViewColor = loadingViewColor
    self.loadingMessage = msg
    super.init(frame: CGRect(x: inview.frame.midX - 90, y: inview.frame.midY - 250 , width: 180, height: 50))
    initalizeCustomIndicator()

}
convenience init(inview:UIView) {

    self.init(inview: inview,loadingViewColor: UIColor.brown,indicatorColor:UIColor.black, msg: "Loading..")
}
convenience init(inview:UIView,messsage:String) {

    self.init(inview: inview,loadingViewColor: UIColor.brown,indicatorColor:UIColor.black, msg: messsage)
}

required init?(coder aDecoder: NSCoder) {

    fatalError("init(coder:) has not been implemented")
}

func initalizeCustomIndicator(){

    messageFrame.frame = self.bounds
    activityIndicator = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.medium)
    activityIndicator.tintColor = indicatorColor
    activityIndicator.hidesWhenStopped = true
    activityIndicator.frame = CGRect(x: self.bounds.origin.x + 6, y: 0, width: 20, height: 50)
    print(activityIndicator.frame)
    let strLabel = UILabel(frame:CGRect(x: self.bounds.origin.x + 30, y: 0, width: self.bounds.width - (self.bounds.origin.x + 30) , height: 50))
    strLabel.text = loadingMessage
    strLabel.adjustsFontSizeToFitWidth = true
    strLabel.textColor = UIColor.white
    messageFrame.layer.cornerRadius = 15
    messageFrame.backgroundColor = loadingViewColor
    messageFrame.alpha = 0.8
    messageFrame.addSubview(activityIndicator)
    messageFrame.addSubview(strLabel)


}

func  start(){
    //check if view is already there or not..if again started
    if !self.subviews.contains(messageFrame){

        activityIndicator.startAnimating()
        self.addSubview(messageFrame)

    }
}

func stop(){

    if self.subviews.contains(messageFrame){

        activityIndicator.stopAnimating()
        messageFrame.removeFromSuperview()

    }
}
}

Put this class in your project and then call from any ViewController as

var indicator:ProgressIndicator?
override func viewDidLoad() {
    super.viewDidLoad()

    //indicator = ProgressIndicator(inview: self.view,messsage: "Hello from Nepal..")
    //self.view.addSubview(indicator!)
    //OR
    indicator = ProgressIndicator(inview:self.view,loadingViewColor: UIColor.grayColor(), indicatorColor: UIColor.blackColor(), msg: "Landing within minutes,Please hold tight..")
    self.view.addSubview(indicator!)

}

@IBAction func startBtn(sender: AnyObject) {
    indicator!.start()
}


@IBAction func stopBtn(sender: AnyObject) {
    indicator!.stop()
}

select the TOP N rows from a table

In MySql, you can get 10 rows starting from row 20 using:

SELECT * FROM Reflow  
WHERE ReflowProcessID = somenumber
ORDER BY ID DESC
LIMIT 10 OFFSET 20 --Equivalent to LIMIT 20, 10

How to use Angular4 to set focus by element id

This helped to me (in ionic, but idea is the same) https://mhartington.io/post/setting-input-focus/

in template:

<ion-item>
      <ion-label>Home</ion-label>
      <ion-input #input type="text"></ion-input>
</ion-item>
<button (click)="focusInput(input)">Focus</button>

in controller:

  focusInput(input) {
    input.setFocus();
  }

How do I edit $PATH (.bash_profile) on OSX?

Simplest answer is:

Step 1: Fire up Terminal.app

Step 2: Type nano .bash_profile – This command will open the .bash_profile document (or create it if it doesn’t already exist) in the easiest to use text editor in Terminal – Nano.

Step 3: Now you can make a simple change to the file. Paste these lines of code to change your Terminal prompt.

export PS1="___________________ | \w @ \h (\u) \n| => "

export PS2="| => "

Step 4: Now save your changes by typing ctrl +o Hit return to save. Then exit Nano by typing ctrl+x

Step 5: Now we need to *activate your changes. Type source .bash_profile and watch your prompt change.

That's it! Enjoy!

Center a position:fixed element

This one worked the best for me:

    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;

How to make HTML Text unselectable

You can't do this with plain vanilla HTML, so JSF can't do much for you here as well.

If you're targeting decent browsers only, then just make use of CSS3:

.unselectable {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
<label class="unselectable">Unselectable label</label>

If you'd like to cover older browsers as well, then consider this JavaScript fallback:

<!doctype html>
<html lang="en">
    <head>
        <title>SO question 2310734</title>
        <script>
            window.onload = function() {
                var labels = document.getElementsByTagName('label');
                for (var i = 0; i < labels.length; i++) {
                    disableSelection(labels[i]);
                }
            };
            function disableSelection(element) {
                if (typeof element.onselectstart != 'undefined') {
                    element.onselectstart = function() { return false; };
                } else if (typeof element.style.MozUserSelect != 'undefined') {
                    element.style.MozUserSelect = 'none';
                } else {
                    element.onmousedown = function() { return false; };
                }
            }
        </script>
    </head>
    <body>
        <label>Try to select this</label>
    </body>
</html>

If you're already using jQuery, then here's another example which adds a new function disableSelection() to jQuery so that you can use it anywhere in your jQuery code:

<!doctype html>
<html lang="en">
    <head>
        <title>SO question 2310734 with jQuery</title>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script>
            $.fn.extend({ 
                disableSelection: function() { 
                    this.each(function() { 
                        if (typeof this.onselectstart != 'undefined') {
                            this.onselectstart = function() { return false; };
                        } else if (typeof this.style.MozUserSelect != 'undefined') {
                            this.style.MozUserSelect = 'none';
                        } else {
                            this.onmousedown = function() { return false; };
                        }
                    }); 
                } 
            });

            $(document).ready(function() {
                $('label').disableSelection();            
            });
        </script>
    </head>
    <body>
        <label>Try to select this</label>
    </body>
</html>

How to convert a string variable containing time to time_t type in c++?

This should work:

int hh, mm, ss;
struct tm when = {0};

sscanf_s(date, "%d:%d:%d", &hh, &mm, &ss);


when.tm_hour = hh;
when.tm_min = mm;
when.tm_sec = ss;

time_t converted;
converted = mktime(&when);

Modify as needed.

Create two blank lines in Markdown

You can use the sequence of a no-break space (U+00a0) followed by two spaces (U+0020×2) followed by a newline (U+000a) repeatedly to achieve this. Two or more times is required depending on your use case.

Using (not markdown interpreted here, but) actual white space characters (theoretically copy-and-paste-able):

Preceding
   
   
   
Following.

How can I increase the JVM memory?

If you are using Eclipse then you can do this by specifying the required size for the particular application in its Run Configuration's VM Arguments as EX: -Xms128m -Xmx512m

Or if you want all applications running from your eclipse to have the same specified size then you can specify this in the eclipse.ini file which is present in your Eclipse home directory.

To get the size of the JVM during Runtime you can use Runtime.totalMemory() which returns the total amount of memory in the Java virtual machine, measured in bytes.

Application Crashes With "Internal Error In The .NET Runtime"

For those arriving here from google, I've eventually come across this SO question, and this specific answer solved my problem. I've contacted Microsoft for the hotfix through the live chat on support.microsoft.com and they sent me a link to the hotfix by email.

A select query selecting a select statement

I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:

SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;

Thanks for answering, it helped my train of thought.

Why can't I initialize non-const static member or static array in class?

Why I can't initialize static data members in class?

The C++ standard allows only static constant integral or enumeration types to be initialized inside the class. This is the reason a is allowed to be initialized while others are not.

Reference:
C++03 9.4.2 Static data members
§4

If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.

What are integral types?

C++03 3.9.1 Fundamental types
§7

Types bool, char, wchar_t, and the signed and unsigned integer types are collectively called integral types.43) A synonym for integral type is integer type.

Footnote:

43) Therefore, enumerations (7.2) are not integral; however, enumerations can be promoted to int, unsigned int, long, or unsigned long, as specified in 4.5.

Workaround:

You could use the enum trick to initialize an array inside your class definition.

class A 
{
    static const int a = 3;
    enum { arrsize = 2 };

    static const int c[arrsize] = { 1, 2 };

};

Why does the Standard does not allow this?

Bjarne explains this aptly here:

A class is typically declared in a header file and a header file is typically included into many translation units. However, to avoid complicated linker rules, C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects.

Why are only static const integral types & enums allowed In-class Initialization?

The answer is hidden in Bjarne's quote read it closely,
"C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects."

Note that only static const integers can be treated as compile time constants. The compiler knows that the integer value will not change anytime and hence it can apply its own magic and apply optimizations, the compiler simply inlines such class members i.e, they are not stored in memory anymore, As the need of being stored in memory is removed, it gives such variables the exception to rule mentioned by Bjarne.

It is noteworthy to note here that even if static const integral values can have In-Class Initialization, taking address of such variables is not allowed. One can take the address of a static member if (and only if) it has an out-of-class definition.This further validates the reasoning above.

enums are allowed this because values of an enumerated type can be used where ints are expected.see citation above


How does this change in C++11?

C++11 relaxes the restriction to certain extent.

C++11 9.4.2 Static data members
§3

If a static data member is of const literal type, its declaration in the class definition can specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. A static data member of literal type can be declared in the class definition with the constexpr specifier; if so, its declaration shall specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. [ Note: In both these cases, the member may appear in constant expressions. —end note ] The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.

Also, C++11 will allow(§12.6.2.8) a non-static data member to be initialized where it is declared(in its class). This will mean much easy user semantics.

Note that these features have not yet been implemented in latest gcc 4.7, So you might still get compilation errors.

Creating a "Hello World" WebSocket example

WebSockets is protocol that relies on TCP streamed connection. Although WebSockets is Message based protocol.

If you want to implement your own protocol then I recommend to use latest and stable specification (for 18/04/12) RFC 6455. This specification contains all necessary information regarding handshake and framing. As well most of description on scenarios of behaving from browser side as well as from server side. It is highly recommended to follow what recommendations tells regarding server side during implementing of your code.

In few words, I would describe working with WebSockets like this:

  1. Create server Socket (System.Net.Sockets) bind it to specific port, and keep listening with asynchronous accepting of connections. Something like that:

    Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
    serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8080));
    serverSocket.Listen(128);
    serverSocket.BeginAccept(null, 0, OnAccept, null);
  2. You should have accepting function "OnAccept" that will implement handshake. In future it has to be in another thread if system is meant to handle huge amount of connections per second.

    private void OnAccept(IAsyncResult result) {
    try {
        Socket client = null;
        if (serverSocket != null && serverSocket.IsBound) {
            client = serverSocket.EndAccept(result);
        }
        if (client != null) {
            /* Handshaking and managing ClientSocket */
        }
    } catch(SocketException exception) {
    
    } finally {
        if (serverSocket != null && serverSocket.IsBound) {
            serverSocket.BeginAccept(null, 0, OnAccept, null);
        }
    }
    }
  3. After connection established, you have to do handshake. Based on specification 1.3 Opening Handshake, after connection established you will receive basic HTTP request with some information. Example:

    GET /chat HTTP/1.1
    Host: server.example.com
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
    Origin: http://example.com
    Sec-WebSocket-Protocol: chat, superchat
    Sec-WebSocket-Version: 13

    This example is based on version of protocol 13. Bear in mind that older versions have some differences but mostly latest versions are cross-compatible. Different browsers may send you some additional data. For example Browser and OS details, cache and others.

    Based on provided handshake details, you have to generate answer lines, they are mostly same, but will contain Accpet-Key, that is based on provided Sec-WebSocket-Key. In specification 1.3 it is described clearly how to generate response key. Here is my function I've been using for V13:

    static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
    private string AcceptKey(ref string key) {
        string longKey = key + guid;
        SHA1 sha1 = SHA1CryptoServiceProvider.Create();
        byte[] hashBytes = sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(longKey));
        return Convert.ToBase64String(hashBytes);
    }
    

    Handshake answer looks like that:

    HTTP/1.1 101 Switching Protocols
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

    But accept key have to be the generated one based on provided key from client and method AcceptKey I provided before. As well, make sure after last character of accept key you put two new lines "\r\n\r\n".

  4. After handshake answer is sent from server, client should trigger "onopen" function, that means you can send messages after.
  5. Messages are not sent in raw format, but they have Data Framing. And from client to server as well implement masking for data based on provided 4 bytes in message header. Although from server to client you don't need to apply masking over data. Read section 5. Data Framing in specification. Here is copy-paste from my own implementation. It is not ready-to-use code, and have to be modified, I am posting it just to give an idea and overall logic of read/write with WebSocket framing. Go to this link.
  6. After framing is implemented, make sure that you receive data right way using sockets. For example to prevent that some messages get merged into one, because TCP is still stream based protocol. That means you have to read ONLY specific amount of bytes. Length of message is always based on header and provided data length details in header it self. So when you receiving data from Socket, first receive 2 bytes, get details from header based on Framing specification, then if mask provided another 4 bytes, and then length that might be 1, 4 or 8 bytes based on length of data. And after data it self. After you read it, apply demasking and your message data is ready to use.
  7. You might want to use some Data Protocol, I recommend to use JSON due traffic economy and easy to use on client side in JavaScript. For server side you might want to check some of parsers. There is lots of them, google can be really helpful.

Implementing own WebSockets protocol definitely have some benefits and great experience you get as well as control over protocol it self. But you have to spend some time doing it, and make sure that implementation is highly reliable.

In same time you might have a look in ready to use solutions that google (again) have enough.

jQuery Validate - Enable validation for hidden fields

The plugin's author says you should use "square brackets without the quotes", []

http://bassistance.de/2011/10/07/release-validation-plugin-1-9-0/

Release: Validation Plugin 1.9.0: "...Another change should make the setup of forms with hidden elements easier, these are now ignored by default (option “ignore” has “:hidden” now as default). In theory, this could break an existing setup. In the unlikely case that it actually does, you can fix it by setting the ignore-option to “[]” (square brackets without the quotes)."

To change this setting for all forms:

$.validator.setDefaults({ 
    ignore: [],
    // any other default options and/or rules
});

(It is not required that .setDefaults() be within the document.ready function)

OR for one specific form:

$(document).ready(function() {

    $('#myform').validate({
        ignore: [],
        // any other options and/or rules
    });

});

EDIT:

See this answer for how to enable validation on some hidden fields but still ignore others.


EDIT 2:

Before leaving comments that "this does not work", keep in mind that the OP is simply asking about the jQuery Validate plugin and his question has nothing to do with how ASP.NET, MVC, or any other Microsoft framework can alter this plugin's normal expected behavior. If you're using a Microsoft framework, the default functioning of the jQuery Validate plugin is over-written by Microsoft's unobtrusive-validation plugin.

If you're struggling with the unobtrusive-validation plugin, then please refer to this answer instead: https://stackoverflow.com/a/11053251/594235

How do function pointers in C work?

Function pointers in C can be used to perform object-oriented programming in C.

For example, the following lines is written in C:

String s1 = newString();
s1->set(s1, "hello");

Yes, the -> and the lack of a new operator is a dead give away, but it sure seems to imply that we're setting the text of some String class to be "hello".

By using function pointers, it is possible to emulate methods in C.

How is this accomplished?

The String class is actually a struct with a bunch of function pointers which act as a way to simulate methods. The following is a partial declaration of the String class:

typedef struct String_Struct* String;

struct String_Struct
{
    char* (*get)(const void* self);
    void (*set)(const void* self, char* value);
    int (*length)(const void* self);
};

char* getString(const void* self);
void setString(const void* self, char* value);
int lengthString(const void* self);

String newString();

As can be seen, the methods of the String class are actually function pointers to the declared function. In preparing the instance of the String, the newString function is called in order to set up the function pointers to their respective functions:

String newString()
{
    String self = (String)malloc(sizeof(struct String_Struct));

    self->get = &getString;
    self->set = &setString;
    self->length = &lengthString;

    self->set(self, "");

    return self;
}

For example, the getString function that is called by invoking the get method is defined as the following:

char* getString(const void* self_obj)
{
    return ((String)self_obj)->internal->value;
}

One thing that can be noticed is that there is no concept of an instance of an object and having methods that are actually a part of an object, so a "self object" must be passed in on each invocation. (And the internal is just a hidden struct which was omitted from the code listing earlier -- it is a way of performing information hiding, but that is not relevant to function pointers.)

So, rather than being able to do s1->set("hello");, one must pass in the object to perform the action on s1->set(s1, "hello").

With that minor explanation having to pass in a reference to yourself out of the way, we'll move to the next part, which is inheritance in C.

Let's say we want to make a subclass of String, say an ImmutableString. In order to make the string immutable, the set method will not be accessible, while maintaining access to get and length, and force the "constructor" to accept a char*:

typedef struct ImmutableString_Struct* ImmutableString;

struct ImmutableString_Struct
{
    String base;

    char* (*get)(const void* self);
    int (*length)(const void* self);
};

ImmutableString newImmutableString(const char* value);

Basically, for all subclasses, the available methods are once again function pointers. This time, the declaration for the set method is not present, therefore, it cannot be called in a ImmutableString.

As for the implementation of the ImmutableString, the only relevant code is the "constructor" function, the newImmutableString:

ImmutableString newImmutableString(const char* value)
{
    ImmutableString self = (ImmutableString)malloc(sizeof(struct ImmutableString_Struct));

    self->base = newString();

    self->get = self->base->get;
    self->length = self->base->length;

    self->base->set(self->base, (char*)value);

    return self;
}

In instantiating the ImmutableString, the function pointers to the get and length methods actually refer to the String.get and String.length method, by going through the base variable which is an internally stored String object.

The use of a function pointer can achieve inheritance of a method from a superclass.

We can further continue to polymorphism in C.

If for example we wanted to change the behavior of the length method to return 0 all the time in the ImmutableString class for some reason, all that would have to be done is to:

  1. Add a function that is going to serve as the overriding length method.
  2. Go to the "constructor" and set the function pointer to the overriding length method.

Adding an overriding length method in ImmutableString may be performed by adding an lengthOverrideMethod:

int lengthOverrideMethod(const void* self)
{
    return 0;
}

Then, the function pointer for the length method in the constructor is hooked up to the lengthOverrideMethod:

ImmutableString newImmutableString(const char* value)
{
    ImmutableString self = (ImmutableString)malloc(sizeof(struct ImmutableString_Struct));

    self->base = newString();

    self->get = self->base->get;
    self->length = &lengthOverrideMethod;

    self->base->set(self->base, (char*)value);

    return self;
}

Now, rather than having an identical behavior for the length method in ImmutableString class as the String class, now the length method will refer to the behavior defined in the lengthOverrideMethod function.

I must add a disclaimer that I am still learning how to write with an object-oriented programming style in C, so there probably are points that I didn't explain well, or may just be off mark in terms of how best to implement OOP in C. But my purpose was to try to illustrate one of many uses of function pointers.

For more information on how to perform object-oriented programming in C, please refer to the following questions:

The 'json' native gem requires installed build tools

I would like to add that you should make sure that the generated config.yml file when doing ruby dk.rb init contains the path to the ruby installation you want to use DevKit with. In my case, I had the Heroku Toolbelt installed on my system, which provided its own ruby installation, located at a different place. The config.yml file used that particular installation, and that's not what I wanted. I had to manually edit the file to point it to the correct one, then continue with ruby dk.rb review, etc.

TypeError: $(...).on is not a function

If you are using old version of jQuery(< 1.7) then you can use "bind" instead of "on". This will only work in case you are using old version, since as of jQuery 3.0, "bind" has been deprecated.

Adding a 'share by email' link to website

Something like this might be the easiest way.

<a href="mailto:?subject=I wanted you to see this site&amp;body=Check out this site http://www.website.com."
   title="Share by Email">
  <img src="http://png-2.findicons.com/files/icons/573/must_have/48/mail.png">
</a>

You could find another email image and add that if you wanted.

Git: Cannot see new remote branch

Let's say we are searching for release/1.0.5

When git fetch -all is not working and that you cannot see the remote branch and git branch -r not show this specific branch.

1. Print all refs from remote (branches, tags, ...):

git ls-remote origin Should show you remote branch you are searching for.

e51c80fc0e03abeb2379327d85ceca3ca7bc3ee5        refs/heads/fix/PROJECT-352
179b545ac9dab49f85cecb5aca0d85cec8fb152d        refs/heads/fix/PROJECT-5
e850a29846ee1ecc9561f7717205c5f2d78a992b        refs/heads/master
ab4539faa42777bf98fb8785cec654f46f858d2a        refs/heads/release/1.0.5
dee135fb65685cec287c99b9d195d92441a60c2d        refs/heads/release/1.0.4
36e385cec9b639560d1d8b093034ed16a402c855        refs/heads/release/1.0
d80c1a52012985cec2f191a660341d8b7dd91deb        refs/tags/v1.0

The new branch 'release/1.0.5' appears in the output.

2. Force fetching a remote branch:

git fetch origin <name_branch>:<name_branch>

$ git fetch origin release/1.0.5:release/1.0.5

remote: Enumerating objects: 385, done.
remote: Counting objects: 100% (313/313), done.
remote: Compressing objects: 100% (160/160), done.

Receiving objects: 100% (231/231), 21.02 KiB | 1.05 MiB/s, done.
Resolving deltas: 100% (98/98), completed with 42 local objects.
From http://git.repo:8080/projects/projectX
 * [new branch]        release/1.0.5 -> release/1.0.5

Now you have also the refs locally, you checkout (or whatever) this branch.

Job done!

Chart.js - Formatting Y axis

Chart.js 2.X.X

I know this post is old. But if anyone is looking for more flexible solution, here it is

var options = {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true,
                    callback: function(label, index, labels) {
                        return Intl.NumberFormat().format(label);
                        // 1,350

                        return Intl.NumberFormat('hi', { 
                            style: 'currency', currency: 'INR', minimumFractionDigits: 0, 
                        }).format(label).replace(/^(\D+)/, '$1 ');
                        // ? 1,350

                        // return Intl.NumberFormat('hi', {
                            style: 'currency', currency: 'INR', currencyDisplay: 'symbol', minimumFractionDigits: 2 
                        }).format(label).replace(/^(\D+)/, '$1 ');
                        // ? 1,350.00
                    }
                }
            }]
        }
    }

'hi' is Hindi. Check here for other locales argument
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation#locales_argument

for more currency symbol
https://www.currency-iso.org/en/home/tables/table-a1.html

Insert a background image in CSS (Twitter Bootstrap)

The problem can also be the ordering of your style sheet imports. I had to move my custom style sheet import below the bootstrap import.

How to get all the AD groups for a particular user?

Use tokenGroups:

DirectorySearcher ds = new DirectorySearcher();
ds.Filter = String.Format("(&(objectClass=user)(sAMAccountName={0}))", username);
SearchResult sr = ds.FindOne();

DirectoryEntry user = sr.GetDirectoryEntry();
user.RefreshCache(new string[] { "tokenGroups" });

for (int i = 0; i < user.Properties["tokenGroups"].Count; i++) {
    SecurityIdentifier sid = new SecurityIdentifier((byte[]) user.Properties["tokenGroups"][i], 0);
    NTAccount nt = (NTAccount)sid.Translate(typeof(NTAccount));
    //do something with the SID or name (nt.Value)
}

Note: this only gets security groups

Convert JSON to Map

import net.sf.json.JSONObject

JSONObject.fromObject(yourJsonString).toMap

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

I would solve it using Extension methods, Math.Pow function and Enums:

public static class MyExtension
{
    public enum SizeUnits
    {
        Byte, KB, MB, GB, TB, PB, EB, ZB, YB
    }

    public static string ToSize(this Int64 value, SizeUnits unit)
    {
        return (value / (double)Math.Pow(1024, (Int64)unit)).ToString("0.00");
    }
}

and use it like:

string h = x.ToSize(MyExtension.SizeUnits.KB);

Bash script to check running process

#!/bin/bash
ps axho comm| grep $1 > /dev/null
result=$?
echo "exit code: ${result}"
if [ "${result}" -eq "0" ] ; then
echo "`date`: $SERVICE service running, everything is fine"
else
echo "`date`: $SERVICE is not running"
/etc/init.d/$1 restart
fi

Something like this

How to dynamically build a JSON object with Python?

  • json.loads take a string as input and returns a dictionary as output.
  • json.dumps take a dictionary as input and returns a string as output.

If you need to convert JSON data into a python object, it can do so with Python3, in one line without additional installations, using SimpleNamespace and object_hook:

from string

import json
from types import SimpleNamespace

string = '{"foo":3, "bar":{"x":1, "y":2}}'

# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(string, object_hook=lambda d: SimpleNamespace(**d))

print(x.foo)
print(x.bar.x)
print(x.bar.y)

output:

3
1
2

from file:

JSON object: data.json

{
    "foo": 3,
    "bar": {
        "x": 1,
        "y": 2
    }
}
import json
from types import SimpleNamespace

with open("data.json") as fh:
    string = fh.read()

# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(string, object_hook=lambda d: SimpleNamespace(**d))

print(x.foo)
print(x.bar.x)
print(x.bar.y)

output:

3
1
2

from requests

import json
from types import SimpleNamespace
import requests

r = requests.get('https://api.github.com/users/MilovanTomasevic')

# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(r.text, object_hook=lambda d: SimpleNamespace(**d))

print(x.name)
print(x.company)
print(x.blog)

output:

Milovan Tomaševic
NLB
milovantomasevic.com

For more beautiful and faster access to JSON response from API, take a look at this response.

socket.emit() vs. socket.send()

In basic two way communication systems, socket.emit has proved to be more convincing and easy to use (personal experience) and is a part of Socket.IO which is primarily built for such purposes

is there any PHP function for open page in new tab

This is a trick,

function OpenInNewTab(url) {

  var win = window.open(url, '_blank');
  win.focus();
}

In most cases, this should happen directly in the onclick handler for the link to prevent pop-up blockers, and the default "new window" behavior. You could do it this way, or by adding an event listener to your DOM object.

<div onclick="OpenInNewTab();">Something To Click On</div>

Foreach with JSONArray and JSONObject

Seems like you can't iterate through JSONArray with a for each. You can loop through your JSONArray like this:

for (int i=0; i < arr.length(); i++) {
    arr.getJSONObject(i);
}

Source

Sort an Array by keys based on another Array?

IF you have array in your array, you'll have to adapt the function by Eran a little bit...

function sortArrayByArray($array,$orderArray) {
    $ordered = array();
    foreach($orderArray as $key => $value) {
        if(array_key_exists($key,$array)) {
                $ordered[$key] = $array[$key];
                unset($array[$key]);
        }
    }
    return $ordered + $array;
}

How do I update a Mongo document after inserting it?

mycollection.find_one_and_update({"_id": mongo_id}, 
                                 {"$set": {"newfield": "abc"}})

should work splendidly for you. If there is no document of id mongo_id, it will fail, unless you also use upsert=True. This returns the old document by default. To get the new one, pass return_document=ReturnDocument.AFTER. All parameters are described in the API.

The method was introduced for MongoDB 3.0. It was extended for 3.2, 3.4, and 3.6.

How to map an array of objects in React

you must put object in your JSX, It`s easy way to do this just see my simple code here:

const link = [
  {
   name: "Cold Drink",
   link: "/coldDrink"
  },
  {
   name: "Hot Drink",
   link: "/HotDrink"
  },

{ name: "chease Cake", link: "/CheaseCake" } ]; and you must map this array in your code with simple object see this code :

const links = (this.props.link);
{links.map((item, i) => (
 <li key={i}>
   <Link to={item.link}>{item.name}</Link>
 </li>
 ))}

I hope this answer will be helpful for you ...:)

How to get span tag inside a div in jQuery and assign a text?

Vanilla JS, without jQuery:

document.querySelector('#message span').innerHTML = 'hello world!'

Available in all browsers: https://caniuse.com/#search=querySelector

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

Windows Firewall was creating this error for me. SMTP was trying to post to GMAIL at port 587. Adding port 587 to the Outbound rule [Outbound HTTP/SMTP/RDP] resolved the issue.

How do I determine if my python shell is executing in 32bit or 64bit?

Open python console:

import platform
platform.architecture()[0]

it should display the '64bit' or '32bit' according to your platform.

Alternatively( in case of OS X binaries ):

import sys
sys.maxsize > 2**32 
# it should display True in case of 64bit and False in case of 32bit

Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

Move script tag at the end of BODY instead of HEAD because in current code when the script is computed html element doesn't exist in document.

Since you don't want to you jquery. Use window.onload or document.onload to execute the entire piece of code that you have in current script tag. window.onload vs document.onload

How do I add a library (android-support-v7-appcompat) in IntelliJ IDEA

Without Gradle (Click here for the Gradle solution)

  1. Create a support library project.

  2. Import your library project to Intellij from Eclipse project (this step only applies if you created your library in Eclipse).

  3. Right click on module and choose Open Module Settings.

  4. Setup libraries of v7 jar file Setup libraries of v7 jar file

  5. Setup library module of v7 Setup library module of v7

  6. Setup app module dependency of v7 library module Setup app module dependency of v7 library module

MatPlotLib: Multiple datasets on the same scatter plot

I came across this question as I had exact same problem. Although accepted answer works good but with matplotlib version 2.1.0, it is pretty straight forward to have two scatter plots in one plot without using a reference to Axes

import matplotlib.pyplot as plt

plt.scatter(x,y, c='b', marker='x', label='1')
plt.scatter(x, y, c='r', marker='s', label='-1')
plt.legend(loc='upper left')
plt.show()

SQL Server Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >=

The fix is to stop using correlated subqueries and use joins instead. Correlated subqueries are essentially cursors as they cause the query to run row-by-row and should be avoided.

You may need a derived table in the join in order to get the value you want in the field if you want only one record to match, if you need both values then the ordinary join will do that but you will get multiple records for the same id in the results set. If you only want one, you need to decide which one and do that in the code, you could use a top 1 with an order by, you could use max(), you could use min(), etc, depending on what your real requirement for the data is.

Best C/C++ Network Library

Aggregated List of Libraries

How to show grep result with complete path or file name

If you want to see the full paths, I would recommend to cd to the top directory (of your drive if using windows)

cd C:\
grep -r somethingtosearch C:\Users\Ozzesh\temp

Or on Linux:

cd /
grep -r somethingtosearch ~/temp

if you really resist on your file name filtering (*.log) AND you want recursive (files are not all in the same directory), combining find and grep is the most flexible way:

cd /
find ~/temp -iname '*.log' -type f -exec grep somethingtosearch '{}' \;

POST request via RestTemplate in JSON

If you don't want to map the JSON by yourself, you can do it as follows:

RestTemplate restTemplate = new RestTemplate();
restTemplate.setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter()));
ResponseEntity<String> result = restTemplate.postForEntity(uri, yourObject, String.class);

Can dplyr package be used for conditional mutating?

dplyr now has a function case_when that offers a vectorised if. The syntax is a little strange compared to mosaic:::derivedFactor as you cannot access variables in the standard dplyr way, and need to declare the mode of NA, but it is considerably faster than mosaic:::derivedFactor.

df %>%
mutate(g = case_when(a %in% c(2,5,7) | (a==1 & b==4) ~ 2L, 
                     a %in% c(0,1,3,4) | c == 4 ~ 3L, 
                     TRUE~as.integer(NA)))

EDIT: If you're using dplyr::case_when() from before version 0.7.0 of the package, then you need to precede variable names with '.$' (e.g. write .$a == 1 inside case_when).

Benchmark: For the benchmark (reusing functions from Arun 's post) and reducing sample size:

require(data.table) 
require(mosaic) 
require(dplyr)
require(microbenchmark)

set.seed(42) # To recreate the dataframe
DT <- setDT(lapply(1:6, function(x) sample(7, 10000, TRUE)))
setnames(DT, letters[1:6])
DF <- as.data.frame(DT)

DPLYR_case_when <- function(DF) {
  DF %>%
  mutate(g = case_when(a %in% c(2,5,7) | (a==1 & b==4) ~ 2L, 
                       a %in% c(0,1,3,4) | c==4 ~ 3L, 
                       TRUE~as.integer(NA)))
}

DT_fun <- function(DT) {
  DT[(a %in% c(0,1,3,4) | c == 4), g := 3L]
  DT[a %in% c(2,5,7) | (a==1 & b==4), g := 2L]
}

DPLYR_fun <- function(DF) {
  mutate(DF, g = ifelse(a %in% c(2,5,7) | (a==1 & b==4), 2L, 
                    ifelse(a %in% c(0,1,3,4) | c==4, 3L, NA_integer_)))
}

mosa_fun <- function(DF) {
  mutate(DF, g = derivedFactor(
    "2" = (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)),
    "3" = (a == 0 | a == 1 | a == 4 | a == 3 |  c == 4),
    .method = "first",
    .default = NA
  ))
}

perf_results <- microbenchmark(
  dt_fun <- DT_fun(copy(DT)),
  dplyr_ifelse <- DPLYR_fun(copy(DF)),
  dplyr_case_when <- DPLYR_case_when(copy(DF)),
  mosa <- mosa_fun(copy(DF)),
  times = 100L
)

This gives:

print(perf_results)
Unit: milliseconds
           expr        min         lq       mean     median         uq        max neval
         dt_fun   1.391402    1.560751   1.658337   1.651201   1.716851   2.383801   100
   dplyr_ifelse   1.172601    1.230351   1.331538   1.294851   1.390351   1.995701   100
dplyr_case_when   1.648201    1.768002   1.860968   1.844101   1.958801   2.207001   100
           mosa 255.591301  281.158350 291.391586 286.549802 292.101601 545.880702   100

Get file size before uploading

Best solution working on all browsers ;)

function GetFileSize(fileid) {
    try {
        var fileSize = 0;
        // for IE
        if(checkIE()) { //we could use this $.browser.msie but since it's deprecated, we'll use this function
            // before making an object of ActiveXObject, 
            // please make sure ActiveX is enabled in your IE browser
            var objFSO = new ActiveXObject("Scripting.FileSystemObject");
            var filePath = $("#" + fileid)[0].value;
            var objFile = objFSO.getFile(filePath);
            var fileSize = objFile.size; //size in b
            fileSize = fileSize / 1048576; //size in mb 
        }
        // for FF, Safari, Opeara and Others
        else {
            fileSize = $("#" + fileid)[0].files[0].size //size in b
            fileSize = fileSize / 1048576; //size in mb 
        }
        alert("Uploaded File Size is" + fileSize + "MB");
    }
    catch (e) {
        alert("Error is :" + e);
    }
}

from http://www.dotnet-tricks.com/Tutorial/jquery/HHLN180712-Get-file-size-before-upload-using-jquery.html

UPDATE : We'll use this function to check if it's IE browser or not

function checkIE() {
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)){  
        // If Internet Explorer, return version number
        alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
    } else {
        // If another browser, return 0
        alert('otherbrowser');
    }

    return false;
}

git pull remote branch cannot find remote ref

I had this issue when after rebooted and the last copy of VSCode reopened. The above fix did not work, but when I closed and reopened VSCode via explorer it worked. Here are the steps I did:

_x000D_
_x000D_
//received fatal error_x000D_
git remote remove origin_x000D_
git init_x000D_
git remote add origin git@github:<yoursite>/<your project>.git_x000D_
// still received an err _x000D_
//restarted VSCode and folder via IE _x000D_
//updated one char and resaved the index.html  _x000D_
git add ._x000D_
git commit -m "blah"_x000D_
git push origin master
_x000D_
_x000D_
_x000D_

Cannot find R.layout.activity_main

JUST REMOVE the import.android.R;

Then the R.layout.(XML LAYOUTNAME) will turn to BLUE

IT TOOK ME HOURS TO FIND THIS ONE ERROR

Align image in center and middle within div

Daaawx's answer works, but I think it would be cleaner if we eliminate the inline css.

_x000D_
_x000D_
body {_x000D_
 margin: 0;_x000D_
}_x000D_
_x000D_
#over img {_x000D_
 margin-left: auto;_x000D_
 margin-right: auto;_x000D_
 display: block;_x000D_
}_x000D_
div.example {_x000D_
  position: absolute;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}
_x000D_
<div class="example" id="over">_x000D_
 <img src="http://www.garcard.com/images/garcard_symbol.png">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Is it possible to use a div as content for Twitter's Popover

All of these answers miss a very important aspect!

By using .html or innerHtml or outerHtml you are not actually using the referenced element. You are using a copy of the element's html. This has some serious draw backs.

  1. You can't use any ids because the ids will be duplicated.
  2. If you load the contents every time that the popover is shown you will lose all of the user's input.

What you want to do is load the object itself into the popover.

https://jsfiddle.net/shrewmouse/ex6tuzm2/4/

HTML:

<h1> Test </h1>

<div><button id="target">click me</button></div>

<!-- This will be the contents of our popover -->
<div class='_content' id='blah'>
<h1>Extra Stuff</h1>
<input type='number' placeholder='number'/>
</div>

JQuery:

$(document).ready(function() {

    // We don't want to see the popover contents until the user clicks the target.
    // If you don't hide 'blah' first it will be visible outside of the popover.
    //
    $('#blah').hide();

    // Initialize our popover
    //
    $('#target').popover({
        content: $('#blah'), // set the content to be the 'blah' div
        placement: 'bottom',
        html: true
    });
    // The popover contents will not be set until the popover is shown.  Since we don't 
    // want to see the popover when the page loads, we will show it then hide it.
    //
    $('#target').popover('show');
    $('#target').popover('hide');

    // Now that the popover's content is the 'blah' dive we can make it visisble again.
    //
    $('#blah').show();


});

Lock down Microsoft Excel macro

Protect/Lock Excel VBA Code:

When we write VBA code it is often desired to have the VBA Macro code not visible to end-users. This is to protect your intellectual property and/or stop users messing about with your code. Just be aware that Excel's protection ability is far from what would be considered secure. There are also many VBA Password Recovery [tools] for sale on the www.

To protect your code, open the Excel Workbook and go to Tools>Macro>Visual Basic Editor (Alt+F11). Now, from within the VBE go to Tools>VBAProject Properties and then click the Protection page tab and then check "Lock project from viewing" and then enter your password and again to confirm it. After doing this you must save, close & reopen the Workbook for the protection to take effect.

(Emphasis mine)

Seems like your best bet. It won't stop people determined to steal your code but it's enough to stop casual pirates.

Remember, even if you were able to distribute a compiled copy of your code there'd be nothing to stop people decompiling it.

Simple C example of doing an HTTP POST and consuming the response

After weeks of research. I came up with the following code. I believe this is the bare minimum needed to make a secure connection with SSL to a web server.

#include <stdio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/bio.h>

#define APIKEY "YOUR_API_KEY"
#define HOST "YOUR_WEB_SERVER_URI"
#define PORT "443"

int main() {

    //
    //  Initialize the variables
    //
    BIO* bio;
    SSL* ssl;
    SSL_CTX* ctx;

    //
    //   Registers the SSL/TLS ciphers and digests.
    //
    //   Basically start the security layer.
    //
    SSL_library_init();

    //
    //  Creates a new SSL_CTX object as a framework to establish TLS/SSL
    //  or DTLS enabled connections
    //
    ctx = SSL_CTX_new(SSLv23_client_method());

    //
    //  -> Error check
    //
    if (ctx == NULL)
    {
        printf("Ctx is null\n");
    }

    //
    //   Creates a new BIO chain consisting of an SSL BIO
    //
    bio = BIO_new_ssl_connect(ctx);

    //
    //  Use the variable from the beginning of the file to create a 
    //  string that contains the URL to the site that you want to connect
    //  to while also specifying the port.
    //
    BIO_set_conn_hostname(bio, HOST ":" PORT);

    //
    //   Attempts to connect the supplied BIO
    //
    if(BIO_do_connect(bio) <= 0)
    {
        printf("Failed connection\n");
        return 1;
    }
    else
    {
        printf("Connected\n");
    }

    //
    //  The bare minimum to make a HTTP request.
    //
    char* write_buf = "POST / HTTP/1.1\r\n"
                      "Host: " HOST "\r\n"
                      "Authorization: Basic " APIKEY "\r\n"
                      "Connection: close\r\n"
                      "\r\n";

    //
    //   Attempts to write len bytes from buf to BIO
    //
    if(BIO_write(bio, write_buf, strlen(write_buf)) <= 0)
    {
        //
        //  Handle failed writes here
        //
        if(!BIO_should_retry(bio))
        {
            // Not worth implementing, but worth knowing.
        }

        //
        //  -> Let us know about the failed writes
        //
        printf("Failed write\n");
    }

    //
    //  Variables used to read the response from the server
    //
    int size;
    char buf[1024];

    //
    //  Read the response message
    //
    for(;;)
    {
        //
        //  Get chunks of the response 1023 at the time.
        //
        size = BIO_read(bio, buf, 1023);

        //
        //  If no more data, then exit the loop
        //
        if(size <= 0)
        {
            break;
        }

        //
        //  Terminate the string with a 0, to let know C when the string 
        //  ends.
        //
        buf[size] = 0;

        //
        //  ->  Print out the response
        //
        printf("%s", buf);
    }

    //
    //  Clean after ourselves
    //
    BIO_free_all(bio);
    SSL_CTX_free(ctx);

    return 0;
}

The code above will explain in details how to establish a TLS connection with a remote server.

Important note: this code doesn't check if the public key was signed by a valid authority. Meaning I don't use root certificates for validation. Don't forget to implement this check otherwise you won't know if you are connecting the right website

When it comes to the request itself. It is nothing more then writing the HTTP request by hand.

You can also find under this link an explanation how to instal openSSL in your system, and how to compile the code so it uses the secure library.

How to show "Done" button on iPhone number pad

Here is an adaptation for Luda's answer for Swift:

In the declaration of your UIViewController subclass put

let numberToolbar: UIToolbar = UIToolbar()

in ViewDidLoad put:

    numberToolbar.barStyle = UIBarStyle.BlackTranslucent
    numberToolbar.items=[
        UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Bordered, target: self, action: "hoopla"),
        UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil),
        UIBarButtonItem(title: "Apply", style: UIBarButtonItemStyle.Bordered, target: self, action: "boopla")
    ]

    numberToolbar.sizeToFit()

    textField.inputAccessoryView = numberToolbar //do it for every relevant textfield if there are more than one 

and the add the functions hoopla and hoopla (feel free to choose other names, just change the selector names in ViewDidLoad accordingly

func boopla () {
    textField.resignFirstResponder()
}

func hoopla () {
    textField.text=""
    textField.resignFirstResponder()
}

AngularJS: factory $http.get JSON file

this answer helped me out a lot and pointed me in the right direction but what worked for me, and hopefully others, is:

menuApp.controller("dynamicMenuController", function($scope, $http) {
$scope.appetizers= [];
$http.get('config/menu.json').success(function(data) { 
    console.log("success!");
    $scope.appetizers = data.appetizers;
        console.log(data.appetizers);
    });    
});

How create table only using <div> tag and Css

In building a custom set of layout tags, I found another answer to this problem. Provided here is the custom set of tags and their CSS classes.

HTML

<layout-table>
   <layout-header> 
       <layout-column> 1 a</layout-column>
       <layout-column>  </layout-column>
       <layout-column> 3 </layout-column>
       <layout-column> 4 </layout-column>
   </layout-header>

   <layout-row> 
       <layout-column> a </layout-column>
       <layout-column> a 1</layout-column>
       <layout-column> a </layout-column>
       <layout-column> a </layout-column>
   </layout-row>

   <layout-footer> 
       <layout-column> 1 </layout-column>
       <layout-column>  </layout-column>
       <layout-column> 3 b</layout-column>
       <layout-column> 4 </layout-column>
   </layout-footer>
</layout-table>

CSS

layout-table
{
    display : table;
    clear : both;
    table-layout : fixed;
    width : 100%;
}

layout-table:unresolved
{
    color : red;
    border: 1px blue solid;
    empty-cells : show;
}

layout-header, layout-footer, layout-row 
{
    display : table-row;
    clear : both;   
    empty-cells : show;
    width : 100%;
}

layout-column 
{ 
    display : table-column;
    float : left;
    width : 25%;
    min-width : 25%;
    empty-cells : show;
    box-sizing: border-box;
    /* border: 1px solid white; */
    padding : 1px 1px 1px 1px;
}

layout-row:nth-child(even)
{ 
    background-color : lightblue;
}

layout-row:hover 
{ background-color: #f5f5f5 }

The key to getting empty cells and cells in general to be the right size, is Box-Sizing and Padding. Border will do the same thing as well, but creates a line in the row. Padding doesn't. And, while I haven't tried it, I think Margin will act the same way as Padding, in forcing and empty cell to be rendered properly.

Execute a batch file on a remote PC using a batch file on local PC

If you are in same WORKGROUP shutdown.exe /s /m \\<target-computer-name> should be enough shutdown /? for more, otherwise you need software to connect and control the target server.

UPDATE:

Seems shutdown.bat here is for shutting down apache-tomcat.

So, you might be interested to psexec or PuTTY: A Free Telnet/SSH Client

As native solution could be wmic

Example:

wmic /node:<target-computer-name> process call create "cmd.exe c:\\somefolder\\batch.bat"

In your example should be:

wmic /node:inidsoasrv01 process call create ^
    "cmd.exe D:\\apache-tomcat-6.0.20\\apache-tomcat-7.0.30\\bin\\shutdown.bat"

wmic /? and wmic /node /? for more

AES Encrypt and Decrypt

CryptoSwift is very interesting project but for now it has some AES speed limitations. Be carefull if you need to do some serious crypto - it might be worth to go through the pain of bridge implemmenting CommonCrypto.

BigUps to Marcin for pureSwift implementation

'Use of Unresolved Identifier' in Swift

If this is regarding a class you created, be sure that the class is not nested.

F.e

A.swift

class A {

   class ARelated {

   }
}

calling var b = ARelated() will give 'Use of unresolved identifier: ARelated'.

You can either:

1) separate the classes if wanted on the same file:

A.swift

class A {

}

class ARelated {

}

2) Maintain your same structure and use the enclosing class to get to the subclass:

var b = A.ARelated

Populate a datagridview with sql query results

Years late but here's the simplest for others in case.

String connectionString = @"Data Source=LOCALHOST;Initial Catalog=DB;Integrated Security=true";

SqlConnection cnn = new SqlConnection(connectionString);
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM tblEmployee;", cnn);

DataTable data = new DataTable();
sda.Fill(data);

DataGridView1.DataSource = data;

Using DataSet is not necessary and DataTable should be good enough. SQLCommandBuilder is unnecessary either.

"ORA-01438: value larger than specified precision allowed for this column" when inserting 3

You can't update with a number greater than 1 for datatype number(2,2) is because, the first parameter is the total number of digits in the number and the second one (.i.e 2 here) is the number of digits in decimal part. I guess you can insert or update data < 1. i.e. 0.12, 0.95 etc.

Please check NUMBER DATATYPE in NUMBER Datatype.

why numpy.ndarray is object is not callable in my simple for python loop

The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function.

Use

Z=XY[0]+XY[1]

Instead of

Z=XY(i,0)+XY(i,1)

The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via

I needed the following bindings to get mine to work:

        <binding name="SI_PurchaseRequisition_ISBindingSSL">
          <security mode="Transport">
            <transport clientCredentialType="Basic" proxyCredentialType="None" realm="" />
          </security>
        </binding>

Javascript - sort array based on another array

I had to do this for a JSON payload I receive from an API, but it wasn't in the order I wanted it.

Array to be the reference array, the one you want the second array sorted by:

var columns = [
    {last_name: "last_name"},
    {first_name: "first_name"},
    {book_description: "book_description"},
    {book_id: "book_id"},
    {book_number: "book_number"},
    {due_date: "due_date"},
    {loaned_out: "loaned_out"}
];

I did these as objects because these will have other properties eventually.

Created array:

 var referenceArray= [];
 for (var key in columns) {
     for (var j in columns[key]){
         referenceArray.push(j);
     }
  }

Used this with result set from database. I don't know how efficient it is but with the few number of columns I used, it worked fine.

result.forEach((element, index, array) => {                            
    var tr = document.createElement('tr');
    for (var i = 0; i < referenceArray.length - 1; i++) {
        var td = document.createElement('td');
        td.innerHTML = element[referenceArray[i]];
        tr.appendChild(td);

    }
    tableBody.appendChild(tr);
}); 

Efficient way to do batch INSERTS with JDBC

You can use this rewriteBatchedStatements parameter to make the batch insert even faster.

you can read here about the param: MySQL and JDBC with rewriteBatchedStatements=true

How to write to Console.Out during execution of an MSTest test

I found a solution of my own. I know that Andras answer is probably the most consistent with MSTEST, but I didn't feel like refactoring my code.

[TestMethod]
public void OneIsOne()
{
    using (ConsoleRedirector cr = new ConsoleRedirector())
    {
        Assert.IsFalse(cr.ToString().Contains("New text"));
        /* call some method that writes "New text" to stdout */
        Assert.IsTrue(cr.ToString().Contains("New text"));
    }
}

The disposable ConsoleRedirector is defined as:

internal class ConsoleRedirector : IDisposable
{
    private StringWriter _consoleOutput = new StringWriter();
    private TextWriter _originalConsoleOutput;
    public ConsoleRedirector()
    {
        this._originalConsoleOutput = Console.Out;
        Console.SetOut(_consoleOutput);
    }
    public void Dispose()
    {
        Console.SetOut(_originalConsoleOutput);
        Console.Write(this.ToString());
        this._consoleOutput.Dispose();
    }
    public override string ToString()
    {
        return this._consoleOutput.ToString();
    }
}

how to add a day to a date using jquery datepicker

Try this:

 $('.pickupDate').change(function() {
  var date2 = $('.pickupDate').datepicker('getDate', '+1d'); 
  date2.setDate(date2.getDate()+1); 
  $('.dropoffDate').datepicker('setDate', date2);
});

log4j:WARN No appenders could be found for logger in web.xml

If still help, verify the name of archive, it must be exact "log4j.properties" or "log4j.xml" (case sensitive), and follow the hint by "Alain O'Dea". I was geting the same error, but after make these changes everthing works fine. just like a charm :-). hope this helps.

vertical-align with Bootstrap 3

I ran into the same situation where I wanted to align a few div elements vertically in a row and found that Bootstrap classes col-xx-xx applies style to the div as float: left.

I had to apply the style on the div elements like style="Float:none" and all my div elements started vertically aligned. Here is the working example:

<div class="col-lg-4" style="float:none;">

JsFiddle Link

Just in case someone wants to read more about the float property:

W3Schools - Float

How can I iterate JSONObject to get individual items

How about this?

JSONObject jsonObject = new JSONObject           (YOUR_JSON_STRING);
JSONObject ipinfo     = jsonObject.getJSONObject ("ipinfo");
String     ip_address = ipinfo.getString         ("ip_address");
JSONObject location   = ipinfo.getJSONObject     ("Location");
String     latitude   = location.getString       ("latitude");
System.out.println (latitude);

This sample code using "org.json.JSONObject"

AttributeError("'str' object has no attribute 'read'")

The problem is that for json.load you should pass a file like object with a read function defined. So either you use json.load(response) or json.loads(response.read()).

Linux Command History with date and time

In case you are using zsh you can use for example the -E or -i switch:

history -E

If you do a man zshoptions or man zshbuiltins you can find out more information about these switches as well as other info related to history:

Also when listing,
 -d     prints timestamps for each event
 -f     prints full time-date stamps in the US `MM/DD/YY hh:mm' format
 -E     prints full time-date stamps in the European `dd.mm.yyyy hh:mm' format
 -i     prints full time-date stamps in ISO8601 `yyyy-mm-dd hh:mm' format
 -t fmt prints time and date stamps in the given format; fmt is formatted with the strftime function with the zsh extensions  described  for  the  %D{string} prompt format in the section EXPANSION OF PROMPT SEQUENCES in zshmisc(1).  The resulting formatted string must be no more than 256 characters or will not be printed
 -D     prints elapsed times; may be combined with one of the options above

git add only modified changes and ignore untracked files

You didn't say what's currently your .gitignore, but a .gitignore with the following contents in your root directory should do the trick.

.metadata
build

How to pass the id of an element that triggers an `onclick` event to the event handling function

Use this:

<link onclick='doWithThisElement(this.attributes["id"].value)' />

In the context of the onclick JavaScript, this refers to the current element (which in this case is the whole HTML element link).

Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset)

Pass a UTC timezone object to datetime.now() instead of using datetime.utcnow():

from datetime import datetime, timezone

datetime.now(timezone.utc)
>>> datetime.datetime(2020, 1, 8, 6, 6, 24, 260810, tzinfo=datetime.timezone.utc)

datetime.now(timezone.utc).isoformat()
>>> '2020-01-08T06:07:04.492045+00:00'

That looks good, so let's see what Django and dateutil think:

from django.utils.timezone import is_aware

is_aware(datetime.now(timezone.utc))
>>> True

from dateutil.parser import isoparse

is_aware(isoparse(datetime.now(timezone.utc).isoformat()))
>>> True

Note that you need to use isoparse() because the Python documentation for datetime.fromisoformat() says it "does not support parsing arbitrary ISO 8601 strings".

Okay, the Python datetime object and the ISO 8601 string are both UTC "aware". Now let's look at what JavaScript thinks of the datetime string. Borrowing from this answer we get:

let date= '2020-01-08T06:07:04.492045+00:00';
const dateParsed = new Date(Date.parse(date))

document.write(dateParsed);
document.write("\n");
// Tue Jan 07 2020 22:07:04 GMT-0800 (Pacific Standard Time)

document.write(dateParsed.toISOString());
document.write("\n");
// 2020-01-08T06:07:04.492Z

document.write(dateParsed.toUTCString());
document.write("\n");
// Wed, 08 Jan 2020 06:07:04 GMT

Notes:

I approached this problem with a few goals:

  • generate a UTC "aware" datetime string in ISO 8601 format
  • use only Python Standard Library functions for datetime object and string creation
  • validate the datetime object and string with the Django timezone utility function and the dateutil parser
  • use JavaScript functions to validate that the ISO 8601 datetime string is UTC aware

Note that this approach does not include a Z suffix and does not use utcnow(). But it's based on the recommendation in the Python documentation and it passes muster with both Django and JavaScript.

See also:

Quick way to list all files in Amazon S3 bucket?

Update 15-02-2019:

This command will give you a list of all buckets in AWS S3:

aws s3 ls

This command will give you a list of all top-level objects inside an AWS S3 bucket:

aws s3 ls bucket-name

This command will give you a list of ALL objects inside an AWS S3 bucket:

aws s3 ls bucket-name --recursive

This command will place a list of ALL inside an AWS S3 bucket... inside a text file in your current directory:

aws s3 ls bucket-name --recursive | cat >> file-name.txt

Setting JDK in Eclipse

You manage the list of available compilers in the Window -> Preferences -> Java -> Installed JRE's tab.

In the project build path configuration dialog, under the libraries tab, you can delete the entry for JRE System Library, click on Add Library and choose the installed JRE to compile with. Some compilers can be configured to compile at a back-level compiler version. I think that's why you're seeing the addition version options.

How to get a list of installed android applications and pick one to run

Getting list of installed non-system apps

public static void installedApps()
{
    List<PackageInfo> packList = getPackageManager().getInstalledPackages(0);
    for (int i=0; i < packList.size(); i++)
    {
        PackageInfo packInfo = packList.get(i);
        if (  (packInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0)
        {
            String appName = packInfo.applicationInfo.loadLabel(getPackageManager()).toString();
            Log.e("App ? " + Integer.toString(i), appName);
        }
    }
}

Correct way to import lodash

You can import them as

import {concat, filter, orderBy} from 'lodash';

or as

import concat from 'lodash/concat';
import orderBy from 'lodash/orderBy';
import filter from 'lodash/filter';

the second one is much optimized than the first because it only loads the needed modules

then use like this

pendingArray: concat(
                    orderBy(
                        filter(payload, obj => obj.flag),
                        ['flag'],
                        ['desc'],
                    ),
                    filter(payload, obj => !obj.flag),

Error: Could not create the Java Virtual Machine Mac OSX Mavericks

So try uninstalling all other versions other than the one you need, then set the JAVA_HOMEpath variable for that JDK remaining, and you're done.

That's worked for me, I have two JDK (version 8 & 11) installed on my local mac, that causes the issue, for uninstalling, I followed these two steps:

  • cd /Library/Java/JavaVirtualMachines
  • rm -rf openjdk-11.0.1.jdk

Execute curl command within a Python script

You can use below code snippet

import shlex
import subprocess
import json

def call_curl(curl):
    args = shlex.split(curl)
    process = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate()
    return json.loads(stdout.decode('utf-8'))


if __name__ == '__main__':
    curl = '''curl - X
    POST - d
    '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}'
    http: // localhost: 8080 / firewall / rules / 0000000000000001 '''
    output = call_curl(curl)
    print(output)

Case insensitive std::string.find()

wxWidgets has a very rich string API wxString

it can be done with (using the case conversion way)

int Contains(const wxString& SpecProgramName, const wxString& str)
{
  wxString SpecProgramName_ = SpecProgramName.Upper();
  wxString str_ = str.Upper();
  int found = SpecProgramName.Find(str_);
  if (wxNOT_FOUND == found)
  {
    return 0;
  }
  return 1;
}

How can I see the specific value of the sql_mode?

You can also try this to determine the current global sql_mode value:

SELECT @@GLOBAL.sql_mode;

or session sql_mode value:

SELECT @@SESSION.sql_mode;

I also had the feeling that the SQL mode was indeed empty.

What are the differences between Pandas and NumPy+SciPy in Python?

pandas provides high level data manipulation tools built on top of NumPy. NumPy by itself is a fairly low-level tool, similar to MATLAB. pandas on the other hand provides rich time series functionality, data alignment, NA-friendly statistics, groupby, merge and join methods, and lots of other conveniences. It has become very popular in recent years in financial applications. I will have a chapter dedicated to financial data analysis using pandas in my upcoming book.

React.js: Wrapping one component into another

Try:

var Wrapper = React.createClass({
  render: function() {
    return (
      <div className="wrapper">
        before
          {this.props.children}
        after
      </div>
    );
  }
});

See Multiple Components: Children and Type of the Children props in the docs for more info.

cannot open shared object file: No such file or directory

When working on a supercomputer, I received this error when I ran:

module load python/3.4.0
screen
python

To resolve the error, I simply needed to reload the module in the screen terminal:

module load python/3.4.0
python

Subscript out of range error in this Excel VBA script

This looks a little better than your previous version but get rid of that .Activate on that line and see if you still get that error.

Dim sh1 As Worksheet
set sh1 = Workbooks.Add(filenum(lngPosition) & ".csv")

Creates a worksheet object. Not until you create that object do you want to start working with it. Once you have that object you can do the following:

sh1.Range("A69").Paste
sh1.Range("A69").Select

The sh1. explicitely tells Excel which object you are saying to work with... otherwise if you start selecting other worksheets while this code is running you could wind up pasting data to the wrong place.

What is wrong with this code that uses the mysql extension to fetch data from a database in PHP?

Code:

while ($rows = mysql_fetch_array($query)):
       $name = $rows['Name'];
       $address = $rows['Address'];
       $email = $rows['Email'];
       $subject = $rows['Subject'];
       $comment = $rows['Comment']
       echo "$name<br>$address<br>$email<br>$subject<br>$comment<br><br>";
endwhile;

sql delete statement where date is greater than 30 days

We can use this:

    DELETE FROM table_name WHERE date_column < 
           CAST(CONVERT(char(8), (DATEADD(day,-30,GETDATE())), 112) AS datetime)

But a better option is to use:

DELETE FROM table_name WHERE DATEDIFF(dd, date_column, GETDATE()) > 30

The former is not sargable (i.e. functions on the right side of the expression so it can’t use index) and takes 30 seconds, the latter is sargable and takes less than a second.

Bootstrap Carousel image doesn't align properly

I think I have a solution:

In your personal style sheet page, assign the width & height to match your image dimensions.

Create an additional separate "class" on that top div that appropriates the space with spans...(Shown below)

        <div class="span6 columns" class="carousel">
            <div id="myCarousel" class="carousel slide">
                <div class="carousel-inner">
                <div class="item active">

Without touching the bootstrap.css, in your own style sheet, call "carousel"(or whatever label you choose) to match the width and height of your original pix!

.carousel       {
            width: 320px;
            height: 200px;

}

So in my case, I am using small 320x200 images to carousel with. There is probably preset dimensions in the bootstrap.css, but I don't like changing that so I can try to stay current with future releases. Hope this helps~~

Generic Interface

Here's one suggestion:

public interface Service<T,U> {
    T executeService(U... args);
}

public class MyService implements Service<String, Integer> {
    @Override
    public String executeService(Integer... args) {
        // do stuff
        return null;
    }
}

Because of type erasure any class will only be able to implement one of these. This eliminates the redundant method at least.

It's not an unreasonable interface that you're proposing but I'm not 100% sure of what value it adds either. You might just want to use the standard Callable interface. It doesn't support arguments but that part of the interface has the least value (imho).

Regex using javascript to return just numbers

I guess you want to get number(s) from the string. In which case, you can use the following:

// Returns an array of numbers located in the string
function get_numbers(input) {
    return input.match(/[0-9]+/g);
}

var first_test = get_numbers('something102');
var second_test = get_numbers('something102or12');
var third_test = get_numbers('no numbers here!');

alert(first_test); // [102]
alert(second_test); // [102,12]
alert(third_test); // null

How to get file_get_contents() to work with HTTPS?

HTTPS is supported starting from PHP 4.3.0, if you have compiled in support for OpenSSL. Also, make sure the target server has a valid certificate, the firewall allows outbound connections and allow_url_fopen in php.ini is set to true.