Programs & Examples On #Mediacontroller

"Could not find acceptable representation" using spring-boot-starter-web

Add below dependency to your pom.xml:

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.10.2</version>
</dependency>

How to play .mp4 video in videoview in android?

Use Like this:

Uri uri = Uri.parse(URL); //Declare your url here.

VideoView mVideoView  = (VideoView)findViewById(R.id.videoview)
mVideoView.setMediaController(new MediaController(this));       
mVideoView.setVideoURI(uri);
mVideoView.requestFocus();
mVideoView.start();

Another Method:

  String LINK = "type_here_the_link";
  VideoView mVideoView  = (VideoView) findViewById(R.id.videoview);
  MediaController mc = new MediaController(this);
  mc.setAnchorView(videoView);
  mc.setMediaPlayer(videoView);
  Uri video = Uri.parse(LINK);
  mVideoView.setMediaController(mc);
  mVideoView.setVideoURI(video);
  mVideoView.start();

If you are getting this error Couldn't open file on client side, trying server side Error in Android. and also Refer this. Hope this will give you some solution.

Code for download video from Youtube on Java, Android

METHOD 1 ( Recommanded )

Library YouTubeExtractor

Add into your gradle file

 allprojects {
        repositories {
            maven { url "https://jitpack.io" }
        }
    }

And dependencies

 compile 'com.github.Commit451.YouTubeExtractor:youtubeextractor:2.1.0'

Add this small code and you done. Demo HERE

public class MainActivity extends AppCompatActivity {

    private static final String YOUTUBE_ID = "ea4-5mrpGfE";

    private final YouTubeExtractor mExtractor = YouTubeExtractor.create();


    private Callback<YouTubeExtractionResult> mExtractionCallback = new Callback<YouTubeExtractionResult>() {
        @Override
        public void onResponse(Call<YouTubeExtractionResult> call, Response<YouTubeExtractionResult> response) {
            bindVideoResult(response.body());
        }

        @Override
        public void onFailure(Call<YouTubeExtractionResult> call, Throwable t) {
            onError(t);
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


//        For android youtube extractor library  com.github.Commit451.YouTubeExtractor:youtubeextractor:2.1.0'
        mExtractor.extract(YOUTUBE_ID).enqueue(mExtractionCallback);

    }


    private void onError(Throwable t) {
        t.printStackTrace();
        Toast.makeText(MainActivity.this, "It failed to extract. So sad", Toast.LENGTH_SHORT).show();
    }


    private void bindVideoResult(YouTubeExtractionResult result) {

//        Here you can get download url link
        Log.d("OnSuccess", "Got a result with the best url: " + result.getBestAvailableQualityVideoUri());

        Toast.makeText(this, "result : " + result.getSd360VideoUri(), Toast.LENGTH_SHORT).show();
    }
}

You can get download link in bindVideoResult() method.

METHOD 2

Using this library android-youtubeExtractor

Add into gradle file

repositories {
    maven { url "https://jitpack.io" }
}

compile 'com.github.HaarigerHarald:android-youtubeExtractor:master-SNAPSHOT'

Here is the code for getting download url.

       String youtubeLink = "http://youtube.com/watch?v=xxxx";

    YouTubeUriExtractor ytEx = new YouTubeUriExtractor(this) {
        @Override
        public void onUrisAvailable(String videoId, String videoTitle, SparseArray<YtFile> ytFiles) {
            if (ytFiles != null) {
                int itag = 22;
// Here you can get download url
                String downloadUrl = ytFiles.get(itag).getUrl();
            }
        }
    };

    ytEx.execute(youtubeLink);

Playing a video in VideoView in Android

Add android.permission.READ_EXTERNAL_STORAGE in manifest, worked for me

how to play video from url

Check whether your phone supports the video format or not.Even I had the problem when playing a 3gp file but it played a mp4 file perfectly.

Install Android App Bundle on device

Use (on Linux): cd android ./gradlew assemblyRelease|assemblyDebug

An unsigned APK is generated for each case (for debug or testing)

NOTE: On Windows, replace gradle executable for gradlew.bat

How do I add records to a DataGridView in VB.Net?

I think you should build a dataset/datatable in code and bind the grid to that.

no module named zlib

I had a lot of problems making a virtual environment (venv) as described in the tensorflow installation guide.

Most of the commands listed in this post didn't help me either so, if this is also your case this is what I did:

  1. pip3 install --user pipenv
  2. pip install virtualenv

Installs the dependencies to create a virtual environment

  1. mkdir myenv

Makes a new directory called myenv but you can call it whatever you want e.g. mynewenv

  1. cd myenv

Or whatever you call your directory so: cd [your_directory_name]

  1. virtualenv -p /usr/bin/python3 venv

Creates a virtual environment called venv in the folder myenv. You can call your virtual env whatever you like e.g. vitualenv [v_env_name]

  1. source ./venv/bin/activate

Activates the virtual environment. Note that if you choose a different v. env. name your commands should be written as such source ./[v_env_name]/bin/activate

  1. deactivate

Deactivates the virtual environment.

Note: I am using Python 3.6.6 & Ubuntu 18.04

source for the commands

MySQL Workbench - Connect to a Localhost

You need to install mysql server for your machine first. Once done, you will be able to add local db details to it.

For e.g. IP: 127.0.0.1
port: 3306
user: root
pass: pass of root which you have set

Here is the link on step by step guide for linux.

https://support.rackspace.com/how-to/install-mysql-server-on-the-ubuntu-operating-system/

How to get root access on Android emulator?

I used part of the method from the solutions above; however, they did not work completely. On the latest version of Andy, this worked for me:

On Andy (Root Shell) [To get, right click the HandyAndy icon and select Term Shell]

Inside the shell, run these commands:

mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system
cd /system/bin
cat sh > su && chmod 4775 su

Then, install SuperSU and install SU binary. This will replace the SU binary we just created. (Optional) Remove SuperSU and install Superuser by CWM. Install the su binary again. Now, root works!

How to redirect to another page using AngularJS?

Using location.href="./index.html"

or create scope $window

and using $window.location.href="./index.html"

Right way to convert data.frame to a numeric matrix, when df also contains strings?

data.matrix(SFI)

From ?data.matrix:

Description:

 Return the matrix obtained by converting all the variables in a
 data frame to numeric mode and then binding them together as the
 columns of a matrix.  Factors and ordered factors are replaced by
 their internal codes.

Repeat each row of data.frame the number of times specified in a column

Another dplyr alternative with slice where we repeat each row number freq times

library(dplyr)

df %>%  
  slice(rep(seq_len(n()), freq)) %>% 
  select(-freq)

#  var1 var2
#1    a    d
#2    b    e
#3    b    e
#4    c    f
#5    c    f
#6    c    f

seq_len(n()) part can be replaced with any of the following.

df %>% slice(rep(1:nrow(df), freq)) %>% select(-freq)
#Or
df %>% slice(rep(row_number(), freq)) %>% select(-freq)
#Or
df %>% slice(rep(seq_len(nrow(.)), freq)) %>% select(-freq)

Remove Top Line of Text File with PowerShell

Another approach to remove the first line from file, using multiple assignment technique. Refer Link

 $firstLine, $restOfDocument = Get-Content -Path $filename 
 $modifiedContent = $restOfDocument 
 $modifiedContent | Out-String | Set-Content $filename

Use ffmpeg to add text subtitles

I tried using MP4Box for this task, but it couldn't handle the M4V I was dealing with. I had success embedding the SRT as soft subtitles with ffmpeg with the following command line:

ffmpeg -i input.m4v -i input.srt -vcodec copy -acodec copy -scodec copy -map 0:0 -map 0:1 -map 1:0 -y output.mkv

Like you I had to use an MKV output file - I wasn't able to create an M4V file.

How do I select last 5 rows in a table without sorting?

i am using this code:

select * from tweets where placeID = '$placeID' and id > (
    (select count(*) from tweets where placeID = '$placeID')-2)

What does template <unsigned int N> mean?

You templatize your class based on an 'unsigned int'.

Example:

template <unsigned int N>
class MyArray
{
    public:
    private:
        double    data[N]; // Use N as the size of the array
};

int main()
{
    MyArray<2>     a1;
    MyArray<2>     a2;

    MyArray<4>     b1;

    a1 = a2;  // OK The arrays are the same size.
    a1 = b1;  // FAIL because the size of the array is part of the
              //      template and thus the type, a1 and b1 are different types.
              //      Thus this is a COMPILE time failure.
 }

How do I configure different environments in Angular.js?

We could also do something like this.

(function(){
    'use strict';

    angular.module('app').service('env', function env() {

        var _environments = {
            local: {
                host: 'localhost:3000',
                config: {
                    apiroot: 'http://localhost:3000'
                }
            },
            dev: {
                host: 'dev.com',
                config: {
                    apiroot: 'http://localhost:3000'
                }
            },
            test: {
                host: 'test.com',
                config: {
                    apiroot: 'http://localhost:3000'
                }
            },
            stage: {
                host: 'stage.com',
                config: {
                apiroot: 'staging'
                }
            },
            prod: {
                host: 'production.com',
                config: {
                    apiroot: 'production'
                }
            }
        },
        _environment;

        return {
            getEnvironment: function(){
                var host = window.location.host;
                if(_environment){
                    return _environment;
                }

                for(var environment in _environments){
                    if(typeof _environments[environment].host && _environments[environment].host == host){
                        _environment = environment;
                        return _environment;
                    }
                }

                return null;
            },
            get: function(property){
                return _environments[this.getEnvironment()].config[property];
            }
        }

    });

})();

And in your controller/service, we can inject the dependency and call the get method with property to be accessed.

(function() {
    'use strict';

    angular.module('app').service('apiService', apiService);

    apiService.$inject = ['configurations', '$q', '$http', 'env'];

    function apiService(config, $q, $http, env) {

        var service = {};
        /* **********APIs **************** */
        service.get = function() {
            return $http.get(env.get('apiroot') + '/api/yourservice');
        };

        return service;
    }

})();

$http.get(env.get('apiroot') would return the url based on the host environment.

Java Constructor Inheritance

Suppose constructors were inherited... then because every class eventually derives from Object, every class would end up with a parameterless constructor. That's a bad idea. What exactly would you expect:

FileInputStream stream = new FileInputStream();

to do?

Now potentially there should be a way of easily creating the "pass-through" constructors which are fairly common, but I don't think it should be the default. The parameters needed to construct a subclass are often different from those required by the superclass.

Can't find the 'libpq-fe.h header when trying to install pg gem

I had also tried doing gem install libpq-dev, but I received this error:

Can't find the 'libpq-fe.h header
*** extconf.rb failed ***

However I found that installing with sudo apt-get (which I try to avoid using with Ruby on Rails) worked, i.e.

sudo apt-get install libpq-dev
# or
apt-get install postgres-server-dev-{pg.version}
# for postgresql 9.4 on Ubuntu 14.04

then I was able to do

gem install pg

without issues.

How to upgrade safely php version in wamp server

One important step is missing in all answers. I successfully upgraded with following steps:

  • stop apache service with wamp stack manager.
  • rename your wampstack/php dir to wampstack/php_old
  • copy new php dir to wampstack/
  • replace wampstack/php/php.ini by wampstack/php_old/php.ini
  • test and fix any error with php -v (for example missing extensions)
  • [optional] update php version in wampstack/properties.ini
  • Replace wampstack/apache/bin/php7ts.dll by wampstack/php/php7ts.dll
    • This is not mentioned in the other answers but you need this to use the right php version in apache!
  • start apache service

Difference between shared objects (.so), static libraries (.a), and DLL's (.so)?

I can elaborate on the details of DLLs in Windows to help clarify those mysteries to my friends here in *NIX-land...

A DLL is like a Shared Object file. Both are images, ready to load into memory by the program loader of the respective OS. The images are accompanied by various bits of metadata to help linkers and loaders make the necessary associations and use the library of code.

Windows DLLs have an export table. The exports can be by name, or by table position (numeric). The latter method is considered "old school" and is much more fragile -- rebuilding the DLL and changing the position of a function in the table will end in disaster, whereas there is no real issue if linking of entry points is by name. So, forget that as an issue, but just be aware it's there if you work with "dinosaur" code such as 3rd-party vendor libs.

Windows DLLs are built by compiling and linking, just as you would for an EXE (executable application), but the DLL is meant to not stand alone, just like an SO is meant to be used by an application, either via dynamic loading, or by link-time binding (the reference to the SO is embedded in the application binary's metadata, and the OS program loader will auto-load the referenced SO's). DLLs can reference other DLLs, just as SOs can reference other SOs.

In Windows, DLLs will make available only specific entry points. These are called "exports". The developer can either use a special compiler keyword to make a symbol an externally-visible (to other linkers and the dynamic loader), or the exports can be listed in a module-definition file which is used at link time when the DLL itself is being created. The modern practice is to decorate the function definition with the keyword to export the symbol name. It is also possible to create header files with keywords which will declare that symbol as one to be imported from a DLL outside the current compilation unit. Look up the keywords __declspec(dllexport) and __declspec(dllimport) for more information.

One of the interesting features of DLLs is that they can declare a standard "upon load/unload" handler function. Whenever the DLL is loaded or unloaded, the DLL can perform some initialization or cleanup, as the case may be. This maps nicely into having a DLL as an object-oriented resource manager, such as a device driver or shared object interface.

When a developer wants to use an already-built DLL, she must either reference an "export library" (*.LIB) created by the DLL developer when she created the DLL, or she must explicitly load the DLL at run time and request the entry point address by name via the LoadLibrary() and GetProcAddress() mechanisms. Most of the time, linking against a LIB file (which simply contains the linker metadata for the DLL's exported entry points) is the way DLLs get used. Dynamic loading is reserved typically for implementing "polymorphism" or "runtime configurability" in program behaviors (accessing add-ons or later-defined functionality, aka "plugins").

The Windows way of doing things can cause some confusion at times; the system uses the .LIB extension to refer to both normal static libraries (archives, like POSIX *.a files) and to the "export stub" libraries needed to bind an application to a DLL at link time. So, one should always look to see if a *.LIB file has a same-named *.DLL file; if not, chances are good that *.LIB file is a static library archive, and not export binding metadata for a DLL.

Determining 32 vs 64 bit in C++

I'm adding this answer as a use case and complete example for the runtime-check described in another answer.

This is the approach I've been taking for conveying to the end-user whether the program was compiled as 64-bit or 32-bit (or other, for that matter):

version.h

#ifndef MY_VERSION
#define MY_VERSION

#include <string>

const std::string version = "0.09";
const std::string arch = (std::to_string(sizeof(void*) * 8) + "-bit");

#endif

test.cc

#include <iostream>
#include "version.h"

int main()
{
    std::cerr << "My App v" << version << " [" << arch << "]" << std::endl;
}

Compile and Test

g++ -g test.cc
./a.out
My App v0.09 [64-bit]

bash assign default value

Please look at http://www.tldp.org/LDP/abs/html/parameter-substitution.html for examples

${parameter-default}, ${parameter:-default}

If parameter not set, use default. After the call, parameter is still not set.
Both forms are almost equivalent. The extra : makes a difference only when parameter has been declared, but is null.

unset EGGS
echo 1 ${EGGS-spam}   # 1 spam
echo 2 ${EGGS:-spam}  # 2 spam

EGGS=
echo 3 ${EGGS-spam}   # 3
echo 4 ${EGGS:-spam}  # 4 spam

EGGS=cheese
echo 5 ${EGGS-spam}   # 5 cheese
echo 6 ${EGGS:-spam}  # 6 cheese

${parameter=default}, ${parameter:=default}

If parameter not set, set parameter value to default.
Both forms nearly equivalent. The : makes a difference only when parameter has been declared and is null

# sets variable without needing to reassign
# colons suppress attempting to run the string
unset EGGS
: ${EGGS=spam}
echo 1 $EGGS     # 1 spam
unset EGGS
: ${EGGS:=spam}
echo 2 $EGGS     # 2 spam

EGGS=
: ${EGGS=spam}
echo 3 $EGGS     # 3        (set, but blank -> leaves alone)
EGGS=
: ${EGGS:=spam}
echo 4 $EGGS     # 4 spam

EGGS=cheese
: ${EGGS:=spam}
echo 5 $EGGS     # 5 cheese
EGGS=cheese
: ${EGGS=spam}
echo 6 $EGGS     # 6 cheese

${parameter+alt_value}, ${parameter:+alt_value}

If parameter set, use alt_value, else use null string. After the call, parameter value not changed.
Both forms nearly equivalent. The : makes a difference only when parameter has been declared and is null

unset EGGS
echo 1 ${EGGS+spam}  # 1
echo 2 ${EGGS:+spam} # 2

EGGS=
echo 3 ${EGGS+spam}  # 3 spam
echo 4 ${EGGS:+spam} # 4

EGGS=cheese
echo 5 ${EGGS+spam}  # 5 spam
echo 6 ${EGGS:+spam} # 6 spam

Find object by its property in array of objects with AngularJS way

The solucion that work for me is the following

$filter('filter')(data, {'id':10}) 

How do I change JPanel inside a JFrame on the fly?

frame.setContentPane(newContents());
frame.revalidate(); // frame.pack() if you want to resize.

Remember, Java use 'copy reference by value' argument passing. So changing a variable wont change copies of the reference passed to other methods.

Also note JFrame is very confusing in the name of usability. Adding a component or setting a layout (usually) performs the operation on the content pane. Oddly enough, getting the layout really does give you the frame's layout manager.

How to update a single library with Composer?

You can use the following command to update any module with its dependencies

composer update vendor-name/module-name --with-dependencies

How to find all occurrences of an element in a list

While not a solution for lists directly, numpy really shines for this sort of thing:

import numpy as np
values = np.array([1,2,3,1,2,4,5,6,3,2,1])
searchval = 3
ii = np.where(values == searchval)[0]

returns:

ii ==>array([2, 8])

This can be significantly faster for lists (arrays) with a large number of elements vs some of the other solutions.

What does 'Unsupported major.minor version 52.0' mean, and how do I fix it?

Your code was compiled with Java 8.

Either compile your code with an older JDK (compliance level) or run it on a Java 8 JRE.

Hope this helps...

JavaScript closure inside loops – simple practical example

With the support of ES6, the best way to this is to use let and const keywords for this exact circumstance. So var variable get hoisted and with the end of loop the value of i gets updated for all the closures..., we can just use let to set a loop scope variable like this:

var funcs = [];
for (let i = 0; i < 3; i++) {          
    funcs[i] = function() {            
      console.log("My value: " + i); 
    };
}

Request failed: unacceptable content-type: text/html using AFNetworking 2.0

On the server side, I added:

header('Content-type: application/json');

into my .php code and this also fixed the problem.

Why would Oracle.ManagedDataAccess not work when Oracle.DataAccess does?

A "little" late to the party but the real answer to this - if you use Oracle.ManagedDataAccess ODP.NET provider, you should forget about things like network\admin, Oracle client, Oracle_Home, etc.

Here is what you need

  1. Download and install Oracle Developer Tools for VS or ODAC. Note - Dev tools will install ODAC for you. This will create relatively small installation under C:\Program Files (x86). With full dev tools, under 60Mb
  2. In your project you will install Nuget package with corresponding version of ODP.net (Oracle.ManagedDataAccess.dll) which you will reference
  3. At this point you have 2 options to connect.

    • a) In the connection string set datasource in the following format

      DataSource=ServerName:Port/SID . . . or DataSource=IP:Port/SID . . .

    • b) Create tnsnames.ora file (only it is going to be different from previous experiences). Have entry in it:

