Programs & Examples On #Sfinae

Substitution failure is not an error. This is a C++ programming technique that allows templates to verify properties about their template parameters, thus allowing different specializations to be used if certain kinds of objects are available.

Templated check for the existence of a class member function?

A simple solution for C++11:

template<class T>
auto optionalToString(T* obj)
 -> decltype(  obj->toString()  )
{
    return     obj->toString();
}
auto optionalToString(...) -> string
{
    return "toString not defined";
}

Update, 3 years later: (and this is untested). To test for the existence, I think this will work:

template<class T>
constexpr auto test_has_toString_method(T* obj)
 -> decltype(  obj->toString() , std::true_type{} )
{
    return     obj->toString();
}
constexpr auto test_has_toString_method(...) -> std::false_type
{
    return "toString not defined";
}

How can I add reflection to a C++ application?

I think you might find interesting the article "Using Templates for Reflection in C++" by Dominic Filion. It is in section 1.4 of Game Programming Gems 5. Unfortunately I dont have my copy with me, but look for it because I think it explains what you are asking for.

Confused about Service vs Factory

There are three ways of handling business logic in AngularJS: (Inspired by Yaakov's Coursera AngularJS course) which are:

  1. Service
  2. Factory
  3. Provider

Here we are only going to talk about Service vs Factory

SERVICE:

Syntax:

app.js

 var app = angular.module('ServiceExample',[]);
 var serviceExampleController =
              app.controller('ServiceExampleController', ServiceExampleController);
 var serviceExample = app.service('NameOfTheService', NameOfTheService);

 ServiceExampleController.$inject = ['NameOfTheService'] //very important as this protects from minification of js files

function ServiceExampleController(NameOfTheService){
     serviceExampleController = this;
     serviceExampleController.data = NameOfTheService.getSomeData();
 }

function NameOfTheService(){
     nameOfTheService = this;
     nameOfTheService.data = "Some Data";
     nameOfTheService.getSomeData = function(){
           return nameOfTheService.data;
     }     
}

index.html

<div ng-controller = "ServiceExampleController as serviceExample">
   {{serviceExample.data}}
</div>

The main features of Service:

  1. Lazily Instantiated: If the service is not injected it won't be instantiated ever. So to use it you will have to inject it to a module.

  2. Singleton: If it is injected to multiple modules, all will have access to only one particular instance. That is why, it is very convenient to share data across different controllers.

FACTORY

Now let's talk about the Factory in AngularJS

First let's have a look at the syntax:

app.js:

var app = angular.module('FactoryExample',[]);
var factoryController = app.controller('FactoryController', FactoryController);
var factoryExampleOne = app.factory('NameOfTheFactoryOne', NameOfTheFactoryOne);
var factoryExampleTwo = app.factory('NameOfTheFactoryTwo', NameOfTheFactoryTwo);

//first implementation where it returns a function
function NameOfTheFactoryOne(){
   var factory = function(){
      return new SomeService();
    }
   return factory;
}

//second implementation where an object literal would be returned
function NameOfTheFactoryTwo(){
   var factory = {
      getSomeService : function(){
          return new SomeService();
       }
    };
   return factory;
}

Now using the above two in the controller:

 var factoryOne = NameOfTheFactoryOne() //since it returns a function
 factoryOne.someMethod();

 var factoryTwo = NameOfTheFactoryTwo.getSomeService(); //accessing the object
 factoryTwo.someMethod();

Features of Factory:

  1. This types of services follow the factory design pattern. The factory can be thought of as a central place that creates new objects or methods.

  2. This does not only produce singleton, but also customizable services.

  3. The .service() method is a factory that always produces the same type of service, which is a singleton. There is no easy way to configure it's behavior. That .service() method is usually used as a shortcut for something that doesn't require any configuration whatsoever.

How to make a TextBox accept only alphabetic characters?

Here is my solution and it works as planned:

string errmsg = "ERROR : Wrong input";
ErrorLbl.Text = errmsg;

if (e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space))
{
  ErrorLbl.Text = "ERROR : Wrong input";
}
else ErrorLbl.Text = string.Empty;
if (ErrorLbl.Text == errmsg)
{
  Nametxt.Text = string.Empty;
}

Is it possible to run an .exe or .bat file on 'onclick' in HTML

You can not run/execute an .exe file that is in the users local machine or through a site. The user must first download the exe file and then run the executable file.
So there is no possible way

The following code works only when the EXE is Present in the User's Machine.

<a href = "C:\folder_name\program.exe">

What is the difference between "word-break: break-all" versus "word-wrap: break-word" in CSS

At least in Firefox (as of v24) and Chrome (as of v30), when applied to content in a table element:

word-wrap:break-word

will not actually cause long words to wrap, which can result in the table exceeding the bounds of its container;

word-break:break-all

will result in words wrapping, and the table fitting within its container.

enter image description here

jsfiddle demo.

Spring Boot - Loading Initial Data

If I just want to insert simple test data I often implement a ApplicationRunner. Implementations of this interface are run at application startup and can use e.g. a autowired repository to insert some test data.

I think such an implementation would be slightly more explicit than yours because the interface implies that your implementation contains something you would like to do directly after your application is ready.

Your implementation would look sth. like this:

@Component
public class DataLoader implements ApplicationRunner {

    private UserRepository userRepository;

    @Autowired
    public DataLoader(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public void run(ApplicationArguments args) {
        userRepository.save(new User("lala", "lala", "lala"));
    }
}

"Large data" workflows using pandas

I spotted this a little late, but I work with a similar problem (mortgage prepayment models). My solution has been to skip the pandas HDFStore layer and use straight pytables. I save each column as an individual HDF5 array in my final file.

My basic workflow is to first get a CSV file from the database. I gzip it, so it's not as huge. Then I convert that to a row-oriented HDF5 file, by iterating over it in python, converting each row to a real data type, and writing it to a HDF5 file. That takes some tens of minutes, but it doesn't use any memory, since it's only operating row-by-row. Then I "transpose" the row-oriented HDF5 file into a column-oriented HDF5 file.

The table transpose looks like:

def transpose_table(h_in, table_path, h_out, group_name="data", group_path="/"):
    # Get a reference to the input data.
    tb = h_in.getNode(table_path)
    # Create the output group to hold the columns.
    grp = h_out.createGroup(group_path, group_name, filters=tables.Filters(complevel=1))
    for col_name in tb.colnames:
        logger.debug("Processing %s", col_name)
        # Get the data.
        col_data = tb.col(col_name)
        # Create the output array.
        arr = h_out.createCArray(grp,
                                 col_name,
                                 tables.Atom.from_dtype(col_data.dtype),
                                 col_data.shape)
        # Store the data.
        arr[:] = col_data
    h_out.flush()

Reading it back in then looks like:

def read_hdf5(hdf5_path, group_path="/data", columns=None):
    """Read a transposed data set from a HDF5 file."""
    if isinstance(hdf5_path, tables.file.File):
        hf = hdf5_path
    else:
        hf = tables.openFile(hdf5_path)

    grp = hf.getNode(group_path)
    if columns is None:
        data = [(child.name, child[:]) for child in grp]
    else:
        data = [(child.name, child[:]) for child in grp if child.name in columns]

    # Convert any float32 columns to float64 for processing.
    for i in range(len(data)):
        name, vec = data[i]
        if vec.dtype == np.float32:
            data[i] = (name, vec.astype(np.float64))

    if not isinstance(hdf5_path, tables.file.File):
        hf.close()
    return pd.DataFrame.from_items(data)

Now, I generally run this on a machine with a ton of memory, so I may not be careful enough with my memory usage. For example, by default the load operation reads the whole data set.

This generally works for me, but it's a bit clunky, and I can't use the fancy pytables magic.

Edit: The real advantage of this approach, over the array-of-records pytables default, is that I can then load the data into R using h5r, which can't handle tables. Or, at least, I've been unable to get it to load heterogeneous tables.

How can you program if you're blind?

As many have pointed out, emacspeak has been the enduring solution cross platform for many of the older hackers out there. Since it supports Linux and Mac out of the box, it has become my prefered means of developing Windows egnostic projects.

To the issue of actually getting down syntax through an auditory one as opposed to a visual one, I have found that there exists a variety of techniques to get one close if not on the same playing field.

Auditory icons can stand in place for verbal descriptors for one example. You can, put tones for how far a line is indented. The longer the tone, the further the indent. Since tones can play in parallel with text to speech, the information comes through in the same timeframe and doesn't serialize the communication of something so basic.

Braille can quickly and precisely decode to the user the exact syntax of a line. This is something more useful for people who use braille in daily life; the biggest advantage is random access to the contents of the display. Refreshable units typically have router keys above each character cell which can place the cursor to that cell. No fiddling with arrow keys O(n) op vs O(1) access.

Auditory dimensionality (pitch, rate, volume, inflection, richness, stress, etc) can convey a concept (keyword, class, variable, error, etc). For example, comments can be read in a monotone inflection...suiting, if I might say so :).

Emacs and other editors to lesser extents (Visual Studio) allow a coder to peruse a program symantically (next block, fold block, down defun, jump to def, walk up the parse tree, etc). You can very quickly get the "big" picture of the structure of an entire project doing this; with extensions like Cedet, you can get the goodness of VS/Eclipse/etc cross platform and in a textual editor.

Could probably go on and on, but that in a nutshell, is the basis of why a few of us are out there hacking away in industry, adacdemia, or in our basements :).

php resize image on upload

<form action="<?php echo $_SERVER["PHP_SELF"];  ?>" method="post" enctype="multipart/form-data" id="something" class="uniForm">
    <input name="new_image" id="new_image" size="30" type="file" class="fileUpload" />
    <button name="submit" type="submit" class="submitButton">Upload Image</button>
</form>

<?php
    if(isset($_POST['submit'])){
      if (isset ($_FILES['new_image'])){              
          $imagename = $_FILES['new_image']['name'];
          $source = $_FILES['new_image']['tmp_name'];
          $target = "images/".$imagename;
          $type=$_FILES["new_image"]["type"];

          if($type=="image/jpeg" || $type=="image/jpg"){
          move_uploaded_file($source, $target);
          //orginal image making part

          $imagepath = $imagename;
          $save = "images/" . $imagepath; //This is the new file you saving
          $file = "images/" . $imagepath; //This is the original file
          list($width, $height) = getimagesize($file) ;
          $modwidth = 1000;
          $diff = $width / $modwidth;
          $modheight = $height / $diff;   
          $tn = imagecreatetruecolor($modwidth, $modheight) ;
          $image = imagecreatefromjpeg($file) ;
          imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;
          echo "Large image: <img src='images/".$imagepath."'><br>";                     
          imagejpeg($tn, $save, 100) ;

          //thumbnail image making part
          $save = "images/thumb/" . $imagepath; //This is the new file you saving
          $file = "images/" . $imagepath; //This is the original file   
          list($width, $height) = getimagesize($file) ;
          $modwidth = 150;
          $diff = $width / $modwidth;
          $modheight = $height / $diff;
          $tn = imagecreatetruecolor($modwidth, $modheight) ;
          $image = imagecreatefromjpeg($file) ;
          imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;
        //echo "Thumbnail: <img src='images/sml_".$imagepath."'>";
          imagejpeg($tn, $save, 100) ;
          }
        else{
            echo "File is not image";
            }
      }
    }
?>

Disable all dialog boxes in Excel while running VB script?

Have you tried using the ConflictResolution:=xlLocalSessionChanges parameter in the SaveAs method?

As so:

Public Sub example()
Application.DisplayAlerts = False
Application.EnableEvents = False

For Each element In sArray
    XLSMToXLSX(element)
Next element

Application.DisplayAlerts = False
Application.EnableEvents = False
End Sub

Sub XLSMToXLSX(ByVal file As String)
    Do While WorkFile <> ""
        If Right(WorkFile, 4) <> "xlsx" Then
            Workbooks.Open Filename:=myPath & WorkFile

            Application.DisplayAlerts = False
            Application.EnableEvents = False

            ActiveWorkbook.SaveAs Filename:= _
            modifiedFileName, FileFormat:= _
            xlOpenXMLWorkbook, CreateBackup:=False, _
            ConflictResolution:=xlLocalSessionChanges

            Application.DisplayAlerts = True
            Application.EnableEvents = True

            ActiveWorkbook.Close
        End If
        WorkFile = Dir()
    Loop
End Sub

What is use of c_str function In c++

c_str returns a const char* that points to a null-terminated string (i.e. a C-style string). It is useful when you want to pass the "contents"¹ of an std::string to a function that expects to work with a C-style string.

For example, consider this code:

std::string str("Hello world!");
int pos1 = str.find_first_of('w');

int pos2 = strchr(str.c_str(), 'w') - str.c_str();

if (pos1 == pos2) {
    printf("Both ways give the same result.\n");
}

See it in action.

Notes:

¹ This is not entirely true because an std::string (unlike a C string) can contain the \0 character. If it does, the code that receives the return value of c_str() will be fooled into thinking that the string is shorter than it really is, since it will interpret \0 as the end of the string.

What is the Python 3 equivalent of "python -m SimpleHTTPServer"

From the docs:

The SimpleHTTPServer module has been merged into http.server in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0.

So, your command is python -m http.server, or depending on your installation, it can be:

python3 -m http.server

Add Text on Image using PIL

First, you have to download a font type...for example: https://www.wfonts.com/font/microsoft-sans-serif.

After that, use this code to draw the text:

from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw 
img = Image.open("filename.jpg")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(r'filepath\..\sans-serif.ttf', 16)
draw.text((0, 0),"Draw This Text",(0,0,0),font=font) # this will draw text with Blackcolor and 16 size

img.save('sample-out.jpg')

Insert/Update/Delete with function in SQL Server

Yes, you can.

However, it requires SQL CLR with EXTERNAL_ACCESS or UNSAFE permission and specifying a connection string. This is obviously not recommended.

