Programs & Examples On #Quine

A program that generates a copy of its own source text as its complete output (generally of interest in theory only).

Select random lines from a file

# Function to sample N lines randomly from a file
# Parameter $1: Name of the original file
# Parameter $2: N lines to be sampled 
rand_line_sampler() {
    N_t=$(awk '{print $1}' $1 | wc -l) # Number of total lines

    N_t_m_d=$(( $N_t - $2 - 1 )) # Number oftotal lines minus desired number of lines

    N_d_m_1=$(( $2 - 1)) # Number of desired lines minus 1

    # vector to have the 0 (fail) with size of N_t_m_d 
    echo '0' > vector_0.temp
    for i in $(seq 1 1 $N_t_m_d); do
            echo "0" >> vector_0.temp
    done

    # vector to have the 1 (success) with size of desired number of lines
    echo '1' > vector_1.temp
    for i in $(seq 1 1 $N_d_m_1); do
            echo "1" >> vector_1.temp
    done

    cat vector_1.temp vector_0.temp | shuf > rand_vector.temp

    paste -d" " rand_vector.temp $1 |
    awk '$1 != 0 {$1=""; print}' |
    sed 's/^ *//' > sampled_file.txt # file with the sampled lines

    rm vector_0.temp vector_1.temp rand_vector.temp
}

rand_line_sampler "parameter_1" "parameter_2"

Rotate camera in Three.js with mouse

take a look at the following examples

http://threejs.org/examples/#misc_controls_orbit

http://threejs.org/examples/#misc_controls_trackball

there are other examples for different mouse controls, but both of these allow the camera to rotate around a point and zoom in and out with the mouse wheel, the main difference is OrbitControls enforces the camera up direction, and TrackballControls allows the camera to rotate upside-down.

All you have to do is include the controls in your html document

<script src="js/OrbitControls.js"></script>

and include this line in your source

controls = new THREE.OrbitControls( camera, renderer.domElement );

Using dig to search for SPF records

I believe that I found the correct answer through this dig How To. I was able to look up the SPF records on a specific DNS, by using the following query:

dig @ns1.nameserver1.com domain.com txt

Random strings in Python

You can build random ascii characters like:

import random
print chr(random.randint(0,255))

And then build up a longer string like:

len = 50
print ''.join( [chr(random.randint(0,255)) for i in xrange(0,len)] )

How to correctly use the ASP.NET FileUpload control

I have noticed that when intellisence doesn't work for an object there is usually an error somewhere in the class above line you are working on.

The other option is that you didn't instantiated the FileUpload object as an instance variable. make sure the code:

FileUpload fileUpload = new FileUpload();

is not inside a function in your code behind.

Trying to use Spring Boot REST to Read JSON String from POST

To receive arbitrary Json in Spring-Boot, you can simply use Jackson's JsonNode. The appropriate converter is automatically configured.

    @PostMapping(value="/process")
    public void process(@RequestBody com.fasterxml.jackson.databind.JsonNode payload) {
        System.out.println(payload);
    }

How to replace list item in best way

Use FindIndex and lambda to find and replace your values:

int j = listofelements.FindIndex(i => i.Contains(valueFieldValue.ToString())); //Finds the item index

lstString[j] = lstString[j].Replace(valueFieldValue.ToString(), value.ToString()); //Replaces the item by new value

Show week number with Javascript?

Martin Schillinger's version seems to be the strictly correct one.

Since I knew I only needed it to work correctly on business week days, I went with this simpler form, based on something I found online, don't remember where:

ISOWeekday = (0 == InputDate.getDay()) ? 7 : InputDate.getDay();
ISOCalendarWeek = Math.floor( ( ((InputDate.getTime() - (new Date(InputDate.getFullYear(),0,1)).getTime()) / 86400000) - ISOWeekday + 10) / 7 );

It fails in early January on days that belong to the previous year's last week (it produces CW = 0 in those cases) but is correct for everything else.

"Port 4200 is already in use" when running the ng serve command

It says already we are running the services with port no 4200 please use another port instead of 4200. Below command is to solve the problem

ng serve --port 4300

C++ Double Address Operator? (&&)

As other answers have mentioned, the && token in this context is new to C++0x (the next C++ standard) and represent an "rvalue reference".

Rvalue references are one of the more important new things in the upcoming standard; they enable support for 'move' semantics on objects and permit perfect forwarding of function calls.

It's a rather complex topic - one of the best introductions (that's not merely cursory) is an article by Stephan T. Lavavej, "Rvalue References: C++0x Features in VC10, Part 2"

Note that the article is still quite heavy reading, but well worthwhile. And even though it's on a Microsoft VC++ Blog, all (or nearly all) the information is applicable to any C++0x compiler.

CSS values using HTML5 data attribute

As of today, you can read some values from HTML5 data attributes in CSS3 declarations. In CaioToOn's fiddle the CSS code can use the data properties for setting the content.

Unfortunately it is not working for the width and height (tested in Google Chrome 35, Mozilla Firefox 30 & Internet Explorer 11).

But there is a CSS3 attr() Polyfill from Fabrice Weinberg which provides support for data-width and data-height. You can find the GitHub repo to it here: cssattr.js.

Bootstrap 3 2-column form layout

You can use the bootstrap grid system. as Yoann said


 <div class="container">
    <div class="row">
        <form role="form">
           <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputEmail1">Email address</label>
                        <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
                    </div>
                    <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputEmail1">Name</label>
                        <input type="text" class="form-control" id="exampleInputEmail1" placeholder="Enter Name">
                    </div>
                    <div class="clearfix"></div>
                    <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputPassword1">Password</label>
                        <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
                    </div>
                    <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputPassword1">Confirm Password</label>
                        <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Confirm Password">
                    </div>
          </form>
         <div class="clearfix">
      </div>
    </div>
</div>

Can I use Twitter Bootstrap and jQuery UI at the same time?

In my limited experience I am coming across issues as well. It appears that JQuery elements (such as buttons) can be styled using bootstrap CSS. However, I am experiencing issues having created a JQuery UI tab and wanting to lock a bootstrap only input (using the input-append class) to the bottom of each tab, only the first sits correctly. So, JQuery tabs + Bootstrap buttons = probably not.

How can I read large text files in Python, line by line, without loading it into memory?

Heres the code for loading text files of any size without causing memory issues. It support gigabytes sized files

https://gist.github.com/iyvinjose/e6c1cb2821abd5f01fd1b9065cbc759d

download the file data_loading_utils.py and import it into your code

usage

import data_loading_utils.py.py
file_name = 'file_name.ext'
CHUNK_SIZE = 1000000


def process_lines(data, eof, file_name):

    # check if end of file reached
    if not eof:
         # process data, data is one single line of the file

    else:
         # end of file reached

data_loading_utils.read_lines_from_file_as_data_chunks(file_name, chunk_size=CHUNK_SIZE, callback=self.process_lines)

process_lines method is the callback function. It will be called for all the lines, with parameter data representing one single line of the file at a time.

You can configure the variable CHUNK_SIZE depending on your machine hardware configurations.

Java decimal formatting using String.format?

You want java.text.DecimalFormat

OR is not supported with CASE Statement in SQL Server

select id,phno,case gender
when 'G' then 'M'
when 'L' then 'F'
else
'No gender'
end
as gender 
from contacts

jQuery count child elements

pure js

selected.children[0].children.length;

_x000D_
_x000D_
let num = selected.children[0].children.length;_x000D_
_x000D_
console.log(num);
_x000D_
<div id="selected">_x000D_
  <ul>_x000D_
    <li>29</li>_x000D_
    <li>16</li>_x000D_
    <li>5</li>_x000D_
    <li>8</li>_x000D_
    <li>10</li>_x000D_
    <li>7</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Run chrome in fullscreen mode on Windows

You can also add --disable-session-crashed-bubble to eliminate the errors that come up after a crash or improper shutdown.

How to convert JSONObjects to JSONArray?

Even shorter and with json-functions:

JSONObject songsObject = json.getJSONObject("songs");
JSONArray songsArray = songsObject.toJSONArray(songsObject.names());

How do I generate sourcemaps when using babel and webpack?

If optimizing for dev + production, you could try something like this in your config:

const dev = process.env.NODE_ENV !== 'production'

// in config

{
  devtool: dev ? 'eval-cheap-module-source-map' : 'source-map',
}

From the docs:

  • devtool: "eval-cheap-module-source-map" offers SourceMaps that only maps lines (no column mappings) and are much faster
  • devtool: "source-map" cannot cache SourceMaps for modules and need to regenerate complete SourceMap for the chunk. It’s something for production.

I am using webpack 2.1.0-beta.19

Fastest way to remove first char in a String

I would just use

string data= "/temp string";
data = data.substring(1)

Output: temp string

That always works for me.

get client time zone from browser

No. There is no single reliable way and there will never be. Did you really think you could trust the client?

Php - testing if a radio button is selected and get the value

my form:

<form method="post" action="radio.php">
   select your gender: 
    <input type="radio" name="radioGender" value="female">
    <input type="radio" name="radioGender" value="male">
    <input type="submit" name="btnSubmit" value="submit">
</form>

my php:

   <?php
      if (isset($_POST["btnSubmit"])) {
        if (isset($_POST["radioGender"])) {
        $answer = $_POST['radioGender'];
           if ($answer == "female") {
               echo "female";
           } else {
               echo "male";
           }    
        }else{
            echo "please select your gender";
             }
      }
  ?>

What's the difference between size_t and int in C++?

From the friendly Wikipedia:

The stdlib.h and stddef.h header files define a datatype called size_t which is used to represent the size of an object. Library functions that take sizes expect them to be of type size_t, and the sizeof operator evaluates to size_t.

The actual type of size_t is platform-dependent; a common mistake is to assume size_t is the same as unsigned int, which can lead to programming errors, particularly as 64-bit architectures become more prevalent.

Also, check Why size_t matters

Correct use of flush() in JPA/Hibernate

Can em.flush() cause any harm when using it within a transaction?

Yes, it may hold locks in the database for a longer duration than necessary.

Generally, When using JPA you delegates the transaction management to the container (a.k.a CMT - using @Transactional annotation on business methods) which means that a transaction is automatically started when entering the method and commited / rolled back at the end. If you let the EntityManager handle the database synchronization, sql statements execution will be only triggered just before the commit, leading to short lived locks in database. Otherwise your manually flushed write operations may retain locks between the manual flush and the automatic commit which can be long according to remaining method execution time.

Notes that some operation automatically triggers a flush : executing a native query against the same session (EM state must be flushed to be reachable by the SQL query), inserting entities using native generated id (generated by the database, so the insert statement must be triggered thus the EM is able to retrieve the generated id and properly manage relationships)

How do I automatically resize an image for a mobile site?

Your css with doesn't have any effect as the outer element doesn't have a width defined (and body is missing as well).

A different approach is to deliver already scaled images. http://www.sencha.com/products/io/ for example delivers the image already scaled down depending on the viewing device.

Check, using jQuery, if an element is 'display:none' or block on click

another shortcut i personally prefer more than .is() or .length:

if($('.myclass:visible')[0]){
   // is visible
}else {
   // is hidden
}

How to redirect the output of the time command to a file in Linux?

If you are using GNU time instead of the bash built-in, try

time -o outfile command

(Note: GNU time formats a little differently than the bash built-in).

mysql extract year from date format

try this code:

SELECT DATE_FORMAT(FROM_UNIXTIME(field), '%Y') FROM table

right align an image using CSS HTML

Float the image right, which will at first cause your text to wrap around it.

Then whatever the very next element is, set it to { clear: right; } and everything will stop wrapping around the image.

Pagination using MySQL LIMIT, OFFSET

First off, don't have a separate server script for each page, that is just madness. Most applications implement pagination via use of a pagination parameter in the URL. Something like:

http://yoursite.com/itempage.php?page=2

You can access the requested page number via $_GET['page'].

This makes your SQL formulation really easy:

// determine page number from $_GET
$page = 1;
if(!empty($_GET['page'])) {
    $page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
    if(false === $page) {
        $page = 1;
    }
}

// set the number of items to display per page
$items_per_page = 4;

// build query
$offset = ($page - 1) * $items_per_page;
$sql = "SELECT * FROM menuitem LIMIT " . $offset . "," . $items_per_page;

So for example if input here was page=2, with 4 rows per page, your query would be"

SELECT * FROM menuitem LIMIT 4,4

So that is the basic problem of pagination. Now, you have the added requirement that you want to understand the total number of pages (so that you can determine if "NEXT PAGE" should be shown or if you wanted to allow direct access to page X via a link).

In order to do this, you must understand the number of rows in the table.

You can simply do this with a DB call before trying to return your actual limited record set (I say BEFORE since you obviously want to validate that the requested page exists).

This is actually quite simple:

$sql = "SELECT your_primary_key_field FROM menuitem";
$result = mysqli_query($con, $sql);
if(false === $result) {
   throw new Exception('Query failed with: ' . mysqli_error());
} else {
   $row_count = mysqli_num_rows($result);
   // free the result set as you don't need it anymore
   mysqli_free_result($result);
}

$page_count = 0;
if (0 === $row_count) {  
    // maybe show some error since there is nothing in your table
} else {
   // determine page_count
   $page_count = (int)ceil($row_count / $items_per_page);
   // double check that request page is in range
   if($page > $page_count) {
        // error to user, maybe set page to 1
        $page = 1;
   }
}

// make your LIMIT query here as shown above


// later when outputting page, you can simply work with $page and $page_count to output links
// for example
for ($i = 1; $i <= $page_count; $i++) {
   if ($i === $page) { // this is current page
       echo 'Page ' . $i . '<br>';
   } else { // show link to other page   
       echo '<a href="/menuitem.php?page=' . $i . '">Page ' . $i . '</a><br>';
   }
}