      AAA = (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = ServerNameOrIP)(PORT = 1521))
      (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = SIDNAME)))

      And place this file into your bin folder, where your application is running from. Now you can connect using your connection name - DataSource=AAA . . . So, even though you have tnsnames.ora, with ODP.net managed it works a bit different - you create local TNS file. And now, it is easy to manage it.

To summarize - with managed, no need for heavy Oracle Client, Oracle_home or knowing depths of oracle installation folders. Everything can be done within your .net application structures.

Make multiple-select to adjust its height to fit options without scroll bar

I had this requirement recently and used other posts from this question to create this script:

$("select[multiple]").each(function() {
  $(this).css("height","100%")
    .attr("size",this.length);
})

How do you get the "object reference" of an object in java when toString() and hashCode() have been overridden?

This is how I solved it:

Integer.toHexString(System.identityHashCode(object));

How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

I found a possible solution, but... I don't know if it's a good solution.

@Entity
public class Role extends Identifiable {

    @ManyToMany(cascade ={CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinTable(name="Role_Permission",
            joinColumns=@JoinColumn(name="Role_id"),
            inverseJoinColumns=@JoinColumn(name="Permission_id")
        )
    public List<Permission> getPermissions() {
        return permissions;
    }

    public void setPermissions(List<Permission> permissions) {
        this.permissions = permissions;
    }
}

@Entity
public class Permission extends Identifiable {

    @ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinTable(name="Role_Permission",
            joinColumns=@JoinColumn(name="Permission_id"),
            inverseJoinColumns=@JoinColumn(name="Role_id")
        )
    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }

I have tried this and it works. When you delete Role, also the relations are deleted (but not the Permission entities) and when you delete Permission, the relations with Role are deleted too (but not the Role instance). But we are mapping a unidirectional relation two times and both entities are the owner of the relation. Could this cause some problems to Hibernate? Which type of problems?

Thanks!

The code above is from another post related.

Button background as transparent

Code:

button.setVisibility(View.INVISIBLE);

Xml:

android:background="@android:color/transparent"

How should I resolve java.lang.IllegalArgumentException: protocol = https host = null Exception?

URLs use forward slashes (/), not backward ones (as windows). Try:

serverURLS = "https://abc.my.domain.com:55555/update";

The reason why you get the error is that the URL class can't parse the host part of the string and therefore, host is null.

how to write procedure to insert data in to the table in phpmyadmin?

This method work for me:

DELIMITER $$
DROP PROCEDURE IF EXISTS db.test $$
CREATE PROCEDURE db.test(IN id INT(12),IN NAME VARCHAR(255))
 BEGIN
 INSERT INTO USER VALUES(id,NAME);
 END$$
DELIMITER ;

Can I install the "app store" in an IOS simulator?

You can install other builds but not Appstore build.

From Xcode 8.2,drag and drop the build to simulator for the installation.

https://stackoverflow.com/a/41671233/1522584

What is the role of "Flatten" in Keras?

It is rule of thumb that the first layer in your network should be the same shape as your data. For example our data is 28x28 images, and 28 layers of 28 neurons would be infeasible, so it makes more sense to 'flatten' that 28,28 into a 784x1. Instead of wriitng all the code to handle that ourselves, we add the Flatten() layer at the begining, and when the arrays are loaded into the model later, they'll automatically be flattened for us.

Python pandas: fill a dataframe row by row

If your input rows are lists rather than dictionaries, then the following is a simple solution:

import pandas as pd
list_of_lists = []
list_of_lists.append([1,2,3])
list_of_lists.append([4,5,6])

pd.DataFrame(list_of_lists, columns=['A', 'B', 'C'])
#    A  B  C
# 0  1  2  3
# 1  4  5  6

Insert Picture into SQL Server 2005 Image Field using only SQL

I achieved the goal where I have multiple images to insert in the DB as

INSERT INTO [dbo].[User]
           ([Name]
           ,[Image1]
           ,[Age]
           ,[Image2]
           ,[GroupId]
           ,[GroupName])
           VALUES
           ('Umar'
           , (SELECT BulkColumn 
            FROM Openrowset( Bulk 'path-to-file.jpg', Single_Blob) as Image1)
           ,26
           ,(SELECT BulkColumn 
            FROM Openrowset( Bulk 'path-to-file.jpg', Single_Blob) as Image2)
            ,'Group123'
           ,'GroupABC')

git with IntelliJ IDEA: Could not read from remote repository

what @yabin ya says is a cool solution, just remind you that: if u still get the same problem,go to Settings-Version Control-GitHub and uncheck the Clone git repositories using ssh.

Setting Timeout Value For .NET Web Service

Try setting the timeout value in your web service proxy class:

WebReference.ProxyClass myProxy = new WebReference.ProxyClass();
myProxy.Timeout = 100000; //in milliseconds, e.g. 100 seconds

Malformed String ValueError ast.literal_eval() with String representation of Tuple

I know this is an old question, but I think found a very simple answer, in case anybody needs it.

If you put string quotes inside your string ("'hello'"), ast_literaleval() will understand it perfectly.

You can use a simple function:

    def doubleStringify(a):
        b = "\'" + a + "\'"
        return b

Or probably more suitable for this example:

    def perfectEval(anonstring):
        try:
            ev = ast.literal_eval(anonstring)
            return ev
        except ValueError:
            corrected = "\'" + anonstring + "\'"
            ev = ast.literal_eval(corrected)
            return ev

How to merge remote changes at GitHub?

This problem can also occur when you have conflicting tags. If your local version and remote version use same tag name for different commits, you can end up here.

You can solve it my deleting the local tag:

$ git tag --delete foo_tag

Regular cast vs. static_cast vs. dynamic_cast

You should look at the article C++ Programming/Type Casting.

It contains a good description of all of the different cast types. The following taken from the above link:

const_cast

const_cast(expression) The const_cast<>() is used to add/remove const(ness) (or volatile-ness) of a variable.

static_cast

static_cast(expression) The static_cast<>() is used to cast between the integer types. 'e.g.' char->long, int->short etc.

Static cast is also used to cast pointers to related types, for example casting void* to the appropriate type.

dynamic_cast

Dynamic cast is used to convert pointers and references at run-time, generally for the purpose of casting a pointer or reference up or down an inheritance chain (inheritance hierarchy).

dynamic_cast(expression)

The target type must be a pointer or reference type, and the expression must evaluate to a pointer or reference. Dynamic cast works only when the type of object to which the expression refers is compatible with the target type and the base class has at least one virtual member function. If not, and the type of expression being cast is a pointer, NULL is returned, if a dynamic cast on a reference fails, a bad_cast exception is thrown. When it doesn't fail, dynamic cast returns a pointer or reference of the target type to the object to which expression referred.

reinterpret_cast

Reinterpret cast simply casts one type bitwise to another. Any pointer or integral type can be casted to any other with reinterpret cast, easily allowing for misuse. For instance, with reinterpret cast one might, unsafely, cast an integer pointer to a string pointer.

Trees in Twitter Bootstrap

For those still searching for a tree with CSS3, this is a fantastic piece of code I found on the net:

http://thecodeplayer.com/walkthrough/css3-family-tree

HTML

<div class="tree">
  <ul>
    <li>
      <a href="#">Parent</a>
      <ul>
        <li>
          <a href="#">Child</a>
          <ul>
            <li>
              <a href="#">Grand Child</a>
            </li>
          </ul>
        </li>
        <li>
          <a href="#">Child</a>
          <ul>
            <li><a href="#">Grand Child</a></li>
            <li>
              <a href="#">Grand Child</a>
              <ul>
                <li>
                  <a href="#">Great Grand Child</a>
                </li>
                <li>
                  <a href="#">Great Grand Child</a>
                </li>
                <li>
                  <a href="#">Great Grand Child</a>
                </li>
              </ul>
            </li>
            <li><a href="#">Grand Child</a></li>
          </ul>
        </li>
      </ul>
    </li>
  </ul>
</div>

CSS

* {margin: 0; padding: 0;}

.tree ul {
  padding-top: 20px; position: relative;

  transition: all 0.5s;
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
}

.tree li {
  float: left; text-align: center;
  list-style-type: none;
  position: relative;
  padding: 20px 5px 0 5px;

  transition: all 0.5s;
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
}

/*We will use ::before and ::after to draw the connectors*/

.tree li::before, .tree li::after{
  content: '';
  position: absolute; top: 0; right: 50%;
  border-top: 1px solid #ccc;
  width: 50%; height: 20px;
}
.tree li::after{
  right: auto; left: 50%;
  border-left: 1px solid #ccc;
}

/*We need to remove left-right connectors from elements without 
any siblings*/
.tree li:only-child::after, .tree li:only-child::before {
  display: none;
}

/*Remove space from the top of single children*/
.tree li:only-child{ padding-top: 0;}

/*Remove left connector from first child and 
right connector from last child*/
.tree li:first-child::before, .tree li:last-child::after{
  border: 0 none;
}
/*Adding back the vertical connector to the last nodes*/
.tree li:last-child::before{
  border-right: 1px solid #ccc;
  border-radius: 0 5px 0 0;
  -webkit-border-radius: 0 5px 0 0;
  -moz-border-radius: 0 5px 0 0;
}
.tree li:first-child::after{
  border-radius: 5px 0 0 0;
  -webkit-border-radius: 5px 0 0 0;
  -moz-border-radius: 5px 0 0 0;
}

/*Time to add downward connectors from parents*/
.tree ul ul::before{
  content: '';
  position: absolute; top: 0; left: 50%;
  border-left: 1px solid #ccc;
  width: 0; height: 20px;
}

.tree li a{
  border: 1px solid #ccc;
  padding: 5px 10px;
  text-decoration: none;
  color: #666;
  font-family: arial, verdana, tahoma;
  font-size: 11px;
  display: inline-block;

  border-radius: 5px;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;

  transition: all 0.5s;
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
}

/*Time for some hover effects*/
/*We will apply the hover effect the the lineage of the element also*/
.tree li a:hover, .tree li a:hover+ul li a {
  background: #c8e4f8; color: #000; border: 1px solid #94a0b4;
}
/*Connector styles on hover*/
.tree li a:hover+ul li::after, 
.tree li a:hover+ul li::before, 
.tree li a:hover+ul::before, 
.tree li a:hover+ul ul::before{
  border-color:  #94a0b4;
}

PS: apart from the code, I also like the way the site shows it in action... really innovative.

Cannot overwrite model once compiled Mongoose

I solved this issue by doing this

// Created Schema - Users
// models/Users.js
const mongoose = require("mongoose");

const Schema = mongoose.Schema;

export const userSchema = new Schema({
  // ...
});

Then in other files

// Another file
// index.js
import { userSchema } from "../models/Users";
const conn = mongoose.createConnection(process.env.CONNECTION_STRING, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
conn.models = {};
const Users = conn.model("Users", userSchema);
const results = await Users.find({});

Better Solution

let User;
try {
  User = mongoose.model("User");
} catch {
  User = mongoose.model("User", userSchema);
}

I hope this helps...

How to convert an array of key-value tuples into an object

Update 2020: As baao notes, Object.fromEntries(arr) now does this on all modern browsers.


You can use Object.assign, the spread operator, and destructuring assignment for an approach that uses map instead of @royhowie’s reduce, which may or may not be more intuitive:

Object.assign(...arr.map(([key, val]) => ({[key]: val})))

E.g.:

_x000D_
_x000D_
var arr = [ [ 'cardType', 'iDEBIT' ],
  [ 'txnAmount', '17.64' ],
  [ 'txnId', '20181' ],
  [ 'txnType', 'Purchase' ],
  [ 'txnDate', '2015/08/13 21:50:04' ],
  [ 'respCode', '0' ],
  [ 'isoCode', '0' ],
  [ 'authCode', '' ],
  [ 'acquirerInvoice', '0' ],
  [ 'message', '' ],
  [ 'isComplete', 'true' ],
  [ 'isTimeout', 'false' ] ]

var obj = Object.assign(...arr.map(([key, val]) => ({[key]: val})))

console.log(obj)
_x000D_
_x000D_
_x000D_

Declare a constant array

From Effective Go:

Constants in Go are just that—constant. They are created at compile time, even when defined as locals in functions, and can only be numbers, characters (runes), strings or booleans. Because of the compile-time restriction, the expressions that define them must be constant expressions, evaluatable by the compiler. For instance, 1<<3 is a constant expression, while math.Sin(math.Pi/4) is not because the function call to math.Sin needs to happen at run time.

Slices and arrays are always evaluated during runtime:

var TestSlice = []float32 {.03, .02}
var TestArray = [2]float32 {.03, .02}
var TestArray2 = [...]float32 {.03, .02}

[...] tells the compiler to figure out the length of the array itself. Slices wrap arrays and are easier to work with in most cases. Instead of using constants, just make the variables unaccessible to other packages by using a lower case first letter:

var ThisIsPublic = [2]float32 {.03, .02}
var thisIsPrivate = [2]float32 {.03, .02}

thisIsPrivate is available only in the package it is defined. If you need read access from outside, you can write a simple getter function (see Getters in golang).

Convert Dictionary to JSON in Swift

Swift 3:

let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: [])
let jsonString = String(data: jsonData!, encoding: .utf8)!
print(jsonString)

Possible cases for Javascript error: "Expected identifier, string or number"

This sounds to me like a script that was pulled in with src, and loaded just halfway, causing a syntax error sine the remainder is not loaded.

Java, How to implement a Shift Cipher (Caesar Cipher)

Java Shift Caesar Cipher by shift spaces.

Restrictions:

  1. Only works with a positive number in the shift parameter.
  2. Only works with shift less than 26.
  3. Does a += which will bog the computer down for bodies of text longer than a few thousand characters.
  4. Does a cast number to character, so it will fail with anything but ascii letters.
  5. Only tolerates letters a through z. Cannot handle spaces, numbers, symbols or unicode.
  6. Code violates the DRY (don't repeat yourself) principle by repeating the calculation more than it has to.

Pseudocode:

  1. Loop through each character in the string.
  2. Add shift to the character and if it falls off the end of the alphabet then subtract shift from the number of letters in the alphabet (26)
  3. If the shift does not make the character fall off the end of the alphabet, then add the shift to the character.
  4. Append the character onto a new string. Return the string.

Function:

String cipher(String msg, int shift){
    String s = "";
    int len = msg.length();
    for(int x = 0; x < len; x++){
        char c = (char)(msg.charAt(x) + shift);
        if (c > 'z')
            s += (char)(msg.charAt(x) - (26-shift));
        else
            s += (char)(msg.charAt(x) + shift);
    }
    return s;
}

How to invoke it:

System.out.println(cipher("abc", 3));  //prints def
System.out.println(cipher("xyz", 3));  //prints abc

What is the use of BindingResult interface in spring MVC?

Basically BindingResult is an interface which dictates how the object that stores the result of validation should store and retrieve the result of the validation(errors, attempt to bind to disallowed fields etc)

From Spring MVC Form Validation with Annotations Tutorial:

[BindingResult] is Spring’s object that holds the result of the validation and binding and contains errors that may have occurred. The BindingResult must come right after the model object that is validated or else Spring will fail to validate the object and throw an exception.

When Spring sees @Valid, it tries to find the validator for the object being validated. Spring automatically picks up validation annotations if you have “annotation-driven” enabled. Spring then invokes the validator and puts any errors in the BindingResult and adds the BindingResult to the view model.

What are the benefits of learning Vim?

I learned Vim. It wasn't too much effort. Now I absolutely love ci" ci( cw V:s/from/to/g

Getting Exception(org.apache.poi.openxml4j.exception - no content type [M1.13]) when reading xlsx file using Apache POI?

The error is telling you that POI couldn't find a core part of the OOXML file, in this case the content types part. Your file isn't a valid OOXML file, let alone a valid .xlsx file. It is a valid zip file though, otherwise you'd have got an earlier error

Can Excel really load this file? I'd expect it wouldn't be able to, as the exception is most commonly triggered by giving POI a regular .zip file! I suspect your file isn't valid, hence the exception

.

Update: In Apache POI 3.15 (from beta 1 onwards), there's a more helpful set of Exception messages for the more common causes of this problem. You'll now get more descriptive exceptions in this case, eg ODFNotOfficeXmlFileException and OLE2NotOfficeXmlFileException. This raw form should only ever show up if POI really has no clue what you've given it but knows it's broken or invalid.

Use LINQ to get items in one List<>, that are not in another List<>

This can be addressed using the following LINQ expression:

var result = peopleList2.Where(p => !peopleList1.Any(p2 => p2.ID == p.ID));

An alternate way of expressing this via LINQ, which some developers find more readable:

var result = peopleList2.Where(p => peopleList1.All(p2 => p2.ID != p.ID));

Warning: As noted in the comments, these approaches mandate an O(n*m) operation. That may be fine, but could introduce performance issues, and especially if the data set is quite large. If this doesn't satisfy your performance requirements, you may need to evaluate other options. Since the stated requirement is for a solution in LINQ, however, those options aren't explored here. As always, evaluate any approach against the performance requirements your project might have.

How to add background image for input type="button"?

background-image takes an url as a value. Use either

background-image: url ('/image/btn.png');

or

background: url ('/image/btn.png') no-repeat;

which is a shorthand for

background-image: url ('/image/btn.png');
background-repeat: no-repeat;

Also, you might want to look at the button HTML element for fancy submit buttons.

Mock MVC - Add Request Parameter to test

When i analyzed your code. I have also faced the same problem but my problem is if i give value for both first and last name means it is working fine. but when i give only one value means it says 400. anyway use the .andDo(print()) method to find out the error

public void testGetUserByName() throws Exception {
    String firstName = "Jack";
    String lastName = "s";       
    this.userClientObject = client.createClient();
    mockMvc.perform(get("/byName")
            .sessionAttr("userClientObject", this.userClientObject)
            .param("firstName", firstName)
            .param("lastName", lastName)               
    ).andDo(print())
     .andExpect(status().isOk())
            .andExpect(content().contentType("application/json"))
            .andExpect(jsonPath("$[0].id").exists())
            .andExpect(jsonPath("$[0].fn").value("Marge"));
}

If your problem is org.springframework.web.bind.missingservletrequestparameterexception you have to change your code to

@RequestMapping(value = "/byName", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public
    @ResponseBody
    String getUserByName(
        @RequestParam( value="firstName",required = false) String firstName,
        @RequestParam(value="lastName",required = false) String lastName, 
        @ModelAttribute("userClientObject") UserClient userClient)
    {

        return client.getUserByName(userClient, firstName, lastName);
    }

python error: no module named pylab

The error means pylab is not part of the standard Python libraries. You will need to down-load it and install it. I think it's available Here They have installation instructions here

How to delete an item in a list if it exists?

1) Almost-English style:

Test for presence using the in operator, then apply the remove method.

if thing in some_list: some_list.remove(thing)

The removemethod will remove only the first occurrence of thing, in order to remove all occurrences you can use while instead of if.

while thing in some_list: some_list.remove(thing)    
  • Simple enough, probably my choice.for small lists (can't resist one-liners)

2) Duck-typed, EAFP style:

This shoot-first-ask-questions-last attitude is common in Python. Instead of testing in advance if the object is suitable, just carry out the operation and catch relevant Exceptions:

try:
    some_list.remove(thing)
except ValueError:
    pass # or scream: thing not in some_list!
except AttributeError:
    call_security("some_list not quacking like a list!")

Off course the second except clause in the example above is not only of questionable humor but totally unnecessary (the point was to illustrate duck-typing for people not familiar with the concept).

If you expect multiple occurrences of thing:

while True:
    try:
        some_list.remove(thing)
    except ValueError:
        break
  • a little verbose for this specific use case, but very idiomatic in Python.
  • this performs better than #1
  • PEP 463 proposed a shorter syntax for try/except simple usage that would be handy here, but it was not approved.

However, with contextlib's suppress() contextmanager (introduced in python 3.4) the above code can be simplified to this:

with suppress(ValueError, AttributeError):
    some_list.remove(thing)

Again, if you expect multiple occurrences of thing:

with suppress(ValueError):
    while True:
        some_list.remove(thing)

3) Functional style:

Around 1993, Python got lambda, reduce(), filter() and map(), courtesy of a Lisp hacker who missed them and submitted working patches*. You can use filter to remove elements from the list:

is_not_thing = lambda x: x is not thing
cleaned_list = filter(is_not_thing, some_list)

There is a shortcut that may be useful for your case: if you want to filter out empty items (in fact items where bool(item) == False, like None, zero, empty strings or other empty collections), you can pass None as the first argument:

cleaned_list = filter(None, some_list)
  • [update]: in Python 2.x, filter(function, iterable) used to be equivalent to [item for item in iterable if function(item)] (or [item for item in iterable if item] if the first argument is None); in Python 3.x, it is now equivalent to (item for item in iterable if function(item)). The subtle difference is that filter used to return a list, now it works like a generator expression - this is OK if you are only iterating over the cleaned list and discarding it, but if you really need a list, you have to enclose the filter() call with the list() constructor.
  • *These Lispy flavored constructs are considered a little alien in Python. Around 2005, Guido was even talking about dropping filter - along with companions map and reduce (they are not gone yet but reduce was moved into the functools module, which is worth a look if you like high order functions).

4) Mathematical style:

List comprehensions became the preferred style for list manipulation in Python since introduced in version 2.0 by PEP 202. The rationale behind it is that List comprehensions provide a more concise way to create lists in situations where map() and filter() and/or nested loops would currently be used.

cleaned_list = [ x for x in some_list if x is not thing ]

Generator expressions were introduced in version 2.4 by PEP 289. A generator expression is better for situations where you don't really need (or want) to have a full list created in memory - like when you just want to iterate over the elements one at a time. If you are only iterating over the list, you can think of a generator expression as a lazy evaluated list comprehension:

for item in (x for x in some_list if x is not thing):
    do_your_thing_with(item)

Notes

