Programs & Examples On #Relaxng

RELAX NG (ISO/IEC 19757-2) is an International Standard schema language for XML. A RELAX NG schema specifies a grammar that a validator can apply to XML documents to determine whether or not they are schema-valid.

pip is not able to install packages correctly: Permission denied error

It looks like you're having a permissions error, based on this message in your output: error: could not create '/lib/python2.7/site-packages/lxml': Permission denied.

One thing you can try is doing a user install of the package with pip install lxml --user. For more information on how that works, check out this StackOverflow answer. (Thanks to Ishaan Taylor for the suggestion)

You can also run pip install as a superuser with sudo pip install lxml but it is not generally a good idea because it can cause issues with your system-level packages.

java.lang.UnsupportedClassVersionError Unsupported major.minor version 51.0

Use Maven and use the maven-compiler-plugin to explicitly call the actual correct version JDK javac.exe command, because Maven could be running any version; this also catches the really stupid long standing bug in javac that does not spot runtime breaking class version jars and missing classes/methods/properties when compiling for earlier java versions! This later part could have easily been fixed in Java 1.5+ by adding versioning attributes to new classes, methods, and properties, or separate compiler versioning data, so is a quite stupid oversight by Sun and Oracle.

How do I determine if a checkbox is checked?

Place the var lfckv inside the function. When that line is executed, the body isn't parsed yet and the element "lifecheck" doesn't exist. This works perfectly fine:

_x000D_
_x000D_
function exefunction() {_x000D_
  var lfckv = document.getElementById("lifecheck").checked;_x000D_
  alert(lfckv);_x000D_
}
_x000D_
<label><input id="lifecheck" type="checkbox" >Lives</label>_x000D_
<button onclick="exefunction()">Check value</button>
_x000D_
_x000D_
_x000D_

How to insert selected columns from a CSV file to a MySQL database using LOAD DATA INFILE

For those who have the following error:

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

You can simply run this command to see which folder can load files from:

SHOW VARIABLES LIKE "secure_file_priv";

After that, you have to copy the files in that folder and run the query with LOAD DATA LOCAL INFILE instead of LOAD DATA INFILE.

Multiple FROMs - what it means

The first answer is too complex, historic, and uninformative for my tastes.


It's actually rather simple. Docker provides for a functionality called multi-stage builds the basic idea here is to,

  • Free you from having to manually remove what you don't want, by forcing you to whitelist what you do want,
  • Free resources that would otherwise be taken up because of Docker's implementation.

Let's start with the first. Very often with something like Debian you'll see.

RUN apt-get update \ 
  && apt-get dist-upgrade \
  && apt-get install <whatever> \
  && apt-get clean

We can explain all of this in terms of the above. The above command is chained together so it represents a single change with no intermediate Images required. If it was written like this,

RUN apt-get update ;
RUN apt-get dist-upgrade;
RUN apt-get install <whatever>;
RUN apt-get clean;

It would result in 3 more temporary intermediate Images. Having it reduced to one image, there is one remaining problem: apt-get clean doesn't clean up artifacts used in the install. If a Debian maintainer includes in his install a script that modifies the system that modification will also be present in the final solution (see something like pepperflashplugin-nonfree for an example of that).

By using a multi-stage build you get all the benefits of a single changed action, but it will require you to manually whitelist and copy over files that were introduced in the temporary image using the COPY --from syntax documented here. Moreover, it's a great solution where there is no alternative (like an apt-get clean), and you would otherwise have lots of un-needed files in your final image.

See also

How can I read the client's machine/computer name from the browser?

Well you could get the ip address using asp.net, then do a reverse DNS lookup on the ip to get the hostname.

From the ASP.NET Developer's cookbook ... Performing a Reverse-DNS Lookup.

Connection Java-MySql : Public Key Retrieval is not allowed

First of all, please make sure your Database server is up and running. I was getting the same error, after trying all the answers listed here I found out that my Database server was not running.

You can check the same from MySQL Workbench, or Command line using

mysql -u USERNAME -p

This sounds obvious, but many times we assume that Database server is up and running all the time, especially when we are working on our local machine, when we restart/shutdown the machine, Database server will be shutdown automatically.

What does the line "#!/bin/sh" mean in a UNIX shell script?

When you try to execute a program in unix (one with the executable bit set), the operating system will look at the first few bytes of the file. These form the so-called "magic number", which can be used to decide the format of the program and how to execute it.

#! corresponds to the magic number 0x2321 (look it up in an ascii table). When the system sees that the magic number, it knows that it is dealing with a text script and reads until the next \n (there is a limit, but it escapes me atm). Having identified the interpreter (the first argument after the shebang) it will call the interpreter.

Other files also have magic numbers. Try looking at a bitmap (.BMP) file via less and you will see the first two characters are BM. This magic number denotes that the file is indeed a bitmap.

Windows Batch: How to add Host-Entries?

Plain typo. hostspath vs hostpath ;)

@echo off 

set `hostspath`=%windir%\System32\drivers\etc\hosts 

echo 62.116.159.4 ns1.intranet.de >> `%hostspath%`   
echo 217.160.113.37 ns2.intranet.de >> `%hostpath%`  
echo 89.146.248.4 ns3.intranet.de >> `%hostpath%`   
echo 74.208.254.4 ns4.intranet.de >> `%hostpath%`   

exit 

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

SFTP file transfer using Java JSch

Below code works for me

   public static void sftpsript(String filepath) {

 try {
  String user ="demouser"; // username for remote host
  String password ="demo123"; // password of the remote host

   String host = "demo.net"; // remote host address
  JSch jsch = new JSch();
  Session session = jsch.getSession(user, host);
  session.setPassword(password);
  session.connect();

  ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
  sftpChannel.connect();

  sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
  sftpChannel.disconnect();
  session.disconnect();
 }catch(Exception ex){
     ex.printStackTrace();
 }
   }

OR using StrictHostKeyChecking as "NO" (security consequences)

public static void sftpsript(String filepath) {

 try {
  String user ="demouser"; // username for remote host
  String password ="demo123"; // password of the remote host

   String host = "demo.net"; // remote host address
  JSch jsch = new JSch();
   Session session = jsch.getSession(user, host, 22);
   Properties config = new Properties();
   config.put("StrictHostKeyChecking", "no");
   session.setConfig(config);;
   session.setPassword(password);
   System.out.println("user=="+user+"\n host=="+host);
   session.connect();

  ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
  sftpChannel.connect();

  sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
  sftpChannel.disconnect();
  session.disconnect();
 }catch(Exception ex){
     ex.printStackTrace();
 }
   }

Changing an element's ID with jQuery

What you mean to do is:

jQuery(this).prev("li").attr("id", "newID");

That will set the ID to the new ID

calculating number of days between 2 columns of dates in data frame

You need to use the as.Date formats correctly.

Eg.

x = '2012/07/25'
xd = as.Date(x,'%Y/%m/%d')
xd    # Prints "2012-07-25"

R date formats are similary to *nix ones.

Doing a typeof(xd) shows it as a double ie. days since 1970.

How do I embed a mp4 movie into my html?

You should look into Video For Everyone:

Video for Everybody is very simply a chunk of HTML code that embeds a video into a website using the HTML5 element which offers native playback in Firefox 3.5 and Safari 3 & 4 and an increasing number of other browsers.

The video is played by the browser itself. It loads quickly and doesn’t threaten to crash your browser.

In other browsers that do not support , it falls back to QuickTime.

If QuickTime is not installed, Adobe Flash is used. You can host locally or embed any Flash file, such as a YouTube video.

The only downside, is that you have to have 2/3 versions of the same video stored, but you can serve to every existing device/browser that supports video (i.e.: the iPhone).

<video width="640" height="360" poster="__POSTER__.jpg" controls="controls">
    <source src="__VIDEO__.mp4" type="video/mp4" />
    <source src="__VIDEO__.webm" type="video/webm" />
    <source src="__VIDEO__.ogv" type="video/ogg" /><!--[if gt IE 6]>
    <object width="640" height="375" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"><!
    [endif]--><!--[if !IE]><!-->
    <object width="640" height="375" type="video/quicktime" data="__VIDEO__.mp4"><!--<![endif]-->
    <param name="src" value="__VIDEO__.mp4" />
    <param name="autoplay" value="false" />
    <param name="showlogo" value="false" />
    <object width="640" height="380" type="application/x-shockwave-flash"
        data="__FLASH__.swf?image=__POSTER__.jpg&amp;file=__VIDEO__.mp4">
        <param name="movie" value="__FLASH__.swf?image=__POSTER__.jpg&amp;file=__VIDEO__.mp4" />
        <img src="__POSTER__.jpg" width="640" height="360" />
        <p>
            <strong>No video playback capabilities detected.</strong>
            Why not try to download the file instead?<br />
            <a href="__VIDEO__.mp4">MPEG4 / H.264 “.mp4” (Windows / Mac)</a> |
            <a href="__VIDEO__.ogv">Ogg Theora &amp; Vorbis “.ogv” (Linux)</a>
        </p>
    </object><!--[if gt IE 6]><!-->
    </object><!--<![endif]-->
</video>

There is an updated version that is a bit more readable:

<!-- "Video For Everybody" v0.4.1 by Kroc Camen of Camen Design <camendesign.com/code/video_for_everybody>
     =================================================================================================================== -->
<!-- first try HTML5 playback: if serving as XML, expand `controls` to `controls="controls"` and autoplay likewise       -->
<!-- warning: playback does not work on iPad/iPhone if you include the poster attribute! fixed in iOS4.0                 -->
<video width="640" height="360" controls preload="none">
    <!-- MP4 must be first for iPad! -->
    <source src="__VIDEO__.MP4" type="video/mp4" /><!-- WebKit video    -->
    <source src="__VIDEO__.webm" type="video/webm" /><!-- Chrome / Newest versions of Firefox and Opera -->
    <source src="__VIDEO__.OGV" type="video/ogg" /><!-- Firefox / Opera -->
    <!-- fallback to Flash: -->
    <object width="640" height="384" type="application/x-shockwave-flash" data="__FLASH__.SWF">
        <!-- Firefox uses the `data` attribute above, IE/Safari uses the param below -->
        <param name="movie" value="__FLASH__.SWF" />
        <param name="flashvars" value="image=__POSTER__.JPG&amp;file=__VIDEO__.MP4" />
        <!-- fallback image. note the title field below, put the title of the video there -->
        <img src="__VIDEO__.JPG" width="640" height="360" alt="__TITLE__"
             title="No video playback capabilities, please download the video below" />
    </object>
</video>
<!-- you *must* offer a download link as they may be able to play the file locally. customise this bit all you want -->
<p> <strong>Download Video:</strong>
    Closed Format:  <a href="__VIDEO__.MP4">"MP4"</a>
    Open Format:    <a href="__VIDEO__.OGV">"OGG"</a>
</p>

Resize jqGrid when browser is resized?

If you:

  • have shrinkToFit: false (mean fixed width columns)
  • have autowidth: true
  • don't care about fluid height
  • have horizontal scrollbar

You can make grid with fluid width with following styles:

.ui-jqgrid {
  max-width: 100% !important;
  width: auto !important;
}

.ui-jqgrid-view,
.ui-jqgrid-hdiv,
.ui-jqgrid-bdiv {
   width: auto !important;
}

Here is a demo

In Jenkins, how to checkout a project into a specific directory (using GIT)

Furthermore, if in the same Jenkins project we need to checkout several private GitHub repositories into several separate dirs under a project root. How can we do it please?

The Jenkin's Multiple SCMs Plugin has solved the several repositories problem for me very nicely. I have just got working a project build that checks out four different git repos under a common folder. (I'm a bit reluctant to use git super-projects as suggested previously by Lukasz Rzanek, as git is complex enough without submodules.)

Properties file in python (similar to Java Properties)

For .ini files there is the ConfigParser module that provides a format compatible with .ini files.

Anyway there's nothing available for parsing complete .properties files, when I have to do that I simply use jython (I'm talking about scripting).

C# - Making a Process.Start wait until the process has start-up

Are you sure the Start method returns before the child process starts? I was always under the impression that Start starts the child process synchronously.

If you want to wait until your child process finishes some sort of initialization then you need inter-process communication - see Interprocess communication for Windows in C# (.NET 2.0).

Error with multiple definitions of function

The problem is that if you include fun.cpp in two places in your program, you will end up defining it twice, which isn't valid.

You don't want to include cpp files. You want to include header files.

The header file should just have the class definition. The corresponding cpp file, which you will compile separately, will have the function definition.

fun.hpp:

#include <iostream>

class classA {
    friend void funct();
public:
    classA(int a=1,int b=2):propa(a),propb(b){std::cout<<"constructor\n";}
private:
    int propa;
    int propb;
    void outfun(){
        std::cout<<"propa="<<propa<<endl<<"propb="<<propb<< std::endl;
    }
};

fun.cpp:

#include "fun.hpp"

using namespace std;

void funct(){
    cout<<"enter funct"<<endl;
    classA tmp(1,2);
    tmp.outfun();
    cout<<"exit funct"<<endl;
}

mainfile.cpp:

#include <iostream>
#include "fun.hpp"
using namespace std;

int main(int nargin,char* varargin[]) {
    cout<<"call funct"<<endl;
    funct();
    cout<<"exit main"<<endl;
    return 0;
}

Note that it is generally recommended to avoid using namespace std in header files.

How can I open a link in a new window?

Here's how to force the target inside a click handler:

$('a#link_id').click(function() {
    $(this).attr('target', '_blank');
});

Greater than and less than in one statement

Please just write a static method somewhere and write:

if( isSizeBetween(orderBean.getFiles(), 0, 5) ){
    // do your stuff 
}

How do I sum values in a column that match a given condition using pandas?

You can also do this without using groupby or loc. By simply including the condition in code. Let the name of dataframe be df. Then you can try :

df[df['a']==1]['b'].sum()

or you can also try :

sum(df[df['a']==1]['b'])

Another way could be to use the numpy library of python :

import numpy as np
print(np.where(df['a']==1, df['b'],0).sum())