For example, using Eval SQL.NET (a SQL CLR which allow to add C# syntax in SQL)

CREATE FUNCTION [dbo].[fn_modify_table_state]
    (
      @conn VARCHAR(8000) ,
      @sql VARCHAR(8000)
    )
RETURNS INT
AS
    BEGIN
        RETURN SQLNET::New('
using(var connection = new SqlConnection(conn))
{
    connection.Open();

    using(var command = new SqlCommand(sql, connection))
    {
        return command.ExecuteNonQuery();
    }
}
').ValueString('conn', @conn).ValueString('sql', @sql).EvalReadAccessInt()

    END

    GO

DECLARE @conn VARCHAR(8000) = 'Data Source=XPS8700;Initial Catalog=SqlServerEval_Debug;Integrated Security=True'
DECLARE @sql VARCHAR(8000) = 'UPDATE [Table_1] SET Value = -1 WHERE Name = ''zzz'''

DECLARE @rowAffecteds INT =  dbo.fn_modify_table_state(@conn, @sql)

Documentation: Modify table state within a SQL Function

Disclaimer: I'm the owner of the project Eval SQL.NET

Sort a Map<Key, Value> by values

If there is a preference of having a Map data structure that inherently sorts by values without having to trigger any sort methods or explicitly pass to a utility, then the following solutions may be applicable:

(1) org.drools.chance.core.util.ValueSortedMap (JBoss project) maintains two maps internally one for lookup and one for maintaining the sorted values. Quite similar to previously added answers, but probably it is the abstraction and encapsulation part (including copying mechanism) that makes it safer to use from the outside.

(2) http://techblog.molindo.at/2008/11/java-map-sorted-by-value.html avoids maintaining two maps and instead relies/extends from Apache Common's LinkedMap. (Blog author's note: as all the code here is in the public domain):

// required to access LinkEntry.before and LinkEntry.after
package org.apache.commons.collections.map;

// SNIP: imports

/**
* map implementation based on LinkedMap that maintains a sorted list of
* values for iteration
*/
public class ValueSortedHashMap extends LinkedMap {
    private final boolean _asc;

    // don't use super()!
    public ValueSortedHashMap(final boolean asc) {
        super(DEFAULT_CAPACITY);
        _asc = asc;
    }

    // SNIP: some more constructors with initial capacity and the like

    protected void addEntry(final HashEntry entry, final int hashIndex) {
        final LinkEntry link = (LinkEntry) entry;
        insertSorted(link);
        data[hashIndex] = entry;
    }

    protected void updateEntry(final HashEntry entry, final Object newValue) {
        entry.setValue(newValue);
        final LinkEntry link = (LinkEntry) entry;
        link.before.after = link.after;
        link.after.before = link.before;
        link.after = link.before = null;
        insertSorted(link);
    }

    private void insertSorted(final LinkEntry link) {
        LinkEntry cur = header;
        // iterate whole list, could (should?) be replaced with quicksearch
        // start at end to optimize speed for in-order insertions
        while ((cur = cur.before) != header & amp; & amp; !insertAfter(cur, link)) {}
        link.after = cur.after;
        link.before = cur;
        cur.after.before = link;
        cur.after = link;
    }

    protected boolean insertAfter(final LinkEntry cur, final LinkEntry link) {
        if (_asc) {
            return ((Comparable) cur.getValue())
            .compareTo((V) link.getValue()) & lt; = 0;
        } else {
            return ((Comparable) cur.getValue())
            .compareTo((V) link.getValue()) & gt; = 0;
        }
    }

    public boolean isAscending() {
        return _asc;
    }
}

(3) Write a custom Map or extends from LinkedHashMap that will only sort during enumeration (e.g., values(), keyset(), entryset()) as needed. The inner implementation/behavior is abstracted from the one using this class but it appears to the client of this class that values are always sorted when requested for enumeration. This class hopes that sorting will happen mostly once if all put operations have been completed before enumerations. Sorting method adopts some of the previous answers to this question.

public class SortByValueMap<K, V> implements Map<K, V> {

    private boolean isSortingNeeded = false;

    private final Map<K, V> map = new LinkedHashMap<>();

    @Override
    public V put(K key, V value) {
        isSortingNeeded = true;
        return map.put(key, value);
    }

    @Override
    public void putAll(Map<? extends K, ? extends V> map) {
        isSortingNeeded = true;
        map.putAll(map);
    }

    @Override
    public Set<K> keySet() {
        sort();
        return map.keySet();
    }

    @Override
    public Set<Entry<K, V>> entrySet() {
        sort();
        return map.entrySet();
    }

    @Override
    public Collection<V> values() {
        sort();
        return map.values();
    }

    private void sort() {
        if (!isSortingNeeded) {
            return;
        }

        List<Entry<K, V>> list = new ArrayList<>(size());

        for (Iterator<Map.Entry<K, V>> it = map.entrySet().iterator(); it.hasNext();) {
            Map.Entry<K, V> entry = it.next();
            list.add(entry);
            it.remove();
        }

        Collections.sort(list);

        for (Entry<K, V> entry : list) {
            map.put(entry.getKey(), entry.getValue());
        }

        isSortingNeeded = false;
    }

    @Override
    public String toString() {
        sort();
        return map.toString();
    }
}

(4) Guava offers ImmutableMap.Builder.orderEntriesByValue(Comparator valueComparator) although the resulting map will be immutable:

Configures this Builder to order entries by value according to the specified comparator.

The sort order is stable, that is, if two entries have values that compare as equivalent, the entry that was inserted first will be first in the built map's iteration order.

Is it possible to program Android to act as physical USB keyboard?

I believe that you can do it if you have a rooted device with a recent Android. For example, the Asus Eee Pad Transformer running Android 4 has the libraries /system/lib/libusb.so and /system/lib/libusbhost.so, so you can write a Java application that calls them using JNI to emulate a USB keyboard. This means that you must write some glue C code that emulates the way a USB keyboard is communicating with a PC (=you must study the way the USB protocol works).

I say "rooted", because some permissions are usually needed to use these libraries.

Edit: The above is true when programming an Android device to act as a USB host, in your case you need to be a "gadget". I don't know how much of the Linux gadget functionality is contained in the kernel of your Android device. See this for a similar question.

How to implement authenticated routes in React Router 4?

Based on the answer of @Tyler McGinnis. I made a different approach using ES6 syntax and nested routes with wrapped components:

import React, { cloneElement, Children } from 'react'
import { Route, Redirect } from 'react-router-dom'

const PrivateRoute = ({ children, authed, ...rest }) =>
  <Route
    {...rest}
    render={(props) => authed ?
      <div>
        {Children.map(children, child => cloneElement(child, { ...child.props }))}
      </div>
      :
      <Redirect to={{ pathname: '/', state: { from: props.location } }} />}
  />

export default PrivateRoute

And using it:

<BrowserRouter>
  <div>
    <PrivateRoute path='/home' authed={auth}>
      <Navigation>
        <Route component={Home} path="/home" />
      </Navigation>
    </PrivateRoute>

    <Route exact path='/' component={PublicHomePage} />
  </div>
</BrowserRouter>

How to check the extension of a filename in a bash script?

I wrote a bash script that looks at the type of a file then copies it to a location, I use it to look through the videos I've watched online from my firefox cache:

#!/bin/bash
# flvcache script

CACHE=~/.mozilla/firefox/xxxxxxxx.default/Cache
OUTPUTDIR=~/Videos/flvs
MINFILESIZE=2M

for f in `find $CACHE -size +$MINFILESIZE`
do
    a=$(file $f | cut -f2 -d ' ')
    o=$(basename $f)
    if [ "$a" = "Macromedia" ]
        then
            cp "$f" "$OUTPUTDIR/$o"
    fi
done

nautilus  "$OUTPUTDIR"&

It uses similar ideas to those presented here, hope this is helpful to someone.

How to move div vertically down using CSS

A standard width space for a standard 16px font is 4px.

Source: http://jkorpela.fi/styles/spaces.html

Bulk Record Update with SQL

The SQL you posted in your question is one way to do it. Most things in SQL have more than one way to do it.

UPDATE
  [Table1] 
SET
  [Description]=(SELECT [Description] FROM [Table2] t2 WHERE t2.[ID]=Table1.DescriptionID)

If you are planning on running this on a PROD DB, it is best to create a snapshot or mirror of it first and test it out. Verify the data ends up as you expect for a couple records. And if you are satisfied, run it on the real DB.

Why is Node.js single threaded?

Long story short, node draws from V8, which is internally single-threaded. There are ways to work around the constraints for CPU-intensive tasks.

At one point (0.7) the authors tried to introduce isolates as a way of implementing multiple threads of computation, but were ultimately removed: https://groups.google.com/forum/#!msg/nodejs/zLzuo292hX0/F7gqfUiKi2sJ

sed command with -i option failing on Mac, but works on Linux

Here's how to apply environment variables to template file (no backup need).

1. Create template with {{FOO}} for later replace.

echo "Hello {{FOO}}" > foo.conf.tmpl

2. Replace {{FOO}} with FOO variable and output to new foo.conf file

FOO="world" && sed -e "s/{{FOO}}/$FOO/g" foo.conf.tmpl > foo.conf

Working both macOS 10.12.4 and Ubuntu 14.04.5

How to force a line break on a Javascript concatenated string?

You can't have multiple lines in a text box, you need a textarea. Then it works with \n between the values.

Rails ActiveRecord date between

This code should work for you:

Comment.find(:all, :conditions => {:created_at => @selected_date.beginning_of_day..@selected_date.end_of_day})

For more info have a look at Time calculations

Note: This code is deprecated. Use the code from the answer if you are using Rails 3.1/3.2

Make index.html default, but allow index.php to be visited if typed in

I agree with @TheAlpha's accepted answer, Apache reads the DirectoryIndex target files from left to right , if the first file exists ,apche serves it and if it doesnt then the next file is served as an index for the directory. So if you have the following Directive :

DirectoryIndex file1.html file2.html

Apache will serve /file.html as index ,You will need to change the order of files if you want to set /file2.html as index

DirectoryIndex file2.html file1.html

You can also set index file using a RewriteRule

RewriteEngine on

RewriteRule ^$ /index.html [L]

RewriteRule above will rewrite your homepage to /index.html the rewriting happens internally so http://example.com/ would show you the contents ofindex.html .

:first-child not working as expected

You could wrap your h1 tags in another div and then the first one would be the first-child. That div doesn't even need styles. It's just a way to segregate those children.

<div class="h1-holder">
    <h1>Title 1</h1>
    <h1>Title 2</h1>
</div>

How to apply multiple transforms in CSS?

You have to put them on one line like this:

li:nth-child(2) {
    transform: rotate(15deg) translate(-20px,0px);
}

When you have multiple transform directives, only the last one will be applied. It's like any other CSS rule.


Keep in mind multiple transform one line directives are applied from right to left.

This: transform: scale(1,1.5) rotate(90deg);
and: transform: rotate(90deg) scale(1,1.5);

will not produce the same result:

_x000D_
_x000D_
.orderOne, .orderTwo {_x000D_
  font-family: sans-serif;_x000D_
  font-size: 22px;_x000D_
  color: #000;_x000D_
  display: inline-block;_x000D_
}_x000D_
_x000D_
.orderOne {_x000D_
  transform: scale(1, 1.5) rotate(90deg);_x000D_
}_x000D_
_x000D_
.orderTwo {_x000D_
  transform: rotate(90deg) scale(1, 1.5);_x000D_
}
_x000D_
<div class="orderOne">_x000D_
  A_x000D_
</div>_x000D_
_x000D_
<div class="orderTwo">_x000D_
  A_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I get the index from a JSON object with value?

Once you have a json object

obj.valueOf(Object.keys(obj).indexOf('String_to_Find'))

How can I "disable" zoom on a mobile web page?

You can accomplish the task by simply adding the following 'meta' element into your 'head':

<meta name="viewport" content="user-scalable=no">

Adding all the attributes like 'width','initial-scale', 'maximum-width', 'maximum-scale' might not work. Therefore, just add the above element.

Color Tint UIButton Image

Not sure exactly what you want but this category method will mask a UIImage with a specified color so you can have a single image and change its color to whatever you want.

ImageUtils.h

- (UIImage *) maskWithColor:(UIColor *)color;

ImageUtils.m

-(UIImage *) maskWithColor:(UIColor *)color 
{
    CGImageRef maskImage = self.CGImage;
    CGFloat width = self.size.width;
    CGFloat height = self.size.height;
    CGRect bounds = CGRectMake(0,0,width,height);

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef bitmapContext = CGBitmapContextCreate(NULL, width, height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
    CGContextClipToMask(bitmapContext, bounds, maskImage);
    CGContextSetFillColorWithColor(bitmapContext, color.CGColor);    
    CGContextFillRect(bitmapContext, bounds);

    CGImageRef cImage = CGBitmapContextCreateImage(bitmapContext);
    UIImage *coloredImage = [UIImage imageWithCGImage:cImage];

    CGContextRelease(bitmapContext);
    CGColorSpaceRelease(colorSpace);
    CGImageRelease(cImage);

    return coloredImage;    
}

Import the ImageUtils category and do something like this...

#import "ImageUtils.h"

...

UIImage *icon = [UIImage imageNamed:ICON_IMAGE];

UIImage *redIcon = [icon maskWithColor:UIColor.redColor];
UIImage *blueIcon = [icon maskWithColor:UIColor.blueColor];

Why SQL Server throws Arithmetic overflow error converting int to data type numeric?

NUMERIC(3,2) means: 3 digits in total, 2 after the decimal point. So you only have a single decimal before the decimal point.

Try NUMERIC(5,2) - three before, two after the decimal point.

List files ONLY in the current directory

Just use os.listdir and os.path.isfile instead of os.walk.

Example:

import os
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
    # do something

But be careful while applying this to other directory, like

files = [f for f in os.listdir(somedir) if os.path.isfile(f)].

which would not work because f is not a full path but relative to the current dir.

Therefore, for filtering on another directory, do os.path.isfile(os.path.join(somedir, f))

(Thanks Causality for the hint)

How to restrict the selectable date ranges in Bootstrap Datepicker?

Another possibility is to use the options with data attributes, like this(minimum date 1 week before):

<input class='datepicker' data-date-start-date="-1w">

More info: http://bootstrap-datepicker.readthedocs.io/en/latest/options.html

How to get a file or blob from an object URL?

See Getting BLOB data from XHR request which points out that BlobBuilder doesn't work in Chrome so you need to use:

xhr.responseType = 'arraybuffer';

How to serialize a JObject without the formatting?

Call JObject's ToString(Formatting.None) method.

Alternatively if you pass the object to the JsonConvert.SerializeObject method it will return the JSON without formatting.

Documentation: Write JSON text with JToken.ToString

What's the difference between "Solutions Architect" and "Applications Architect"?

An 'architect' is the title given to someone who can design multiple layers of applications that work together well at a high level. Anything that gets into a generic type of 'architect' without a specific type of technology (i.e. "Solutions", "Applications", "Business", etc) is marketing speak.

How to solve munmap_chunk(): invalid pointer error in C++

The hint is, the output file is created even if you get this error. The automatic deconstruction of vector starts after your code executed. Elements in the vector are deconstructed as well. This is most probably where the error occurs. The way you access the vector is through vector::operator[] with an index read from stream. Try vector::at() instead of vector::operator[]. This won't solve your problem, but will show which assignment to the vector causes error.

Commenting out a set of lines in a shell script

As per this site:

#!/bin/bash
foo=bar
: '
This is a test comment
Author foo bar
Released under GNU 
'

echo "Init..."
# rest of script

How to create temp table using Create statement in SQL Server?

A temporary table can have 3 kinds, the # is the most used. This is a temp table that only exists in the current session. An equivalent of this is @, a declared table variable. This has a little less "functions" (like indexes etc) and is also only used for the current session. The ## is one that is the same as the #, however, the scope is wider, so you can use it within the same session, within other stored procedures.

You can create a temp table in various ways:

declare @table table (id int)
create table #table (id int)
create table ##table (id int)
select * into #table from xyz

python: how to identify if a variable is an array or a scalar

Simply use size instead of len!

>>> from numpy import size
>>> N = [2, 3, 5]
>>> size(N)
3
>>> N = array([2, 3, 5])
>>> size(N)
3
>>> P = 5
>>> size(P)
1

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

This is a very common question seen on Stackoverflow.

The important part here is not the command displayed in the error, but what the actual error tells you instead.

a Quick breakdown on why this error is received.

cmd.exe Being a terminal window relies on input and system Environment variables, in order to perform what you request it to do. it does NOT know the location of everything and it also does not know when to distinguish between commands or executable names which are separated by whitespace like space and tab or commands with whitespace as switch variables.

How do I fix this:

When Actual Command/executable fails

First we make sure, is the executable actually installed? If yes, continue with the rest, if not, install it first.

If you have any executable which you are attempting to run from cmd.exe then you need to tell cmd.exe where this file is located. There are 2 ways of doing this.

  1. specify the full path to the file.

    "C:\My_Files\mycommand.exe"

  2. Add the location of the file to your environment Variables.

Goto:
------> Control Panel-> System-> Advanced System Settings->Environment Variables

In the System Variables Window, locate path and select edit

Now simply add your path to the end of the string, seperated by a semicolon ; as:

;C:\My_Files\

Save the changes and exit. You need to make sure that ANY cmd.exe windows you had open are then closed and re-opened to allow it to re-import the environment variables. Now you should be able to run mycommand.exe from any path, within cmd.exe as the environment is aware of the path to it.

When C:\Program or Similar fails

This is a very simple error. Each string after a white space is seen as a different command in cmd.exe terminal, you simply have to enclose the entire path in double quotes in order for cmd.exe to see it as a single string, and not separate commands.

So to execute C:\Program Files\My-App\Mobile.exe simply run as:

"C:\Program Files\My-App\Mobile.exe"

About catching ANY exception

You can do this to handle general exceptions

try:
    a = 2/0
except Exception as e:
    print e.__doc__
    print e.message

java.util.zip.ZipException: duplicate entry during packageAllDebugClassesForMultiDex

Try this:

android {
configurations {
        all*.exclude  module: 'PhotoView'  //???????
    }
}

How to convert a String to Bytearray

String.prototype.encodeHex = function () {
    return this.split('').map(e => e.charCodeAt())
};

String.prototype.decodeHex = function () {    
    return this.map(e => String.fromCharCode(e)).join('')
};

How to cut first n and last n columns?

To use AWK to cut off the first and last fields:

awk '{$1 = ""; $NF = ""; print}' inputfile

Unfortunately, that leaves the field separators, so

aaa bbb ccc

becomes

[space]bbb[space]

To do this using kurumi's answer which won't leave extra spaces, but in a way that's specific to your requirements:

awk '{delim = ""; for (i=2;i<=NF-1;i++) {printf delim "%s", $i; delim = OFS}; printf "\n"}' inputfile

This also fixes a couple of problems in that answer.

To generalize that:

awk -v skipstart=1 -v skipend=1 '{delim = ""; for (i=skipstart+1;i<=NF-skipend;i++) {printf delim "%s", $i; delim = OFS}; printf "\n"}' inputfile

Then you can change the number of fields to skip at the beginning or end by changing the variable assignments at the beginning of the command.

An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll

In static class, if you are getting information from xml or reg, class tries to initialize all properties. therefore, you should control if the config variable is there otherwise properties will not initialize so the class.

Check xml referance variable is there, Check reg referance variable is is there, Make sure you handle if they are not there.

How to align absolutely positioned element to center?

Move the parent div to the middle with

left: 50%;
top: 50%;
margin-left: -50px;

Move the second layer over the other with

position: relative;
left: -100px;

Git, fatal: The remote end hung up unexpectedly

Seems like it can be one of a thousand things.

For me, I was initially pushing master and develop (master had no changes) via SourceTree. Changing this to develop only worked.

Get bytes from std::string in C++

Normally, encryption functions take

encrypt(const void *ptr, size_t bufferSize);

as arguments. You can pass c_str and length directly:

encrypt(strng.c_str(), strng.length());

This way, extra space is allocated or wasted.

run program in Python shell

It depends on what is in test.py. The following is an appropriate structure:

# suppose this is your 'test.py' file
def main():
 """This function runs the core of your program"""
 print("running main")

if __name__ == "__main__":
 # if you call this script from the command line (the shell) it will
 # run the 'main' function
 main()

If you keep this structure, you can run it like this in the command line (assume that $ is your command-line prompt):

$ python test.py
$ # it will print "running main"

If you want to run it from the Python shell, then you simply do the following:

>>> import test
>>> test.main() # this calls the main part of your program

There is no necessity to use the subprocess module if you are already using Python. Instead, try to structure your Python files in such a way that they can be run both from the command line and the Python interpreter.

ImportError: Cannot import name X

Also not directly relevant to the OP, but failing to restart a PyCharm Python console, after adding a new object to a module, is also a great way to get a very confusing ImportError: Cannot import name ...

The confusing part is that PyCharm will autocomplete the import in the console, but the import then fails.

How to create a Rectangle object in Java using g.fillRect method

Try this:

public void paint (Graphics g) {    
    Rectangle r = new Rectangle(xPos,yPos,width,height);
    g.fillRect(r.getX(), r.getY(), r.getWidth(), r.getHeight());  
}

[edit]

// With explicit casting
public void paint (Graphics g) {    
        Rectangle r = new Rectangle(xPos, yPos, width, height);
        g.fillRect(
           (int)r.getX(),
           (int)r.getY(),
           (int)r.getWidth(),
           (int)r.getHeight()
        );  
    }

How to hide UINavigationBar 1px bottom line

Here's another option - I think this only works if you don't require translucency on your nav bar (I didn't). I just added a 1 pixel high UIView to the bottom of the nav bar (1 pixel below the nav bar) with the same colour as my nav bar:

UIView *view = [[UIView alloc] init];
[view setBackgroundColor:self.navigationController.navigationBar.barTintColor];
[self.navigationController.navigationBar addSubview:view];
[view mas_makeConstraints:^(MASConstraintMaker *make) {
    make.height.equalTo(@(1.0f));
    make.leading.trailing.equalTo(self.navigationController.navigationBar);
    make.bottom.equalTo(self.navigationController.navigationBar).offset(1.0f);
}];

I'm adding the constraints using Masonry.

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

In the Global.asax I am using the code below. My URI to get JSON is http://www.digantakumar.com/api/values?json=true

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new  QueryStringMapping("json", "true", "application/json"));
}

How to refresh table contents in div using jquery/ajax

You can load HTML page partial, in your case is everything inside div#mytable.

setTimeout(function(){
   $( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds

more information read this http://api.jquery.com/load/

Update Code (if you don't want it auto-refresh)

<button id="refresh-btn">Refresh Table</button>

<script>
$(document).ready(function() {

   function RefreshTable() {
       $( "#mytable" ).load( "your-current-page.html #mytable" );
   }

   $("#refresh-btn").on("click", RefreshTable);

   // OR CAN THIS WAY
   //
   // $("#refresh-btn").on("click", function() {
   //    $( "#mytable" ).load( "your-current-page.html #mytable" );
   // });


});
</script>

create multiple tag docker image

docker build  -t name1:tag1 -t name2:tag2 -f Dockerfile.ui .

Print content of JavaScript object?

Javascript for all!

String.prototype.repeat = function(num) {
    if (num < 0) {
        return '';
    } else {
        return new Array(num + 1).join(this);
    }
};

function is_defined(x) {
    return typeof x !== 'undefined';
}

function is_object(x) {
    return Object.prototype.toString.call(x) === "[object Object]";
}

function is_array(x) {
    return Object.prototype.toString.call(x) === "[object Array]";
}

/**
 * Main.
 */
function xlog(v, label) {
    var tab = 0;

    var rt = function() {
        return '    '.repeat(tab);
    };

    // Log Fn
    var lg = function(x) {
        // Limit
        if (tab > 10) return '[...]';
        var r = '';
        if (!is_defined(x)) {
            r = '[VAR: UNDEFINED]';
        } else if (x === '') {
            r = '[VAR: EMPTY STRING]';
        } else if (is_array(x)) {
            r = '[\n';
            tab++;
            for (var k in x) {
                r += rt() + k + ' : ' + lg(x[k]) + ',\n';
            }
            tab--;
            r += rt() + ']';
        } else if (is_object(x)) {
            r = '{\n';
            tab++;
            for (var k in x) {
                r += rt() + k + ' : ' + lg(x[k]) + ',\n';
            }
            tab--;
            r += rt() + '}';
        } else {
            r = x;
        }
        return r;
    };

    // Space
    document.write('\n\n');

    // Log
    document.write('< ' + (is_defined(label) ? (label + ' ') : '') + Object.prototype.toString.call(v) + ' >\n' + lg(v));
};



// Demo //

var o = {
    'aaa' : 123,
    'bbb' : 'zzzz',
    'o' : {
        'obj1' : 'val1',
        'obj2' : 'val2',
        'obj3' : [1, 3, 5, 6],
        'obj4' : {
            'a' : 'aaaa',
            'b' : null
        }
    },
    'a' : [ 'asd', 123, false, true ],
    'func' : function() {
        alert('test');
    },
    'fff' : false,
    't' : true,
    'nnn' : null
};

xlog(o, 'Object'); // With label
xlog(o); // Without label

xlog(['asd', 'bbb', 123, true], 'ARRAY Title!');

var no_definido;
xlog(no_definido, 'Undefined!');

xlog(true);

xlog('', 'Empty String');

Unable to simultaneously satisfy constraints, will attempt to recover by breaking constraint

None of the foregoing answers is helpful in my situation. I am running XCode 10.1 and testing my app on the simulator for an "iPad (5th generation)". The simulator is running iOS 12.1.

I've got a simple root view in my storyboard, with two UITextField subviews. There are no constraints being used in the storyboard at all. And I have no UIButtonBarView objects in the app or the storyboard.

No messages get printed when the app launches and lays the root view out. None when the simulated device is rotated.

But in the simulator, the moment I click on one of the text fields, the keyboard extension arises from the bottom of the screen, although not the full keyboard, which never seems to show up in the simulator. But the following is printed out on the terminal:

Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want. 
Try this: 
    (1) look at each constraint and try to figure out which you don't expect; 
    (2) find the code that added the unwanted constraint or constraints and fix it. 
(Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
"<NSAutoresizingMaskLayoutConstraint:0x6000034e7700 h=--& v=--& UIKeyboardAssistantBar:0x7f9c7d714af0.height == 0   (active)>",
"<NSLayoutConstraint:0x6000034aba20 V:|-(0)-[_UIUCBKBSelectionBackground:0x7f9c7d51ec70]   (active, names: '|':_UIButtonBarButton:0x7f9c7d51de40 )>",
"<NSLayoutConstraint:0x6000034aba70 _UIUCBKBSelectionBackground:0x7f9c7d51ec70.bottom == _UIButtonBarButton:0x7f9c7d51de40.bottom   (active)>",
"<NSLayoutConstraint:0x6000034fb3e0 V:|-(0)-[_UIButtonBarStackView:0x7f9c7d715880]   (active, names: '|':UIKeyboardAssistantBar:0x7f9c7d714af0 )>",
"<NSLayoutConstraint:0x6000034fb750 V:[_UIButtonBarStackView:0x7f9c7d715880]-(0)-|   (active, names: '|':UIKeyboardAssistantBar:0x7f9c7d714af0 )>",
"<NSLayoutConstraint:0x6000034abc00 'UIButtonBar.maximumAlignmentSize' _UIButtonBarButton:0x7f9c7d51de40.height == UILayoutGuide:0x600002ef4e00'UIViewLayoutMarginsGuide'.height   (active)>",
"<NSLayoutConstraint:0x6000034d7cf0 'UIView-bottomMargin-guide-constraint' V:[UILayoutGuide:0x600002ef4e00'UIViewLayoutMarginsGuide']-(9)-|   (active, names: '|':_UIButtonBarStackView:0x7f9c7d715880 )>",
"<NSLayoutConstraint:0x6000034d7c50 'UIView-topMargin-guide-constraint' V:|-(10)-[UILayoutGuide:0x600002ef4e00'UIViewLayoutMarginsGuide']   (active, names: '|':_UIButtonBarStackView:0x7f9c7d715880 )>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x6000034aba70 _UIUCBKBSelectionBackground:0x7f9c7d51ec70.bottom == _UIButtonBarButton:0x7f9c7d51de40.bottom   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.

It certainly appears to me that all this has to do with nothing in my app, and everything to do with how Apple is creating its own keyboard view, even with my small extension declared to be combined with it.

So the question remains, is there something I as an app developer am responsible for doing (on the presumption this is a bunch of stuff worth attending to) or is it just Apple's own problem/bug?

FWIW, this constraint problem message doesn't occur when simulating a newer iPad model, such as the iPad Pro 12.9-inch (3rd generation). But the message does show up when simulating an iPad Pro 9.7-inch". All claiming they're running iOS 12.1.

In Python, what happens when you import inside of a function?

It imports once when the function executes first time.

Pros:

  • imports related to the function they're used in
  • easy to move functions around the package

Cons:

  • couldn't see what modules this module might depend on

Font Awesome not working, icons showing as squares

Use this <i class="fa fa-camera-retro" ></i> you have not defined fa classes

Can an AJAX response set a cookie?

Yes, you can set cookie in the AJAX request in the server-side code just as you'd do for a normal request since the server cannot differentiate between a normal request or an AJAX request.

AJAX requests are just a special way of requesting to server, the server will need to respond back as in any HTTP request. In the response of the request you can add cookies.

Generate a dummy-variable

What I normally do to work with this kind of dummy variables is:

(1) how do I generate a dummy variable for observation #10, i.e. for year 1957 (value = 1 at 1957 and zero otherwise)

data$factor_year_1 <- factor ( with ( data, ifelse ( ( year == 1957 ), 1 , 0 ) ) )

(2) how do I generate a dummy-variable which is zero before 1957 and takes the value 1 from 1957 and onwards to 2009?

data$factor_year_2 <- factor ( with ( data, ifelse ( ( year < 1957 ), 0 , 1 ) ) )

Then, I can introduce this factor as a dummy variable in my models. For example, to see whether there is a long-term trend in a varible y :

summary ( lm ( y ~ t,  data = data ) )

Hope this helps!

How can I rebuild indexes and update stats in MySQL innoDB?

To date (mysql 8.0.18) there is no suitable function inside mysql to re-create indexes.
Since mysql 8.0 myisam is slowly phasing into deprecated status, innodb is the current main storage engine.
In most practical cases innodb is the best choice and it's supposed to keep indexes working well.
In most practical cases innodb also does a good job, you do not need to recreate indexes. Almost always.

When it comes to large tables with hundreds of GB data amd rows and a lot of writing the situation changes, indexes can degrade in performance.
In my personal case I've seen performance drop from ~15 minutes for a count(*) using a secondary index to 4300 minutes after 2 months of writing to the table with linear time increase.
After recreating the index the performance goes back to 15 minutes.

To date we have two options to do that:
1) OPTIMIZE TABLE (or ALTER TABLE)
Innodb doesn't support optimization so in both cases the entire table will be read and re-created.
This means you need the storage for the temporary file and depending on the table a lot of time (I've cases where an optimize takes a week to complete). This will compact the data and rebuild all indexes.
Despite not being officially recommended, I highly recommend the OPTIMIZE process on write-heavy tables up to 100GB in size.

2) ALTER TABLE DROP KEY -> ALTER TABLE ADD KEY
You manually drop the key by name, you manually create it again. In a production environment you'll want to create it first, then drop the old version.
The upside: this can be a lot faster than optimize. The downside: you need to manually create the syntax.
"SHOW CREATE TABLE" can be used to quickly see which indexes are available and how they are called.

Appendix:
1) To just update statistics you can use the already mentioned "ANALYZE TABLE".
2) If you experience performance degradation on write-heavy servers you might need to restart mysql. There are a couple of bugs in current mysql (8.0) that can cause significant slowdown without showing up in error log. Eventually those slowdowns lead to a server crash but it can take weeks or even months to build up to the crash, in this process the server gets slower and slower in responses.
3) If you wish to re-create a large table that takes weeks to complete or fails after hours due to internal data integrity problems you should do a CREATE TABLE LIKE, INSERT INTO SELECT *. then 'atomic RENAME' the tables.
4) If INSERT INTO SELECT * takes hours to days to complete on huge tables you can speed up the process by about 20-30 times using a multi-threaded approach. You "partition" the table into chunks and INSERT INTO SELECT * in parallel.

How to read values from properties file?

Here is an additional answer that was also great help for me to understand how it worked : http://www.javacodegeeks.com/2013/07/spring-bean-and-propertyplaceholderconfigurer.html

any BeanFactoryPostProcessor beans have to be declared with a static, modifier

@Configuration
@PropertySource("classpath:root/test.props")
public class SampleConfig {
 @Value("${test.prop}")
 private String attr;
 @Bean
 public SampleService sampleService() {
  return new SampleService(attr);
 }

 @Bean
 public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
  return new PropertySourcesPlaceholderConfigurer();
 }
}

split string only on first instance - java

String[] func(String apple){
String[] tmp = new String[2];
for(int i=0;i<apple.length;i++){
   if(apple.charAt(i)=='='){
      tmp[0]=apple.substring(0,i);
      tmp[1]=apple.substring(i+1,apple.length);
      break;
   }
}
return tmp;
}
//returns string_ARRAY_!

i like writing own methods :)