  1. you may want to use the inequality operator != instead of is not (the difference is important)
  2. for critics of methods implying a list copy: contrary to popular belief, generator expressions are not always more efficient than list comprehensions - please profile before complaining

How can I use a carriage return in a HTML tooltip?

As for whom &#10; didn't work you have to style the element on which lines are visible in as : white-space: pre-line;

Referenced from this Answer : https://stackoverflow.com/a/17172412/1460591

How do I convert this list of dictionaries to a csv file?

import csv
toCSV = [{'name':'bob','age':25,'weight':200},
         {'name':'jim','age':31,'weight':180}]
keys = toCSV[0].keys()
with open('people.csv', 'w', newline='')  as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(toCSV)

EDIT: My prior solution doesn't handle the order. As noted by Wilduck, DictWriter is more appropriate here.

multiple where condition codeigniter

$wherecond = "( ( ( username ='" . $username . "' OR status='" . $status . "') AND (id='" . $id . "') ) )"; $this->db->where($wherecond);

If you want to add AND and OR conditions at a time. this will work.

What is the difference between %g and %f in C?

E = exponent expression, simply means power(10, n) or 10 ^ n

F = fraction expression, default 6 digits precision

G = gerneral expression, somehow smart to show the number in a concise way (but really?)

See the below example,

The code

void main(int argc, char* argv[])  
{  
        double a = 4.5;
        printf("=>>>> below is the example for printf 4.5\n");
        printf("%%e %e\n",a);
        printf("%%f %f\n",a);
        printf("%%g %g\n",a);
        printf("%%E %E\n",a);
        printf("%%F %F\n",a);
        printf("%%G %G\n",a);
          
        double b = 1.79e308;
        printf("=>>>> below is the exbmple for printf 1.79*10^308\n");
        printf("%%e %e\n",b);
        printf("%%f %f\n",b);
        printf("%%g %g\n",b);
        printf("%%E %E\n",b);
        printf("%%F %F\n",b);
        printf("%%G %G\n",b);

        double d = 2.25074e-308;
        printf("=>>>> below is the example for printf 2.25074*10^-308\n");
        printf("%%e %e\n",d);
        printf("%%f %f\n",d);
        printf("%%g %g\n",d);
        printf("%%E %E\n",d);
        printf("%%F %F\n",d);
        printf("%%G %G\n",d);
}  

The output

=>>>> below is the example for printf 4.5
%e 4.500000e+00
%f 4.500000
%g 4.5
%E 4.500000E+00
%F 4.500000
%G 4.5
=>>>> below is the exbmple for printf 1.79*10^308
%e 1.790000e+308
%f 178999999999999996376899522972626047077637637819240219954027593177370961667659291027329061638406108931437333529420935752785895444161234074984843178962619172326295244262722141766382622299223626438470088150218987997954747866198184686628013966119769261150988554952970462018533787926725176560021258785656871583744.000000
%g 1.79e+308
%E 1.790000E+308
%F 178999999999999996376899522972626047077637637819240219954027593177370961667659291027329061638406108931437333529420935752785895444161234074984843178962619172326295244262722141766382622299223626438470088150218987997954747866198184686628013966119769261150988554952970462018533787926725176560021258785656871583744.000000
%G 1.79E+308
=>>>> below is the example for printf 2.25074*10^-308
%e 2.250740e-308
%f 0.000000
%g 2.25074e-308
%E 2.250740E-308
%F 0.000000
%G 2.25074E-308

How to fix a locale setting warning from Perl

I am now using this:

$ cat /etc/environment
...
LC_ALL=en_US.UTF-8
LANG=en_US.UTF-8

Then log out of SSH session and log in again.

Old answer:

Only this helped me:

$ locale
locale: Cannot set LC_ALL to default locale: No such file or directory
LANG=en_US.UTF-8
LANGUAGE=
LC_CTYPE=en_US.UTF-8
LC_NUMERIC=ru_RU.UTF-8
LC_TIME=ru_RU.UTF-8
LC_COLLATE="en_US.UTF-8"
LC_MONETARY=ru_RU.UTF-8
LC_MESSAGES="en_US.UTF-8"
LC_PAPER=ru_RU.UTF-8
LC_NAME=ru_RU.UTF-8
LC_ADDRESS=ru_RU.UTF-8
LC_TELEPHONE=ru_RU.UTF-8
LC_MEASUREMENT=ru_RU.UTF-8
LC_IDENTIFICATION=ru_RU.UTF-8
LC_ALL=

$ sudo su

# export LANGUAGE=en_US.UTF-8
# export LANG=en_US.UTF-8
# export LC_ALL=en_US.UTF-8

# locale-gen en_US.UTF-8
Generating locales...
  en_US.UTF-8... up-to-date
Generation complete.

# dpkg-reconfigure locales
Generating locales...
  en_AG.UTF-8... done
  en_AU.UTF-8... done
  en_BW.UTF-8... done
  en_CA.UTF-8... done
  en_DK.UTF-8... done
  en_GB.UTF-8... done
  en_HK.UTF-8... done
  en_IE.UTF-8... done
  en_IN.UTF-8... done
  en_NG.UTF-8... done
  en_NZ.UTF-8... done
  en_PH.UTF-8... done
  en_SG.UTF-8... done
  en_US.UTF-8... up-to-date
  en_ZA.UTF-8... done
  en_ZM.UTF-8... done
  en_ZW.UTF-8... done
Generation complete.

# exit

$ locale
LANG=en_US.UTF-8
LANGUAGE=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=en_US.UTF-8

Java Garbage Collection Log messages

Most of it is explained in the GC Tuning Guide (which you would do well to read anyway).

The command line option -verbose:gc causes information about the heap and garbage collection to be printed at each collection. For example, here is output from a large server application:

[GC 325407K->83000K(776768K), 0.2300771 secs]
[GC 325816K->83372K(776768K), 0.2454258 secs]
[Full GC 267628K->83769K(776768K), 1.8479984 secs]

Here we see two minor collections followed by one major collection. The numbers before and after the arrow (e.g., 325407K->83000K from the first line) indicate the combined size of live objects before and after garbage collection, respectively. After minor collections the size includes some objects that are garbage (no longer alive) but that cannot be reclaimed. These objects are either contained in the tenured generation, or referenced from the tenured or permanent generations.

The next number in parentheses (e.g., (776768K) again from the first line) is the committed size of the heap: the amount of space usable for java objects without requesting more memory from the operating system. Note that this number does not include one of the survivor spaces, since only one can be used at any given time, and also does not include the permanent generation, which holds metadata used by the virtual machine.

The last item on the line (e.g., 0.2300771 secs) indicates the time taken to perform the collection; in this case approximately a quarter of a second.

The format for the major collection in the third line is similar.

The format of the output produced by -verbose:gc is subject to change in future releases.

I'm not certain why there's a PSYoungGen in yours; did you change the garbage collector?

HTML input file selection event not firing upon selecting the same file

Do whatever you want to do after the file loads successfully.just after the completion of your file processing set the value of file control to blank string.so the .change() will always be called even the file name changes or not. like for example you can do this thing and worked for me like charm