error: use of deleted function

In the current C++0x standard you can explicitly disable default constructors with the delete syntax, e.g.

MyClass() = delete;

Gcc 4.6 is the first version to support this syntax, so maybe that is the problem...

Where is web.xml in Eclipse Dynamic Web Project

If your deployment descriptor tab is disabled, then click on update libraries it will also do your work. It will create. Xml file in Web content

How can I create tests in Android Studio?

As of now (studio 0.61) maintaining proper project structure is enough. No need to create separate test project as in eclipse (see below).

Tests structure

Why is there no String.Empty in Java?

Use org.apache.commons.lang.StringUtils.EMPTY

How do you run a crontab in Cygwin on Windows?

Applied the instructions from this answer and it worked Just to point out a more copy paste like answer ( because cygwin installation procedure is kind of anti-copy-paste wise implemented )
Click WinLogo button , type cmd.exe , right click it , choose "Start As Administrator". In cmd prompt:

 cd <directory_where_i_forgot_the setup-x86_64.exe> cygwin installer:
 set package_name=cygrunsrv cron
 setup-x86_64.exe -n -q -s http://cygwin.mirror.constant.com -P %package_name%

Ensure the installer does not throw any errors in the prompt ... If it has - you probably have some cygwin binaries running or you are not an Windows admin, or some freaky bug ...

Now in cmd promt:

 C:\cygwin64\bin\cygrunsrv.exe -I cron -p /usr/sbin/cron -a -D   

or whatever full file path you might have to the cygrunsrv.exe and start the cron as windows service in the cmd prompt

 net start cron

Now in bash terminal run crontab -e

set up you cron entry an example bellow:

        #sync my gdrive each 10th minute
    */10 * * * * /home/Yordan/sync_gdrive.sh

    # * * * * * command to be executed
    # - - - - -
    # | | | | |
    # | | | | +- - - - day of week (0 - 6) (Sunday=0)
    # | | | +- - - - - month (1 - 12)
    # | | +- - - - - - day of month (1 - 31)
    # | +- - - - - - - hour (0 - 23)
    # +--------------- minute

Read a text file using Node.js?

You can use readstream and pipe to read the file line by line without read all the file into memory one time.

var fs = require('fs'),
    es = require('event-stream'),
    os = require('os');

var s = fs.createReadStream(path)
    .pipe(es.split())
    .pipe(es.mapSync(function(line) {
        //pause the readstream
        s.pause();
        console.log("line:", line);
        s.resume();
    })
    .on('error', function(err) {
        console.log('Error:', err);
    })
    .on('end', function() {
        console.log('Finish reading.');
    })
);

Java 8 Streams FlatMap method example

Extract unique words sorted ASC from a list of phrases:

List<String> phrases = Arrays.asList(
        "sporadic perjury",
        "confounded skimming",
        "incumbent jailer",
        "confounded jailer");

List<String> uniqueWords = phrases
        .stream()
        .flatMap(phrase -> Stream.of(phrase.split("\\s+")))
        .distinct()
        .sorted()
        .collect(Collectors.toList());
System.out.println("Unique words: " + uniqueWords);

... and the output:

Unique words: [confounded, incumbent, jailer, perjury, skimming, sporadic]

How to make connection to Postgres via Node.js

Connection String

The connection string is a string of the form:

postgres://[user[:password]@][host][:port][/dbname]

(where the parts in [...] can optionally be included or excluded)

Some examples of valid connection strings include:

postgres://localhost
postgres://localhost:5432
postgres://localhost/mydb
postgres://user@localhost
postgres://user:secret_password@localhost

If you've just started a database on your local machine, the connection string postgres://localhost will typically work, as that uses the default port number, username, and no password. If the database was started with a specific account, you might find you need to use postgres://pg@localhost or postgres://postgres@localhost

If none of these work, and you have installed docker, another option is to run npx @databases/pg-test start. This will start a postgres server in a docker container and then print out the connection string for you. The pg-test databases are only intended for testing though, so you will loose all your data if your computer restarts.

Connecting in node.js

You can connect to the database and issue queries using @databases/pg:

const createPool = require('@databases/pg');
const {sql} = require('@databases/pg');

// If you're using TypeScript or Babel, you can swap
// the two `require` calls for this import statement:

// import createPool, {sql} from '@databases/pg';

// create a "pool" of connections, you can think of this as a single
// connection, the pool is just used behind the scenes to improve
// performance
const db = createPool('postgres://localhost');

// wrap code in an `async` function so we can use `await`
async function run() {

  // we can run sql by tagging it as "sql" and then passing it to db.query
  await db.query(sql`
    CREATE TABLE IF NOT EXISTS beatles (
      name TEXT NOT NULL,
      height INT NOT NULL,
      birthday DATE NOT NULL
    );
  `);

  const beatle = {
    name: 'George',
    height: 70,
    birthday: new Date(1946, 02, 14),
  };

  // If we need to pass values, we can use ${...} and they will
  // be safely & securely escaped for us
  await db.query(sql`
    INSERT INTO beatles (name, height, birthday)
    VALUES (${beatle.name}, ${beatle.height}, ${beatle.birthday});
  `);

  console.log(
    await db.query(sql`SELECT * FROM beatles;`)
  );
}

run().catch(ex => {
  // It's a good idea to always report errors using
  // `console.error` and set the process.exitCode if
  // you're calling an async function at the top level
  console.error(ex);
  process.exitCode = 1;
}).then(() => {
  // For this little demonstration, we'll dispose of the
  // connection pool when we're done, so that the process
  // exists. If you're building a web server/backend API
  // you probably never need to call this.
  return db.dispose();
});

You can find a more complete guide to querying Postgres using node.js at https://www.atdatabases.org/docs/pg

How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

Agreed, i had the same issues and this is what worked and what did not:

WORKED: <img src="Docs/pinoutDOIT32devkitv1.png" width="800"/>
*DOES NOT WORK: <img src="/Docs/pinoutDOIT32devkitv1.png" width="800"/>
DOES NOT WORK: <img src="./Docs/pinoutDOIT32devkitv1.png" width="800"/>*

How to return part of string before a certain character?

In General a function to return string after substring is

_x000D_
_x000D_
function getStringAfterSubstring(parentString, substring) {_x000D_
    return parentString.substring(parentString.indexOf(substring) + substring.length)_x000D_
}_x000D_
_x000D_
function getStringBeforeSubstring(parentString, substring) {_x000D_
    return parentString.substring(0, parentString.indexOf(substring))_x000D_
}_x000D_
console.log(getStringAfterSubstring('abcxyz123uvw', '123'))_x000D_
console.log(getStringBeforeSubstring('abcxyz123uvw', '123'))
_x000D_
_x000D_
_x000D_

Find Oracle JDBC driver in Maven repository

Up to now, its not possible to use maven repositories. I'm using ivy as dependency management tool, but also use maven2' s ibiblio repositories. And this is working for ivy:

<dependency org="oracle" name="ojdbc14" rev="10.2.0.2" conf="*->default"/>

Maven2' s dependency could be something like that:

<dependency> 
    <groupId>oracle</groupId> 
    <artifactId>ojdbc14</artifactId> 
    <version>10.2.0.2</version> 
</dependency>

Notice that i define http://download.java.net/maven/2/ and http://mirrors.ibiblio.org/pub/mirrors/maven/mule/dependencies/maven2/[organisation]/[module]/[revision]/[artifact]-[revision].[ext] as external maven2 repos on my ivy settings.

Android Split string

android split string by comma

String data = "1,Diego Maradona,Footballer,Argentina";
String[] items = data.split(",");
for (String item : items)
{
    System.out.println("item = " + item);
}

Error CS2001: Source file '.cs' could not be found

They are likely still referenced by the project file. Make sure they are deleted using the Solution Explorer in Visual Studio - it should show them as being missing (with an exclamation mark).

PHP Redirect with POST data

There is a simple hack, use $_SESSION and create an array of the posted values, and once you go to the File_C.php you can use it then do you process after that destroy it.

Relative URLs in WordPress

<?php wp_make_link_relative( $link ) ?>

Convert full URL paths to relative paths.

Removes the http or https protocols and the domain. Keeps the path '/' at the beginning, so it isn't a true relative link, but from the web root base.

Reference: Wordpress Codex

Django DB Settings 'Improperly Configured' Error

For people using IntelliJ, with these settings I was able to query from the shell (on windows).

enter image description here

Rails 4: how to use $(document).ready() with turbo-links

$(document).on 'ready turbolinks:load', ->
  console.log '(document).turbolinks:load'

ASP.NET MVC Return Json Result?

It should be :

public async Task<ActionResult> GetSomeJsonData()
{
    var model = // ... get data or build model etc.

    return Json(new { Data = model }, JsonRequestBehavior.AllowGet); 
}

or more simply:

return Json(model, JsonRequestBehavior.AllowGet); 

I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...

VBA module that runs other modules

As long as the macros in question are in the same workbook and you verify the names exist, you can call those macros from any other module by name, not by module.

So if in Module1 you had two macros Macro1 and Macro2 and in Module2 you had Macro3 and Macro 4, then in another macro you could call them all:

Sub MasterMacro()
    Call Macro1
    Call Macro2
    Call Macro3
    Call Macro4
End Sub

How to check if an element is off-screen

Depends on what your definition of "offscreen" is. Is that within the viewport, or within the defined boundaries of your page?

Using Element.getBoundingClientRect() you can easily detect whether or not your element is within the boundries of your viewport (i.e. onscreen or offscreen):

jQuery.expr.filters.offscreen = function(el) {
  var rect = el.getBoundingClientRect();
  return (
           (rect.x + rect.width) < 0 
             || (rect.y + rect.height) < 0
             || (rect.x > window.innerWidth || rect.y > window.innerHeight)
         );
};

You could then use that in several ways:

// returns all elements that are offscreen
$(':offscreen');

// boolean returned if element is offscreen
$('div').is(':offscreen');

wamp server does not start: Windows 7, 64Bit

Check your apache error log. I had this error "[error] (OS 5)Access is denied. : could not open transfer log file C:/wamp/logs/access.log. Unable to open logs" Then I rename my "access.log" to other name, you can delete if you don't need/never see your access log. Then restart your apache service. This happen because the file size too big. I think if you trying to open this file using notepad, it will not open, I tried to open that before. Hope it help.

Given a filesystem path, is there a shorter way to extract the filename without its extension?

try

System.IO.Path.GetFileNameWithoutExtension(path); 

demo

string fileName = @"C:\mydir\myfile.ext";
string path = @"C:\mydir\";
string result;

result = Path.GetFileNameWithoutExtension(fileName);
Console.WriteLine("GetFileNameWithoutExtension('{0}') returns '{1}'", 
    fileName, result);

result = Path.GetFileName(path);
Console.WriteLine("GetFileName('{0}') returns '{1}'", 
    path, result);

// This code produces output similar to the following:
//
// GetFileNameWithoutExtension('C:\mydir\myfile.ext') returns 'myfile'
// GetFileName('C:\mydir\') returns ''

https://msdn.microsoft.com/en-gb/library/system.io.path.getfilenamewithoutextension%28v=vs.80%29.aspx

test attribute in JSTL <c:if> tag

Attributes in JSP tag libraries in general can be either static or resolved at request time. If they are resolved at request time the JSP will resolve their value at runtime and pass the output on to the tag. This means you can put pretty much any JSP code into the attribute and the tag will behave accordingly to what output that produces.

If you look at the jstl taglib docs you can see which attributes are reuest time and which are not. http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/index.html

VBA check if file exists

I'll throw this out there and then duck. The usual reason to check if a file exists is to avoid an error when attempting to open it. How about using the error handler to deal with that:

Function openFileTest(filePathName As String, ByRef wkBook As Workbook, _
                      errorHandlingMethod As Long) As Boolean
'Returns True if filePathName is successfully opened,
'        False otherwise.
   Dim errorNum As Long

'***************************************************************************
'  Open the file or determine that it doesn't exist.
   On Error Resume Next:
   Set wkBook = Workbooks.Open(fileName:=filePathName)
   If Err.Number <> 0 Then
      errorNum = Err.Number
      'Error while attempting to open the file. Maybe it doesn't exist?
      If Err.Number = 1004 Then
'***************************************************************************
      'File doesn't exist.
         'Better clear the error and point to the error handler before moving on.
         Err.Clear
         On Error GoTo OPENFILETEST_FAIL:
         '[Clever code here to cope with non-existant file]
         '...
         'If the problem could not be resolved, invoke the error handler.
         Err.Raise errorNum
      Else
         'No idea what the error is, but it's not due to a non-existant file
         'Invoke the error handler.
         Err.Clear
         On Error GoTo OPENFILETEST_FAIL:
         Err.Raise errorNum
      End If
   End If

   'Either the file was successfully opened or the problem was resolved.
   openFileTest = True
   Exit Function

OPENFILETEST_FAIL:
   errorNum = Err.Number
   'Presumabley the problem is not a non-existant file, so it's
   'some other error. Not sure what this would be, so...
   If errorHandlingMethod < 2 Then
      'The easy out is to clear the error, reset to the default error handler,
      'and raise the error number again.
      'This will immediately cause the code to terminate with VBA's standard
      'run time error Message box:
      errorNum = Err.Number
      Err.Clear
      On Error GoTo 0
      Err.Raise errorNum
      Exit Function

   ElseIf errorHandlingMethod = 2 Then
      'Easier debugging, generate a more informative message box, then terminate:
      MsgBox "" _
           & "Error while opening workbook." _
           & "PathName: " & filePathName & vbCrLf _
           & "Error " & errorNum & ": " & Err.Description & vbCrLf _
           , vbExclamation _
           , "Failure in function OpenFile(), IO Module"
      End

   Else
      'The calling function is ok with a false result. That is the point
      'of returning a boolean, after all.
      openFileTest = False
      Exit Function
   End If