How to find the Vagrant IP?

I find that I do need the IP in order to configure /etc/hosts on the host system to point at services on the fresh VM.

Here's a rough version of what I use to fetch the IP. Let Vagrant do its SSH magic and ask the VM for its address; tweak for your needs.

new_ip=$(vagrant ssh -c "ip address show eth0 | grep 'inet ' | sed -e 's/^.*inet //' -e 's/\/.*$//'")

I just found this in the Vagrant Docs. Looks like they consider it a valid approach:

This will automatically assign an IP address from the reserved address space. The IP address can be determined by using vagrant ssh to SSH into the machine and using the appropriate command line tool to find the IP, such as ifconfig.

Connecting to local SQL Server database using C#

In Data Source (on the left of Visual Studio) right click on the database, then Configure Data Source With Wizard. A new window will appear, expand the Connection string, you can find the connection string in there

How to restore PostgreSQL dump file into Postgres databases?

By using pg_restore command you can restore postgres database

First open terminal type

sudo su postgres

Create new database

createdb [database name] -O [owner]

createdb test_db [-O openerp]

pg_restore -d [Database Name] [path of dump file]

pg_restore -d test_db /home/sagar/Download/sample_dbump

Wait for completion of database restoring.

Remember that dump file should have read, write, execute access, so for that you can apply chmod command