   $('#myFile').change(function () {
       LoadFile("myFile");//function to do processing of file.
       $('#myFile').val('');// set the value to empty of myfile control.
    });

Add a column in a table in HIVE QL

You cannot add a column with a default value in Hive. You have the right syntax for adding the column ALTER TABLE test1 ADD COLUMNS (access_count1 int);, you just need to get rid of default sum(max_count). No changes to that files backing your table will happen as a result of adding the column. Hive handles the "missing" data by interpreting NULL as the value for every cell in that column.

So now your have the problem of needing to populate the column. Unfortunately in Hive you essentially need to rewrite the whole table, this time with the column populated. It may be easier to rerun your original query with the new column. Or you could add the column to the table you have now, then select all of its columns plus value for the new column.

You also have the option to always COALESCE the column to your desired default and leave it NULL for now. This option fails when you want NULL to have a meaning distinct from your desired default. It also requires you to depend on always remembering to COALESCE.

If you are very confident in your abilities to deal with the files backing Hive, you could also directly alter them to add your default. In general I would recommend against this because most of the time it will be slower and more dangerous. There might be some case where it makes sense though, so I've included this option for completeness.

How do I debug "Error: spawn ENOENT" on node.js?

Are you changing the env option?

Then look at this answer.


I was trying to spawn a node process and TIL that you should spread the existing environment variables when you spawn else you'll loose the PATH environment variable and possibly other important ones.

This was the fix for me:

const nodeProcess = spawn('node', ['--help'], {
  env: {
    // by default, spawn uses `process.env` for the value of `env`
    // you can _add_ to this behavior, by spreading `process.env`
    ...process.env,
    OTHER_ENV_VARIABLE: 'test',
  }
});

Simple 3x3 matrix inverse code (C++)

I have just created a QMatrix class. It uses the built in vector > container. QMatrix.h It uses the Jordan-Gauss method to compute the inverse of a square matrix.

You can use it as follows:

#include "QMatrix.h"
#include <iostream>

int main(){
QMatrix<double> A(3,3,true);
QMatrix<double> Result = A.inverse()*A; //should give the idendity matrix

std::cout<<A.inverse()<<std::endl;
std::cout<<Result<<std::endl; // for checking
return 0;
}

The inverse function is implemented as follows:

Given a class with the following fields:

template<class T> class QMatrix{
public:
int rows, cols;
std::vector<std::vector<T> > A;

the inverse() function:

template<class T> 
QMatrix<T> QMatrix<T>:: inverse(){
Identity<T> Id(rows); //the Identity Matrix as a subclass of QMatrix.
QMatrix<T> Result = *this; // making a copy and transforming it to the Identity matrix
T epsilon = 0.000001;
for(int i=0;i<rows;++i){
    //check if Result(i,i)==0, if true, switch the row with another

    for(int j=i;j<rows;++j){
        if(std::abs(Result(j,j))<epsilon) { //uses Overloading()(int int) to extract element from Result Matrix
            Result.replace_rows(i,j+1); //switches rows i with j+1
        }
        else break;
    }
    // main part, making a triangular matrix
    Id(i)=Id(i)*(1.0/Result(i,i));
    Result(i)=Result(i)*(1.0/Result(i,i));  // Using overloading ()(int) to get a row form the matrix
    for(int j=i+1;j<rows;++j){
        T temp = Result(j,i);
        Result(j) = Result(j) - Result(i)*temp;
        Id(j) = Id(j) - Id(i)*temp; //doing the same operations to the identity matrix
        Result(j,i)=0; //not necessary, but looks nicer than 10^-15
    }
}

// solving a triangular matrix 
for(int i=rows-1;i>0;--i){
    for(int j=i-1;j>=0;--j){
        T temp = Result(j,i);
        Id(j) = Id(j) - temp*Id(i);
        Result(j)=Result(j)-temp*Result(i);
    }
}

return Id;
}

How do I grant myself admin access to a local SQL Server instance?

I adopted a SQL 2012 database where I was not a sysadmin but was an administrator on the machine. I used SSMS with "Run as Administrator", added my NT account as a SQL login and set the server role to sysadmin. No problem.

JavaScript Extending Class

If you don't like the prototype approach, because it doesn't really behave in a nice OOP-way, you could try this:

var BaseClass = function() 
{
    this.some_var = "foobar";

    /**
     * @return string
     */
    this.someMethod = function() {
        return this.some_var;
    }
};

var MyClass = new Class({ extends: BaseClass }, function()
{
    /**
     * @param string value
     */
    this.__construct = function(value)
    {
        this.some_var = value;
    }
})

Using lightweight library (2k minified): https://github.com/haroldiedema/joii

Return values from the row above to the current row

To solve this problem in Excel, usually I would just type in the literal row number of the cell above, e.g., if I'm typing in Cell A7, I would use the formula =A6. Then if I copied that formula to other cells, they would also use the row of the previous cell.

Another option is to use Indirect(), which resolves the literal statement inside to be a formula. You could use something like:

=INDIRECT("A" & ROW() - 1)

The above formula will resolve to the value of the cell in column A and the row that is one less than that of the cell which contains the formula.

"Please try running this command again as Root/Administrator" error when trying to install LESS

In my case i needed to update the npm version from 5.3.0 ? 5.4.2 .

Before i could use this -- npm i -g npm .. i needed to run two commands which perfectly solved my problem. It is highly likely that it will even solve your problem.

Step 1: sudo chown -R $USER /usr/local

Step 2: npm install -g cordova ionic

After this you should update your npm to latest version

Step 3: npm i -g npm

Then you are good to go. Hope This solves your problem. Cheers!!

Questions every good PHP Developer should be able to answer

I think a good question would be: how does HTTP work? Working with GET and POST data among other HTTP communications is inherent in PHP development. Understanding how HTTP works in a broader context and how PHP implements this goes a long way.

Find unique lines

While sort takes O(n log(n)) time, I prefer using

awk '!seen[$0]++'

awk '!seen[$0]++' is an abbreviation for awk '!seen[$0]++ {print}', print line(=$0) if seen[$0] is not zero. It take more space but only O(n) time.

How to see my Eclipse version?

Same issue i was getting , but When we open our eclipse software then automatically we can see eclipse version and workspace location like these pic below enter image description here

firestore: PERMISSION_DENIED: Missing or insufficient permissions

time limit may be over

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {

    // This rule allows anyone on the internet to view, edit, and delete
    // all data in your Firestore database. It is useful for getting
    // started, but it is configured to expire after 30 days because it
    // leaves your app open to attackers. At that time, all client
    // requests to your Firestore database will be denied.
    //
    // Make sure to write security rules for your app before that time, or else
    // your app will lose access to your Firestore database
    match /{document=**} {
      allow read, write: if request.time < timestamp.date(2020,7, 1);
    }
  }
}

there change date for nowadays in this line:

 allow read, write: if request.time < timestamp.date(2020,7, 1);

http://localhost:8080/ Access Error: 404 -- Not Found Cannot locate document: /

I think I figured out the questions after reading the log. Thanks to Will's reminder, I checked the log and found out the some program else is listening to that port. Before I can start to figure out which program, my computer was restarted and localhost:8080 works and showing tomcat page. Whooh

Finding non-numeric rows in dataframe in pandas?

Already some great answers to this question, however here is a nice snippet that I use regularly to drop rows if they have non-numeric values on some columns:

# Eliminate invalid data from dataframe (see Example below for more context)

num_df = (df.drop(data_columns, axis=1)
         .join(df[data_columns].apply(pd.to_numeric, errors='coerce')))

num_df = num_df[num_df[data_columns].notnull().all(axis=1)]

The way this works is we first drop all the data_columns from the df, and then use a join to put them back in after passing them through pd.to_numeric (with option 'coerce', such that all non-numeric entries are converted to NaN). The result is saved to num_df.

On the second line we use a filter that keeps only rows where all values are not null.

Note that pd.to_numeric is coercing to NaN everything that cannot be converted to a numeric value, so strings that represent numeric values will not be removed. For example '1.25' will be recognized as the numeric value 1.25.

Disclaimer: pd.to_numeric was introduced in pandas version 0.17.0

Example:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({"item": ["a", "b", "c", "d", "e"],
   ...:                    "a": [1,2,3,"bad",5],
   ...:                    "b":[0.1,0.2,0.3,0.4,0.5]})

In [3]: df
Out[3]: 
     a    b item
0    1  0.1    a
1    2  0.2    b
2    3  0.3    c
3  bad  0.4    d
4    5  0.5    e

In [4]: data_columns = ['a', 'b']

In [5]: num_df = (df
   ...:           .drop(data_columns, axis=1)
   ...:           .join(df[data_columns].apply(pd.to_numeric, errors='coerce')))

In [6]: num_df
Out[6]: 
  item   a    b
0    a   1  0.1
1    b   2  0.2
2    c   3  0.3
3    d NaN  0.4
4    e   5  0.5

In [7]: num_df[num_df[data_columns].notnull().all(axis=1)]
Out[7]: 
  item  a    b
0    a  1  0.1
1    b  2  0.2
2    c  3  0.3
4    e  5  0.5

How to copy a folder via cmd?

xcopy "%userprofile%\Desktop\?????????" "D:\Backup\" /s/h/e/k/f/c

should work, assuming that your language setting allows Cyrillic (or you use Unicode fonts in the console).

For reference about the arguments: http://ss64.com/nt/xcopy.html

Remote Procedure call failed with sql server 2008 R2

After trying everything between Stackoverflow and Google, I finally found a solution : http://blogs.lessthandot.com/index.php/datamgmt/dbadmin/remote-procedure-call-failed/

TL;DR :

If you are (or were) running multiple versions of SQL Server on your machine, that Configuration Manager shortcut on your start menu might be pointing to an older version, which it shouldn't be. It was pointing to an old Sql Server 2008 instance in my case.

The solution was to :

  1. Go to either C:\Windows\SysWOW64 or C:\Windows\System32, depending on your system.
  2. Look for an executable called SQLServerManagerXX.msc, and run the latest version if you have multiple ones. In my case, I had both SQLServerManager11.msc and SQLServerManager10.msc, where the 10th gave the error, and the 11th worked perfectly.

Django Server Error: port is already in use

It seems that IDEs, VSCode, Puppeteer, nodemon, express, etc. causes this problem, you ran a process in the background or just closed the debugging area [browser, terminal, etc. ] or whatever , anyway, i have answered same question before, Here you are it's link

https://stackoverflow.com/a/49797588/2918720

Qt - reading from a text file

You have to replace string line

QString line = in.readLine();

into while:

QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
    QMessageBox::information(0, "error", file.errorString());
}

QTextStream in(&file);

while(!in.atEnd()) {
    QString line = in.readLine();    
    QStringList fields = line.split(",");    
    model->appendRow(fields);    
}

file.close();

SQL to add column and comment in table in single command

No, you can't.

There's no reason why you would need to. This is a one-time operation and so takes only an additional second or two to actually type and execute.

If you're adding columns in your web application this is more indicative of a flaw in your data-model as you shouldn't need to be doing it.


In response to your comment that a comment is a column attribute; it may seem so but behind the scenes Oracle stores this as an attribute of an object.

SQL> desc sys.com$
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 OBJ#                                      NOT NULL NUMBER
 COL#                                               NUMBER
 COMMENT$                                           VARCHAR2(4000)

SQL>

The column is optional and sys.col$ does not contain comment information.

I assume, I have no knowledge, that this was done in order to only have one system of dealing with comments rather than multiple.

Java 8 Streams: multiple filters vs. complex condition

A complex filter condition is better in performance perspective, but the best performance will show old fashion for loop with a standard if clause is the best option. The difference on a small array 10 elements difference might ~ 2 times, for a large array the difference is not that big.
You can take a look on my GitHub project, where I did performance tests for multiple array iteration options

For small array 10 element throughput ops/s: 10 element array For medium 10,000 elements throughput ops/s: enter image description here For large array 1,000,000 elements throughput ops/s: 1M elements

NOTE: tests runs on

  • 8 CPU
  • 1 GB RAM
  • OS version: 16.04.1 LTS (Xenial Xerus)
  • java version: 1.8.0_121
  • jvm: -XX:+UseG1GC -server -Xmx1024m -Xms1024m

UPDATE: Java 11 has some progress on the performance, but the dynamics stay the same

Benchmark mode: Throughput, ops/time Java 8vs11

Is it possible to get the current spark context settings in PySpark?

Spark 2.1+

spark.sparkContext.getConf().getAll() where spark is your sparksession (gives you a dict with all configured settings)

Should a RESTful 'PUT' operation return something

If the backend of the REST API is a SQL relational database, then

  1. you should have RowVersion in every record that can be updated (to avoid the lost update problem)
  2. you should always return a new copy of the record after PUT (to get the new RowVersion).

If you don't care about lost updates, or if you want to force your clients to do a GET immediately after a PUT, then don't return anything from PUT.

Get height of div with no height set in css

Can do this in jQuery. Try all options .height(), .innerHeight() or .outerHeight().

$('document').ready(function() {
    $('#right_div').css({'height': $('#left_div').innerHeight()});
});

Example Screenshot

enter image description here

Hope this helps. Thanks!!

How to stop line breaking in vim