End Function 'openFileTest()

Use Font Awesome icon as CSS content

As it says at FontAwesome website FontAwesome =>

HTML:

<span class="icon login"></span> Login</li>

CSS:

 .icon::before {
    display: inline-block;
    font-style: normal;
    font-variant: normal;
    text-rendering: auto;
    -webkit-font-smoothing: antialiased;
  }

    .login::before {
        font-family: "Font Awesome 5 Free";
        font-weight: 900;
        content: "\f007";
   }

In .login::before -> edit content:''; to suit your unicode.

cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome

To stop seeing those cast_sender.js errors, edit the youtube link in the iframe src and change embed to v

Is the NOLOCK (Sql Server hint) bad practice?

Prior to working on Stack Overflow, I was against NOLOCK on the principal that you could potentially perform a SELECT with NOLOCK and get back results with data that may be out of date or inconsistent. A factor to think about is how many records may be inserted/updated at the same time another process may be selecting data from the same table. If this happens a lot then there's a high probability of deadlocks unless you use a database mode such as READ COMMITED SNAPSHOT.

I have since changed my perspective on the use of NOLOCK after witnessing how it can improve SELECT performance as well as eliminate deadlocks on a massively loaded SQL Server. There are times that you may not care that your data isn't exactly 100% committed and you need results back quickly even though they may be out of date.

Ask yourself a question when thinking of using NOLOCK:

Does my query include a table that has a high number of INSERT/UPDATE commands and do I care if the data returned from a query may be missing these changes at a given moment?

If the answer is no, then use NOLOCK to improve performance.


I just performed a quick search for the NOLOCK keyword within the code base for Stack Overflow and found 138 instances, so we use it in quite a few places.

Open Google Chrome from VBA/Excel

I found an easier way to do it and it works perfectly even if you don't know the path where the chrome is located.

First of all, you have to paste this code in the top of the module.

Option Explicit
Private pWebAddress As String
Public Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _
(ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, _
ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

After that you have to create this two modules:

Sub LoadExplorer()
    LoadFile "Chrome.exe" ' Here you are executing the chrome. exe
End Sub

Sub LoadFile(FileName As String)
    ShellExecute 0, "Open", FileName, "http://test.123", "", 1 ' You can change the URL.
End Sub

With this you will be able (if you want) to set a variable for the url or just leave it like hardcode.

Ps: It works perfectly for others browsers just changing "Chrome.exe" to opera, bing, etc.

HTML: How to create a DIV with only vertical scroll-bars for long paragraphs?

I also faced the same issue...try to do this...this worked for me

        .scrollBbar 
        {
        position:fixed;
        top:50px;
        bottom:0;
        left:0;
        width:200px;
        overflow-x:hidden;
        overflow-y:auto;
       }

If Python is interpreted, what are .pyc files?

THIS IS FOR BEGINNERS,

Python automatically compiles your script to compiled code, so called byte code, before running it.

Running a script is not considered an import and no .pyc will be created.

For example, if you have a script file abc.py that imports another module xyz.py, when you run abc.py, xyz.pyc will be created since xyz is imported, but no abc.pyc file will be created since abc.py isn’t being imported.

If you need to create a .pyc file for a module that is not imported, you can use the py_compile and compileall modules.

The py_compile module can manually compile any module. One way is to use the py_compile.compile function in that module interactively:

>>> import py_compile
>>> py_compile.compile('abc.py')

This will write the .pyc to the same location as abc.py (you can override that with the optional parameter cfile).

You can also automatically compile all files in a directory or directories using the compileall module.

python -m compileall

If the directory name (the current directory in this example) is omitted, the module compiles everything found on sys.path

What does "var" mean in C#?

It means the data type is derived (implied) from the context.

From http://msdn.microsoft.com/en-us/library/bb383973.aspx

Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent:

var i = 10; // implicitly typed
int i = 10; //explicitly typed

var is useful for eliminating keyboard typing and visual noise, e.g.,

MyReallyReallyLongClassName x = new MyReallyReallyLongClassName();

becomes

var x = new MyReallyReallyLongClassName();

but can be overused to the point where readability is sacrificed.

error: command 'gcc' failed with exit status 1 while installing eventlet

Your install is failing because you don't have the python development headers installed. You can do this through apt on ubuntu/debian with:

sudo apt-get install python-dev 

for python3 use:

sudo apt-get install python3-dev

For eventlet you might also need the libevent libraries installed so if you get an error talking about that you can install libevent with:

sudo apt-get install libevent-dev

Pivoting rows into columns dynamically in Oracle

First of all, dynamically pivot using pivot xml again needs to be parsed. We have another way of doing this by storing the column names in a variable and passing them in the dynamic sql as below.

Consider we have a table like below.

enter image description here

If we need to show the values in the column YR as column names and the values in those columns from QTY, then we can use the below code.

declare
  sqlqry clob;
  cols clob;
begin
  select listagg('''' || YR || ''' as "' || YR || '"', ',') within group (order by YR)
  into   cols
  from   (select distinct YR from EMPLOYEE);


  sqlqry :=
  '      
  select * from
  (
      select *
      from EMPLOYEE
  )
  pivot
  (
    MIN(QTY) for YR in (' || cols  || ')
  )';

  execute immediate sqlqry;
end;
/

RESULT

enter image description here

How to query MongoDB with "like"?

db.customer.find({"customerid": {"$regex": "CU_00000*", "$options": "i"}}).pretty()

When we are searching for string patterns, always it is better to use the above pattern as when we are not sure about case. Hope that helps!!!

Create WordPress Page that redirects to another URL

I'm not familiar with Wordpress templates, but I'm assuming that headers are sent to the browser by WP before your template is even loaded. Because of that, the common redirection method of:

header("Location: new_url");

won't work. Unless there's a way to force sending headers through a template before WP does anything, you'll need to use some Javascript like so:

<script language="javascript" type="text/javascript">
document.location = "new_url";
</script>

Put that in the section and it'll be run when the page loads. This method won't be instant, and it also won't work for people with Javascript disabled.

jQuery Validation plugin: validate check box

You had several issues with your code.

1) Missing a closing brace, }, within your rules.

2) In this case, there is no reason to use a function for the required rule. By default, the plugin can handle checkbox and radio inputs just fine, so using true is enough. However, this will simply do the same logic as in your original function and verify that at least one is checked.

3) If you also want only a maximum of two to be checked, then you'll need to apply the maxlength rule.

4) The messages option was missing the rule specification. It will work, but the one custom message would apply to all rules on the same field.

5) If a name attribute contains brackets, you must enclose it within quotes.

DEMO: http://jsfiddle.net/K6Wvk/

$(document).ready(function () {

    $('#formid').validate({ // initialize the plugin
        rules: {
            'test[]': {
                required: true,
                maxlength: 2
            }
        },
        messages: {
            'test[]': {
                required: "You must check at least 1 box",
                maxlength: "Check no more than {0} boxes"
            }
        }
    });

});

Skip certain tables with mysqldump

I like Rubo77's solution, I hadn't seen it before I modified Paul's. This one will backup a single database, excluding any tables you don't want. It will then gzip it, and delete any files over 8 days old. I will probably use 2 versions of this that do a full (minus logs table) once a day, and another that just backs up the most important tables that change the most every hour using a couple cron jobs.

#!/bin/sh
PASSWORD=XXXX
HOST=127.0.0.1
USER=root
DATABASE=MyFavoriteDB

now="$(date +'%d_%m_%Y_%H_%M')"
filename="${DATABASE}_db_backup_$now"
backupfolder="/opt/backups/mysql"
DB_FILE="$backupfolder/$filename"
logfile="$backupfolder/"backup_log_"$(date +'%Y_%m')".txt

EXCLUDED_TABLES=(
logs
)
IGNORED_TABLES_STRING=''
for TABLE in "${EXCLUDED_TABLES[@]}"
do :
   IGNORED_TABLES_STRING+=" --ignore-table=${DATABASE}.${TABLE}"
done

echo "Dump structure started at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
mysqldump --host=${HOST} --user=${USER} --password=${PASSWORD} --single-transaction --no-data --routines ${DATABASE}  > ${DB_FILE} 
echo "Dump structure finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
echo "Dump content"
mysqldump --host=${HOST} --user=${USER} --password=${PASSWORD} ${DATABASE} --no-create-info --skip-triggers ${IGNORED_TABLES_STRING} >> ${DB_FILE}
gzip ${DB_FILE}

find "$backupfolder" -name ${DATABASE}_db_backup_* -mtime +8 -exec rm {} \;
echo "old files deleted" >> "$logfile"
echo "operation finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
echo "*****************" >> "$logfile"
exit 0

Python: How to check if keys exists and retrieve value from Dictionary in descending priority

If we encapsulate that in a function we could use recursion and state clearly the purpose by naming the function properly (not sure if getAny is actually a good name):

def getAny(dic, keys, default=None):
    return (keys or default) and dic.get(keys[0], 
                                         getAny( dic, keys[1:], default=default))

or even better, without recursion and more clear:

def getAny(dic, keys, default=None):
    for k in keys: 
        if k in dic:
           return dic[k]
    return default

Then that could be used in a way similar to the dict.get method, like:

getAny(myDict, keySet)

and even have a default result in case of no keys found at all:

getAny(myDict, keySet, "not found")

displaying a string on the textview when clicking a button in android

You can do like this:

 String hello;
public void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.main);
    super.onCreate(savedInstanceState);

    mybtn = (Button)findViewById(R.id.mybtn);
    txtView=(TextView)findViewById(R.id.txtView);
    txtwidth = (TextView)findViewById(R.id.viewwidth);
    hello="This is my first project";


    mybtn.setOnClickListener(this);
}
public void onClick(View view){
    txtView.setText(hello);
}

Check your textview names. Both are same . You must use different object names and you have mentioned that textview object which is not available in your xml layout file. Hope this will help you.

How to: Create trigger for auto update modified date with SQL Server 2008

My approach:

  • define a default constraint on the ModDate column with a value of GETDATE() - this handles the INSERT case

  • have a AFTER UPDATE trigger to update the ModDate column

Something like:

CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
    UPDATE dbo.TimeEntry
    SET ModDate = GETDATE()
    WHERE ID IN (SELECT DISTINCT ID FROM Inserted)

How to make unicode string with python3

What's new in Python 3.0 says:

All text is Unicode; however encoded Unicode is represented as binary data

If you want to ensure you are outputting utf-8, here's an example from this page on unicode in 3.0:

b'\x80abc'.decode("utf-8", "strict")

How to shift a column in Pandas DataFrame

Lets define the dataframe from your example by

>>> df = pd.DataFrame([[206, 214], [226, 234], [245, 253], [265, 272], [283, 291]], 
    columns=[1, 2])
>>> df
     1    2
0  206  214
1  226  234
2  245  253
3  265  272
4  283  291

Then you could manipulate the index of the second column by

>>> df[2].index = df[2].index+1

and finally re-combine the single columns

>>> pd.concat([df[1], df[2]], axis=1)
       1      2
0  206.0    NaN
1  226.0  214.0
2  245.0  234.0
3  265.0  253.0
4  283.0  272.0
5    NaN  291.0

Perhaps not fast but simple to read. Consider setting variables for the column names and the actual shift required.

Edit: Generally shifting is possible by df[2].shift(1) as already posted however would that cut-off the carryover.

Detailed 500 error message, ASP + IIS 7.5

If you're on a remote server you can configure your web.config file like so:

<configuration>
<system.webServer>
    <httpErrors errorMode="Detailed" />
    <asp scriptErrorSentToBrowser="true"/>
</system.webServer>
<system.web>
    <customErrors mode="Off"/>
    <compilation debug="true"/>
</system.web>

How can I make a clickable link in an NSAttributedString?

In case you're having issues with what @Karl Nosworthy and @esilver had provided above, I've updated the NSMutableAttributedString extension to its Swift 4 version.

extension NSMutableAttributedString {

public func setAsLink(textToFind:String, linkURL:String) -> Bool {

    let foundRange = self.mutableString.range(of: textToFind)
    if foundRange.location != NSNotFound {
         _ = NSMutableAttributedString(string: textToFind)
        // Set Attribuets for Color, HyperLink and Font Size
        let attributes = [NSFontAttributeName: UIFont.bodyFont(.regular, shouldResize: true), NSLinkAttributeName:NSURL(string: linkURL)!, NSForegroundColorAttributeName: UIColor.blue]

        self.setAttributes(attributes, range: foundRange)
        return true
    }
    return false
  }
}

How can I start an interactive console for Perl?

You can use the perl debugger on a trivial program, like so:

perl -de1

Alternatively there's Alexis Sukrieh's Perl Console application, but I haven't used it.

Get int from String, also containing letters, in Java

Replace all non-digit with blank: the remaining string contains only digits.

Integer.parseInt(s.replaceAll("[\\D]", ""))

This will also remove non-digits inbetween digits, so "x1x1x" becomes 11.

If you need to confirm that the string consists of a sequence of digits (at least one) possibly followed a letter, then use this:

s.matches("[\\d]+[A-Za-z]?")

How do I configure php to enable pdo and include mysqli on CentOS?

mysqli is provided by php-mysql-5.3.3-40.el6_6.x86_64

You may need to try the following

yum install php-mysql-5.3.3-40.el6_6.x86_64

Is there a Python equivalent of the C# null-coalescing operator?

other = s or "some default value"

Ok, it must be clarified how the or operator works. It is a boolean operator, so it works in a boolean context. If the values are not boolean, they are converted to boolean for the purposes of the operator.

Note that the or operator does not return only True or False. Instead, it returns the first operand if the first operand evaluates to true, and it returns the second operand if the first operand evaluates to false.