Best approach to real time http streaming to HTML5 video client

Take a look at this solution. As I know, Flashphoner allows to play Live audio+video stream in the pure HTML5 page.

They use MPEG1 and G.711 codecs for playback. The hack is rendering decoded video to HTML5 canvas element and playing decoded audio via HTML5 audio context.

Convert String to equivalent Enum value

Hope you realise, java.util.Enumeration is different from the Java 1.5 Enum types.

You can simply use YourEnum.valueOf("String") to get the equivalent enum type.

Thus if your enum is defined as so:

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 
    THURSDAY, FRIDAY, SATURDAY
}

You could do this:

String day = "SUNDAY";

Day dayEnum = Day.valueOf(day);

html5 localStorage error with Safari: "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota."

The accepted answer seems not adequate in several situations.

To check whether the localStorage or sessionStorage are supported, I use the following snippet from MDN.

function storageAvailable(type) {
    var storage;
    try {
        storage = window[type];
        var x = '__storage_test__';
        storage.setItem(x, x);
        storage.removeItem(x);
        return true;
    }
    catch(e) {
        return e instanceof DOMException && (
            // everything except Firefox
            e.code === 22 ||
            // Firefox
            e.code === 1014 ||
            // test name field too, because code might not be present
            // everything except Firefox
            e.name === 'QuotaExceededError' ||
            // Firefox
            e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
            // acknowledge QuotaExceededError only if there's something already stored
            (storage && storage.length !== 0);
    }
}

Use this snippet like this, and fallback to, for example, using cookie:

if (storageAvailable('localStorage')) {
  // Yippee! We can use localStorage awesomeness
}
else {
  // Too bad, no localStorage for us
  document.cookie = key + "=" + encodeURIComponent(value) + expires + "; path=/";
}

I have made the fallbackstorage package which uses this snippet to check for the storage availability and fallback to a manually implemented MemoryStorage.

import {getSafeStorage} from 'fallbackstorage'

getSafeStorage().setItem('test', '1') // always work

How to decrypt a password from SQL server?

You cannot decrypt this password again but there is another method named "pwdcompare". Here is a example how to use it with SQL syntax:

USE TEMPDB
GO
declare @hash varbinary (255)
CREATE TABLE tempdb..h (id_num int, hash varbinary (255))
SET @hash = pwdencrypt('123') -- encryption
INSERT INTO tempdb..h (id_num,hash) VALUES (1,@hash)
SET @hash = pwdencrypt('123')
INSERT INTO tempdb..h (id_num,hash) VALUES (2,@hash)
SELECT TOP 1 @hash = hash FROM tempdb..h WHERE id_num = 2
SELECT pwdcompare ('123', @hash) AS [Success of check] -- Comparison
SELECT * FROM tempdb..h
INSERT INTO tempdb..h (id_num,hash) 
VALUES (3,CONVERT(varbinary (255),
0x01002D60BA07FE612C8DE537DF3BFCFA49CD9968324481C1A8A8FE612C8DE537DF3BFCFA49CD9968324481C1A8A8))
SELECT TOP 1 @hash = hash FROM tempdb..h WHERE id_num = 3
SELECT pwdcompare ('123', @hash) AS [Success of check] -- Comparison
SELECT * FROM tempdb..h
DROP TABLE tempdb..h
GO

CSS: borders between table columns only

I may be simplifying the issue, but does td {border-right: 1px solid red;} work for your table setup?

rand() between 0 and 1

This is entirely implementation specific, but it appears that in the C++ environment you're working in, RAND_MAX is equal to INT_MAX.

Because of this, RAND_MAX + 1 exhibits undefined (overflow) behavior, and becomes INT_MIN. While your initial statement was dividing (random # between 0 and INT_MAX)/(INT_MAX) and generating a value 0 <= r < 1, now it's dividing (random # between 0 and INT_MAX)/(INT_MIN), generating a value -1 < r <= 0

In order to generate a random number 1 <= r < 2, you would want

r = ((double) rand() / (RAND_MAX)) + 1

How to fill DataTable with SQL Table

You can make method which return the datatable of given sql query:

public DataTable GetDataTable()
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BarManConnectionString"].ConnectionString);
conn.Open();
string query = "SELECT * FROM [EventOne] ";

SqlCommand cmd = new SqlCommand(query, conn);

DataTable t1 = new DataTable();
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
    a.Fill(t1);
}
return t1;
}

and now can be used like this:

table = GetDataTable();

Close a div by clicking outside

An other way which makes then your jsfiddle less buggy (needed double click on open).

This doesn't use any delegated event to body level

Set tabindex="-1" to DIV .popup ( and for style CSS outline:0 )

DEMO

$(".link").click(function(e){
    e.preventDefault();
    $(".popup").fadeIn(300,function(){$(this).focus();});
});

$('.close').click(function() {
   $(".popup").fadeOut(300);
});
$(".popup").on('blur',function(){
    $(this).fadeOut(300);
});

JQuery Validate input file type

So, I had the same issue and sadly just adding to the rules didn't work. I found out that accept: and extension: are not part of JQuery validate.js by default and it requires an additional-Methods.js plugin to make it work.

So for anyone else who followed this thread and it still didn't work, you can try adding additional-Methods.js to your tag in addition to the answer above and it should work.

How to indent/format a selection of code in Visual Studio Code with Ctrl + Shift + F

(This works at least up to version 1.52.0, 10 Dec 2020)


On macOS Visual Studio Code version 1.36.1 (2019)

Visual Studio Code version 1.36.1 (2019)

To auto-format the selection, use ?K ?F (the trick is that this is to be done in sequence, ?K first, followed by ?F).

Auto-format selection or document

To just indent (shift right) without auto-formatting, use ?]

Indent options

As in Keyboard Shortcuts (?K ?S, or from the menu as shown below)

Keyboard shortcuts

Can Mockito stub a method without regard to the argument?

Use like this:

when(
  fooDao.getBar(
    Matchers.<Bazoo>any()
  )
).thenReturn(myFoo);

Before you need to import Mockito.Matchers

HTTP 404 Page Not Found in Web Api hosted in IIS 7.5

None of the above worked for me. Finally it wasn't anything related to any configuration.

I was getting the 404 error while trying to run a debug session through Visual Studio 2017 using the built in IISExpress 10.0. For me it was working when the release was published to the IIS server but getting a 404 when debugging locally through VS.

The issue turned out to be some old compiled files lying in the project bin directory which appeared to be interfering. Finally did a "Clean solution", closed VS, deleted the bin and obj folder. Restarted VS and rebuild project and the error went away.

CodeIgniter: Create new helper?

Well for me only works adding the text "_helper" after in the php file like:

Codeiginiter Helpers

And to load automatically the helper in the folder aplication -> file autoload.php add in the array helper's the name without "_helper" like:

$autoload['helper'] = array('comunes');

And with that I can use all the helper's functions

What USB driver should we use for the Nexus 5?

I installed the LG United Mobile Driver, and I was finally able to get ADB to recognize my device.

How to return a file (FileContentResult) in ASP.NET WebAPI

I am not exactly sure which part to blame, but here's why MemoryStream doesn't work for you:

As you write to MemoryStream, it increments it's Position property. The constructor of StreamContent takes into account the stream's current Position. So if you write to the stream, then pass it to StreamContent, the response will start from the nothingness at the end of the stream.

There's two ways to properly fix this:

1) construct content, write to stream

[HttpGet]
public HttpResponseMessage Test()
{
    var stream = new MemoryStream();
    var response = Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new StreamContent(stream);
    // ...
    // stream.Write(...);
    // ...
    return response;
}

2) write to stream, reset position, construct content

[HttpGet]
public HttpResponseMessage Test()
{
    var stream = new MemoryStream();
    // ...
    // stream.Write(...);
    // ...
    stream.Position = 0;

    var response = Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new StreamContent(stream);
    return response;
}

2) looks a little better if you have a fresh Stream, 1) is simpler if your stream does not start at 0

Simulate a specific CURL in PostMan

1) Put https://api-server.com/API/index.php/member/signin in the url input box and choose POST from the dropdown

2) In Headers tab, enter:

Content-Type: image/jpeg

Content-Transfer-Encoding: binary

3) In Body tab, select the raw radio button and write:

{"description":"","phone":"","lastname":"","app_version":"2.6.2","firstname":"","password":"my_pass","city":"","apikey":"213","lang":"fr","platform":"1","email":"[email protected]","pseudo":"example"}

select form-data radio button and write:

key = name Value = userfile Select Text key = filename Select File and upload your profil.jpg

How to clear the cache in NetBeans

For NetBeans 8+ on Windows 10 there's a definitive bug with duplicate classes error which is being solved by cleaning the cache at C:\Users\<user>\AppData\Local\NetBeans\Cache.

adb connection over tcp not working now

Step 1 . Go to Androidsdk\platform-tools on PC/Laptop

Step 2 :

Connect your device via USB and run:

adb kill-server

then run

adb tcpip 5555

you will see below message...

daemon not running. starting it now on port 5037 * daemon started successfully * restarting in TCP mode port: 5555

Step3:

Now open new CMD window,

Go to Androidsdk\platform-tools

Now run

adb connect xx.xx.xx.xx:5555 (xx.xx.xx.xx is device IP)

Step4: Disconnect your device from USB and it will work as if connected from your Android studio.

How to print struct variables in console?

I want to recommend go-spew, which according to their github "Implements a deep pretty printer for Go data structures to aid in debugging"

go get -u github.com/davecgh/go-spew/spew

usage example:

package main

import (
    "github.com/davecgh/go-spew/spew"
)

type Project struct {
    Id      int64  `json:"project_id"`
    Title   string `json:"title"`
    Name    string `json:"name"`
    Data    string `json:"data"`
    Commits string `json:"commits"`
}

func main() {

    o := Project{Name: "hello", Title: "world"}
    spew.Dump(o)
}

output:

(main.Project) {
 Id: (int64) 0,
 Title: (string) (len=5) "world",
 Name: (string) (len=5) "hello",
 Data: (string) "",
 Commits: (string) ""
}

How to convert FileInputStream to InputStream?

If you wrap one stream into another, you don't close intermediate streams, and very important: You don't close them before finishing using the outer streams. Because you would close the outer stream too.

how to get request path with express req object

If you want to really get only "path" without querystring, you can use url library to parse and get only path part of url.

var url = require('url');

//auth required or redirect
app.use('/account', function(req, res, next) {
    var path = url.parse(req.url).pathname;
    if ( !req.session.user ) {
      res.redirect('/login?ref='+path);
    } else {
      next();
    }
});

How to access host port from docker container

You can access the local webserver which is running in your host machine in two ways.

  1. Approach 1 with public IP

    Use host machine public IP address to access webserver in Jenkins docker container.

  2. Approach 2 with the host network

    Use "--net host" to add the Jenkins docker container on the host's network stack. Containers which are deployed on host's stack have entire access to the host interface. You can access local webserver in docker container with a private IP address of the host machine.

NETWORK ID          NAME                      DRIVER              SCOPE
b3554ea51ca3        bridge                    bridge              local
2f0d6d6fdd88        host                      host                local
b9c2a4bc23b2        none                      null                local

Start a container with the host network Eg: docker run --net host -it ubuntu and run ifconfig to list all available network IP addresses which are reachable from docker container.

Eg: I started a nginx server in my local host machine and I am able to access the nginx website URLs from Ubuntu docker container.

docker run --net host -it ubuntu

$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
a604f7af5e36        ubuntu              "/bin/bash"         22 seconds ago      Up 20 seconds                           ubuntu_server

Accessing the Nginx web server (running in local host machine) from Ubuntu docker container with private network IP address.

root@linuxkit-025000000001:/# curl 192.168.x.x -I
HTTP/1.1 200 OK
Server: nginx/1.15.10
Date: Tue, 09 Apr 2019 05:12:12 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 26 Mar 2019 14:04:38 GMT
Connection: keep-alive
ETag: "5c9a3176-264"
Accept-Ranges: bytes

how does Array.prototype.slice.call() work?

Normally, calling

var b = a.slice();

will copy the array a into b. However, we can't do

var a = arguments.slice();

because arguments isn't a real array, and doesn't have slice as a method. Array.prototype.slice is the slice function for arrays, and call runs the function with this set to arguments.

How to pass ArrayList of Objects from one to another activity using Intent in android?

Your bean or pojo class should implements parcelable interface.

For example:

public class BeanClass implements Parcelable{
    String name;
    int age;
    String sex;

    public BeanClass(String name, int age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    } 
     public static final Creator<BeanClass> CREATOR = new Creator<BeanClass>() {
        @Override
        public BeanClass createFromParcel(Parcel in) {
            return new BeanClass(in);
        }

        @Override
        public BeanClass[] newArray(int size) {
            return new BeanClass[size];
        }
    };
    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(age);
        dest.writeString(sex);
    }
}

Consider a scenario that you want to send the arraylist of beanclass type from Activity1 to Activity2.
Use the following code

Activity1:

ArrayList<BeanClass> list=new ArrayList<BeanClass>();

private ArrayList<BeanClass> getList() {
    for(int i=0;i<5;i++) {

        list.add(new BeanClass("xyz", 25, "M"));
    }
    return list;
}
private void gotoNextActivity() {
    Intent intent=new Intent(this,Activity2.class);
    /* Bundle args = new Bundle();
    args.putSerializable("ARRAYLIST",(Serializable)list);
    intent.putExtra("BUNDLE",args);*/

    Bundle bundle = new Bundle();
    bundle.putParcelableArrayList("StudentDetails", list);
    intent.putExtras(bundle);
    startActivity(intent);
}

Activity2:

ArrayList<BeanClass> listFromActivity1=new ArrayList<>();

listFromActivity1=this.getIntent().getExtras().getParcelableArrayList("StudentDetails");

if (listFromActivity1 != null) {

    Log.d("listis",""+listFromActivity1.toString());
}

I think this basic to understand the concept.

How can I sort an ArrayList of Strings in Java?

Take a look at the Collections.sort(List<T> list).