Display a table/list data dynamically in MVC3/Razor from a JsonResult?

If you really need to go this way, then this is what you can do. There are probably better ways of doing it, but this is all that I have at the moment. I did no database calls, I just used dummy data. Please modify the code to fit in with your scenario. I used jQuery to populate the HTML table.

In my controller I have the an action method called GetEmployees that returns a JSON result with all the employees. This is where you would call your repository to return the users from a database:

public ActionResult GetEmployees()
{
     List<User> userList = new List<User>();

     User user1 = new User
     {
          Id = 1,
          FirstName = "First name 1",
          LastName = "Last name 1"
     };

     User user2 = new User
     {
          Id = 2,
          FirstName = "First name 2",
          LastName = "Last name 2"
     };

     userList.Add(user1);
     userList.Add(user2);

     return Json(userList, JsonRequestBehavior.AllowGet);
}

The User class looks like this:

public class User
{
     public int Id { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
}

In your view you could have the following:

<div id="users">
     <table></table>
</div>

<script>

     $(document).ready(function () {

          var url = '/Home/GetEmployees';

          $.getJSON(url, function (data) {

               $.each(data, function (key, val) {

                    var user = '<tr><td>' + val.FirstName + '</td></tr>';

                    $('#users table').append(user);

               });
          });
     });

</script>

Regarding the code above: var url = '/Home/GetEmployees'; Home is the controller and GetEmployees is the action method that you defined above.

I hope this helps.

UPDATE:

This is how I would have done it..

I always create a view model class for a view. In this case I would have called it something like UserListViewModel:

public class UserListViewModel
{
     IEnumerable<User> Users { get; set; }
}

In my controller I would populate this Users list from a call to the database returning all the users:

public ActionResult List()
{
     UserListViewModel viewModel = new UserListViewModel
     {
          Users = userRepository.GetAllUsers()
     };

     return View(viewModel);
}

And in my view I would have the following:

<table>

@foreach(User user in Model.Users)
{
     <tr>
          <td>First Name:</td>
          <td>user.FirstName</td>
     </tr>
}

</table>

How to get response using cURL in PHP

The crux of the solution is setting

CURLOPT_RETURNTRANSFER => true

then

$response = curl_exec($ch);

CURLOPT_RETURNTRANSFER tells PHP to store the response in a variable instead of printing it to the page, so $response will contain your response. Here's your most basic working code (I think, didn't test it):

// init curl object        
$ch = curl_init();

// define options
$optArray = array(
    CURLOPT_URL => 'http://www.google.com',
    CURLOPT_RETURNTRANSFER => true
);

// apply those options
curl_setopt_array($ch, $optArray);

// execute request and get response
$result = curl_exec($ch);

How to run a Powershell script from the command line and pass a directory as a parameter

Change your code to the following :

Function Foo($directory)
    {
        echo $directory
    }

    if ($args.Length -eq 0)
    {
        echo "Usage: Foo <directory>"
    }
    else
    {
        Foo([string[]]$args)
    }

And then invoke it as:

powershell -ExecutionPolicy RemoteSigned -File "c:\foo.ps1" "c:\Documents and Settings" "c:\test"

DISTINCT for only one column

You can over that by using GROUP BY like this:

SELECT ID, Email, ProductName, ProductModel
FROM Products
GROUP BY Email

Nested lists python

The question title is too wide and the author's need is more specific. In my case, I needed to extract all elements from nested list like in the example below:

Example:

input -> [1,2,[3,4]]
output -> [1,2,3,4]

The code below gives me the result, but I would like to know if anyone can create a simpler answer:

def get_elements_from_nested_list(l, new_l):
    if l is not None:
        e = l[0]
        if isinstance(e, list):
            get_elements_from_nested_list(e, new_l)
        else:
            new_l.append(e)
        if len(l) > 1:
            return get_elements_from_nested_list(l[1:], new_l)
        else:
            return new_l

Call of the method

l = [1,2,[3,4]]
new_l = []

get_elements_from_nested_list(l, new_l)

CSS Vertical align does not work with float

Edited:

The vertical-align CSS property specifies the vertical alignment of an inline, inline-block or table-cell element.

Read this article for Understanding vertical-align

Using IF..ELSE in UPDATE (SQL server 2005 and/or ACCESS 2007)

this should work

update table_name
  set column_b = case
                  when column_a = 1 then 'Y'
                  else null
                 end,
  set column_c = case
                  when column_a = 2 then 'Y'
                  else null
                 end,
  set column_d = case
                  when column_a = 3 then 'Y'
                  else null
                 end
where
 conditions

the question is why would you want to do that...you may want to rethink the data model. you can replace null with whatever you want.

Expected initializer before function name

You are missing a semicolon at the end of your 'struct' definition.

Also,

*sotrudnik

needs to be

sotrudnik*

Write to custom log file from a Bash script

logger logs to syslog facilities. If you want the message to go to a particular file you have to modify the syslog configuration accordingly. You could add a line like this:

local7.*   -/var/log/mycustomlog

and restart syslog. Then you can log like this:

logger -p local7.info "information message"
logger -p local7.err "error message"

and the messages will appear in the desired logfile with the correct log level.

Without making changes to the syslog configuration you could use logger like this:

logger -s "foo bar" >> /var/log/mycustomlog

That would instruct logger to print the message to STDERR as well (in addition to logging it to syslog), so you could redirect STDERR to a file. However, it would be utterly pointless, because the message is already logged via syslog anyway (with the default priority user.notice).

How to delete a cookie using jQuery?

Try this

 $.cookie('_cookieName', null, { path: '/' });

The { path: '/' } do the job for you

How to style a disabled checkbox?

You can select it using css like this:

input[disabled] { /* css attributes */ }

Looping through a DataTable

Please try the following code below:

//Here I am using a reader object to fetch data from database, along with sqlcommand onject (cmd).
//Once the data is loaded to the Datatable object (datatable) you can loop through it using the datatable.rows.count prop.

using (reader = cmd.ExecuteReader())
{
// Load the Data table object
  dataTable.Load(reader);
  if (dataTable.Rows.Count > 0)
  {
    DataColumn col = dataTable.Columns["YourColumnName"];  
    foreach (DataRow row in dataTable.Rows)
    {                                   
       strJsonData = row[col].ToString();
    }
  }
}

Can You Get A Users Local LAN IP Address Via JavaScript?

I cleaned up mido's post and then cleaned up the function that they found. This will either return false or an array. When testing remember that you need to collapse the array in the web developer console otherwise it's nonintuitive default behavior may deceive you in to thinking that it is returning an empty array.

function ip_local()
{
 var ip = false;
 window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection || false;

 if (window.RTCPeerConnection)
 {
  ip = [];
  var pc = new RTCPeerConnection({iceServers:[]}), noop = function(){};
  pc.createDataChannel('');
  pc.createOffer(pc.setLocalDescription.bind(pc), noop);

  pc.onicecandidate = function(event)
  {
   if (event && event.candidate && event.candidate.candidate)
   {
    var s = event.candidate.candidate.split('\n');
    ip.push(s[0].split(' ')[4]);
   }
  }
 }

 return ip;
}

Additionally please keep in mind folks that this isn't something old-new like CSS border-radius though one of those bits that is outright not supported by IE11 and older. Always use object detection, test in reasonably older browsers (e.g. Firefox 4, IE9, Opera 12.1) and make sure your newer scripts aren't breaking your newer bits of code. Additionally always detect standards compliant code first so if there is something with say a CSS prefix detect the standard non-prefixed code first and then fall back as in the long term support will eventually be standardized for the rest of it's existence.

Remove the last three characters from a string

myString.Substring(myString.Length - 3, 3)

Here are examples on substring.>>

http://www.dotnetperls.com/substring

Refer those.

Why is String immutable in Java?

String class is FINAL it mean you can't create any class to inherit it and change the basic structure and make the Sting mutable.

Another thing instance variable and methods of String class that are provided are such that you can't change String object once created.

The reason what you have added doesn't make the String immutable at all.This all says how the String is stored in heap.Also string pool make the huge difference in performance

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ' '

For the OP's command:

select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0,  Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from  #tmp_CTF** 

I get this error:

Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.

when debugging something like this split the long line up so you'll get a better row number:

select compid
,2
, convert(datetime
, '01/01/' 
+ CONVERT(char(4)
,cal_yr) 
,101) 
,0
,  Update_dt
, th1
, th2
, th3_pc 
, Update_id
, Update_dt
,1
from  #tmp_CTF** 

this now results in:

Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.

which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:

from [#tmp_CTF**]

if that is the table name.

Dart SDK is not configured

Downloading and Configuring the Dart SDK

If you don’t already have the Dart SDK, install it. You can get it either by itself or by downloading the Flutter SDK, which (as of Flutter 1.21) includes the full Dart SDK.

Choose one:

Here’s one way to configure Dart support:

  1. Start the IDE, and install the Dart plugin. To find the Dart plugin, from the Welcome screen choose Configure > Plugins, then click Install JetBrains plugin, and then search or scroll down until you find Dart. Once you've installed the Dart plugin, restart the IDE.

  2. Create a new Dart project:

    • From the Welcome screen, click Create New Project.
    • In the next dialog, click Dart.
  3. If you don't see a value for the Dart SDK path, enter it.

    • For example, the SDK path might be <dart installation directory>/dart/dart-sdk.

Cross-browser window resize event - JavaScript / jQuery

Sorry to bring up an old thread, but if someone doesn't want to use jQuery you can use this:

function foo(){....};
window.onresize=foo;

How to read/write from/to file using Go?

Using io.Copy

package main

import (
    "io"
    "log"
    "os"
)

func main () {
    // open files r and w
    r, err := os.Open("input.txt")
    if err != nil {
        panic(err)
    }
    defer r.Close()

    w, err := os.Create("output.txt")
    if err != nil {
        panic(err)
    }
    defer w.Close()

    // do the actual work
    n, err := io.Copy(w, r)
    if err != nil {
        panic(err)
    }
    log.Printf("Copied %v bytes\n", n)
}

If you don't feel like reinventing the wheel, the io.Copy and io.CopyN may serve you well. If you check the source of the io.Copy function, it is nothing but one of the Mostafa's solutions (the 'basic' one, actually) packaged in the Go library. They are using a significantly larger buffer than he is, though.

Maintain/Save/Restore scroll position when returning to a ListView

private Parcelable state;
@Override
public void onPause() {
    state = mAlbumListView.onSaveInstanceState();
    super.onPause();
}

@Override
public void onResume() {
    super.onResume();

    if (getAdapter() != null) {
        mAlbumListView.setAdapter(getAdapter());
        if (state != null){
            mAlbumListView.requestFocus();
            mAlbumListView.onRestoreInstanceState(state);
        }
    }
}

That's enough

Transaction marked as rollback only: How do I find the cause

Found a good explanation with solutions: https://vcfvct.wordpress.com/2016/12/15/spring-nested-transactional-rollback-only/

1) remove the @Transacional from the nested method if it does not really require transaction control. So even it has exception, it just bubbles up and does not affect transactional stuff.