You may find set lbr useful; with set wrap on this will wrap but only cutting the line on whitespace and not in the middle of a word.

e.g.

without lbr the li
ne can be split on
a word

and

with lbr on the
line will be
split on 
whitespace only

AngularJS : ng-model binding not updating when changed with jQuery

Angular doesn't know about that change. For this you should call $scope.$digest() or make the change inside of $scope.$apply():

$scope.$apply(function() { 
   // every changes goes here
   $('#selectedDueDate').val(dateText); 
});

See this to better understand dirty-checking

UPDATE: Here is an example

How to check if an item is selected from an HTML drop down list?

<label class="paylabel" for="cardtype">Card Type:</label>
<select id="cardtype" name="cards">
<option value="selectcard">--- Please select ---</option>
<option value="mastercard" selected="selected">Mastercard</option>
<option value="maestro">Maestro</option>
<option value="solo">Solo (UK only)</option>
<option value="visaelectron">Visa Electron</option>
<option value="visadebit">Visa Debit</option>
</select><br />

<script>
    var card = document.getElementById("cardtype");
    if (card.options[card.selectedIndex].value == 'selectcard') {
          alert("Please select a card type");
          return false;
    }
</script>

Remote JMX connection

it seams that your ending quote comes too early. It should be after the last parameter.

This trick worked for me.

I noticed something interesting: when I start my application using the following command line:

java -Dcom.sun.management.jmxremote.port=9999
     -Dcom.sun.management.jmxremote.authenticate=false
     -Dcom.sun.management.jmxremote.ssl=false

If I try to connect to this port from a remote machine using jconsole, the TCP connection succeeds, some data is exchanged between remote jconsole and local jmx agent where my MBean is deployed, and then, jconsole displays a connect error message. I performed a wireshark capture, and it shows data exchange coming from both agent and jconsole.

Thus, this is not a network issue, if I perform a netstat -an with or without java.rmi.server.hostname system property, I have the following bindings:

 TCP    0.0.0.0:9999           0.0.0.0:0              LISTENING
 TCP    [::]:9999              [::]:0                 LISTENING

It means that in both cases the socket created on port 9999 accepts connections from any host on any address.

I think the content of this system property is used somewhere at connection and compared with the actual IP address used by agent to communicate with jconsole. And if those address do not match, connection fails.

I did not have this problem while connecting from the same host using jconsole, only from real physical remote hosts. So, I suppose that this check is done only when connection is coming from the "outside".

Can I disable a CSS :hover effect via JavaScript?

I'd recommend to replace all :hover properties to :active when you detect that device supports touch. Just call this function when you do so as touch().

function touch() {
  if ('ontouchstart' in document.documentElement) {
    for (var sheetI = document.styleSheets.length - 1; sheetI >= 0; sheetI--) {
      var sheet = document.styleSheets[sheetI];
      if (sheet.cssRules) {
        for (var ruleI = sheet.cssRules.length - 1; ruleI >= 0; ruleI--) {
          var rule = sheet.cssRules[ruleI];

          if (rule.selectorText) {
            rule.selectorText = rule.selectorText.replace(':hover', ':active');
          }
        }
      }
    }
  }
}

in iPhone App How to detect the screen resolution of the device

UIScreen class lets you find screen resolution in Points and Pixels.

Screen resolutions is measured in Points or Pixels. It should never be confused with screen size. A smaller screen size can have higher resolution.

UIScreen's 'bounds.width' return rectangular size in Points enter image description here

UIScreen's 'nativeBounds.width' return rectangular size in Pixels.This value is detected as PPI ( Point per inch ). Shows the sharpness & clarity of the Image on a device. enter image description here

You can use UIScreen class to detect all these values.

Swift3

// Normal Screen Bounds - Detect Screen size in Points.
let width = UIScreen.main.bounds.width
let height = UIScreen.main.bounds.height
print("\n width:\(width) \n height:\(height)")

// Native Bounds - Detect Screen size in Pixels.
let nWidth = UIScreen.main.nativeBounds.width
let nHeight = UIScreen.main.nativeBounds.height
print("\n Native Width:\(nWidth) \n Native Height:\(nHeight)")

Console

width:736.0 
height:414.0

Native Width:1080.0 
Native Height:1920.0

Swift 2.x

//Normal Bounds - Detect Screen size in Points.
    let width  = UIScreen.mainScreen.bounds.width
    let height = UIScreen.mainScreen.bounds.height

// Native Bounds - Detect Screen size in Pixels.
    let nWidth  = UIScreen.mainScreen.nativeBounds.width
    let nHeight = UIScreen.mainScreen.nativeBounds.height

ObjectiveC

// Normal Bounds - Detect Screen size in Points.
CGFloat *width  = [UIScreen mainScreen].bounds.size.width;
CGFloat *height = [UIScreen mainScreen].bounds.size.height;

// Native Bounds - Detect Screen size in Pixels.
CGFloat *width  = [UIScreen mainScreen].nativeBounds.size.width
CGFloat *height = [UIScreen mainScreen].nativeBounds.size.width

php Replacing multiple spaces with a single space

Use preg_replace() and instead of [ \t\n\r] use \s:

$output = preg_replace('!\s+!', ' ', $input);

From Regular Expression Basic Syntax Reference:

\d, \w and \s

Shorthand character classes matching digits, word characters (letters, digits, and underscores), and whitespace (spaces, tabs, and line breaks). Can be used inside and outside character classes.

regex with space and letters only?

$('#input').on('keyup', function() {
     var RegExpression = /^[a-zA-Z\s]*$/;  
     ...

});

\s will allow the space

Qt 5.1.1: Application failed to start because platform plugin "windows" is missing

Setting the QT_QPA_PLATFORM_PLUGIN_PATH environment variable to %QTDIR%\plugins\platforms\ worked for me.

It was also mentioned here and here.

What is the purpose of mvnw and mvnw.cmd files?

Command mvnw uses Maven that is by default downloaded to ~/.m2/wrapper on the first use.

URL with Maven is specified in each project at .mvn/wrapper/maven-wrapper.properties:

distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip

To update or change Maven version invoke the following (remember about --non-recursive for multi-module projects):

./mvnw io.takari:maven:wrapper -Dmaven=3.3.9 

or just modify .mvn/wrapper/maven-wrapper.properties manually.

To generate wrapper from scratch using Maven (you need to have it already in PATH run:

mvn io.takari:maven:wrapper -Dmaven=3.3.9 

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

Yes Fiddler is an option for me:

  1. Open Fiddler menu > Rules > Customize Rules (this effectively edits CustomRules.js).
  2. Find the function OnBeforeResponse
  3. Add the following lines:

    oSession.oResponse.headers.Remove("X-Frame-Options");
    oSession.oResponse.headers.Add("Access-Control-Allow-Origin", "*");
    
  4. Remember to save the script!

How do I line up 3 divs on the same row?

2019 answer:

Using CSS grid:

.parent {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr;
}

How to get first and last day of previous month (with timestamp) in SQL Server

I have used the following logic in SSRS reports.

BUS_DATE = 17-09-2013

X=DATEADD(MONTH,-1,BUS_DATE) = 17-08-2013

Y=DAY(BUS_DATE)=17

first_date = DATEADD(DAY,-Y+1,X)=01-08-2013

last_date  = DATEADD(DAY,-Y,BUS_DATE)=31-08-2013

Bootstrap 4 card-deck with number of columns based on viewport

@Zim provided a great solution above (well deserved up-vote from me), however, it didn't quite fit what I needed since I was implementing this in Jekyll and wanted my card deck to automatically update every time I added a post to my site. Growing a card deck such as this with each new post is straight forward in Jekyll, the challenge was to correctly place the breakpoints. My solution make use of additional liquid tags and modulo mathematics.

While this question is old, I came across it and found it useful, and maybe someday someone will come along wanting to do this with Jekyll.

<div class = "container">
  <div class = "card-deck">

    {% for post in site.posts %}
      <div class = "card border-0 mt-2">
        <a href = "{{ post.url }}"><img src = "{{ site.baseurl }}{{ post.image }}" class = "mx-auto" alt = "..."></a>
        <div class = "card-body">
          <h5 class = "card-title"><a href = "{{ post.url }}">{{ post.title }}</a></h5>
          <span>Published: {{ post.date | date_to_long_string }} </span>
          <p class = "text-muted">{{ post.excerpt }}</p>
        </div>
        <div class = "card-footer bg-white border-0"><a href = "{{ post.url }}" class = "btn btn-primary">Read more</a></div>
      </div>

      <!-- Use modulo to add divs to handle break points -->
      {% assign sm = forloop.index | modulo: 2 %}
      {% assign md = forloop.index | modulo: 3 %}
      {% assign lg = forloop.index | modulo: 4 %}
      {% assign xl = forloop.index | modulo: 5 %}

      {% if sm == 0 %}
        <div class="w-100 d-none d-sm-block d-md-none"><!-- wrap every 2 on sm--></div>
      {% endif %}

      {% if md == 0 %}
        <div class="w-100 d-none d-md-block d-lg-none"><!-- wrap every 3 on md--></div>
      {% endif %}

      {% if lg == 0 %}
        <div class="w-100 d-none d-lg-block d-xl-none"><!-- wrap every 4 on lg--></div>
      {% endif %}

      {% if xl == 0 %}
        <div class="w-100 d-none d-xl-block"><!-- wrap every 5 on xl--></div>
      {% endif %}

    {% endfor %}
  </div>
</div>

This whole code block can be used directly in a website or saved in your Jekyll project _includes folder.

Best way in asp.net to force https for an entire site?

What you need to do is :

1) Add a key inside of web.config, depending upon the production or stage server like below

<add key="HttpsServer" value="stage"/>
             or
<add key="HttpsServer" value="prod"/>

2) Inside your Global.asax file add below method.

void Application_BeginRequest(Object sender, EventArgs e)
{
    //if (ConfigurationManager.AppSettings["HttpsServer"].ToString() == "prod")
    if (ConfigurationManager.AppSettings["HttpsServer"].ToString() == "stage")
    {
        if (!HttpContext.Current.Request.IsSecureConnection)
        {
            if (!Request.Url.GetLeftPart(UriPartial.Authority).Contains("www"))
            {
                HttpContext.Current.Response.Redirect(
                    Request.Url.GetLeftPart(UriPartial.Authority).Replace("http://", "https://www."), true);
            }
            else
            {
                HttpContext.Current.Response.Redirect(
                    Request.Url.GetLeftPart(UriPartial.Authority).Replace("http://", "https://"), true);
            }
        }
    }
}

Detect end of ScrollView

You can make use of the Support Library's NestedScrollView and it's NestedScrollView.OnScrollChangeListener interface.

https://developer.android.com/reference/android/support/v4/widget/NestedScrollView.html

Alternatively if your app is targeting API 23 or above, you can make use of the following method on the ScrollView:

View.setOnScrollChangeListener(OnScrollChangeListener listener) 

Then follow the example that @Fustigador described in his answer. Note however that as @Will described, you should consider adding a small buffer in case the user or system isn't able to reach the complete bottom of the list for any reason.

Also worth noting is that the scroll change listener will sometimes be called with negative values or values greater than the view height. Presumably these values represent the 'momentum' of the scroll action. However unless handled appropriately (floor / abs) they can cause problems detecting the scroll direction when the view is scrolled to the top or bottom of the range.

https://developer.android.com/reference/android/view/View.html#setOnScrollChangeListener(android.view.View.OnScrollChangeListener)

How do I check OS with a preprocessor directive?

The Predefined Macros for OS site has a very complete list of checks. Here are a few of them, with links to where they're found:

Windows

_WIN32   Both 32 bit and 64 bit
_WIN64   64 bit only

Unix (Linux, *BSD, Mac OS X)

See this related question on some of the pitfalls of using this check.

unix
__unix
__unix__

Mac OS X

__APPLE__
__MACH__

Both are defined; checking for either should work.

Linux

__linux__
linux Obsolete (not POSIX compliant)
__linux Obsolete (not POSIX compliant)

FreeBSD

__FreeBSD__

Android

__ANDROID__

Number of times a particular character appears in a string

You may do this completely in-line by replacing the desired character with an empty string, calling LENGTH function and substracting from the original string's length.

SELECT 
  CustomerName, 
  LENGTH(CustomerName) -
  LENGTH(REPLACE(CustomerName, ' ', '')) AS NumberOfSpaces
FROM Customers;

Java using scanner enter key pressed

This works using java.util.Scanner and will take multiple "enter" keystrokes:

    Scanner scanner = new Scanner(System.in);
    String readString = scanner.nextLine();
    while(readString!=null) {
        System.out.println(readString);

        if (readString.isEmpty()) {
            System.out.println("Read Enter Key.");
        }

        if (scanner.hasNextLine()) {
            readString = scanner.nextLine();
        } else {
            readString = null;
        }
    }

To break it down:

Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();