You can simply remove the first element, sort the list and then add it back again.

Preventing an image from being draggable or selectable without using JS

You can use the pointer-events property in your CSS, and set it equal to 'none'

img {
    pointer-events: none;
}

Edited

this will block (click) event. So better solution would be

<img draggable="false" (dragstart)="false;" class="unselectable">

.unselectable {
  user-drag: none; 
  user-select: none;
  -moz-user-select: none;
  -webkit-user-drag: none;
  -webkit-user-select: none;
  -ms-user-select: none;
}

JavaScript CSS how to add and remove multiple CSS classes to an element

var el = document.getElementsByClassName('myclass')

el[0].classList.add('newclass');

el[0].classList.remove('newclass');

To find whether the class exists or not, use:

el[0].classList.contains('newclass'); // this will return true or false 

Browser support IE8+

HTML Text with tags to formatted text in an Excel cell

I know this thread is ancient, but after assigning the innerHTML, ExecWB worked for me:

_x000D_
_x000D_
.ExecWB 17, 0_x000D_
'Select all contents in browser_x000D_
.ExecWB 12, 2_x000D_
'Copy them
_x000D_
_x000D_
_x000D_

And then just paste the contents into Excel. Since these methods are prone to runtime errors, but work fine after one or two tries in debug mode, you might have to tell Excel to try again if it runs into an error. I solved this by adding this error handler to the sub, and it works fine:

_x000D_
_x000D_
Sub ApplyHTML()_x000D_
  On Error GoTo ErrorHandler_x000D_
    ..._x000D_
  Exit Sub_x000D_
_x000D_
ErrorHandler:_x000D_
    Resume _x000D_
    'I.e. re-run the line of code that caused the error_x000D_
Exit Sub_x000D_
     _x000D_
End Sub
_x000D_
_x000D_
_x000D_

How do I pass command line arguments to a Node.js program?

npm install ps-grab

If you want to run something like this :

node greeting.js --user Abdennour --website http://abdennoor.com 

--

var grab=require('ps-grab');
grab('--username') // return 'Abdennour'
grab('--action') // return 'http://abdennoor.com'

Or something like :

node vbox.js -OS redhat -VM template-12332 ;

--

var grab=require('ps-grab');
grab('-OS') // return 'redhat'
grab('-VM') // return 'template-12332'

Cloud Firestore collection count

Increment a counter using admin.firestore.FieldValue.increment:

exports.onInstanceCreate = functions.firestore.document('projects/{projectId}/instances/{instanceId}')
  .onCreate((snap, context) =>
    db.collection('projects').doc(context.params.projectId).update({
      instanceCount: admin.firestore.FieldValue.increment(1),
    })
  );

exports.onInstanceDelete = functions.firestore.document('projects/{projectId}/instances/{instanceId}')
  .onDelete((snap, context) =>
    db.collection('projects').doc(context.params.projectId).update({
      instanceCount: admin.firestore.FieldValue.increment(-1),
    })
  );

In this example we increment an instanceCount field in the project each time a document is added to the instances sub collection. If the field doesn't exist yet it will be created and incremented to 1.

The incrementation is transactional internally but you should use a distributed counter if you need to increment more frequently than every 1 second.

It's often preferable to implement onCreate and onDelete rather than onWrite as you will call onWrite for updates which means you are spending more money on unnecessary function invocations (if you update the docs in your collection).

How to load image files with webpack file-loader

Install file loader first:

$ npm install file-loader --save-dev

And add this rule in webpack.config.js

           {
                test: /\.(png|jpg|gif)$/,
                use: [{
                    loader: 'file-loader',
                    options: {}
                }]
            }

How to regex in a MySQL query

In my case (Oracle), it's WHERE REGEXP_LIKE(column, 'regex.*'). See here:

SQL Function

Description


REGEXP_LIKE

This function searches a character column for a pattern. Use this function in the WHERE clause of a query to return rows matching the regular expression you specify.

...

REGEXP_REPLACE

This function searches for a pattern in a character column and replaces each occurrence of that pattern with the pattern you specify.

...

REGEXP_INSTR

This function searches a string for a given occurrence of a regular expression pattern. You specify which occurrence you want to find and the start position to search from. This function returns an integer indicating the position in the string where the match is found.

...

REGEXP_SUBSTR

This function returns the actual substring matching the regular expression pattern you specify.

(Of course, REGEXP_LIKE only matches queries containing the search string, so if you want a complete match, you'll have to use '^$' for a beginning (^) and end ($) match, e.g.: '^regex.*$'.)

What is the meaning of "POSIX"?

A specification (blueprint) about how to make an OS compatible with late UNIX OS (may God bless him!). This is why macOS and GNU/Linux have very similar terminal command lines, GUI's, libraries, etc. Because they both were designed according to POSIX blueprint.

POSIX does not tell engineers and programmers how to code but what to code.

Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click

I ran into this error while trying to click some element (or its overlay, I didn't care), and the other answers didn't work for me. I fixed it by using the elementFromPoint DOM API to find the element that Selenium wanted me to click on instead:

element_i_care_about = something()
loc = element_i_care_about.location
element_to_click = driver.execute_script(
    "return document.elementFromPoint(arguments[0], arguments[1]);",
    loc['x'],
    loc['y'])
element_to_click.click()

I've also had situations where an element was moving, for example because an element above it on the page was doing an animated expand or collapse. In that case, this Expected Condition class helped. You give it the elements that are animated, not the ones you want to click. This version only works for jQuery animations.

class elements_not_to_be_animated(object):
    def __init__(self, locator):
        self.locator = locator

    def __call__(self, driver):
        try:
            elements = EC._find_elements(driver, self.locator)
            # :animated is an artificial jQuery selector for things that are
            # currently animated by jQuery.
            return driver.execute_script(
                'return !jQuery(arguments[0]).filter(":animated").length;',
                elements)
        except StaleElementReferenceException:
            return False

This app won't run unless you update Google Play Services (via Bazaar)

I spent about one day to configure the new gmaps API (Google Maps Android API v2) on the Android emulator. None of the methods of those I found on the Internet was working correctly for me. But still I did it. Here is how:

  1. Create a new emulator with the following configuration:

Enter image description here

On the other versions I could not configure because of various errors when I installed the necessary applications.

2) Start the emulator and install the following applications:

  • GoogleLoginService.apk
  • GoogleServicesFramework.apk
  • Phonesky.apk

You can do this with following commands:

2.1) adb shell mount -o remount,rw -t yaffs2 /dev/block/mtdblock0 /system
2.2) adb shell chmod 777 /system/app
2.3-2.5) adb push Each_of_the_3_apk_files.apk /system/app/

Links to download APK files. I have copied them from my rooted Android device.

3) Install Google Play Services and Google Maps on the emulator. I have an error 491, if I install them from Google Play store. I uploaded the apps to the emulator and run the installation locally. (You can use adb to install this). Links to the apps:

4) I successfully run a demo sample on the emulator after these steps. Here is a screenshot:

Google Maps

Interfaces — What's the point?

In this case, you could ( and probably would ) just define a Pizza base class and inherit from them. However, there are two reasons where Interfaces allow you to do things that cannot be achieved in other ways:

  1. A class can implement multiple interfaces. It just defines features that the class must have. Implementing a range of interfaces means that a class can fulfil multiple functions in different places.

  2. An interface can be defined in a hogher scope than the class or the caller. This means that you can separate the functionality, separate the project dependency, and keep the functionality in one project or class, and the implementation of this elsewhere.

One implication of 2 is that you can change the class that is being used, just requiring that it implements the appropriate interface.

How do I revert to a previous package in Anaconda?

I know it was not available at the time, but now you could also use Anaconda navigator to install a specific version of packages in the environments tab.

How to solve a pair of nonlinear equations using Python?

You can use openopt package and its NLP method. It has many dynamic programming algorithms to solve nonlinear algebraic equations consisting:
goldenSection, scipy_fminbound, scipy_bfgs, scipy_cg, scipy_ncg, amsg2p, scipy_lbfgsb, scipy_tnc, bobyqa, ralg, ipopt, scipy_slsqp, scipy_cobyla, lincher, algencan, which you can choose from.
Some of the latter algorithms can solve constrained nonlinear programming problem. So, you can introduce your system of equations to openopt.NLP() with a function like this:

lambda x: x[0] + x[1]**2 - 4, np.exp(x[0]) + x[0]*x[1]

How to deselect a selected UITableView cell?

What I've found is that on top of setting the cell as selected, you have to let the table view know to select the row at the given index path.

// Swift 3+  

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if appDelegate.indexPathDelegate.row == indexPath.row {
        self.tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
        cell.setSelected(true, animated: true)
    }
}

What is the right way to write my script 'src' url for a local development environment?

This is an old post but...

You can reference the working directory (the folder the .html file is located in) with ./, and the directory above that with ../

Example directory structure:

/html/public/
- index.html
- script2.js
- js/
   - script.js

To load script.js from inside index.html:

<script type="text/javascript" src="./js/script.js">

This goes to the current working directory (location of index.html) and then to the js folder, and then finds the script.

You could also specify ../ to go one directory above the working directory, to load things from there. But that is unusual.

How to reset radiobuttons in jQuery so that none is checked

Although prop changed the checked status but change also show that in the form.

$('input[name="correctAnswer"]').prop('checked', false).change();

Hash function for a string

First, it usually does not matter that much in practice. Most hash functions are "good enough".

But if you really care, you should know that it is a research subject by itself. There are thousand of papers about that. You can still get a PhD today by studying & designing hashing algorithms.

Your second hash function might be slightly better, because it probably should separate the string "ab" from the string "ba". On the other hand, it is probably less quick than the first hash function. It may, or may not, be relevant for your application.

I'll guess that hash functions used for genome strings are quite different than those used to hash family names in telephone databases. Perhaps even some string hash functions are better suited for German, than for English or French words.

Many software libraries give you good enough hash functions, e.g. Qt has qhash, and C++11 has std::hash in <functional>, Glib has several hash functions in C, and POCO has some hash function.