OR:

2) if nested method does need transaction control, make it as REQUIRE_NEW for the propagation policy that way even if throws exception and marked as rollback only, the caller will not be affected.

Unfamiliar symbol in algorithm: what does ? mean?

yes, these are the well-known quantifiers used in math. Another example is ? which reads as "exists".

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

How to do a JUnit assert on a message in a logger

The API for Log4J2 is slightly different. Also you might be using its async appender. I created a latched appender for this:

    public static class LatchedAppender extends AbstractAppender implements AutoCloseable {

    private final List<LogEvent> messages = new ArrayList<>();
    private final CountDownLatch latch;
    private final LoggerConfig loggerConfig;

    public LatchedAppender(Class<?> classThatLogs, int expectedMessages) {
        this(classThatLogs, null, null, expectedMessages);
    }
    public LatchedAppender(Class<?> classThatLogs, Filter filter, Layout<? extends Serializable> layout, int expectedMessages) {
        super(classThatLogs.getName()+"."+"LatchedAppender", filter, layout);
        latch = new CountDownLatch(expectedMessages);
        final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        final Configuration config = ctx.getConfiguration();
        loggerConfig = config.getLoggerConfig(LogManager.getLogger(classThatLogs).getName());
        loggerConfig.addAppender(this, Level.ALL, ThresholdFilter.createFilter(Level.ALL, null, null));
        start();
    }

    @Override
    public void append(LogEvent event) {
        messages.add(event);
        latch.countDown();
    }

    public List<LogEvent> awaitMessages() throws InterruptedException {
        assertTrue(latch.await(10, TimeUnit.SECONDS));
        return messages;
    }

    @Override
    public void close() {
        stop();
        loggerConfig.removeAppender(this.getName());
    }
}

Use it like this:

        try (LatchedAppender appender = new LatchedAppender(ClassUnderTest.class, 1)) {

        ClassUnderTest.methodThatLogs();
        List<LogEvent> events = appender.awaitMessages();
        assertEquals(1, events.size());
        //more assertions here

    }//appender removed

jQuery check if it is clicked or not

Using jQuery, I would suggest a shorter solution.

var elementClicked;
$("element").click(function(){
   elementClicked = true;
});
if( elementClicked != true ) {
    alert("element not clicked");
}else{
    alert("element clicked");
}

("element" here is to be replaced with the actual name tag)

"Parser Error Message: Could not load type" in Global.asax

This can also happen if you accidentally forget to set your VS solution to "Multiple Startup Projects" if you are running a Web and WebApi from the same solution.

You can check this by right-clicking on Solution in the Solution Explorer and select 'Properties". Then look for 'Startup Projects'.

Angular - res.json() is not a function

Don't need to use this method:

 .map((res: Response) => res.json() );

Just use this simple method instead of the previous method. hopefully you'll get your result:

.map(res => res );

Simulate low network connectivity for Android

Do you want to test for no network connection, or just a slow network connection? If the former, you can go to Settings > Wireless & networks > Airplane mode and turn Airplane mode on. That will let you test network unavailability on an actual device.

How to launch multiple Internet Explorer windows/tabs from batch file?

There is a setting in the IE options that controls whether it should open new links in an existing window or in a new window. I'm not sure if you can control it from the command line but maybe changing this option would be enough for you.

In IE7 it looks like the option is "Reuse windows for launching shortcuts (when tabbed browsing is disabled)".

Bootstrap modal link

Please remove . from your target it should be a id

<a href="#bannerformmodal" data-toggle="modal" data-target="#bannerformmodal">Load me</a>

Also you have to give your modal id like below

<div class="modal fade bannerformmodal" tabindex="-1" role="dialog" aria-labelledby="bannerformmodal" aria-hidden="true" id="bannerformmodal">

Here is the solution in a fiddle.

Get type of all variables

lapply(your_dataframe, class) gives you something like:

$tikr [1] "factor"

$Date [1] "Date"

$Open [1] "numeric"

$High [1] "numeric"

... etc.

Update row values where certain condition is met in pandas

I think you can use loc if you need update two columns to same value:

df1.loc[df1['stream'] == 2, ['feat','another_feat']] = 'aaaa'
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2        aaaa         aaaa
c       2        aaaa         aaaa
d       3  some_value   some_value

If you need update separate, one option is use:

df1.loc[df1['stream'] == 2, 'feat'] = 10
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2          10   some_value
c       2          10   some_value
d       3  some_value   some_value

Another common option is use numpy.where:

df1['feat'] = np.where(df1['stream'] == 2, 10,20)
print df1
   stream  feat another_feat
a       1    20   some_value
b       2    10   some_value
c       2    10   some_value
d       3    20   some_value

EDIT: If you need divide all columns without stream where condition is True, use:

print df1
   stream  feat  another_feat
a       1     4             5
b       2     4             5
c       2     2             9
d       3     1             7

#filter columns all without stream
cols = [col for col in df1.columns if col != 'stream']
print cols
['feat', 'another_feat']

df1.loc[df1['stream'] == 2, cols ] = df1 / 2
print df1
   stream  feat  another_feat
a       1   4.0           5.0
b       2   2.0           2.5
c       2   1.0           4.5
d       3   1.0           7.0

If working with multiple conditions is possible use multiple numpy.where or numpy.select:

df0 = pd.DataFrame({'Col':[5,0,-6]})

df0['New Col1'] = np.where((df0['Col'] > 0), 'Increasing', 
                          np.where((df0['Col'] < 0), 'Decreasing', 'No Change'))

df0['New Col2'] = np.select([df0['Col'] > 0, df0['Col'] < 0],
                            ['Increasing',  'Decreasing'], 
                            default='No Change')

print (df0)
   Col    New Col1    New Col2
0    5  Increasing  Increasing
1    0   No Change   No Change
2   -6  Decreasing  Decreasing

for each inside a for each - Java