These lines initialize a new Scanner that is reading from the standard input stream (the keyboard) and reads a single line from it.

    while(readString!=null) {
        System.out.println(readString);

While the scanner is still returning non-null data, print each line to the screen.

        if (readString.isEmpty()) {
            System.out.println("Read Enter Key.");
        }

If the "enter" (or return, or whatever) key is supplied by the input, the nextLine() method will return an empty string; by checking to see if the string is empty, we can determine whether that key was pressed. Here the text Read Enter Key is printed, but you could perform whatever action you want here.

        if (scanner.hasNextLine()) {
            readString = scanner.nextLine();
        } else {
            readString = null;
        }

Finally, after printing the content and/or doing something when the "enter" key is pressed, we check to see if the scanner has another line; for the standard input stream, this method will "block" until either the stream is closed, the execution of the program ends, or further input is supplied.

Numpy matrix to array

If you'd like something a bit more readable, you can do this:

A = np.squeeze(np.asarray(M))

Equivalently, you could also do: A = np.asarray(M).reshape(-1), but that's a bit less easy to read.

GitHub - failed to connect to github 443 windows/ Failed to connect to gitHub - No Error

I am using Tortoise Git and simply going to Git in Settings and applying the same settings to Global. Apply and Ok. Worked for me.

How to get current time in milliseconds in PHP?

try this:

public function getTimeToMicroseconds() {
    $t = microtime(true);
    $micro = sprintf("%06d", ($t - floor($t)) * 1000000);
    $d = new DateTime(date('Y-m-d H:i:s.' . $micro, $t));

    return $d->format("Y-m-d H:i:s.u"); 
}

Using MySQL with Entity Framework

I didn't see the link here, but there's a beta .NET Connector for MySql. Click "Development Releases" to download 6.3.2 beta, which has EF4/VS2010 integration:

http://dev.mysql.com/downloads/connector/net/5.0.html#downloads

How to plot a 2D FFT in Matlab?

Assuming that I is your input image and F is its Fourier Transform (i.e. F = fft2(I))

You can use this code:

F = fftshift(F); % Center FFT

F = abs(F); % Get the magnitude
F = log(F+1); % Use log, for perceptual scaling, and +1 since log(0) is undefined
F = mat2gray(F); % Use mat2gray to scale the image between 0 and 1

imshow(F,[]); % Display the result

To delay JavaScript function call using jQuery

Very easy, just call the function within a specific amount of milliseconds using setTimeout()

setTimeout(myFunction, 2000)

function myFunction() {
    alert('Was called after 2 seconds');
}

Or you can even initiate the function inside the timeout, like so:

setTimeout(function() {
    alert('Was called after 2 seconds');
}, 2000)

How can I revert multiple Git commits (already pushed) to a published repository?

The Problem

There are a number of work-flows you can use. The main point is not to break history in a published branch unless you've communicated with everyone who might consume the branch and are willing to do surgery on everyone's clones. It's best not to do that if you can avoid it.

Solutions for Published Branches

Your outlined steps have merit. If you need the dev branch to be stable right away, do it that way. You have a number of tools for Debugging with Git that will help you find the right branch point, and then you can revert all the commits between your last stable commit and HEAD.

Either revert commits one at a time, in reverse order, or use the <first_bad_commit>..<last_bad_commit> range. Hashes are the simplest way to specify the commit range, but there are other notations. For example, if you've pushed 5 bad commits, you could revert them with:

# Revert a series using ancestor notation.
git revert --no-edit dev~5..dev

# Revert a series using commit hashes.
git revert --no-edit ffffffff..12345678

This will apply reversed patches to your working directory in sequence, working backwards towards your known-good commit. With the --no-edit flag, the changes to your working directory will be automatically committed after each reversed patch is applied.

See man 1 git-revert for more options, and man 7 gitrevisions for different ways to specify the commits to be reverted.

Alternatively, you can branch off your HEAD, fix things the way they need to be, and re-merge. Your build will be broken in the meantime, but this may make sense in some situations.

The Danger Zone

Of course, if you're absolutely sure that no one has pulled from the repository since your bad pushes, and if the remote is a bare repository, then you can do a non-fast-forward commit.

git reset --hard <last_good_commit>
git push --force

This will leave the reflog intact on your system and the upstream host, but your bad commits will disappear from the directly-accessible history and won't propagate on pulls. Your old changes will hang around until the repositories are pruned, but only Git ninjas will be able to see or recover the commits you made by mistake.

Undefined reference to vtable

What is a vtable?

It might be useful to know what the error message is talking about before trying to fix it. I'll start at a high level, then work down to some more details. That way people can skip ahead once they are comfortable with their understanding of vtables. …and there goes a bunch of people skipping ahead right now. :) For those sticking around:

A vtable is basically the most common implementation of polymorphism in C++. When vtables are used, every polymorphic class has a vtable somewhere in the program; you can think of it as a (hidden) static data member of the class. Every object of a polymorphic class is associated with the vtable for its most-derived class. By checking this association, the program can work its polymorphic magic. Important caveat: a vtable is an implementation detail. It is not mandated by the C++ standard, even though most (all?) C++ compilers use vtables to implement polymorphic behavior. The details I am presenting are either typical or reasonable approaches. Compilers are allowed to deviate from this!

Each polymorphic object has a (hidden) pointer to the vtable for the object's most-derived class (possibly multiple pointers, in the more complex cases). By looking at the pointer, the program can tell what the "real" type of an object is (except during construction, but let's skip that special case). For example, if an object of type A does not point to the vtable of A, then that object is actually a sub-object of something derived from A.

The name "vtable" comes from "virtual function table". It is a table that stores pointers to (virtual) functions. A compiler chooses its convention for how the table is laid out; a simple approach is to go through the virtual functions in the order they are declared within class definitions. When a virtual function is called, the program follows the object's pointer to a vtable, goes to the entry associated with the desired function, then uses the stored function pointer to invoke the correct function. There are various tricks for making this work, but I won't go into those here.

Where/when is a vtable generated?

A vtable is automatically generated (sometimes called "emitted") by the compiler. A compiler could emit a vtable in every translation unit that sees a polymorphic class definition, but that would usually be unnecessary overkill. An alternative (used by gcc, and probably by others) is to pick a single translation unit in which to place the vtable, similar to how you would pick a single source file in which to put a class' static data members. If this selection process fails to pick any translation units, then the vtable becomes an undefined reference. Hence the error, whose message is admittedly not particularly clear.

Similarly, if the selection process does pick a translation unit, but that object file is not provided to the linker, then the vtable becomes an undefined reference. Unfortunately, the error message can be even less clear in this case than in the case where the selection process failed. (Thanks to the answerers who mentioned this possibility. I probably would have forgotten it otherwise.)

The selection process used by gcc makes sense if we start with the tradition of devoting a (single) source file to each class that needs one for its implementation. It would be nice to emit the vtable when compiling that source file. Let's call that our goal. However, the selection process needs to work even if this tradition is not followed. So instead of looking for the implementation of the entire class, let's look for the implementation of a specific member of the class. If tradition is followed – and if that member is in fact implemented – then this achieves the goal.

The member selected by gcc (and potentially by other compilers) is the first non-inline virtual function that is not pure virtual. If you are part of the crowd that declares constructors and destructors before other member functions, then that destructor has a good chance of being selected. (You did remember to make the destructor virtual, right?) There are exceptions; I'd expect that the most common exceptions are when an inline definition is provided for the destructor and when the default destructor is requested (using "= default").

The astute might notice that a polymorphic class is allowed to provide inline definitions for all of its virtual functions. Doesn't that cause the selection process to fail? It does in older compilers. I've read that the latest compilers have addressed this situation, but I do not know relevant version numbers. I could try looking this up, but it's easier to either code around it or wait for the compiler to complain.

In summary, there are three key causes of the "undefined reference to vtable" error:

  1. A member function is missing its definition.
  2. An object file is not being linked.
  3. All virtual functions have inline definitions.

These causes are by themselves insufficient to cause the error on their own. Rather, these are what you would address to resolve the error. Do not expect that intentionally creating one of these situations will definitely produce this error; there are other requirements. Do expect that resolving these situations will resolve this error.

(OK, number 3 might have been sufficient when this question was asked.)

How to fix the error?

Welcome back people skipping ahead! :)

  1. Look at your class definition. Find the first non-inline virtual function that is not pure virtual (not "= 0") and whose definition you provide (not "= default").
    • If there is no such function, try modifying your class so there is one. (Error possibly resolved.)
    • See also the answer by Philip Thomas for a caveat.
  2. Find the definition for that function. If it is missing, add it! (Error possibly resolved.)
  3. Check your link command. If it does not mention the object file with that function's definition, fix that! (Error possibly resolved.)
  4. Repeat steps 2 and 3 for each virtual function, then for each non-virtual function, until the error is resolved. If you're still stuck, repeat for each static data member.

Example
The details of what to do can vary, and sometimes branch off into separate questions (like What is an undefined reference/unresolved external symbol error and how do I fix it?). I will, though, provide an example of what to do in a specific case that might befuddle newer programmers.

Step 1 mentions modifying your class so that it has a function of a certain type. If the description of that function went over your head, you might be in the situation I intend to address. Keep in mind that this is a way to accomplish the goal; it is not the only way, and there easily could be better ways in your specific situation. Let's call your class A. Is your destructor declared (in your class definition) as either

virtual ~A() = default;

or

virtual ~A() {}

? If so, two steps will change your destructor into the type of function we want. First, change that line to

virtual ~A();

Second, put the following line in a source file that is part of your project (preferably the file with the class implementation, if you have one):

A::~A() {}

That makes your (virtual) destructor non-inline and not generated by the compiler. (Feel free to modify things to better match your code formatting style, such as adding a header comment to the function definition.)

What does the 'static' keyword do in a class?

static members belong to the class instead of a specific instance.

It means that only one instance of a static field exists[1] even if you create a million instances of the class or you don't create any. It will be shared by all instances.

Since static methods also do not belong to a specific instance, they can't refer to instance members. In the example given, main does not know which instance of the Hello class (and therefore which instance of the Clock class) it should refer to. static members can only refer to static members. Instance members can, of course access static members.

Side note: Of course, static members can access instance members through an object reference.

Example:

public class Example {
    private static boolean staticField;
    private boolean instanceField;
    public static void main(String[] args) {
        // a static method can access static fields
        staticField = true;

        // a static method can access instance fields through an object reference
        Example instance = new Example();
        instance.instanceField = true;
    }

[1]: Depending on the runtime characteristics, it can be one per ClassLoader or AppDomain or thread, but that is beside the point.

Centering a canvas

This will center the canvas horizontally:

#canvas-container {
   width: 100%;
   text-align:center;
}

canvas {
   display: inline;
}

HTML:

<div id="canvas-container">
   <canvas>Your browser doesn't support canvas</canvas>
</div>

PHP Get Highest Value from Array

Try using asort().

From documentation:

asort - Sort an array and maintain index association

Description:

bool asort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.

Python TypeError: not enough arguments for format string

You need to put the format arguments into a tuple (add parentheses):

instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % (softname, procversion, int(percent), exe, description, company, procurl)

What you currently have is equivalent to the following:

intstr = ("'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname), procversion, int(percent), exe, description, company, procurl

Example:

>>> "%s %s" % 'hello', 'world'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s %s" % ('hello', 'world')
'hello world'

SQL Insert into table only if record doesn't exist

This might be a simple solution to achieve this:

INSERT INTO funds (ID, date, price)
SELECT 23, DATE('2013-02-12'), 22.5
  FROM dual
 WHERE NOT EXISTS (SELECT 1 
                     FROM funds 
                    WHERE ID = 23
                      AND date = DATE('2013-02-12'));

p.s. alternatively (if ID a primary key):

 INSERT INTO funds (ID, date, price)
    VALUES (23, DATE('2013-02-12'), 22.5)
        ON DUPLICATE KEY UPDATE ID = 23; -- or whatever you need

see this Fiddle.

How to make a JSONP request from Javascript without JQuery?

My understanding is that you actually use script tags with JSONP, sooo...

The first step is to create your function that will handle the JSON:

function hooray(json) {
    // dealin wit teh jsonz
}

Make sure that this function is accessible on a global level.

Next, add a script element to the DOM:

var script = document.createElement('script');
script.src = 'http://domain.com/?function=hooray';
document.body.appendChild(script);

The script will load the JavaScript that the API provider builds, and execute it.

Convert dd-mm-yyyy string to date

You could use a Regexp.

var result = /^(\d{2})-(\d{2})-(\d{4})$/.exec($("#datepicker").val());
if (result) {
    from = new Date(
        parseInt(result[3], 10), 
        parseInt(result[2], 10) - 1, 
        parseInt(result[1], 10)
    );
}

How can I select an element with multiple classes in jQuery?

You do not need jQuery for this

In Vanilla you can do :

document.querySelectorAll('.a.b')

How to get the PYTHONPATH in shell?

Adding to @zzzzzzz answer, I ran the command:python3 -c "import sys; print(sys.path)" and it provided me with different paths comparing to the same command with python. The paths that were displayed with python3 were "python3 oriented".

See the output of the two different commands:

python -c "import sys; print(sys.path)"

['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/local/lib/python2.7/dist-packages/setuptools-39.1.0-py2.7.egg', '/usr/lib/python2.7/dist-packages']

python3 -c "import sys; print(sys.path)"

['', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']

Both commands were executed on my Ubuntu 18.04 machine.

How do I execute a program from Python? os.system fails due to spaces in path

For Python 3.7, use subprocess.call. Use raw string to simplify the Windows paths:

import subprocess
subprocess.call([r'C:\Temp\Example\Notepad.exe', 'C:\test.txt'])

List method to delete last element in list as well as all elements

you can use lst.pop() or del lst[-1]

pop() removes and returns the item, in case you don't want have a return use del

HTML/Javascript: how to access JSON data loaded in a script tag with src set

Another solution would be to make use of a server-side scripting language and to simply include json-data inline. Here's an example that uses PHP:

<script id="data" type="application/json"><?php include('stuff.json'); ?></script>
<script>
var jsonData = JSON.parse(document.getElementById('data').textContent)
</script>

The above example uses an extra script tag with type application/json. An even simpler solution is to include the JSON directly into the JavaScript:

<script>var jsonData = <?php include('stuff.json');?>;</script>

The advantage of the solution with the extra tag is that JavaScript code and JSON data are kept separated from each other.

start MySQL server from command line on Mac OS Lion

111028 16:57:43 [ERROR] Fatal error: Please read "Security" section of the manual to find out how to run mysqld as root!

Have you set a root password for your mysql installation? This is different to your sudo root password. Try /usr/local/mysql/bin/mysql_secure_installation

relative path in BAT script

either bin\Iris.exe (no leading slash - because that means start right from the root)
or \Program\bin\Iris.exe (full path)

how to create a Java Date object of midnight today and midnight tomorrow?

The simplest way with JodaTime

DateMidnight date = DateMidnight.now();

How to create a remote Git repository from a local one?

There is an interesting difference between the two popular solutions above:

  1. If you create the bare repository like this:

    cd     /outside_of_any_repo
    mkdir  my_remote.git
    cd     my_remote.git
    git init --bare
    

and then

cd  /your_path/original_repo
git remote add origin /outside_of_any_repo/my_remote.git
git push --set-upstream origin master

Then git sets up the configuration in 'original_repo' with this relationship:

original_repo origin --> /outside_of_any_repo/my_remote.git/

with the latter as the upstream remote. And the upstream remote doesn't have any other remotes in its configuration.

  1. However, if you do it the other way around:

    (from in directory original_repo)
    cd ..
    git clone --bare original_repo  /outside_of_any_repo/my_remote.git
    

then 'my_remote.git' winds up with its configuration having 'origin' pointing back to 'original_repo' as a remote, with a remote.origin.url equating to local directory path, which might not be appropriate if it is going to be moved to a server.

While that "remote" reference is easy to get rid of later if it isn't appropriate, 'original_repo' still has to be set up to point to 'my_remote.git' as an up-stream remote (or to wherever it is going to be shared from). So technically, you can arrive at the same result with a few more steps with approach #2. But #1 seems a more direct approach to creating a "central bare shared repo" originating from a local one, appropriate for moving to a server, with fewer steps involved. I think it depends on the role you want the remote repo to play. (And yes, this is in conflict with the documentation here.)

Caveat: I learned the above (at this writing in early August 2019) by doing a test on my local system with a real repo, and then doing a file-by-file comparison between the results. But! I am still learning, so there could be a more correct way. But my tests have helped me conclude that #1 is my currently-preferred method.

Passing data to a bootstrap modal

For updating an href value, for example, I would do something like:

<a href="#myModal" data-toggle="modal" data-url="http://example.com">Show modal</a>

$('#myModal').on('show.bs.modal', function (e) {
    var url = $(e.relatedTarget).data('url');
    $(e.currentTarget).find('.any-class').attr("href", "url");
})

How can I see if a Perl hash already has a certain key?

I would counsel against using if ($hash{$key}) since it will not do what you expect if the key exists but its value is zero or empty.

Difference between RegisterStartupScript and RegisterClientScriptBlock?

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

To explain the differences as relevant to your posted example:

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

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

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

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

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

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

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

Edit after comments:


For instance, the following function would work:

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

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

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

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

How to create a GUID/UUID using iOS

[[UIDevice currentDevice] uniqueIdentifier]

Returns the Unique ID of your iPhone.

EDIT: -[UIDevice uniqueIdentifier] is now deprecated and apps are being rejected from the App Store for using it. The method below is now the preferred approach.

If you need to create several UUID, just use this method (with ARC):

+ (NSString *)GetUUID
{
  CFUUIDRef theUUID = CFUUIDCreate(NULL);
  CFStringRef string = CFUUIDCreateString(NULL, theUUID);
  CFRelease(theUUID);
  return (__bridge NSString *)string;
}

EDIT: Jan, 29 2014: If you're targeting iOS 6 or later, you can now use the much simpler method:

NSString *UUID = [[NSUUID UUID] UUIDString];

Query an XDocument for elements by name at any depth

(Code and Instructions is for C# and may need to be slightly altered for other languages)

This example works perfect if you want to read from a Parent Node that has many children, for example look at the following XML;

<?xml version="1.0" encoding="UTF-8"?> 
<emails>
    <emailAddress>[email protected]</emailAddress>
    <emailAddress>[email protected]</emailAddress>
    <emailAddress>rgreen@set_ig.ca</emailAddress> 
</emails>

Now with this code below (keeping in mind that the XML File is stored in resources (See the links at end of snippet for help on resources) You can obtain each email address within the "emails" tag.

XDocument doc = XDocument.Parse(Properties.Resources.EmailAddresses);

var emailAddresses = (from emails in doc.Descendants("emailAddress")
                      select emails.Value);

foreach (var email in emailAddresses)
{
    //Comment out if using WPF or Windows Form project
    Console.WriteLine(email.ToString());

   //Remove comment if using WPF or Windows Form project
   //MessageBox.Show(email.ToString());
}

Results

  1. [email protected]
  2. [email protected]
  3. rgreen@set_ig.ca

Note: For Console Application and WPF or Windows Forms you must add the "using System.Xml.Linq;" Using directive at the top of your project, for Console you will also need to add a reference to this namespace before adding the Using directive. Also for Console there will be no Resource file by default under the "Properties folder" so you have to manually add the Resource file. The MSDN articles below, explain this in detail.

Adding and Editing Resources

How to: Add or Remove Resources

How can I programmatically determine if my app is running in the iphone simulator?

I had the same problem, both TARGET_IPHONE_SIMULATOR and TARGET_OS_IPHONE are always defined, and are set to 1. Pete's solution works, of course, but if you ever happen to build on something other than intel (unlikely, but who knows), here's something that's safe as long as the iphone hardware doesn't change (so your code will always work for the iphones currently out there):

#if defined __arm__ || defined __thumb__
#undef TARGET_IPHONE_SIMULATOR
#define TARGET_OS_IPHONE
#else
#define TARGET_IPHONE_SIMULATOR 1
#undef TARGET_OS_IPHONE
#endif

Put that somewhere convenient, and then pretend that the TARGET_* constants were defined correctly.

Comparing user-inputted characters in C

For a start, your answer variable should be of type char, not char*.

As for the if statement:

if (answer == ('Y' || 'y'))

This is first evaluating 'Y' || 'y' which, in Boolean logic (and for ASCII) is true since both of them are "true" (non-zero). In other words, you'd only get the if statement to fire if you'd somehow entered CTRLA (again, for ASCII, and where a true values equates to 1)*a.

You could use the more correct:

if ((answer == 'Y') || (answer == 'y'))

but you really should be using:

if (toupper(answer) == 'Y')

since that's the more portable way to achieve the same end.


*a You may be wondering why I'm putting in all sorts of conditionals for my statements. While the vast majority of C implementations use ASCII and certain known values, it's not necessarily mandated by the ISO standards. I know for a fact that at least one compiler still uses EBCDIC so I don't like making unwarranted assumptions.

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

trim() method removes the leading and trailing spaces and using replaceAll("regex", "string to replace") method with regex "\s+" matches more than one space and will replace it with a single space

myText = myText.trim().replaceAll("\\s+"," ");

ASP MVC in IIS 7 results in: HTTP Error 403.14 - Forbidden

Please also check, if you are running x64, that you have enabled 32-bit applications in the app pool settings

enter image description here

Connecting client to server using Socket.io

You need to make sure that you add forward slash before your link to socket.io:

<script src="/socket.io/socket.io.js"></script>

Then in the view/controller just do:

var socket = io.connect()

That should solve your problem.

How to disable all div content

function disableItems(divSelector){
    var disableInputs = $(divSelector).find(":input").not("[disabled]");
    disableInputs.attr("data-reenable", true);
    disableInputs.attr("disabled", true);
}

function reEnableItems(divSelector){
    var reenableInputs = $(divSelector).find("[data-reenable]");
    reenableInputs.removeAttr("disabled");
    reenableInputs.removeAttr("data-reenable");
}

How to get a .csv file into R?

As Dirk said, the function you are after is 'read.csv' or one of the other read.table variants. Given your sample data above, I think you will want to do something like this:

setwd("c:/random/directory")

df <- read.csv("myRandomFile.csv", header=TRUE)

All we did in the above was set the directory to where your .csv file is and then read the .csv into a dataframe named df. You can check that the data loaded properly by checking the structure of the object with:

str(df)

Assuming the data loaded properly, you can think go on to perform any number of statistical methods with the data in your data frame. I think summary(df) would be a good place to start. Learning how to use the help in R will be immensely useful, and a quick read through the help on CRAN will save you lots of time in the future: http://cran.r-project.org/

Generate random colors (RGB)

Here:

def random_color():
    rgbl=[255,0,0]
    random.shuffle(rgbl)
    return tuple(rgbl)

The result is either red, green or blue. The method is not applicable to other sets of colors though, where you'd have to build a list of all the colors you want to choose from and then use random.choice to pick one at random.

What does git rev-parse do?

Just to elaborate on the etymology of the command name rev-parse, Git consistently uses the term rev in plumbing commands as short for "revision" and generally meaning the 40-character SHA1 hash for a commit. The command rev-list for example prints a list of 40-char commit hashes for a branch or whatever.

In this case the name might be expanded to parse-a-commitish-to-a-full-SHA1-hash. While the command has the several ancillary functions mentioned in Tuxdude's answer, its namesake appears to be the use case of transforming a user-friendly reference like a branch name or abbreviated hash into the unambiguous 40-character SHA1 hash most useful for many programming/plumbing purposes.

I know I was thinking it was "reverse-parse" something for quite a while before I figured it out and had the same trouble making sense of the terms "massaging" and "manipulation" :)

Anyway, I find this "parse-to-a-revision" notion a satisfying way to think of it, and a reliable concept for bringing this command to mind when I need that sort of thing. Frequently in scripting Git you take a user-friendly commit reference as user input and generally want to get it resolved to a validated and unambiguous working reference as soon after receiving it as possible. Otherwise input translation and validation tends to proliferate through the script.

Excel add one hour

=A1+TIME(1,0,0)

Although, maybe this should be posted on Super User.

How to print a int64_t type in C

The C99 way is

#include <inttypes.h>
int64_t my_int = 999999999999999999;
printf("%" PRId64 "\n", my_int);

Or you could cast!

printf("%ld", (long)my_int);
printf("%lld", (long long)my_int); /* C89 didn't define `long long` */
printf("%f", (double)my_int);

If you're stuck with a C89 implementation (notably Visual Studio) you can perhaps use an open source <inttypes.h> (and <stdint.h>): http://code.google.com/p/msinttypes/

Python list sort in descending order

Since your list is already in ascending order, we can simply reverse the list.

>>> timestamps.reverse()
>>> timestamps
['2010-04-20 10:25:38', 
'2010-04-20 10:12:13', 
'2010-04-20 10:12:13', 
'2010-04-20 10:11:50', 
'2010-04-20 10:10:58', 
'2010-04-20 10:10:37', 
'2010-04-20 10:09:46', 
'2010-04-20 10:08:22',
'2010-04-20 10:08:22', 
'2010-04-20 10:07:52', 
'2010-04-20 10:07:38', 
'2010-04-20 10:07:30']

How to draw vectors (physical 2D/3D vectors) in MATLAB?

a = [2 3 5];
b = [1 1 0];
c = a+b;

starts = zeros(3,3);
ends = [a;b;c];

quiver3(starts(:,1), starts(:,2), starts(:,3), ends(:,1), ends(:,2), ends(:,3))
axis equal

Writing sqlplus output to a file

Also note that the SPOOL output is driven by a few SQLPlus settings:

  • SET LINESIZE nn - maximum line width; if the output is longer it will wrap to display the contents of each result row.

  • SET TRIMSPOOL OFF|ON - if set OFF (the default), every output line will be padded to LINESIZE. If set ON, every output line will be trimmed.

  • SET PAGESIZE nn - number of lines to output for each repetition of the header. If set to zero, no header is output; just the detail.

Those are the biggies, but there are some others to consider if you just want the output without all the SQLPlus chatter.

How can I get href links from HTML using Python?

Try with Beautifulsoup:

from BeautifulSoup import BeautifulSoup
import urllib2
import re

html_page = urllib2.urlopen("http://www.yourwebsite.com")
soup = BeautifulSoup(html_page)
for link in soup.findAll('a'):
    print link.get('href')

In case you just want links starting with http://, you should use:

soup.findAll('a', attrs={'href': re.compile("^http://")})

In Python 3 with BS4 it should be:

from bs4 import BeautifulSoup
import urllib.request

html_page = urllib.request.urlopen("http://www.yourwebsite.com")
soup = BeautifulSoup(html_page, "html.parser")
for link in soup.findAll('a'):
    print(link.get('href'))

Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?

I don't think this is allowed by most browsers for security reasons, in a pure JavaScript context as the question asks.

How to convert Double to int directly?

double myDb = 12.3;
int myInt = (int) myDb;

Result is: myInt = 12

JavaScript equivalent of PHP's in_array()

haystack.find(value => value == needle)

where haystack is an array and needle is an element in array. If element not found will be returned undefined else the same element.

IF formula to compare a date with current date and return result

I think this will cover any possible scenario for what is in O10:

=IF(ISBLANK(O10),"",IF(O10<TODAY(),IF(TODAY()-O10<>1,CONCATENATE("Due in ",TEXT(TODAY()-O10,"d")," days"),CONCATENATE("Due in ",TEXT(TODAY()-O10,"d")," day")),IF(O10=TODAY(),"Due Today","Overdue")))

For Dates that are before Today, it will tell you how many days the item is due in. If O10 = Today then it will say "Due Today". Anything past Today and it will read overdue. Lastly, if it is blank, the cell will also appear blank. Let me know what you think!

How to install python developer package?

For me none of the packages mentioned above did help.

I finally managed to install lxml after running:

sudo apt-get install python3.5-dev

How to find the Number of CPU Cores via .NET/C#?

I was looking for the same thing but I don't want to install any nuget or servicepack, so I found this solution, it is pretty simple and straight forward, using this discussion, I thought it would be so easy to run that WMIC command and get that value, here is the C# code. You only need to use System.Management namespace (and couple more standard namespaces for process and so on).

string fileName = Path.Combine(Environment.SystemDirectory, "wbem", "wmic.exe");
string arguments = @"cpu get NumberOfCores";

Process process = new Process
{
    StartInfo =
    {
        FileName = fileName,
        Arguments = arguments,
        UseShellExecute = false,
        CreateNoWindow = true,
        RedirectStandardOutput = true,
        RedirectStandardError = true
    }
};

process.Start();

StreamReader output = process.StandardOutput;
Console.WriteLine(output.ReadToEnd());


process.WaitForExit();
int exitCode = process.ExitCode;
process.Close();

How to jump back to NERDTree from file in tab?

All The Shortcuts And Functionality is At

press CTRL-?

Android: How do bluetooth UUIDs work?

To sum up: UUid is used to uniquely identify applications. Each application has a unique UUid

So, use the same UUid for each device

How can I commit files with git?

Git uses "the index" to prepare commits. You can add and remove changes from the index before you commit (in your paste you already have deleted ~10 files with git rm). When the index looks like you want it, run git commit.

Usually this will fire up vim. To insert text hit i, <esc> goes back to normal mode, hit ZZ to save and quit (ZQ to quit without saving). voilà, there's your commit

How do I install TensorFlow's tensorboard?

The steps to install Tensorflow are here: https://www.tensorflow.org/install/

For example, on Linux for CPU-only (no GPU), you would type this command:

pip install -U pip
pip install tensorflow

Since TensorFlow depends on TensorBoard, running the following command should not be necessary:

pip install tensorboard

"unrecognized selector sent to instance" error in Objective-C

This also might happen when you want to set a property from a ControllerA to a public property inside a custom ControllerB class and you haven't set the "Custom Class" inside the identity inspector in storyboards yet.

form_for but to post to a different action

new syntax

<%= form_for :user, url: custom_user_path, method: :post do |f|%>
<%end%>

java, get set methods

To understand get and set, it's all related to how variables are passed between different classes.

The get method is used to obtain or retrieve a particular variable value from a class.

A set value is used to store the variables.

The whole point of the get and set is to retrieve and store the data values accordingly.

What I did in this old project was I had a User class with my get and set methods that I used in my Server class.

The User class's get set methods:

public int getuserID()
    {
        //getting the userID variable instance
        return userID;
    }
    public String getfirstName()
    {
        //getting the firstName variable instance
        return firstName;
    }
    public String getlastName()
    {
        //getting the lastName variable instance
        return lastName;
    }
    public int getage()
    {
        //getting the age variable instance
        return age;
    }

    public void setuserID(int userID)
    {
        //setting the userID variable value
        this.userID = userID;
    }
    public void setfirstName(String firstName)
    {
        //setting the firstName variable text
        this.firstName = firstName;
    }
    public void setlastName(String lastName)
    {
        //setting the lastName variable text
        this.lastName = lastName;
    }
    public void setage(int age)
    {
        //setting the age variable value
        this.age = age;
    }
}

Then this was implemented in the run() method in my Server class as follows:

//creates user object
                User use = new User(userID, firstName, lastName, age);
                //Mutator methods to set user objects
                use.setuserID(userID);
                use.setlastName(lastName);
                use.setfirstName(firstName);               
                use.setage(age); 

Which one is the best PDF-API for PHP?

This is just a quick review of how fPDF stands up against tcPDF in the area of performance at each libraries most basic functions.

SPEED TEST

17.0366 seconds to process 2000 PDF files using fPDF || 79.5982 seconds to process 2000 PDF files using tcPDF

FILE SIZE CHECK (in bytes)

788 fPDF || 1,860 tcPDF

The code used was as identical as possible and renders just a clean PDF file with no text. This is also using the latest version of each library as of June 22, 2011.

What does <a href="#" class="view"> mean?

It probably works with Javascript. When you click the link, nothing happens because it points to the current site. The javascript will then load a window or an url. It's used a lot in AJAX web apps.

Missing Push Notification Entitlement

The biggest problem that i have after enabling the Push Notification from Capabilities and remaking all the certificates is that the Target name and the folder name where was stored the project was composed from 2 strings separated by space. After removing the space all worked just fine!

How to iterate through LinkedHashMap with lists as values

In Java 8:

Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>();
test1.forEach((key,value) -> {
    System.out.println(key + " -> " + value);
});

How to combine multiple conditions to subset a data-frame using "OR"?

Just for the sake of completeness, we can use the operators [ and [[:

set.seed(1)
df <- data.frame(v1 = runif(10), v2 = letters[1:10])

Several options

df[df[1] < 0.5 | df[2] == "g", ] 
df[df[[1]] < 0.5 | df[[2]] == "g", ] 
df[df["v1"] < 0.5 | df["v2"] == "g", ]

df$name is equivalent to df[["name", exact = FALSE]]

Using dplyr:

library(dplyr)
filter(df, v1 < 0.5 | v2 == "g")

Using sqldf:

library(sqldf)
sqldf('SELECT *
      FROM df 
      WHERE v1 < 0.5 OR v2 = "g"')

Output for the above options:

          v1 v2
1 0.26550866  a
2 0.37212390  b
3 0.20168193  e
4 0.94467527  g
5 0.06178627  j

Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib

In my case after downgrading from .NET 4.5 to .NET 4.0 project was working fine on a local machine, but was failing on server after publishing.

Turns out that destination had some old assemblies, which were still referencing .NET 4.5.

Fixed it by enabling publishing option "Delete all existing files prior to publish"

How do you pass view parameters when navigating from an action in JSF2?

The unintuitive thing about passing parameters in JSF is that you do not decide what to send (in the action), but rather what you wish to receive (in the target page).

When you do an action that ends with a redirect, the target page metadata is loaded and all required parameters are read and appended to the url as params.

Note that this is exactly the same mechanism as with any other JSF binding: you cannot read inputText's value from one place and have it write somewhere else. The value expression defined in viewParam is used both for reading (before the redirect) and for writing (after the redirect).

With your bean you just do:

@ManagedBean
@RequestScoped
public class MyBean {

private int id;

public String submit() {
    //Does stuff
    id = setID();
    return "success?faces-redirect=true&includeViewParams=true";
}

// setter and getter for id

If the receiving side has:

    <f:metadata>
        <f:viewParam name="id" value="#{myBean.id}" />
    </f:metadata>

It will do exactly what you want.

Bootstrap: adding gaps between divs

Adding a padding between the divs to simulate a gap might be a hack, but why not use something Bootstrap provides. It's called offsets. But again, you can define a class in your custom.css (you shouldn't edit the core stylesheet anyway) file and add something like .gap. However, .col-md-offset-* does the job most of the times for me, allowing me to precisely leave a gap between the divs.

As for vertical spacing, unfortunately, there isn't anything set built-in like that in Bootstrap 3, so you will have to invent your own custom class to do that. I'd usually do something like .top-buffer { margin-top:20px; }. This does the trick, and obviously, it doesn't have to be 20px, it can be anything you like.

How do you get the footer to stay at the bottom of a Web page?

You could use position: absolute following to put the footer at the bottom of the page, but then make sure your 2 columns have the appropriate margin-bottom so that they never get occluded by the footer.

#footer {
    position: absolute;
    bottom: 0px;
    width: 100%;
}
#content, #sidebar { 
    margin-bottom: 5em; 
}

iPhone system font

Swift

You should always use the system defaults and not hard coding the font name because the default font could be changed by Apple at any time.

There are a couple of system default fonts(normal, bold, italic) with different sizes(label, button, others):

let font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
let font2 = UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)
let font3 = UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)

beaware that the default font size depends on the target view (label, button, others)

Examples:

let labelFont = UIFont.systemFont(ofSize: UIFont.labelFontSize)
let buttonFont = UIFont.systemFont(ofSize: UIFont.buttonFontSize)
let textFieldFont = UIFont.systemFont(ofSize: UIFont.systemFontSize)

Provisioning Profiles menu item missing from Xcode 5

Stupid as it may sound but all "Provisioning Profiles" re-appear under "Organizer - Devices" once you connect a real device.

increment date by one month

If you want to get the date of one month from now you can do it like this

echo date('Y-m-d', strtotime('1 month'));

If you want to get the date of two months from now, you can achieve that by doing this

echo date('Y-m-d', strtotime('2 month'));

And so on, that's all.

Where do I download JDBC drivers for DB2 that are compatible with JDK 1.5?

I know its late but i recently ran into this situation. After wasting entire day I finally found the solution. I am suprised that I got this info on oracle's website whereas this seems nowhere to be found on IBM's website.

If you want to use JDBC drivers for DB2 that are compatible with JDK 1.5 or 1.4 , you need to use the jar db2jcc.jar, which is available in SQLLIB/java/ folder of your db2 installation.

Viewing PDF in Windows forms using C#

i think the easiest way is to use the Adobe PDF reader COM Component

  1. right click on your toolbox & select "Choose Items"
  2. Select the "COM Components" tab
  3. Select "Adobe PDF Reader" then click ok
  4. Drag & Drop the control on your form & modify the "src" Property to the PDF files you want to read

i hope this helps

Storing JSON in database vs. having a new column for each key

short answer you have to mix between them , use json for data that you are not going to make relations with them like contact data , address , products variabls

How to list the contents of a package using YUM?

There is a package called yum-utils that builds on YUM and contains a tool called repoquery that can do this.

$ repoquery --help | grep -E "list\ files" 
  -l, --list            list files in this package/group

Combined into one example:

$ repoquery -l time
/usr/bin/time
/usr/share/doc/time-1.7
/usr/share/doc/time-1.7/COPYING
/usr/share/doc/time-1.7/NEWS
/usr/share/doc/time-1.7/README
/usr/share/info/time.info.gz

On at least one RH system, with rpm v4.8.0, yum v3.2.29, and repoquery v0.0.11, repoquery -l rpm prints nothing.

If you are having this issue, try adding the --installed flag: repoquery --installed -l rpm.


DNF Update:

To use dnf instead of yum-utils, use the following command:

$ dnf repoquery -l time
/usr/bin/time
/usr/share/doc/time-1.7
/usr/share/doc/time-1.7/COPYING
/usr/share/doc/time-1.7/NEWS
/usr/share/doc/time-1.7/README
/usr/share/info/time.info.gz

Navigation drawer: How do I set the selected item at startup?

Below code is used to selected the first item and highlight the selected first item in the menu.

onNavigationItemSelected(mNavigationView.getMenu().getItem(0).setChecked(true));

SQL Logic Operator Precedence: And and Or

And has precedence over Or, so, even if a <=> a1 Or a2

Where a And b 

is not the same as

Where a1 Or a2 And b,

because that would be Executed as

Where a1 Or (a2 And b)

and what you want, to make them the same, is the following (using parentheses to override rules of precedence):

 Where (a1 Or a2) And b

Here's an example to illustrate:

Declare @x tinyInt = 1
Declare @y tinyInt = 0
Declare @z tinyInt = 0

Select Case When @x=1 OR @y=1 And @z=1 Then 'T' Else 'F' End -- outputs T
Select Case When (@x=1 OR @y=1) And @z=1 Then 'T' Else 'F' End -- outputs F

For those who like to consult references (in alphabetic order):

Default password of mysql in ubuntu server 16.04

You can simply reset the root password by running the server with --skip-grant-tables and logging in without a password by running the following as root or with sudo:

service mysql stop
mysqld_safe --skip-grant-tables &
mysql -u root

mysql> use mysql;
mysql> update user set authentication_string=PASSWORD("YOUR-NEW-ROOT-PASSWORD") where User='root';
mysql> flush privileges;
mysql> quit

# service mysql stop
# service mysql start
$ mysql -u root -p

How to sort rows of HTML table that are called from MySQL

A SIMPLE TABLE SORT PHP CODE:

(the simple table for several values processing and sorting, using this sortable.js script )

<html><head>
<script src="sorttable.js"></script>

<style>
tbody tr td {color:green;border-right:1px solid;width:200px;}
</style>
</head><body>

<?php
$First = array('a', 'b', 'c', 'd');
$Second = array('1', '2', '3', '4');

if (!empty($_POST['myFirstvalues'])) 
{ $First = explode("\r\n",$_POST['myFirstvalues']); $Second = explode("\r\n",$_POST['mySecondvalues']);}

?>

</br>Hi User. PUT your values</br></br>
<form action="" method="POST">
projectX</br>
<textarea cols="20" rows="20" name="myFirstvalues" style="width:200px;background:url(untitled.PNG);position:relative;top:19px;Float:left;">
<?php foreach($First as $vv) {echo $vv."\r\n";}?>
</textarea>

The due amount</br>
<textarea cols="20" rows="20" name="mySecondvalues" style="width:200px;background:url(untitled.PNG);Float:left;">
<?php foreach($Second as $vv) {echo $vv."\r\n";}?>
</textarea>
<input type="submit">
</form>

<table class="sortable" style="padding:100px 0 0 300px;">
<thead style="background-color:#999999; color:red; font-weight: bold; cursor: default;  position:relative;">
  <tr><th>ProjectX</th><th>Due amount</th></tr>
</thead>
<tbody>

<?php
foreach($First as $indx => $value) {
    echo '<tr><td>'.$First[$indx].'</td><td>'.$Second[$indx].'</td></tr>';
}
?>
</tbody>
<tfoot><tr><td>TOTAL  = &nbsp;<b>111111111</b></td><td>Still to spend  = &nbsp;<b>5555555</b></td></tr></tfoot></br></br>
</table>
</body>
</html>

source: php sortable table

Adjust plot title (main) position

Try this:

par(adj = 0)
plot(1, 1, main = "Title")

or equivalent:

plot(1, 1, main = "Title", adj = 0)

adj = 0 produces left-justified text, 0.5 (the default) centered text and 1 right-justified text. Any value in [0, 1] is allowed.

However, the issue is that this will also change the position of the label of the x-axis and y-axis.

Convert columns to string in Pandas

I usually use this one:

pd['Column'].map(str)

How to use operator '-replace' in PowerShell to replace strings of texts with special characters and replace successfully

In your example, you prepended your source string with AccountKey= but not your target string.

$c = $c -replace 'AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','AccountKey=DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA=='

By not including that in the target string, the resulting string will remove AccountKey= instead of replacing it. You correctly do this with the AccountName= example, which seems to support this conclusion since it is not giving you any problems. If you really mean to have that prepended, then this may resolve your issue.

Print in Landscape format

you cannot set this in javascript, you have to do this with html/css:

<style type="text/css" media="print">
  @page { size: landscape; }
</style>

EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?

How can I get list of values from dict?

out: dict_values([{1:a, 2:b}])

in:  str(dict.values())[14:-3]    
out: 1:a, 2:b

Purely for visual purposes. Does not produce a useful product... Only useful if you want a long dictionary to print in a paragraph type form.

Select option padding not working in chrome

No Jquery - No Third party js file

_x000D_
_x000D_
function clickComboBox(){_x000D_
  comboOpt = document.getElementsByClassName("opt");_x000D_
  for (i = 0; i < comboOpt.length; i++) {_x000D_
      if (comboOpt[i].style.display === "block") {_x000D_
        comboOpt[i].style.display = "none";_x000D_
      } else {_x000D_
        comboOpt[i].style.display = "block";_x000D_
      }_x000D_
  }    _x000D_
}_x000D_
function clickOpt(value1,text1){_x000D_
  document.getElementById("selectedValue").value=value1;_x000D_
  document.getElementById("customComboBox").innerHTML=text1;_x000D_
  clickComboBox();_x000D_
}
_x000D_
#customComboBox{_x000D_
width: 150px;_x000D_
height: 20px;_x000D_
border: 1px solid #CCCCCC;_x000D_
display: block;_x000D_
padding: 2px 5px;_x000D_
}_x000D_
.opt{_x000D_
padding: 5px 0px;background-color:#CCCCCC;_x000D_
width: 160px;_x000D_
display: none;_x000D_
}
_x000D_
<div id="customComboBox"  onClick="clickComboBox()">_x000D_
-Select Value-_x000D_
</div>_x000D_
<input type="hidden" id="selectedValue">_x000D_
  <div class="opt">_x000D_
  <div onClick="clickOpt('01','Test1')"><img  src="https://pasteboard.co/J6940Vs.png" height="20">Test1</div>_x000D_
  <div style="padding-left:10px;" onClick="clickOpt('02','Test2')">Test2</div>_x000D_
  <div onClick="clickOpt('03','Test3')">Test3</div>_x000D_
  </div>
_x000D_
_x000D_
_x000D_

smart code - use jquery

How to re-sign the ipa file?

It's really easy to do from the command line. I had a gist of a script for doing this. It has now been incorporated into the ipa_sign script in https://github.com/RichardBronosky/ota-tools which I use daily. If you have any questions about using these tools, don't hesitate to ask.

The heart of it is this:

CODESIGN_ALLOCATE=`xcrun --find codesign_allocate`; export CODESIGN_ALLOCATE
IPA="/path/to/file.ipa"
PROVISION="/path/to/file.mobileprovision"
CERTIFICATE="Name of certificate: To sign with" # must be in keychain
# unzip the ipa
unzip -q "$IPA"
# remove the signature
rm -rf Payload/*.app/_CodeSignature
# replace the provision
cp "$PROVISION" Payload/*.app/embedded.mobileprovision
# sign with the new certificate (--resource-rules has been deprecated OS X Yosemite (10.10), it can safely be removed)
/usr/bin/codesign -f -s "$CERTIFICATE" Payload/*.app
# zip it back up
zip -qr resigned.ipa Payload

Your new signed app is called resigned.ipa

Console errors. Failed to load resource: net::ERR_INSECURE_RESPONSE

In my case, sometimes when i tests my MVC project by a localhost https url (E.g. https://localhost:44373/), the Chrome raise this error: net::ERR_INSECURE_RESPONSE for the website resources (such as JS files).

So i resolve it by Clear Cache. Then i refresh the page and Chrome show me a special page about insecure url and i just allow it by click on Proceed to localhost (unsafe).

enter image description here

How exactly does <script defer="defer"> work?

UPDATED: 2/19/2016

Consider this answer outdated. Refer to other answers on this post for information relevant to newer browser version.


Basically, defer tells the browser to wait "until it's ready" before executing the javascript in that script block. Usually this is after the DOM has finished loading and document.readyState == 4

The defer attribute is specific to internet explorer. In Internet Explorer 8, on Windows 7 the result I am seeing in your JS Fiddle test page is, 1 - 2 - 3.

The results may vary from browser to browser.

http://msdn.microsoft.com/en-us/library/ms533719(v=vs.85).aspx

Contrary to popular belief IE follows standards more often than people let on, in actuality the "defer" attribute is defined in the DOM Level 1 spec http://www.w3.org/TR/REC-DOM-Level-1/level-one-html.html

The W3C's definition of defer: http://www.w3.org/TR/REC-html40/interact/scripts.html#adef-defer:

"When set, this boolean attribute provides a hint to the user agent that the script is not going to generate any document content (e.g., no "document.write" in javascript) and thus, the user agent can continue parsing and rendering."

How to fix java.net.SocketException: Broken pipe?

In our case we experienced this while performing a load test on our app server. The issue turned out that we need to add additional memory to our JVM because it was running out. This resolved the issue.

Try increasing the memory available to the JVM and or monitor the memory usage when you get those errors.

Simplest way to detect keypresses in javascript

Use event.key and modern JS!

No number codes anymore. You can use "Enter", "ArrowLeft", "r", or any key name directly, making your code far more readable.

NOTE: The old alternatives (.keyCode and .which) are Deprecated.

document.addEventListener("keypress", function onEvent(event) {
    if (event.key === "ArrowLeft") {
        // Move Left
    }
    else if (event.key === "Enter") {
        // Open Menu...
    }
});

Mozilla Docs

Supported Browsers

How to make a simple popup box in Visual C#?

System.Windows.Forms.MessageBox.Show("My message here");

Make sure the System.Windows.Forms assembly is referenced your project.

How to append contents of multiple files into one file

Another option, for those of you who still stumble upon this post like I did, is to use find -exec:

find . -type f -name '*.txt' -exec cat {} + >> output.file

In my case, I needed a more robust option that would look through multiple subdirectories so I chose to use find. Breaking it down:

find .

Look within the current working directory.

-type f

Only interested in files, not directories, etc.

-name '*.txt'

Whittle down the result set by name

-exec cat {} +

Execute the cat command for each result. "+" means only 1 instance of cat is spawned (thx @gniourf_gniourf)

 >> output.file

As explained in other answers, append the cat-ed contents to the end of an output file.

How to check if a std::string is set or not?

The default constructor for std::string always returns an object that is set to a null string.