Programs & Examples On #Facebook java sdk

The Facebook-Java-SDK provides Facebook Platform support to your java-based web apps.

Converting Object to JSON and JSON to Object in PHP, (library like Gson for Java)

This should do the trick!

// convert object => json
$json = json_encode($myObject);

// convert json => object
$obj = json_decode($json);

Here's an example

$foo = new StdClass();
$foo->hello = "world";
$foo->bar = "baz";

$json = json_encode($foo);
echo $json;
//=> {"hello":"world","bar":"baz"}

print_r(json_decode($json));
// stdClass Object
// (
//   [hello] => world
//   [bar] => baz
// )

If you want the output as an Array instead of an Object, pass true to json_decode

print_r(json_decode($json, true));
// Array
// (
//   [hello] => world
//   [bar] => baz
// )    

More about json_encode()

See also: json_decode()

Resolving MSB3247 - Found conflicts between different versions of the same dependent assembly

Visual Studio for Mac Community addition:

As AMissico's answer requires changing the log level, and neither ASMSpy nor ASMSpyPlus are available as a cross-platform solution, here is a short addition for Visual Studio for Mac:

https://docs.microsoft.com/en-us/visualstudio/mac/compiling-and-building

It's in Visual Studio Community ? Preferences... ? Projects ? Build Log ? verbosity

How to save a BufferedImage as a File

The answer lies within the Java Documentation's Tutorial for Writing/Saving an Image.

The Image I/O class provides the following method for saving an image:

static boolean ImageIO.write(RenderedImage im, String formatName, File output)  throws IOException

The tutorial explains that

The BufferedImage class implements the RenderedImage interface.

so it's able to be used in the method.

For example,

try {
    BufferedImage bi = getMyImage();  // retrieve image
    File outputfile = new File("saved.png");
    ImageIO.write(bi, "png", outputfile);
} catch (IOException e) {
    // handle exception
}

It's important to surround the write call with a try block because, as per the API, the method throws an IOException "if an error occurs during writing"

Also explained are the method's objective, parameters, returns, and throws, in more detail:

Writes an image using an arbitrary ImageWriter that supports the given format to a File. If there is already a File present, its contents are discarded.

Parameters:

im - a RenderedImage to be written.

formatName - a String containg the informal name of the format.

output - a File to be written to.

Returns:

false if no appropriate writer is found.

Throws:

IllegalArgumentException - if any parameter is null.

IOException - if an error occurs during writing.

However, formatName may still seem rather vague and ambiguous; the tutorial clears it up a bit:

The ImageIO.write method calls the code that implements PNG writing a “PNG writer plug-in”. The term plug-in is used since Image I/O is extensible and can support a wide range of formats.

But the following standard image format plugins : JPEG, PNG, GIF, BMP and WBMP are always be present.

For most applications it is sufficient to use one of these standard plugins. They have the advantage of being readily available.

There are, however, additional formats you can use:

The Image I/O class provides a way to plug in support for additional formats which can be used, and many such plug-ins exist. If you are interested in what file formats are available to load or save in your system, you may use the getReaderFormatNames and getWriterFormatNames methods of the ImageIO class. These methods return an array of strings listing all of the formats supported in this JRE.

String writerNames[] = ImageIO.getWriterFormatNames();

The returned array of names will include any additional plug-ins that are installed and any of these names may be used as a format name to select an image writer.

For a full and practical example, one can refer to Oracle's SaveImage.java example.

How to implement an android:background that doesn't stretch?

You can use a FrameLayout with an ImageView as the first child, then your normal layout as the second child:

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

  <ImageView
        android:id="@+id/background_image_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        android:src="@drawable/your_drawable"/>

  <LinearLayout
        android:id="@+id/your_actual_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

  </LinearLayout>

</FrameLayout>

How to define an empty object in PHP

As others have pointed out, you can use stdClass. However I think it is cleaner without the (), like so:

$obj = new stdClass;

However based on the question, it seems like what you really want is to be able to add properties to an object on the fly. You don't need to use stdClass for that, although you can. Really you can use any class. Just create an object instance of any class and start setting properties. I like to create my own class whose name is simply o with some basic extended functionality that I like to use in these cases and is nice for extending from other classes. Basically it is my own base object class. I also like to have a function simply named o(). Like so:

class o {
  // some custom shared magic, constructor, properties, or methods here
}

function o() {
  return new o;
}

If you don't like to have your own base object type, you can simply have o() return a new stdClass. One advantage is that o is easier to remember than stdClass and is shorter, regardless of if you use it as a class name, function name, or both. Even if you don't have any code inside your o class, it is still easier to memorize than the awkwardly capitalized and named stdClass (which may invoke the idea of a 'sexually transmitted disease class'). If you do customize the o class, you might find a use for the o() function instead of the constructor syntax. It is a normal function that returns a value, which is less limited than a constructor. For example, a function name can be passed as a string to a function that accepts a callable parameter. A function also supports chaining. So you can do something like: $result= o($internal_value)->some_operation_or_conversion_on_this_value();

This is a great start for a base "language" to build other language layers upon with the top layer being written in full internal DSLs. This is similar to the lisp style of development, and PHP supports it way better than most people realize. I realize this is a bit of a tangent for the question, but the question touches on what I think is the base for fully utilizing the power of PHP.

Check which element has been clicked with jQuery

Hope this useful for you.

$(document).click(function(e){
    if ($('#news_gallery').on('clicked')) {
        var article = $('#news-article .news-article');
    }  
});

Style input type file?

Same solution via Jquery. Works if you have more than one file input in the page.

$j(".filebutton").click(function() {
    var input = $j(this).next().find('input');
    input.click();
});

$j(".fileinput").change(function(){

    var file = $j(this).val();
    var fileName = file.split("\\");
    var pai =$j(this).parent().parent().prev();
    pai.html(fileName[fileName.length-1]);
    event.preventDefault();
});

`React/RCTBridgeModule.h` file not found

For me, this error occurred when I added a new scheme/target (app.staging) in the app and installed pods using pod install.

This issue is occurring due to pods are not shared for all targets. So I need to add newly added target (app.staging) inside the Podfile.

Here is my Podfile.

platform :ios, '9.0'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

target 'app' do
  # Pods for app
  pod 'FBLazyVector', :path => "../node_modules/react-native/Libraries/FBLazyVector"
  pod 'FBReactNativeSpec', :path => "../node_modules/react-native/Libraries/FBReactNativeSpec"

  target 'appTests' do
    inherit! :search_paths
    # Pods for testing
  end

  # Pods for staging app // important line below
  target 'app.staging'

  use_native_modules!
end

How can I send JSON response in symfony2 controller

If your data is already serialized:

a) send a JSON response

public function someAction()
{
    $response = new Response();
    $response->setContent(file_get_contents('path/to/file'));
    $response->headers->set('Content-Type', 'application/json');
    return $response;
}

b) send a JSONP response (with callback)

public function someAction()
{
    $response = new Response();
    $response->setContent('/**/FUNCTION_CALLBACK_NAME(' . file_get_contents('path/to/file') . ');');
    $response->headers->set('Content-Type', 'text/javascript');
    return $response;
}

If your data needs be serialized:

c) send a JSON response

public function someAction()
{
    $response = new JsonResponse();
    $response->setData([some array]);
    return $response;
}

d) send a JSONP response (with callback)

public function someAction()
{
    $response = new JsonResponse();
    $response->setData([some array]);
    $response->setCallback('FUNCTION_CALLBACK_NAME');
    return $response;
}

e) use groups in Symfony 3.x.x

Create groups inside your Entities

<?php

namespace Mindlahus;

use Symfony\Component\Serializer\Annotation\Groups;

/**
 * Some Super Class Name
 *
 * @ORM    able("table_name")
 * @ORM\Entity(repositoryClass="SomeSuperClassNameRepository")
 * @UniqueEntity(
 *  fields={"foo", "boo"},
 *  ignoreNull=false
 * )
 */
class SomeSuperClassName
{
    /**
     * @Groups({"group1", "group2"})
     */
    public $foo;
    /**
     * @Groups({"group1"})
     */
    public $date;

    /**
     * @Groups({"group3"})
     */
    public function getBar() // is* methods are also supported
    {
        return $this->bar;
    }

    // ...
}

Normalize your Doctrine Object inside the logic of your application

<?php

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
// For annotations
use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;

...

$repository = $this->getDoctrine()->getRepository('Mindlahus:SomeSuperClassName');
$SomeSuperObject = $repository->findOneById($id);

$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$encoder = new JsonEncoder();
$normalizer = new ObjectNormalizer($classMetadataFactory);
$callback = function ($dateTime) {
    return $dateTime instanceof \DateTime
        ? $dateTime->format('m-d-Y')
        : '';
};
$normalizer->setCallbacks(array('date' => $callback));
$serializer = new Serializer(array($normalizer), array($encoder));
$data = $serializer->normalize($SomeSuperObject, null, array('groups' => array('group1')));

$response = new Response();
$response->setContent($serializer->serialize($data, 'json'));
$response->headers->set('Content-Type', 'application/json');
return $response;

Java Regex Replace with Capturing Group

Source: java-implementation-of-rubys-gsub

Usage:

// Rewrite an ancient unit of length in SI units.
String result = new Rewriter("([0-9]+(\\.[0-9]+)?)[- ]?(inch(es)?)") {
    public String replacement() {
        float inches = Float.parseFloat(group(1));
        return Float.toString(2.54f * inches) + " cm";
    }
}.rewrite("a 17 inch display");
System.out.println(result);

// The "Searching and Replacing with Non-Constant Values Using a
// Regular Expression" example from the Java Almanac.
result = new Rewriter("([a-zA-Z]+[0-9]+)") {
    public String replacement() {
        return group(1).toUpperCase();
    }
}.rewrite("ab12 cd efg34");
System.out.println(result);

Implementation (redesigned):