for (Tweet : tweets){ ...

should really be

for(Tweet tweet: tweets){...

Working with UTF-8 encoding in Python source

In the source header you can declare:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
....

It is described in the PEP 0263:

Then you can use UTF-8 in strings:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

u = 'idzie waz waska drózka'
uu = u.decode('utf8')
s = uu.encode('cp1250')
print(s)

This declaration is not needed in Python 3 as UTF-8 is the default source encoding (see PEP 3120).

In addition, it may be worth verifying that your text editor properly encodes your code in UTF-8. Otherwise, you may have invisible characters that are not interpreted as UTF-8.

Android getText from EditText field

You can simply get the text in editText by applying below code:

EditText editText=(EditText)findViewById(R.id.vnosZadeve);
String text=editText.getText().toString();

then you can toast string text!

Happy coding!

Find a value in DataTable

A DataTable or DataSet object will have a Select Method that will return a DataRow array of results based on the query passed in as it's parameter.

Looking at your requirement your filterexpression will have to be somewhat general to make this work.

myDataTable.Select("columnName1 like '%" + value + "%'");

How do I check if an object has a specific property in JavaScript?

Showing how to use this answer

const object= {key1: 'data', key2: 'data2'};

Object.keys(object).includes('key1') //returns true

We can use indexOf as well, I prefer includes

How to load all the images from one of my folder into my web page, using Jquery/Javascript

Here is one way to do it. Involves doing a little PHP as well.

The PHP part:

$filenameArray = [];

$handle = opendir(dirname(realpath(__FILE__)).'/images/');
        while($file = readdir($handle)){
            if($file !== '.' && $file !== '..'){
                array_push($filenameArray, "images/$file");
            }
        }

echo json_encode($filenameArray);

The jQuery part:

$.ajax({
            url: "getImages.php",
            dataType: "json",
            success: function (data) {

                $.each(data, function(i,filename) {
                    $('#imageDiv').prepend('<img src="'+ filename +'"><br>');
                });
            }
        });

So basically you do a PHP file to return you the list of image filenames as JSON, grab that JSON using an ajax call, and prepend/append them to the html. You would probably want to filter the files u grab from the folder.

Had some help on the php part from 1

Getting Index of an item in an arraylist;

for (int i = 0; i < list.length; i++) {
   if (list.get(i) .getName().equalsIgnoreCase("myName")) {
    System.out.println(i);
    break;
  }
}

R command for setting working directory to source file location in Rstudio

I understand this is outdated, but I couldn't get the former answers to work very satisfactorily, so I wanted to contribute my method in case any one else encounters the same error mentioned in the comments to BumbleBee's answer.

Mine is based on a simple system command. All you feed the function is the name of your script:

extractRootDir <- function(x) {
    abs <- suppressWarnings(system(paste("find ./ -name",x), wait=T, intern=T, ignore.stderr=T))[1];
    path <- paste("~",substr(abs, 3, length(strsplit(abs,"")[[1]])),sep="");
    ret <- gsub(x, "", path);
    return(ret);
}

setwd(extractRootDir("myScript.R"));

The output from the function would look like "/Users/you/Path/To/Script". Hope this helps anyone else who may have gotten stuck.

JPanel vs JFrame in Java

You should not extend the JFrame class unnecessarily (only if you are adding extra functionality to the JFrame class)

JFrame:

JFrame extends Component and Container.

It is a top level container used to represent the minimum requirements for a window. This includes Borders, resizability (is the JFrame resizeable?), title bar, controls (minimize/maximize allowed?), and event handlers for various Events like windowClose, windowOpened etc.

JPanel:

JPanel extends Component, Container and JComponent

It is a generic class used to group other Components together.

  • It is useful when working with LayoutManagers e.g. GridLayout f.i adding components to different JPanels which will then be added to the JFrame to create the gui. It will be more manageable in terms of Layout and re-usability.

  • It is also useful for when painting/drawing in Swing, you would override paintComponent(..) and of course have the full joys of double buffering.

A Swing GUI cannot exist without a top level container like (JWindow, Window, JFrame Frame or Applet), while it may exist without JPanels.

What are the differences between struct and class in C++?

According to Stroustrup in the C++ Programming Language:

Which style you use depends on circumstances and taste. I usually prefer to use struct for classes that have all data public. I think of such classes as "not quite proper types, just data structures."

Functionally, there is no difference other than the public / private

How to concat two ArrayLists?

for a lightweight list that does not copy the entries, you may use sth like this:

List<Object> mergedList = new ConcatList<>(list1, list2);

here the implementation:

public class ConcatList<E> extends AbstractList<E> {

    private final List<E> list1;
    private final List<E> list2;

    public ConcatList(final List<E> list1, final List<E> list2) {
        this.list1 = list1;
        this.list2 = list2;
    }

    @Override
    public E get(final int index) {
        return getList(index).get(getListIndex(index));
    }

    @Override
    public E set(final int index, final E element) {
        return getList(index).set(getListIndex(index), element);
    }

    @Override
    public void add(final int index, final E element) {
        getList(index).add(getListIndex(index), element);
    }

    @Override
    public E remove(final int index) {
        return getList(index).remove(getListIndex(index));
    }

    @Override
    public int size() {
        return list1.size() + list2.size();
    }

    @Override
    public void clear() {
        list1.clear();
        list2.clear();
    }

    private int getListIndex(final int index) {
        final int size1 = list1.size();
        return index >= size1 ? index - size1 : index;
    }

    private List<E> getList(final int index) {
        return index >= list1.size() ? list2 : list1;
    }

}

cor shows only NA or 1 for correlations - Why?

In my case I was using more than two variables, and this worked for me better:

cor(x = as.matrix(tbl), method = "pearson", use = "pairwise.complete.obs")

However:

If use has the value "pairwise.complete.obs" then the correlation or covariance between each pair of variables is computed using all complete pairs of observations on those variables. This can result in covariance or correlation matrices which are not positive semi-definite, as well as NA entries if there are no complete pairs for that pair of variables.

How to restore the menu bar in Visual Studio Code

To restore menu bar visibility so that you don't press key Alt to make the menu bar visible and the menu bar remains visible all the time, see the setting below.

You inadvertently changed the value from "default" to "toggle", so restore the setting to "default" as shown below.

"window.menuBarVisibility": "default"

JDK was not found on the computer for NetBeans 6.5

You have to either provide JAVA_HOME environment variable which points to the JDK location or as it says, you can run the installer from the command line passing JDK address through its -javahome argument like this:

C:> <NetBeans_Installer_Name> -javahome <JDK-PATH>

You must also make sure that your installed JDK is the Windows 64-bit version of the program. This is the download link for JDK6U37: http://download.oracle.com/otn-pub/java/jdk/6u37-b06/jdk-6u37-windows-x64.exe

How to get .pem file from .key and .crt files?

  • Open terminal.
  • Go to the folder where your certificate is located.
  • Execute below command by replacing name with your certificate.

openssl pkcs12 -in YOUR_CERTIFICATE.p12 -out YOUR_CERTIFICATE.pem -nodes -clcerts

  • Hope it will work!!

Iterating through a variable length array

Arrays have an implicit member variable holding the length:

for(int i=0; i<myArray.length; i++) {
    System.out.println(myArray[i]);
}

Alternatively if using >=java5, use a for each loop:

for(Object o : myArray) {
    System.out.println(o);
}

Equivalent of varchar(max) in MySQL?

TLDR; MySql does not have an equivalent concept of varchar(max), this is a MS SQL Server feature.

What is VARCHAR(max)?

varchar(max) is a feature of Microsoft SQL Server.

The amount of data that a column could store in Microsoft SQL server versions prior to version 2005 was limited to 8KB. In order to store more than 8KB you would have to use TEXT, NTEXT, or BLOB columns types, these column types stored their data as a collection of 8K pages separate from the table data pages; they supported storing up to 2GB per row.

The big caveat to these column types was that they usually required special functions and statements to access and modify the data (e.g. READTEXT, WRITETEXT, and UPDATETEXT)

In SQL Server 2005, varchar(max) was introduced to unify the data and queries used to retrieve and modify data in large columns. The data for varchar(max) columns is stored inline with the table data pages.

As the data in the MAX column fills an 8KB data page an overflow page is allocated and the previous page points to it forming a linked list. Unlike TEXT, NTEXT, and BLOB the varchar(max) column type supports all the same query semantics as other column types.

So varchar(MAX) really means varchar(AS_MUCH_AS_I_WANT_TO_STUFF_IN_HERE_JUST_KEEP_GROWING) and not varchar(MAX_SIZE_OF_A_COLUMN).

MySql does not have an equivalent idiom.

In order to get the same amount of storage as a varchar(max) in MySql you would still need to resort to a BLOB column type. This article discusses a very effective method of storing large amounts of data in MySql efficiently.

How to add icons to React Native app

You can import react-native-elements and use the font-awesome icons to your react native app

Install

npm install --save react-native-elements

then import that where you want to use icons

import { Icon } from 'react-native-elements'

Use it like

render() {
   return(
    <Icon
      reverse
      name='ios-american-football'
      type='ionicon'
      color='#517fa4'
    />
 );
}

Android Studio doesn't see device

Update last usb driver

Install the Google USB Driver

  1. In Android Studio, click Tools > Android > SDK Manager.
  2. Click the SDK Tools tab.
  3. Select Google USB Driver package and click Install.
  4. Proceed to install the package. When done, the driver files are downloaded into the \extras\google\usb_driver\ directory.

Python: subplot within a loop: first panel appears in wrong position

Basically the same solution as provided by Rutger Kassies, but using a more pythonic syntax:

fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)

data = np.arange(250, 260)

for ax, d in zip(axs.ravel(), data):
    ax.contourf(np.random.rand(10,10), 5, cmap=plt.cm.Oranges)
    ax.set_title(str(d))

MySQl Error #1064

Sometimes when your table has a similar name to the database name you should use back tick. so instead of:

INSERT INTO books.book(field1, field2) VALUES ('value1', 'value2');

You should have this:

INSERT INTO `books`.`book`(`field1`, `field2`) VALUES ('value1', 'value2');

How can I switch my signed in user in Visual Studio 2013?

I resolved this problem by deleting the registry key under

hkey_current_user\software\Microsoft\VSCommon\12.0\clientservices\tokenstorage\visualstudio\ideuser

Saving a high resolution image in R

You can do the following. Add your ggplot code after the first line of code and end with dev.off().

tiff("test.tiff", units="in", width=5, height=5, res=300)
# insert ggplot code
dev.off()

res=300 specifies that you need a figure with a resolution of 300 dpi. The figure file named 'test.tiff' is saved in your working directory.

Change width and height in the code above depending on the desired output.

Note that this also works for other R plots including plot, image, and pheatmap.

Other file formats

In addition to TIFF, you can easily use other image file formats including JPEG, BMP, and PNG. Some of these formats require less memory for saving.

What online brokers offer APIs?

Looks like E*Trade has an API now.

For access to historical data, I've found EODData to have reasonable prices for their data dumps. For side projects, I can't afford (rather don't want to afford) a huge subscription fee just for some data to tinker with.

What is the meaning of single and double underscore before an object name?

Sometimes you have what appears to be a tuple with a leading underscore as in

def foo(bar):
    return _('my_' + bar)

In this case, what's going on is that _() is an alias for a localization function that operates on text to put it into the proper language, etc. based on the locale. For example, Sphinx does this, and you'll find among the imports

from sphinx.locale import l_, _

and in sphinx.locale, _() is assigned as an alias of some localization function.

How to make unicode string with python3

This how I solved my problem to convert chars like \uFE0F, \u000A, etc. And also emojis that encoded with 16 bytes.

example = 'raw vegan chocolate cocoa pie w chocolate &amp; vanilla cream\\uD83D\\uDE0D\\uD83D\\uDE0D\\u2764\\uFE0F Present Moment Caf\\u00E8 in St.Augustine\\u2764\\uFE0F\\u2764\\uFE0F '
import codecs
new_str = codecs.unicode_escape_decode(example)[0]
print(new_str)
>>> 'raw vegan chocolate cocoa pie w chocolate &amp; vanilla cream\ud83d\ude0d\ud83d\ude0d?? Present Moment Cafè in St.Augustine???? '
new_new_str = new_str.encode('utf-16', 'surrogatepass').decode('utf-16')
print(new_new_str)
>>> 'raw vegan chocolate cocoa pie w chocolate &amp; vanilla cream?? Present Moment Cafè in St.Augustine???? '

How do I see the extensions loaded by PHP?

Running

php -m
will give you all the modules, and
php -i
will give you a lot more detailed information on what the current configuration.

How to drop a table if it exists?

I wrote a little UDF that returns 1 if its argument is the name of an extant table, 0 otherwise:

CREATE FUNCTION [dbo].[Table_exists]
(
    @TableName VARCHAR(200)
)
    RETURNS BIT
AS
BEGIN
    If Exists(select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = @TableName)
        RETURN 1;

    RETURN 0;
END

GO

To delete table User if it exists, call it like so:

IF [dbo].[Table_exists]('User') = 1 Drop table [User]

How to represent a fix number of repeats in regular expression?

For Java:

Quantifiers documentation

X, exactly n times: X{n}
X, at least n times: X{n,}
X, at least n but not more than m times: X{n,m}

Call a PHP function after onClick HTML event

 cell1.innerHTML="<?php echo $customerDESC; ?>";
 cell2.innerHTML="<?php echo $comm; ?>";
 cell3.innerHTML="<?php echo $expressFEE; ?>";
 cell4.innerHTML="<?php echo $totao_unit_price; ?>";

it is working like a charm, the javascript is inside a php while loop

wget can't download - 404 error

Actually I don't know what is the reason exactly, I have faced this like of problem. if you have the domain's IP address (ex 208.113.139.4), please use the IP address instead of domain (in this case www.icerts.com)

wget 192.243.111.11/images/logo.jpg

Go to find the IP from URL https://ipinfo.info/html/ip_checker.php

How to put text in the upper right, or lower right corner of a "box" using css

If the position of the element containing the Lorum Ipsum is set absolute, you can specify the position via CSS. The "here" and "and here" elements would need to be contained in a block level element. I'll use markup like this.

print("<div id="lipsum">");
print("<div id="here">");
print("  here");
print("</div>");
print("<div id="andhere">");
print("and here");
print("</div>");
print("blah");
print("</div>");

Here's the CSS for above.

#lipsum {position:absolute;top:0;left:0;} /* example */
#here {position:absolute;top:0;right:0;}
#andhere {position:absolute;bottom:0;right:0;}

Again, the above only works (reliably) if #lipsum is positioned via absolute.

If not, you'll need to use the float property.

#here, #andhere {float:right;}

You'll also need to put your markup in the appropriate place. For better presentation, your two divs will probably need some padding and margins so that the text doesn't all run together.

go to character in vim

:goto 21490 will take you to the 21490th byte in the buffer.

Setting up a JavaScript variable from Spring model by using Thymeleaf

I've seen this kind of thing work in the wild:

<input type="button"  th:onclick="'javascript:getContactId(\'' + ${contact.id} + '\');'" />

How to quit a java app from within the program

There's two simple answers to the question.

This is the "Professional way":

//This just terminates the program.
System.exit(0);

This is a more clumsier way:

//This just terminates the program, just like System.exit(0).
return;

How to use Python's pip to download and keep the zipped files for a package?

pip install --download is deprecated. Starting from version 8.0.0 you should use pip download command:

 pip download <package-name>

How do I resolve "Cannot find module" error using Node.js?

Using npm install installs the module into the current directory only (in a subdirectory called node_modules). Is app.js located under home/dave/src/server/? If not and you want to use the module from any directory, you need to install it globally using npm install -g.

I usually install most packages locally so that they get checked in along with my project code.

Update (8/2019):

Nowadays you can use package-lock.json file, which is automatically generated when npm modifies your node_modules directory. Therefore you can leave out checking in packages, because the package-lock.json tracks the exact versions of your node_modules, you're currently using. To install packages from package-lock.json instead of package.json use the command npm ci.

Update (3/2016):

I've received a lot of flak for my response, specifically that I check in the packages that my code depends on. A few days ago, somebody unpublished all of their packages (https://kodfabrik.com/journal/i-ve-just-liberated-my-modules) which broke React, Babel, and just about everything else. Hopefully it's clear now that if you have production code, you can't rely on NPM actually maintaining your dependencies for you.

SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

From how it looks, I think grouping by multiple columns/fields wont hurt your result. Why don't you try adding to the group by like this:

GROUP BY `proof_type`, `id`

This will group by proof_type first then id. I hope this does not alter the results. In some/most cases group by multiple columns gives wrong results.

How can I get screen resolution in java?

int screenResolution = Toolkit.getDefaultToolkit().getScreenResolution();
System.out.println(""+screenResolution);

What is move semantics?

I find it easiest to understand move semantics with example code. Let's start with a very simple string class which only holds a pointer to a heap-allocated block of memory:

#include <cstring>
#include <algorithm>

class string
{
    char* data;

public:

    string(const char* p)
    {
        size_t size = std::strlen(p) + 1;
        data = new char[size];
        std::memcpy(data, p, size);
    }

Since we chose to manage the memory ourselves, we need to follow the rule of three. I am going to defer writing the assignment operator and only implement the destructor and the copy constructor for now:

    ~string()
    {
        delete[] data;
    }

    string(const string& that)
    {
        size_t size = std::strlen(that.data) + 1;
        data = new char[size];
        std::memcpy(data, that.data, size);
    }

The copy constructor defines what it means to copy string objects. The parameter const string& that binds to all expressions of type string which allows you to make copies in the following examples:

string a(x);                                    // Line 1
string b(x + y);                                // Line 2
string c(some_function_returning_a_string());   // Line 3

Now comes the key insight into move semantics. Note that only in the first line where we copy x is this deep copy really necessary, because we might want to inspect x later and would be very surprised if x had changed somehow. Did you notice how I just said x three times (four times if you include this sentence) and meant the exact same object every time? We call expressions such as x "lvalues".

The arguments in lines 2 and 3 are not lvalues, but rvalues, because the underlying string objects have no names, so the client has no way to inspect them again at a later point in time. rvalues denote temporary objects which are destroyed at the next semicolon (to be more precise: at the end of the full-expression that lexically contains the rvalue). This is important because during the initialization of b and c, we could do whatever we wanted with the source string, and the client couldn't tell a difference!

C++0x introduces a new mechanism called "rvalue reference" which, among other things, allows us to detect rvalue arguments via function overloading. All we have to do is write a constructor with an rvalue reference parameter. Inside that constructor we can do anything we want with the source, as long as we leave it in some valid state:

    string(string&& that)   // string&& is an rvalue reference to a string
    {
        data = that.data;
        that.data = nullptr;
    }

What have we done here? Instead of deeply copying the heap data, we have just copied the pointer and then set the original pointer to null (to prevent 'delete[]' from source object's destructor from releasing our 'just stolen data'). In effect, we have "stolen" the data that originally belonged to the source string. Again, the key insight is that under no circumstance could the client detect that the source had been modified. Since we don't really do a copy here, we call this constructor a "move constructor". Its job is to move resources from one object to another instead of copying them.

Congratulations, you now understand the basics of move semantics! Let's continue by implementing the assignment operator. If you're unfamiliar with the copy and swap idiom, learn it and come back, because it's an awesome C++ idiom related to exception safety.

    string& operator=(string that)
    {
        std::swap(data, that.data);
        return *this;
    }
};

Huh, that's it? "Where's the rvalue reference?" you might ask. "We don't need it here!" is my answer :)

Note that we pass the parameter that by value, so that has to be initialized just like any other string object. Exactly how is that going to be initialized? In the olden days of C++98, the answer would have been "by the copy constructor". In C++0x, the compiler chooses between the copy constructor and the move constructor based on whether the argument to the assignment operator is an lvalue or an rvalue.

So if you say a = b, the copy constructor will initialize that (because the expression b is an lvalue), and the assignment operator swaps the contents with a freshly created, deep copy. That is the very definition of the copy and swap idiom -- make a copy, swap the contents with the copy, and then get rid of the copy by leaving the scope. Nothing new here.

But if you say a = x + y, the move constructor will initialize that (because the expression x + y is an rvalue), so there is no deep copy involved, only an efficient move. that is still an independent object from the argument, but its construction was trivial, since the heap data didn't have to be copied, just moved. It wasn't necessary to copy it because x + y is an rvalue, and again, it is okay to move from string objects denoted by rvalues.

To summarize, the copy constructor makes a deep copy, because the source must remain untouched. The move constructor, on the other hand, can just copy the pointer and then set the pointer in the source to null. It is okay to "nullify" the source object in this manner, because the client has no way of inspecting the object again.

I hope this example got the main point across. There is a lot more to rvalue references and move semantics which I intentionally left out to keep it simple. If you want more details please see my supplementary answer.

How can I format a decimal to always show 2 decimal places?

.format is a more readable way to handle variable formatting:

'{:.{prec}f}'.format(26.034, prec=2)

mongodb how to get max value from collections

The performance of the suggested answer is fine. According to the MongoDB documentation:

When a $sort immediately precedes a $limit, the optimizer can coalesce the $limit into the $sort. This allows the sort operation to only maintain the top n results as it progresses, where n is the specified limit, and MongoDB only needs to store n items in memory.

Changed in version 4.0.

So in the case of

db.collection.find().sort({age:-1}).limit(1)

we get only the highest element WITHOUT sorting the collection because of the mentioned optimization.

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

Detecting sheet of paper is kinda old school. If you want to tackle skew detection then it is better if you straightaway aim for text line detection. With this you will get the extremas left, right, top and bottom. Discard any graphics in the image if you dont want and then do some statistics on the text line segments to find the most occurring angle range or rather angle. This is how you will narrow down to a good skew angle. Now after this you put these parameters the skew angle and the extremas to deskew and chop the image to what is required.

As for the current image requirement, it is better if you try CV_RETR_EXTERNAL instead of CV_RETR_LIST.

Another method of detecting edges is to train a random forests classifier on the paper edges and then use the classifier to get the edge Map. This is by far a robust method but requires training and time.

Random forests will work with low contrast difference scenarios for example white paper on roughly white background.

What is the syntax of the enhanced for loop in Java?

An enhanced for loop is just limiting the number of parameters inside the parenthesis.

for (int i = 0; i < myArray.length; i++) {
    System.out.println(myArray[i]);
}

Can be written as:

for (int myValue : myArray) {
    System.out.println(myValue);
}

PHP - Indirect modification of overloaded property

I agree with VinnyD that what you need to do is add "&" in front of your __get function, as to make it to return the needed result as a reference:

public function &__get ( $propertyname )

But be aware of two things:

1) You should also do

return &$something;

or you might still be returning a value and not a reference...

2) Remember that in any case that __get returns a reference this also means that the corresponding __set will NEVER be called; this is because php resolves this by using the reference returned by __get, which is called instead!

So:

$var = $object->NonExistentArrayProperty; 

means __get is called and, since __get has &__get and return &$something, $var is now, as intended, a reference to the overloaded property...

$object->NonExistentArrayProperty = array(); 

works as expected and __set is called as expected...

But:

$object->NonExistentArrayProperty[] = $value;

or

$object->NonExistentArrayProperty["index"] = $value;

works as expected in the sense that the element will be correctly added or modified in the overloaded array property, BUT __set WILL NOT BE CALLED: __get will be called instead!

These two calls would NOT work if not using &__get and return &$something, but while they do work in this way, they NEVER call __set, but always call __get.

This is why I decided to return a reference

return &$something;

when $something is an array(), or when the overloaded property has no special setter method, and instead return a value

return $something;

when $something is NOT an array or has a special setter function.

In any case, this was quite tricky to understand properly for me! :)