I quite often have hashing functions involving primes (see Bézout's identity) and xor, like e.g.

#define A 54059 /* a prime */
#define B 76963 /* another prime */
#define C 86969 /* yet another prime */
#define FIRSTH 37 /* also prime */
unsigned hash_str(const char* s)
{
   unsigned h = FIRSTH;
   while (*s) {
     h = (h * A) ^ (s[0] * B);
     s++;
   }
   return h; // or return h % C;
}

But I don't claim to be an hash expert. Of course, the values of A, B, C, FIRSTH should preferably be primes, but you could have chosen other prime numbers.

Look at some MD5 implementation to get a feeling of what hash functions can be.

Most good books on algorithmics have at least a whole chapter dedicated to hashing. Start with wikipages on hash function & hash table.

Tick symbol in HTML/XHTML

You can add a little white one with a Base64 Encoded GIF (online generator here):

url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==")

With Chrome, for instance, I use it to style the checkbox control:

INPUT[type=checkbox]:focus
{
outline:1px solid rgba(0,0,0,0.2);
}

INPUT[type=checkbox]
{
background-color: #DDD;
border-radius: 2px;
-webkit-appearance: button;
width: 17px;
height: 17px;
margin-top: 1px;
cursor:pointer;
}

INPUT[type=checkbox]:checked
{
background:#409fd6 url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==") 3px 3px no-repeat;
}

If you just wanted it in an IMG tag, you would do the checkmark/tickmark as:

<img alt="" src="data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==" width="11" height="10">

How do I compare two files using Eclipse? Is there any option provided by Eclipse?

If your compairing javascript you might find it not displaying.

https://bugs.eclipse.org/bugs/show_bug.cgi?id=509820

Here is a workround...

  • Window > Preferences > Compare/Patch > General Tab
  • Deselect checkbox next to "Open structure compare automatically"

How to detect orientation change?

I like checking the orientation notification because you can add this feature in any class, no needs to be a view or a view controller. Even in your app delegate.

SWIFT 5:

    //ask the system to start notifying when interface change
    UIDevice.current.beginGeneratingDeviceOrientationNotifications()
    //add the observer
    NotificationCenter.default.addObserver(
        self,
        selector: #selector(orientationChanged(notification:)),
        name: UIDevice.orientationDidChangeNotification,
        object: nil)

than caching the notification

    @objc func orientationChanged(notification : NSNotification) {
        //your code there
    }

Best JavaScript compressor

Try JSMin, got C#, Java, C and other ports and readily available too.

git still shows files as modified after adding to .gitignore

To the people who might be searching for this issue still, are looking at this page only.

This will help you remove cached index files, and then only add the ones you need, including changes to your .gitignore file.

1. git rm -r --cached .  
2. git add .
3. git commit -m 'Removing ignored files'

Here is a little bit more info.

  1. This command will remove all cached files from index.
  2. This command will add all files except those which are mentioned in gitignore.
  3. This command will commit your files again and remove the files you want git to ignore, but keep them in your local directory.

Do Java arrays have a maximum size?

Maximum number of elements of an array is (2^31)-1 or 2 147 483 647

How to remove commits from a pull request

You have several techniques to do it.

This post - read the part about the revert will explain in details what we want to do and how to do it.

Here is the most simple solution to your problem:

# Checkout the desired branch
git checkout <branch>

# Undo the desired commit
git revert <commit>

# Update the remote with the undo of the code
git push origin <branch>

The revert command will create a new commit with the undo of the original commit.

VBScript -- Using error handling

Note that On Error Resume Next is not set globally. You can put your unsafe part of code eg into a function, which will interrupted immediately if error occurs, and call this function from sub containing precedent OERN statement.

ErrCatch()

Sub ErrCatch()
    Dim Res, CurrentStep

    On Error Resume Next

    Res = UnSafeCode(20, CurrentStep)
    MsgBox "ErrStep " & CurrentStep & vbCrLf & Err.Description

End Sub

Function UnSafeCode(Arg, ErrStep)

    ErrStep = 1
    UnSafeCode = 1 / (Arg - 10)

    ErrStep = 2
    UnSafeCode = 1 / (Arg - 20)

    ErrStep = 3
    UnSafeCode = 1 / (Arg - 30)

    ErrStep = 0
End Function

PHP function to get the subdomain of a URL

As the only reliable source for domain suffixes are the domain registrars, you can't find the subdomain without their knowledge. There is a list with all domain suffixes at https://publicsuffix.org. This site also links to a PHP library: https://github.com/jeremykendall/php-domain-parser.

Please find an example below. I also added the sample for en.test.co.uk which is a domain with a multi suffix (co.uk).

<?php

require_once 'vendor/autoload.php';

$pslManager = new Pdp\PublicSuffixListManager();
$parser = new Pdp\Parser($pslManager->getList());
$host = 'http://en.example.com';
$url = $parser->parseUrl($host);

echo $url->host->subdomain;


$host = 'http://en.test.co.uk';
$url = $parser->parseUrl($host);

echo $url->host->subdomain;

Can I update a JSF component from a JSF backing bean method?

I also tried to update a component from a jsf backing bean/class

You need to do the following after manipulating the UI component:

FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add(componentToBeRerendered.getClientId())

It is important to use the clientId instead of the (server-side) componentId!!

How do you change library location in R?

You can edit Rprofile in the base library (in 'C:/Program Files/R.Files/library/base/R' by default) to include code to be run on startup. Append

########        User code        ########
.libPaths('C:/my/dir')

to Rprofile using any text editor (like Notepad) to cause R to add 'C:/my/dir' to the list of libraries it knows about.

(Notepad can't save to Program Files, so save your edited Rprofile somewhere else and then copy it in using Windows Explorer.)

Why not use tables for layout in HTML?

No arguments in DIVs favour from me.

I'd say : If the shoe fits, wear it.

It's worth noting that it's difficult if not impossible to find a good DIV+CSS method of rendering contents in two or three columns, that is consistent on all browsers, and still looks just the way I intended.

This tips the balance a bit towards tables in most of my layouts, and altough I feel guilty of using them (dunny why, people just say it's bad so I try to listen to them), in the end , the pragmatic view is it's just easier and faster for me to use TABLEs. I'm not being payed by the hour, so tables are cheaper for me.

Bash script processing limited number of commands in parallel

You can run 20 processes and use the command:

wait

Your script will wait and continue when all your background jobs are finished.

Example for boost shared_mutex (multiple reads/one write)?

Since C++ 17 (VS2015) you can use the standard for read-write locks:

#include <shared_mutex>

typedef std::shared_mutex Lock;
typedef std::unique_lock< Lock > WriteLock;
typedef std::shared_lock< Lock > ReadLock;

Lock myLock;


void ReadFunction()
{
    ReadLock r_lock(myLock);
    //Do reader stuff
}

void WriteFunction()
{
     WriteLock w_lock(myLock);
     //Do writer stuff
}

For older version, you can use boost with the same syntax:

#include <boost/thread/locks.hpp>
#include <boost/thread/shared_mutex.hpp>

typedef boost::shared_mutex Lock;
typedef boost::unique_lock< Lock >  WriteLock;
typedef boost::shared_lock< Lock >  ReadLock;

Getting the size of an array in an object

Javascript arrays have a length property. Use it like this:

st.itemb.length

ModuleNotFoundError: What does it mean __main__ is not a package?

Simply remove the dot for the relative import and do:

from p_02_paying_debt_off_in_a_year import compute_balance_after

Why is the minidlna database not being refreshed?

AzP already provided most of the information, but some of it is incorrect.

First of all, there is no such option inotify_interval. The only option that exists is notify_interval and has nothing to do with inotify.

So to clarify, notify_interval controls how frequently the (mini)dlna server announces itself in the network. The default value of 895 means it will announce itself about once every 15 minutes, meaning clients will need at most 15 minutes to find the server. I personally use 1-5 minutes depending on client volatility in the network.

In terms of getting minidlna to find files that have been added, there are two options:

  • The first is equivalent to removing the file files.db and consists in restarting minidlna while passing the -R argument, which forces a full rescan and builds the database from scratch. Since version 1.2.0 there's now also the -r argument which performs a rebuild action. This preserves any existing database and drops and adds old and new records, respectively.
  • The second is to rely on inotify events by setting inotify=yes and restarting minidlna. If inotify is set to =no, the only option to update the file database is the forced full rescan.

Additionally, in order to have inotify working, the file-system must support inotify events, which is not the case in most remote file-systems. If you have minidlna running over NFS it will not see any inotify events because these are generated on the server side and not on the client.

Finally, even if inotify is working and is supported by the file-system, the user under which minidlna is running must be able to read the file, otherwise it will not be able to retrieve necessary metadata. In this case, the logfile (usually /var/log/minidlna.log) should contain useful information.

Differences between MySQL and SQL Server

@Cebjyre. The IDE whether Enterprise Manager or Management Studio is better than anything I have seen so far for MySQL. I say 'easier to use' because I can do many things in MSSQL where MySQL has no counterparts. In MySQL I have no idea how to tune the queries by simply looking at the query plan or looking at the statistics. The index tuning wizard in MSSQL takes most of the guess work on what indexes are missing or misplaced.

One shortcoming of MySQL is there's no max size for a database. The database would just increase in size till it fills up the disk. Imagine if this disk is sharing databases with other users and suddenly all of their queries are failing because their databases can't grow. I have reported this issue to MySQL long time ago. I don't think it's fixed yet.

move div with CSS transition

Something like this?

DEMO

And the code I used:

.box{
    position: relative;
    overflow: hidden;
}

.box:hover .hidden{

    left: 0px;
}

.box .hidden {    
    background: yellow;
    height: 300px;    
    position: absolute; 
    top: 0;
    left: -500px;    
    width: 500px;
    opacity: 1;    
    -webkit-transition: all 0.7s ease-out;
       -moz-transition: all 0.7s ease-out;
        -ms-transition: all 0.7s ease-out;
         -o-transition: all 0.7s ease-out;
            transition: all 0.7s ease-out;
}

I may also add that it's possible to move an elment using transform: translate(); , which in this case could work something like this - DEMO nr2

CSS Selector for <input type="?"

Sadly the other posters are correct that you're ...actually as corrected by kRON, you are ok with your IE7 and a strict doc, but most of us with IE6 requirements are reduced to JS or class references for this, but it is a CSS2 property, just one without sufficient support from IE^h^h browsers.

Out of completeness, the type selector is - similar to xpath - of the form [attribute=value] but many interesting variants exist. It will be quite powerful when it's available, good thing to keep in your head for IE8.

Check string for nil & empty

Swift 3 For check Empty String best way

if !string.isEmpty{

// do stuff

}

Android: How to open a specific folder via Intent and show its content in a file browser?

this code will work with OI File Manager :

        File root = new File(Environment.getExternalStorageDirectory().getPath()
+ "/myFolder/");
        Uri uri = Uri.fromFile(root);

        Intent intent = new Intent();
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setData(uri);
        startActivityForResult(intent, 1);

you can get OI File manager here : http://www.openintents.org/en/filemanager

How to prevent page scrolling when scrolling a DIV element?

Use below CSS property overscroll-behavior: contain; to child element

Laravel Check If Related Model Exists

After Php 7.1, The accepted answer won't work for all types of relationships.

Because depending of type the relationship, Eloquent will return a Collection, a Model or Null. And in Php 7.1 count(null) will throw an error.

So, to check if the relation exist you can use:

For relationships single: For example hasOne and belongsTo

if(!is_null($model->relation)) {
   ....
}

For relationships multiple: For Example: hasMany and belongsToMany

if ($model->relation->isNotEmpty()) {
   ....
}

How do I put variables inside javascript strings?

I wrote a function which solves the problem precisely.

First argument is the string that wanted to be parameterized. You should put your variables in this string like this format "%s1, %s2, ... %s12".

Other arguments are the parameters respectively for that string.

/***
 * @example parameterizedString("my name is %s1 and surname is %s2", "John", "Doe");
 * @return "my name is John and surname is Doe"
 *
 * @firstArgument {String} like "my name is %s1 and surname is %s2"
 * @otherArguments {String | Number}
 * @returns {String}
 */
const parameterizedString = (...args) => {
  const str = args[0];
  const params = args.filter((arg, index) => index !== 0);
  if (!str) return "";
  return str.replace(/%s[0-9]+/g, matchedStr => {
    const variableIndex = matchedStr.replace("%s", "") - 1;
    return params[variableIndex];
  });
}

Examples

parameterizedString("my name is %s1 and surname is %s2", "John", "Doe");
// returns "my name is John and surname is Doe"

parameterizedString("this%s1 %s2 %s3", " method", "sooo", "goood");
// returns "this method sooo goood"

If variable position changes in that string, this function supports it too without changing the function parameters.

parameterizedString("i have %s2 %s1 and %s4 %s3.", "books", 5, "pencils", "6");
// returns "i have 5 books and 6 pencils."

Javascript receipt printing using POS Printer

If you are talking about a browser based POS app then it basically can't be done out of the box. There are a number of alternatives.

  1. Use an applet like Scott Selby says
  2. Print from the server. If this is a cloud server, ie not connectable to the receipt printer then what you can do is
    • From the server generate it as a pdf which can be made to popup a print dialog in the browser
    • Use something like Google Cloud Print which will allow connecting printers to a cloud service

BitBucket - download source as ZIP

To Download Specific Branch - Go To Downloads from Left panel, Select Branches on Downloads page. It will list all Branches available. Download your desired branch in zip, gz, or bz2 format.

enter image description here

jQuery date formatting

Just use this:

var date_str=('0'+date.getDate()).substr(-2,2)+' '+('0'+date.getMonth()).substr(-2,2)+' '+('0'+date.getFullYear()).substr(-2,2);

How to increase Bootstrap Modal Width?

In my case,

  1. Giving a static width to the modal hurts the responsiveness.
  2. The modal-lg class was not wide enough.

so the solution was

@media (min-width: 1200px) {
   .modal-xlg {
      width: 90%; 
   }
}

and use the above class instead of modal-lg class

Why is the apt-get function not working in the terminal on Mac OS X v10.9 (Mavericks)?

Alternatively You can use the brew or curl command for installing things, wherever apt-get is mentioned with a URL...

For example,

curl -O http://www.magentocommerce.com/downloads/assets/1.8.1.0/magento-1.8.1.0.tar.gz

Is there a way to detect if an image is blurry?

That's what I do in Opencv to detect focus quality in a region:

Mat grad;
int scale = 1;
int delta = 0;
int ddepth = CV_8U;
Mat grad_x, grad_y;
Mat abs_grad_x, abs_grad_y;
/// Gradient X
Sobel(matFromSensor, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT);
/// Gradient Y
Sobel(matFromSensor, grad_y, ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT);
convertScaleAbs(grad_x, abs_grad_x);
convertScaleAbs(grad_y, abs_grad_y);
addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad);
cv::Scalar mu, sigma;
cv::meanStdDev(grad, /* mean */ mu, /*stdev*/ sigma);
focusMeasure = mu.val[0] * mu.val[0];

How to use clock() in C++

An alternative solution, which is portable and with higher precision, available since C++11, is to use std::chrono.

Here is an example:

#include <iostream>
#include <chrono>
typedef std::chrono::high_resolution_clock Clock;

int main()
{
    auto t1 = Clock::now();
    auto t2 = Clock::now();
    std::cout << "Delta t2-t1: " 
              << std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count()
              << " nanoseconds" << std::endl;
}

Running this on ideone.com gave me:

Delta t2-t1: 282 nanoseconds

Chrome doesn't delete session cookies

I had the same problem with "document.cookie" in Windows 8.1, the only way that Chrome deletes the cookie was shutting it from task manager (not a really fancy way), so I decided to manage the cookies from the backend or use something like "js-cookie".

How do I trim whitespace from a string?

As pointed out in answers above

my_string.strip()

will remove all the leading and trailing whitespace characters such as \n, \r, \t, \f, space .

For more flexibility use the following

  • Removes only leading whitespace chars: my_string.lstrip()
  • Removes only trailing whitespace chars: my_string.rstrip()
  • Removes specific whitespace chars: my_string.strip('\n') or my_string.lstrip('\n\r') or my_string.rstrip('\n\t') and so on.

More details are available in the docs.

Ruby function to remove all white spaces?

Ruby's .strip method performs the PHP equivalent to trim().

To remove all whitespace:

"  leading    trailing   ".squeeze(' ').strip
=> "leading trailing"

@Tass made me aware that my original answer removes duplicate letters in succession - YUCK! I've since switched to the squish method which is smarter about such occurrences if using the Rails framework.

require 'active_support/all'
"  leading    trailing   ".squish
=> "leading trailing"

"  good    men   ".squish
=> "good men"

Cite: http://apidock.com/rails/String/squish

How do I read input character-by-character in Java?

Use Reader.read(). A return value of -1 means end of stream; else, cast to char.

This code reads character data from a list of file arguments:

public class CharacterHandler {
    //Java 7 source level
    public static void main(String[] args) throws IOException {
        // replace this with a known encoding if possible
        Charset encoding = Charset.defaultCharset();
        for (String filename : args) {
            File file = new File(filename);
            handleFile(file, encoding);
        }
    }

    private static void handleFile(File file, Charset encoding)
            throws IOException {
        try (InputStream in = new FileInputStream(file);
             Reader reader = new InputStreamReader(in, encoding);
             // buffer for efficiency
             Reader buffer = new BufferedReader(reader)) {
            handleCharacters(buffer);
        }
    }

    private static void handleCharacters(Reader reader)
            throws IOException {
        int r;
        while ((r = reader.read()) != -1) {
            char ch = (char) r;
            System.out.println("Do something with " + ch);
        }
    }
}

The bad thing about the above code is that it uses the system's default character set. Wherever possible, prefer a known encoding (ideally, a Unicode encoding if you have a choice). See the Charset class for more. (If you feel masochistic, you can read this guide to character encoding.)

(One thing you might want to look out for are supplementary Unicode characters - those that require two char values to store. See the Character class for more details; this is an edge case that probably won't apply to homework.)

Submit form using a button outside the <form> tag

This work perfectly! ;)

This can be done using Ajax and with what I call: "a form mirror element". Instead to send a form with an element outside, you can create a fake form. The previous form is not needed.

<!-- This will do the trick -->
<div >
    <input id="mirror_element" type="text" name="your_input_name">
    <input type="button" value="Send Form">
</div>

Code ajax would be like:

    <script>
        ajax_form_mirror("#mirror_element", "your_file.php", "#your_element_response", "POST");

        function ajax_form_mirror(form, file, element, method) {
            $(document).ready(function() {
                // Ajax
                $(form).change(function() { // catch the forms submit event
                    $.ajax({                // create an AJAX call...
                        data: $(this).serialize(),      // get the form data
                        type: method,                   // GET or POST
                        url: file,                      // the file to call
                        success: function (response) {   // on success..
                        $(element).html(response);  // update the DIV
                        }
                    });

                    return false; // cancel original event to prevent form submitting
                });
            });
        }
   </script>

This is very usefull if you want to send some data inside another form without submit the parent form.

This code probably can be adapted/optimized according to the need. It works perfectly!! ;) Also works if you want a select option box like this:

<div>
    <select id="mirror_element" name="your_input_name">
        <option id="1" value="1">A</option>
        <option id="2" value="2">B</option>
        <option id="3" value="3">C</option>
        <option id="4" value="4">D</option>
    </select>
</div>

I hope it helped someone like it helped me. ;)