In this case, the expression x or y returns x if it is True or evaluates to true when converted to boolean. Otherwise, it returns y. For most cases, this will serve for the very same purpose of C?'s null-coalescing operator, but keep in mind:

42    or "something"    # returns 42
0     or "something"    # returns "something"
None  or "something"    # returns "something"
False or "something"    # returns "something"
""    or "something"    # returns "something"

If you use your variable s to hold something that is either a reference to the instance of a class or None (as long as your class does not define members __nonzero__() and __len__()), it is secure to use the same semantics as the null-coalescing operator.

In fact, it may even be useful to have this side-effect of Python. Since you know what values evaluates to false, you can use this to trigger the default value without using None specifically (an error object, for example).

In some languages this behavior is referred to as the Elvis operator.

How to enable external request in IIS Express?

For me using this, relatively simple, and straight forward:

Download the Visual Studio Extension by searching for 'Conveyor' in the Extensions dialog. Then just install.

form: https://marketplace.visualstudio.com/items?itemName=vs-publisher-1448185.ConveyorbyKeyoti

Skip to next iteration in loop vba

For i = 2 To 24
  Level = Cells(i, 4)
  Return = Cells(i, 5)

  If Return = 0 And Level = 0 Then GoTo NextIteration
  'Go to the next iteration
  Else
  End If
  ' This is how you make a line label in VBA - Do not use keyword or
  ' integer and end it in colon
  NextIteration:
Next

How to compare two dates to find time difference in SQL Server 2005, date manipulation

I think you need the time gap between job_start & job_end.

Try this...

select SUBSTRING(CONVERT(VARCHAR(20),(job_end - job_start),120),12,8) from tableA

I ended up with this.

01:14:37

vi/vim editor, copy a block (not usual action)

Their Documentation says:

Cut and paste:

  1. Position the cursor where you want to begin cutting.
  2. Press v to select characters (or uppercase V to select whole lines).
  3. Move the cursor to the end of what you want to cut.
  4. Press d to cut (or y to copy).
  5. Move to where you would like to paste.
  6. Press P to paste before the cursor, or p to paste after.

Copy and paste is performed with the same steps except for step 4 where you would press y instead of d:

d = delete = cut

y = yank = copy

What exactly does the T and Z mean in timestamp?

The T doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.

The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).

Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime() method. You could have used Q or M or Monty Python and the method would have returned them unchanged as well; the method only looks for patterns starting with % to replace those with information from the datetime object.

How to convert an int value to string in Go?

Use the strconv package's Itoa function.

For example:

package main

import (
    "strconv"
    "fmt"
)

func main() {
    t := strconv.Itoa(123)
    fmt.Println(t)
}

You can concat strings simply by +'ing them, or by using the Join function of the strings package.

How to return a boolean method in java?

Best way would be to declare Boolean variable within the code block and return it at end of code, like this:

public boolean Test(){
    boolean booleanFlag= true; 
    if (A>B)
    {booleanFlag= true;}
    else 
    {booleanFlag = false;}
    return booleanFlag;

}

I find this the best way.

How do I bind the enter key to a function in tkinter?

Another alternative is to use a lambda:

ent.bind("<Return>", (lambda event: name_of_function()))

Full code:

from tkinter import *
from tkinter.messagebox import showinfo

def reply(name):
    showinfo(title="Reply", message = "Hello %s!" % name)


top = Tk()
top.title("Echo")
top.iconbitmap("Iconshock-Folder-Gallery.ico")

Label(top, text="Enter your name:").pack(side=TOP)
ent = Entry(top)
ent.bind("<Return>", (lambda event: reply(ent.get())))
ent.pack(side=TOP)
btn = Button(top,text="Submit", command=(lambda: reply(ent.get())))
btn.pack(side=LEFT)

top.mainloop()

As you can see, creating a lambda function with an unused variable "event" solves the problem.

How to read xml file contents in jQuery and display in html elements?

Get the XML using Ajax call, find the main element, loop through all the element and append data in table.

Sample code

 //ajax call to load XML and parse it
        $.ajax({
            type: 'GET',
            url: 'https://res.cloudinary.com/dmsxwwfb5/raw/upload/v1591716537/book.xml',           // The file path.
            dataType: 'xml',    
            success: function(xml) {
               //find all book tags, loop them and append to table body
                $(xml).find('book').each(function() {
                    
                    // Append new data to the tbody element.
                    $('#tableBody').append(
                        '<tr>' +
                            '<td>' +
                                $(this).find('author').text() + '</td> ' +
                            '<td>' +
                                $(this).find('title').text() + '</td> ' +
                            '<td>' +
                                $(this).find('genre').text() + '</td> ' +
                                '<td>' +
                                $(this).find('price').text() + '</td> ' +
                                '<td>' +
                                $(this).find('description').text() + '</td> ' +
                        '</tr>');
                });
            }
        });

Fiddle link: https://jsfiddle.net/pn9xs8hf/2/

Source: Read XML using jQuery & load it in HTML Table

Detecting the character encoding of an HTTP POST request

The Charset used in the POST will match that of the Charset specified in the HTML hosting the form. Hence if your form is sent using UTF-8 encoding that is the encoding used for the posted content. The URL encoding is applied after the values are converted to the set of octets for the character encoding.

How to get position of a certain element in strings vector, to use it as an index in ints vector?

I am a beginner so here is a beginners answer. The if in the for loop gives i which can then be used however needed such as Numbers[i] in another vector. Most is fluff for examples sake, the for/if really says it all.