import static java.lang.String.format;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class Rewriter {
    private Pattern pattern;
    private Matcher matcher;

    public Rewriter(String regularExpression) {
        this.pattern = Pattern.compile(regularExpression);
    }

    public String group(int i) {
        return matcher.group(i);
    }

    public abstract String replacement() throws Exception;

    public String rewrite(CharSequence original) {
        return rewrite(original, new StringBuffer(original.length())).toString();
    }

    public StringBuffer rewrite(CharSequence original, StringBuffer destination) {
        try {
            this.matcher = pattern.matcher(original);
            while (matcher.find()) {
                matcher.appendReplacement(destination, "");
                destination.append(replacement());
            }
            matcher.appendTail(destination);
            return destination;
        } catch (Exception e) {
            throw new RuntimeException("Cannot rewrite " + toString(), e);
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(pattern.pattern());
        for (int i = 0; i <= matcher.groupCount(); i++)
            sb.append(format("\n\t(%s) - %s", i, group(i)));
        return sb.toString();
    }
}

How to create global variables accessible in all views using Express / Node.JS?

After having a chance to study the Express 3 API Reference a bit more I discovered what I was looking for. Specifically the entries for app.locals and then a bit farther down res.locals held the answers I needed.

I discovered for myself that the function app.locals takes an object and stores all of its properties as global variables scoped to the application. These globals are passed as local variables to each view. The function res.locals, however, is scoped to the request and thus, response local variables are accessible only to the view(s) rendered during that particular request/response.

So for my case in my app.js what I did was add:

app.locals({
    site: {
        title: 'ExpressBootstrapEJS',
        description: 'A boilerplate for a simple web application with a Node.JS and Express backend, with an EJS template with using Twitter Bootstrap.'
    },
    author: {
        name: 'Cory Gross',
        contact: '[email protected]'
    }
});

Then all of these variables are accessible in my views as site.title, site.description, author.name, author.contact.

I could also define local variables for each response to a request with res.locals, or simply pass variables like the page's title in as the optionsparameter in the render call.

EDIT: This method will not allow you to use these locals in your middleware. I actually did run into this as Pickels suggests in the comment below. In this case you will need to create a middleware function as such in his alternative (and appreciated) answer. Your middleware function will need to add them to res.locals for each response and then call next. This middleware function will need to be placed above any other middleware which needs to use these locals.

EDIT: Another difference between declaring locals via app.locals and res.locals is that with app.locals the variables are set a single time and persist throughout the life of the application. When you set locals with res.locals in your middleware, these are set everytime you get a request. You should basically prefer setting globals via app.locals unless the value depends on the request req variable passed into the middleware. If the value doesn't change then it will be more efficient for it to be set just once in app.locals.

How to generate auto increment field in select query

If it is MySql you can try

SELECT @n := @n + 1 n,
       first_name, 
       last_name
  FROM table1, (SELECT @n := 0) m
 ORDER BY first_name, last_name

SQLFiddle

And for SQLServer

SELECT row_number() OVER (ORDER BY first_name, last_name) n,
       first_name, 
       last_name 
  FROM table1 

SQLFiddle

How to connect Robomongo to MongoDB

Currently, Robomongo 0.8.x doesn't work with MongoDB 3.0:

For now, don't use Robomongo. For me, the best solution is to use MongoChef.

How can I get a resource "Folder" from inside my jar File?

Inside my jar file I had a folder called Upload, this folder had three other text files inside it and I needed to have an exactly the same folder and files outside of the jar file, I used the code below:

URL inputUrl = getClass().getResource("/upload/blabla1.txt");
File dest1 = new File("upload/blabla1.txt");
FileUtils.copyURLToFile(inputUrl, dest1);

URL inputUrl2 = getClass().getResource("/upload/blabla2.txt");
File dest2 = new File("upload/blabla2.txt");
FileUtils.copyURLToFile(inputUrl2, dest2);

URL inputUrl3 = getClass().getResource("/upload/blabla3.txt");
File dest3 = new File("upload/Bblabla3.txt");
FileUtils.copyURLToFile(inputUrl3, dest3);

Inserting multiple rows in mysql

BEGIN;
INSERT INTO test_b (price_sum)
  SELECT price
  FROM   test_a;
INSERT INTO test_c (price_summ) 
  SELECT price
FROM   test_a;
COMMIT;

"Could not find a valid gem in any repository" (rubygame and others)

You can also add the source you want on the command whenever you have troubles using https, like this:

gem install GEMNAME --source http://rubygems.org

It's better to fix the SSL problem though.

Calculate RSA key fingerprint

A key pair (the private and public keys) will have the same fingerprint; so in the case you can't remember which private key belong to which public key, find the match by comparing their fingerprints.

The most voted answer by Marvin Vinto provides the fingerprint of a public SSH key file. The fingerprint of the corresponding private SSH key can also be queried, but it requires a longer series of step, as shown below.

  1. Load the SSH agent, if you haven't done so. The easiest way is to invoke

    $ ssh-agent bash
    

    or

    $ ssh-agent tcsh
    

    (or another shell you use).

  2. Load the private key you want to test:

    $ ssh-add /path/to/your-ssh-private-key
    

    You will be asked to enter the passphrase if the key is password-protected.

  3. Now, as others have said, type

    $ ssh-add -l
    1024 fd:bc:8a:81:58:8f:2c:78:86:a2:cf:02:40:7d:9d:3c you@yourhost (DSA)
    

    fd:bc:... is the fingerprint you are after. If there are multiple keys, multiple lines will be printed, and the last line contains the fingerprint of the last loaded key.

  4. If you want to stop the agent (i.e., if you invoked step 1 above), then simply type `exit' on the shell, and you'll be back on the shell prior to the loading of ssh agent.

I do not add new information, but hopefully this answer is clear to users of all levels.

Can someone explain how to implement the jQuery File Upload plugin?

You can use uploadify this is the best multiupload jquery plugin i have used.

The implementation is easy, the browser support is perfect.

How to set JAVA_HOME in Mac permanently?

sql-surfer and MikroDel,

actually, the answer is not that complicated! You just need to add:

export JAVA_HOME=(/usr/libexec/java_home)

to your shell profile/configuration file. The only question is - which shell are you using? If you're using for example FISH, then adding that line to .profile or .bash_profile will not work at all. Adding it to config.fish file though will do the trick. Permanently.

Sorting a Data Table

This worked for me:

dt.DefaultView.Sort = "Town ASC, Cutomer ASC";
dt = dt.DefaultView.ToTable();

Converting JSONarray to ArrayList

Generic variant

public static <T> List<T> getList(JSONArray jsonArray) throws Exception {

    List<T> list = new ArrayList<>(jsonArray.length());

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

        list.add((T)jsonArray.get(i));
    }

    return list;

}

//Usage

List<String> listKeyString = getList(dataJsonObject.getJSONArray("keyString"));

Changing fonts in ggplot2

Another option is to use showtext package which supports more types of fonts (TrueType, OpenType, Type 1, web fonts, etc.) and more graphics devices, and avoids using external software such as Ghostscript.

# install.packages('showtext', dependencies = TRUE)
library(showtext)

Import some Google Fonts

# https://fonts.google.com/featured/Superfamilies
font_add_google("Montserrat", "Montserrat")
font_add_google("Roboto", "Roboto")

Load font from the current search path into showtext

# Check the current search path for fonts
font_paths()    
#> [1] "C:\\Windows\\Fonts"

# List available font files in the search path
font_files()    
#>   [1] "AcadEref.ttf"                                
#>   [2] "AGENCYB.TTF"                           
#> [428] "pala.ttf"                                    
#> [429] "palab.ttf"                                   
#> [430] "palabi.ttf"                                  
#> [431] "palai.ttf"

# syntax: font_add(family = "<family_name>", regular = "/path/to/font/file")
font_add("Palatino", "pala.ttf")

font_families()
#> [1] "sans"         "serif"        "mono"         "wqy-microhei"
#> [5] "Montserrat"   "Roboto"       "Palatino"

## automatically use showtext for new devices
showtext_auto() 

Plot: need to open Windows graphics device as showtext does not work well with RStudio built-in graphics device

# https://github.com/yixuan/showtext/issues/7
# https://journal.r-project.org/archive/2015-1/qiu.pdf
# `x11()` on Linux, or `quartz()` on Mac OS
windows()

myFont1 <- "Montserrat"
myFont2 <- "Roboto"
myFont3 <- "Palatino"

library(ggplot2)

a <- ggplot(mtcars, aes(x = wt, y = mpg)) + 
  geom_point() +
  ggtitle("Fuel Efficiency of 32 Cars") +
  xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
  theme(text = element_text(size = 16, family = myFont1)) +
  annotate("text", 4, 30, label = 'Palatino Linotype',
           family = myFont3, size = 10) +
  annotate("text", 1, 11, label = 'Roboto', hjust = 0,
           family = myFont2, size = 10) 

## On-screen device
print(a) 

## Save to PNG 
ggsave("plot_showtext.png", plot = a, 
       type = 'cairo',
       width = 6, height = 6, dpi = 150)  

## Save to PDF
ggsave("plot_showtext.pdf", plot = a, 
       device = cairo_pdf,
       width = 6, height = 6, dpi = 150)  

## turn showtext off if no longer needed
showtext_auto(FALSE) 

Edit: another workaround to use showtext in RStudio. Run the following code at the beginning of the R session (source)

trace(grDevices::png, exit = quote({
    showtext::showtext_begin()
}), print = FALSE)

Edit 2: Starting from version 0.9, showtext can work well with the RStudio graphics device (RStudioGD). Simply call showtext_auto() in the RStudio session and then the plots will be displayed correctly.

What is LDAP used for?

LDAP is the Lightweight Directory Access Protocol. Basically, it's a protocol used to access data from a database (or other source) and it's mostly suited for large numbers of queries and minimal updates (the sort of thing you would use for login information for example).

LDAP doesn't itself provide a database, just a means to query data in the database.

Put search icon near textbox using bootstrap

<input type="text" name="whatever" id="funkystyling" />

Here's the CSS for the image on the left:

#funkystyling {
    background: white url(/path/to/icon.png) left no-repeat;
    padding-left: 17px;
}

And here's the CSS for the image on the right:

#funkystyling {
    background: white url(/path/to/icon.png) right no-repeat;
    padding-right: 17px;
}

Change all files and folders permissions of a directory to 644/755

One approach could be using find:

for directories

find /desired_location -type d -print0 | xargs -0 chmod 0755

for files

find /desired_location -type f -print0 | xargs -0 chmod 0644

Java: Check if command line arguments are null

If you don't pass any argument then even in that case args gets initialized but without any item/element. Try the following one, you will get the same effect:

 
public static void main(String[] args) throws InterruptedException {
        String [] dummy= new String [] {};
        if(dummy[0] == null)
        {
            System.out.println("Proper Usage is: java program filename");
            System.exit(0);
        }

    }

Html- how to disable <a href>?

<script>
    $(document).ready(function(){
        $('#connectBtn').click(function(e){
            e.preventDefault();
        })
    });
</script>

This will prevent the default action.

Software Design vs. Software Architecture

I found this as I was looking for simple distinction between architecture and design myself;
What do you think of this way of looking at them:

  • architecture is "what" we're building;
  • design is "how" we're building;

Node.js/Express routing with get params

For Query parameters like domain.com/test?format=json&type=mini format, then you can easily receive it via - req.query.

app.get('/test', function(req, res){
  var format = req.query.format,
      type = req.query.type;
});

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

There are some problems with your code. First I advise to use parametrized queries so you avoid SQL Injection attacks and also parameter types are discovered by framework:

var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con);
cmd.Parameters.AddWithValue("@id", id.Text);

Second, as you are interested only in one value getting returned from the query, it is better to use ExecuteScalar:

var name = cmd.ExecuteScalar();

if (name != null)
{
   position = name.ToString();
   Response.Write("User Registration successful");
}
else
{
    Console.WriteLine("No Employee found.");
}

The last thing is to wrap SqlConnection and SqlCommand into using so any resources used by those will be disposed of:

string position;

using (SqlConnection con = new SqlConnection("server=free-pc\\FATMAH; Integrated Security=True; database=Workflow; "))
{
  con.Open();

  using (var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con))
  {
    cmd.Parameters.AddWithValue("@id", id.Text);
  
    var name = cmd.ExecuteScalar();
  
    if (name != null)
    {
       position = name.ToString();
       Response.Write("User Registration successful");
    }
    else
    {
        Console.WriteLine("No Employee found.");
    }
  }
}

Freeze screen in chrome debugger / DevTools panel for popover inspection?

  1. Right click anywhere inside Elements Tab
  2. Choose Breakon... > subtree modifications
  3. Trigger the popup you want to see and it will freeze if it see changes in the DOM
  4. If you still don't see the popup, click Step over the next function(F10) button beside Resume(F8) in the upper top center of the chrome until you freeze the popup you want to see.

How to list imported modules?

This code lists modules imported by your module:

import sys
before = [str(m) for m in sys.modules]
import my_module
after = [str(m) for m in sys.modules]
print [m for m in after if not m in before]

It should be useful if you want to know what external modules to install on a new system to run your code, without the need to try again and again.

It won't list the sys module or modules imported from it.

Set specific precision of a BigDecimal

You can use setScale() e.g.

double d = ...
BigDecimal db = new BigDecimal(d).setScale(12, BigDecimal.ROUND_HALF_UP);

Example JavaScript code to parse CSV data

Just use .split(','):

var str = "How are you doing today?";
var n = str.split(" ");

Reading file using relative path in python project

This worked for me.

with open('data/test.csv') as f:

 

What is the easiest way to ignore a JPA field during persistence?

None of the above answers worked for me using Hibernate 5.2.10, Jersey 2.25.1 and Jackson 2.8.9. I finally found the answer (sort of, they reference hibernate4module but it works for 5 too) here. None of the Json annotations worked at all with @Transient. Apparently Jackson2 is 'smart' enough to kindly ignore stuff marked with @Transient unless you explicitly tell it not to. The key was to add the hibernate5 module (which I was using to deal with other Hibernate annotations) and disable the USE_TRANSIENT_ANNOTATION feature in my Jersey Application:

ObjectMapper jacksonObjectMapper = new ObjectMapper();
Hibernate5Module jacksonHibernateModule = new Hibernate5Module();
jacksonHibernateModule.disable(Hibernate5Module.Feature.USE_TRANSIENT_ANNOTATION);
jacksonObjectMapper.registerModule(jacksonHibernateModule);  

Here is the dependency for the Hibernate5Module:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-hibernate5</artifactId>
    <version>2.8.9</version>
</dependency>

What does Html.HiddenFor do?

The Use of Razor code @Html.Hidden or @Html.HiddenFor is similar to the following Html code

 <input type="hidden"/>

And also refer the following link

https://msdn.microsoft.com/en-us/library/system.web.mvc.html.inputextensions.hiddenfor(v=vs.118).aspx

Reading text files using read.table

From ?read.table: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.

So, perhaps your data file isn't clean. Being more specific will help the data import:

d = read.table("foobar.txt", 
               sep="\t", 
               col.names=c("id", "name"), 
               fill=FALSE, 
               strip.white=TRUE)

will specify exact columns and fill=FALSE will force a two column data frame.

RAW POST using cURL in PHP

Implementation with Guzzle library:

use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

$httpClient = new Client();

$response = $httpClient->post(
    'https://postman-echo.com/post',
    [
        RequestOptions::BODY => 'POST raw request content',
        RequestOptions::HEADERS => [
            'Content-Type' => 'application/x-www-form-urlencoded',
        ],
    ]
);

echo(
    $response->getBody()->getContents()
);

PHP CURL extension:

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
    CURLOPT_URL => 'https://postman-echo.com/post',
    CURLOPT_RETURNTRANSFER => true,

    /**
     * Specify POST method
     */
    CURLOPT_POST => true,

    /**
     * Specify request content
     */
    CURLOPT_POSTFIELDS => 'POST raw request content',
]);

$response = curl_exec($curlHandler);

curl_close($curlHandler);

echo($response);

Source code

how to insert datetime into the SQL Database table?

DateTime values should be inserted as if they are strings surrounded by single quotes '20201231' but in many cases they need to be casted explicitly to datetime CAST(N'20201231' AS DATETIME) to avoid bad execution plans with CONVERSION_IMPLICIT warnings that affect negatively the performance. Hier is an example:

CREATE TABLE dbo.T(D DATETIME)

--wrong way
INSERT INTO dbo.T (D) VALUES ('20201231'), ('20201231')

Warnings in the execution plan

--better way
INSERT INTO dbo.T (D) VALUES (CAST(N'20201231' AS DATETIME)), (CAST(N'20201231' AS DATETIME))

No warnings

How to programmatically set drawableLeft on Android button?

Add a Kotlin Extension

If you are going to be doing this frequently, adding an extension makes your code more readable. Button extends TextView; use Button if you want to be more narrow.

fun TextView.leftDrawable(@DrawableRes id: Int = 0) {
    this.setCompoundDrawablesWithIntrinsicBounds(id, 0, 0, 0)
}

To use the extension, simply call

view.leftDrawable(R.drawable.my_drawable)

Anytime you need to clear, don't pass a param or make another extension called removeDrawables

How to split a string by spaces in a Windows batch file?

I ended up with the following:

set input=AAA BBB CCC DDD EEE FFF
set nth=4
for /F "tokens=%nth% delims= " %%a in ("%input%") do set nthstring=%%a
echo %nthstring%

With this you can parameterize the input and index. Make sure to put this code in a bat file.

find a minimum value in an array of floats

You need to iterate the 2d array in order to get the min value of each row, then you have to push any gotten min value to another array and finally you need to get the min value of the array where each min row value was pushed

def get_min_value(self, table):
    min_values = []
    for i in range(0, len(table)):
        min_value = min(table[i])
        min_values.append(min_value)

    return min(min_values)

Mysql SELECT CASE WHEN something then return field

You are mixing the 2 different CASE syntaxes inappropriately.

Use this style (Searched)

  CASE  
  WHEN u.nnmu ='0' THEN mu.naziv_mesta
  WHEN u.nnmu ='1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

Or this style (Simple)

  CASE u.nnmu 
  WHEN '0' THEN mu.naziv_mesta
  WHEN '1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

Not This (Simple but with boolean search predicates)

  CASE u.nnmu 
  WHEN u.nnmu ='0' THEN mu.naziv_mesta
  WHEN u.nnmu ='1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

In MySQL this will end up testing whether u.nnmu is equal to the value of the boolean expression u.nnmu ='0' itself. Regardless of whether u.nnmu is 1 or 0 the result of the case expression itself will be 1

For example if nmu = '0' then (nnmu ='0') evaluates as true (1) and (nnmu ='1') evaluates as false (0). Substituting these into the case expression gives

 SELECT CASE  '0'
  WHEN 1 THEN '0'
  WHEN 0 THEN '1'
 ELSE 'GRESKA'
 END as mesto_utovara

if nmu = '1' then (nnmu ='0') evaluates as false (0) and (nnmu ='1') evaluates as true (1). Substituting these into the case expression gives

 SELECT CASE  '1'
  WHEN 0 THEN '0'
  WHEN 1 THEN '1'
 ELSE 'GRESKA'
 END as mesto_utovara

How to do a num_rows() on COUNT query in codeigniter?

In CI it's really simple actually, all you need is

$this->db->where('account_status', $i);
$num_rows = $this->db->count_all_results('users');
var_dump($num_rows); // prints the number of rows in table users with account status $i

How to generate random colors in matplotlib?

Improving the answer https://stackoverflow.com/a/14720445/6654512 to work with Python3. That piece of code would sometimes generate numbers greater than 1 and matplotlib would throw an error.

for X,Y in data:
   scatter(X, Y, c=numpy.random.random(3))

Why is SQL server throwing this error: Cannot insert the value NULL into column 'id'?

If the id column has no default value, but has NOT NULL constraint, then you have to provide a value yourself

INSERT INTO dbo.role (id, name, created) VALUES ('something', 'Content Coordinator', GETDATE()), ('Content Viewer', GETDATE())

How can I create a memory leak in Java?

I have had a nice "memory leak" in relation to PermGen and XML parsing once. The XML parser we used (I can't remember which one it was) did a String.intern() on tag names, to make comparison faster. One of our customers had the great idea to store data values not in XML attributes or text, but as tagnames, so we had a document like:

<data>
   <1>bla</1>
   <2>foo</>
   ...
</data>

In fact, they did not use numbers but longer textual IDs (around 20 characters), which were unique and came in at a rate of 10-15 million a day. That makes 200 MB of rubbish a day, which is never needed again, and never GCed (since it is in PermGen). We had permgen set to 512 MB, so it took around two days for the out-of-memory exception (OOME) to arrive...

Initializing C dynamic arrays

You cannot use the syntax you have suggested. If you have a C99 compiler, though, you can do this:

int *p;

p = malloc(3 * sizeof p[0]);
memcpy(p, (int []){ 0, 1, 2 }, 3 * sizeof p[0]);

If your compiler does not support C99 compound literals, you need to use a named template to copy from:

int *p;

p = malloc(3 * sizeof p[0]);
{
    static const int p_init[] = { 0, 1, 2 };
    memcpy(p, p_init, 3 * sizeof p[0]);
}

How do I set up curl to permanently use a proxy?

One notice. On Windows, place your _curlrc in '%APPDATA%' or '%USERPROFILE%\Application Data'.

Unit testing void methods?

Depends on what it's doing. If it has parameters, pass in mocks that you could ask later on if they have been called with the right set of parameters.

Excel formula to get cell color

Anticipating that I already had the answer, which is that there is no built-in worksheet function that returns the background color of a cell, I decided to review this article, in case I was wrong. I was amused to notice a citation to the very same MVP article that I used in the course of my ongoing research into colors in Microsoft Excel.

While I agree that, in the purest sense, color is not data, it is meta-data, and it has uses as such. To that end, I shall attempt to develop a function that returns the color of a cell. If I succeed, I plan to put it into an add-in, so that I can use it in any workbook, where it will join a growing legion of other functions that I think Microsoft left out of the product.

Regardless, IMO, the ColorIndex property is virtually useless, since there is essentially no connection between color indexes and the colors that can be selected in the standard foreground and background color pickers. See Color Combinations: Working with Colors in Microsoft Office and the associated binary workbook, Color_Combinations Workbook.

Export table data from one SQL Server to another

There is script table option in Tasks/Generate scripts! I also missed it at beginning! But you can generate insert scripts there (very nice feature, but in very un-intuitive place).

When you get to step "Set Scripting Options" go to "Advanced" tab.

Steps described here (pictures can understand, but i do write in latvian there).

ImportError: No module named 'django.core.urlresolvers'

For those who might be trying to create a Travis Build, the default path from which Django is installed from the requirements.txt file points to a repo whose django_extensions module has not been updated. The only workaround, for now, is to install from the master branch using pip. That is where the patch is made. But for now, we'll have to wait.

You can try this in the meantime, it might help

- pip install git+https://github.com/chibisov/drf-extensions.git@master

- pip install git+https://github.com/django-extensions/django-extensions.git@master

Call function with setInterval in jQuery?

To write the best code, you "should" use the latter approach, with a function reference:

var refreshId = setInterval(function() {}, 5000);

or

function test() {}
var refreshId = setInterval(test, 5000);

but your approach of

function test() {}
var refreshId = setInterval("test()", 5000);

is basically valid, too (as long as test() is global).

Note that there is no such thing really as "in jQuery". You're still writing the Javascript language; you're just using some pre-made functions that are the jQuery library.

How do I combine a background-image and CSS3 gradient on the same element?

you could simply type :

_x000D_
_x000D_
background: linear-gradient(_x000D_
    to bottom,_x000D_
    rgba(0,0,0, 0),_x000D_
    rgba(0,0,0, 100)_x000D_
  ),url(../images/image.jpg);
_x000D_
_x000D_
_x000D_

CSS: Truncate table cells, but fit as much as possible

Like samplebias answer, again if Javascript is an acceptable answer, I made a jQuery plugin specifically for this purpose: https://github.com/marcogrcr/jquery-tableoverflow

To use the plugin just type

$('selector').tableoverflow();

Full example: http://jsfiddle.net/Cw7TD/3/embedded/result/

Edits:

  • Fix in jsfiddle for IE compatibility.
  • Fix in jsfiddle for better browser compatibility (Chrome, Firefox, IE8+).

Set content of iframe

I managed to do it with

var html_string= "content";
document.getElementById('output_iframe1').src = "data:text/html;charset=utf-8," + escape(html_string);

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

For others looking for an answer to why a file is not readable especially on a sdcard, write the file like this first.. Notice the MODE_WORLD_READABLE

try {
            FileOutputStream fos = Main.this.openFileOutput("exported_data.csv", MODE_WORLD_READABLE);
            fos.write(csv.getBytes());
            fos.close();
            File file = Main.this.getFileStreamPath("exported_data.csv");
            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

How can I remove jenkins completely from linux

If your jenkins is running as service instead of process you should stop it first using

sudo service jenkins stop

After stopping it you can follow the normal flow of removing it using commands respective to your linux flavour

For centos it will be

sudo yum remove jenkins

For ubuntu it will

sudo apt-get remove --purge jenkins

I hope this will solve your issue.

"Cannot update paths and switch to branch at the same time"

'origin/master' which can not be resolved as commit

Strange: you need to check your remotes:

git remote -v

And make sure origin is fetched:

git fetch origin

Then:

git branch -avv

(to see if you do have fetched an origin/master branch)

Finally, use git switch instead of the confusing git checkout, with Git 2.23+ (August 2019).

git switch -c test --track origin/master

How to restore PostgreSQL dump file into Postgres databases?

Combining the advice from MartinP and user664833, I was also able to get it to work. Caveat is that entering psql from the pgAdmin GUI tool via choosing Plugins...PSQL Console sets the credentials and permission level for the psql session, so you must have Admin or CRUD permissions on the table and maybe also Admin on the DB (do not know for sure on that). The command then in the psql console would take this form:

postgres=# \i driveletter:/folder_path/backupfilename.backup

where postgres=# is the psql prompt, not part of the command.

The .backup file will include the commands used to create the table, so you may also get things like "ALTER TABLE ..." commands in the file that get executed but reported as errors. I suppose you can always delete these commands before running the restore but you're probably better safe than sorry to keep them in there, as these will not likely cause the restore of data to fail. But always check to be sure the data you wanted to resore actually got there. (Sorry if this seems like patronizing advice to anyone, but it's an oversight that can happen to anyone no matter how long they have been at this stuff -- a moment's distraction from a colleague, a phone call, etc., and it's easy to forget this step. I have done it myself using other databases earlier in my career and wondered "Gee, why am I not seeing any data back from this query?" Answer was the data never actually got restored, and I just wasted 2 hours trying to hunt down suspected possible bugs that didn't exist.)

How can I load storyboard programmatically from class?

Swift 3

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "viewController")
self.navigationController!.pushViewController(vc, animated: true)

Swift 2

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("viewController")
self.navigationController!.pushViewController(vc, animated: true)

Prerequisite

Assign a Storyboard ID to your view controller.

Storyboard ID

IB > Show the Identity inspector > Identity > Storyboard ID

Swift (legacy)

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("viewController") as? UIViewController
self.navigationController!.pushViewController(vc!, animated: true)

Edit: Swift 2 suggested in a comment by Fred A.

if you want to use without any navigationController you have to use like following :

    let Storyboard  = UIStoryboard(name: "Main", bundle: nil)
    let vc = Storyboard.instantiateViewController(withIdentifier: "viewController")
    present(vc , animated: true , completion: nil)

JavaScript error (Uncaught SyntaxError: Unexpected end of input)

Add a second });.

When properly indented, your code reads

$(function() {
    $("#mewlyDiagnosed").hover(function() {
        $("#mewlyDiagnosed").animate({'height': '237px', 'top': "-75px"});
    }, function() {
        $("#mewlyDiagnosed").animate({'height': '162px', 'top': "0px"});
    });
MISSING!

You never closed the outer $(function() {.

Appending a line break to an output file in a shell script

Try:

echo "`date` User `whoami` started the script."$'\n' >> output.log

or just:

echo $'\n' >> output.log

Efficient evaluation of a function at every cell of a NumPy array

A similar question is: Mapping a NumPy array in place. If you can find a ufunc for your f(), then you should use the out parameter.

Check to see if python script is running

Of course the example from Dan will not work as it should be.

Indeed, if the script crash, rise an exception, or does not clean pid file, the script will be run multiple times.

I suggest the following based from another website:

This is to check if there is already a lock file existing

\#/usr/bin/env python
import os
import sys
if os.access(os.path.expanduser("~/.lockfile.vestibular.lock"), os.F_OK):
        #if the lockfile is already there then check the PID number
        #in the lock file
        pidfile = open(os.path.expanduser("~/.lockfile.vestibular.lock"), "r")
        pidfile.seek(0)
        old_pid = pidfile.readline()
        # Now we check the PID from lock file matches to the current
        # process PID
        if os.path.exists("/proc/%s" % old_pid):
                print "You already have an instance of the program running"
                print "It is running as process %s," % old_pid
                sys.exit(1)
        else:
                print "File is there but the program is not running"
                print "Removing lock file for the: %s as it can be there because of the program last time it was run" % old_pid
                os.remove(os.path.expanduser("~/.lockfile.vestibular.lock"))

This is part of code where we put a PID file in the lock file

pidfile = open(os.path.expanduser("~/.lockfile.vestibular.lock"), "w")
pidfile.write("%s" % os.getpid())
pidfile.close()

This code will check the value of pid compared to existing running process., avoiding double execution.

I hope it will help.

Android: How to detect double-tap?

While I liked the simplicity of the approach in the original answer

Here is my version

public abstract class OnDoubleClickListener implements View.OnClickListener {

    private static final int TIME_OUT = ViewConfiguration.getDoubleTapTimeout();
    private TapHandler tapHandler = new TapHandler();

    public abstract void onSingleClick(View v);
    public abstract void onDoubleClick(View v);

    @Override
    public void onClick(View v) {
        tapHandler.cancelSingleTap(v);
        if (tapHandler.isDoubleTap()){
            onDoubleClick(v);
        } else {
            tapHandler.performSingleTap(v);
        }
    }

    private class TapHandler implements Runnable {
        public boolean isDoubleTap() {
            final long tapTime = System.currentTimeMillis();
            boolean doubleTap = tapTime - lastTapTime < TIME_OUT;
            lastTapTime = tapTime;
            return doubleTap;
        }
        public void performSingleTap(View v) {
            view = v;
            v.postDelayed(this, TIME_OUT);
        }
        public void cancelSingleTap(View v) {
            view = null;
            v.removeCallbacks(this);
        }

        @Override
        public void run() {
            if (view != null) {
                onSingleClick(view);
            }
        }
        private View view;
        private long lastTapTime = 0;
    }
}

Usage is same as the original

view.setOnClickListener(new OnDoubleClickListener() {

    @Override
    public void onSingleClick(View v) {

    }

    @Override
    public void onDoubleClick(View v) {

    }
});

Access a function variable outside the function without using "global"

The problem is you were calling print x.bye after you set x as a string. When you run x = hi() it runs hi() and sets the value of x to 5 (the value of bye; it does NOT set the value of x as a reference to the bye variable itself). EX: bye = 5; x = bye; bye = 4; print x; prints 5, not 4

Also, you don't have to run hi() twice, just run x = hi(), not hi();x=hi() (the way you had it it was running hi(), not doing anything with the resulting value of 5, and then rerunning the same hi() and saving the value of 5 to the x variable.

So full code should be

def hi():
    something
    something
    bye = 5
    return bye 
x = hi()
print x

If you wanted to return multiple variables, one option would be to use a list, or dictionary, depending on what you need.

ex:

def hi():
    something
    xyz = { 'bye': 7, 'foobar': 8}
    return xyz
x = hi()
print x['bye']

more on python dictionaries at http://docs.python.org/2/tutorial/datastructures.html#dictionaries

Empty or Null value display in SSRS text boxes

I agree on performing the replace on the SQL side, but using the ISNULL function would be the way I'd go.

SELECT ISNULL(table.MyField, "NA") AS MyField

I usually do as much processing of data on our SQL servers and try to do as little data manipulation in SSRS as possible. This is mainly because my SQL server is considerably more powerful than my SSRS server.

fs: how do I locate a parent folder?

You can use

path.join(__dirname, '../..');

How to add Drop-Down list (<select>) programmatically?

const countryResolver = (data = [{}]) => {
    const countrySelecter = document.createElement('select');
    countrySelecter.className = `custom-select`;
    countrySelecter.id = `countrySelect`;
    countrySelecter.setAttribute("aria-label", "Example select with button addon");

    let opt = document.createElement("option");
    opt.text = "Select language";
    opt.disabled = true;
    countrySelecter.add(opt, null);
    let i = 0;
    for (let item of data) {
        let opt = document.createElement("option");
        opt.value = item.Id;
        opt.text = `${i++}. ${item.Id} - ${item.Value}(${item.Comment})`;
        countrySelecter.add(opt, null);
    }
    return countrySelecter;
};

Android Service needs to run always (Never pause or stop)

I found a simple and clear way of keeping the Service running always.

This guy has explained it so clearly and have used a good algorithm. His approach is to send a Broadcast when the service is about to get killed and then use it to restart the service.

You should check it out: http://fabcirablog.weebly.com/blog/creating-a-never-ending-background-service-in-android

How to make a JTable non-editable

table.setDefaultEditor(Object.class, null);

heroku - how to see all the logs

Follow on Heroku logging

To view your logs we have:

  1. logs command retrives 100 log lines by default.

heroku logs

  1. show maximum 1500 lines, --num (or -n) option.

heroku logs -n 200

  1. Show logs in real time

heroku logs --tail

  1. If you have many apps on heroku

heroku logs --app your_app_name

How do I install the babel-polyfill library?

If your package.json looks something like the following:

  ...
  "devDependencies": {
    "babel": "^6.5.2",
    "babel-eslint": "^6.0.4",
    "babel-polyfill": "^6.8.0",
    "babel-preset-es2015": "^6.6.0",
    "babelify": "^7.3.0",
  ...

And you get the Cannot find module 'babel/polyfill' error message, then you probably just need to change your import statement FROM:

import "babel/polyfill";

TO:

import "babel-polyfill";

And make sure it comes before any other import statement (not necessarily at the entry point of your application).

Reference: https://babeljs.io/docs/usage/polyfill/

How to convert array values to lowercase in PHP?

array_change_value_case

by continue

    function array_change_value_case($array, $case = CASE_LOWER){
        if ( ! is_array($array)) return false;
        foreach ($array as $key => &$value){
            if (is_array($value))
            call_user_func_array(__function__, array (&$value, $case ) ) ;
            else
            $array[$key] = ($case == CASE_UPPER )
            ? strtoupper($array[$key])
            : strtolower($array[$key]);
        }
        return $array;
    }


    $arrays = array ( 1 => 'ONE', 2=> 'TWO', 3 => 'THREE',
                     'FOUR' => array ('a' => 'Ahmed', 'b' => 'basem',
                     'c' => 'Continue'),
                      5=> 'FIVE',
                      array('AbCdeF'));


    $change_case = array_change_value_case($arrays, CASE_UPPER);
    echo "<pre>";
    print_r($change_case);
Array
(
 [1] => one
 [2] => two
 [3] => three
 [FOUR] => Array
  (
   [a] => ahmed
   [b] => basem
   [c] => continue
  )

 [5] => five
 [6] => Array
  (
   [0] => abcdef
  )

)

Link entire table row?

I agree with Matti. Would be easy to do with some simple javascript. A quick jquery example would be something like this:

<tr>
  <td><a href="http://www.example.com/">example</a></td>
  <td>another cell</td>
  <td>one more</td>
</tr>

and

$('tr').click( function() {
    window.location = $(this).find('a').attr('href');
}).hover( function() {
    $(this).toggleClass('hover');
});

then in your CSS

tr.hover {
   cursor: pointer;
   /* whatever other hover styles you want */
}

Subversion ignoring "--password" and "--username" options

I had a similar problem, I wanted to use a different user name for a svn+ssh repository. In the end, I used svn relocate (as described in in this answer. In my case, I'm using svn 1.6.11 and did the following:

svn switch --relocate \
    svn+ssh://olduser@svnserver/path/to/repo \
    svn+ssh://newuser@svnserver/path/to/repo

where svn+ssh://olduser@svnserver/path/to/repo can be found in the URL: line output of svn info command. This command asked me for the password of newuser.

Note that this change is persistent, i.e. if you want only temporarily switch to the new username with this method, you'll have to issue a similar command again after svn update etc.

Java SimpleDateFormat for time zone with a colon separator?

Here's a snippet I used - with plain SimpleDateFormat. Hope somebody else may benefit from it:

public static void main(String[] args) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") {
        public StringBuffer format(Date date, StringBuffer toAppendTo, java.text.FieldPosition pos) {
            StringBuffer toFix = super.format(date, toAppendTo, pos);
            return toFix.insert(toFix.length()-2, ':');
        };
    };
    // Usage:
    System.out.println(dateFormat.format(new Date()));
}

Output:

- Usual Output.........: 2013-06-14T10:54:07-0200
- This snippet's Output: 2013-06-14T10:54:07-02:00

Or... better, use a simpler, different, pattern:

SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
// Usage:
System.out.println(dateFormat2.format(new Date()));

Output:

- This pattern's output: 2013-06-14T10:54:07-02:00

See the docs for that.

What is considered a good response time for a dynamic, personalized web application?

I think you will find that if your web app is performing a complex operation then provided feedback is given to the user, they won't mind (too much).

For example: Loading Google Mail.

Strange PostgreSQL "value too long for type character varying(500)"

We had this same issue. We solved it adding 'length' to entity attribute definition:

@Column(columnDefinition="text", length=10485760)
private String configFileXml = ""; 

Best way to Format a Double value to 2 Decimal places

An alternative is to use String.format:

double[] arr = { 23.59004,
    35.7,
    3.0,
    9
};

for ( double dub : arr ) {
  System.out.println( String.format( "%.2f", dub ) );
}

output:

23.59
35.70
3.00
9.00

You could also use System.out.format (same method signature), or create a java.util.Formatter which works in the same way.

@UniqueConstraint annotation in Java

Note: In Kotlin the syntax for declaring the arrays in annotations uses arrayOf(...) instead of {...}

@Entity
@Table(uniqueConstraints=arrayOf(UniqueConstraint(columnNames=arrayOf("book", "chapter_number"))))
class Chapter(@ManyToOne var book:Book,
              @Column var chapterNumber:Int)

Note: As of Kotlin 1.2 its is possible to use the [...] syntax so the code become much simpler

@Entity
@Table(uniqueConstraints=[UniqueConstraint(columnNames=["book", "chapter_number"])])
class Chapter(@ManyToOne var book:Book,
              @Column var chapterNumber:Int)

Angular 4 - get input value

HTML Component

<input type="text" [formControl]="txtValue">

TS Component

public txtValue = new FormControl('', { validators:[Validators.required] });

We can use this method to save using API. LearnersModules is the module file on our Angular files SaveSampleExams is the service file is one function method.

>  this.service.SaveSampleExams(LearnersModules).subscribe(
>             (data) => {
>               this.dataSaved = true;
>               LearnersModules.txtValue = this.txtValue.value; 
>              });

How to query for today's date and 7 days before data?

Query in Parado's answer is correct, if you want to use MySql too instead GETDATE() you must use (because you've tagged this question with Sql server and Mysql):

select * from tab
where DateCol between adddate(now(),-7) and now() 

How to check if a file exists in a shell script

The backdrop to my solution recommendation is the story of a friend who, well into the second week of his first job, wiped half a build-server clean. So the basic task is to figure out if a file exists, and if so, let's delete it. But there are a few treacherous rapids on this river:

  • Everything is a file.

  • Scripts have real power only if they solve general tasks

  • To be general, we use variables

  • We often use -f force in scripts to avoid manual intervention

  • And also love -r recursive to make sure we create, copy and destroy in a timely fashion.

Consider the following scenario:

We have the file we want to delete: filesexists.json

This filename is stored in a variable

<host>:~/Documents/thisfolderexists filevariable="filesexists.json"

We also hava a path variable to make things really flexible

<host>:~/Documents/thisfolderexists pathtofile=".."

<host>:~/Documents/thisfolderexists ls $pathtofile

filesexists.json  history20170728  SE-Data-API.pem  thisfolderexists

So let's see if -e does what it is supposed to. Does the files exist?

<host>:~/Documents/thisfolderexists [ -e $pathtofile/$filevariable ]; echo $?

0

It does. Magic.

However, what would happen, if the file variable got accidentally be evaluated to nuffin'

<host>:~/Documents/thisfolderexists filevariable=""

<host>:~/Documents/thisfolderexists [ -e $pathtofile/$filevariable ]; echo $?

0

What? It is supposed to return with an error... And this is the beginning of the story how that entire folder got deleted by accident

An alternative could be to test specifically for what we understand to be a 'file'

<host>:~/Documents/thisfolderexists filevariable="filesexists.json"

<host>:~/Documents/thisfolderexists test -f $pathtofile/$filevariable; echo $?

0

So the file exists...

<host>:~/Documents/thisfolderexists filevariable=""

<host>:~/Documents/thisfolderexists test -f $pathtofile/$filevariable; echo $?

1

So this is not a file and maybe, we do not want to delete that entire directory

man test has the following to say:

-b FILE

       FILE exists and is block special

-c FILE

       FILE exists and is character special

-d FILE

       FILE exists and is a directory

-e FILE

       FILE exists

-f FILE

       FILE exists and is a regular file

...

-h FILE

       FILE exists and is a symbolic link (same as -L)

Switch statement: must default be the last case?

The C99 standard is not explicit about this, but taking all facts together, it is perfectly valid.

A case and default label are equivalent to a goto label. See 6.8.1 Labeled statements. Especially interesting is 6.8.1.4, which enables the already mentioned Duff's Device:

Any statement may be preceded by a prefix that declares an identifier as a label name. Labels in themselves do not alter the flow of control, which continues unimpeded across them.

Edit: The code within a switch is nothing special; it is a normal block of code as in an if-statement, with additional jump labels. This explains the fall-through behaviour and why break is necessary.

6.8.4.2.7 even gives an example:

switch (expr) 
{ 
    int i = 4; 
    f(i); 
case 0: 
    i=17; 
    /*falls through into default code */ 
default: 
    printf("%d\n", i); 
} 

In the artificial program fragment the object whose identifier is i exists with automatic storage duration (within the block) but is never initialized, and thus if the controlling expression has a nonzero value, the call to the printf function will access an indeterminate value. Similarly, the call to the function f cannot be reached.

The case constants must be unique within a switch statement:

6.8.4.2.3 The expression of each case label shall be an integer constant expression and no two of the case constant expressions in the same switch statement shall have the same value after conversion. There may be at most one default label in a switch statement.

All cases are evaluated, then it jumps to the default label, if given:

6.8.4.2.5 The integer promotions are performed on the controlling expression. The constant expression in each case label is converted to the promoted type of the controlling expression. If a converted value matches that of the promoted controlling expression, control jumps to the statement following the matched case label. Otherwise, if there is a default label, control jumps to the labeled statement. If no converted case constant expression matches and there is no default label, no part of the switch body is executed.

Statistics: combinations in Python

Using dynamic programming, the time complexity is T(n*m) and space complexity T(m):

def binomial(n, k):
""" (int, int) -> int

         | c(n-1, k-1) + c(n-1, k), if 0 < k < n
c(n,k) = | 1                      , if n = k
         | 1                      , if k = 0

Precondition: n > k

>>> binomial(9, 2)
36
"""

c = [0] * (n + 1)
c[0] = 1
for i in range(1, n + 1):
    c[i] = 1
    j = i - 1
    while j > 0:
        c[j] += c[j - 1]
        j -= 1

return c[k]

Why do I get "Cannot redirect after HTTP headers have been sent" when I call Response.Redirect()?

Be sure that you don't use Responses' methods like Response.Flush(); before your redirecting part.

Why does an onclick property set with setAttribute fail to work in IE?

I did this to get around it and move on, in my case I'm not using an 'input' element, instead I use an image, when I tried setting the "onclick" attribute for this image I experienced the same problem, so I tried wrapping the image with an "a" element and making the reference point to the function like this.

var rowIndex = 1;
var linkDeleter = document.createElement('a');
linkDeleter.setAttribute('href', "javascript:function(" + rowIndex + ");");

var imgDeleter = document.createElement('img');
imgDeleter.setAttribute('alt', "Delete");
imgDeleter.setAttribute('src', "Imagenes/DeleteHS.png");
imgDeleter.setAttribute('border', "0");

linkDeleter.appendChild(imgDeleter);

Check whether IIS is installed or not?

I simple gave below in all my browsers. I got image IIS7

http://localhost/

Stop floating divs from wrapping

After reading John's answer, I discovered the following seemed to work for us (did not require specifying width):

<style>
.row {
    float:left;
    border: 1px solid yellow;
    overflow: visible;
    white-space: nowrap;
}

.cell {
    display: inline-block;
    border: 1px solid red;
    height: 100px;
}
</style>

<div class="row">
    <div class="cell">hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello </div>
    <div class="cell">hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello </div>
    <div class="cell">hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello </div>
</div>

Getting json body in aws Lambda via API gateway

I think there are a few things to understand when working with API Gateway integration with Lambda.

Lambda Integration vs Lambda Proxy Integration

There used to be only Lambda Integration which requires mapping templates. I suppose this is why still seeing many examples using it.

As of September 2017, you no longer have to configure mappings to access the request body.

Lambda Proxy Integration, If you enable it, API Gateway will map every request to JSON and pass it to Lambda as the event object. In the Lambda function you’ll be able to retrieve query string parameters, headers, stage variables, path parameters, request context, and the body from it.

Without enabling Lambda Proxy Integration, you’ll have to create a mapping template in the Integration Request section of API Gateway and decide how to map the HTTP request to JSON yourself. And you’d likely have to create an Integration Response mapping if you were to pass information back to the client.

Before Lambda Proxy Integration was added, users were forced to map requests and responses manually, which was a source of consternation, especially with more complex mappings.

Words need to navigate the thinking. To get the terminologies straight.

  • Lambda Proxy Integration = Pass through
    Simply pass the HTTP request through to lambda.

  • Lambda Integration = Template transformation
    Go through a transformation process using the Apache Velocity template and you need to write the template by yourself.

body is escaped string, not JSON

Using Lambda Proxy Integration, the body in the event of lambda is a string escaped with backslash, not a JSON.

"body": "{\"foo\":\"bar\"}" 

If tested in a JSON formatter.

Parse error on line 1:
{\"foo\":\"bar\"}
-^
Expecting 'STRING', '}', got 'undefined'

The document below is about response but it should apply to request.

The body field, if you are returning JSON, must be converted to a string or it will cause further problems with the response. You can use JSON.stringify to handle this in Node.js functions; other runtimes will require different solutions, but the concept is the same.

For JavaScript to access it as a JSON object, need to convert it back into JSON object with json.parse in JapaScript, json.dumps in Python.

Strings are useful for transporting but you’ll want to be able to convert them back to a JSON object on the client and/or the server side.

The AWS documentation shows what to do.

if (event.body !== null && event.body !== undefined) {
    let body = JSON.parse(event.body)
    if (body.time) 
        time = body.time;
}
...
var response = {
    statusCode: responseCode,
    headers: {
        "x-custom-header" : "my custom header value"
    },
    body: JSON.stringify(responseBody)
};
console.log("response: " + JSON.stringify(response))
callback(null, response);

What is the difference between ApplicationContext and WebApplicationContext in Spring MVC?

The accepted answer is through but there is official explanation on this:

The WebApplicationContext is an extension of the plain ApplicationContext that has some extra features necessary for web applications. It differs from a normal ApplicationContext in that it is capable of resolving themes (see Using themes), and that it knows which Servlet it is associated with (by having a link to the ServletContext). The WebApplicationContext is bound in the ServletContext, and by using static methods on the RequestContextUtils class you can always look up the WebApplicationContext if you need access to it.

Cited from Spring web framework reference

By the way servlet and root context are both webApplicationContext:

Typical context hierarchy in Spring Web MVC

How to make a SIMPLE C++ Makefile

I suggest (note that the indent is a TAB):

tool: tool.o file1.o file2.o
    $(CXX) $(LDFLAGS) $^ $(LDLIBS) -o $@

or

LINK.o = $(CXX) $(LDFLAGS) $(TARGET_ARCH)
tool: tool.o file1.o file2.o

The latter suggestion is slightly better since it reuses GNU Make implicit rules. However, in order to work, a source file must have the same name as the final executable (i.e.: tool.c and tool).

Notice, it is not necessary to declare sources. Intermediate object files are generated using implicit rule. Consequently, this Makefile work for C and C++ (and also for Fortran, etc...).

Also notice, by default, Makefile use $(CC) as the linker. $(CC) does not work for linking C++ object files. We modify LINK.o only because of that. If you want to compile C code, you don't have to force the LINK.o value.

Sure, you can also add your compilation flags with variable CFLAGS and add your libraries in LDLIBS. For example:

CFLAGS = -Wall
LDLIBS = -lm

One side note: if you have to use external libraries, I suggest to use pkg-config in order to correctly set CFLAGS and LDLIBS:

CFLAGS += $(shell pkg-config --cflags libssl)
LDLIBS += $(shell pkg-config --libs libssl)

The attentive reader will notice that this Makefile does not rebuild properly if one header is changed. Add these lines to fix the problem:

override CPPFLAGS += -MMD
include $(wildcard *.d)

-MMD allows to build .d files that contains Makefile fragments about headers dependencies. The second line just uses them.

For sure, a well written Makefile should also include clean and distclean rules:

clean:
    $(RM) *.o *.d

distclean: clean
    $(RM) tool

Notice, $(RM) is the equivalent of rm -f, but it is a good practice to not call rm directly.

The all rule is also appreciated. In order to work, it should be the first rule of your file:

all: tool

You may also add an install rule:

PREFIX = /usr/local
install:
    install -m 755 tool $(DESTDIR)$(PREFIX)/bin

DESTDIR is empty by default. The user can set it to install your program at an alternative system (mandatory for cross-compilation process). Package maintainers for multiple distribution may also change PREFIX in order to install your package in /usr.

One final word: Do not place source files in sub-directories. If you really want to do that, keep this Makefile in the root directory and use full paths to identify your files (i.e. subdir/file.o).

So to summarise, your full Makefile should look like:

LINK.o = $(CXX) $(LDFLAGS) $(TARGET_ARCH)
PREFIX = /usr/local
override CPPFLAGS += -MMD
include $(wildcard *.d)

all: tool
tool: tool.o file1.o file2.o
clean:
    $(RM) *.o *.d
distclean: clean
    $(RM) tool
install:
    install -m 755 tool $(DESTDIR)$(PREFIX)/bin

How to get root view controller?

Swift 3

let rootViewController = UIApplication.shared.keyWindow?.rootViewController

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's an old discussion thread where I listed the main differences and the conditions in which you should use each of these methods. I think you may find it useful to go through the discussion.

To explain the differences as relevant to your posted example:

a. When you use RegisterStartupScript, it will render your script after all the elements in the page (right before the form's end tag). This enables the script to call or reference page elements without the possibility of it not finding them in the Page's DOM.

Here is the rendered source of the page when you invoke the RegisterStartupScript method:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
        <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        </div>
        <div> <span id="lblDisplayDate">Label</span>
            <br />
            <input type="submit" name="btnPostback" value="Register Startup Script" id="btnPostback" />
            <br />
            <input type="submit" name="btnPostBack2" value="Register" id="btnPostBack2" />
        </div>
        <div>
            <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="someViewstategibberish" />
        </div>
        <!-- Note this part -->
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            lbl.style.color = 'red';
        </script>
    </form>
    <!-- Note this part -->
</body>
</html>

b. When you use RegisterClientScriptBlock, the script is rendered right after the Viewstate tag, but before any of the page elements. Since this is a direct script (not a function that can be called, it will immediately be executed by the browser. But the browser does not find the label in the Page's DOM at this stage and hence you should receive an "Object not found" error.

Here is the rendered source of the page when you invoke the RegisterClientScriptBlock method:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
        <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        </div>
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            // Error is thrown in the next line because lbl is null.
            lbl.style.color = 'green';

Therefore, to summarize, you should call the latter method if you intend to render a function definition. You can then render the call to that function using the former method (or add a client side attribute).

Edit after comments:


For instance, the following function would work:

protected void btnPostBack2_Click(object sender, EventArgs e) 
{ 
  System.Text.StringBuilder sb = new System.Text.StringBuilder(); 
  sb.Append("<script language='javascript'>function ChangeColor() {"); 
  sb.Append("var lbl = document.getElementById('lblDisplayDate');"); 
  sb.Append("lbl.style.color='green';"); 
  sb.Append("}</script>"); 

  //Render the function definition. 
  if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock")) 
  {
    ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock", sb.ToString()); 
  }

  //Render the function invocation. 
  string funcCall = "<script language='javascript'>ChangeColor();</script>"; 

  if (!ClientScript.IsStartupScriptRegistered("JSScript"))
  { 
    ClientScript.RegisterStartupScript(this.GetType(), "JSScript", funcCall); 
  } 
} 

EOFError: EOF when reading a line

width, height = map(int, input().split())
def rectanglePerimeter(width, height):
   return ((width + height)*2)
print(rectanglePerimeter(width, height))

Running it like this produces:

% echo "1 2" | test.py
6

I suspect IDLE is simply passing a single string to your script. The first input() is slurping the entire string. Notice what happens if you put some print statements in after the calls to input():

width = input()
print(width)
height = input()
print(height)

Running echo "1 2" | test.py produces

1 2
Traceback (most recent call last):
  File "/home/unutbu/pybin/test.py", line 5, in <module>
    height = input()
EOFError: EOF when reading a line

Notice the first print statement prints the entire string '1 2'. The second call to input() raises the EOFError (end-of-file error).

So a simple pipe such as the one I used only allows you to pass one string. Thus you can only call input() once. You must then process this string, split it on whitespace, and convert the string fragments to ints yourself. That is what

width, height = map(int, input().split())

does.

Note, there are other ways to pass input to your program. If you had run test.py in a terminal, then you could have typed 1 and 2 separately with no problem. Or, you could have written a program with pexpect to simulate a terminal, passing 1 and 2 programmatically. Or, you could use argparse to pass arguments on the command line, allowing you to call your program with

test.py 1 2

Jasmine JavaScript Testing - toBe vs toEqual

For primitive types (e.g. numbers, booleans, strings, etc.), there is no difference between toBe and toEqual; either one will work for 5, true, or "the cake is a lie".

To understand the difference between toBe and toEqual, let's imagine three objects.

var a = { bar: 'baz' },
    b = { foo: a },
    c = { foo: a };

Using a strict comparison (===), some things are "the same":

> b.foo.bar === c.foo.bar
true

> b.foo.bar === a.bar
true

> c.foo === b.foo
true

But some things, even though they are "equal", are not "the same", since they represent objects that live in different locations in memory.

> b === c
false

Jasmine's toBe matcher is nothing more than a wrapper for a strict equality comparison

expect(c.foo).toBe(b.foo)

is the same thing as

expect(c.foo === b.foo).toBe(true)

Don't just take my word for it; see the source code for toBe.

But b and c represent functionally equivalent objects; they both look like

{ foo: { bar: 'baz' } }

Wouldn't it be great if we could say that b and c are "equal" even if they don't represent the same object?

Enter toEqual, which checks "deep equality" (i.e. does a recursive search through the objects to determine whether the values for their keys are equivalent). Both of the following tests will pass:

expect(b).not.toBe(c);
expect(b).toEqual(c);

Hope that helps clarify some things.

How to get all selected values from <select multiple=multiple>?

Actually, I found the best, most-succinct, fastest, and most-compatible way using pure JavaScript (assuming you don't need to fully support IE lte 8) is the following:

var values = Array.prototype.slice.call(document.querySelectorAll('#select-meal-type option:checked'),0).map(function(v,i,a) { 
    return v.value; 
});

UPDATE (2017-02-14):

An even more succinct way using ES6/ES2015 (for the browsers that support it):

const selected = document.querySelectorAll('#select-meal-type option:checked');
const values = Array.from(selected).map(el => el.value);

How to get GMT date in yyyy-mm-dd hh:mm:ss in PHP

You had selected the time format wrong

<?php 
date_default_timezone_set('GMT');

echo date("Y-m-d,h:m:s");
?>

How to label scatterplot points by name?

For all those who don't have the option in Excel (like me), there is a macro which works and is explained here: https://www.get-digital-help.com/2015/08/03/custom-data-labels-in-x-y-scatter-chart/ Very useful

Remove pattern from string with gsub

as.numeric(gsub(pattern=".*_", replacement = '', a)
[1] 5 7

What is causing "Unable to allocate memory for pool" in PHP?

solution for me:

  • apc.ttl=0
  • apc.shm_size=anything you want

edit start

warning!

@bokan indicated me that i should add a warning here.

if you have a ttl of 0 this means the every cached item can be purged immediately. so if you have a small cache size like 2mb and a ttl of 0 this would render the apc useless, because the data in the cache gets always overwritten.

lowering the ttl means only that the cache cannot become full, only with items which can't be replaced.

so you have to choose a good balance between ttl and cache size.

in my case i had a cache size of 1gb, so it was more than enough for me.

edit end

had the same issue on centos 5 with php 5.2.17 and noticed that if the cache size is small and the ttl parameter is "high" (like 7200) while having a lot of php files to cache, then the cache fills up quite fast and apc doesn't find anything which it can remove because all files in the cache still fit in the ttl.

increasing the memory size is only a part solution, you still run in this error if you cache fills up and all files are within the ttl.

so my solution was to set the ttl to 0, so apc fills up the cache an there is allways the possibility for apc to clear some memory for new data.

hope that helps

edit: see also: http://pecl.php.net/bugs/bug.php?id=16966

download http://pecl.php.net/get/APC extract and run the apc.php, there you have a nice diagram how your cache usage look like

Put a Delay in Javascript

Use a AJAX function which will call a php page synchronously and then in that page you can put the php usleep() function which will act as a delay.

function delay(t){

var xmlhttp;

if (window.XMLHttpRequest)

{// code for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp=new XMLHttpRequest();

}

else

{// code for IE6, IE5

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}

xmlhttp.open("POST","http://www.hklabs.org/files/delay.php?time="+t,false);

//This will call the page named delay.php and the response will be sent to a division with ID as "response"

xmlhttp.send();

document.getElementById("response").innerHTML=xmlhttp.responseText;

}

http://www.hklabs.org/articles/put-delay-in-javascript

How do you test a public/private DSA keypair?

The check can be made easier with diff:

diff <(ssh-keygen -y -f $private_key_file) $public_key_file

The only odd thing is that diff says nothing if the files are the same, so you'll only be told if the public and private don't match.

Best HTTP Authorization header type for JWT

Short answer

The Bearer authentication scheme is what you are looking for.

Long answer

Is it related to bears?

Errr... No :)

According to the Oxford Dictionaries, here's the definition of bearer:

bearer /'b??r?/
noun

  1. A person or thing that carries or holds something.

  2. A person who presents a cheque or other order to pay money.

The first definition includes the following synonyms: messenger, agent, conveyor, emissary, carrier, provider.

And here's the definition of bearer token according to the RFC 6750:

1.2. Terminology

Bearer Token

A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

The Bearer authentication scheme is registered in IANA and originally defined in the RFC 6750 for the OAuth 2.0 authorization framework, but nothing stops you from using the Bearer scheme for access tokens in applications that don't use OAuth 2.0.

Stick to the standards as much as you can and don't create your own authentication schemes.


An access token must be sent in the Authorization request header using the Bearer authentication scheme:

2.1. Authorization Request Header Field

When sending the access token in the Authorization request header field defined by HTTP/1.1, the client uses the Bearer authentication scheme to transmit the access token.

For example:

GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer mF_9.B5f-4.1JqM

[...]

Clients SHOULD make authenticated requests with a bearer token using the Authorization request header field with the Bearer HTTP authorization scheme. [...]

In case of invalid or missing token, the Bearer scheme should be included in the WWW-Authenticate response header:

3. The WWW-Authenticate Response Header Field

If the protected resource request does not include authentication credentials or does not contain an access token that enables access to the protected resource, the resource server MUST include the HTTP WWW-Authenticate response header field [...].

All challenges defined by this specification MUST use the auth-scheme value Bearer. This scheme MUST be followed by one or more auth-param values. [...].

For example, in response to a protected resource request without authentication:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example"

And in response to a protected resource request with an authentication attempt using an expired access token:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example",
                         error="invalid_token",
                         error_description="The access token expired"

Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)

_x000D_
_x000D_
 $('.span').attr('data-txt', 'foo');_x000D_
        $('.span').click(function () {_x000D_
         $(this).attr('data-txt',"any other text");_x000D_
        })
_x000D_
.span{_x000D_
}_x000D_
.span:after{ _x000D_
  content: attr(data-txt);_x000D_
 }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class='span'></div>
_x000D_
_x000D_
_x000D_

How do I compile jrxml to get jasper?

Using iReport designer 5.6.0, if you wish to compile multiple jrxml files without previewing - go to Tools -> Massive Processing Tool. Select Elaboration Type as "Compile Files", select the folder where all your jrxml reports are stored, and compile them in a batch.

Getting java.net.SocketTimeoutException: Connection timed out in android

If you are using Kotlin + Retrofit + Coroutines then just use try and catch for network operations like,

viewModelScope.launch(Dispatchers.IO) {
        try {
            val userListResponseModel = apiEndPointsInterface.usersList()
            returnusersList(userListResponseModel)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

Where, Exception is type of kotlin and not of java.lang

This will handle every exception like,

  1. HttpException
  2. SocketTimeoutException
  3. FATAL EXCEPTION: DefaultDispatcher etc

Here is my usersList() function

@GET(AppConstants.APIEndPoints.HOME_CONTENT)
suspend fun usersList(): UserListResponseModel

Note: Your RetrofitClient Classs must have this as client

OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)

How do I resolve "Please make sure that the file is accessible and that it is a valid assembly or COM component"?

In my case I also have unmanaged dll's (C++) in workspace and if you specify:

<files>
    <file src="bin\*.dll" target="lib" />
</files>

nuget would try to load every dll as an assembly, even the C++ libraries! To avoid this behaviour explicitly define your C# assemblies with references tag:

<references>
    <reference file="Managed1.dll" />
    <reference file="Managed2.dll" />
</references>

Remark: parent of references is metadata -> according to documentation https://docs.microsoft.com/en-us/nuget/reference/nuspec#general-form-and-schema

Documentation: https://docs.microsoft.com/en-us/nuget/reference/nuspec

How do I add button on each row in datatable?

Basically your code is okay, thats the right way to do this. Anyhow, there are some misunderstandings:

  1. fetchUserData.cfm does not contain key/value pairs. So it doesn't make sense to address keys in mData. Just use mData[index]

  2. dataTables expects some more info from your serverside. At least you should tell datatables how many items in total are on your serverside and how many are filtered. I just hardcoded this info to your data. You should get the right values from counts in your server sided script.

    {
     "iTotalRecords":"6",
     "iTotalDisplayRecords":"6",
      "aaData": [
    [
        "1",
        "sameek",
        "sam",
        "sam",
        "[email protected]",
        "1",
        ""
    ],...
    
  3. If you have the column names already set in the html part, you don't need to add sTitle.

  4. The mRender Function takes three parameters:

    • data = The data for this cell, as defined in mData
    • type = The datatype (can be ignored mostly)
    • full = The full data array for this row.

So your mRender function should look like this:

  "mRender": function(data, type, full) {
    return '<a class="btn btn-info btn-sm" href=#/' + full[0] + '>' + 'Edit' + '</a>';
  }

Find a working Plunker here

How do I correct the character encoding of a file?

Follow these steps with Notepad++

1- Copy the original text

2- In Notepad++, open new file, change Encoding -> pick an encoding you think the original text follows. Try as well the encoding "ANSI" as sometimes Unicode files are read as ANSI by certain programs

3- Paste

4- Then to convert to Unicode by going again over the same menu: Encoding -> "Encode in UTF-8" (Not "Convert to UTF-8") and hopefully it will become readable

The above steps apply for most languages. You just need to guess the original encoding before pasting in notepad++, then convert through the same menu to an alternate Unicode-based encoding to see if things become readable.

Most languages exist in 2 forms of encoding: 1- The old legacy ANSI (ASCII) form, only 8 bits, was used initially by most computers. 8 bits only allowed 256 possibilities, 128 of them where the regular latin and control characters, the final 128 bits were read differently depending on the PC language settings 2- The new Unicode standard (up to 32 bit) give a unique code for each character in all currently known languages and plenty more to come. if a file is unicode it should be understood on any PC with the language's font installed. Note that even UTF-8 goes up to 32 bit and is just as broad as UTF-16 and UTF-32 only it tries to stay 8 bits with latin characters just to save up disk space

Bootstrap Alert Auto Close

$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
    $("#success-alert").alert('close');
});

Where fadeTo parameters are fadeTo(speed, opacity)

Pandas : compute mean or std (standard deviation) over entire dataframe

You could convert the dataframe to be a single column with stack (this changes the shape from 5x3 to 15x1) and then take the standard deviation:

df.stack().std()         # pandas default degrees of freedom is one

Alternatively, you can use values to convert from a pandas dataframe to a numpy array before taking the standard deviation:

df.values.std(ddof=1)    # numpy default degrees of freedom is zero

Unlike pandas, numpy will give the standard deviation of the entire array by default, so there is no need to reshape before taking the standard deviation.

A couple of additional notes:

  • The numpy approach here is a bit faster than the pandas one, which is generally true when you have the option to accomplish the same thing with either numpy or pandas. The speed difference will depend on the size of your data, but numpy was roughly 10x faster when I tested a few different sized dataframes on my laptop (numpy version 1.15.4 and pandas version 0.23.4).

  • The numpy and pandas approaches here will not give exactly the same answers, but will be extremely close (identical at several digits of precision). The discrepancy is due to slight differences in implementation behind the scenes that affect how the floating point values get rounded.

How to select the first, second, or third element with a given class name?

Use CSS nth-child with the prefix class name

div.myclass:nth-child(1) {
  color: #000;
}

div.myclass:nth-child(2) {
  color: #FFF;
}

div.myclass:nth-child(3) {
  color: #006;
}

Node.js setting up environment specific configs to be used with everyauth

In brief

This kind of a setup is simple and elegant :

env.json

{
  "development": {
      "facebook_app_id": "facebook_dummy_dev_app_id",
      "facebook_app_secret": "facebook_dummy_dev_app_secret",
  }, 
  "production": {
      "facebook_app_id": "facebook_dummy_prod_app_id",
      "facebook_app_secret": "facebook_dummy_prod_app_secret",
  }
}

common.js

var env = require('env.json');

exports.config = function() {
  var node_env = process.env.NODE_ENV || 'development';
  return env[node_env];
};

app.js

var common = require('./routes/common')
var config = common.config();

var facebook_app_id = config.facebook_app_id;
// do something with facebook_app_id

To run in production mode : $ NODE_ENV=production node app.js


In detail

This solution is from : http://himanshu.gilani.info/blog/2012/09/26/bootstraping-a-node-dot-js-app-for-dev-slash-prod-environment/, check it out for more detail.

How to find the duration of difference between two dates in java?

I solved the similar problem using a simple method recently.

public static void main(String[] args) throws IOException, ParseException {
        TimeZone utc = TimeZone.getTimeZone("UTC");
        Calendar calendar = Calendar.getInstance(utc);
        Date until = calendar.getTime();
        calendar.add(Calendar.DAY_OF_MONTH, -7);
        Date since = calendar.getTime();
        long durationInSeconds  = TimeUnit.MILLISECONDS.toSeconds(until.getTime() - since.getTime());

        long SECONDS_IN_A_MINUTE = 60;
        long MINUTES_IN_AN_HOUR = 60;
        long HOURS_IN_A_DAY = 24;
        long DAYS_IN_A_MONTH = 30;
        long MONTHS_IN_A_YEAR = 12;

        long sec = (durationInSeconds >= SECONDS_IN_A_MINUTE) ? durationInSeconds % SECONDS_IN_A_MINUTE : durationInSeconds;
        long min = (durationInSeconds /= SECONDS_IN_A_MINUTE) >= MINUTES_IN_AN_HOUR ? durationInSeconds%MINUTES_IN_AN_HOUR : durationInSeconds;
        long hrs = (durationInSeconds /= MINUTES_IN_AN_HOUR) >= HOURS_IN_A_DAY ? durationInSeconds % HOURS_IN_A_DAY : durationInSeconds;
        long days = (durationInSeconds /= HOURS_IN_A_DAY) >= DAYS_IN_A_MONTH ? durationInSeconds % DAYS_IN_A_MONTH : durationInSeconds;
        long months = (durationInSeconds /=DAYS_IN_A_MONTH) >= MONTHS_IN_A_YEAR ? durationInSeconds % MONTHS_IN_A_YEAR : durationInSeconds;
        long years = (durationInSeconds /= MONTHS_IN_A_YEAR);

        String duration = getDuration(sec,min,hrs,days,months,years);
        System.out.println(duration);
    }
    private static String getDuration(long secs, long mins, long hrs, long days, long months, long years) {
        StringBuffer sb = new StringBuffer();
        String EMPTY_STRING = "";
        sb.append(years > 0 ? years + (years > 1 ? " years " : " year "): EMPTY_STRING);
        sb.append(months > 0 ? months + (months > 1 ? " months " : " month "): EMPTY_STRING);
        sb.append(days > 0 ? days + (days > 1 ? " days " : " day "): EMPTY_STRING);
        sb.append(hrs > 0 ? hrs + (hrs > 1 ? " hours " : " hour "): EMPTY_STRING);
        sb.append(mins > 0 ? mins + (mins > 1 ? " mins " : " min "): EMPTY_STRING);
        sb.append(secs > 0 ? secs + (secs > 1 ? " secs " : " secs "): EMPTY_STRING);
        sb.append("ago");
        return sb.toString();
    }

And as expected it prints: 7 days ago.

How can I represent a range in Java?

You could create a class to represent this

public class Range
{
    private int low;
    private int high;

    public Range(int low, int high){
        this.low = low;
        this.high = high;
    }

    public boolean contains(int number){
        return (number >= low && number <= high);
    }
}

Sample usage:

Range range = new Range(0, 2147483647);

if (range.contains(foo)) {
    //do something
}

find difference between two text files with one item per line

file1 
m1
m2
m3

file2 
m2
m4
m5

>awk 'NR == FNR {file1[$0]++; next} !($0 in file1)' file1 file2
m4
m5

>awk 'NR == FNR {file1[$0]++; next} ($0 in file1)' file1 file2
m2

> What's awk command to get 'm1 and m3' ??  as in file1 and not in file2? 
m1
m3

makefile execute another target

If you removed the make all line from your "fresh" target:

fresh :
    rm -f *.o $(EXEC)
    clear

You could simply run the command make fresh all, which will execute as make fresh; make all.

Some might consider this as a second instance of make, but it's certainly not a sub-instance of make (a make inside of a make), which is what your attempt seemed to result in.

Bootstrap - dropdown menu not working?

I had to download the source files instead of just the compressed files that it says to use for quick start on the bootstrap website

What is the difference between LATERAL and a subquery in PostgreSQL?

Database table

Having the following blog database table storing the blogs hosted by our platform:

Blog table

And, we have two blogs currently hosted:

id created_on title url
1 2013-09-30 Vlad Mihalcea's Blog https://vladmihalcea.com
2 2017-01-22 Hypersistence https://hypersistence.io

Getting our report without using the SQL LATERAL JOIN

We need to build a report that extracts the following data from the blog table:

  • the blog id
  • the blog age, in years
  • the date for the next blog anniversary
  • the number of days remaining until the next anniversary.

If you're using PostgreSQL, then you have to execute the following SQL query:

SELECT
  b.id as blog_id,
  extract(
    YEAR FROM age(now(), b.created_on)
  ) AS age_in_years,
  date(
    created_on + (
      extract(YEAR FROM age(now(), b.created_on)) + 1
    ) * interval '1 year'
  ) AS next_anniversary,
  date(
    created_on + (
      extract(YEAR FROM age(now(), b.created_on)) + 1
    ) * interval '1 year'
  ) - date(now()) AS days_to_next_anniversary
FROM blog b
ORDER BY blog_id

As you can see, the age_in_years has to be defined three times because you need it when calculating the next_anniversary and days_to_next_anniversary values.

And, that's exactly where LATERAL JOIN can help us.

Getting the report using the SQL LATERAL JOIN

The following relational database systems support the LATERAL JOIN syntax:

  • Oracle since 12c
  • PostgreSQL since 9.3
  • MySQL since 8.0.14

SQL Server can emulate the LATERAL JOIN using CROSS APPLY and OUTER APPLY.

LATERAL JOIN allows us to reuse the age_in_years value and just pass it further when calculating the next_anniversary and days_to_next_anniversary values.

The previous query can be rewritten to use the LATERAL JOIN, as follows:

SELECT
  b.id as blog_id,
  age_in_years,
  date(
    created_on + (age_in_years + 1) * interval '1 year'
  ) AS next_anniversary,
  date(
    created_on + (age_in_years + 1) * interval '1 year'
  ) - date(now()) AS days_to_next_anniversary
FROM blog b
CROSS JOIN LATERAL (
  SELECT
    cast(
      extract(YEAR FROM age(now(), b.created_on)) AS int
    ) AS age_in_years
) AS t
ORDER BY blog_id

And, the age_in_years value can be calculated one and reused for the next_anniversary and days_to_next_anniversary computations:

blog_id age_in_years next_anniversary days_to_next_anniversary
1 7 2021-09-30 295
2 3 2021-01-22 44

Much better, right?

The age_in_years is calculated for every record of the blog table. So, it works like a correlated subquery, but the subquery records are joined with the primary table and, for this reason, we can reference the columns produced by the subquery.

C# : "A first chance exception of type 'System.InvalidOperationException'"

The problem here is that your timer starts a thread and when it runs the callback function, the callback function ( updatelistview) is accessing controls on UI thread so this can not be done becuase of this

How to use 'cp' command to exclude a specific directory?

10 years late. Credits to Linus Kleen.

I hate rsync! ;) So why not use find and cp? And with this answer also mkdir to create a non-existent folder structure.

cd /source_folder/ && find . -type d -not -path '*/not-from-here/*' -print -exec mkdir -p '/destination_folder/{}' \;

cd /source_folder/ && find . -type f -not -path '*/not-from-here/*' -print -exec cp -au '{}' '/destination_folder/{}' \;

It looks like cd ìs necessary to concat relative paths with find.

mkdir -p will create all subfolders and will not complain when a folder already exists.


Housten we have the next problem. What happens when someone creates a new folder with a new file in the middle of it? Exactly: it will fail for these new files. (Solution: just run it again! :)) The solution to put everything into one find command seems difficult.


For clean-up: https://unix.stackexchange.com/q/627218/239596

OpenCV in Android Studio

In your build.gradle

repositories {
  jcenter()
}

implementation 'com.quickbirdstudios:opencv:4.1.0'

More information

Regular expression for URL validation (in JavaScript)

After a long research I build this reg expression. I hope it will help others too.......

url = 'https://google.co.in';
var re = /[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?$/;
if (!re.test(url)) { 
 alert("url error");
return false;
}else{
alert('success')
}

Search and replace in bash using regular expressions

Use sed:

MYVAR=ho02123ware38384you443d34o3434ingtod38384day
echo "$MYVAR" | sed -e 's/[a-zA-Z]/X/g' -e 's/[0-9]/N/g'
# prints XXNNNNNXXXXNNNNNXXXNNNXNNXNNNNXXXXXXNNNNNXXX

Note that the subsequent -e's are processed in order. Also, the g flag for the expression will match all occurrences in the input.

You can also pick your favorite tool using this method, i.e. perl, awk, e.g.:

echo "$MYVAR" | perl -pe 's/[a-zA-Z]/X/g and s/[0-9]/N/g'

This may allow you to do more creative matches... For example, in the snip above, the numeric replacement would not be used unless there was a match on the first expression (due to lazy and evaluation). And of course, you have the full language support of Perl to do your bidding...

Get a list of all the files in a directory (recursive)

Newer versions of Groovy (1.7.2+) offer a JDK extension to more easily traverse over files in a directory, for example:

import static groovy.io.FileType.FILES
def dir = new File(".");
def files = [];
dir.traverse(type: FILES, maxDepth: 0) { files.add(it) };

See also [1] for more examples.

[1] http://mrhaki.blogspot.nl/2010/04/groovy-goodness-traversing-directory.html

Image vs zImage vs uImage

What is the difference between them?

Image: the generic Linux kernel binary image file.

zImage: a compressed version of the Linux kernel image that is self-extracting.

uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.


Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:

Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.

(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)


Which type of kernel image do I have to use?

You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.

ADDENDUM

I know that u-boot needs a kernel in uImage format.

That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.

How can I encode a string to Base64 in Swift?

Swift 5.1, Xcode 11:

public extension String {

    /// Assuming the current string is base64 encoded, this property returns a String
    /// initialized by converting the current string into Unicode characters, encoded to
    /// utf8. If the current string is not base64 encoded, nil is returned instead.
    var base64Decoded: String? {
        guard let base64 = Data(base64Encoded: self) else { return nil }
        let utf8 = String(data: base64, encoding: .utf8)
        return utf8
    }

    /// Returns a base64 representation of the current string, or nil if the
    /// operation fails.
    var base64Encoded: String? {
        let utf8 = self.data(using: .utf8)
        let base64 = utf8?.base64EncodedString()
        return base64
    }

}

jQuery get the image src

When dealing with the HTML DOM (ie. this), the array selector [0] must be used to retrieve the jQuery element from the Javascript array.

$(this)[0].getAttribute('src');

HTTPS connection Python

To check for ssl support in Python 2.6+:

try:
    import ssl
except ImportError:
    print "error: no ssl support"

To connect via https:

import urllib2

try:
    response = urllib2.urlopen('https://example.com') 
    print 'response headers: "%s"' % response.info()
except IOError, e:
    if hasattr(e, 'code'): # HTTPError
        print 'http error code: ', e.code
    elif hasattr(e, 'reason'): # URLError
        print "can't connect, reason: ", e.reason
    else:
        raise

Get selected key/value of a combo box using jQuery

This works:

<select name="foo" id="foo">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
</select>
<input type="button" id="button" value="Button" />

$('#button').click(function() {
    alert($('#foo option:selected').text());
    alert($('#foo option:selected').val());
});

How do I find files that do not contain a given string pattern?

Problem

I need to refactor a large project which uses .phtml files to write out HTML using inline PHP code. I want to use Mustache templates instead. I want to find any .phtml giles which do not contain the string new Mustache as these still need to be rewritten.

Solution

find . -iname '*.phtml' -exec grep -H -E -o -c 'new Mustache' {} \; | grep :0$ | sed 's/..$//'

Explanation

Before the pipes:

Find

find . Find files recursively, starting in this directory

-iname '*.phtml' Filename must contain .phtml (the i makes it case-insensitive)

-exec 'grep -H -E -o -c 'new Mustache' {}' Run the grep command on each of the matched paths

Grep

-H Always print filename headers with output lines.

-E Interpret pattern as an extended regular expression (i.e. force grep to behave as egrep).

-o Prints only the matching part of the lines.

-c Only a count of selected lines is written to standard output.


This will give me a list of all file paths ending in .phtml, with a count of the number of times the string new Mustache occurs in each of them.

$> find . -iname '*.phtml$' -exec 'grep -H -E -o -c 'new Mustache' {}'\;

./app/MyApp/Customer/View/Account/quickcodemanagestore.phtml:0
./app/MyApp/Customer/View/Account/studio.phtml:0
./app/MyApp/Customer/View/Account/orders.phtml:1
./app/MyApp/Customer/View/Account/banking.phtml:1
./app/MyApp/Customer/View/Account/applycomplete.phtml:1
./app/MyApp/Customer/View/Account/catalogue.phtml:1
./app/MyApp/Customer/View/Account/classadd.phtml:0
./app/MyApp/Customer/View/Account/orders-trade.phtml:0

The first pipe grep :0$ filters this list to only include lines ending in :0:

$> find . -iname '*.phtml' -exec grep -H -E -o -c 'new Mustache' {} \; | grep :0$

./app/MyApp/Customer/View/Account/quickcodemanagestore.phtml:0
./app/MyApp/Customer/View/Account/studio.phtml:0
./app/MyApp/Customer/View/Account/classadd.phtml:0
./app/MyApp/Customer/View/Account/orders-trade.phtml:0

The second pipe sed 's/..$//' strips off the final two characters of each line, leaving just the file paths.

$> find . -iname '*.phtml' -exec grep -H -E -o -c 'new Mustache' {} \; | grep :0$ | sed 's/..$//'

./app/MyApp/Customer/View/Account/quickcodemanagestore.phtml
./app/MyApp/Customer/View/Account/studio.phtml
./app/MyApp/Customer/View/Account/classadd.phtml
./app/MyApp/Customer/View/Account/orders-trade.phtml

Filezilla FTP Server Fails to Retrieve Directory Listing

If you're using VestaCP, you might want to allow ports 12000-12100 TCP on your Linux Firewall.

You can do this in VestaCP settings.

Spring's overriding bean

Any given Spring context can only have one bean for any given id or name. In the case of the XML id attribute, this is enforced by the schema validation. In the case of the name attribute, this is enforced by Spring's logic.

However, if a context is constructed from two different XML descriptor files, and an id is used by both files, then one will "override" the other. The exact behaviour depends on the ordering of the files when they get loaded by the context.

So while it's possible, it's not recommended. It's error-prone and fragile, and you'll get no help from Spring if you change the ID of one but not the other.

C# Clear all items in ListView

My guess is that Clear() causes a Changed event to be sent, which in turn triggers an automatic update of your listview from the data source. So this is a feature, not a bug ;-)

Have you tried myListView.Clear() instead of myListView.Items.Clear()? Maybe that works better.

Is there an "if -then - else " statement in XPath?

How about using fn:replace(string,pattern,replace) instead?

XPATH is very often used in XSLTs and if you are in that situation and does not have XPATH 2.0 you could use:

  <xsl:choose>
    <xsl:when test="condition1">
      condition1-statements
    </xsl:when>
    <xsl:when test="condition2">
      condition2-statements
    </xsl:when>
    <xsl:otherwise>
      otherwise-statements
    </xsl:otherwise>
  </xsl:choose>

Login to remote site with PHP cURL

View the source of the login page. Look for the form HTML tag. Within that tag is something that will look like action= Use that value as $url, not the URL of the form itself.

Also, while you are there, verify the input boxes are named what you have them listed as.

For example, a basic login form will look similar to:

<form method='post' action='postlogin.php'>
    Email Address: <input type='text' name='email'>
    Password: <input type='password' name='password'>
</form>

Using the above form as an example, change your value of $url to:

$url="http://www.myremotesite.com/postlogin.php";

Verify the values you have listed in $postdata:

$postdata = "email=".$username."&password=".$password;

and it should work just fine.

Redirection of standard and error output appending to the same log file

Maybe it is not quite as elegant, but the following might also work. I suspect asynchronously this would not be a good solution.

$p = Start-Process myjob.bat -redirectstandardoutput $logtempfile -redirecterroroutput $logtempfile -wait
add-content $logfile (get-content $logtempfile)

Bootstrap 3 modal responsive

Old post. I ended up setting media queries and using max-width: YYpx; and width:auto; for each breakpoint. This will scale w/ images as well (per say you have an image that's 740px width on the md screen), the modal will scale down to 740px (excluding padding for the .modal-body, if applied)

<div class="modal fade" id="bs-button-info-modal" tabindex="-1" role="dialog" aria-labelledby="Button Information Modal">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
            <div class="modal-body"></div>
        </div>
    </div>
</div>

Note that I'm using SCSS, bootstrap 3.3.7, and did not make any additional edits to the _modals.scss file that _bootstrap.scss imports. The CSS below is added to an additional SCSS file and imported AFTER _bootstrap.scss.

It is also important to note that the original bootstrap styles for .modal-dialog is not set for the default 992px breakpoint, only as high as the 768px breakpoint (which has a hard set width applied width: 600px;, hence why I overrode it w/ width: auto;.

@media (min-width: $screen-sm-min) { // this is the 768px breakpoint
    .modal-dialog {
        max-width: 600px;
        width: auto;
    }
}

@media (min-width: $screen-md-min) { // this is the 992px breakpoint
    .modal-dialog { 
        max-width: 800px;
    }
}

Example below of modal being responsive with an image.

enter image description here

Is there a way to get a list of all current temporary tables in SQL Server?

If you need to 'see' the list of temporary tables, you could simply log the names used. (and as others have noted, it is possible to directly query this information)

If you need to 'see' the content of temporary tables, you will need to create real tables with a (unique) temporary name.

You can trace the SQL being executed using SQL Profiler:

[These articles target SQL Server versions later than 2000, but much of the advice is the same.]

If you have a lengthy process that is important to your business, it's a good idea to log various steps (step name/number, start and end time) in the process. That way you have a baseline to compare against when things don't perform well, and you can pinpoint which step(s) are causing the problem more quickly.

How do you use the Immediate Window in Visual Studio?

The Immediate window is used to debug and evaluate expressions, execute statements, print variable values, and so forth. It allows you to enter expressions to be evaluated or executed by the development language during debugging.

To display Immediate Window, choose Debug >Windows >Immediate or press Ctrl-Alt-I

enter image description here

Here is an example with Immediate Window:

int Sum(int x, int y) { return (x + y);}
void main(){
int a, b, c;
a = 5;
b = 7;
c = Sum(a, b);
char temp = getchar();}

add breakpoint

enter image description here

call commands

enter image description here

https://msdn.microsoft.com/en-us/library/f177hahy.aspx

How to center a WPF app on screen?

You can still use the Screen class from a WPF app. You just need to reference the System.Windows.Forms assembly from your application. Once you've done that, (and referenced System.Drawing for the example below):

Rectangle workingArea = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;

...works just fine.

Have you considered setting your main window property WindowStartupLocation to CenterScreen?

What are some examples of commonly used practices for naming git branches?

Note, as illustrated in the commit e703d7 or commit b6c2a0d (March 2014), now part of Git 2.0, you will find another naming convention (that you can apply to branches).

"When you need to use space, use dash" is a strange way to say that you must not use a space.
Because it is more common for the command line descriptions to use dashed-multi-words, you do not even want to use spaces in these places.

A branch name cannot have space (see "Which characters are illegal within a branch name?" and git check-ref-format man page).

So for every branch name that would be represented by a multi-word expression, using a '-' (dash) as a separator is a good idea.

Python copy files to a new directory and rename if file name already exists

I would say you have an indentation problem, at least as you wrote it here:

while not os.path.exists(file + "_" + str(i) + extension):
   i+=1
   print "Already 2x exists..."
   print "Renaming"
   shutil.copy(path, file + "_" + str(i) + extension)

should be:

while os.path.exists(file + "_" + str(i) + extension):
    i+=1
print "Already 2x exists..."
print "Renaming"
shutil.copy(path, file + "_" + str(i) + extension)

Check this out, please!

Nginx: Permission denied for nginx on Ubuntu

If i assume that your second code is the puppet config then i have a logical explaination, if the error and log files were create before, you can try this

sudo chown -R www-data:www-data /var/log/nginx;
sudo chmod -R 755 /var/log/nginx;

How to run cron once, daily at 10pm

Here is what I look at everytime I am writing a new crontab entry:

To start editing from terminal -type:

 zee$ crontab -e

what you will add to crontab file:

0 22 * * 0  some-user /opt/somescript/to/run.sh

What it means:

[ 
+ user => 'some-user',      
+ minute => ‘0’,             <<= on top of the hour.
+ hour => '22',              <<= at 10 PM. Military time.
+ monthday => '*',           <<= Every day of the month*
+ month => '*',              <<= Every month*
+ weekday => ‘0’,            <<= Everyday (0 thru 6) = sunday thru saturday
] 

Also, check what shell your machine is running and name the the file accordingly OR it wont execute.

Check the shell with either echo $SHELL or echo $0

It can be "Bourne shell (sh) , Bourne again shell (bash),Korn shell (ksh)..etc"

What is Activity.finish() method doing exactly?

calling finish in onCreate() will not call onDestroy() directly as @prakash said. The finish() operation will not even begin until you return control to Android.

Calling finish() in onCreate(): onCreate() -> onStart() -> onResume(). If user exit the app will call -> onPause() -> onStop() -> onDestroy()

Calling finish() in onStart() : onCreate() -> onStart() -> onStop() -> onDestroy()

Calling finish() in onResume(): onCreate() -> onStart() -> onResume() -> onPause() -> onStop() -> onDestroy()

For further reference check look at this oncreate continuous after finish & about finish()

int to string in MySQL

Try it using CONCAT

CONCAT('site.com/path/','%', CAST(t1.id AS CHAR(25)), '%','/more')

How do you force a CIFS connection to unmount

I use lazy unmount: umount -l (that's a lowercase L)

Lazy unmount. Detach the filesystem from the filesystem hierarchy now, and cleanup all references to the filesystem as soon as it is not busy anymore. (Requires kernel 2.4.11 or later.)

Formula to check if string is empty in Crystal Reports

If IsNull({TABLE.FIELD1}) then "NULL" +',' + {TABLE.FIELD2} else {TABLE.FIELD1} + ', ' + {TABLE.FIELD2}

Here I put NULL as string to display the string value NULL in place of the null value in the data field. Hope you understand.

How to create an Explorer-like folder browser control?

Take a look at Shell MegaPack control set. It provides Windows Explorer like folder/file browsing with most of the features and functionality like context menus, renaming, drag-drop, icons, overlay icons, thumbnails, etc

When to use IList and when to use List

It's always best to use the lowest base type possible. This gives the implementer of your interface, or consumer of your method, the opportunity to use whatever they like behind the scenes.

For collections you should aim to use IEnumerable where possible. This gives the most flexibility but is not always suited.

How to type a new line character in SQL Server Management Studio

I had trouble initially (don't know why) but I finally got the following to work with SSMS for SQL Server 2008.

Insert ALT-13 then ALT-10 where desired in your text in a varchar type column (music symbol and square appear and save when you leave the row). Initially you'll get a warning(!) to the left of the row after leaving it. Just re-excecute your SELECT statement. The symbols and warning will disappear but the CR/LF is saved. You must include ALT-13 if you want the text displayed properly in HTML. To quickly determine if this worked, copy the saved text from SSMS to Notepad.

Alternatively, if you can't get this to work, you can do the same thing starting with an nvarchar column. However the symbols will be saved as text so you must convert the column to varchar when you're done to convert the symbols to CR/LFs.

If you want to copy & paste text from another source (another row or table, HTML, Notepad, etc.) and not have your text truncated at the first CR, I found that the solution (Programmer's Notepad) referred to at the following link works with SSMS for SQL Server 2008 using varchar & nvarchar column types.

http://dbaspot.com/sqlserver-programming/409451-how-i-enter-linefeed-when-modifying-text-field-2.html#post1523145

The author of the post (dbaspot) mentions something about creating SQL queries - not sure what he means. Just follow the intructions about Programmer's Notepad and you can copy & paste text to and from SSMS and retain the LFs both ways (using Programmer's Notepad, not Notepad). To have the text display properly in HTML you must add CRs to the text copied to SSMS. The best way to do this is by executing an UPDATE statement using the REPLACE function to add CRs as follows:

UPDATE table_name
SET column_name = REPLACE(column_name , CHAR(10), CHAR(13) + CHAR(10)).

Detect if a browser in a mobile device (iOS/Android phone/tablet) is used

I know this is an old thread but I thought this might help someone:

Mobile devices have greater height than width, in contrary, computers have greater width than height. For example:

@media all and (max-width: 320px) and (min-height: 320px)

so that would have to be done for every width i guess.

How to detect duplicate values in PHP array?

if(count(array_unique($array))<count($array))
{
    // Array has duplicates
}
else
{
    // Array does not have duplicates
}

How to change letter spacing in a Textview?

As android doesn't support such a thing, you can do it manually with FontCreator. It has good options for font modifying. I used this tool to build a custom font, even if it takes some times but you can always use it in your projects.

Shortest way to print current year in a website

TJ's answer is excellent but I ran into one scenario where my HTML was already rendered and the document.write script would overwrite all of the page contents with just the date year.

For this scenario, you can append a text node to the existing element using the following code:

<div>
    &copy;
    <span id="copyright">
        <script>document.getElementById('copyright').appendChild(document.createTextNode(new Date().getFullYear()))</script>
    </span>
    Company Name
</div>

How to edit the size of the submit button on a form?

Using CSS.

Either inside your <head> tag (the #search means "the element with an ID of search")

<style type="text/css">
    input#search
    {
        width: 20px;
        height: 20px;
    }
</style>

Or inline, in your <input> tag

<input type="submit" id="search" value="Search"  style="width: 20px; height: 20px;" />

Angular directive how to add an attribute to the element?

A directive which adds another directive to the same element:

Similar answers:

Here is a plunker: http://plnkr.co/edit/ziU8d826WF6SwQllHHQq?p=preview

app.directive("myDir", function($compile) {
  return {
    priority:1001, // compiles first
    terminal:true, // prevent lower priority directives to compile after it
    compile: function(el) {
      el.removeAttr('my-dir'); // necessary to avoid infinite compile loop
      el.attr('ng-click', 'fxn()');
      var fn = $compile(el);
      return function(scope){
        fn(scope);
      };
    }
  };
});

Much cleaner solution - not to use ngClick at all:

A plunker: http://plnkr.co/edit/jY10enUVm31BwvLkDIAO?p=preview

app.directive("myDir", function($parse) {
  return {
    compile: function(tElm,tAttrs){
      var exp = $parse('fxn()');
      return function (scope,elm){
        elm.bind('click',function(){
          exp(scope);
        });  
      };
    }
  };
});

SQL query to find record with ID not in another table

Fast Alternative

I ran some tests (on postgres 9.5) using two tables with ~2M rows each. This query below performed at least 5* better than the other queries proposed:

-- Count
SELECT count(*) FROM (
    (SELECT id FROM table1) EXCEPT (SELECT id FROM table2)
) t1_not_in_t2;

-- Get full row
SELECT table1.* FROM (
    (SELECT id FROM table1) EXCEPT (SELECT id FROM table2)
) t1_not_in_t2 JOIN table1 ON t1_not_in_t2.id=table1.id;

How do I get the SelectedItem or SelectedIndex of ListView in vb.net?

VB6: Listview1.selecteditem

VB10: Listview1.FocusedItem.Text

POST an array from an HTML form without javascript

You can also post multiple inputs with the same name and have them save into an array by adding empty square brackets to the input name like this:

<input type="text" name="comment[]" value="comment1"/>
<input type="text" name="comment[]" value="comment2"/>
<input type="text" name="comment[]" value="comment3"/>
<input type="text" name="comment[]" value="comment4"/>

If you use php:

print_r($_POST['comment']) 

you will get this:

Array ( [0] => 'comment1' [1] => 'comment2' [2] => 'comment3' [3] => 'comment4' )

Read all files in a folder and apply a function to each data frame

usually i don't use for loop in R, but here is my solution using for loops and two packages : plyr and dostats

plyr is on cran and you can download dostats on https://github.com/halpo/dostats (may be using install_github from Hadley devtools package)

Assuming that i have your first two data.frame (Df.1 and Df.2) in csv files, you can do something like this.

require(plyr)
require(dostats)

files <- list.files(pattern = ".csv")


for (i in seq_along(files)) {

    assign(paste("Df", i, sep = "."), read.csv(files[i]))

    assign(paste(paste("Df", i, sep = ""), "summary", sep = "."), 
           ldply(get(paste("Df", i, sep = ".")), dostats, sum, min, mean, median, max))

}

Here is the output

R> Df1.summary
  .id sum min   mean median max
1   A  34   4 5.6667    5.5   8
2   B  22   1 3.6667    3.0   9
R> Df2.summary
  .id sum min   mean median max
1   A  21   1 3.5000    3.5   6
2   B  16   1 2.6667    2.5   5

SSIS Connection not found in package

In my case, I could solve this in an easier way. I opened the x.dtsConfig archive, and for an unknown reason this archive was not in the standard format, so ssis could not recognize the configurations. Fortunately, I had backed up the archive previously, so I just had to copy it to the original folder, and everything was working again.

Excel Define a range based on a cell value

Based on answer by @Cici I give here a more generic solution:

=SUM(INDIRECT(CONCATENATE(B1,C1)):INDIRECT(CONCATENATE(B2,C2)))

In Italian version of Excel:

=SOMMA(INDIRETTO(CONCATENA(B1;C1)):INDIRETTO(CONCATENA(B2;C2)))

Where B1-C2 cells hold these values:

  • A, 1
  • A, 5

You can change these valuese to change the final range at wish.


Splitting the formula in parts:

  • SUM(INDIRECT(CONCATENATE(B1,C1)):INDIRECT(CONCATENATE(B2,C2)))
  • CONCATENATE(B1,C1) - result is A1
  • INDIRECT(CONCATENATE(B1,C1)) - result is reference to A1

Hence:

=SUM(INDIRECT(CONCATENATE(B1,C1)):INDIRECT(CONCATENATE(B2,C2)))

results in

=SUM(A1:A5)


I'll write down here a couple of SEO keywords for Italian users:

  • come creare dinamicamente l'indirizzo di un intervallo in excel
  • formula per definire un intervallo di celle in excel.

Con la formula indicata qui sopra basta scrivere nelle caselle da B1 a C2 gli estremi dell'intervallo per vedelo cambiare dentro la formula stessa.

Passing a method as a parameter in Ruby

The comments referring to blocks and Procs are correct in that they are more usual in Ruby. But you can pass a method if you want. You call method to get the method and .call to call it:

def weightedknn( data, vec1, k = 5, weightf = method(:gaussian) )
  ...
  weight = weightf.call( dist )
  ...
end

How to make an element in XML schema optional?

Try this

<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="1" />

if you want 0 or 1 "description" elements, Or

<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="unbounded" />

if you want 0 to infinity number of "description" elements.

iPad WebApp Full Screen in Safari

It only opens the first (bookmarked) page full screen. Any next page will be opened WITH the address bar visible again. Whatever meta tag you put into your page header...

check for null date in CASE statement, where have I gone wrong?

select Id, StartDate,
Case IsNull (StartDate , '01/01/1800')
When '01/01/1800' then
  'Awaiting'
Else
  'Approved'
END AS StartDateStatus
From MyTable

Using IF ELSE in Oracle

You can use Decode as well:

SELECT DISTINCT a.item, decode(b.salesman,'VIKKIE','ICKY',Else),NVL(a.manufacturer,'Not Set')Manufacturer
FROM inv_items a, arv_sales b
WHERE a.co = b.co
      AND A.ITEM_KEY = b.item_key
      AND a.co = '100'
AND a.item LIKE 'BX%'
AND b.salesman in ('01','15')
AND trans_date BETWEEN to_date('010113','mmddrr')
                         and to_date('011713','mmddrr')
GROUP BY a.item, b.salesman, a.manufacturer
ORDER BY a.item

What does the SQL Server Error "String Data, Right Truncation" mean and how do I fix it?

This is a known issue of the mssql ODBC driver. According to the Microsoft blog post:

The ColumnSize parameter of SQLBindParameter refers to the number of characters in the SQL type, while BufferLength is the number of bytes in the application's buffer. However, if the SQL data type is varchar(n) or char(n), the application binds the parameter as SQL_C_CHAR or SQL_C_VARCHAR, and the character encoding of the client is UTF-8, you may get a "String data, right truncation" error from the driver even if the value of ColumnSize is aligned with the size of the data type on the server. This error occurs since conversions between character encodings may change the length of the data. For example, a right apostrophe character (U+2019) is encoded in CP-1252 as the single byte 0x92, but in UTF-8 as the 3-byte sequence 0xe2 0x80 0x99.

You can find the full article here.

Multiple file upload in php

Nice link on:

PHP Single File Uploading with vary basic explanation.

PHP file uploading with the Validation

PHP Multiple Files Upload With Validation Click here to download source code

PHP/jQuery Multiple Files Upload With The ProgressBar And Validation (Click here to download source code)

How To Upload Files In PHP And Store In MySql Database (Click here to download source code)

extract($_POST);
    $error=array();
    $extension=array("jpeg","jpg","png","gif");
    foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name)
            {
                $file_name=$_FILES["files"]["name"][$key];
                $file_tmp=$_FILES["files"]["tmp_name"][$key];
                $ext=pathinfo($file_name,PATHINFO_EXTENSION);
                if(in_array($ext,$extension))
                {
                    if(!file_exists("photo_gallery/".$txtGalleryName."/".$file_name))
                    {
                        move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"photo_gallery/".$txtGalleryName."/".$file_name);
                    }
                    else
                    {
                        $filename=basename($file_name,$ext);
                        $newFileName=$filename.time().".".$ext;
                        move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"photo_gallery/".$txtGalleryName."/".$newFileName);
                    }
                }
                else
                {
                    array_push($error,"$file_name, ");
                }
            }

and you must check your HTML code

<form action="create_photo_gallery.php" method="post" enctype="multipart/form-data">
    <table width="100%">
        <tr>
            <td>Select Photo (one or multiple):</td>
            <td><input type="file" name="files[]" multiple/></td>
        </tr>
        <tr>
            <td colspan="2" align="center">Note: Supported image format: .jpeg, .jpg, .png, .gif</td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" value="Create Gallery" id="selectedButton"/></td>
        </tr>
    </table>
</form>

Nice link on:

PHP Single File Uploading with vary basic explanation.

PHP file uploading with the Validation

PHP Multiple Files Upload With Validation Click here to download source code

PHP/jQuery Multiple Files Upload With The ProgressBar And Validation (Click here to download source code)

How To Upload Files In PHP And Store In MySql Database (Click here to download source code)

How to detect input type=file "change" for the same file?

If you don't want to use jQuery

<form enctype='multipart/form-data'>
    <input onchange="alert(this.value); return false;" type='file'>
    <br>
    <input type='submit' value='Upload'>
</form>

It works fine in Firefox, but for Chrome you need to add this.value=null; after alert.

What is the difference between a data flow diagram and a flow chart?

You should use whatever you like. The diagram is just a tool. Use whatever tool fits you and your problem best. I usually just use boxes and arrows and squiggles and circles and little stick figures and whatever else I think gets the point across to the viewer. In short it doesn't matter if you even use a standard diagraming standard. People are usually pretty good at understanding pictures.

Two dimensional array in python

a = [[] for index in range(1, n)]

Hide strange unwanted Xcode logs

This is related to a known issue with logging found in the Xcode 8 Beta Release Notes (also asked an engineer at WWDC).

When debugging WatchOS applications in the Watch simulator, the OS may produce an excessive amount of unhelpful logging. (26652255)

There is currently no workaround available, you must wait for a new version of Xcode.

EDIT 7/5/16: This is supposedly fixed as of Xcode 8 Beta 2:

Resolved in Xcode 8 beta 2 – IDE

Debugging

  • When debugging an app on the Simulator, logs are visible. (26457535)

Xcode 8 Beta 2 Release Notes

Entity Framework - "An error occurred while updating the entries. See the inner exception for details"

Turn the Pluralization On. The problem is that you model object are using singular name (Pupil) convention, while in your database you are using pluralized names Pupils with s.

UPDATE

This post shows how can you turn it on or off. Some relevant excerpt of that post:

To turn pluralization on and off

  • On the Tools menu, click Options.

  • In the Options dialog box, expand Database Tools. Note: Select Show all settings if the Database Tools node is not visible.

  • Click O/R Designer.

  • Set Pluralization of names to Enabled = False to set the O/R Designer so that it does not change class names.

  • Set Pluralization of names to Enabled = True to apply pluralization rules to the class names of objects added to the O/R Designer.

UPDATE 2

But note that, you should avoid pluralized names. You can read here how to do it (I'll cite it here, just in case the link gets broken).

(...) When you work with Entity Framework Code First approach, you are creating your database tables from your model classes. Usually Entity Framework will create tables with Pluralized names. that means if you have a model class called PhoneNumber, Entity framework will create a table for this class called “PhoneNumbers“. If you wish to avoid pluralized name and wants singular name like Customer , you can do it like this In your DBContext class, Override the “OnModelCreating” method like this (...)

enter image description here

(...) Having this Method Overriding will avoid creating tables with pluralized names. Now it will create a Table called “PhoneNumber” , Not “PhoneNumbers” (...)

Could not extract response: no suitable HttpMessageConverter found for response type

public class Application {

    private static List<HttpMessageConverter<?>> getMessageConverters() {
        List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
        converters.add(new MappingJacksonHttpMessageConverter());
        return converters;
    }   

    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();

        restTemplate.setMessageConverters(getMessageConverters());
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        //Page page = restTemplate.getForObject("http://graph.facebook.com/pivotalsoftware", Page.class);

        ResponseEntity<Page> response = 
                  restTemplate.exchange("http://graph.facebook.com/skbh86", HttpMethod.GET, entity, Page.class, "1");
        Page page = response.getBody();
        System.out.println("Name:    " + page.getId());
        System.out.println("About:   " + page.getFirst_name());
        System.out.println("Phone:   " + page.getLast_name());
        System.out.println("Website: " + page.getMiddle_name());
        System.out.println("Website: " + page.getName());
    }
}

In PANDAS, how to get the index of a known value?

To get the index by value, simply add .index[0] to the end of a query. This will return the index of the first row of the result...

So, applied to your dataframe:

In [1]: a[a['c2'] == 1].index[0]     In [2]: a[a['c1'] > 7].index[0]   
Out[1]: 0                            Out[2]: 4                         

Where the query returns more than one row, the additional index results can be accessed by specifying the desired index, e.g. .index[n]

In [3]: a[a['c2'] >= 7].index[1]     In [4]: a[(a['c2'] > 1) & (a['c1'] < 8)].index[2]  
Out[3]: 4                            Out[4]: 3 

Check if all checkboxes are selected

I think the easiest way is checking for this condition:

$('.abc:checked').length == $('.abc').length

You could do it every time a new checkbox is checked:

$(".abc").change(function(){
    if ($('.abc:checked').length == $('.abc').length) {
       //do something
    }
});

QR Code encoding and decoding using zxing

I tried using ISO-8859-1 as said in the first answer. All went ok on encoding, but when I tried to get the byte[] using result string on decoding, all negative bytes became the character 63 (question mark). The following code does not work:

// Encoding works great
byte[] contents = new byte[]{-1};
QRCodeWriter codeWriter = new QRCodeWriter();
BitMatrix bitMatrix = codeWriter.encode(new String(contents, Charset.forName("ISO-8859-1")), BarcodeFormat.QR_CODE, w, h);

// Decodes like this fails
LuminanceSource ls = new BufferedImageLuminanceSource(encodedBufferedImage);
Result result = new QRCodeReader().decode(new BinaryBitmap( new HybridBinarizer(ls)));
byte[] resultBytes = result.getText().getBytes(Charset.forName("ISO-8859-1")); // a byte[] with byte 63 is given
return resultBytes;

It looks so strange because the API in a very old version (don't know exactly) had a method thar works well:

Vector byteSegments = result.getByteSegments();

So I tried to search why this method was removed and realized that there is a way to get ByteSegments, through metadata. So my decode method looks like:

// Decodes like this works perfectly
LuminanceSource ls = new BufferedImageLuminanceSource(encodedBufferedImage);
Result result = new QRCodeReader().decode(new BinaryBitmap( new HybridBinarizer(ls)));
Vector byteSegments = (Vector) result.getResultMetadata().get(ResultMetadataType.BYTE_SEGMENTS);  
int i = 0;
int tam = 0;
for (Object o : byteSegments) {
    byte[] bs = (byte[])o;
    tam += bs.length;
}
byte[] resultBytes = new byte[tam];
i = 0;
for (Object o : byteSegments) {
    byte[] bs = (byte[])o;
    for (byte b : bs) {
        resultBytes[i++] = b;
    }
}
return resultBytes;

Reading e-mails from Outlook with Python through MAPI

Sorry for my bad English. Checking Mails using Python with MAPI is easier,

outlook =win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders[5]
Subfldr = folder.Folders[5]
messages_REACH = Subfldr.Items
message = messages_REACH.GetFirst()

Here we can get the most first mail into the Mail box, or into any sub folder. Actually, we need to check the Mailbox number & orientation. With the help of this analysis we can check each mailbox & its sub mailbox folders.

Similarly please find the below code, where we can see, the last/ earlier mails. How we need to check.

`outlook =win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders[5]
Subfldr = folder.Folders[5]
messages_REACH = Subfldr.Items
message = messages_REACH.GetLast()`

With this we can get most recent email into the mailbox. According to the above mentioned code, we can check our all mail boxes, & its sub folders.

What does the fpermissive flag do?

The -fpermissive flag causes the compiler to report some things that are actually errors (but are permitted by some compilers) as warnings, to permit code to compile even if it doesn't conform to the language rules. You really should fix the underlying problem. Post the smallest, compilable code sample that demonstrates the problem.

-fpermissive
Downgrade some diagnostics about nonconformant code from errors to warnings. Thus, using -fpermissive will allow some nonconforming code to compile.

Send POST request with JSON data using Volley

final String URL = "/volley/resource/12";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "AbCdEfGh123456");

JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
       new Response.Listener<JSONObject>() {
           @Override
           public void onResponse(JSONObject response) {
               try {
                   VolleyLog.v("Response:%n %s", response.toString(4));
               } catch (JSONException e) {
                   e.printStackTrace();
               }
           }
       }, new Response.ErrorListener() {
           @Override
           public void onErrorResponse(VolleyError error) {
               VolleyLog.e("Error: ", error.getMessage());
           }
       });

// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);

refer

How to stop/kill a query in postgresql?

What I did is first check what are the running processes by

SELECT * FROM pg_stat_activity WHERE state = 'active';

Find the process you want to kill, then type:

SELECT pg_cancel_backend(<pid of the process>)

This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.

If the process cannot be killed, try:

SELECT pg_terminate_backend(<pid of the process>)

Retrieve version from maven pom.xml in code

If you use mvn packaging such as jar or war, use:

getClass().getPackage().getImplementationVersion()

It reads a property "Implementation-Version" of the generated META-INF/MANIFEST.MF (that is set to the pom.xml's version) in the archive.

how to set imageview src?

What you are looking for is probably this:

ImageView myImageView;
myImageView = mDialog.findViewById(R.id.image_id);
String src = "imageFileName"

int drawableId = this.getResources().getIdentifier(src, "drawable", context.getPackageName())
popupImageView.setImageResource(drawableId);

Let me know if this was helpful :)

Failed to import new Gradle project: failed to find Build Tools revision *.0.0

i think you can download the latest android SDK and use it.i do this and fixed the problem and work well. here is the link: http://developer.android.com/sdk/index.html#download

Need to ZIP an entire directory using Node.js

To include all files and directories:

archive.bulk([
  {
    expand: true,
    cwd: "temp/freewheel-bvi-120",
    src: ["**/*"],
    dot: true
  }
]);

It uses node-glob(https://github.com/isaacs/node-glob) underneath, so any matching expression compatible with that will work.

sys.argv[1], IndexError: list index out of range

sys.argv represents the command line options you execute a script with.

sys.argv[0] is the name of the script you are running. All additional options are contained in sys.argv[1:].

You are attempting to open a file that uses sys.argv[1] (the first argument) as what looks to be the directory.

Try running something like this:

python ConcatenateFiles.py /tmp