How to define global variable in Google Apps Script

I'm using a workaround by returning a function with an object of my global variables:

function globalVariables(){
  var variables = {
    sheetName: 'Sheet1',
    variable1: 1,
    variable2: 2
  };
  return variables;
}

function functionThatUsesVariable (){
  var sheet =   SpreadsheetApp.getActiveSpreadsheet().getSheetByName(globalVariables().sheetName);
}

CSS rounded corners in IE8

Rounded corners in IE8

Internet Explorer 8 (and earlier versions) doesn't support rounded corners, however there are few other solutions you may consider:

  • Use Rounded Corners Images instead (this generator is a good resource)

  • Use a jQuery Corner plugin from here

  • Use a very good script called CSS3 PIE from here (Pro's & Con's here)

  • Checkout CSS Juice from here

  • Another good script is IE-CSS3 from here

Even though CSS PIE is the most popular solution, I'm suggesting you to review all other solutions and choose what works best for your needs.

Hope it was useful. Good Luck!

get the latest fragment in backstack

You can use the getName() method of FragmentManager.BackStackEntry which was introduced in API level 14. This method will return a tag which was the one you used when you added the Fragment to the backstack with addTobackStack(tag).

int index = getActivity().getFragmentManager().getBackStackEntryCount() - 1
FragmentManager.BackStackEntry backEntry = getFragmentManager().getBackStackEntryAt(index);
String tag = backEntry.getName();
Fragment fragment = getFragmentManager().findFragmentByTag(tag);

You need to make sure that you added the fragment to the backstack like this:

fragmentTransaction.addToBackStack(tag);

Stacked bar chart

You will need to melt your dataframe to get it into the so-called long format:

require(reshape2)
sample.data.M <- melt(sample.data)

Now your field values are represented by their own rows and identified through the variable column. This can now be leveraged within the ggplot aesthetics:

require(ggplot2)
c <- ggplot(sample.data.M, aes(x = Rank, y = value, fill = variable))
c + geom_bar(stat = "identity")

Instead of stacking you may also be interested in showing multiple plots using facets:

c <- ggplot(sample.data.M, aes(x = Rank, y = value))
c + facet_wrap(~ variable) + geom_bar(stat = "identity")

Is there a shortcut to make a block comment in Xcode?

If you have a keyboard layout that requires you to also press the shift key (i.e. cmd + shift + 7 on a German keyboard), the shortcut won't work and open the help menu, instead.

Apple's "Think Different" in its fullest extent ...

You can define your own shortcut to make it work, if you go to Xcode > Preferences > Key Bindings:

Changing comment selection key map in Xcode

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

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

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

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

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

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

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

Update React component every second

The following code is a modified example from React.js website.

Original code is available here: https://reactjs.org/#a-simple-component

class Timer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      seconds: parseInt(props.startTimeInSeconds, 10) || 0
    };
  }

  tick() {
    this.setState(state => ({
      seconds: state.seconds + 1
    }));
  }

  componentDidMount() {
    this.interval = setInterval(() => this.tick(), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  formatTime(secs) {
    let hours   = Math.floor(secs / 3600);
    let minutes = Math.floor(secs / 60) % 60;
    let seconds = secs % 60;
    return [hours, minutes, seconds]
        .map(v => ('' + v).padStart(2, '0'))
        .filter((v,i) => v !== '00' || i > 0)
        .join(':');
  }

  render() {
    return (
      <div>
        Timer: {this.formatTime(this.state.seconds)}
      </div>
    );
  }
}

ReactDOM.render(
  <Timer startTimeInSeconds="300" />,
  document.getElementById('timer-example')
);

How to perform Unwind segue programmatically?

  1. Create a manual segue (ctrl-drag from File’s Owner to Exit),
  2. Choose it in the Left Controller Menu below green EXIT button.

Choose it in the Left Controller Menu below green EXIT button

Insert Name of Segue to unwind.

Then,- (void)performSegueWithIdentifier:(NSString *)identifier sender:(id)sender. with your segue identify.

How to format a URL to get a file from Amazon S3?

Perhaps not what the OP was after, but for those searching the URL to simply access a readable object on S3 is more like:

https://<region>.amazonaws.com/<bucket-name>/<key>

Where <region> is something like s3-ap-southeast-2.

Click on the item in the S3 GUI to get the link for your bucket.

Check a radio button with javascript

Easiest way would probably be with jQuery, as follows:

$(document).ready(function(){
  $("#_1234").attr("checked","checked");
})

This adds a new attribute "checked" (which in HTML does not need a value). Just remember to include the jQuery library:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

FPDF utf-8 encoding (HOW-TO)

How do I create PDF's in FPDF that support Chinese, Japanese, Russian, etc.?

(snapshots of code in use below)

I'd like to provide: a summary of the problem, the solution, a github project with the working code, and an online example with the expected, resultant PDF.

The Problem :

  1. As stated by Tarsis, swap FPDF to TFPDF.
  2. You actually need a font that supports the UTF-8 characters you are using.

    I.E., merely using Helvetica and trying to display Japanese will not work. If you use Font Forge, or some other font tool, you can scroll to the Chinese characters of the font, and see that they are blank.

    Google has a font (Noto font) that contains all languages, and it is 20mb, which is usually several factors the size of your text. So, you can see why many fonts simply won't cover every single language.

The Solution :

I'm using rounded-mgenplus-20140828.ttf and ZCOOL_QingKe_HuangYou.ttf font packs for Japanese and Chinese, which are open source and can be found in many open source projects. In tFPDF itself, or a new inheriting class of it, like class HTMLtoPDF extends tFPDF {...}, you'll do this...

$this->AddFont('japanese', '', 'rounded-mgenplus-20140828.ttf', true);
$this->SetFont('japanese', '', 14);
$this->Write(14, '???');

Should be nothing more to it!

Code Package on GitHub :

https://github.com/HoldOffHunger/php-html-to-pdf

Working, Online Demo of Japanese :

https://www.earthfluent.com/privacy.pdf?language=ja

Break a previous commit into multiple commits

Here is how to split one commit in IntelliJ IDEA, PyCharm, PhpStorm etc

  1. In Version Control log window, select the commit you would like to split, right click and select the Interactively Rebase from Here

  2. mark the one you want to split as edit, click Start Rebasing

  3. You should see a yellow tag is placed meaning that the HEAD is set to that commit. Right click on that commit, select Undo Commit

  4. Now those commits are back to staging area, you can then commit them separately. After all change has been committed, the old commit becomes inactive.

Get file path of image on Android

To get the path of all images in android I am using following code

public void allImages() 
{
    ContentResolver cr = getContentResolver();
    Cursor cursor;
    Uri allimagessuri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    String selection = MediaStore.Images.Media._ID + " != 0";

    cursor = cr.query(allsongsuri, STAR, selection, null, null);

    if (cursor != null) {
        if (cursor.moveToFirst()) {
            do {

                String fullpath = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Images.Media.DATA));
                Log.i("Image path ", fullpath + "");


            } while (cursor.moveToNext());
        }
        cursor.close();
    }

}

android pick images from gallery

If you are only looking for images and multiple selection.

Look @ once https://stackoverflow.com/a/15029515/1136023

It's helpful for future.I personally feel great by using MultipleImagePick.

Fast check for NaN in NumPy

  1. use .any()

    if numpy.isnan(myarray).any()

  2. numpy.isfinite maybe better than isnan for checking

    if not np.isfinite(prop).all()

syntax for creating a dictionary into another dictionary in python

You can declare a dictionary inside a dictionary by nesting the {} containers:

d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}

And then you can access the elements using the [] syntax:

print d['dict1']           # {'foo': 1, 'bar': 2}
print d['dict1']['foo']    # 1
print d['dict2']['quux']   # 4

Given the above, if you want to add another dictionary to the dictionary, it can be done like so:

d['dict3'] = {'spam': 5, 'ham': 6}

or if you prefer to add items to the internal dictionary one by one:

d['dict4'] = {}
d['dict4']['king'] = 7
d['dict4']['queen'] = 8

Getting "method not valid without suitable object" error when trying to make a HTTP request in VBA?

I had to use Debug.print instead of Print, which works in the Immediate window.

Sub SendEmail()
    'Dim objHTTP As New MSXML2.XMLHTTP
    'Set objHTTP = New MSXML2.XMLHTTP60
    'Dim objHTTP As New MSXML2.XMLHTTP60
    Dim objHTTP As New WinHttp.WinHttpRequest
    'Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
    'Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
    URL = "http://localhost:8888/rest/mail/send"
    objHTTP.Open "POST", URL, False
    objHTTP.setRequestHeader "Content-Type", "application/json"
    objHTTP.send ("{""key"":null,""from"":""[email protected]"",""to"":null,""cc"":null,""bcc"":null,""date"":null,""subject"":""My Subject"",""body"":null,""attachments"":null}")
    Debug.Print objHTTP.Status
    Debug.Print objHTTP.ResponseText

End Sub

How to prevent form from submitting multiple times from client side?

The simpliest and elegant solution for me:

function checkForm(form) // Submit button clicked
{
    form.myButton.disabled = true;
    form.myButton.value = "Please wait...";
    return true;
}

<form method="POST" action="..." onsubmit="return checkForm(this);">
    ...
    <input type="submit" name="myButton" value="Submit">
</form>

Link for more...

Stopping Docker containers by image name - Ubuntu

docker stop $(docker ps -a | grep "zalenium")
docker rm $(docker ps -a | grep "zalenium")

This should be enough.

When to use window.opener / window.parent / window.top

when you are dealing with popups window.opener plays an important role, because we have to deal with fields of parent page as well as child page, when we have to use values on parent page we can use window.opener or we want some data on the child window or popup window at the time of loading then again we can set the values using window.opener

Most concise way to convert a Set<T> to a List<T>

List<String> list = new ArrayList<String>(listOfTopicAuthors);

Windows-1252 to UTF-8 encoding

There's no general way to tell if a file is encoded with a specific encoding. Remember that an encoding is nothing more but an "agreement" how the bits in a file should be mapped to characters.

If you don't know which of your files are actually already encoded in UTF-8 and which ones are encoded in windows-1252, you will have to inspect all files and find out yourself. In the worst case that could mean that you have to open every single one of them with either of the two encodings and see whether they "look" correct -- i.e., all characters are displayed correctly. Of course, you may use tool support in order to do that, for instance, if you know for sure that certain characters are contained in the files that have a different mapping in windows-1252 vs. UTF-8, you could grep for them after running the files through 'iconv' as mentioned by Seva Akekseyev.

Another lucky case for you would be, if you know that the files actually contain only characters that are encoded identically in both UTF-8 and windows-1252. In that case, of course, you're done already.

SFTP Libraries for .NET

We use WinSCP. Its free. Its not a lib, but has a well documented and full featured command line interface that you can use with Process.Start.

Update: with v.5.0, WinSCP has a .NET wrapper library to the scripting layer of WinSCP.

How can I compile LaTeX in UTF8?

You needed to iconv your source.

That said, the TEX-based compiler invoked by latex doesn't really support variable-length encodings; it needs big libraries that tell it that certain bytes go together. Xelatex is Unicode-aware and works much better.

Manage toolbar's navigation and back button from fragment in android

(Kotlin) In the activity hosting the fragment(s):

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
    when (item.itemId) {
        android.R.id.home -> {
            onBackPressed()
            return true
        }
    }
    return super.onOptionsItemSelected(item)
}

I have found that when I add fragments to a project, they show the action bar home button by default, to remove/disable it put this in onViewCreated() (use true to enable it if it is not showing):

val actionBar = this.requireActivity().actionBar
    actionBar?.setDisplayHomeAsUpEnabled(false)

HTML: can I display button text in multiple lines?

Yes it is, and you can also use it like this

<button>Click here to<br/> start playing</button>

if you want to make the break yourself.

querying WHERE condition to character length?

SELECT *
   FROM   my_table
   WHERE  substr(my_field,1,5) = "abcde";

Difference between acceptance test and functional test?

The answer is opinion. I worked in a lot of projects and being testmanager and issuemanager and all different roles and the descriptions in various books differ so here is my variation:

functional-testing: take the business requirements and test all of it good and thorougly from a functional viewpoint.

acceptance-testing: the "paying" customer does the testing he likes to do so that he can accept the product delivered. It depends on the customer but usually the tests are not as thorough as the functional-testing especially if it is an in-house project because the stakeholders review and trust the test results done in earlier test phases.

As I said this is my viewpoint and experience. The functional-testing is systematic and the acceptance-testing is rather the business department testing the thing.