int main(){
vector<string>names{"Sara", "Harold", "Frank", "Taylor", "Sasha", "Seymore"};
string req_name;
cout<<"Enter search name: "<<'\n';
cin>>req_name;
    for(int i=0; i<=names.size()-1; ++i) {
        if(names[i]==req_name){
            cout<<"The index number for "<<req_name<<" is "<<i<<'\n';
            return 0;
        }
        else if(names[i]!=req_name && i==names.size()-1) {
            cout<<"That name is not an element in this vector"<<'\n';
        } else {
            continue;
        }
    }

Jenkins pipeline how to change to another folder

The dir wrapper can wrap, any other step, and it all works inside a steps block, for example:

steps {
    sh "pwd"
    dir('your-sub-directory') {
      sh "pwd"
    }
    sh "pwd"
} 

how to mysqldump remote db from local machine

As I haven't seen it at serverfault yet, and the answer is quite simple:

Change:

ssh -f -L3310:remote.server:3306 [email protected] -N

To:

ssh -f -L3310:localhost:3306 [email protected] -N

And change:

mysqldump -P 3310 -h localhost -u mysql_user -p database_name table_name

To:

mysqldump -P 3310 -h 127.0.0.1 -u mysql_user -p database_name table_name

(do not use localhost, it's one of these 'special meaning' nonsense that probably connects by socket rather then by port)

edit: well, to elaborate: if host is set to localhost, a configured (or default) --socket option is assumed. See the manual for which option files are sought / used. Under Windows, this can be a named pipe.

How to convert char* to wchar_t*?

Use a std::wstring instead of a C99 variable length array. The current standard guarantees a contiguous buffer for std::basic_string. E.g.,

std::wstring wc( cSize, L'#' );
mbstowcs( &wc[0], c, cSize );

C++ does not support C99 variable length arrays, and so if you compiled your code as pure C++, it would not even compile.

With that change your function return type should also be std::wstring.

Remember to set relevant locale in main.

E.g., setlocale( LC_ALL, "" ).

Cheers & hth.,

Oracle pl-sql escape character (for a " ' ")

you can use ESCAPE like given example below

The '_' wild card character is used to match exactly one character, while '%' is used to match zero or more occurrences of any characters. These characters can be escaped in SQL.

SELECT name FROM emp WHERE id LIKE '%/_%' ESCAPE '/';

The same works inside PL/SQL:

 if( id like '%/_%' ESCAPE '/' )

This applies only to like patterns, for example in an insert there is no need to escape _ or %, they are used as plain characters anyhow. In arbitrary strings only ' needs to be escaped by ''.

Spark : how to run spark file from spark shell

You can use either sbt or maven to compile spark programs. Simply add the spark as dependency to maven

<repository>
      <id>Spark repository</id>
      <url>http://www.sparkjava.com/nexus/content/repositories/spark/</url>
</repository>

And then the dependency:

<dependency>
      <groupId>spark</groupId>
      <artifactId>spark</artifactId>
      <version>1.2.0</version>
</dependency>

In terms of running a file with spark commands: you can simply do this:

echo"
   import org.apache.spark.sql.*
   ssc = new SQLContext(sc)
   ssc.sql("select * from mytable").collect
" > spark.input

Now run the commands script:

cat spark.input | spark-shell

How to get screen width without (minus) scrollbar?

None of these solutions worked for me, however I was able to fix it by taking the width and subtracting the width of the scroll bar. I'm not sure how cross-browser compatible this is.

Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51

For Electron modules, install electron-rebuild.

Format:
electron-rebuild -o <module_name> -v <electron version>

Example:
electron-rebuild -o myaddon -v 9.0.0-beta.6

Specify the same version that you have installed in the current directory

You might have this experience where a standard node-gyp build would report as 64, then a basic electron-rebuild would report 76, not until you add -v with exact version it bumps to actual version 80 (for 9.0.0-beta.6)

Cannot set property 'display' of undefined

I've found this answer in the site https://plainjs.com/javascript/styles/set-and-get-css-styles-of-elements-53/.

In this code we add multiple styles in an element:

_x000D_
_x000D_
let_x000D_
    element = document.querySelector('span')_x000D_
  , cssStyle = (el, styles) => {_x000D_
      for (var property in styles) {_x000D_
          el.style[property] = styles[property];_x000D_
      }_x000D_
  }_x000D_
;_x000D_
_x000D_
cssStyle(element, { background:'tomato', color: 'white', padding: '0.5rem 1rem'});
_x000D_
span{_x000D_
font-family: sans-serif;_x000D_
color: #323232;_x000D_
background: #fff;_x000D_
}
_x000D_
<span>_x000D_
lorem ipsum_x000D_
</span>
_x000D_
_x000D_
_x000D_

jquery select option click handler

One possible solution is to add a class to every option

<select name="export_type" id="export_type">
    <option class="export_option" value="pdf">PDF</option>
    <option class="export_option" value="xlsx">Excel</option>
    <option class="export_option" value="docx">DocX</option>
</select>

and then use the click handler for this class

$(document).ready(function () {

    $(".export_option").click(function (e) {
        //alert('click');
    });

});

UPDATE: it looks like the code works in FF, IE and Opera but not in Chrome. Looking at the specs http://www.w3.org/TR/html401/interact/forms.html#h-17.6 I would say it's a bug in Chrome.

Block Comments in a Shell Script

In Vim:

  1. go to first line of block you want to comment
  2. shift-V (enter visual mode), up down highlight lines in block
  3. execute the following on selection :s/^/#/
  4. the command will look like this:

      :'<,'>s/^/#
    
  5. hit enter

e.g.

shift-V
jjj
:s/^/#
<enter>

No route matches "/users/sign_out" devise rails 3

Add:

  <%= csrf_meta_tag %>  and 
  <%= javascript_include_tag :defaults %>  to layouts

Use these link_to tags

 link_to 'Sign out', destroy_user_session_path, :method => :delete

  or

 link_to 'Sign out', '/users/sign_out', :method => :delete

In routes add:

  devise_for :users do
    get '/users/sign_out' => 'devise/sessions#destroy'
  end

Check a collection size with JSTL

use ${fn:length(companies) > 0} to check the size. This returns a boolean

How to test if a string contains one of the substrings in a list, in pandas?

You can use str.contains alone with a regex pattern using OR (|):

s[s.str.contains('og|at')]

Or you could add the series to a dataframe then use str.contains:

df = pd.DataFrame(s)
df[s.str.contains('og|at')] 

Output:

0 cat
1 hat
2 dog
3 fog 

How to convert Varchar to Double in sql?

use DECIMAL() or NUMERIC() as they are fixed precision and scale numbers.

SELECT fullName, 
       CAST(totalBal as DECIMAL(9,2)) _totalBal
FROM client_info 
ORDER BY _totalBal DESC

sed whole word search and replace

In one of my machine, delimiting the word with "\b" (without the quotes) did not work. The solution was to use "\<" for starting delimiter and "\>" for ending delimiter.

To explain with Joakim Lundberg's example:

$ echo "bar embarassment" | sed "s/\<bar\>/no bar/g"
no bar embarassment

Getting Spring Application Context

Before you implement any of the other suggestions, ask yourself these questions...

  • Why am I trying to get the ApplicationContext?
  • Am I effectively using the ApplicationContext as a service locator?
  • Can I avoid accessing the ApplicationContext at all?

The answers to these questions are easier in certain types of applications (Web apps, for example) than they are in others, but are worth asking anyway.

Accessing the ApplicationContext does kind of violate the whole dependency injection principle, but sometimes you've not got much choice.

Taking inputs with BufferedReader in Java

The problem id because of inp.read(); method. Its return single character at a time and because you are storing it into int type of array so that is just storing ascii value of that.

What you can do simply

for(int i=0;i<T;i++) {
    String s= inp.readLine();
    String[] intValues = inp.readLine().split(" ");
    int[] m= new int[2];
    m[0]=Integer.parseInt(intValues[0]);
    m[1]=Integer.parseInt(intValues[1]);

    // Checking whether I am taking the inputs correctly
    System.out.println(s);
    System.out.println(m[0]);
    System.out.println(m[1]);
}

Key Presses in Python

AutoHotKey is perfect for this kind of tasks (keyboard automation / remapping)

Script to send "A" 100 times:

Send {A 100}

That's all

EDIT: to send the keys to an specific application:

WinActivate Word
Send {A 100}

ReferenceError: Invalid left-hand side in assignment

The same happened for me with eslint module. EsLinter throw Parsing error: Invalid left-hand side in assignment expression for await in second if statement.

if (condition_one) {
  let result = await myFunction()
}

if (condition_two) {
  let result = await myFunction() // eslint parsing error
}

As strange as it sounds what fixed this error was to add ; semicolon at the end of line where await occurred.

if (condition_one) {
  let result = await myFunction();
}

if (condition_two) {
  let result = await myFunction();
}

How do I update a Tomcat webapp without restarting the entire service?

In conf directory of apache tomcat you can find context.xml file. In that edit tag as <Context reloadable="true">. this should solve the issue and you need not restart the server

/lib/ld-linux.so.2: bad ELF interpreter: No such file or directory

These are the installation i had to run in order to make it work on fedora 22 :-

glibc-2.21-7.fc22.i686

alsa-lib-1.0.29-1.fc22.i686

qt3-3.3.8b-64.fc22.i686

libusb-1:0.1.5-5.fc22.i686

Classes vs. Modules in VB.NET

Modules are fine for storing enums and some global variables, constants and shared functions. its very good thing and I often use it. Declared variables are visible acros entire project.

What is class="mb-0" in Bootstrap 4?

m - for classes that set margin, like this :

  • mt - for classes that set margin-top
  • mb - for classes that set margin-bottom
  • ml - for classes that set margin-left
  • mr - for classes that set margin-right
  • mx - for classes that set both margin-left and margin-right
  • my - for classes that set both margin-top and margin-bottom

Where size is one of margin :

  • 0 - for classes that eliminate the margin by setting it to 0, like mt-0
  • 1 - (by default) for classes that set the margin to $spacer * .25, like mt-1
  • 2 - (by default) for classes that set the margin to $spacer * .5, like mt-2
  • 3 - (by default) for classes that set the margin to $spacer, like mt-3
  • 4 - (by default) for classes that set the margin to $spacer * 1.5, like mt-4
  • 5 - (by default) for classes that set the margin to $spacer * 3, like mt-5
  • auto - for classes that set the margin to auto, like mx-auto

Pass a list to a function to act as multiple arguments

Since Python 3.5 you can unpack unlimited amount of lists.

PEP 448 - Additional Unpacking Generalizations

So this will work:

a = ['1', '2', '3', '4']
b = ['5', '6']
function_that_needs_strings(*a, *b)

How can I include all JavaScript files in a directory via JavaScript file?

You can't do that in JavaScript, since JS is executed in the browser, not in the server, so it didn't know anything about directories or other server resources.

The best option is using a server side script like the one posted by jellyfishtree.

append to url and refresh page

Try this

var url = ApiUrl(`/customers`);
  if(data){
   url += '?search='+data; 
  }
  else
  { 
      url +=  `?page=${page}&per_page=${perpage}`;
  }
  console.log(url);

how to Call super constructor in Lombok

As an option you can use com.fasterxml.jackson.databind.ObjectMapper to initialize a child class from parent

public class A {
    int x;
    int y;
}

public class B extends A {
    int z;
}

ObjectMapper MAPPER = new ObjectMapper(); //it's configurable
MAPPER.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false );
MAPPER.configure( SerializationFeature.FAIL_ON_EMPTY_BEANS, false );

//Then wherever you need to initialize child from parent:
A parent = new A(x, y);
B child = MAPPER.convertValue( parent, B.class);
child.setZ(z);

You can still use any lombok annotations on A and B if you need.

Using HTML5/Canvas/JavaScript to take in-browser screenshots

Your web app can now take a 'native' screenshot of the client's entire desktop using getUserMedia():

Have a look at this example:

https://www.webrtc-experiment.com/Pluginfree-Screen-Sharing/

The client will have to be using chrome (for now) and will need to enable screen capture support under chrome://flags.

react hooks useEffect() cleanup for only componentWillUnmount?

Since the cleanup is not dependent on the username, you could put the cleanup in a separate useEffect that is given an empty array as second argument.

Example

_x000D_
_x000D_
const { useState, useEffect } = React;_x000D_
_x000D_
const ForExample = () => {_x000D_
  const [name, setName] = useState("");_x000D_
  const [username, setUsername] = useState("");_x000D_
_x000D_
  useEffect(_x000D_
    () => {_x000D_
      console.log("effect");_x000D_
    },_x000D_
    [username]_x000D_
  );_x000D_
_x000D_
  useEffect(() => {_x000D_
    return () => {_x000D_
      console.log("cleaned up");_x000D_
    };_x000D_
  }, []);_x000D_
_x000D_
  const handleName = e => {_x000D_
    const { value } = e.target;_x000D_
_x000D_
    setName(value);_x000D_
  };_x000D_
_x000D_
  const handleUsername = e => {_x000D_
    const { value } = e.target;_x000D_
_x000D_
    setUsername(value);_x000D_
  };_x000D_
_x000D_
  return (_x000D_
    <div>_x000D_
      <div>_x000D_
        <input value={name} onChange={handleName} />_x000D_
        <input value={username} onChange={handleUsername} />_x000D_
      </div>_x000D_
      <div>_x000D_
        <div>_x000D_
          <span>{name}</span>_x000D_
        </div>_x000D_
        <div>_x000D_
          <span>{username}</span>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  );_x000D_
};_x000D_
_x000D_
function App() {_x000D_
  const [shouldRender, setShouldRender] = useState(true);_x000D_
_x000D_
  useEffect(() => {_x000D_
    setTimeout(() => {_x000D_
      setShouldRender(false);_x000D_
    }, 5000);_x000D_
  }, []);_x000D_
_x000D_
  return shouldRender ? <ForExample /> : null;_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App />, document.getElementById("root"));
_x000D_
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>_x000D_
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>_x000D_
_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

exclude @Component from @ComponentScan

I needed to exclude an auditing @Aspect @Component from the app context but only for a few test classes. I ended up using @Profile("audit") on the aspect class; including the profile for normal operations but excluding it (don't put it in @ActiveProfiles) on the specific test classes.

Counting inversions in an array

Here is c++ solution

/**
*array sorting needed to verify if first arrays n'th element is greater than sencond arrays
*some element then all elements following n will do the same
*/
#include<stdio.h>
#include<iostream>
using namespace std;
int countInversions(int array[],int size);
int merge(int arr1[],int size1,int arr2[],int size2,int[]);
int main()
{
    int array[] = {2, 4, 1, 3, 5};
    int size = sizeof(array) / sizeof(array[0]);
    int x = countInversions(array,size);
    printf("number of inversions = %d",x);
}

int countInversions(int array[],int size)
{
    if(size > 1 )
    {
    int mid = size / 2;
    int count1 = countInversions(array,mid);
    int count2 = countInversions(array+mid,size-mid);
    int temp[size];
    int count3 = merge(array,mid,array+mid,size-mid,temp);
    for(int x =0;x<size ;x++)
    {
        array[x] = temp[x];
    }
    return count1 + count2 + count3;
    }else{
        return 0;
    }
}

int merge(int arr1[],int size1,int arr2[],int size2,int temp[])
{
    int count  = 0;
    int a = 0;
    int b = 0;
    int c = 0;
    while(a < size1 && b < size2)
    {
        if(arr1[a] < arr2[b])
        {
            temp[c] = arr1[a];
            c++;
            a++;
        }else{
            temp[c] = arr2[b];
            b++;
            c++;
            count = count + size1 -a;
        }
    }

    while(a < size1)
    {
        temp[c] = arr1[a];
        c++;a++;
    }

while(b < size2)
    {
        temp[c] = arr2[b];
        c++;b++;
    }

    return count;
}

Drawing an image from a data URL to a canvas

Perhaps this fiddle would help ThumbGen - jsFiddle It uses File API and Canvas to dynamically generate thumbnails of images.

(function (doc) {
    var oError = null;
    var oFileIn = doc.getElementById('fileIn');
    var oFileReader = new FileReader();
    var oImage = new Image();
    oFileIn.addEventListener('change', function () {
        var oFile = this.files[0];
        var oLogInfo = doc.getElementById('logInfo');
        var rFltr = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i
        try {
            if (rFltr.test(oFile.type)) {
                oFileReader.readAsDataURL(oFile);
                oLogInfo.setAttribute('class', 'message info');
                throw 'Preview for ' + oFile.name;
            } else {
                oLogInfo.setAttribute('class', 'message error');
                throw oFile.name + ' is not a valid image';
            }
        } catch (err) {
            if (oError) {
                oLogInfo.removeChild(oError);
                oError = null;
                $('#logInfo').fadeOut();
                $('#imgThumb').fadeOut();
            }
            oError = doc.createTextNode(err);
            oLogInfo.appendChild(oError);
            $('#logInfo').fadeIn();
        }
    }, false);
    oFileReader.addEventListener('load', function (e) {
        oImage.src = e.target.result;
    }, false);
    oImage.addEventListener('load', function () {
        if (oCanvas) {
            oCanvas = null;
            oContext = null;
            $('#imgThumb').fadeOut();
        }
        var oCanvas = doc.getElementById('imgThumb');
        var oContext = oCanvas.getContext('2d');
        var nWidth = (this.width > 500) ? this.width / 4 : this.width;
        var nHeight = (this.height > 500) ? this.height / 4 : this.height;
        oCanvas.setAttribute('width', nWidth);
        oCanvas.setAttribute('height', nHeight);
        oContext.drawImage(this, 0, 0, nWidth, nHeight);
        $('#imgThumb').fadeIn();
    }, false);
})(document);

Google maps Marker Label with multiple characters

You can change easy marker label css without use any extra plugin.

var marker = new google.maps.Marker({
        position: this.overlay_text,
        draggable: true,
        icon: '',
        label: {
          text: this.overlay_field_text,
          color: '#fff',
          fontSize: '20px',
          fontWeight: 'bold',
          fontFamily: 'custom-label'
        },
        map:map
      });
      marker.setMap(map);

$("[style*='custom-label']").css({'text-shadow': '2px 2px #000'})

How to add two edit text fields in an alert dialog

Check the following code. It shows 2 edit text fields programmatically without any layout xml. Change 'this' to 'getActivity()' if you use it in a fragment.

The tricky thing is we have to set the second text field's input type after creating alert dialog, otherwise, the second text field shows texts instead of dots.

    public void showInput() {
        OnFocusChangeListener onFocusChangeListener = new OnFocusChangeListener() {
            @Override
            public void onFocusChange(final View v, boolean hasFocus) {
                if (hasFocus) {
                    // Must use message queue to show keyboard
                    v.post(new Runnable() {
                        @Override
                        public void run() {
                            InputMethodManager inputMethodManager= (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                            inputMethodManager.showSoftInput(v, 0);
                        }
                    });
                }
            }
        };

        final EditText editTextName = new EditText(this);
        editTextName.setHint("Name");
        editTextName.setFocusable(true);
        editTextName.setClickable(true);
        editTextName.setFocusableInTouchMode(true);
        editTextName.setSelectAllOnFocus(true);
        editTextName.setSingleLine(true);
        editTextName.setImeOptions(EditorInfo.IME_ACTION_NEXT);
        editTextName.setOnFocusChangeListener(onFocusChangeListener);

        final EditText editTextPassword = new EditText(this);
        editTextPassword.setHint("Password");
        editTextPassword.setFocusable(true);
        editTextPassword.setClickable(true);
        editTextPassword.setFocusableInTouchMode(true);
        editTextPassword.setSelectAllOnFocus(true);
        editTextPassword.setSingleLine(true);
        editTextPassword.setImeOptions(EditorInfo.IME_ACTION_DONE);
        editTextPassword.setOnFocusChangeListener(onFocusChangeListener);

        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.addView(editTextName);
        linearLayout.addView(editTextPassword);

        DialogInterface.OnClickListener alertDialogClickListener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which){
                case DialogInterface.BUTTON_POSITIVE:
                    // Done button clicked
                    break;
                case DialogInterface.BUTTON_NEGATIVE:
                    // Cancel button clicked
                    break;
                }
            }
        };
        final AlertDialog alertDialog = (new AlertDialog.Builder(this)).setMessage("Please enter name and password")
                .setView(linearLayout)
                .setPositiveButton("Done", alertDialogClickListener)
                .setNegativeButton("Cancel", alertDialogClickListener)
                .create();

        editTextName.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                editTextPassword.requestFocus(); // Press Return to focus next one
                return false;
            }
        });
        editTextPassword.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                // Press Return to invoke positive button on alertDialog.
                alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).performClick();
                return false;
            }
        });

        // Must set password mode after creating alert dialog.
        editTextPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
        editTextPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        alertDialog.show();
    }

Delete an element from a dictionary

… how can I delete an item from a dictionary to return a copy (i.e., not modifying the original)?

A dict is the wrong data structure to use for this.

Sure, copying the dict and popping from the copy works, and so does building a new dict with a comprehension, but all that copying takes time—you've replaced a constant-time operation with a linear-time one. And all those copies alive at once take space—linear space per copy.

Other data structures, like hash array mapped tries, are designed for exactly this kind of use case: adding or removing an element returns a copy in logarithmic time, sharing most of its storage with the original.1

Of course there are some downsides. Performance is logarithmic rather than constant (although with a large base, usually 32-128). And, while you can make the non-mutating API identical to dict, the "mutating" API is obviously different. And, most of all, there's no HAMT batteries included with Python.2

The pyrsistent library is a pretty solid implementation of HAMT-based dict-replacements (and various other types) for Python. It even has a nifty evolver API for porting existing mutating code to persistent code as smoothly as possible. But if you want to be explicit about returning copies rather than mutating, you just use it like this:

>>> from pyrsistent import m
>>> d1 = m(a=1, b=2)
>>> d2 = d1.set('c', 3)
>>> d3 = d1.remove('a')
>>> d1
pmap({'a': 1, 'b': 2})
>>> d2
pmap({'c': 3, 'a': 1, 'b': 2})
>>> d3
pmap({'b': 2})