Creating an empty file in C#

To avoid accidentally overwriting an existing file use:

using (new FileStream(filename, FileMode.CreateNew)) {}

...and handle the IOException which will occur if the file already exists.

File.Create, which is suggested in other answers, will overwrite the contents of the file if it already exists. In simple cases you could mitigate this using File.Exists(). However something more robust is necessary in scenarios where multiple threads and/or processes are attempting to create files in the same folder simultaneously.

How can I add a hint or tooltip to a label in C# Winforms?

just another way to do it.

Label lbl = new Label();
new ToolTip().SetToolTip(lbl, "tooltip text here");

Disable-web-security in Chrome 48+

As of the date of this answer (March 2020) there is a plugin for chrome called CORS unblock that allows you to skip that browser policy. The 'same origin policy' is an important security feature of browsers. Please only install this plugin for development or testing purposes. Do not promote its installation in end client browsers because you compromise the security of users and the chrome community will be forced to remove this plugin from the store.

Angularjs $q.all

In javascript there are no block-level scopes only function-level scopes:

Read this article about javaScript Scoping and Hoisting.

See how I debugged your code:

var deferred = $q.defer();
deferred.count = i;

console.log(deferred.count); // 0,1,2,3,4,5 --< all deferred objects

// some code

.success(function(data){
   console.log(deferred.count); // 5,5,5,5,5,5 --< only the last deferred object
   deferred.resolve(data);
})
  • When you write var deferred= $q.defer(); inside a for loop it's hoisted to the top of the function, it means that javascript declares this variable on the function scope outside of the for loop.
  • With each loop, the last deferred is overriding the previous one, there is no block-level scope to save a reference to that object.
  • When asynchronous callbacks (success / error) are invoked, they reference only the last deferred object and only it gets resolved, so $q.all is never resolved because it still waits for other deferred objects.
  • What you need is to create an anonymous function for each item you iterate.
  • Since functions do have scopes, the reference to the deferred objects are preserved in a closure scope even after functions are executed.
  • As #dfsq commented: There is no need to manually construct a new deferred object since $http itself returns a promise.

Solution with angular.forEach:

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

UploadService.uploadQuestion = function(questions){

    var promises = [];

    angular.forEach(questions , function(question) {

        var promise = $http({
            url   : 'upload/question',
            method: 'POST',
            data  : question
        });

        promises.push(promise);

    });

    return $q.all(promises);
}

My favorite way is to use Array#map:

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

UploadService.uploadQuestion = function(questions){

    var promises = questions.map(function(question) {

        return $http({
            url   : 'upload/question',
            method: 'POST',
            data  : question
        });

    });

    return $q.all(promises);
}

Error in Python IOError: [Errno 2] No such file or directory: 'data.csv'

Try to give the full path to your csv file

open('/users/gcameron/Desktop/map/data.csv')

The python process is looking for file in the directory it is running from.

Change the current directory from a Bash script

I like to do the same thing for different projects without firing up a new shell.

In your case:

cd /home/artemb

Save the_script as:

echo cd /home/artemb

Then fire it up with:

\`./the_script\`

Then you get to the directory using the same shell.

Recover from git reset --hard?

 git reset HEAD@{4}

4 is changes before 4 steps ago. if you select a correct step, it should show the list of files that you removed from hard. then do:

$ git reflog show

it's going to show you local commit history we've already created. now do:

$ git reset --hard 8c4d112

8c4d112 is a code you want to reset your hard there. let's look at https://www.theserverside.com/video/How-to-use-the-git-reset-hard-command-to-change-a-commit-history to get more information.

How To Execute SSH Commands Via PHP

//Update 2018, works//

Method1:

Download phpseclib v1 and use this code:

<?php
set_include_path(__DIR__ . '/phpseclib1.0.11');
include("Net/SSH2.php");

$key ="MyPassword";
  /* ### if using PrivateKey ### 
  include("Crypt/RSA.php");
  $key = new Crypt_RSA();
  $key->loadKey(file_get_contents('private-key.ppk'));
  */

$ssh = new Net_SSH2('www.example.com', 22);   // Domain or IP
if (!$ssh->login('your_username', $key))  exit('Login Failed');

echo $ssh->exec('pwd');
?>

or Method2:

Download newest phpseclib v2 (requires composer install at first):

<?php

set_include_path($path=__DIR__ . '/phpseclib-master/phpseclib');
include ($path.'/../vendor/autoload.php');

$loader = new \Composer\Autoload\ClassLoader();

use phpseclib\Net\SSH2;

$key ="MyPassword";
  /* ### if using PrivateKey ### 
  use phpseclib\Crypt\RSA;
  $key = new RSA();
  $key->load(file_get_contents('private-key.ppk'));
  */

$ssh = new SSH2('www.example.com', 22);   // Domain or IP
if (!$ssh->login('your_username', $key))   exit('Login Failed'); 

echo $ssh->exec('pwd');
?>

p.s. if you get "Connection timed out" then it's probably the issue of HOST/FIREWALL (local or remote) or like that, not a fault of script.

Running Git through Cygwin from Windows

call your (windows-)git with cygpath as parameter, in order to convert the "calling path". I m confused why that should be a problem.

In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

Use next:

(1..10).each do |a|
  next if a.even?
  puts a
end

prints:

1
3   
5
7
9

For additional coolness check out also redo and retry.

Works also for friends like times, upto, downto, each_with_index, select, map and other iterators (and more generally blocks).

For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.

How to force a line break in a long word in a DIV?

Found that using the following worked across most major browsers (Chrome, IE, Safari iOS/OSX) except Firefox (v50.0.2) when using flexbox and relying on width: auto.

.your_element {
    word-wrap: break-word;   
    overflow-wrap: break-word;
    word-break: break-word;
}

Note: you may need to add browser vendor prefixes if you are not using an autoprefixer.

Another thing to watch out for is text using &nbsp; for spacing can cause line breaks mid-word.

Stored procedure or function expects parameter which is not supplied

in my case, I was passing all the parameters but one of the parameter my code was passing a null value for string.

Eg: cmd.Parameters.AddWithValue("@userName", userName);

in the above case, if the data type of userName is string, I was passing userName as null.

Redirect from an HTML page

I would use both meta, and JavaScript code and would have a link just in case.

<!DOCTYPE HTML>
<html lang="en-US">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="refresh" content="0; url=http://example.com">
        <script type="text/javascript">
            window.location.href = "http://example.com"
        </script>
        <title>Page Redirection</title>
    </head>
    <body>
        <!-- Note: don't tell people to `click` the link, just tell them that it is a link. -->
        If you are not redirected automatically, follow this <a href='http://example.com'>link to example</a>.
    </body>
</html>

For completeness, I think the best way, if possible, is to use server redirects, so send a 301 status code. This is easy to do via .htaccess files using Apache, or via numerous plugins using WordPress. I am sure there are also plugins for all the major content management systems. Also, cPanel has very easy configuration for 301 redirects if you have that installed on your server.

How to get the SHA-1 fingerprint certificate in Android Studio for debug mode?

The best solution for generating an SHA-1 key for Android is from Android Studio.

Click on Gradle on the far right side:

Click on the refresh icon, and you will see the name of the app:

Click on Tasks -> Report -> Signing Report:

Find the SHA-1 key on the bottom part in the console:

Setting the Textbox read only property to true using JavaScript

it depends on how you trigger the event. the key you are looking is textbox.clientid.

x.aspx code

<script type="text/javascript">

   function disable_textbox(tid) {
        var mytextbox = document.getElementById(tid);
         mytextbox.disabled=false
   }
</script>

code behind x.aspx.cs

    string frameScript = "<script language='javascript'>" + "disable_textbox(" + tx.ClientID  ");</script>";
    Page.ClientScript.RegisterStartupScript(Page.GetType(), "FrameScript", frameScript);

How do you clear a slice in Go?

It all depends on what is your definition of 'clear'. One of the valid ones certainly is:

slice = slice[:0]

But there's a catch. If slice elements are of type T:

var slice []T

then enforcing len(slice) to be zero, by the above "trick", doesn't make any element of

slice[:cap(slice)]

eligible for garbage collection. This might be the optimal approach in some scenarios. But it might also be a cause of "memory leaks" - memory not used, but potentially reachable (after re-slicing of 'slice') and thus not garbage "collectable".

Python: slicing a multi-dimensional array

If you use numpy, this is easy:

slice = arr[:2,:2]

or if you want the 0's,

slice = arr[0:2,0:2]

You'll get the same result.

*note that slice is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".


Another way, if you're working with lists of lists*:

slice = [arr[i][0:2] for i in range(0,2)]

(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)] would also work.).

What I did here is that I take each desired row 1 at a time (arr[i]). I then slice the columns I want out of that row and add it to the list that I'm building.

If you naively try: arr[0:2] You get the first 2 rows which if you then slice again arr[0:2][0:2], you're just slicing the first two rows over again.

*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.

Convert list of ASCII codes to string (byte array) in Python

I much prefer the array module to the struct module for this kind of tasks (ones involving sequences of homogeneous values):

>>> import array
>>> array.array('B', [17, 24, 121, 1, 12, 222, 34, 76]).tostring()
'\x11\x18y\x01\x0c\xde"L'

no len call, no string manipulation needed, etc -- fast, simple, direct, why prefer any other approach?!

Pandas dataframe groupby plot

Simple plot,

you can use:

df.plot(x='Date',y='adj_close')

Or you can set the index to be Date beforehand, then it's easy to plot the column you want:

df.set_index('Date', inplace=True)
df['adj_close'].plot()

If you want a chart with one series by ticker on it

You need to groupby before:

df.set_index('Date', inplace=True)
df.groupby('ticker')['adj_close'].plot(legend=True)

enter image description here


If you want a chart with individual subplots:

grouped = df.groupby('ticker')

ncols=2
nrows = int(np.ceil(grouped.ngroups/ncols))

fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,4), sharey=True)

for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
    grouped.get_group(key).plot(ax=ax)

ax.legend()
plt.show()

enter image description here

Is Java a Compiled or an Interpreted programming language ?

Java is compiled to bytecode, which then goes into the Java VM, which interprets it.

How to remove all ListBox items?

I think it would be better to actually bind your listBoxes to a datasource, since it looks like you are adding the same elements to each listbox. A simple example would be something like this:

    private List<String> _weight = new List<string>() { "kilogram", "pound" };
    private List<String> _height = new List<string>() { "foot", "inch", "meter" };

    public Window1()
    {            
        InitializeComponent();
    }        

    private void Weight_Click(object sender, RoutedEventArgs e)
    {
        listBox1.ItemsSource = _weight;
        listBox2.ItemsSource = _weight;
    }

    private void Height_Click(object sender, RoutedEventArgs e)
    {
        listBox1.ItemsSource = _height;
        listBox2.ItemsSource = _height;
    }

Android- create JSON Array and JSON Object

  public void DataSendReg(String picPath, final String ed2, String ed4, int bty1, String bdatee, String ed1, String cno, String address , String select_item, String select_item1, String height, String weight) {

      final ProgressDialog dialog=new ProgressDialog(SignInAct.this);
      dialog.setMessage("Process....");
      AsyncHttpClient httpClient=new AsyncHttpClient();
      RequestParams params=new RequestParams();
      File pic = new File(picPath);
      try {
          params.put("image",pic);
      } catch (FileNotFoundException e) {
          e.printStackTrace();
      }
      params.put("height",height);
      params.put("weight",weight);
      params.put("pincode",select_item1);
      params.put("area",select_item);
      params.put("address",address);
      params.put("contactno",cno);
      params.put("username",ed1);
      params.put("email",ed2);
      params.put("pass",ed4);
      params.put("bid",bty1);
      params.put("birthdate",bdatee);
      params.put("city","Surat");
      params.put("state","Gujarat");


      httpClient.post(WebAPI.REGAPI,params,new JsonHttpResponseHandler(){
          @Override
          public void onStart() {
              dialog.show();
          }

          @Override
          public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
              try {
                  String done=response.get("msg").toString();
                  if(done.equals("s")) {
                      Toast.makeText(SignInAct.this, "Registration Success Fully", Toast.LENGTH_SHORT).show();
                      DataPrefrenceMaster.SetRing(ed2);
                      startActivity(new Intent(SignInAct.this, LoginAct.class));
                      finish();
                  }
                  else  if(done.equals("ex")) {
                      Toast.makeText(SignInAct.this, "email already exist", Toast.LENGTH_SHORT).show();
                  }else Toast.makeText(SignInAct.this, "Registration failed", Toast.LENGTH_SHORT).show();
              } catch (JSONException e) {
                  Toast.makeText(SignInAct.this, "e :: ="+e.getMessage(), Toast.LENGTH_SHORT).show();
              }
          }

          @Override
          public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
              Toast.makeText(SignInAct.this, "Server not Responce", Toast.LENGTH_SHORT).show();
              Log.d("jkl","error");
          }

          @Override
          public void onFinish() {
                   dialog.dismiss();
        }
    });
}

Calculate difference between two dates (number of days)?

protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
    DateTime d = Calendar1.SelectedDate;
    // int a;
    TextBox2.Text = d.ToShortDateString();
    string s = Convert.ToDateTime(TextBox2.Text).ToShortDateString();
    string s1 =  Convert.ToDateTime(Label7.Text).ToShortDateString();
    DateTime dt = Convert.ToDateTime(s).Date;
    DateTime dt1 = Convert.ToDateTime(s1).Date;
    if (dt <= dt1)
    {
        Response.Write("<script>alert(' Not a valid Date to extend warranty')</script>");
    }
    else
    {
        string diff = dt.Subtract(dt1).ToString();
        Response.Write(diff);
        Label18.Text = diff;
        Session["diff"] = Label18.Text;
    }
}   

Check whether variable is number or string in JavaScript

Very late to the party; however, the following has always worked well for me when I want to check whether some input is either a string or a number in one shot.

return !!Object.prototype.toString.call(input).match(/\[object (String|Number)\]/);

How do you perform address validation?

Fixaddress.com service is available that provides following services,

1) Address Validation.

2) Address Correction.

3) Address spell correcting.

4) Correct addresses phonetic mistakes.

Fixaddress.com uses USPS and Tiger data as reference data.

For more detail visit below link,

http://www.fixaddress.com/

How to get Chrome to allow mixed content?

On OSX the following works from the command line:

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --allow-running-insecure-content

Expanding tuples into arguments

myfun(*some_tuple) does exactly what you request. The * operator simply unpacks the tuple (or any iterable) and passes them as the positional arguments to the function. Read more about unpacking arguments.

C++ JSON Serialization

There is no reflection in C++. True. But if the compiler can't provide you the metadata you need, you can provide it yourself.

Let's start by making a property struct:

template<typename Class, typename T>
struct PropertyImpl {
    constexpr PropertyImpl(T Class::*aMember, const char* aName) : member{aMember}, name{aName} {}

    using Type = T;

    T Class::*member;
    const char* name;
};

template<typename Class, typename T>
constexpr auto property(T Class::*member, const char* name) {
    return PropertyImpl<Class, T>{member, name};
}

Of course, you also can have a property that takes a setter and getter instead of a pointer to member, and maybe read only properties for calculated value you'd like to serialize. If you use C++17, you can extend it further to make a property that works with lambdas.

Ok, now we have the building block of our compile-time introspection system.

Now in your class Dog, add your metadata:

struct Dog {
    std::string barkType;
    std::string color;
    int weight = 0;

    bool operator==(const Dog& rhs) const {
        return std::tie(barkType, color, weight) == std::tie(rhs.barkType, rhs.color, rhs.weight);
    }

    constexpr static auto properties = std::make_tuple(
        property(&Dog::barkType, "barkType"),
        property(&Dog::color, "color"),
        property(&Dog::weight, "weight")
    );
};

We will need to iterate on that list. To iterate on a tuple, there are many ways, but my preferred one is this:

template <typename T, T... S, typename F>
constexpr void for_sequence(std::integer_sequence<T, S...>, F&& f) {
    using unpack_t = int[];
    (void)unpack_t{(static_cast<void>(f(std::integral_constant<T, S>{})), 0)..., 0};
}

If C++17 fold expressions are available in your compiler, then for_sequence can be simplified to:

template <typename T, T... S, typename F>
constexpr void for_sequence(std::integer_sequence<T, S...>, F&& f) {
    (static_cast<void>(f(std::integral_constant<T, S>{})), ...);
}

This will call a function for each constant in the integer sequence.

If this method don't work or gives trouble to your compiler, you can always use the array expansion trick.

Now that you have the desired metadata and tools, you can iterate through the properties to unserialize:

// unserialize function
template<typename T>
T fromJson(const Json::Value& data) {
    T object;

    // We first get the number of properties
    constexpr auto nbProperties = std::tuple_size<decltype(T::properties)>::value;

    // We iterate on the index sequence of size `nbProperties`
    for_sequence(std::make_index_sequence<nbProperties>{}, [&](auto i) {
        // get the property
        constexpr auto property = std::get<i>(T::properties);

        // get the type of the property
        using Type = typename decltype(property)::Type;

        // set the value to the member
        // you can also replace `asAny` by `fromJson` to recursively serialize
        object.*(property.member) = Json::asAny<Type>(data[property.name]);
    });

    return object;
}

And for serialize:

template<typename T>
Json::Value toJson(const T& object) {
    Json::Value data;

    // We first get the number of properties
    constexpr auto nbProperties = std::tuple_size<decltype(T::properties)>::value;

    // We iterate on the index sequence of size `nbProperties`
    for_sequence(std::make_index_sequence<nbProperties>{}, [&](auto i) {
        // get the property
        constexpr auto property = std::get<i>(T::properties);

        // set the value to the member
        data[property.name] = object.*(property.member);
    });

    return data;
}

If you want recursive serialization and unserialization, you can replace asAny by fromJson.

Now you can use your functions like this:

Dog dog;

dog.color = "green";
dog.barkType = "whaf";
dog.weight = 30;

Json::Value jsonDog = toJson(dog); // produces {"color":"green", "barkType":"whaf", "weight": 30}
auto dog2 = fromJson<Dog>(jsonDog);

std::cout << std::boolalpha << (dog == dog2) << std::endl; // pass the test, both dog are equal!

Done! No need for run-time reflection, just some C++14 goodness!

This code could benefit from some improvement, and could of course work with C++11 with some ajustements.

Note that one would need to write the asAny function. It's just a function that takes a Json::Value and call the right as... function, or another fromJson.

Here's a complete, working example made from the various code snippet of this answer. Feel free to use it.

As mentionned in the comments, this code won't work with msvc. Please refer to this question if you want a compatible code: Pointer to member: works in GCC but not in VS2015

'method' object is not subscriptable. Don't know what's wrong

You need to use parentheses: myList.insert([1, 2, 3]). When you leave out the parentheses, python thinks you are trying to access myList.insert at position 1, 2, 3, because that's what brackets are used for when they are right next to a variable.

Reading from a text file and storing in a String

These are the necersary imports:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

And this is a method that will allow you to read from a File by passing it the filename as a parameter like this: readFile("yourFile.txt");

String readFile(String fileName) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
        return sb.toString();
    } finally {
        br.close();
    }
}

What do I need to do to get Internet Explorer 8 to accept a self signed certificate?

I had the same issue while working with web services. Here Microsoft has a (long) walk-thru showing you how to install stuff on the client to basically say that your self-signed cert is ok. In the end, I just spent the $30 and bought a full certificate from Godaddy.com.

P.S. I know that you can code around the error message but we didn't want to do that for testing reasons.

Python : Trying to POST form using requests

I was having problems here (i.e. sending form-data whilst uploading a file) until I used the following:

files = {'file': (filename, open(filepath, 'rb'), 'text/xml'),
         'Content-Disposition': 'form-data; name="file"; filename="' + filename + '"',
         'Content-Type': 'text/xml'}

That's the input that ended up working for me. In Chrome Dev Tools -> Network tab, I clicked the request I was interested in. In the Headers tab, there's a Form Data section, and it showed both the Content-Disposition and the Content-Type headers being set there.

I did NOT need to set headers in the actual requests.post() command for this to succeed (including them actually caused it to fail)

Get connection string from App.config

It seems like problem is not with reference, you are getting connectionstring as null so please make sure you have added the value to the config file your running project meaning the main program/library that gets started/executed first.

Android: Scale a Drawable or background image?

To customize background image scaling create a resource like this:

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:gravity="center"
    android:src="@drawable/list_bkgnd" />

Then it will be centered in the view if used as background. There are also other flags: http://developer.android.com/guide/topics/resources/drawable-resource.html

Differences between Lodash and Underscore.js

Lodash has got _.mapValues() which is identical to Underscore.js's _.mapObject().

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

Use a XHR and see if it responds you a 404 or not.

var request = new XMLHttpRequest();  
request.open('GET', 'http://www.mozilla.org', true);
request.onreadystatechange = function(){
    if (request.readyState === 4){
        if (request.status === 404) {  
            alert("Oh no, it does not exist!");
        }  
    }
};
request.send();

But notice that it will only work on the same origin. For another host, you will have to use a server-side language to do that, which you will have to figure it out by yourself.

mysqli::query(): Couldn't fetch mysqli

I had the same problem. I changed the localhost parameter in the mysqli object to '127.0.0.1' instead of writing 'localhost'. It worked; I’m not sure how or why.

$db_connection = new mysqli("127.0.0.1","root","","db_name");

Hope it helps.

PHP Multiple Checkbox Array

add [] in the name of the attributes in the input tag

 <form action="" name="frm" method="post">
<input type="checkbox" name="hobby[]" value="coding">  coding &nbsp
<input type="checkbox" name="hobby[]" value="database">  database &nbsp
<input type="checkbox" name="hobby[]" value="software engineer">  soft Engineering <br>
<input type="submit" name="submit" value="submit"> 
</form>

for PHP Code :

<?php
 if(isset($_POST['submit']){
   $hobby = $_POST['hobby'];

   foreach ($hobby as $hobys=>$value) {
             echo "Hobby : ".$value."<br />";
        }
}
?>

iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

The easiest way I found to fix this was to set the height of the body and html elements to 100.1% for any request where the user agent was an iphone. This only works in Landscape mode, but thats all I needed.

html.iphone, 
html.iphone body { height: 100.1%; }

Check it out at https://www.360jungle.com/virtual-tour/25

Cannot find module cv2 when using OpenCV

Try this out:

sudo ldconfig

sudo nano /etc/ld.so.conf.d/opencv.conf

and add this following line in the opencv.conf not in the command window

/usr/local/lib

Then:

sudo ldconfig

sudo nano /etc/bash.bashrc

and add this two lines in the bash.bashrc not in the command window

PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig       
export PKG_CONFIG_PATH

at last reboot your Pi sudo reboot now

and try import cv2

jQuery Combobox/select autocomplete?

jQuery 1.8.1 has an example of this under autocomplete. It's very easy to implement.

How to change the text color of first select option

What about this:

_x000D_
_x000D_
select{
  width: 150px;
  height: 30px;
  padding: 5px;
  color: green;
}
select option { color: black; }
select option:first-child{
  color: green;
}
_x000D_
<select>
  <option>one</option>
  <option>two</option>
</select>
_x000D_
_x000D_
_x000D_

http://jsbin.com/acucan/9

Releasing memory in Python

Memory allocated on the heap can be subject to high-water marks. This is complicated by Python's internal optimizations for allocating small objects (PyObject_Malloc) in 4 KiB pools, classed for allocation sizes at multiples of 8 bytes -- up to 256 bytes (512 bytes in 3.3). The pools themselves are in 256 KiB arenas, so if just one block in one pool is used, the entire 256 KiB arena will not be released. In Python 3.3 the small object allocator was switched to using anonymous memory maps instead of the heap, so it should perform better at releasing memory.

Additionally, the built-in types maintain freelists of previously allocated objects that may or may not use the small object allocator. The int type maintains a freelist with its own allocated memory, and clearing it requires calling PyInt_ClearFreeList(). This can be called indirectly by doing a full gc.collect.

Try it like this, and tell me what you get. Here's the link for psutil.Process.memory_info.

import os
import gc
import psutil

proc = psutil.Process(os.getpid())
gc.collect()
mem0 = proc.get_memory_info().rss

# create approx. 10**7 int objects and pointers
foo = ['abc' for x in range(10**7)]
mem1 = proc.get_memory_info().rss

# unreference, including x == 9999999
del foo, x
mem2 = proc.get_memory_info().rss

# collect() calls PyInt_ClearFreeList()
# or use ctypes: pythonapi.PyInt_ClearFreeList()
gc.collect()
mem3 = proc.get_memory_info().rss

pd = lambda x2, x1: 100.0 * (x2 - x1) / mem0
print "Allocation: %0.2f%%" % pd(mem1, mem0)
print "Unreference: %0.2f%%" % pd(mem2, mem1)
print "Collect: %0.2f%%" % pd(mem3, mem2)
print "Overall: %0.2f%%" % pd(mem3, mem0)

Output:

Allocation: 3034.36%
Unreference: -752.39%
Collect: -2279.74%
Overall: 2.23%

Edit:

I switched to measuring relative to the process VM size to eliminate the effects of other processes in the system.

The C runtime (e.g. glibc, msvcrt) shrinks the heap when contiguous free space at the top reaches a constant, dynamic, or configurable threshold. With glibc you can tune this with mallopt (M_TRIM_THRESHOLD). Given this, it isn't surprising if the heap shrinks by more -- even a lot more -- than the block that you free.

In 3.x range doesn't create a list, so the test above won't create 10 million int objects. Even if it did, the int type in 3.x is basically a 2.x long, which doesn't implement a freelist.

Get all rows from SQLite

I have been looking into the same problem! I think your problem is related to where you identify the variable that you use to populate the ArrayList that you return. If you define it inside the loop, then it will always reference the last row in the table in the database. In order to avoid this, you have to identify it outside the loop:

String name;
if (cursor.moveToFirst()) {

        while (cursor.isAfterLast() == false) {
            name = cursor.getString(cursor
                    .getColumnIndex(countyname));

            list.add(name);
            cursor.moveToNext();
        }
}

Paritition array into N chunks with Numpy

Try numpy.array_split.

From the documentation:

>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
    [array([ 0.,  1.,  2.]), array([ 3.,  4.,  5.]), array([ 6.,  7.])]

Identical to numpy.split, but won't raise an exception if the groups aren't equal length.

If number of chunks > len(array) you get blank arrays nested inside, to address that - if your split array is saved in a, then you can remove empty arrays by:

[x for x in a if x.size > 0]

Just save that back in a if you wish.

How to style the menu items on an Android action bar

I think the code below

<item name="android:actionMenuTextAppearance">@style/MyActionBar.MenuTextStyle</item> 

must be in MyAppTheme section.

Find the max of two or more columns with pandas

You can get the maximum like this:

>>> import pandas as pd
>>> df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
>>> df
   A  B
0  1 -2
1  2  8
2  3  1
>>> df[["A", "B"]]
   A  B
0  1 -2
1  2  8
2  3  1
>>> df[["A", "B"]].max(axis=1)
0    1
1    8
2    3

and so:

>>> df["C"] = df[["A", "B"]].max(axis=1)
>>> df
   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3

If you know that "A" and "B" are the only columns, you could even get away with

>>> df["C"] = df.max(axis=1)

And you could use .apply(max, axis=1) too, I guess.

how do I query sql for a latest record date for each user

Select * from table1 where lastest_date=(select Max(latest_date) from table1 where user=yourUserName)

Inner Query will return the latest date for the current user, Outer query will pull all the data according to the inner query result.

Programmatically scroll to a specific position in an Android ListView

The Listview scroll will be positioned to top by default, but want to scroll if not visible then use this:

if (listView1.getFirstVisiblePosition() > position || listView1.getLastVisiblePosition() < position)
            listView1.setSelection(position);

How to take last four characters from a varchar?

Use the RIGHT() function: http://msdn.microsoft.com/en-us/library/ms177532(v=sql.105).aspx

SELECT RIGHT( '1234567890', 4 ); -- returns '7890'

List<String> to ArrayList<String> conversion issue

Arrays.asList does not return instance of java.util.ArrayListbut it returns instance of java.util.Arrays.ArrayList.

You will need to convert to ArrayList if you want to access ArrayList specific information

allWords.addAll(Arrays.asList(strTemp.toLowerCase().split("\\s+")));

VBA for filtering columns

Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:

Sub FilterAndCopy()
Dim LastRow As Long

Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
    .Range("$A:$E").AutoFilter
    .Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
    .Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
    .Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
    .Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
    LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
            Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub

As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.

Access: Move to next record until EOF

I have done this in the past, and have always used this:

  With Me.RecordsetClone
    .MoveFirst
    Do Until .EOF
      If Me.Dirty Then
         Me.Dirty = False
      End If
      .MoveNext
      Me.Bookmark = .Bookmark
    Loop
  End With

Some people would use the form's Recordset, which doesn't require setting the bookmark (i.e., navigating the form's Recordset navigates the form's edit buffer automatically, so the user sees the move immediately), but I prefer the indirection of the RecordsetClone.