Check that a variable is a number in UNIX shell

( test ! -z $num && test $num -eq $num 2> /dev/null ) && {
   # $num is a number
}

How to scp in Python?

Try the Python scp module for Paramiko. It's very easy to use. See the following example:

import paramiko
from scp import SCPClient

def createSSHClient(server, port, user, password):
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(server, port, user, password)
    return client

ssh = createSSHClient(server, port, user, password)
scp = SCPClient(ssh.get_transport())

Then call scp.get() or scp.put() to do SCP operations.

(SCPClient code)

mongodb service is not starting up

Fixed!

The reason was the dbpath variable in /etc/mongodb.conf. Previously, I was using mongodb 1.8, where the default value for dbpath was /data/db. The upstart job mongodb(which comes with mongodb-10gen package) invokes the mongod with --config /etc/mongodb.conf option.

As a solution, I only had to change the owner of the /data/db directory recursively.

Remove a git commit which has not been pushed

I just had the same problem and ended up doing:

git rebase -i HEAD~N

(N is the number of commits git will show you)

That prompts your text editor and then you can remove the commit you want by deleting the line associated with it.

How can I create numbered map markers in Google Maps V3?

I did this using a solution similar to @ZuzEL.

Instead of use the default solution (http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=7|FF0000|000000), you can create these images as you wish, using JavaScript, without any server-side code.

Google google.maps.Marker accepts Base64 for its icon property. With this we can create a valid Base64 from a SVG.

enter image description here

You can see the code to produce the same as this image in this Plunker: http://plnkr.co/edit/jep5mVN3DsVRgtlz1GGQ?p=preview

_x000D_
_x000D_
var markers = [_x000D_
  [1002, -14.2350040, -51.9252800],_x000D_
  [2000, -34.028249, 151.157507],_x000D_
  [123, 39.0119020, -98.4842460],_x000D_
  [50, 48.8566140, 2.3522220],_x000D_
  [22, 38.7755940, -9.1353670],_x000D_
  [12, 12.0733335, 52.8234367],_x000D_
];_x000D_
_x000D_
function initializeMaps() {_x000D_
  var myLatLng = {_x000D_
    lat: -25.363,_x000D_
    lng: 131.044_x000D_
  };_x000D_
_x000D_
  var map = new google.maps.Map(document.getElementById('map_canvas'), {_x000D_
    zoom: 4,_x000D_
    center: myLatLng_x000D_
  });_x000D_
_x000D_
  var bounds = new google.maps.LatLngBounds();_x000D_
_x000D_
  markers.forEach(function(point) {_x000D_
    generateIcon(point[0], function(src) {_x000D_
      var pos = new google.maps.LatLng(point[1], point[2]);_x000D_
_x000D_
      bounds.extend(pos);_x000D_
_x000D_
      new google.maps.Marker({_x000D_
        position: pos,_x000D_
        map: map,_x000D_
        icon: src_x000D_
      });_x000D_
    });_x000D_
  });_x000D_
_x000D_
  map.fitBounds(bounds);_x000D_
}_x000D_
_x000D_
var generateIconCache = {};_x000D_
_x000D_
function generateIcon(number, callback) {_x000D_
  if (generateIconCache[number] !== undefined) {_x000D_
    callback(generateIconCache[number]);_x000D_
  }_x000D_
_x000D_
  var fontSize = 16,_x000D_
    imageWidth = imageHeight = 35;_x000D_
_x000D_
  if (number >= 1000) {_x000D_
    fontSize = 10;_x000D_
    imageWidth = imageHeight = 55;_x000D_
  } else if (number < 1000 && number > 100) {_x000D_
    fontSize = 14;_x000D_
    imageWidth = imageHeight = 45;_x000D_
  }_x000D_
_x000D_
  var svg = d3.select(document.createElement('div')).append('svg')_x000D_
    .attr('viewBox', '0 0 54.4 54.4')_x000D_
    .append('g')_x000D_
_x000D_
  var circles = svg.append('circle')_x000D_
    .attr('cx', '27.2')_x000D_
    .attr('cy', '27.2')_x000D_
    .attr('r', '21.2')_x000D_
    .style('fill', '#2063C6');_x000D_
_x000D_
  var path = svg.append('path')_x000D_
    .attr('d', 'M27.2,0C12.2,0,0,12.2,0,27.2s12.2,27.2,27.2,27.2s27.2-12.2,27.2-27.2S42.2,0,27.2,0z M6,27.2 C6,15.5,15.5,6,27.2,6s21.2,9.5,21.2,21.2c0,11.7-9.5,21.2-21.2,21.2S6,38.9,6,27.2z')_x000D_
    .attr('fill', '#FFFFFF');_x000D_
_x000D_
  var text = svg.append('text')_x000D_
    .attr('dx', 27)_x000D_
    .attr('dy', 32)_x000D_
    .attr('text-anchor', 'middle')_x000D_
    .attr('style', 'font-size:' + fontSize + 'px; fill: #FFFFFF; font-family: Arial, Verdana; font-weight: bold')_x000D_
    .text(number);_x000D_
_x000D_
  var svgNode = svg.node().parentNode.cloneNode(true),_x000D_
    image = new Image();_x000D_
_x000D_
  d3.select(svgNode).select('clippath').remove();_x000D_
_x000D_
  var xmlSource = (new XMLSerializer()).serializeToString(svgNode);_x000D_
_x000D_
  image.onload = (function(imageWidth, imageHeight) {_x000D_
    var canvas = document.createElement('canvas'),_x000D_
      context = canvas.getContext('2d'),_x000D_
      dataURL;_x000D_
_x000D_
    d3.select(canvas)_x000D_
      .attr('width', imageWidth)_x000D_
      .attr('height', imageHeight);_x000D_
_x000D_
    context.drawImage(image, 0, 0, imageWidth, imageHeight);_x000D_
_x000D_
    dataURL = canvas.toDataURL();_x000D_
    generateIconCache[number] = dataURL;_x000D_
_x000D_
    callback(dataURL);_x000D_
  }).bind(this, imageWidth, imageHeight);_x000D_
_x000D_
  image.src = 'data:image/svg+xml;base64,' + btoa(encodeURIComponent(xmlSource).replace(/%([0-9A-F]{2})/g, function(match, p1) {_x000D_
    return String.fromCharCode('0x' + p1);_x000D_
  }));_x000D_
}_x000D_
_x000D_
initializeMaps();
_x000D_
#map_canvas {_x000D_
  width: 100%;_x000D_
  height: 300px;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
  <head>_x000D_
    <link rel="stylesheet" href="style.css">_x000D_
    _x000D_
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>_x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>_x000D_
    _x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <div id="map_canvas"></div>_x000D_
  </body>_x000D_
  _x000D_
  <script src="script.js"></script>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

In this demo I create the SVG using D3.js, then transformed SVG to Canvas, so I can resize the image as I want and after that I get Base64 from canvas' toDataURL method.

All this demo was based on my fellow @thiago-mata code. Kudos for him.

IIS: Where can I find the IIS logs?

A much easier way to do this is using PowerShell, like so:

Get-Website yoursite | % { Join-Path ($_.logFile.Directory -replace '%SystemDrive%', $env:SystemDrive) "W3SVC$($_.id)" }

or simply

Get-Website yoursite | % { $_.logFile.Directory, $_.id }

if you just need the info for yourself and don't mind parsing the result in your brain :).

For bonus points, append | ii to the first command to open in Explorer, or | gci to list the contents of the folder.

Spring boot - Not a managed type

Configure the location of entities using @EntityScan in Spring Boot entry point class.

Update on Sept 2016: For Spring Boot 1.4+:
use org.springframework.boot.autoconfigure.domain.EntityScan
instead of org.springframework.boot.orm.jpa.EntityScan, as ...boot.orm.jpa.EntityScan is deprecated as of Spring Boot 1.4

find difference between two text files with one item per line

I successfully used

diff "${file1}" "${file2}" | grep "<" | sed 's/^<//g' > "${diff_file}"

Outputting the difference to a file.

Keyboard shortcut to clear cell output in Jupyter notebook

STEP 1 :Click on the "Help"and click on "Edit Keyboard Shortcut" STEP1-screenshot

STEP 2 :Add the Shortcut you desire to the "Clear Cell" field STEP2-screenshot

When to use LinkedList over ArrayList in Java?

If your code has add(0) and remove(0), use a LinkedList and it's prettier addFirst() and removeFirst() methods. Otherwise, use ArrayList.

And of course, Guava's ImmutableList is your best friend.

How do you join on the same table, twice, in mysql?

you'd use another join, something along these lines:

SELECT toD.dom_url AS ToURL, 
    fromD.dom_url AS FromUrl, 
    rvw.*

FROM reviews AS rvw

LEFT JOIN domain AS toD 
    ON toD.Dom_ID = rvw.rev_dom_for

LEFT JOIN domain AS fromD 
    ON fromD.Dom_ID = rvw.rev_dom_from

EDIT:

All you're doing is joining in the table multiple times. Look at the query in the post: it selects the values from the Reviews tables (aliased as rvw), that table provides you 2 references to the Domain table (a FOR and a FROM).

At this point it's a simple matter to left join the Domain table to the Reviews table. Once (aliased as toD) for the FOR, and a second time (aliased as fromD) for the FROM.

Then in the SELECT list, you will select the DOM_URL fields from both LEFT JOINS of the DOMAIN table, referencing them by the table alias for each joined in reference to the Domains table, and alias them as the ToURL and FromUrl.

For more info about aliasing in SQL, read here.

Remove Unnamed columns in pandas dataframe

df = df.loc[:, ~df.columns.str.contains('^Unnamed')]

In [162]: df
Out[162]:
   colA  ColB  colC  colD  colE  colF  colG
0    44    45    26    26    40    26    46
1    47    16    38    47    48    22    37
2    19    28    36    18    40    18    46
3    50    14    12    33    12    44    23
4    39    47    16    42    33    48    38

if the first column in the CSV file has index values, then you can do this instead:

df = pd.read_csv('data.csv', index_col=0)

MongoDB: Is it possible to make a case-insensitive query?

I had faced a similar issue and this is what worked for me:

  const flavorExists = await Flavors.findOne({
    'flavor.name': { $regex: flavorName, $options: 'i' },
  });

How to restart ADB manually from Android Studio

After reinstalling Android Studio, Is working without adb kill-server

Where can I find the API KEY for Firebase Cloud Messaging?

It's in https://console.firebase.google.com/project/(your-project-id)/settings/cloudmessaging

You can find the API KEY in:

(gear-next-to-project-name) > Project Settings > Cloud Messaging

Server Key is the API key.

Dynamically add event listener

Here's my workaround:

I created a library with Angular 6. I added a common component commonlib-header which is used like this in an external application.

Note the serviceReference which is the class (injected in the component constructor(public serviceReference: MyService) that uses the commonlib-header) that holds the stringFunctionName method:

<commonlib-header
    [logo]="{ src: 'assets/img/logo.svg', alt: 'Logo', href: '#' }"
    [buttons]="[{ index: 0, innerHtml: 'Button', class: 'btn btn-primary', onClick: [serviceReference, 'stringFunctionName', ['arg1','arg2','arg3']] }]">
    </common-header>

The library component is programmed like this. The dynamic event is added in the onClick(fn: any) method:

export class HeaderComponent implements OnInit {

 _buttons: Array<NavItem> = []

 @Input()
  set buttons(buttons: Array<any>) {
    buttons.forEach(navItem => {
      let _navItem = new NavItem(navItem.href, navItem.innerHtml)

      _navItem.class = navItem.class

      _navItem.onClick = navItem.onClick // this is the array from the component @Input properties above

      this._buttons[navItem.index] = _navItem
    })
  }

  constructor() {}

  ngOnInit() {}

  onClick(fn: any){
    let ref = fn[0]
    let fnName = fn[1]
    let args = fn[2]

    ref[fnName].apply(ref, args)
  }

The reusable header.component.html:

<div class="topbar-right">
  <button *ngFor="let btn of _buttons"
    class="{{ btn.class }}"
    (click)="onClick(btn.onClick)"
    [innerHTML]="btn.innerHtml | keepHtml"></button>
</div>

Changing CSS style from ASP.NET code

VB Version:

Class:

Protected divControl As System.Web.UI.HtmlControls.HtmlGenericControl

OnLoad/Other function:

divControl.Style("height") = "200px"

I've never tried the Add method with the styles. What if the height already exists on the DIV?

How to unzip a file in Powershell?

Here is a simple way using ExtractToDirectory from System.IO.Compression.ZipFile:

Add-Type -AssemblyName System.IO.Compression.FileSystem
function Unzip
{
    param([string]$zipfile, [string]$outpath)

    [System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath)
}

Unzip "C:\a.zip" "C:\a"

Note that if the target folder doesn't exist, ExtractToDirectory will create it. Other caveats:

See also:

Python reshape list to ndim array

You can specify the interpretation order of the axes using the order parameter:

np.reshape(arr, (2, -1), order='F')

Java - No enclosing instance of type Foo is accessible

You've declared the class Thing as a non-static inner class. That means it must be associated with an instance of the Hello class.

In your code, you're trying to create an instance of Thing from a static context. That is what the compiler is complaining about.

There are a few possible solutions. Which solution to use depends on what you want to achieve.

  • Move Thing out of the Hello class.

  • Change Thing to be a static nested class.

    static class Thing
    
  • Create an instance of Hello before creating an instance of Thing.

    public static void main(String[] args)
    {
        Hello h = new Hello();
        Thing thing1 = h.new Thing(); // hope this syntax is right, typing on the fly :P
    }
    

The last solution (a non-static nested class) would be mandatory if any instance of Thing depended on an instance of Hello to be meaningful. For example, if we had:

public class Hello {
    public int enormous;

    public Hello(int n) {
        enormous = n;
    }

    public class Thing {
        public int size;