That d3 = d1.remove('a') is exactly what the question is asking for.

If you've got mutable data structures like dict and list embedded in the pmap, you'll still have aliasing issues—you can only fix that by going immutable all the way down, embedding pmaps and pvectors.


1. HAMTs have also become popular in languages like Scala, Clojure, Haskell because they play very nicely with lock-free programming and software transactional memory, but neither of those is very relevant in Python.

2. In fact, there is an HAMT in the stdlib, used in the implementation of contextvars. The earlier withdrawn PEP explains why. But this is a hidden implementation detail of the library, not a public collection type.

python: NameError:global name '...‘ is not defined

You need to call self.a() to invoke a from b. a is not a global function, it is a method on the class.

You may want to read through the Python tutorial on classes some more to get the finer details down.

Python integer incrementing with ++

Simply put, the ++ and -- operators don't exist in Python because they wouldn't be operators, they would have to be statements. All namespace modification in Python is a statement, for simplicity and consistency. That's one of the design decisions. And because integers are immutable, the only way to 'change' a variable is by reassigning it.

Fortunately we have wonderful tools for the use-cases of ++ and -- in other languages, like enumerate() and itertools.count().

jQuery UI themes and HTML tables

I've got a one liner to make HTML Tables look BootStrapped:

<table class="table table-striped table-bordered table-hover">

The theme suits other controls and it supports alternate row highlighting.

Remove a specific character using awk or sed

Use sed's substitution: sed 's/"//g'

s/X/Y/ replaces X with Y.

g means all occurrences should be replaced, not just the first one.

How to fill Matrix with zeros in OpenCV?

You can use this to fill zeroes in a Mat object already containing data:

image1 = Scalar::all(0);

For eg, if you use it this way:

Mat image,image1;
image = imread("IMG_20160107_185956.jpg", CV_LOAD_IMAGE_COLOR);   // Read the file

if(! image.data )                              // Check for invalid input
{
    cout <<  "Could not open or find the image" << std::endl ;
    return -1;
}
cvtColor(image,image1,CV_BGR2GRAY);
image1 = Scalar::all(0);

It will work fine. But you cannot use this for uninitialised Mat. For that you can go for other options mentioned in above answers, like

Mat drawing = Mat::zeros( image.size(), CV_8UC3 );

How to move/rename a file using an Ansible task on a remote system

Bruce wasn't attempting to stat the destination to check whether or not to move the file if it was already there; he was making sure the file to be moved actually existed before attempting the mv.

If your interest, like Tom's, is to only move if the file doesn't already exist, I think we should still integrate Bruce's check into the mix:

- name: stat foo
  stat: path=/path/to/foo
  register: foo_stat

- name: Move foo to bar
  command: creates="path/to/bar" mv /path/to/foo /path/to/bar
  when: foo_stat.stat.exists

What is the difference between single-quoted and double-quoted strings in PHP?

One thing:

It is very important to note that the line with the closing identifier of Heredoc must contain no other characters, except a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon.

Example:

   $str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;

What is a simple C or C++ TCP server and client example?

Although many year ago, clsocket seems a really nice small cross-platform (Windows, Linux, Mac OSX): https://github.com/DFHack/clsocket

Gmail Error :The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required

I have faced the same problem. It happens when you turn on 2 Step Verification (MFA). Just Turn off 2 Step Verification and your problem should be solved.

What's the "average" requests per second for a production web application?

personally, I like both analysis done every time....requests/second and average time/request and love seeing the max request time as well on top of that. it is easy to flip if you have 61 requests/second, you can then just flip it to 1000ms / 61 requests.

To answer your question, we have been doing a huge load test ourselves and find it ranges on various amazon hardware we use(best value was the 32 bit medium cpu when it came down to $$ / event / second) and our requests / seconds ranged from 29 requests / second / node up to 150 requests/second/node.

Giving better hardware of course gives better results but not the best ROI. Anyways, this post was great as I was looking for some parallels to see if my numbers where in the ballpark and shared mine as well in case someone else is looking. Mine is purely loaded as high as I can go.

NOTE: thanks to requests/second analysis(not ms/request) we found a major linux issue that we are trying to resolve where linux(we tested a server in C and java) freezes all the calls into socket libraries when under too much load which seems very odd. The full post can be found here actually.... http://ubuntuforums.org/showthread.php?p=11202389

We are still trying to resolve that as it gives us a huge performance boost in that our test goes from 2 minutes 42 seconds to 1 minute 35 seconds when this is fixed so we see a 33% performancce improvement....not to mention, the worse the DoS attack is the longer these pauses are so that all cpus drop to zero and stop processing...in my opinion server processing should continue in the face of a DoS but for some reason, it freezes up every once in a while during the Dos sometimes up to 30 seconds!!!

ADDITION: We found out it was actually a jdk race condition bug....hard to isolate on big clusters but when we ran 1 server 1 data node but 10 of those, we could reproduce it every time then and just looked at the server/datanode it occurred on. Switching the jdk to an earlier release fixed the issue. We were on jdk1.6.0_26 I believe.

Select last N rows from MySQL

You can do it with a sub-query:

SELECT * FROM (
    SELECT * FROM table ORDER BY id DESC LIMIT 50
) sub
ORDER BY id ASC

This will select the last 50 rows from table, and then order them in ascending order.

How to remove a key from Hash and get the remaining hash in Ruby/Rails?

If you want to use pure Ruby (no Rails), don't want to create extension methods (maybe you need this only in one or two places and don't want to pollute namespace with tons of methods) and don't want to edit hash in place (i.e., you're fan of functional programming like me), you can 'select':

>> x = {:a => 1, :b => 2, :c => 3}
=> {:a=>1, :b=>2, :c=>3}
>> x.select{|x| x != :a}
=> {:b=>2, :c=>3}
>> x.select{|x| ![:a, :b].include?(x)}
=> {:c=>3}
>> x
=> {:a=>1, :b=>2, :c=>3}

SignalR Console app example

The Self-Host now uses Owin. Checkout http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-signalr-20-self-host to setup the server. It's compatible with the client code above.

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

Just check if you have set the buffering option to false (by default its true). For response.redirect to work,

  1. Buffering should be true,
  2. you should not have sent more data using response.write which exceeds the default buffer size (in which case it will flush itself causing the headers to be sent) therefore disallowing you to redirect.

Backup a single table with its data from a database in sql server 2008

select * into mytable_backup from mytable

Makes a copy of table mytable, and every row in it, called mytable_backup.

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

just use style attribute with height and width option

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

Drop all data in a pandas dataframe

You need to pass the labels to be dropped.

df.drop(df.index, inplace=True)

By default, it operates on axis=0.

You can achieve the same with

df.iloc[0:0]

which is much more efficient.

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

By specifying the column as VARCHAR(500) you've set an explicit 500 character limit. You might not have done this yourself explicitly, but Django has done it for you somewhere. Telling you where is hard when you haven't shown your model, the full error text, or the query that produced the error.

If you don't want one, use an unqualified VARCHAR, or use the TEXT type.

varchar and text are limited in length only by the system limits on column size - about 1GB - and by your memory. However, adding a length-qualifier to varchar sets a smaller limit manually. All of the following are largely equivalent:

column_name VARCHAR(500)

column_name VARCHAR CHECK (length(column_name) <= 500) 

column_name TEXT CHECK (length(column_name) <= 500) 

The only differences are in how database metadata is reported and which SQLSTATE is raised when the constraint is violated.

The length constraint is not generally obeyed in prepared statement parameters, function calls, etc, as shown:

regress=> \x
Expanded display is on.
regress=> PREPARE t2(varchar(500)) AS SELECT $1;
PREPARE
regress=> EXECUTE t2( repeat('x',601) );
-[ RECORD 1 ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
?column? | xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

and in explicit casts it result in truncation:

regress=> SELECT repeat('x',501)::varchar(1);
-[ RECORD 1 ]
repeat | x

so I think you are using a VARCHAR(500) column, and you're looking at the wrong table or wrong instance of the database.

BLOB to String, SQL Server

Can you try this:

select convert(nvarchar(max),convert(varbinary(max),blob_column)) from table_name

What does from __future__ import absolute_import actually do?

The changelog is sloppily worded. from __future__ import absolute_import does not care about whether something is part of the standard library, and import string will not always give you the standard-library module with absolute imports on.

from __future__ import absolute_import means that if you import string, Python will always look for a top-level string module, rather than current_package.string. However, it does not affect the logic Python uses to decide what file is the string module. When you do

python pkg/script.py

pkg/script.py doesn't look like part of a package to Python. Following the normal procedures, the pkg directory is added to the path, and all .py files in the pkg directory look like top-level modules. import string finds pkg/string.py not because it's doing a relative import, but because pkg/string.py appears to be the top-level module string. The fact that this isn't the standard-library string module doesn't come up.

To run the file as part of the pkg package, you could do

python -m pkg.script

In this case, the pkg directory will not be added to the path. However, the current directory will be added to the path.

You can also add some boilerplate to pkg/script.py to make Python treat it as part of the pkg package even when run as a file:

if __name__ == '__main__' and __package__ is None:
    __package__ = 'pkg'

However, this won't affect sys.path. You'll need some additional handling to remove the pkg directory from the path, and if pkg's parent directory isn't on the path, you'll need to stick that on the path too.

Maximum concurrent Socket.IO connections

I tried to use socket.io on AWS, I can at most keep around 600 connections stable.

And I found out it is because socket.io used long polling first and upgraded to websocket later.

after I set the config to use websocket only, I can keep around 9000 connections.

Set this config at client side:

const socket = require('socket.io-client')
const conn = socket(host, { upgrade: false, transports: ['websocket'] })

Automatic vertical scroll bar in WPF TextBlock?

Dont know if someone else has this problem but wrapping my TextBlock into a ScrollViewer somewhow messed up my UI - as a simple workaround I figured out that replacing the TextBlock by a TextBox like this one

<TextBox  Name="textBlock" SelectionBrush="Transparent" Cursor="Arrow" IsReadOnly="True" Text="My Text" VerticalScrollBarVisibility="Auto">

creates a TextBox that looks and behaves like a TextBlock with a scrollbar (and you can do it all in the designer).

Oracle PL/SQL : remove "space characters" from a string

select regexp_replace('This is a test   ' || chr(9) || ' foo ', '[[:space:]]', '') from dual;

REGEXP_REPLACE
--------------
Thisisatestfoo

Virtual Memory Usage from Java under Linux, too much memory used

This has been a long-standing complaint with Java, but it's largely meaningless, and usually based on looking at the wrong information. The usual phrasing is something like "Hello World on Java takes 10 megabytes! Why does it need that?" Well, here's a way to make Hello World on a 64-bit JVM claim to take over 4 gigabytes ... at least by one form of measurement.

java -Xms1024m -Xmx4096m com.example.Hello

Different Ways to Measure Memory

On Linux, the top command gives you several different numbers for memory. Here's what it says about the Hello World example:

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 2120 kgregory  20   0 4373m  15m 7152 S    0  0.2   0:00.10 java
  • VIRT is the virtual memory space: the sum of everything in the virtual memory map (see below). It is largely meaningless, except when it isn't (see below).
  • RES is the resident set size: the number of pages that are currently resident in RAM. In almost all cases, this is the only number that you should use when saying "too big." But it's still not a very good number, especially when talking about Java.
  • SHR is the amount of resident memory that is shared with other processes. For a Java process, this is typically limited to shared libraries and memory-mapped JARfiles. In this example, I only had one Java process running, so I suspect that the 7k is a result of libraries used by the OS.
  • SWAP isn't turned on by default, and isn't shown here. It indicates the amount of virtual memory that is currently resident on disk, whether or not it's actually in the swap space. The OS is very good about keeping active pages in RAM, and the only cures for swapping are (1) buy more memory, or (2) reduce the number of processes, so it's best to ignore this number.

The situation for Windows Task Manager is a bit more complicated. Under Windows XP, there are "Memory Usage" and "Virtual Memory Size" columns, but the official documentation is silent on what they mean. Windows Vista and Windows 7 add more columns, and they're actually documented. Of these, the "Working Set" measurement is the most useful; it roughly corresponds to the sum of RES and SHR on Linux.

Understanding the Virtual Memory Map

The virtual memory consumed by a process is the total of everything that's in the process memory map. This includes data (eg, the Java heap), but also all of the shared libraries and memory-mapped files used by the program. On Linux, you can use the pmap command to see all of the things mapped into the process space (from here on out I'm only going to refer to Linux, because it's what I use; I'm sure there are equivalent tools for Windows). Here's an excerpt from the memory map of the "Hello World" program; the entire memory map is over 100 lines long, and it's not unusual to have a thousand-line list.

0000000040000000     36K r-x--  /usr/local/java/jdk-1.6-x64/bin/java
0000000040108000      8K rwx--  /usr/local/java/jdk-1.6-x64/bin/java
0000000040eba000    676K rwx--    [ anon ]
00000006fae00000  21248K rwx--    [ anon ]
00000006fc2c0000  62720K rwx--    [ anon ]
0000000700000000 699072K rwx--    [ anon ]
000000072aab0000 2097152K rwx--    [ anon ]
00000007aaab0000 349504K rwx--    [ anon ]
00000007c0000000 1048576K rwx--    [ anon ]
...
00007fa1ed00d000   1652K r-xs-  /usr/local/java/jdk-1.6-x64/jre/lib/rt.jar
...
00007fa1ed1d3000   1024K rwx--    [ anon ]
00007fa1ed2d3000      4K -----    [ anon ]
00007fa1ed2d4000   1024K rwx--    [ anon ]
00007fa1ed3d4000      4K -----    [ anon ]
...
00007fa1f20d3000    164K r-x--  /usr/local/java/jdk-1.6-x64/jre/lib/amd64/libjava.so
00007fa1f20fc000   1020K -----  /usr/local/java/jdk-1.6-x64/jre/lib/amd64/libjava.so
00007fa1f21fb000     28K rwx--  /usr/local/java/jdk-1.6-x64/jre/lib/amd64/libjava.so
...
00007fa1f34aa000   1576K r-x--  /lib/x86_64-linux-gnu/libc-2.13.so
00007fa1f3634000   2044K -----  /lib/x86_64-linux-gnu/libc-2.13.so
00007fa1f3833000     16K r-x--  /lib/x86_64-linux-gnu/libc-2.13.so
00007fa1f3837000      4K rwx--  /lib/x86_64-linux-gnu/libc-2.13.so
...