        public Thing(int m) {
            if (m > enormous)
                size = enormous;
            else
                size = m;
        }
    }
    ...
}

any raw attempt to create an object of class Thing, as in:

Thing t = new Thing(31);

would be problematic, since there wouldn't be an obvious enormous value to test 31 against it. An instance h of the Hello outer class is necessary to provide this h.enormous value:

...
Hello h = new Hello(30);
...
Thing t = h.new Thing(31);
...

Because it doesn't mean a Thing if it doesn't have a Hello.

For more information on nested/inner classes: Nested Classes (The Java Tutorials)

How can I send an HTTP POST request to a server from Excel using VBA?

If you need it to work on both Mac and Windows, you can use QueryTables:

With ActiveSheet.QueryTables.Add(Connection:="URL;http://carbon.brighterplanet.com/flights.txt", Destination:=Range("A2"))
    .PostText = "origin_airport=MSN&destination_airport=ORD"
    .RefreshStyle = xlOverwriteCells
    .SaveData = True
    .Refresh
End With

Notes:

  • Regarding output... I don't know if it's possible to return the results to the same cell that called the VBA function. In the example above, the result is written into A2.
  • Regarding input... If you want the results to refresh when you change certain cells, make sure those cells are the argument to your VBA function.
  • This won't work on Excel for Mac 2008, which doesn't have VBA. Excel for Mac 2011 got VBA back.

For more details, you can see my full summary about "using web services from Excel."

String replace method is not replacing characters

Strings are immutable, meaning their contents cannot change. When you call replace(this,that) you end up with a totally new String. If you want to keep this new copy, you need to assign it to a variable. You can overwrite the old reference (a la sentence = sentence.replace(this,that) or a new reference as seen below:

public class Test{

    public static void main(String[] args) {

        String sentence = "Define, Measure, Analyze, Design and Verify";

        String replaced = sentence.replace("and", "");
        System.out.println(replaced);

    }
}

As an aside, note that I've removed the contains() check, as it is an unnecessary call here. If it didn't contain it, the replace will just fail to make any replacements. You'd only want that contains method if what you're replacing was different than the actual condition you're checking.

Dealing with nginx 400 "The plain HTTP request was sent to HTTPS port" error

Actually you can do this with:

ssl off; 

This solved my problem in using nginxvhosts; now I am able to use both SSL and plain HTTP. Works even with combined ports.

How do I set cell value to Date and apply default Excel date format?

This example is for working with .xlsx file types. This example comes from a .jsp page used to create a .xslx spreadsheet.

import org.apache.poi.xssf.usermodel.*; //import needed

XSSFWorkbook  wb = new XSSFWorkbook ();  // Create workbook
XSSFSheet sheet = wb.createSheet();      // Create spreadsheet in workbook
XSSFRow row = sheet.createRow(rowIndex); // Create the row in the spreadsheet


//1. Create the date cell style
XSSFCreationHelper createHelper = wb.getCreationHelper();
XSSFCellStyle cellStyle         = wb.createCellStyle();
cellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("MMMM dd, yyyy")); 

//2. Apply the Date cell style to a cell

//This example sets the first cell in the row using the date cell style
cell = row.createCell(0);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);

How to create a jQuery function (a new jQuery method or plugin)?

In spite of all the answers you already received, it is worth noting that you do not need to write a plugin to use jQuery in a function. Certainly if it's a simple, one-time function, I believe writing a plugin is overkill. It could be done much more easily by just passing the selector to the function as a parameter. Your code would look something like this:

function myFunction($param) {
   $param.hide();  // or whatever you want to do
   ...
}

myFunction($('#my_div'));

Note that the $ in the variable name $param is not required. It is just a habit of mine to make it easy to remember that that variable contains a jQuery selector. You could just use param as well.

Prevent HTML5 video from being downloaded (right-click saved)?

The

<body oncontextmenu="return false;"> 

no longer works. Chrome and Opera as of June 2018 has a submenu on the timeline to allow straight download, so user doesn't need to right click to download that video. Interestingly Firefox and Edge don't have this ...

How to properly create composite primary keys - MYSQL

the syntax is CONSTRAINT constraint_name PRIMARY KEY(col1,col2,col3) for example ::

CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)

the above example will work if you are writting it while you are creating the table for example ::

CREATE TABLE person (
   P_Id int ,
   ............,
   ............,
   CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
);

to add this constraint to an existing table you need to follow the following syntax

ALTER TABLE table_name ADD CONSTRAINT constraint_name PRIMARY KEY (P_Id,LastName)

Why can't Python import Image from PIL?

If you did all and it didn't work again like mien, do this copy Image.py and ImageTk.py from /usr/lib/python3/dist-packages/PIL on ubuntu and C:/Users/yourComputerName/AppData/Local/Programs/Python/Python36/Lib/PIL on windows to your projects directory and just import them!

Counter exit code 139 when running, but gdb make it through

this error is also caused by null pointer reference. if you are using a pointer who is not initialized then it causes this error.

to check either a pointer is initialized or not you can try something like

Class *pointer = new Class();
if(pointer!=nullptr){
    pointer->myFunction();
}

Should I use Python 32bit or Python 64bit

64 bit version will allow a single process to use more RAM than 32 bit, however you may find that the memory footprint doubles depending on what you are storing in RAM (Integers in particular).

For example if your app requires > 2GB of RAM, so you switch from 32bit to 64bit you may find that your app is now requiring > 4GB of RAM.

Check whether all of your 3rd party modules are available in 64 bit, otherwise it may be easier to stick to 32bit in the meantime

What are all the escape characters?

Java Escape Sequences:

\u{0000-FFFF}  /* Unicode [Basic Multilingual Plane only, see below] hex value 
                  does not handle unicode values higher than 0xFFFF (65535),
                  the high surrogate has to be separate: \uD852\uDF62
                  Four hex characters only (no variable width) */
\b             /* \u0008: backspace (BS) */
\t             /* \u0009: horizontal tab (HT) */
\n             /* \u000a: linefeed (LF) */
\f             /* \u000c: form feed (FF) */
\r             /* \u000d: carriage return (CR) */
\"             /* \u0022: double quote (") */
\'             /* \u0027: single quote (') */
\\             /* \u005c: backslash (\) */
\{0-377}       /* \u0000 to \u00ff: from octal value 
                  1 to 3 octal digits (variable width) */

The Basic Multilingual Plane is the unicode values from 0x0000 - 0xFFFF (0 - 65535). Additional planes can only be specified in Java by multiple characters: the egyptian heiroglyph A054 (laying down dude) is U+1303F / &#77887; and would have to be broken into "\uD80C\uDC3F" (UTF-16) for Java strings. Some other languages support higher planes with "\U0001303F".

Selenium -- How to wait until page is completely loaded

3 answers, which you can combine:

  1. Set implicit wait immediately after creating the web driver instance:

    _ = driver.Manage().Timeouts().ImplicitWait;

    This will try to wait until the page is fully loaded on every page navigation or page reload.

  2. After page navigation, call JavaScript return document.readyState until "complete" is returned. The web driver instance can serve as JavaScript executor. Sample code:

    C#

    new WebDriverWait(driver, MyDefaultTimeout).Until(
    d => ((IJavaScriptExecutor) d).ExecuteScript("return document.readyState").Equals("complete"));
    

    Java

    new WebDriverWait(firefoxDriver, pageLoadTimeout).until(
          webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));
    
  3. Check if the URL matches the pattern you expect.

How to setup virtual environment for Python in VS Code?

The question is how to create a new virtual environment in VSCode, that is why telling the following Anaconda solution might not the needed answer to the question. It is just relevant for Anaconda users.

Just create a venv using conda, see here. Afterwards open VSCode and left-click on the VSCode interpreter shown in VSCode at the bottom left:

vscode interpreter info

Choose a virtual environment that pops up in a dropdown of the settings window, and you are done. Mind the answer of @RamiMa.

Hibernate: How to set NULL query-parameter value with HQL?

Here is the solution I found on Hibernate 4.1.9. I had to pass a parameter to my query that can have value NULL sometimes. So I passed the using:

setParameter("orderItemId", orderItemId, new LongType())

After that, I use the following where clause in my query:

where ((:orderItemId is null) OR (orderItem.id != :orderItemId))

As you can see, I am using the Query.setParameter(String, Object, Type) method, where I couldn't use the Hibernate.LONG that I found in the documentation (probably that was on older versions). For a full set of options of type parameter, check the list of implementation class of org.hibernate.type.Type interface.

Hope this helps!

How to post JSON to PHP with curl

You need to set a few extra flags so that curl sends the data as JSON.

command

$ curl -H "Content-Type: application/json" \
       -X POST \
       -d '{"JSON": "HERE"}' \
       http://localhost:3000/api/url

flags

  • -H: custom header, next argument is expected to be header
  • -X: custom HTTP verb, next argument is expected to be verb
  • -d: sends the next argument as data in an HTTP POST request

resources

How to center icon and text in a android button with width set to "fill parent"

<style name="captionOnly">
    <item name="android:background">@null</item>
    <item name="android:clickable">false</item>
    <item name="android:focusable">false</item>
    <item name="android:minHeight">0dp</item>
    <item name="android:minWidth">0dp</item>
</style>

<FrameLayout
   style="?android:attr/buttonStyle"
   android:layout_width="match_parent"
   android:layout_height="wrap_content" >

    <Button
       style="@style/captionOnly"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_gravity="center"
       android:drawableLeft="@android:drawable/ic_delete"
       android:gravity="center"
       android:text="Button Challenge" />
</FrameLayout>

Put the FrameLayout in LinearLayout and set orientation to Horizontal.

How to set the timeout for a TcpClient?

The answers above don't cover how to cleanly deal with a connection that has timed out. Calling TcpClient.EndConnect, closing a connection that succeeds but after the timeout, and disposing of the TcpClient.

It may be overkill but this works for me.

    private class State
    {
        public TcpClient Client { get; set; }
        public bool Success { get; set; }
    }

    public TcpClient Connect(string hostName, int port, int timeout)
    {
        var client = new TcpClient();

        //when the connection completes before the timeout it will cause a race
        //we want EndConnect to always treat the connection as successful if it wins
        var state = new State { Client = client, Success = true };

        IAsyncResult ar = client.BeginConnect(hostName, port, EndConnect, state);
        state.Success = ar.AsyncWaitHandle.WaitOne(timeout, false);

        if (!state.Success || !client.Connected)
            throw new Exception("Failed to connect.");

        return client;
    }

    void EndConnect(IAsyncResult ar)
    {
        var state = (State)ar.AsyncState;
        TcpClient client = state.Client;

        try
        {
            client.EndConnect(ar);
        }
        catch { }

        if (client.Connected && state.Success)
            return;

        client.Close();
    }

What are MVP and MVC and what is the difference?

They each addresses different problems and can even be combined together to have something like below

The Combined Pattern

There is also a complete comparison of MVC, MVP and MVVM here

Scripting SQL Server permissions

You can get SQL Server Management Studio to do it for you:

  • Right click the database you want to export permissions for
  • Select 'Tasks' then 'Generate Scripts...'
  • Confirm the database you're scripting
  • Set the following scripting options:
    • Script Create: FALSE
    • Script Object-Level Permissions: TRUE
  • Select the object types whose permission you want to script
  • Select the objects whose permission you want to script
  • Select where you want the script produced

This will produce a script to set permissions for all selected objects but suppresses the object scripts themselves.

This is based on the dialog for MS SQL 2008 with all other scripting options unchanged from install defaults.

How can I find last row that contains data in a specific column?

Function LastRow(rng As Range) As Long
    Dim iRowN As Long
    Dim iRowI As Long
    Dim iColN As Integer
    Dim iColI As Integer
    iRowN = 0
    iColN = rng.Columns.count
    For iColI = 1 To iColN
        iRowI = rng.Columns(iColI).Offset(65536 - rng.Row, 0).End(xlUp).Row
        If iRowI > iRowN Then iRowN = iRowI
    Next
    LastRow = iRowN
End Function 

Get data from fs.readFile

The following is function would work for async wrap or promise then chains

const readFileAsync =  async (path) => fs.readFileSync(path, 'utf8');

Convert a python dict to a string and back

If your dictionary isn't too big maybe str + eval can do the work:

dict1 = {'one':1, 'two':2, 'three': {'three.1': 3.1, 'three.2': 3.2 }}
str1 = str(dict1)

dict2 = eval(str1)

print dict1==dict2

You can use ast.literal_eval instead of eval for additional security if the source is untrusted.

How do I select an element in jQuery by using a variable for the ID?

I don't know much about jQuery, but try this:

row_id = "#5";
row = $("body").find(row_id);

Edit: Of course, if the variable is a number, you have to add "#" to the front:

row_id = 5
row = $("body").find("#"+row_id);

List of tuples to dictionary

Just call dict() on the list of tuples directly

>>> my_list = [('a', 1), ('b', 2)]
>>> dict(my_list)
{'a': 1, 'b': 2}

How to get single value from this multi-dimensional PHP array

Use array_shift function

$myarray = array_shift($myarray);

This will move array elements one level up and you can access any array element without using [0] key

echo $myarray['email'];  

will show [email protected]

Javascript to convert UTC to local time

The solutions above are right but might crash in FireFox and Safari! and that's what webility.js is trying to solve. Check the toUTC function, it works on most of the main browers and it returns the time in ISO format

How to commit changes to a new branch

If you haven't committed changes

If your changes are compatible with the other branch

This is the case from the question because the OP wants to commit to a new branch and also applies if your changes are compatible with the target branch without triggering an overwrite.

As in the accepted answer by John Brodie, you can simply checkout the new branch and commit the work:

git checkout -b branch_name
git add <files>
git commit -m "message"

If your changes are incompatible with the other branch

If you get the error:

error: Your local changes to the following files would be overwritten by checkout:
...
Please commit your changes or stash them before you switch branches

Then you can stash your work, create a new branch, then pop your stash changes, and resolve the conflicts:

git stash
git checkout -b branch_name
git stash pop

It will be as if you had made those changes after creating the new branch. Then you can commit as usual:

git add <files>
git commit -m "message"

If you have committed changes

If you want to keep the commits in the original branch