A quick explanation of the format: each row starts with the virtual memory address of the segment. This is followed by the segment size, permissions, and the source of the segment. This last item is either a file or "anon", which indicates a block of memory allocated via mmap.

Starting from the top, we have

  • The JVM loader (ie, the program that gets run when you type java). This is very small; all it does is load in the shared libraries where the real JVM code is stored.
  • A bunch of anon blocks holding the Java heap and internal data. This is a Sun JVM, so the heap is broken into multiple generations, each of which is its own memory block. Note that the JVM allocates virtual memory space based on the -Xmx value; this allows it to have a contiguous heap. The -Xms value is used internally to say how much of the heap is "in use" when the program starts, and to trigger garbage collection as that limit is approached.
  • A memory-mapped JARfile, in this case the file that holds the "JDK classes." When you memory-map a JAR, you can access the files within it very efficiently (versus reading it from the start each time). The Sun JVM will memory-map all JARs on the classpath; if your application code needs to access a JAR, you can also memory-map it.
  • Per-thread data for two threads. The 1M block is the thread stack. I didn't have a good explanation for the 4k block, but @ericsoe identified it as a "guard block": it does not have read/write permissions, so will cause a segment fault if accessed, and the JVM catches that and translates it to a StackOverFlowError. For a real app, you will see dozens if not hundreds of these entries repeated through the memory map.
  • One of the shared libraries that holds the actual JVM code. There are several of these.
  • The shared library for the C standard library. This is just one of many things that the JVM loads that are not strictly part of Java.

The shared libraries are particularly interesting: each shared library has at least two segments: a read-only segment containing the library code, and a read-write segment that contains global per-process data for the library (I don't know what the segment with no permissions is; I've only seen it on x64 Linux). The read-only portion of the library can be shared between all processes that use the library; for example, libc has 1.5M of virtual memory space that can be shared.

When is Virtual Memory Size Important?

The virtual memory map contains a lot of stuff. Some of it is read-only, some of it is shared, and some of it is allocated but never touched (eg, almost all of the 4Gb of heap in this example). But the operating system is smart enough to only load what it needs, so the virtual memory size is largely irrelevant.

Where virtual memory size is important is if you're running on a 32-bit operating system, where you can only allocate 2Gb (or, in some cases, 3Gb) of process address space. In that case you're dealing with a scarce resource, and might have to make tradeoffs, such as reducing your heap size in order to memory-map a large file or create lots of threads.

But, given that 64-bit machines are ubiquitous, I don't think it will be long before Virtual Memory Size is a completely irrelevant statistic.

When is Resident Set Size Important?

Resident Set size is that portion of the virtual memory space that is actually in RAM. If your RSS grows to be a significant portion of your total physical memory, it might be time to start worrying. If your RSS grows to take up all your physical memory, and your system starts swapping, it's well past time to start worrying.

But RSS is also misleading, especially on a lightly loaded machine. The operating system doesn't expend a lot of effort to reclaiming the pages used by a process. There's little benefit to be gained by doing so, and the potential for an expensive page fault if the process touches the page in the future. As a result, the RSS statistic may include lots of pages that aren't in active use.

Bottom Line

Unless you're swapping, don't get overly concerned about what the various memory statistics are telling you. With the caveat that an ever-growing RSS may indicate some sort of memory leak.

With a Java program, it's far more important to pay attention to what's happening in the heap. The total amount of space consumed is important, and there are some steps that you can take to reduce that. More important is the amount of time that you spend in garbage collection, and which parts of the heap are getting collected.

Accessing the disk (ie, a database) is expensive, and memory is cheap. If you can trade one for the other, do so.

Could not find com.google.android.gms:play-services:3.1.59 3.2.25 4.0.30 4.1.32 4.2.40 4.2.42 4.3.23 4.4.52 5.0.77 5.0.89 5.2.08 6.1.11 6.1.71 6.5.87

I had the same problem because I had:

compile 'com.google.android.gms:play-services:5.2.8'

and I solved changing the version numbers for a '+'. so the lines has to be:

compile 'com.google.android.gms:play-services:+'

Search of table names

select name
  from DBname.sys.tables
 where name like '%xxx%'
   and is_ms_shipped = 0; -- << comment out if you really want to see them

How to parse JSON and access results

If your $result variable is a string json like, you must use json_decode function to parse it as an object or array:

$result = '{"Cancelled":false,"MessageID":"402f481b-c420-481f-b129-7b2d8ce7cf0a","Queued":false,"SMSError":2,"SMSIncomingMessages":null,"Sent":false,"SentDateTime":"\/Date(-62135578800000-0500)\/"}';
$json = json_decode($result, true);
print_r($json);

OUTPUT

Array
(
    [Cancelled] => 
    [MessageID] => 402f481b-c420-481f-b129-7b2d8ce7cf0a
    [Queued] => 
    [SMSError] => 2
    [SMSIncomingMessages] => 
    [Sent] => 
    [SentDateTime] => /Date(-62135578800000-0500)/
)

Now you can work with $json variable as an array:

echo $json['MessageID'];
echo $json['SMSError'];
// other stuff

References:

X close button only using css

You can use svg.

_x000D_
_x000D_
<svg viewPort="0 0 12 12" version="1.1"_x000D_
     xmlns="http://www.w3.org/2000/svg">_x000D_
    <line x1="1" y1="11" _x000D_
          x2="11" y2="1" _x000D_
          stroke="black" _x000D_
          stroke-width="2"/>_x000D_
    <line x1="1" y1="1" _x000D_
          x2="11" y2="11" _x000D_
          stroke="black" _x000D_
          stroke-width="2"/>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

Input Type image submit form value?

Some browsers (IIRC it is just some versions of Internet Explorer) only send the co-ordinates of the image map (in name.x and name.y) and ignore the value. This is a bug.

The workarounds are to either:

  • Have only one submit button and use a hidden input to sent the value
  • Use regular submit buttons instead of image maps
  • Use unique names instead of values and check for the presence of name.x / name.y

Automated way to convert XML files to SQL database?

If there is XML file with 2 different tables then will:

LOAD XML LOCAL INFILE 'table1.xml' INTO TABLE table1 
LOAD XML LOCAL INFILE 'table1.xml' INTO TABLE table2

work

Necessary to add link tag for favicon.ico?

To choose a different location or file type (e.g. PNG or SVG) for the favicon:
One reason can be that you want to have the icon in a specific location, perhaps in the images folder or something alike. For example:

<link rel="icon" href="_/img/favicon.png">

This diferent location may even be a CDN, just like SO seems to do with <link rel="shortcut icon" href="http://cdn.sstatic.net/stackoverflow/img/favicon.ico">.

To learn more about using other file types like PNG check out this question.

For cache busting purposes:
Add a query string to the path for cache-busting purposes:

<link rel="icon" href="/favicon.ico?v=1.1"> 

Favicons are very heavily cached and this a great way to ensure a refresh.


Footnote about default location:
As far as the first bit of the question: all modern browsers would detect a favicon at the default location, so that's not a reason to use a link for it.


Footnote about rel="icon":
As indicated by @Semanino's answer, using rel="shortcut icon" is an old technique which was required by older versions of Internet Explorer, but in most cases can be replaced by the more correct rel="icon" instruction. The article @Semanino based this on properly links to the appropriate spec which shows a rel value of shortcut isn't a valid option.

gdb: how to print the current line or find the current line number?

All the answers above are correct, What I prefer is to use tui mode (ctrl+X A or 'tui enable') which shows your location and the function in a separate window which is very helpful for the users. Hope that helps too.

Jinja2 template not rendering if-elif-else statement properly

You are testing if the values of the variables error and Already are present in RepoOutput[RepoName.index(repo)]. If these variables don't exist then an undefined object is used.

Both of your if and elif tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].

I think you wanted to test if certain strings are in the value instead:

{% if "error" in RepoOutput[RepoName.index(repo)] %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
    <td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>

Other corrections I made:

  • Used {% elif ... %} instead of {$ elif ... %}.
  • moved the </tr> tag out of the if conditional structure, it needs to be there always.
  • put quotes around the id attribute

Note that most likely you want to use a class attribute instead here, not an id, the latter must have a value that must be unique across your HTML document.

Personally, I'd set the class value here and reduce the duplication a little:

{% if "Already" in RepoOutput[RepoName.index(repo)] %}
    {% set row_class = "good" %}
{% else %}
    {% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>

How to deal with persistent storage (e.g. databases) in Docker

Use Persistent Volume Claim (PVC) from Kubernetes, which is a Docker container management and scheduling tool:

Persistent Volumes

The advantages of using Kubernetes for this purpose are that:

  • You can use any storage like NFS or other storage and even when the node is down, the storage need not be.
  • Moreover the data in such volumes can be configured to be retained even after the container itself is destroyed - so that it can be reclaimed, if necessary, by another container.

Letter Count on a string

One problem is that you are using count to refer both to the position in the word that you are checking, and the number of char you have seen, and you are using char to refer both to the input character you are checking, and the current character in the string. Use separate variables instead.

Also, move the return statement outside the loop; otherwise you will always return after checking the first character.

Finally, you only need one loop to iterate over the string. Get rid of the outer while loop and you will not need to track the position in the string.

Taking these suggestions, your code would look like this:

def count_letters(word, char):
  count = 0
  for c in word:
    if char == c:
      count += 1
  return count

How can I manually generate a .pyc file from a .py file

It's been a while since I last used Python, but I believe you can use py_compile:

import py_compile
py_compile.compile("file.py")

Make an HTTP request with android

For me, the easiest way is using library called Retrofit2

We just need to create an Interface that contain our request method, parameters, and also we can make custom header for each request :

    public interface MyService {

      @GET("users/{user}/repos")
      Call<List<Repo>> listRepos(@Path("user") String user);

      @GET("user")
      Call<UserDetails> getUserDetails(@Header("Authorization") String   credentials);

      @POST("users/new")
      Call<User> createUser(@Body User user);

      @FormUrlEncoded
      @POST("user/edit")
      Call<User> updateUser(@Field("first_name") String first, 
                            @Field("last_name") String last);

      @Multipart
      @PUT("user/photo")
      Call<User> updateUser(@Part("photo") RequestBody photo, 
                            @Part("description") RequestBody description);

      @Headers({
        "Accept: application/vnd.github.v3.full+json",
        "User-Agent: Retrofit-Sample-App"
      })
      @GET("users/{username}")
      Call<User> getUser(@Path("username") String username);    

    }

And the best is, we can do it asynchronously easily using enqueue method

Uncaught ReferenceError: $ is not defined error in jQuery

The MVC 5 stock install puts javascript references in the _Layout.cshtml file that is shared in all pages. So the javascript files were below the main content and document.ready function where all my $'s were.

BOTTOM PART OF _Layout.cshtml:

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

</body>
</html>

I moved them above the @RenderBody() and all was fine.

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

</body>
</html>

Get Folder Size from Windows Command Line

Easiest method to get just the total size is powershell, but still is limited by fact that pathnames longer than 260 characters are not included in the total

How to use relative paths without including the context root name?

Just use <c:url>-tag with an application context relative path.

When the value parameter starts with an /, then the tag will treat it as an application relative url, and will add the application-name to the url. Example:

jsp:

<c:url value="/templates/style/main.css" var="mainCssUrl" />`
<link rel="stylesheet" href="${mainCssUrl}" />
...
<c:url value="/home" var="homeUrl" />`
<a href="${homeUrl}">home link</a>

will become this html, with an domain relative url:

<link rel="stylesheet" href="/AppName/templates/style/main.css" />
...
<a href="/AppName/home">home link</a>

DateTime to javascript date

You can try this in your Action:

return DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");

And this in your Ajax success:

success: function (resultDateString) {
    var date = new Date(resultDateString);
}

Or this in your View: (Javascript plus C#)

var date = new Date('@DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")');

What does the question mark in Java generics' type parameter mean?

The question mark is used to define wildcards. Checkout the Oracle documentation about them: http://docs.oracle.com/javase/tutorial/java/generics/wildcards.html

Is there a Java API that can create rich Word documents?

I have developed pure XML based word files in the past. I used .NET, but the language should not matter since it's truely XML. It was not the easiest thing to do (had a project that required it a couple years ago.) These do only work in Word 2007 or above - but all you need is Microsoft's white paper that describe what each tag does. You can accomplish all you want with the tags the same way as if you were using Word (of course a little more painful initially.)

How can I check whether a numpy array is empty or not?

One caveat, though. Note that np.array(None).size returns 1! This is because a.size is equivalent to np.prod(a.shape), np.array(None).shape is (), and an empty product is 1.

>>> import numpy as np
>>> np.array(None).size
1
>>> np.array(None).shape
()
>>> np.prod(())
1.0

Therefore, I use the following to test if a numpy array has elements:

>>> def elements(array):
    ...     return array.ndim and array.size

>>> elements(np.array(None))
0
>>> elements(np.array([]))
0
>>> elements(np.zeros((2,3,4)))
24

How to include CSS file in Symfony 2 and Twig?

The other answers are valid, but the Official Symfony Best Practices guide suggests using the web/ folder to store all assets, instead of different bundles.

Scattering your web assets across tens of different bundles makes it more difficult to manage them. Your designers' lives will be much easier if all the application assets are in one location.

Templates also benefit from centralizing your assets, because the links are much more concise[...]

I'd add to this by suggesting that you only put micro-assets within micro-bundles, such as a few lines of styles only required for a button in a button bundle, for example.

General guidelines to avoid memory leaks in C++

I thoroughly endorse all the advice about RAII and smart pointers, but I'd also like to add a slightly higher-level tip: the easiest memory to manage is the memory you never allocated. Unlike languages like C# and Java, where pretty much everything is a reference, in C++ you should put objects on the stack whenever you can. As I've see several people (including Dr Stroustrup) point out, the main reason why garbage collection has never been popular in C++ is that well-written C++ doesn't produce much garbage in the first place.

Don't write

Object* x = new Object;

or even

shared_ptr<Object> x(new Object);

when you can just write

Object x;

Java executors: how to be notified, without blocking, when a task completes?

If you want to make sure that no tasks will run at the same time then use a SingleThreadedExecutor. The tasks will be processed in the order the are submitted. You don't even need to hold the tasks, just submit them to the exec.

Setting action for back button in navigation controller

You can try accessing the NavigationBars Right Button item and set its selector property...heres a reference UIBarButtonItem reference, another thing if this doenst work that will def work is, set the right button item of the nav bar to a custom UIBarButtonItem that you create and set its selector...hope this helps

iOS: Modal ViewController with transparent background

Swift 4.2

guard let someVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "someVC") as? someVC else {
    return
}
someVC.modalPresentationStyle = .overCurrentContext

present(someVC, animated: true, completion: nil)

HTML Entity Decode

Injecting untrusted HTML into the page is dangerous as explained in How to decode HTML entities using jQuery?.

One alternative is to use a JavaScript-only implementation of PHP's html_entity_decode (from http://phpjs.org/functions/html_entity_decode:424). The example would then be something like:

var varTitle = html_entity_decode("Chris&apos; corner");

What is the equivalent to getch() & getche() in Linux?

You can use the curses.h library in linux as mentioned in the other answer.

You can install it in Ubuntu by:

sudo apt-get update

sudo apt-get install ncurses-dev

I took the installation part from here.

Revert to Eclipse default settings

I went to My workspace

directory/.metadata/.plugins/org.eclipse.core.runtime/.settings/

and then deleted all recently added files !!

Create Git branch with current changes

Like stated in this question: Git: Create a branch from unstagged/uncommited changes on master: stash is not necessary.

Just use:

git checkout -b topic/newbranch

Any uncommitted work will be taken along to the new branch.

If you try to push you will get the following message

fatal: The current branch feature/NEWBRANCH has no upstream branch. To push the current branch and set the remote as upstream, use

git push --set-upstream origin feature/feature/NEWBRANCH

Just do as suggested to create the branch remotely:

git push --set-upstream origin feature/feature/NEWBRANCH

Best database field type for a URL

Most web servers have a URL length limit (which is why there is an error code for "URI too long"), meaning there is a practical upper size. Find the default length limit for the most popular web servers, and use the largest of them as the field's maximum size; it should be more than enough.

How to install popper.js with Bootstrap 4?

I had problems installing it Bootstrap as well, so I did:

Install popper.js: npm install popper.js@^1.12.3 --save

Install jQuery: npm install [email protected] --save

Then I had a high severity vulnerability message when installing [email protected] and got this message:

run npm audit fix to fix them, or npm audit for details

So I did npm audit fix, and after another npm audit fix --force it successfully installed!

Best way to copy a database (SQL Server 2008)

Easiest way is actually a script.

Run this on production:

USE MASTER;

BACKUP DATABASE [MyDatabase]
TO DISK = 'C:\temp\MyDatabase1.bak' -- some writeable folder. 
WITH COPY_ONLY

This one command makes a complete backup copy of the database onto a single file, without interfering with production availability or backup schedule, etc.

To restore, just run this on your dev or test SQL Server:

USE MASTER;

RESTORE DATABASE [MyDatabase]
FROM DISK = 'C:\temp\MyDatabase1.bak'
WITH
MOVE 'MyDatabase'   TO 'C:\Sql\MyDatabase.mdf', -- or wherever these live on target
MOVE 'MyDatabase_log'   TO 'C:\Sql\MyDatabase_log.ldf',
REPLACE, RECOVERY

Then save these scripts on each server. One-click convenience.

Edit:
if you get an error when restoring that the logical names don't match, you can get them like this:

RESTORE FILELISTONLY
FROM disk = 'C:\temp\MyDatabaseName1.bak'

If you use SQL Server logins (not windows authentication) you can run this after restoring each time (on the dev/test machine):

use MyDatabaseName;
sp_change_users_login 'Auto_Fix', 'userloginname', null, 'userpassword';

Getting Index of an item in an arraylist;

I think a for-loop should be a valid solution :

    public int getIndexByname(String pName)
    {
        for(AuctionItem _item : *yourArray*)
        {
            if(_item.getName().equals(pName))
                return *yourarray*.indexOf(_item)
        }
        return -1;
    }

This certificate has an invalid issuer Apple Push Services

This is not actually a development issue. It happens due to expiration of the Apple Worldwide Developer Relations Intermediate Certificate issued by Apple Worldwide Developer Relations Certificate Authority. WWDRCA issues the certificate to sign your software for Apple devices, allowing our systems to confirm that your software is delivered to users as intended and has not been modified.

To resolve this issue, you have to follow the below steps:

  1. Open Keychain Access
  2. Go to View -> Show Expired Certificates

Enter image description here

  1. Go to System in Keychain Enter image description here

  2. Here you find that "Apple Worldwide Developer Relations Certificate Authority" is marked as expired. So delete it. Also check under Login Tab and delete expired WWDRCA.

  3. Download new WWDR Intermediate Certificate from here(The renewed Apple Worldwide Developer Relations Certification Intermediate Certificate will expire on February 7, 2023).

  4. Install it by double clicking on it.

If you still face any issue with your iOS apps, Mac apps, Safari extensions, Apple Wallet and Safari push notifications, then please follow this link of expiration.

The Apple Worldwide Developer Relations Certification Intermediate Certificate expires soon and we've issued a renewed certificate that must be included when signing all new Apple Wallet Passes, push packages for Safari Push Notifications, and Safari Extensions starting February 14, 2016.

While most developers and users will not be affected by the certificate change, we recommend that all developers download and install the renewed certificate on their development systems and servers as a best practice. All apps will remain available on the App Store for iOS, Mac, and Apple TV.

Difference between core and processor

I have read all answers, but this link was more clear explanation for me about difference between CPU(Processor) and Core. So I'm leaving here some notes from there.

The main difference between CPU and Core is that the CPU is an electronic circuit inside the computer that carries out instruction to perform arithmetic, logical, control and input/output operations while the core is an execution unit inside the CPU that receives and executes instructions.

enter image description here

jQuery's .on() method combined with the submit event

I had a problem with the same symtoms. In my case, it turned out that my submit function was missing the "return" statement.

For example:

 $("#id_form").on("submit", function(){
   //Code: Action (like ajax...)
   return false;
 })

Using Excel OleDb to get sheet names IN SHEET ORDER

Can you not just loop through the sheets from 0 to Count of names -1? that way you should get them in the correct order.

Edit

I noticed through the comments that there are a lot of concerns about using the Interop classes to retrieve the sheet names. Therefore here is an example using OLEDB to retrieve them:

/// <summary>
/// This method retrieves the excel sheet names from 
/// an excel workbook.
/// </summary>
/// <param name="excelFile">The excel file.</param>
/// <returns>String[]</returns>
private String[] GetExcelSheetNames(string excelFile)
{
    OleDbConnection objConn = null;
    System.Data.DataTable dt = null;

    try
    {
        // Connection String. Change the excel file to the file you
        // will search.
        String connString = "Provider=Microsoft.Jet.OLEDB.4.0;" + 
          "Data Source=" + excelFile + ";Extended Properties=Excel 8.0;";
        // Create connection object by using the preceding connection string.
        objConn = new OleDbConnection(connString);
        // Open connection with the database.
        objConn.Open();
        // Get the data table containg the schema guid.
        dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

        if(dt == null)
        {
           return null;
        }

        String[] excelSheets = new String[dt.Rows.Count];
        int i = 0;

        // Add the sheet name to the string array.
        foreach(DataRow row in dt.Rows)
        {
           excelSheets[i] = row["TABLE_NAME"].ToString();
           i++;
        }

        // Loop through all of the sheets if you want too...
        for(int j=0; j < excelSheets.Length; j++)
        {
            // Query each excel sheet.
        }

        return excelSheets;
   }
   catch(Exception ex)
   {
       return null;
   }
   finally
   {
      // Clean up.
      if(objConn != null)
      {
          objConn.Close();
          objConn.Dispose();
      }
      if(dt != null)
      {
          dt.Dispose();
      }
   }
}

Extracted from Article on the CodeProject.

Escape dot in a regex range

If you using JavaScript to test your Regex, try \\. instead of \..

It acts on the same way because JS remove first backslash.

Angularjs loading screen on ajax request

If you are using Restangular (which is awesome) you can create an animation during api calls. Here is my solution. Add a response interceptor and a request interceptor that sends out a rootscope broadcast. Then create a directive to listen for that response and request.:

         angular.module('mean.system')
  .factory('myRestangular',['Restangular','$rootScope', function(Restangular,$rootScope) {
    return Restangular.withConfig(function(RestangularConfigurer) {
      RestangularConfigurer.setBaseUrl('http://localhost:3000/api');
      RestangularConfigurer.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
        var extractedData;
        // .. to look for getList operations
        if (operation === 'getList') {
          // .. and handle the data and meta data
          extractedData = data.data;
          extractedData.meta = data.meta;
        } else {
          extractedData = data.data;
        }
        $rootScope.$broadcast('apiResponse');
        return extractedData;
      });
      RestangularConfigurer.setRequestInterceptor(function (elem, operation) {
        if (operation === 'remove') {
          return null;
        }
        return (elem && angular.isObject(elem.data)) ? elem : {data: elem};
      });
      RestangularConfigurer.setRestangularFields({
        id: '_id'
      });
      RestangularConfigurer.addRequestInterceptor(function(element, operation, what, url) {
        $rootScope.$broadcast('apiRequest');
        return element;
      });
    });
  }]);

Here is the directive:

        angular.module('mean.system')
  .directive('smartLoadingIndicator', function($rootScope) {
    return {
      restrict: 'AE',
      template: '<div ng-show="isAPICalling"><p><i class="fa fa-gear fa-4x fa-spin"></i>&nbsp;Loading</p></div>',
      replace: true,
      link: function(scope, elem, attrs) {
        scope.isAPICalling = false;

        $rootScope.$on('apiRequest', function() {
          scope.isAPICalling = true;
        });
        $rootScope.$on('apiResponse', function() {
          scope.isAPICalling = false;
        });
      }
    };
  })
;

How to define custom sort function in javascript?

or shorter

_x000D_
_x000D_
function sortBy(field) {_x000D_
  return function(a, b) {_x000D_
    return (a[field] > b[field]) - (a[field] < b[field])_x000D_
  };_x000D_
}_x000D_
_x000D_
let myArray = [_x000D_
    {tabid: 6237, url: 'https://reddit.com/r/znation'},_x000D_
    {tabid: 8430, url: 'https://reddit.com/r/soccer'},_x000D_
    {tabid: 1400, url: 'https://reddit.com/r/askreddit'},_x000D_
    {tabid: 3620, url: 'https://reddit.com/r/tacobell'},_x000D_
    {tabid: 5753, url: 'https://reddit.com/r/reddevils'},_x000D_
]_x000D_
_x000D_
myArray.sort(sortBy('url'));_x000D_
console.log(myArray);
_x000D_
_x000D_
_x000D_

How do I raise an exception in Rails so it behaves like other Rails exceptions?

If you need an easier way to do it, and don't want much fuss, a simple execution could be:

raise Exception.new('something bad happened!')

This will raise an exception, say e with e.message = something bad happened!

and then you can rescue it as you are rescuing all other exceptions in general.

How to set a default entity property value with Hibernate

To use default value from any column of table. then you must need to define @DynamicInsert as true or else you just define @DynamicInsert. Because hibernate takes by default as a true. Consider as the given example:

@AllArgsConstructor
@Table(name = "core_contact")
@DynamicInsert
public class Contact implements Serializable {

    @Column(name = "status", columnDefinition = "int default 100")
    private Long status;

}

MySQL: Can't create table (errno: 150)

Data types must match exactly. If you are dealing with varchar types, the tables must use the same collation.

How to check if a class inherits another class without instantiating it?

To check for assignability, you can use the Type.IsAssignableFrom method:

typeof(SomeType).IsAssignableFrom(typeof(Derived))

This will work as you expect for type-equality, inheritance-relationships and interface-implementations but not when you are looking for 'assignability' across explicit / implicit conversion operators.

To check for strict inheritance, you can use Type.IsSubclassOf:

typeof(Derived).IsSubclassOf(typeof(SomeType))

how to print an exception using logger?

You can use this method to log the exception stack to String

 public String stackTraceToString(Throwable e) {
    StringBuilder sb = new StringBuilder();
    for (StackTraceElement element : e.getStackTrace()) {
        sb.append(element.toString());
        sb.append("\n");
    }
    return sb.toString();
}

Eclipse: Syntax Error, parameterized types are only if source level is 1.5

This works for me .

In eclipse go to project properties -> java compiler.

Then change to java higher than 1.5 .

change Compiler compliance settings to 1.6 change Generated.class files compatibility to 1.6 change Source compatibility to 1.6

Thanks. Screen Shot for changes