See the answer by Carl Norum with cherry-picking, which is the right tool in this case:

git checkout <target name>
git cherry-pick <original branch>

If you don't want to keep the commits in the original branch

See the answer by joeytwiddle on this potential duplicate. Follow any of the above steps as appropriate, then roll back the original branch:

git branch -f <original branch> <earlier commit id>

If you have pushed your changes to a shared remote like GitHub, you should not attempt this roll-back unless you know what you are doing.

Remove numbers from string sql server

This one works for me

CREATE Function [dbo].[RemoveNumericCharacters](@Temp VarChar(1000))
Returns VarChar(1000)
AS
Begin

    Declare @NumRange as varchar(50) = '%[0-9]%'
    While PatIndex(@NumRange, @Temp) > 0
        Set @Temp = Stuff(@Temp, PatIndex(@NumRange, @Temp), 1, '')

    Return @Temp
End

and you can use it like so

SELECT dbo.[RemoveNumericCharacters](Name) FROM TARGET_TABLE

Regular expression to return text between parenthesis

import re

fancy = u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'

print re.compile( "\((.*)\)" ).search( fancy ).group( 1 )

How to specify table's height such that a vertical scroll bar appears?

to set the height of table, you need to first set css property "display: block" then you can add "width/height" properties. I find this Mozilla Article a very good resource to learn how to style tables : Link

How do I enable NuGet Package Restore in Visual Studio?

I am facing the same problem. I am trying to add a MVC project which was created on Visual Studio 2015 to a solution that I made on Visual Studio 2019.

There are already existing projects on Visual Studio 2019, so adding this existing project which I created on VS 2015 triggers this same error. I've tried all the answers here but it doesn't fixes the problem.

What I did is just put the .nuget folder on the solution folder. Originally the hierarchy of the folder is this:

Solution Folder (VS 2019)
  -> MVC 1 Project
  -> MVC 2 Project
  -> MVC 3 Project (Project that I am adding)
         -> .nuget folder (It contains a .nuget folder)

So the issue was fixed when I moved the .nuget folder on the solution folder itself:

    Solution Folder (VS 2019)
  -> MVC 1 Project
  -> MVC 2 Project
  -> MVC 3 Project (Project that I am adding)
  -> .nuget folder (It contains a .nuget folder)

Check folder size in Bash

If it helps, You can also create an alias in your .bashrc or .bash_profile.

function dsize()
{
    dir=$(pwd)
    if [ "$1" != "" ]; then
            dir=$1
    fi
    echo $(du -hs $dir)
}

This prints the size of the current directory or the directory you have passed as an argument.

How do I do a case-insensitive string comparison?

Assuming ASCII strings:

string1 = 'Hello'
string2 = 'hello'

if string1.lower() == string2.lower():
    print("The strings are the same (case insensitive)")
else:
    print("The strings are NOT the same (case insensitive)")

C++: Converting Hexadecimal to Decimal

I use this:

template <typename T>
bool fromHex(const std::string& hexValue, T& result)
{
    std::stringstream ss;
    ss << std::hex << hexValue;
    ss >> result;

    return !ss.fail();
}

How to list the certificates stored in a PKCS12 keystore with keytool?

You can also use openssl to accomplish the same thing:

$ openssl pkcs12 -nokeys -info \
    -in </path/to/file.pfx> \
    -passin pass:<pfx's password>

MAC Iteration 2048
MAC verified OK
PKCS7 Encrypted data: pbeWithSHA1And40BitRC2-CBC, Iteration 2048
Certificate bag
Bag Attributes
    localKeyID: XX XX XX XX XX XX XX XX XX XX XX XX XX 48 54 A0 47 88 1D 90
    friendlyName: jedis-server
subject=/C=US/ST=NC/L=Raleigh/O=XXX Security/OU=XXX/CN=something1
issuer=/C=US/ST=NC/L=Raleigh/O=XXX Security/OU=XXXX/CN=something1
-----BEGIN CERTIFICATE-----
...
...
...
-----END CERTIFICATE-----
PKCS7 Data
Shrouded Keybag: pbeWithSHA1And3-KeyTripleDES-CBC, Iteration 2048

How to delete all files and folders in a directory?

This version does not use recursive calls, and solves the readonly problem.

public static void EmptyDirectory(string directory)
{
    // First delete all the files, making sure they are not readonly
    var stackA = new Stack<DirectoryInfo>();
    stackA.Push(new DirectoryInfo(directory));

    var stackB = new Stack<DirectoryInfo>();
    while (stackA.Any())
    {
        var dir = stackA.Pop();
        foreach (var file in dir.GetFiles())
        {
            file.IsReadOnly = false;
            file.Delete();
        }
        foreach (var subDir in dir.GetDirectories())
        {
            stackA.Push(subDir);
            stackB.Push(subDir);
        }
    }

    // Then delete the sub directories depth first
    while (stackB.Any())
    {
        stackB.Pop().Delete();
    }
}

How to use \n new line in VB msgbox() ...?

  • for VB: vbCrLf or vbNewLine
  • for VB.NET: Environment.NewLine or vbCrLf or Constants.vbCrLf

Info on VB.NET new line: http://msdn.microsoft.com/en-us/library/system.environment.newline.aspx

The info for Environment.NewLine came from Cody Gray and J Vermeire

How to run wget inside Ubuntu Docker image?

If you're running ubuntu container directly without a local Dockerfile you can ssh into the container and enable root control by entering su then apt-get install -y wget

Jquery bind double click and single click separately

If you don't want to create separate variables to manage the state, you can check this answer https://stackoverflow.com/a/65620562/4437468

Change the value in app.config file dynamically

 XmlReaderSettings _configsettings = new XmlReaderSettings();
 _configsettings.IgnoreComments = true;

 XmlReader _configreader = XmlReader.Create(ConfigFilePath, _configsettings);
 XmlDocument doc_config = new XmlDocument();
 doc_config.Load(_configreader);
 _configreader.Close();

 foreach (XmlNode RootName in doc_config.DocumentElement.ChildNodes)
 {
     if (RootName.LocalName == "appSettings")
     {
         if (RootName.HasChildNodes)
         {
             foreach (XmlNode _child in RootName.ChildNodes)
             {
                 if (_child.Attributes["key"].Value == "HostName")
                 {
                     if (_child.Attributes["value"].Value == "false")
                         _child.Attributes["value"].Value = "true";
                 }
             }
         }
     }
 }
 doc_config.Save(ConfigFilePath);

How to set the LDFLAGS in CMakeLists.txt?

It depends a bit on what you want:

A) If you want to specify which libraries to link to, you can use find_library to find libs and then use link_directories and target_link_libraries to.

Of course, it is often worth the effort to write a good find_package script, which nicely adds "imported" libraries with add_library( YourLib IMPORTED ) with correct locations, and platform/build specific pre- and suffixes. You can then simply refer to 'YourLib' and use target_link_libraries.

B) If you wish to specify particular linker-flags, e.g. '-mthreads' or '-Wl,--export-all-symbols' with MinGW-GCC, you can use CMAKE_EXE_LINKER_FLAGS. There are also two similar but undocumented flags for modules, shared or static libraries:

CMAKE_MODULE_LINKER_FLAGS
CMAKE_SHARED_LINKER_FLAGS
CMAKE_STATIC_LINKER_FLAGS

Access non-numeric Object properties by index?

Get the array of keys, reverse it, then run your loop

  var keys = Object.keys( obj ).reverse();
  for(var i = 0; i < keys.length; i++){
    var key = keys[i];
    var value = obj[key];
    //do stuff backwards
  }

Wpf control size to content?

For most controls, you set its height and width to Auto in the XAML, and it will size to fit its content.

In code, you set the width/height to double.NaN. For details, see FrameworkElement.Width, particularly the "remarks" section.

Correct way to initialize empty slice

They are equivalent. See this code:

mySlice1 := make([]int, 0)
mySlice2 := []int{}
fmt.Println("mySlice1", cap(mySlice1))
fmt.Println("mySlice2", cap(mySlice2))

Output:

mySlice1 0
mySlice2 0

Both slices have 0 capacity which implies both slices have 0 length (cannot be greater than the capacity) which implies both slices have no elements. This means the 2 slices are identical in every aspect.

See similar questions:

What is the point of having nil slice and empty slice in golang?

nil slices vs non-nil slices vs empty slices in Go language

sprintf like functionality in Python

You can use string formatting:

>>> a=42
>>> b="bar"
>>> "The number is %d and the word is %s" % (a,b)
'The number is 42 and the word is bar'

But this is removed in Python 3, you should use "str.format()":

>>> a=42
>>> b="bar"
>>> "The number is {0} and the word is {1}".format(a,b)
'The number is 42 and the word is bar'

How to connect to MongoDB in Windows?

Steps to start a certain local MongoDB instance and to connect to in from NodeJS app:

  1. Create mongod.cfg for a new database using the path C:\Program Files\MongoDB\Server\4.0\mongod.cfg with the content

    systemLog:
      destination: file
      path: C:\Program Files\MongoDB\Server\4.0\log\mongod.log
    storage:
      dbPath: C:\Program Files\MongoDB\Server\4.0\data\db
    
  2. Install mongoDB database by running

    mongod.exe --config "C:\Program Files\MongoDB\Server\4.0\mongod.cfg" --install

  3. Run a particular mongoDB database

    mongod.exe --config "C:\Program Files\MongoDB\Server\4.0\mongod.cfg"

  4. Run mongoDB service

    mongo 127.0.0.1:27017/db
    

    and !see mongoDB actual connection string to coonect to the service from NodeJS app

    MongoDB shell version v4.0.9
    connecting to: mongodb://127.0.0.1:27017/db?gssapiServiceName=mongodb
    Implicit session: session { "id" : UUID("c7ed5ab4-c64e-4bb8-aad0-ab4736406c03") }
    MongoDB server version: 4.0.9
    Server has startup warnings:
    ...
    

What does href expression <a href="javascript:;"></a> do?

It is a way of making a link do absolutely nothing when clicked (unless Javascript events are bound to it).

It is a way of running Javascript instead of following a link:

<a href="Javascript: doStuff();">link</a>

When there isn't actually javascript to run (like your example) it does nothing.

How can one pull the (private) data of one's own Android app?

Newer versions of Android Studio include the Device File Explorer which I've found to be a handy GUI method of downloading files from my development Nexus 7.

You Must make sure you have enabled USB Debugging on the device

  1. Click View > Tool Windows > Device File Explorer or click the Device File Explorer button in the tool window bar to open the Device File Explorer.
  2. Select a device from the drop down list.
  3. Interact with the device content in the file explorer window. Right-click on a file or directory to create a new file or directory, save the selected file or directory to your machine, upload, delete, or synchronize. Double-click a file to open it in Android Studio.

    Android Studio saves files you open this way in a temporary directory outside of your project. If you make modifications to a file you opened using the Device File Explorer, and would like to save your changes back to the device, you must manually upload the modified version of the file to the device.

file explorer

Full Documentation

Determine project root from a running node.js application

I know this one is already too late. But we can fetch root URL by two methods

1st method

var path = require('path');
path.dirname(require.main.filename);

2nd method

var path = require('path');
path.dirname(process.mainModule.filename);

Reference Link:- https://gist.github.com/geekiam/e2e3e0325abd9023d3a3

Python: 'ModuleNotFoundError' when trying to import module from imported package

FIRST, if you want to be able to access man1.py from man1test.py AND manModules.py from man1.py, you need to properly setup your files as packages and modules.

Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A.

...

When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

You need to set it up to something like this:

man
|- __init__.py
|- Mans
   |- __init__.py
   |- man1.py
|- MansTest
   |- __init.__.py
   |- SoftLib
      |- Soft
         |- __init__.py
         |- SoftWork
            |- __init__.py
            |- manModules.py
      |- Unittests
         |- __init__.py
         |- man1test.py

SECOND, for the "ModuleNotFoundError: No module named 'Soft'" error caused by from ...Mans import man1 in man1test.py, the documented solution to that is to add man1.py to sys.path since Mans is outside the MansTest package. See The Module Search Path from the Python documentation. But if you don't want to modify sys.path directly, you can also modify PYTHONPATH:

sys.path is initialized from these locations:

  • The directory containing the input script (or the current directory when no file is specified).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • The installation-dependent default.

THIRD, for from ...MansTest.SoftLib import Soft which you said "was to facilitate the aforementioned import statement in man1.py", that's now how imports work. If you want to import Soft.SoftLib in man1.py, you have to setup man1.py to find Soft.SoftLib and import it there directly.

With that said, here's how I got it to work.

man1.py:

from Soft.SoftWork.manModules import *
# no change to import statement but need to add Soft to PYTHONPATH

def foo():
    print("called foo in man1.py")
    print("foo call module1 from manModules: " + module1())

man1test.py

# no need for "from ...MansTest.SoftLib import Soft" to facilitate importing..
from ...Mans import man1

man1.foo()

manModules.py

def module1():
    return "module1 in manModules"

Terminal output:

$ python3 -m man.MansTest.Unittests.man1test
Traceback (most recent call last):
  ...
    from ...Mans import man1
  File "/temp/man/Mans/man1.py", line 2, in <module>
    from Soft.SoftWork.manModules import *
ModuleNotFoundError: No module named 'Soft'

$ PYTHONPATH=$PYTHONPATH:/temp/man/MansTest/SoftLib
$ export PYTHONPATH
$ echo $PYTHONPATH
:/temp/man/MansTest/SoftLib
$ python3 -m man.MansTest.Unittests.man1test
called foo in man1.py
foo called module1 from manModules: module1 in manModules 

As a suggestion, maybe re-think the purpose of those SoftLib files. Is it some sort of "bridge" between man1.py and man1test.py? The way your files are setup right now, I don't think it's going to work as you expect it to be. Also, it's a bit confusing for the code-under-test (man1.py) to be importing stuff from under the test folder (MansTest).

What is causing the error `string.split is not a function`?

run this

// you'll see that it prints Object
console.log(typeof document.location);

you want document.location.toString() or document.location.href