Programs & Examples On #Billiards

TypeError: Converting circular structure to JSON in nodejs

TypeError: Converting circular structure to JSON in nodejs: This error can be seen on Arangodb when using it with Node.js, because storage is missing in your database. If the archive is created under your database, check in the Aurangobi web interface.

How to link home brew python version and set it as default

This answer is for upgrading Python 2.7.10 to Python 2.7.11 on Mac OS X El Capitan . On Terminal type:

brew unlink python

After that type on Terminal

brew install python

Seeding the random number generator in Javascript

Math.random no, but the ran library solves this. It has almost all distributions you can imagine and supports seeded random number generation. Example:

ran.core.seed(0)
myDist = new ran.Dist.Uniform(0, 1)
samples = myDist.sample(1000)

How to convert AAR to JAR

.aar is a standard zip archive, the same one used in .jar. Just change the extension and, assuming it's not corrupt or anything, it should be fine.

If you needed to, you could extract it to your filesystem and then repackage it as a jar.

1) Rename it to .jar
2) Extract: jar xf filename.jar
3) Repackage: jar cf output.jar input-file(s)

Bootstrap control with multiple "data-toggle"

<a data-toggle="tooltip" data-placement="top" title="My Tooltip text!">+</a>

Error in file(file, "rt") : cannot open the connection

The reason why you see this error I guess is because RStudio lost the path of your working directory.

(1) Go to session...

(2) Set working directory...

(3) Choose directory...

--> Then you can see a window pops up.

--> Choose the folder where you store your data.

This is the way without any code that you change your working directory. Hope this can help you.

enter image description here

Changing column names of a data frame

Use this to change column name by colname function.

colnames(newprice)[1] = "premium"
colnames(newprice)[2] = "change"
colnames(newprice)[3] = "newprice"

Find UNC path of a network drive?

If you have Microsoft Office:

  1. RIGHT-drag the drive, folder or file from Windows Explorer into the body of a Word document or Outlook email
  2. Select 'Create Hyperlink Here'

The inserted text will be the full UNC of the dragged item.

Using CMake to generate Visual Studio C++ project files

We moved our department's build chain to CMake, and we had a few internal roadbumps since other departments where using our project files and where accustomed to just importing them into their solutions. We also had some complaints about CMake not being fully integrated into the Visual Studio project/solution manager, so files had to be added manually to CMakeLists.txt; this was a major break in the workflow people were used to.

But in general, it was a quite smooth transition. We're very happy since we don't have to deal with project files anymore.

The concrete workflow for adding a new file to a project is really simple:

  1. Create the file, make sure it is in the correct place.
  2. Add the file to CMakeLists.txt.
  3. Build.

CMake 2.6 automatically reruns itself if any CMakeLists.txt files have changed (and (semi-)automatically reloads the solution/projects).

Remember that if you're doing out-of-source builds, you need to be careful not to create the source file in the build directory (since Visual Studio only knows about the build directory).

display HTML page after loading complete

The easiest thing to do is putting a div with the following CSS in the body:

#hideAll
 {
   position: fixed;
   left: 0px; 
   right: 0px; 
   top: 0px; 
   bottom: 0px; 
   background-color: white;
   z-index: 99; /* Higher than anything else in the document */

 }

(Note that position: fixed won't work in IE6 - I know of no sure-fire way of doing this in that browser)

Add the DIV like so (directly after the opening body tag):

<div style="display: none" id="hideAll">&nbsp;</div>

show the DIV directly after :

 <script type="text/javascript">
   document.getElementById("hideAll").style.display = "block";
 </script> 

and hide it onload:

 window.onload = function() 
  { document.getElementById("hideAll").style.display = "none"; }

or using jQuery

 $(window).load(function() {  document.getElementById("hideAll").style.display = "none"; });

this approach has the advantage that it will also work for clients who have JavaScript turned off. It shouldn't cause any flickering or other side-effects, but not having tested it, I can't entirely guarantee it for every browser out there.

Git Ignores and Maven targets

I ignore all classes residing in target folder from git. add following line in open .gitignore file:

/.class

OR

*/target/**

It is working perfectly for me. try it.

select and echo a single field from mysql db using PHP

$eventid = $_GET['id'];
$field = $_GET['field'];
$result = mysql_query("SELECT $field FROM `events` WHERE `id` = '$eventid' ");
$row = mysql_fetch_array($result);
echo $row[$field];

but beware of sql injection cause you are using $_GET directly in a query. The danger of injection is particularly bad because there's no database function to escape identifiers. Instead, you need to pass the field through a whitelist or (better still) use a different name externally than the column name and map the external names to column names. Invalid external names would result in an error.

Pass Arraylist as argument to function

It depends on how and where you declared your array list. If it is an instance variable in the same class like your AnalyseArray() method you don't have to pass it along. The method will know the list and you can simply use the A in whatever purpose you need.

If they don't know each other, e.g. beeing a local variable or declared in a different class, define that your AnalyseArray() method needs an ArrayList parameter

public void AnalyseArray(ArrayList<Integer> theList){}

and then work with theList inside that method. But don't forget to actually pass it on when calling the method.AnalyseArray(A);

PS: Some maybe helpful Information to Variables and parameters.

Can vue-router open a link in a new tab?

If you are interested ONLY on relative paths like: /dashboard, /about etc, See other answers.

If you want to open an absolute path like: https://www.google.com to a new tab, you have to know that Vue Router is NOT meant to handle those.

However, they seems to consider that as a feature-request. #1280. But until they do that,



Here is a little trick you can do to handle external links with vue-router.

  • Go to the router configuration (probably router.js) and add this code:
/* Vue Router is not meant to handle absolute urls. */
/* So whenever we want to deal with those, we can use this.$router.absUrl(url) */
Router.prototype.absUrl = function(url, newTab = true) {
  const link = document.createElement('a')
  link.href = url
  link.target = newTab ? '_blank' : ''
  if (newTab) link.rel = 'noopener noreferrer' // IMPORTANT to add this
  link.click()
}

Now, whenever we deal with absolute URLs we have a solution. For example to open google to a new tab

this.$router.absUrl('https://www.google.com)

Remember that whenever we open another page to a new tab we MUST use noopener noreferrer.

Read more here

or Here

Merge PDF files

A slight variation using a dictionary for greater flexibility (e.g. sort, dedup):

import os
from PyPDF2 import PdfFileMerger
# use dict to sort by filepath or filename
file_dict = {}
for subdir, dirs, files in os.walk("<dir>"):
    for file in files:
        filepath = subdir + os.sep + file
        # you can have multiple endswith
        if filepath.endswith((".pdf", ".PDF")):
            file_dict[file] = filepath
# use strict = False to ignore PdfReadError: Illegal character error
merger = PdfFileMerger(strict=False)

for k, v in file_dict.items():
    print(k, v)
    merger.append(v)

merger.write("combined_result.pdf")

Math functions in AngularJS bindings

If you're looking to do a simple round in Angular you can easily set the filter inside your expression. For example:

{{ val | number:0 }}

See this CodePen example & for other number filter options.

Angular Docs on using Number Filters

How do I find the last column with data?

Try using the code after you active the sheet:

Dim J as integer
J = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row

If you use Cells.SpecialCells(xlCellTypeLastCell).Row only, the problem will be that the xlCellTypeLastCell information will not be updated unless one do a "Save file" action. But use UsedRange will always update the information in realtime.

What is wrong with my SQL here? #1089 - Incorrect prefix key

This

PRIMARY KEY (id (11))

is generated automatically by phpmyadmin, change to

PRIMARY KEY (id)

.

Is it a bad practice to use an if-statement without curly braces?

The "rule" I follow is this:

If the "if" statement is testing in order to do something (I.E. call functions, configure variables etc.), use braces.

if($test)
{
    doSomething();
}

This is because I feel you need to make it clear what functions are being called and where the flow of the program is going, under what conditions. Having the programmer understand exactly what functions are called and what variables are set in this condition is important to helping them understand exactly what your program is doing.

If the "if" statement is testing in order to stop doing something (I.E. flow control within a loop or function), use a single line.

if($test) continue;
if($test) break;
if($test) return;

In this case, what's important to the programmer is discovering quickly what the exceptional cases are where you don't want the code to run, and that is all coverred in $test, not in the execution block.

Docker for Windows error: "Hardware assisted virtualization and data execution protection must be enabled in the BIOS"

Below is working solution for me, please follow these steps

  1. Open PowerShell as administrator or CMD prompt as administrator

  2. Run this command in PowerShell-> bcdedit /set hypervisorlaunchtype auto

  3. Now restart the system and try again.

cheers.

How to remove an HTML element using Javascript?

index.html

<input id="suby" type="submit" value="Remove DUMMY"/>

myscripts.js

document.addEventListener("DOMContentLoaded", {
//Do this AFTER elements are loaded

    document.getElementById("suby").addEventListener("click", e => {
        document.getElementById("dummy").remove()
    })

})

Extract year from date

When you convert your variable to Date:

date <-  as.Date('10/30/2018','%m/%d/%Y')

you can then cut out the elements you want and make new variables, like year:

year <- as.numeric(format(date,'%Y'))

or month:

month <- as.numeric(format(date,'%m'))

Passing javascript variable to html textbox

document.getElementById("txtBillingGroupName").value = groupName;

What charset does Microsoft Excel use when saving files?

cp1250 is used extensively in Microsoft Office documents, including Word and Excel 2003.

http://en.wikipedia.org/wiki/Windows-1250

A simple way to confirm this would be to:

  1. Create a spreadsheet with higher order characters, e.g. "Veszprém" in one of the cells;
  2. Use your favourite scripting language to parse and decode the spreadsheet;
  3. Look at what your script produces when you print out the decoded data.

Example perl script:

#!perl

use strict;

use Spreadsheet::ParseExcel::Simple;
use Encode qw( decode );

my $file    = "my_spreadsheet.xls";

my $xls     = Spreadsheet::ParseExcel::Simple->read( $file );
my $sheet   = [ $xls->sheets ]->[0];

while ($sheet->has_data) {

    my @data = $sheet->next_row;

    for my $datum ( @data ) {
        print decode( 'cp1250', $datum );
    }

}

Windows command for file size only

If you are inside a batch script, you can use argument variable tricks to get the filesize:

filesize.bat:

@echo off
echo %~z1

This gives results like the ones you suggest in your question.

Type

help call

at the command prompt for all of the crazy variable manipulation options. Also see this article for more information.

Edit: This only works in Windows 2000 and later

Edit and replay XHR chrome/firefox etc?

Chrome :

  • In the Network panel of devtools, right-click and select Copy as cURL
  • Paste / Edit the request, and then send it from a terminal, assuming you have the curl command

See capture :

enter image description here

Alternatively, and in case you need to send the request in the context of a webpage, select "Copy as fetch" and edit-send the content from the javascript console panel.


Firefox :

Firefox allows to edit and resend XHR right from the Network panel. Capture below is from Firefox 36:

enter image description here

How can I print out C++ map values?

for(map<string, pair<string,string> >::const_iterator it = myMap.begin();
    it != myMap.end(); ++it)
{
    std::cout << it->first << " " << it->second.first << " " << it->second.second << "\n";
}

In C++11, you don't need to spell out map<string, pair<string,string> >::const_iterator. You can use auto

for(auto it = myMap.cbegin(); it != myMap.cend(); ++it)
{
    std::cout << it->first << " " << it->second.first << " " << it->second.second << "\n";
}

Note the use of cbegin() and cend() functions.

Easier still, you can use the range-based for loop:

for(auto elem : myMap)
{
   std::cout << elem.first << " " << elem.second.first << " " << elem.second.second << "\n";
}

base_url() function not working in codeigniter

Check if you have something configured inside the config file /application/config/config.php e.g.

$config['base_url'] = 'http://example.com/';

Is there any kind of hash code function in JavaScript?

Here's my simple solution that returns a unique integer.

function hashcode(obj) {
    var hc = 0;
    var chars = JSON.stringify(obj).replace(/\{|\"|\}|\:|,/g, '');
    var len = chars.length;
    for (var i = 0; i < len; i++) {
        // Bump 7 to larger prime number to increase uniqueness
        hc += (chars.charCodeAt(i) * 7);
    }
    return hc;
}

use jQuery's find() on JSON object

jQuery doesn't work on plain object literals. You can use the below function in a similar way to search all 'id's (or any other property), regardless of its depth in the object:

function getObjects(obj, key, val) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getObjects(obj[i], key, val));
        } else if (i == key && obj[key] == val) {
            objects.push(obj);
        }
    }
    return objects;
}

Use like so:

getObjects(TestObj, 'id', 'A'); // Returns an array of matching objects

What is the best project structure for a Python application?

In my experience, it's just a matter of iteration. Put your data and code wherever you think they go. Chances are, you'll be wrong anyway. But once you get a better idea of exactly how things are going to shape up, you're in a much better position to make these kinds of guesses.

As far as extension sources, we have a Code directory under trunk that contains a directory for python and a directory for various other languages. Personally, I'm more inclined to try putting any extension code into its own repository next time around.

With that said, I go back to my initial point: don't make too big a deal out of it. Put it somewhere that seems to work for you. If you find something that doesn't work, it can (and should) be changed.

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

For Swift 3 and Xcode 8:

      var dataTask: URLSessionDataTask?

      if  let url = URL(string: urlString) {
            self.dataTask = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in

                if let error = error {
                    print(error.localizedDescription)
                } else if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
                     // You can use data received.
                    self.process(data: data as Data?)
                }
            })
        }
     }

//Note: You can always use debugger to check error

How to clone a Date object?

I found out that this simple assignmnent also works:

dateOriginal = new Date();
cloneDate = new Date(dateOriginal);

But I don't know how "safe" it is. Successfully tested in IE7 and Chrome 19.

How can I pass variable to ansible playbook in the command line?

This also worked for me if you want to use shell environment variables:

ansible-playbook -i "localhost," ldap.yaml --extra-vars="LDAP_HOST={{ lookup('env', 'LDAP_HOST') }} clustername=mycluster env=dev LDAP_USERNAME={{ lookup('env', 'LDAP_USERNAME') }} LDAP_PASSWORD={{ lookup('env', 'LDAP_PASSWORD') }}"

select count(*) from table of mysql in php

$result = mysql_query("SELECT COUNT(*) AS `count` FROM `Students`");
$row = mysql_fetch_assoc($result);
$count = $row['count'];

Try this code.

Bootstrap Dropdown with Hover

Use the mouseover() function to trigger the click. In this way the previous click event will not harm. User can use both hover and click/touch. It will be mobile friendly.

$(".dropdown-toggle").mouseover(function(){
    $(this).trigger('click');
})

MySQL, create a simple function

this is a mysql function example. I hope it helps. (I have not tested it yet, but should work)

DROP FUNCTION IF EXISTS F_TEST //
CREATE FUNCTION F_TEST(PID INT) RETURNS VARCHAR
BEGIN
/*DECLARE VALUES YOU MAY NEED, EXAMPLE:
  DECLARE NOM_VAR1 DATATYPE [DEFAULT] VALUE;
  */
  DECLARE NAME_FOUND VARCHAR DEFAULT "";

    SELECT EMPLOYEE_NAME INTO NAME_FOUND FROM TABLE_NAME WHERE ID = PID;
  RETURN NAME_FOUND;
END;//

jQuery: using a variable as a selector

You're thinking too complicated. It's actually just $('#'+openaddress).

Java Round up Any Number

I don't know why you are dividing by 100 but here my assumption int a;

int b = (int) Math.ceil( ((double)a) / 100);

or

int b = (int) Math.ceil( a / 100.0);

How to grant remote access permissions to mysql server for user?

This worked for me. But there was a strange problem that even I tryed first those it didnt affect. I updated phpmyadmin page and got it somehow working.

If you need access to local-xampp-mysql. You can go to xampp-shell -> opening command prompt.

Then mysql -uroot -p --port=3306 or mysql -uroot -p (if there is password set). After that you can grant those acces from mysql shell page (also can work from localhost/phpmyadmin).

Just adding these if somebody find this topic and having beginner problems.

How do I pass multiple parameter in URL?

I do not know much about Java but URL query arguments should be separated by "&", not "?"

http://tools.ietf.org/html/rfc3986 is good place for reference using "sub-delim" as keyword. http://en.wikipedia.org/wiki/Query_string is another good source.

How to check the version of GitLab?

For omnibus versions:\

sudo gitlab-rake gitlab:env:info

Example:

System information
System:     Ubuntu 12.04
Current User:   git
Using RVM:  no
Ruby Version:   2.1.7p400
Gem Version:    2.2.5
Bundler Version:1.10.6
Rake Version:   10.4.2
Sidekiq Version:3.3.0

GitLab information
Version:    8.2.2
Revision:   08fae2f
Directory:  /opt/gitlab/embedded/service/gitlab-rails
DB Adapter: postgresql
URL:        https://your.hostname
HTTP Clone URL: https://your.hostname/some-group/some-project.git
SSH Clone URL:  [email protected]:some-group/some-project.git
Using LDAP: yes
Using Omniauth: no

GitLab Shell
Version:    2.6.8
Repositories:   /var/opt/gitlab/git-data/repositories
Hooks:      /opt/gitlab/embedded/service/gitlab-shell/hooks/
Git:        /opt/gitlab/embedded/bin/git

How to split elements of a list?

I had to split a list for feature extraction in two parts lt,lc:

ltexts = ((df4.ix[0:,[3,7]]).values).tolist()
random.shuffle(ltexts)

featsets = [(act_features((lt)),lc) 
              for lc, lt in ltexts]

def act_features(atext):
  features = {}
  for word in nltk.word_tokenize(atext):
     features['cont({})'.format(word.lower())]=True
  return features

Truncating all tables in a Postgres database

If you can use psql you can use \gexec meta command to execute query output;

SELECT
    format('TRUNCATE TABLE %I.%I', ns.nspname, c.relname)
  FROM pg_namespace ns 
  JOIN pg_class c ON ns.oid = c.relnamespace
  JOIN pg_roles r ON r.oid = c.relowner
  WHERE
    ns.nspname = 'table schema' AND                               -- add table schema criteria 
    r.rolname = 'table owner' AND                                 -- add table owner criteria
    ns.nspname NOT IN ('pg_catalog', 'information_schema') AND    -- exclude system schemas
    c.relkind = 'r' AND                                           -- tables only
    has_table_privilege(c.oid, 'TRUNCATE')                        -- check current user has truncate privilege
  \gexec 

Note that \gexec is introduced into the version 9.6

How can I find the current OS in Python?

If you want user readable data but still detailed, you can use platform.platform()

>>> import platform
>>> platform.platform()
'Linux-3.3.0-8.fc16.x86_64-x86_64-with-fedora-16-Verne'

platform also has some other useful methods:

>>> platform.system()
'Windows'
>>> platform.release()
'XP'
>>> platform.version()
'5.1.2600'

Here's a few different possible calls you can make to identify where you are

import platform
import sys

def linux_distribution():
  try:
    return platform.linux_distribution()
  except:
    return "N/A"

print("""Python version: %s
dist: %s
linux_distribution: %s
system: %s
machine: %s
platform: %s
uname: %s
version: %s
mac_ver: %s
""" % (
sys.version.split('\n'),
str(platform.dist()),
linux_distribution(),
platform.system(),
platform.machine(),
platform.platform(),
platform.uname(),
platform.version(),
platform.mac_ver(),
))

The outputs of this script ran on a few different systems (Linux, Windows, Solaris, MacOS) and architectures (x86, x64, Itanium, power pc, sparc) is available here: https://github.com/hpcugent/easybuild/wiki/OS_flavor_name_version

e.g. Solaris on sparc gave:

Python version: ['2.6.4 (r264:75706, Aug  4 2010, 16:53:32) [C]']
dist: ('', '', '')
linux_distribution: ('', '', '')
system: SunOS
machine: sun4u
platform: SunOS-5.9-sun4u-sparc-32bit-ELF
uname: ('SunOS', 'xxx', '5.9', 'Generic_122300-60', 'sun4u', 'sparc')
version: Generic_122300-60
mac_ver: ('', ('', '', ''), '')

java.util.zip.ZipException: error in opening zip file

I faced the same problem. I had a zip archive which java.util.zip.ZipFile was not able to handle but WinRar unpacked it just fine. I found article on SDN about compressing and decompressing options in Java. I slightly modified one of example codes to produce method which was finally capable of handling the archive. Trick is in using ZipInputStream instead of ZipFile and in sequential reading of zip archive. This method is also capable of handling empty zip archive. I believe you can adjust the method to suit your needs as all zip classes have equivalent subclasses for .jar archives.

public void unzipFileIntoDirectory(File archive, File destinationDir) 
    throws Exception {
    final int BUFFER_SIZE = 1024;
    BufferedOutputStream dest = null;
    FileInputStream fis = new FileInputStream(archive);
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
    ZipEntry entry;
    File destFile;
    while ((entry = zis.getNextEntry()) != null) {
        destFile = FilesystemUtils.combineFileNames(destinationDir, entry.getName());
        if (entry.isDirectory()) {
            destFile.mkdirs();
            continue;
        } else {
            int count;
            byte data[] = new byte[BUFFER_SIZE];
            destFile.getParentFile().mkdirs();
            FileOutputStream fos = new FileOutputStream(destFile);
            dest = new BufferedOutputStream(fos, BUFFER_SIZE);
            while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
                dest.write(data, 0, count);
            }
            dest.flush();
            dest.close();
            fos.close();
        }
    }
    zis.close();
    fis.close();
}

How to create an empty DataFrame with a specified schema?

import scala.reflect.runtime.{universe => ru}
def createEmptyDataFrame[T: ru.TypeTag] =
    hiveContext.createDataFrame(sc.emptyRDD[Row],
      ScalaReflection.schemaFor(ru.typeTag[T].tpe).dataType.asInstanceOf[StructType]
    )
  case class RawData(id: String, firstname: String, lastname: String, age: Int)
  val sourceDF = createEmptyDataFrame[RawData]

Removing viewcontrollers from navigation stack

Swift 2.0:

  var navArray:Array = (self.navigationController?.viewControllers)!
  navArray.removeAtIndex(navArray.count-2)
  self.navigationController?.viewControllers = navArray

Class Not Found: Empty Test Suite in IntelliJ

I had the same problem and rebuilding/invalidating cache etc. didn't work. Seems like that's just a bug in Android Studio...

A temporary solution is just to run your unit tests from the command line with:

./gradlew test

See: https://developer.android.com/studio/test/command-line.html

EXCEL VBA Check if entry is empty or not 'space'

Here is the code to check whether value is present or not.

If Trim(textbox1.text) <> "" Then
     'Your code goes here
Else
     'Nothing
End If

I think this will help.

Assign command output to variable in batch file

A method has already been devised, however this way you don't need a temp file.

for /f "delims=" %%i in ('command') do set output=%%i

However, I'm sure this has its own exceptions and limitations.

How much memory can a 32 bit process access on a 64 bit operating system?

You've got the same basic restriction when running a 32bit process under Win64. Your app runs in a 32 but subsystem which does its best to look like Win32, and this will include the memory restrictions for your process (lower 2GB for you, upper 2GB for the OS)

Exception in thread "main" java.lang.UnsupportedClassVersionError: a (Unsupported major.minor version 51.0)

I had this problem, after installing jdk7 next to Java 6. The binaries were correctly updated using update-alternatives --config java to jdk7, but the $JAVA_HOME environment variable still pointed to the old directory of Java 6.

How to include an HTML page into another HTML page without frame/iframe?

Also make sure to check out how to use Angular includes (using AngularJS). It's pretty straight forward…

<body ng-app="">
  <div ng-include="'myFile.htm'"></div>
</body> 

Unsuccessful append to an empty NumPy array

numpy.append is pretty different from list.append in python. I know that's thrown off a few programers new to numpy. numpy.append is more like concatenate, it makes a new array and fills it with the values from the old array and the new value(s) to be appended. For example:

import numpy

old = numpy.array([1, 2, 3, 4])
new = numpy.append(old, 5)
print old
# [1, 2, 3, 4]
print new
# [1, 2, 3, 4, 5]
new = numpy.append(new, [6, 7])
print new
# [1, 2, 3, 4, 5, 6, 7]

I think you might be able to achieve your goal by doing something like:

result = numpy.zeros((10,))
result[0:2] = [1, 2]

# Or
result = numpy.zeros((10, 2))
result[0, :] = [1, 2]

Update:

If you need to create a numpy array using loop, and you don't know ahead of time what the final size of the array will be, you can do something like:

import numpy as np

a = np.array([0., 1.])
b = np.array([2., 3.])

temp = []
while True:
    rnd = random.randint(0, 100)
    if rnd > 50:
        temp.append(a)
    else:
        temp.append(b)
    if rnd == 0:
         break

 result = np.array(temp)

In my example result will be an (N, 2) array, where N is the number of times the loop ran, but obviously you can adjust it to your needs.

new update

The error you're seeing has nothing to do with types, it has to do with the shape of the numpy arrays you're trying to concatenate. If you do np.append(a, b) the shapes of a and b need to match. If you append an (2, n) and (n,) you'll get a (3, n) array. Your code is trying to append a (1, 0) to a (2,). Those shapes don't match so you get an error.

How do I import other TypeScript files?

If you're using AMD modules, the other answers won't work in TypeScript 1.0 (the newest at the time of writing.)

You have different approaches available to you, depending upon how many things you wish to export from each .ts file.

Multiple exports

Foo.ts

export class Foo {}
export interface IFoo {}

Bar.ts

import fooModule = require("Foo");

var foo1 = new fooModule.Foo();
var foo2: fooModule.IFoo = {};

Single export

Foo.ts

class Foo
{}

export = Foo;

Bar.ts

import Foo = require("Foo");

var foo = new Foo();

Convert Pandas column containing NaNs to dtype `int`

If you want to use it when you chain methods, you can use assign:

df = (
     df.assign(col = lambda x: x['col'].astype('Int64'))
)

How to get the current TimeStamp?

Since Qt 5.8, we now have QDateTime::currentSecsSinceEpoch() to deliver the seconds directly, a.k.a. as real Unix timestamp. So, no need to divide the result by 1000 to get seconds anymore.

Credits: also posted as comment to this answer. However, I think it is easier to find if it is a separate answer.

Setting the JVM via the command line on Windows

Yes - just explicitly provide the path to java.exe. For instance:

c:\Users\Jon\Test>"c:\Program Files\java\jdk1.6.0_03\bin\java.exe" -version
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)

c:\Users\Jon\Test>"c:\Program Files\java\jdk1.6.0_12\bin\java.exe" -version
java version "1.6.0_12"
Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing)

The easiest way to do this for a running command shell is something like:

set PATH=c:\Program Files\Java\jdk1.6.0_03\bin;%PATH%

For example, here's a complete session showing my default JVM, then the change to the path, then the new one:

c:\Users\Jon\Test>java -version
java version "1.6.0_12"
Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing)

c:\Users\Jon\Test>set PATH=c:\Program Files\Java\jdk1.6.0_03\bin;%PATH%

c:\Users\Jon\Test>java -version
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)

This won't change programs which explicitly use JAVA_HOME though.

Note that if you get the wrong directory in the path - including one that doesn't exist - you won't get any errors, it will effectively just be ignored.

Remove char at specific index - python

def remove_char(input_string, index):
    first_part = input_string[:index]
    second_part - input_string[index+1:]
    return first_part + second_part

s = 'aababc'
index = 1
remove_char(s,index)
ababc

zero-based indexing

Sending JSON to PHP using ajax

Lose the contentType: "application/json; charset=utf-8",. You're not sending JSON to the server, you're sending a normal POST query (that happens to contain a JSON string).

That should make what you have work.

Thing is, you don't need to use JSON.stringify or json_decode here at all. Just do:

data: {myData:postData},

Then in PHP:

$obj = $_POST['myData'];

Accessing a local website from another computer inside the local network in IIS 7

Find the local IP address of computer A and find the port that your website is running on. Then from computer B open a web browser and go to IP:port. Example: 192.168.1.5:80 if computer A's IP is 192.168.1.5 and your website is running on port 80

What does Java option -Xmx stand for?

The -Xmx option changes the maximum Heap Space for the VM. java -Xmx1024m means that the VM can allocate a maximum of 1024 MB. In layman terms this means that the application can use a maximum of 1024MB of memory.

Running interactive commands in Paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(server_IP,22,username, password)


stdin, stdout, stderr = ssh.exec_command('/Users/lteue/Downloads/uecontrol-CXC_173_6456-R32A01/uecontrol.sh -host localhost ')
alldata = ""
while not stdout.channel.exit_status_ready():
   solo_line = ""        
   # Print stdout data when available
   if stdout.channel.recv_ready():
      # Retrieve the first 1024 bytes
      solo_line = stdout.channel.recv(1024) 
      alldata += solo_line
   if(cmp(solo_line,'uec> ') ==0 ):    #Change Conditionals to your code here  
     if num_of_input == 0 :
      data_buffer = ""    
      for cmd in commandList :
       #print cmd
       stdin.channel.send(cmd)        # send input commmand 1
      num_of_input += 1
     if num_of_input == 1 :
      stdin.channel.send('q \n')      # send input commmand 2 , in my code is exit the interactive session, the connect will close.
      num_of_input += 1 
print alldata
ssh.close()              

Why the stdout.read() will hang if use dierectly without checking stdout.channel.recv_ready(): in while stdout.channel.exit_status_ready():

For my case ,after run command on remote server , the session is waiting for user input , after input 'q' ,it will close the connection . But before inputting 'q' , the stdout.read() will waiting for EOF,seems this methord does not works if buffer is larger .

  • I tried stdout.read(1) in while , it works
    I tried stdout.readline() in while , it works also.
    stdin, stdout, stderr = ssh.exec_command('/Users/lteue/Downloads/uecontrol')
    stdout.read() will hang

How can I listen for a click-and-hold in jQuery?

Here's my current implementation:

$.liveClickHold = function(selector, fn) {

    $(selector).live("mousedown", function(evt) {

        var $this = $(this).data("mousedown", true);

        setTimeout(function() {
            if ($this.data("mousedown") === true) {
                fn(evt);
            }
        }, 500);

    });

    $(selector).live("mouseup", function(evt) {
        $(this).data("mousedown", false);
    });

}

How can I disable an <option> in a <select> based on its value in JavaScript?

Set an id to the option then use get element by id and disable it when x value has been selected..

example

<body>
      <select class="pull-right text-muted small" 
                 name="driveCapacity" id=driveCapacity onchange="checkRPM()">
      <option value="4000.0" id="4000">4TB</option>
      <option value="900.0" id="900">900GB</option>
      <option value="300.0" id ="300">300GB</option>
    </select>
    </body>
<script>
var perfType = document.getElementById("driveRPM").value;
if(perfType == "7200"){         
        document.getElementById("driveCapacity").value = "4000.0";
        document.getElementById("4000").disabled = false;           
    }else{          
        document.getElementById("4000").disabled = true;            
    }    
</script>

How to get Locale from its String representation in Java?

Well, I would store instead a string concatenation of Locale.getISO3Language(), getISO3Country() and getVariant() as key, which would allow me to latter call Locale(String language, String country, String variant) constructor.

indeed, relying of displayLanguage implies using the langage of locale to display it, which make it locale dependant, contrary to iso language code.

As an example, en locale key would be storable as

en_EN
en_US

and so on ...

How to open a folder in Windows Explorer from VBA?

You can use the following code to open a file location from vba.

Dim Foldername As String
Foldername = "\\server\Instructions\"

Shell "C:\WINDOWS\explorer.exe """ & Foldername & "", vbNormalFocus

You can use this code for both windows shares and local drives.

VbNormalFocus can be swapper for VbMaximizedFocus if you want a maximized view.

Angularjs $q.all

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

Read this article about javaScript Scoping and Hoisting.

See how I debugged your code:

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

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

// some code

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

Solution with angular.forEach:

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

UploadService.uploadQuestion = function(questions){

    var promises = [];

    angular.forEach(questions , function(question) {

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

        promises.push(promise);

    });

    return $q.all(promises);
}

My favorite way is to use Array#map:

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

UploadService.uploadQuestion = function(questions){

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

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

    });

    return $q.all(promises);
}

phpMyAdmin Error: The mbstring extension is missing. Please check your PHP configuration

I see this error after I disabled php5.6 and enabled php7.3 in ubuntu18.0.4

so i reverse it and problem resolved :DDD

Align labels in form next to input

You can also try using flex-box

<head><style>
body {
    color:white;
    font-family:arial;
    font-size:1.2em;
}
form {
    margin:0 auto;
    padding:20px;
    background:#444;
}
.input-group {
    margin-top:10px;
    width:60%;
    display:flex;
    justify-content:space-between;
    flex-wrap:wrap;
}
label, input {
    flex-basis:100px;
}
</style></head>
<body>

<form>
    <div class="wrapper">
        <div class="input-group">
            <label for="user_name">name:</label>
            <input type="text" id="user_name">
        </div>
        <div class="input-group">
            <label for="user_pass">Password:</label>
            <input type="password" id="user_pass">
        </div>
    </div>
</form>

</body>
</html>

How to set the text color of TextView in code?

From API 23 onward, getResources().getColor() is deprecated.

Use this instead:

textView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.color_black));

Changing Locale within the app itself

If you want to effect on the menu options for changing the locale immediately.You have to do like this.

//onCreate method calls only once when menu is called first time.
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    //1.Here you can add your  locale settings . 
    //2.Your menu declaration.
}
//This method is called when your menu is opend to again....
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
    menu.clear();
    onCreateOptionsMenu(menu);
    return super.onMenuOpened(featureId, menu);
}

The infamous java.sql.SQLException: No suitable driver found

For me the same error occurred while connecting to postgres while creating a dataframe from table .It was caused due to,the missing dependency. jdbc dependency was not set .I was using maven for the build ,so added the required dependency to the pom file from maven dependency

jdbc dependency

Asserting successive calls to a mock method

Usually, I don't care about the order of the calls, only that they happened. In that case, I combine assert_any_call with an assertion about call_count.

>>> import mock
>>> m = mock.Mock()
>>> m(1)
<Mock name='mock()' id='37578160'>
>>> m(2)
<Mock name='mock()' id='37578160'>
>>> m(3)
<Mock name='mock()' id='37578160'>
>>> m.assert_any_call(1)
>>> m.assert_any_call(2)
>>> m.assert_any_call(3)
>>> assert 3 == m.call_count
>>> m.assert_any_call(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "[python path]\lib\site-packages\mock.py", line 891, in assert_any_call
    '%s call not found' % expected_string
AssertionError: mock(4) call not found

I find doing it this way to be easier to read and understand than a large list of calls passed into a single method.

If you do care about order or you expect multiple identical calls, assert_has_calls might be more appropriate.

Edit

Since I posted this answer, I've rethought my approach to testing in general. I think it's worth mentioning that if your test is getting this complicated, you may be testing inappropriately or have a design problem. Mocks are designed for testing inter-object communication in an object oriented design. If your design is not objected oriented (as in more procedural or functional), the mock may be totally inappropriate. You may also have too much going on inside the method, or you might be testing internal details that are best left unmocked. I developed the strategy mentioned in this method when my code was not very object oriented, and I believe I was also testing internal details that would have been best left unmocked.

Clear text area

try this

 $("#vinanghinguyen_images_bbocde").attr("value", ""); 

Possible to access MVC ViewBag object from Javascript file?

onclick="myFunction('@ViewBag.MyValue')"

Retrieve data from a ReadableStream object?

Little bit late to the party but had some problems with getting something useful out from a ReadableStream produced from a Odata $batch request using the Sharepoint Framework.

Had similar issues as OP, but the solution in my case was to use a different conversion method than .json(). In my case .text() worked like a charm. Some fiddling was however necessary to get some useful JSON from the textfile.

How to check if a value exists in an array in Ruby

There's the other way around this.

Suppose the array is [ :edit, :update, :create, :show ], well perhaps the entire seven deadly/restful sins.

And further toy with the idea of pulling a valid action from some string:

"my brother would like me to update his profile"

Then:

[ :edit, :update, :create, :show ].select{|v| v if "my brother would like me to update his profile".downcase =~ /[,|.| |]#{v.to_s}[,|.| |]/}

Set NA to 0 in R

To add to James's example, it seems you always have to create an intermediate when performing calculations on NA-containing data frames.

For instance, adding two columns (A and B) together from a data frame dfr:

temp.df <- data.frame(dfr) # copy the original
temp.df[is.na(temp.df)] <- 0
dfr$C <- temp.df$A + temp.df$B # or any other calculation
remove('temp.df')

When I do this I throw away the intermediate afterwards with remove/rm.

How to implement a Boolean search with multiple columns in pandas

All the considerations made by @EdChum in 2014 are still valid, but the pandas.Dataframe.ix method is deprecated from the version 0.0.20 of pandas. Directly from the docs:

Warning: Starting in 0.20.0, the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.

In subsequent versions of pandas, this method has been replaced by new indexing methods pandas.Dataframe.loc and pandas.Dataframe.iloc.

If you want to learn more, in this post you can find comparisons between the methods mentioned above.

Ultimately, to date (and there does not seem to be any change in the upcoming versions of pandas from this point of view), the answer to this question is as follows:

foo = df.loc[(df['column1']==value) | (df['columns2'] == 'b') | (df['column3'] == 'c')]

Java Read Large Text File With 70million line of text

1) I am sure there is no difference speedwise, both use FileInputStream internally and buffering

2) You can take measurements and see for yourself

3) Though there's no performance benefits I like the 1.7 approach

try (BufferedReader br = Files.newBufferedReader(Paths.get("test.txt"), StandardCharsets.UTF_8)) {
    for (String line = null; (line = br.readLine()) != null;) {
        //
    }
}

4) Scanner based version

    try (Scanner sc = new Scanner(new File("test.txt"), "UTF-8")) {
        while (sc.hasNextLine()) {
            String line = sc.nextLine();
        }
        // note that Scanner suppresses exceptions
        if (sc.ioException() != null) {
            throw sc.ioException();
        }
    }

5) This may be faster than the rest

try (SeekableByteChannel ch = Files.newByteChannel(Paths.get("test.txt"))) {
    ByteBuffer bb = ByteBuffer.allocateDirect(1000);
    for(;;) {
        StringBuilder line = new StringBuilder();
        int n = ch.read(bb);
        // add chars to line
        // ...
    }
}

it requires a bit of coding but it can be really faster because of ByteBuffer.allocateDirect. It allows OS to read bytes from file to ByteBuffer directly, without copying

6) Parallel processing would definitely increase speed. Make a big byte buffer, run several tasks that read bytes from file into that buffer in parallel, when ready find first end of line, make a String, find next...

How can I enter latitude and longitude in Google Maps?

You don't need to convert to decimal; you can also enter 46 23S, 115 22E. You can add seconds after the minutes, also separated by a space.

How to set timer in android?

You need to create a thread to handle the update loop and use it to update the textarea. The tricky part though is that only the main thread can actually modify the ui so the update loop thread needs to signal the main thread to do the update. This is done using a Handler.

Check out this link: http://developer.android.com/guide/topics/ui/dialogs.html# Click on the section titled "Example ProgressDialog with a second thread". It's an example of exactly what you need to do, except with a progress dialog instead of a textfield.

What is the difference between syntax and semantics in programming languages?

Syntax: It is referring to grammatically structure of the language.. If you are writing the c language . You have to very care to use of data types, tokens [ it can be literal or symbol like "printf()". It has 3 tokes, "printf, (, )" ]. In the same way, you have to very careful, how you use function, function syntax, function declaration, definition, initialization and calling of it.

While semantics, It concern to logic or concept of sentence or statements. If you saying or writing something out of concept or logic, then you are semantically wrong.

How can I decrease the size of Ratingbar?

You can set it in the XML code for the RatingBar, use scaleX and scaleY to adjust accordingly. "1.0" would be the normal size, and anything in the ".0" will reduce it, also anything greater than "1.0" will increase it.

<RatingBar
  android:id="@+id/ratingBar1"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:scaleX="0.5"
  android:scaleY="0.5" />

JPA mapping: "QuerySyntaxException: foobar is not mapped..."

JPQL mostly is case-insensitive. One of the things that is case-sensitive is Java entity names. Change your query to:

"SELECT r FROM FooBar r"

Key error when selecting columns in pandas dataframe after read_csv

if you need to select multiple columns from dataframe use 2 pairs of square brackets eg.

df[["product_id","customer_id","store_id"]]

Regex match text between tags

/<b>(.*?)<\/b>/g

Regular expression visualization

Add g (global) flag after:

/<b>(.*?)<\/b>/g.exec(str)
             //^-----here it is 

However if you want to get all matched elements, then you need something like this:

var str = "<b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.";

var result = str.match(/<b>(.*?)<\/b>/g).map(function(val){
   return val.replace(/<\/?b>/g,'');
});
//result -> ["Bob", "20", "programming"] 

If an element has attributes, regexp will be:

/<b [^>]+>(.*?)<\/b>/g.exec(str)

Manifest merger failed : uses-sdk:minSdkVersion 14

I have some projects where I prefer to target L.MR1(SDKv22) and some projects where I prefer KK(SDKv19). Your result may be different, but this worked for me.

// Targeting L.MR1 (Android 5.1), SDK 22
android {
    compileSdkVersion 22
    buildToolsVersion "22"

    defaultConfig {
        minSdkVersion 9
        targetSdkVersion 22
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    // google support libraries (22)
    compile 'com.android.support:support-v4:22.0.0'
    compile 'com.android.support:appcompat-v7:22.0.0'
    compile 'com.android.support:cardview-v7:21.0.3'
    compile 'com.android.support:recyclerview-v7:21.0.3'
}



// Targeting KK (Android 4.4.x), SDK 19
android {
    compileSdkVersion 19
    buildToolsVersion "19.1"

    defaultConfig {
        minSdkVersion 9
        targetSdkVersion 19
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    // google libraries (19)
    compile 'com.android.support:support-v4:19.1+'
    compile 'com.android.support:appcompat-v7:19.1+'
    compile 'com.android.support:cardview-v7:+'
    compile 'com.android.support:recyclerview-v7:+'
}

Manually map column names with class properties

Taken from the Dapper Tests which is currently on Dapper 1.42.

// custom mapping
var map = new CustomPropertyTypeMap(typeof(TypeWithMapping), 
                                    (type, columnName) => type.GetProperties().FirstOrDefault(prop => GetDescriptionFromAttribute(prop) == columnName));
Dapper.SqlMapper.SetTypeMap(typeof(TypeWithMapping), map);

Helper class to get name off the Description attribute (I personally have used Column like @kalebs example)

static string GetDescriptionFromAttribute(MemberInfo member)
{
   if (member == null) return null;

   var attrib = (DescriptionAttribute)Attribute.GetCustomAttribute(member, typeof(DescriptionAttribute), false);
   return attrib == null ? null : attrib.Description;
}

Class

public class TypeWithMapping
{
   [Description("B")]
   public string A { get; set; }

   [Description("A")]
   public string B { get; set; }
}

Read a Csv file with powershell and capture corresponding data

What you should be looking at is Import-Csv

Once you import the CSV you can use the column header as the variable.

Example CSV:

Name  | Phone Number | Email
Elvis | 867.5309     | [email protected]
Sammy | 555.1234     | [email protected]

Now we will import the CSV, and loop through the list to add to an array. We can then compare the value input to the array:

$Name = @()
$Phone = @()

Import-Csv H:\Programs\scripts\SomeText.csv |`
    ForEach-Object {
        $Name += $_.Name
        $Phone += $_."Phone Number"
    }

$inputNumber = Read-Host -Prompt "Phone Number"

if ($Phone -contains $inputNumber)
    {
    Write-Host "Customer Exists!"
    $Where = [array]::IndexOf($Phone, $inputNumber)
    Write-Host "Customer Name: " $Name[$Where]
    }

And here is the output:

I Found Sammy

What is the difference between substr and substring?

As hinted at in yatima2975's answer, there is an additional difference:

substr() accepts a negative starting position as an offset from the end of the string. substring() does not.

From MDN:

If start is negative, substr() uses it as a character index from the end of the string.

So to sum up the functional differences:

substring(begin-offset, end-offset-exclusive) where begin-offset is 0 or greater

substr(begin-offset, length) where begin-offset may also be negative

File is universal (three slices), but it does not contain a(n) ARMv7-s slice error for static libraries on iOS, anyway to bypass?

In my case, I was linking to a third-party library that was a bit old (developed for iOS 6, on XCode 5 / iOS 7). Therefore, I had to update the third-party library, do a Clean and Build, and it now builds successfully.

Regular Expression usage with ls

You don't say what shell you are using, but they generally don't support regular expressions that way, although there are common *nix CLI tools (grep, sed, etc) that do.

What shells like bash do support is globbing, which uses some similiar characters (eg, *) but is not the same thing.

Newer versions of bash do have a regular expression operator, =~:

for x in `ls`; do 
    if [[ $x =~ .+\..* ]]; then 
        echo $x; 
    fi; 
done

Amazon S3 boto - how to create a folder?

Assume you wanna create folder abc/123/ in your bucket, it's a piece of cake with Boto

k = bucket.new_key('abc/123/')
k.set_contents_from_string('')

Or use the console

javascript clear field value input

do like

<input name="name" id="name" type="text" value="Name" 
   onblur="fillField(this,'Name');" onfocus="clearField(this,'Name');"/>

and js

function fillField(input,val) {
      if(input.value == "")
         input.value=val;
};

function clearField(input,val) {
      if(input.value == val)
         input.value="";
};

update

here is a demo fiddle of the same

Disable/Enable Submit Button until all forms have been filled

I just posted this on Disable Submit button until Input fields filled in. Works for me.

Use the form onsubmit. Nice and clean. You don't have to worry about the change and keypress events firing. Don't have to worry about keyup and focus issues.

http://www.w3schools.com/jsref/event_form_onsubmit.asp

<form action="formpost.php" method="POST" onsubmit="return validateCreditCardForm()">
   ...
</form>

function validateCreditCardForm(){
    var result = false;
    if (($('#billing-cc-exp').val().length > 0) &&
        ($('#billing-cvv').val().length  > 0) &&
        ($('#billing-cc-number').val().length > 0)) {
            result = true;
    }
    return result;
}

Trim last character from a string

The another example of trimming last character from a string:

string outputText = inputText.Remove(inputText.Length - 1, 1);

You can put it into an extension method and prevent it from null string, etc.

Subtracting Dates in Oracle - Number or Interval Datatype?

Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.

When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.

An example of a DATE subtraction resulting in a positive integer difference:

select date '2009-08-07' - date '2008-08-08' from dual;

Results in:

DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
                              364

select dump(date '2009-08-07' - date '2008-08-08') from dual;

DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0

Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.

An example of a DATE subtraction resulting in a negative integer difference:

select date '1000-08-07' - date '2008-08-08' from dual;

Results in:

DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
                          -368160

select dump(date '1000-08-07' - date '2008-08-08') from dual;

DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0

Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.

An example of a DATE subtraction resulting in a decimal difference:

select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;

TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
                                                                             .25

The difference between those 2 dates is 0.25 days or 6 hours.

select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;

DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0

Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.

Hope this helps anyone who was wondering how a DATE subtraction is actually stored.


You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:

SQL> SELECT DUMP(SYSDATE - start_date) from test;

DUMP(SYSDATE-START_DATE)
-------------------------------------- 
Typ=14 Len=8: 188,10,0,0,223,65,1,0

You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function

For example:

SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;

(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000

SQL> SELECT (SYSDATE - start_date) from test;

(SYSDATE-START_DATE)
--------------------
           2748.9515

SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;

NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000

SQL>

Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.

How to get all enum values in Java?

Here, Role is an enum which contains the following values [ADMIN, USER, OTHER].

List<Role> roleList = Arrays.asList(Role.values());
roleList.forEach(role -> {
    System.out.println(role);
    });

Hidden Features of C#?

I couldn't figure out what use some of the functions in the Convert class had (such as Convert.ToDouble(int), Convert.ToInt(double)) until I combined them with Array.ConvertAll:

int[] someArrayYouHaveAsInt;
double[] copyOfArrayAsDouble = Array.ConvertAll<int, double>(
                                someArrayYouHaveAsInt,
                                new Converter<int,double>(Convert.ToDouble));

Which avoids the resource allocation issues that arise from defining an inline delegate/closure (and slightly more readable):

int[] someArrayYouHaveAsInt;
double[] copyOfArrayAsDouble = Array.ConvertAll<int, double>(
                                someArrayYouHaveAsInt,
                                new Converter<int,double>(
                                  delegate(int i) { return (double)i; }
                                ));

SVN "Already Locked Error"

I got similar error msgs. I run svn clean-up, and then tried "get clock" for a few times. Then this error was gone.

What is difference between Axios and Fetch?

According to mzabriskie on GitHub:

Overall they are very similar. Some benefits of axios:

  • Transformers: allow performing transforms on data before a request is made or after a response is received

  • Interceptors: allow you to alter the request or response entirely (headers as well). also, perform async operations before a request is made or before Promise settles

  • Built-in XSRF protection

please check Browser Support Axios

enter image description here

I think you should use axios.

Length of string in bash

UTF-8 string length

In addition to fedorqui's correct answer, I would like to show the difference between string length and byte length:

myvar='Généralités'
chrlen=${#myvar}
oLang=$LANG oLcAll=$LC_ALL
LANG=C LC_ALL=C
bytlen=${#myvar}
LANG=$oLang LC_ALL=$oLcAll
printf "%s is %d char len, but %d bytes len.\n" "${myvar}" $chrlen $bytlen

will render:

Généralités is 11 char len, but 14 bytes len.

you could even have a look at stored chars:

myvar='Généralités'
chrlen=${#myvar}
oLang=$LANG oLcAll=$LC_ALL
LANG=C LC_ALL=C
bytlen=${#myvar}
printf -v myreal "%q" "$myvar"
LANG=$oLang LC_ALL=$oLcAll
printf "%s has %d chars, %d bytes: (%s).\n" "${myvar}" $chrlen $bytlen "$myreal"

will answer:

Généralités has 11 chars, 14 bytes: ($'G\303\251n\303\251ralit\303\251s').

Nota: According to Isabell Cowan's comment, I've added setting to $LC_ALL along with $LANG.

Length of an argument

Argument work same as regular variables

strLen() {
    local bytlen sreal oLang=$LANG oLcAll=$LC_ALL
    LANG=C LC_ALL=C
    bytlen=${#1}
    printf -v sreal %q "$1"
    LANG=$oLang LC_ALL=$oLcAll
    printf "String '%s' is %d bytes, but %d chars len: %s.\n" "$1" $bytlen ${#1} "$sreal"
}

will work as

strLen théorème
String 'théorème' is 10 bytes, but 8 chars len: $'th\303\251or\303\250me'

Useful printf correction tool:

If you:

for string in Généralités Language Théorème Février  "Left: ?" "Yin Yang ?";do
    printf " - %-14s is %2d char length\n" "'$string'"  ${#string}
done

 - 'Généralités' is 11 char length
 - 'Language'     is  8 char length
 - 'Théorème'   is  8 char length
 - 'Février'     is  7 char length
 - 'Left: ?'    is  7 char length
 - 'Yin Yang ?' is 10 char length

Not really pretty... For this, there is a little function:

strU8DiffLen () { 
    local bytlen oLang=$LANG oLcAll=$LC_ALL
    LANG=C LC_ALL=C
    bytlen=${#1}
    LANG=$oLang LC_ALL=$oLcAll
    return $(( bytlen - ${#1} ))
}

Then now:

for string in Généralités Language Théorème Février  "Left: ?" "Yin Yang ?";do
    strU8DiffLen "$string"
    printf " - %-$((14+$?))s is %2d chars length, but uses %2d bytes\n" \
        "'$string'" ${#string} $((${#string}+$?))
  done 

 - 'Généralités'  is 11 chars length, but uses 14 bytes
 - 'Language'     is  8 chars length, but uses  8 bytes
 - 'Théorème'     is  8 chars length, but uses 10 bytes
 - 'Février'      is  7 chars length, but uses  8 bytes
 - 'Left: ?'      is  7 chars length, but uses  9 bytes
 - 'Yin Yang ?'   is 10 chars length, but uses 12 bytes

Unfortunely, this is not perfect!

But there left some strange UTF-8 behaviour, like double-spaced chars, zero spaced chars, reverse deplacement and other that could not be as simple...

Have a look at diffU8test.sh or diffU8test.sh.txt for more limitations.

Set Windows process (or user) memory limit

No way to do this that I know of, although I'm very curious to read if anyone has a good answer. I have been thinking about adding something like this to one of the apps my company builds, but have found no good way to do it.

The one thing I can think of (although not directly on point) is that I believe you can limit the total memory usage for a COM+ application in Windows. It would require the app to be written to run in COM+, of course, but it's the closest way I know of.

The working set stuff is good (Job Objects also control working sets), but that's not total memory usage, only real memory usage (paged in) at any one time. It may work for what you want, but afaik it doesn't limit total allocated memory.

How do you configure HttpOnly cookies in tomcat / java webapps?

also it should be noted that turning on HttpOnly will break applets that require stateful access back to the jvm.

the Applet http requests will not use the jsessionid cookie and may get assigned to a different tomcat.

Javascript Confirm popup Yes, No button instead of OK and Cancel

the very specific answer to the point is confirm dialogue Js Function:

confirm('Do you really want to do so');

It show dialogue box with ok cancel buttons,to replace these button with yes no is not so simple task,for that you need to write jQuery function.

How to compile makefile using MinGW?

You have to actively choose to install MSYS to get the make.exe. So you should always have at least (the native) mingw32-make.exe if MinGW was installed properly. And if you installed MSYS you will have make.exe (in the MSYS subfolder probably).

Note that many projects require first creating a makefile (e.g. using a configure script or automake .am file) and it is this step that requires MSYS or cygwin. Makes you wonder why they bothered to distribute the native make at all.

Once you have the makefile, it is unclear if the native executable requires a different path separator than the MSYS make (forward slashes vs backward slashes). Any autogenerated makefile is likely to have unix-style paths, assuming the native make can handle those, the compiled output should be the same.

Easiest way to ignore blank lines when reading a file in Python

Why are you all going the hard way?

with open("myfile") as myfile:
    nonempty = filter(str.rstrip, myfile)

Convert nonempty into a list if you have the urge to do so, although I highly suggest keeping nonempty a generator as it is in Python 3.x

In Python 2.x you may use itertools.ifilter to do your bidding instead.

MySQL config file location - redhat linux server

All of them seemed good candidates:

/etc/my.cnf
/etc/mysql/my.cnf
/var/lib/mysql/my.cnf
...

in many cases you could simply check system process list using ps:

server ~ # ps ax | grep '[m]ysqld'

Output

10801 ?        Ssl    0:27 /usr/sbin/mysqld --defaults-file=/etc/mysql/my.cnf --basedir=/usr --datadir=/var/lib/mysql --pid-file=/var/run/mysqld/mysqld.pid --socket=/var/run/mysqld/mysqld.sock

Or

which mysqld
/usr/sbin/mysqld

Then

/usr/sbin/mysqld --verbose --help | grep -A 1 "Default options"

/etc/mysql/my.cnf ~/.my.cnf /usr/etc/my.cnf

Index (zero based) must be greater than or equal to zero

This can also happen when trying to throw an ArgumentException where you inadvertently call the ArgumentException constructor overload

public static void Dostuff(Foo bar)
{

   // this works
   throw new ArgumentException(String.Format("Could not find {0}", bar.SomeStringProperty));

   //this gives the error
   throw new ArgumentException(String.Format("Could not find {0}"), bar.SomeStringProperty);

}

Is there a way to detach matplotlib plots so that the computation can continue?

You may want to read this document in matplotlib's documentation, titled:

Using matplotlib in a python shell

reading from app.config file

Try:

string value = ConfigurationManager.AppSettings[key];

For more details check: Reading Keys from App.Config

getting integer values from textfield

You need to use Integer.parseInt(String)

private void jTextField2MouseClicked(java.awt.event.MouseEvent evt) {
        if(evt.getSource()==jTextField2){
            int jml = Integer.parseInt(jTextField3.getText());
            jTextField1.setText(numberToWord(jml));

        }
    }

How can I add a PHP page to WordPress?

If you wanted to create your own .php file and interact with WordPress without 404 headers and keeping your current permalink structure there is no need for a template file for that one page.

I found that this approach works best, in your .php file:

<?php
    require_once(dirname(__FILE__) . '/wp-config.php');
    $wp->init();
    $wp->parse_request();
    $wp->query_posts();
    $wp->register_globals();
    $wp->send_headers();

    // Your WordPress functions here...
    echo site_url();
?>

Then you can simply perform any WordPress functions after this. Also, this assumes that your .php file is within the root of your WordPress site where your wp-config.php file is located.

This, to me, is a priceless discovery as I was using require_once(dirname(__FILE__) . '/wp-blog-header.php'); for the longest time as WordPress even tells you that this is the approach that you should use to integrate WordPress functions, except, it causes 404 headers, which is weird that they would want you to use this approach. Integrating WordPress with Your Website

I know many people have answered this question, and it already has an accepted answer, but here is a nice approach for a .php file within the root of your WordPress site (or technically anywhere you want in your site), that you can browse to and load without 404 headers!


Update: There is a way to use wp-blog-header.php without 404 headers, but this requires that you add in the headers manually. Something like this will work in the root of your WordPress installation:

<?php
    require_once(dirname(__FILE__) . '/wp-blog-header.php');
    header("HTTP/1.1 200 OK");
    header("Status: 200 All rosy");

    // Your WordPress functions here...
    echo site_url();
?>

Just to update you all on this, a little less code needed for this approach, but it's up to you on which one you use.

How to iterate over the files of a certain directory, in Java?

Use java.io.File.listFiles
Or
If you want to filter the list prior to iteration (or any more complicated use case), use apache-commons FileUtils. FileUtils.listFiles

How to show Bootstrap table with sort icon

You could try using FontAwesome. It contains a sort-icon (http://fontawesome.io/icon/sort/).

To do so, you would

  1. need to include fontawesome:

    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
    
  2. and then simply use the fontawesome-icon instead of the default-bootstrap-icons in your th's:

    <th><b>#</b> <i class="fa fa-fw fa-sort"></i></th>
    

Hope that helps.

What is let-* in Angular 2 templates?

update Angular 5

ngOutletContext was renamed to ngTemplateOutletContext

See also https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29

original

Templates (<template>, or <ng-template> since 4.x) are added as embedded views and get passed a context.

With let-col the context property $implicit is made available as col within the template for bindings. With let-foo="bar" the context property bar is made available as foo.

For example if you add a template

<ng-template #myTemplate let-col let-foo="bar">
  <div>{{col}}</div>
  <div>{{foo}}</div>
</ng-template>

<!-- render above template with a custom context -->
<ng-template [ngTemplateOutlet]="myTemplate"
             [ngTemplateOutletContext]="{
                                           $implicit: 'some col value',
                                           bar: 'some bar value'
                                        }"
></ng-template>

See also this answer and ViewContainerRef#createEmbeddedView.

*ngFor also works this way. The canonical syntax makes this more obvious

<ng-template ngFor let-item [ngForOf]="items" let-i="index" let-odd="odd">
  <div>{{item}}</div>
</ng-template>

where NgFor adds the template as embedded view to the DOM for each item of items and adds a few values (item, index, odd) to the context.

See also Using $implict to pass multiple parameters

error code 1292 incorrect date value mysql

I happened to be working in localhost , in windows 10, using WAMP, as it turns out, Wamp has a really accessible configuration interface to change the MySQL configuration. You just need to go to the Wamp panel, then to MySQL, then to settings and change the mode to sql-mode: none.(essentially disabling the strict mode) The following picture illustrates this.

enter image description here

UnicodeEncodeError: 'latin-1' codec can't encode character

Use the below snippet to convert the text from Latin to English

import unicodedata
def strip_accents(text):
    return "".join(char for char in
                   unicodedata.normalize('NFKD', text)
                   if unicodedata.category(char) != 'Mn')

strip_accents('áéíñóúü')

output:

'aeinouu'

In bootstrap how to add borders to rows without adding up?

You can remove the border from top if the element is sibling of the row . Add this to css :

.row + .row {
   border-top:0;
}

Here is the link to the fiddle http://jsfiddle.net/7cb3Y/3/

Invoke-Command error "Parameter set cannot be resolved using the specified named parameters"

I was solving same problem recently. I was designing a write cmdlet for my Subtitle module. I had six different user stories:

  • Subtitle only
  • Subtitle and path (original file name is used)
  • Subtitle and new file name (original path is used)
  • Subtitle and name suffix is used (original path and modified name is used).
  • Subtile, new path and new file name is is used.
  • Subtitle, new path and suffix is used.

I end up in the big frustration because I though that 4 parameters will be enough. Like most of the times, the frustration was pointless because it was my fault. I didn't know enough about parameter sets.

After some research in documentation, I realized where is the problem. With knowledge how the parameter sets should be used, I developed a general and simple approach how to solve this problem. A pencil and a sheet of paper is required but a spreadsheet editor is better:

  1. Write down all intended ways how the cmdlet should be used => user stories.
  2. Keep adding parameters with meaningful names and mark the use of the parameters until you have a unique collection set => no repetitive combination of parameters.
  3. Implement parameter sets into your code.
  4. Prepare tests for all possible user stories.
  5. Run tests (big surprise, right?). IDEs doesn't checks parameter sets collision, tests could save lots of trouble later one.

Example:

Unique parameter binding resolution approach.

The practical example could be seen over here.

BTW: The parameter uniqueness within parameter sets is the reason why the ParameterSetName property doesn't support [String[]]. It doesn't really make any sense.

Determine number of pages in a PDF file

I have good success using CeTe Dynamic PDF products. They're not free, but are well documented. They did the job for me.

http://www.dynamicpdf.com/

Why do table names in SQL Server start with "dbo"?

dbo is the default schema in SQL Server. You can create your own schemas to allow you to better manage your object namespace.

String.Format for Hex

More generally.

byte[] buf = new byte[] { 123, 2, 233 };

string s = String.Concat(buf.Select(b => b.ToString("X2")));

Replacing some characters in a string with another character

echo "$string" | tr xyz _

would replace each occurrence of x, y, or z with _, giving A__BC___DEF__LMN in your example.

echo "$string" | sed -r 's/[xyz]+/_/g'

would replace repeating occurrences of x, y, or z with a single _, giving A_BC_DEF_LMN in your example.

How do I verify that an Android apk is signed with a release certificate?

Use this command, (go to java < jdk < bin path in cmd prompt)

$ jarsigner -verify -verbose -certs my_application.apk

If you see "CN=Android Debug", this means the .apk was signed with the debug key generated by the Android SDK (means it is unsigned), otherwise you will find something for CN. For more details see: http://developer.android.com/guide/publishing/app-signing.html

TypeError: module.__init__() takes at most 2 arguments (3 given)

Even after @Mickey Perlstein's answer and his 3 hours of detective work, it still took me a few more minutes to apply this to my own mess. In case anyone else is like me and needs a little more help, here's what was going on in my situation.

  • responses is a module
  • Response is a base class within the responses module
  • GeoJsonResponse is a new class derived from Response

Initial GeoJsonResponse class:

from pyexample.responses import Response

class GeoJsonResponse(Response):

    def __init__(self, geo_json_data):

Looks fine. No problems until you try to debug the thing, which is when you get a bunch of seemingly vague error messages like this:

from pyexample.responses import GeoJsonResponse ..\pyexample\responses\GeoJsonResponse.py:12: in (module) class GeoJsonResponse(Response):

E TypeError: module() takes at most 2 arguments (3 given)

=================================== ERRORS ====================================

___________________ ERROR collecting tests/test_geojson.py ____________________

test_geojson.py:2: in (module) from pyexample.responses import GeoJsonResponse ..\pyexample\responses \GeoJsonResponse.py:12: in (module)

class GeoJsonResponse(Response): E TypeError: module() takes at most 2 arguments (3 given)

ERROR: not found: \PyExample\tests\test_geojson.py::TestGeoJson::test_api_response

C:\Python37\lib\site-packages\aenum__init__.py:163

(no name 'PyExample\ tests\test_geojson.py::TestGeoJson::test_api_response' in any of [])

The errors were doing their best to point me in the right direction, and @Mickey Perlstein's answer was dead on, it just took me a minute to put it all together in my own context:

I was importing the module:

from pyexample.responses import Response

when I should have been importing the class:

from pyexample.responses.Response import Response

Hope this helps someone. (In my defense, it's still pretty early.)

Programmatically add new column to DataGridView

Here's a sample method that adds two extra columns programmatically to the grid view:

    private void AddColumnsProgrammatically()
    {
        // I created these columns at function scope but if you want to access 
        // easily from other parts of your class, just move them to class scope.
        // E.g. Declare them outside of the function...
        var col3 = new DataGridViewTextBoxColumn();
        var col4 = new DataGridViewCheckBoxColumn();

        col3.HeaderText = "Column3";
        col3.Name = "Column3";

        col4.HeaderText = "Column4";
        col4.Name = "Column4";

        dataGridView1.Columns.AddRange(new DataGridViewColumn[] {col3,col4});
    }

A great way to figure out how to do this kind of process is to create a form, add a grid view control and add some columns. (This process will actually work for ANY kind of form control. All instantiation and initialization happens in the Designer.) Then examine the form's Designer.cs file to see how the construction takes place. (Visual Studio does everything programmatically but hides it in the Form Designer.)

For this example I created two columns for the view named Column1 and Column2 and then searched Form1.Designer.cs for Column1 to see everywhere it was referenced. The following information is what I gleaned and, copied and modified to create two more columns dynamically:

// Note that this info scattered throughout the designer but can easily collected.

        System.Windows.Forms.DataGridViewTextBoxColumn Column1;
        System.Windows.Forms.DataGridViewCheckBoxColumn Column2;

        this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
        this.Column2 = new System.Windows.Forms.DataGridViewCheckBoxColumn();

        this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
        this.Column1,
        this.Column2});

        this.Column1.HeaderText = "Column1";
        this.Column1.Name = "Column1";

        this.Column2.HeaderText = "Column2";
        this.Column2.Name = "Column2";

github markdown colspan

You can use HTML tables on GitHub (but not on StackOverflow)

<table>
  <tr>
    <td>One</td>
    <td>Two</td>
  </tr>
  <tr>
    <td colspan="2">Three</td>
  </tr>
</table>

Becomes

HTML table output

Why calling react setState method doesn't mutate the state immediately?

From React's documentation:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

If you want a function to be executed after the state change occurs, pass it in as a callback.

this.setState({value: event.target.value}, function () {
    console.log(this.state.value);
});

How should I multiple insert multiple records?

Stored procedure to insert multiple records using single insertion:

ALTER PROCEDURE [dbo].[Ins]
@i varchar(50),
@n varchar(50),
@a varchar(50),
@i1 varchar(50),
@n1 varchar(50),
@a1 varchar(50),
@i2 varchar(50),
@n2 varchar(50),
@a2 varchar(50) 
AS
INSERT INTO t1
SELECT     @i AS Expr1, @i1 AS Expr2, @i2 AS Expr3
UNION ALL
SELECT     @n AS Expr1, @n1 AS Expr2, @n2 AS Expr3
UNION ALL
SELECT     @a AS Expr1, @a1 AS Expr2, @a2 AS Expr3
RETURN

Code behind:

protected void Button1_Click(object sender, EventArgs e)
{
    cn.Open();
    SqlCommand cmd = new SqlCommand("Ins",cn);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@i",TextBox1.Text);
    cmd.Parameters.AddWithValue("@n",TextBox2.Text);
    cmd.Parameters.AddWithValue("@a",TextBox3.Text);
    cmd.Parameters.AddWithValue("@i1",TextBox4.Text);
    cmd.Parameters.AddWithValue("@n1",TextBox5.Text);
    cmd.Parameters.AddWithValue("@a1",TextBox6.Text);
    cmd.Parameters.AddWithValue("@i2",TextBox7.Text);
    cmd.Parameters.AddWithValue("@n2",TextBox8.Text);
    cmd.Parameters.AddWithValue("@a2",TextBox9.Text);
    cmd.ExecuteNonQuery();
    cn.Close();
    Response.Write("inserted");
    clear();
}

Combining CSS Pseudo-elements, ":after" the ":last-child"

I do like this for list items in <menu> elements. Consider the following markup:

<menu>
  <li><a href="/member/profile">Profile</a></li>
  <li><a href="/member/options">Options</a></li>
  <li><a href="/member/logout">Logout</a></li>
</menu>

I style it with the following CSS:

menu > li {
  display: inline;
}

menu > li::after {
  content: ' | ';
}

menu > li:last-child::after {
  content: '';
}

This will display:

Profile | Options | Logout

And this is possible because of what Martin Atkins explained on his comment

Note that in CSS 2 you would use :after, not ::after. If you use CSS 3, use ::after (two semi-columns) because ::after is a pseudo-element (a single semi-column is for pseudo-classes).

How to urlencode data for curl command?

Having php installed I use this way:

URL_ENCODED_DATA=`php -r "echo urlencode('$DATA');"`

insert password into database in md5 format?

Darren Davies is partially correct in saying that you should use a salt - there are several issues with his claim that MD5 is insecure.

You've said that you have to insert the password using an Md5 hash, but that doesn't really tell us why. Is it because that's the format used when validatinb the password? Do you have control over the code which validates the password?

The thing about using a salt is that it avoids the problem where 2 users have the same password - they'll also have the same hash - not a desirable outcome. By using a diferent salt for each password then this does not arise (with very large volumes of data there is still a risk of collisions arising from 2 different passwords - but we'll ignore that for now).

So you can aither generate a random value for the salt and store that in the record too, or you could use some of the data you already hold - such as the username:

$query="INSERT INTO ptb_users (id,
        user_id,
        first_name,
        last_name,
        email )
        VALUES('NULL',
        'NULL',
        '".$firstname."',
        '".$lastname."',
        '".$email."',
        MD5('"$user_id.$password."')
        )";

(I am assuming that you've properly escaped all those strings earlier in your code)

No WebApplicationContext found: no ContextLoaderListener registered?

You'll have to have a ContextLoaderListener in your web.xml - It loads your configuration files.

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

You need to understand the difference between Web application context and root application context .

In the web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext. These inherited beans defined can be overridden in the servlet-specific scope, and new scope-specific beans can be defined local to a given servlet instance.

The dispatcher servlet's application context is a web application context which is only applicable for the Web classes . You cannot use these for your middle tier layers . These need a global app context using ContextLoaderListener .

Read the spring reference here for spring mvc .

Parser Error Message: Could not load type 'TestMvcApplication.MvcApplication'

I have also faced the same issue and somehow IIS Express's config file is not pointing to the correct bin directory for the website. So editing the Config file which will be in Documents/IISExpress/config fixed the issue. Just point to the correct physical path in Site tag as shown below.

     <site name="MYWEBSITE" id="4">
            <application path="/" applicationPool="Clr4IntegratedAppPool">
                <virtualDirectory path="/" physicalPath="D:\MYWEBSITE" />
            </application>
            <bindings>
                <binding protocol="https" bindingInformation="*:44305:localhost" />
                <binding protocol="http" bindingInformation="*:6689:localhost" />
            </bindings>
        </site>

Draggable div without jQuery UI

Here is an implementation without using jQuery at all -
http://thezillion.wordpress.com/2012/09/27/javascript-draggable-2-no-jquery

Embed the JS file (http://zillionhost.xtreemhost.com/tzdragg/tzdragg.js) in your HTML code, and put the following code -

<script>
win.onload = function(){
 tzdragg.drag('elem1, elem2, ..... elemn');
 // ^ IDs of the draggable elements separated by a comma.
}
</script>

And the code is also easy to learn.
http://thezillion.wordpress.com/2012/08/29/javascript-draggable-no-jquery

Recursive search and replace in text files on Mac and Linux

For the mac, a more similar approach would be this:

find . -name '*.txt' -print0 | xargs -0 sed -i "" "s/form/forms/g"

Difference between Static and final?

Think of an object like a Speaker. If Speaker is a class, It will have different variables such as volume, treble, bass, color etc. You define all these fields while defining the Speaker class. For example, you declared the color field with a static modifier, that means you're telling the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated.

Declaring

static final String color = "Black"; 

will make sure that whenever this class is instantiated, the value of color field will be "Black" unless it is not changed.

public class Speaker {

static String color = "Black";

}

public class Sample {

public static void main(String args[]) {
    System.out.println(Speaker.color); //will provide output as "Black"
            Speaker.color = "white";
    System.out.println(Speaker.color);  //will provide output as "White"
}}

Note : Now once you change the color of the speaker as final this code wont execute, because final keyword makes sure that the value of the field never changes.

public class Speaker {

static final String color = "Black";

}

public class Sample {

public static void main(String args[]) {
    System.out.println(Speaker.color); //should provide output as "Black"
            Speaker.color = "white"; //Error because the value of color is fixed.  
    System.out.println(Speaker.color); //Code won't execute.
}}

You may copy/paste this code directly into your emulator and try.

MySQL parameterized queries

Beware of using string interpolation for SQL queries, since it won't escape the input parameters correctly and will leave your application open to SQL injection vulnerabilities. The difference might seem trivial, but in reality it's huge.

Incorrect (with security issues)

c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s" % (param1, param2))

Correct (with escaping)

c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s", (param1, param2))

It adds to the confusion that the modifiers used to bind parameters in a SQL statement varies between different DB API implementations and that the mysql client library uses printf style syntax instead of the more commonly accepted '?' marker (used by eg. python-sqlite).

How do you round a double in Dart to a given degree of precision AFTER the decimal point?

Just write this extension on double

extension Round on double {
  double roundToPrecision(int n) {
    int fac = pow(10, n);
    return (this * fac).round() / fac;
  }
}

How to format a phone number with jQuery

Use a library to handle phone number. Libphonenumber by Google is your best bet.

// Require `PhoneNumberFormat`.
var PNF = require('google-libphonenumber').PhoneNumberFormat;

// Get an instance of `PhoneNumberUtil`.
var phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();

// Parse number with country code.
var phoneNumber = phoneUtil.parse('202-456-1414', 'US');

// Print number in the international format.
console.log(phoneUtil.format(phoneNumber, PNF.INTERNATIONAL));
// => +1 202-456-1414

I recommend to use this package by seegno.

How do I clone into a non-empty directory?

this is work for me ,but you should merge remote repository files to the local files:

git init
git remote add origin url-to-git
git branch --set-upstream-to=origin/master master
git fetch
git status

How can I get the current array index in a foreach loop?

well since this is the first google hit for this problem:

function mb_tell(&$msg) {
    if(count($msg) == 0) {
        return 0;
    }
    //prev($msg);
    $kv = each($msg);
    if(!prev($msg)) {
        end($msg);

        print_r($kv);
        return ($kv[0]+1);
    }
    print_r($kv);
    return ($kv[0]);
}

Using Switch Statement to Handle Button Clicks

I have found that the simplest way to do this is to set onClick for each button in the xml

<Button
android:id="@+id/vrHelp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_menu_help"
android:onClick="helpB" />

and then you can do a switch case like this

  public void helpB(View v) {
    Button clickedButton = (Button) v;
    switch (clickedButton.getId()) {
      case R.id.vrHelp:
        dosomething...
        break;

      case R.id.coHelp:
        dosomething...
        break;

      case R.id.ksHelp:
        dosomething...
        break;

      case R.id.uHelp:
        dosomething...
        break;

      case R.id.pHelp:
        dosomething...
        break;
    }
  }

Android: java.lang.SecurityException: Permission Denial: start Intent

In your Manifest file write this before </application >

<activity android:name="com.fsck.k9.activity.MessageList">
   <intent-filter>
      <action android:name="android.intent.action.MAIN">
      </action>
   </intent-filter>
</activity>

and tell me if it solves your issue :)

wamp server mysql user id and password

Use http://localhost/sqlbuddy --> users interface.

You can find it at the localhost main page at Your Aliases section.

Composer: how can I install another dependency without updating old ones?

To install a new package and only that, you have two options:

  1. Using the require command, just run:

    composer require new/package
    

    Composer will guess the best version constraint to use, install the package, and add it to composer.lock.

    You can also specify an explicit version constraint by running:

    composer require new/package ~2.5
    

–OR–

  1. Using the update command, add the new package manually to composer.json, then run:

    composer update new/package
    

If Composer complains, stating "Your requirements could not be resolved to an installable set of packages.", you can resolve this by passing the flag --with-dependencies. This will whitelist all dependencies of the package you are trying to install/update (but none of your other dependencies).

Regarding the question asker's issues with Laravel and mcrypt: check that it's properly enabled in your CLI php.ini. If php -m doesn't list mcrypt then it's missing.

Important: Don't forget to specify new/package when using composer update! Omitting that argument will cause all dependencies, as well as composer.lock, to be updated.

Change default global installation directory for node.js modules in Windows?

In Windows, if you want to move the npm or nodejs folder in disk C to another location, but it still makes sure node and npm works well, you can create symlink like this: Open Command Prompt:

mklink /D "your_location_want_to_create_symlink" "location_of_node_npm_file"

Example:

mklink /D "C:\Users\MyUser\AppData\Roaming\npm" "D:\Nodejs Data\npm"

Now you've created a symlink for npm folder, this symlink will refer to D:\Nodejs Data\npmEverything will work well.

How to add a button dynamically using jquery

the $("body").append(r) statement should be within the test function, also there was misplaced " in the test method

function test() {
    var r=$('<input/>').attr({
        type: "button",
        id: "field",
        value: 'new'
    });
    $("body").append(r);    
}

Demo: Fiddle

Update
In that case try a more jQuery-ish solution

<!DOCTYPE html>
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript">
          jQuery(function($){
              $('#mybutton').one('click', function(){
                  var r=$('<input/>').attr({
                      type: "button",
                      id: "field",
                      value: 'new'
                  });
                  $("body").append(r);   
              })
          })
        </script>
    </head>
    <body>
        <button id="mybutton">Insert after</button> 
    </body>
</html>

Demo: Plunker

sscanf in Python

There is also the parse module.

parse() is designed to be the opposite of format() (the newer string formatting function in Python 2.6 and higher).

>>> from parse import parse
>>> parse('{} fish', '1')
>>> parse('{} fish', '1 fish')
<Result ('1',) {}>
>>> parse('{} fish', '2 fish')
<Result ('2',) {}>
>>> parse('{} fish', 'red fish')
<Result ('red',) {}>
>>> parse('{} fish', 'blue fish')
<Result ('blue',) {}>

How to clamp an integer to some range?

This one seems more pythonic to me:

>>> def clip(val, min_, max_):
...     return min_ if val < min_ else max_ if val > max_ else val

A few tests:

>>> clip(5, 2, 7)
5
>>> clip(1, 2, 7)
2
>>> clip(8, 2, 7)
7

Build Error - missing required architecture i386 in file

I too got the same error am using xcode version 4.0.2 so what i did was selected the xcode project file and from their i selected the Target option their i could see the app of my project so i clicked on it and went to the build settings option.

Their in the search option i typed Framework search path, and deleted all the settings and then clicked the build button and that worked for me just fine,

Thanks and Regards

@Media min-width & max-width

I've found the best method is to write your default CSS for the older browsers, as older browsers including i.e. 5.5, 6, 7 and 8. Can't read @media. When I use @media I use it like this:

<style type="text/css">
    /* default styles here for older browsers. 
       I tend to go for a 600px - 960px width max but using percentages
    */
    @media only screen and (min-width: 960px) {
        /* styles for browsers larger than 960px; */
    }
    @media only screen and (min-width: 1440px) {
        /* styles for browsers larger than 1440px; */
    }
    @media only screen and (min-width: 2000px) {
        /* for sumo sized (mac) screens */
    }
    @media only screen and (max-device-width: 480px) {
       /* styles for mobile browsers smaller than 480px; (iPhone) */
    }
    @media only screen and (device-width: 768px) {
       /* default iPad screens */
    }
    /* different techniques for iPad screening */
    @media only screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait) {
      /* For portrait layouts only */
    }

    @media only screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape) {
      /* For landscape layouts only */
    }
</style>

But you can do whatever you like with your @media, This is just an example of what I've found best for me when building styles for all browsers.

iPad CSS specifications.

Also! If you're looking for printability you can use @media print{}

Binding ng-model inside ng-repeat loop in AngularJS

<h4>Order List</h4>
<ul>
    <li ng-repeat="val in filter_option.order">
        <span>
            <input title="{{filter_option.order_name[$index]}}" type="radio" ng-model="filter_param.order_option" ng-value="'{{val}}'" />
            &nbsp;{{filter_option.order_name[$index]}}
        </span>
        <select title="" ng-model="filter_param[val]">
            <option value="asc">Asc</option>
            <option value="desc">Desc</option>
        </select>
    </li>
</ul>

Using async/await with a forEach loop

To see how that can go wrong, print console.log at the end of the method.

Things that can go wrong in general:

  • Arbitrary order.
  • printFiles can finish running before printing files.
  • Poor performance.

These are not always wrong but frequently are in standard use cases.

Generally, using forEach will result in all but the last. It'll call each function without awaiting for the function meaning it tells all of the functions to start then finishes without waiting for the functions to finish.

import fs from 'fs-promise'

async function printFiles () {
  const files = (await getFilePaths()).map(file => fs.readFile(file, 'utf8'))

  for(const file of files)
    console.log(await file)
}

printFiles()

This is an example in native JS that will preserve order, prevent the function from returning prematurely and in theory retain optimal performance.

This will:

  • Initiate all of the file reads to happen in parallel.
  • Preserve the order via the use of map to map file names to promises to wait for.
  • Wait for each promise in the order defined by the array.

With this solution the first file will be shown as soon as it is available without having to wait for the others to be available first.

It will also be loading all files at the same time rather than having to wait for the first to finish before the second file read can be started.

The only draw back of this and the original version is that if multiple reads are started at once then it's more difficult to handle errors on account of having more errors that can happen at a time.

With versions that read a file at a time then then will stop on a failure without wasting time trying to read any more files. Even with an elaborate cancellation system it can be hard to avoid it failing on the first file but reading most of the other files already as well.

Performance is not always predictable. While many systems will be faster with parallel file reads some will prefer sequential. Some are dynamic and may shift under load, optimisations that offer latency do not always yield good throughput under heavy contention.

There is also no error handling in that example. If something requires them to either all be successfully shown or not at all it won't do that.

In depth experimentation is recommended with console.log at each stage and fake file read solutions (random delay instead). Although many solutions appear to do the same in simple cases all have subtle differences that take some extra scrutiny to squeeze out.

Use this mock to help tell the difference between solutions:

(async () => {
  const start = +new Date();
  const mock = () => {
    return {
      fs: {readFile: file => new Promise((resolve, reject) => {
        // Instead of this just make three files and try each timing arrangement.
        // IE, all same, [100, 200, 300], [300, 200, 100], [100, 300, 200], etc.
        const time = Math.round(100 + Math.random() * 4900);
        console.log(`Read of ${file} started at ${new Date() - start} and will take ${time}ms.`)
        setTimeout(() => {
          // Bonus material here if random reject instead.
          console.log(`Read of ${file} finished, resolving promise at ${new Date() - start}.`);
          resolve(file);
        }, time);
      })},
      console: {log: file => console.log(`Console Log of ${file} finished at ${new Date() - start}.`)},
      getFilePaths: () => ['A', 'B', 'C', 'D', 'E']
    };
  };

  const printFiles = (({fs, console, getFilePaths}) => {
    return async function() {
      const files = (await getFilePaths()).map(file => fs.readFile(file, 'utf8'));

      for(const file of files)
        console.log(await file);
    };
  })(mock());

  console.log(`Running at ${new Date() - start}`);
  await printFiles();
  console.log(`Finished running at ${new Date() - start}`);
})();

URL to load resources from the classpath in Java

I've created a class which helps to reduce errors in setting up custom handlers and takes advantage of the system property so there are no issues with calling a method first or not being in the right container. There's also an exception class if you get things wrong:

CustomURLScheme.java:
/*
 * The CustomURLScheme class has a static method for adding cutom protocol
 * handlers without getting bogged down with other class loaders and having to
 * call setURLStreamHandlerFactory before the next guy...
 */
package com.cybernostics.lib.net.customurl;

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

/**
 * Allows you to add your own URL handler without running into problems
 * of race conditions with setURLStream handler.
 * 
 * To add your custom protocol eg myprot://blahblah:
 * 
 * 1) Create a new protocol package which ends in myprot eg com.myfirm.protocols.myprot
 * 2) Create a subclass of URLStreamHandler called Handler in this package
 * 3) Before you use the protocol, call CustomURLScheme.add(com.myfirm.protocols.myprot.Handler.class);
 * @author jasonw
 */
public class CustomURLScheme
{

    // this is the package name required to implelent a Handler class
    private static Pattern packagePattern = Pattern.compile( "(.+\\.protocols)\\.[^\\.]+" );

    /**
     * Call this method with your handlerclass
     * @param handlerClass
     * @throws Exception 
     */
    public static void add( Class<? extends URLStreamHandler> handlerClass ) throws Exception
    {
        if ( handlerClass.getSimpleName().equals( "Handler" ) )
        {
            String pkgName = handlerClass.getPackage().getName();
            Matcher m = packagePattern.matcher( pkgName );

            if ( m.matches() )
            {
                String protocolPackage = m.group( 1 );
                add( protocolPackage );
            }
            else
            {
                throw new CustomURLHandlerException( "Your Handler class package must end in 'protocols.yourprotocolname' eg com.somefirm.blah.protocols.yourprotocol" );
            }

        }
        else
        {
            throw new CustomURLHandlerException( "Your handler class must be called 'Handler'" );
        }
    }

    private static void add( String handlerPackage )
    {
        // this property controls where java looks for
        // stream handlers - always uses current value.
        final String key = "java.protocol.handler.pkgs";

        String newValue = handlerPackage;
        if ( System.getProperty( key ) != null )
        {
            final String previousValue = System.getProperty( key );
            newValue += "|" + previousValue;
        }
        System.setProperty( key, newValue );
    }
}


CustomURLHandlerException.java:
/*
 * Exception if you get things mixed up creating a custom url protocol
 */
package com.cybernostics.lib.net.customurl;

/**
 *
 * @author jasonw
 */
public class CustomURLHandlerException extends Exception
{

    public CustomURLHandlerException(String msg )
    {
        super( msg );
    }

}

Parallel.ForEach vs Task.Factory.StartNew

In my view the most realistic scenario is when tasks have a heavy operation to complete. Shivprasad's approach focuses more on object creation/memory allocation than on computing itself. I made a research calling the following method:

public static double SumRootN(int root)
{
    double result = 0;
    for (int i = 1; i < 10000000; i++)
        {
            result += Math.Exp(Math.Log(i) / root);
        }
        return result; 
}

Execution of this method takes about 0.5sec.

I called it 200 times using Parallel:

Parallel.For(0, 200, (int i) =>
{
    SumRootN(10);
});

Then I called it 200 times using the old-fashioned way:

List<Task> tasks = new List<Task>() ;
for (int i = 0; i < loopCounter; i++)
{
    Task t = new Task(() => SumRootN(10));
    t.Start();
    tasks.Add(t);
}

Task.WaitAll(tasks.ToArray()); 

First case completed in 26656ms, the second in 24478ms. I repeated it many times. Everytime the second approach is marginaly faster.

MySql Error: 1364 Field 'display_name' doesn't have default value

Also, I had this issue using Laravel, but fixed by changing my database schema to allow "null" inputs on a table where I plan to collect the information from separate forms:

public function up()
{

    Schema::create('trip_table', function (Blueprint $table) {
        $table->increments('trip_id')->unsigned();
        $table->time('est_start');
        $table->time('est_end');
        $table->time('act_start')->nullable();
        $table->time('act_end')->nullable();
        $table->date('Trip_Date');
        $table->integer('Starting_Miles')->nullable();
        $table->integer('Ending_Miles')->nullable();
        $table->string('Bus_id')->nullable();
        $table->string('Event');
        $table->string('Desc')->nullable();
        $table->string('Destination');
        $table->string('Departure_location');
        $table->text('Drivers_Comment')->nullable();
        $table->string('Requester')->nullable();
        $table->integer('driver_id')->nullable();
        $table->timestamps();
    });

}

The ->nullable(); Added to the end. This is using Laravel. Hope this helps someone, thanks!

Why are the Level.FINE logging messages not showing?

WHY

As mentioned by @Sheepy, the reason why it doesn't work is that java.util.logging.Logger has a root logger that defaults to Level.INFO, and the ConsoleHandler attached to that root logger also defaults to Level.INFO. Therefore, in order to see the FINE (, FINER or FINEST) output, you need to set the default value of the root logger and its ConsoleHandler to Level.FINE as follows:

Logger.getLogger("").setLevel(Level.FINE);
Logger.getLogger("").getHandlers()[0].setLevel(Level.FINE);


The problem of your Update (solution)

As mentioned by @mins, you will have the messages printed twice on the console for INFO and above: first by the anonymous logger, then by its parent, the root logger which also has a ConsoleHandler set to INFO by default. To disable the root logger, you need to add this line of code: logger.setUseParentHandlers(false);

There are other ways to prevent logs from being processed by default Console handler of the root logger mentioned by @Sheepy, e.g.:

Logger.getLogger("").getHandlers()[0].setLevel( Level.OFF );

But Logger.getLogger("").setLevel( Level.OFF ); won't work because it only blocks the message passed directly to the root logger, not the message comes from a child logger. To illustrate how the Logger Hierarchy works, I draw the following diagram:

enter image description here

public void setLevel(Level newLevel) set the log level specifying which message levels will be logged by this logger. Message levels lower than this value will be discarded. The level value Level.OFF can be used to turn off logging. If the new level is null, it means that this node should inherit its level from its nearest ancestor with a specific (non-null) level value.

Constructor in an Interface?

There is only static fields in interface that dosen't need to initialized during object creation in subclass and the method of interface has to provide actual implementation in subclass .So there is no need of constructor in interface.

Second reason-during the object creation of subclass, the parent constructor is called .But if there will be more than one interface implemented then a conflict will occur during call of interface constructor as to which interface's constructor will call first

Tree view of a directory/folder in Windows?

TreeSize professional has what you want. but it focus on the sizes of folders and files.

Python re.sub(): how to substitute all 'u' or 'U's with 'you'

Firstly, why doesn't your solution work. You mix up a lot of concepts. Mostly character class with other ones. In the first character class you use | which stems from alternation. In character classes you don't need the pipe. Just list all characters (and character ranges) you want:

[Uu]

Or simply write u if you use the case-insensitive modifier. If you write a pipe there, the character class will actually match pipes in your subject string.

Now in the second character class you use the comma to separate your characters for some odd reason. That does also nothing but include commas into the matchable characters. s and W are probably supposed to be the built-in character classes. Then escape them! Otherwise they will just match literal s and literal W. But then \W already includes everything else you listed there, so a \W alone (without square brackets) would have been enough. And the last part (^a-zA-Z) also doesn't work, because it will simply include ^, (, ) and all letters into the character class. The negation syntax only works for entire character classes like [^a-zA-Z].

What you actually want is to assert that there is no letter in front or after your u. You can use lookarounds for that. The advantage is that they won't be included in the match and thus won't be removed:

r'(?<![a-zA-Z])[uU](?![a-zA-Z])'

Note that I used a raw string. Is generally good practice for regular expressions, to avoid problems with escape sequences.

These are negative lookarounds that make sure that there is no letter character before or after your u. This is an important difference to asserting that there is a non-letter character around (which is similar to what you did), because the latter approach won't work at the beginning or end of the string.

Of course, you can remove the spaces around you from the replacement string.

If you don't want to replace u that are next to digits, you can easily include the digits into the character classes:

r'(?<![a-zA-Z0-9])[uU](?![a-zA-Z0-9])'

And if for some reason an adjacent underscore would also disqualify your u for replacement, you could include that as well. But then the character class coincides with the built-in \w:

r'(?<!\w)[uU](?!\w)'

Which is, in this case, equivalent to EarlGray's r'\b[uU]\b'.

As mentioned above you can shorten all of these, by using the case-insensitive modifier. Taking the first expression as an example:

re.sub(r'(?<![a-z])u(?![a-z])', 'you', text, flags=re.I)

or

re.sub(r'(?<![a-z])u(?![a-z])', 'you', text, flags=re.IGNORECASE)

depending on your preference.

I suggest that you do some reading through the tutorial I linked several times in this answer. The explanations are very comprehensive and should give you a good headstart on regular expressions, which you will probably encounter again sooner or later.

What is Ruby's double-colon `::`?

Ruby on rails uses :: for namespace resolution.

class User < ActiveRecord::Base

  VIDEOS_COUNT = 10
  Languages = { "English" => "en", "Spanish" => "es", "Mandarin Chinese" => "cn"}

end

To use it :

User::VIDEOS_COUNT
User::Languages
User::Languages.values_at("Spanish") => "en"

Also, other usage is : When using nested routes

OmniauthCallbacksController is defined under users.

And routed as:

devise_for :users, controllers: {omniauth_callbacks: "users/omniauth_callbacks"}


class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController

end

Error while inserting date - Incorrect date value:

You can use "DATE" as a data type while you are creating the table. In this way, you can avoid the above error. Eg:

CREATE TABLE Employee (birth_date DATE);
INSERT INTO Employee VALUES('1967-11-17');

how to run command "mysqladmin flush-hosts" on Amazon RDS database Server instance?

When an Amazon RDS instance is blocked because the value of max_connect_errors has been exceeded, you cannot use the host that generated the connection errors to issue the "flush hosts" command, as the MySQL Server running on the instance is at that point blocking connections from that host.

You therefore need to issue the "flush hosts" command from another EC2 instance or remote server that has access to that RDS instance.

mysqladmin -h [YOUR RDS END POINT URL] -P 3306 -u [DB USER] -p flush-hosts

If this involved launching a new instance, or creating/modifying security groups to permit external access, it may be quicker to simply login to the RDS user interface and reboot the RDS instance that is blocked.

Why does intellisense and code suggestion stop working when Visual Studio is open?

If anyone is still having this issue, simply close the solution and then reopen it.

Best way to pretty print a hash

Using Pry you just need to add the following code to your ~/.pryrc:

require "awesome_print"
AwesomePrint.pry!

Chmod recursively

Adding executable permissions, recursively, to all files (not folders) within the current folder with sh extension:

find . -name '*.sh' -type f | xargs chmod +x

* Notice the pipe (|)

Using a dictionary to select function to execute

This will call methods from dictionary

This is python switch statement with function calling

Create few modules as per the your requirement. If want to pass arguments then pass.

Create a dictionary, which will call these modules as per requirement.

    def function_1(arg):
        print("In function_1")

    def function_2(arg):
        print("In function_2")

    def function_3(fileName):
        print("In function_3")
        f_title,f_course1,f_course2 = fileName.split('_')
        return(f_title,f_course1,f_course2)


    def createDictionary():

        dict = {

            1 : function_1,
            2 : function_2,
            3 : function_3,

        }    
        return dict

    dictionary = createDictionary()
    dictionary[3](Argument)#pass any key value to call the method

Transform hexadecimal information to binary using a Linux command

As @user786653 suggested, use the xxd(1) program:

xxd -r -p input.txt output.bin

Difference between RUN and CMD in a Dockerfile

RUN: Can be many, and it is used in build process, e.g. install multiple libraries

CMD: Can only have 1, which is your execute start point (e.g. ["npm", "start"], ["node", "app.js"])

C# Set collection?

Have a look at PowerCollections over at CodePlex. Apart from Set and OrderedSet it has a few other usefull collection types such as Deque, MultiDictionary, Bag, OrderedBag, OrderedDictionary and OrderedMultiDictionary.

For more collections, there is also the C5 Generic Collection Library.

C# Debug - cannot start debugging because the debug target is missing

I had the same problems. I had to change file rights. Unmark "read only" in their properties.

How to deal with floating point number precision in JavaScript?

Are you only performing multiplication? If so then you can use to your advantage a neat secret about decimal arithmetic. That is that NumberOfDecimals(X) + NumberOfDecimals(Y) = ExpectedNumberOfDecimals. That is to say that if we have 0.123 * 0.12 then we know that there will be 5 decimal places because 0.123 has 3 decimal places and 0.12 has two. Thus if JavaScript gave us a number like 0.014760000002 we can safely round to the 5th decimal place without fear of losing precision.

How to query DATETIME field using only date in Microsoft SQL Server?

You can use this approach which truncates the time part:

select * from test
where convert(datetime,'03/19/2014',102) = DATEADD(dd, DATEDIFF(dd, 0, date), 0)

How to update and delete a cookie?

check this out A little framework: a complete cookies reader/writer with full Unicode support

/*\
|*|
|*|  :: cookies.js ::
|*|
|*|  A complete cookies reader/writer framework with full unicode support.
|*|
|*|  Revision #1 - September 4, 2014
|*|
|*|  https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*|  https://developer.mozilla.org/User:fusionchess
|*|  https://github.com/madmurphy/cookies.js
|*|
|*|  This framework is released under the GNU Public License, version 3 or later.
|*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*|  Syntaxes:
|*|
|*|  * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*|  * docCookies.getItem(name)
|*|  * docCookies.removeItem(name[, path[, domain]])
|*|  * docCookies.hasItem(name)
|*|  * docCookies.keys()
|*|
\*/

var docCookies = {
  getItem: function (sKey) {
    if (!sKey) { return null; }
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
    return true;
  },
  hasItem: function (sKey) {
    if (!sKey) { return false; }
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  },
  keys: function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};

How do I run a docker instance from a DockerFile?

Download the file and from the same directory run docker build -t nodebb .

This will give you an image on your local machine that's named nodebb that you can launch an container from with docker run -d nodebb (you can change nodebb to your own name).

How do I determine file encoding in OS X?

I implemented the bash script below, it works for me.

It first tries to iconv from the encoding returned by file --mime-encoding to utf-8.

If that fails, it goes through all encodings and shows the diff between the original and re-encoded file. It skips over encodings that produce a large diff output ("large" as defined by the MAX_DIFF_LINES variable or the second input argument), since those are most likely the wrong encoding.

If "bad things" happen as a result of using this script, don't blame me. There's a rm -f in there, so there be monsters. I tried to prevent adverse effects by using it on files with a random suffix, but I'm not making any promises.

Tested on Darwin 15.6.0.

#!/bin/bash

if [[ $# -lt 1 ]]
then
  echo "ERROR: need one input argument: file of which the enconding is to be detected."
  exit 3
fi

if [ ! -e "$1" ]
then
  echo "ERROR: cannot find file '$1'"
  exit 3
fi

if [[ $# -ge 2 ]]
then
  MAX_DIFF_LINES=$2
else
  MAX_DIFF_LINES=10
fi


#try the easy way
ENCOD=$(file --mime-encoding $1 | awk '{print $2}')
#check if this enconding is valid
iconv -f $ENCOD -t utf-8 $1 &> /dev/null
if [ $? -eq 0 ]
then
  echo $ENCOD
  exit 0
fi

#hard way, need the user to visually check the difference between the original and re-encoded files
for i in $(iconv -l | awk '{print $1}')
do
  SINK=$1.$i.$RANDOM
  iconv -f $i -t utf-8 $1 2> /dev/null > $SINK
  if [ $? -eq 0 ]
  then
    DIFF=$(diff $1 $SINK)
    if [ ! -z "$DIFF" ] && [ $(echo "$DIFF" | wc -l) -le $MAX_DIFF_LINES ]
    then
      echo "===== $i ====="
      echo "$DIFF"
      echo "Does that make sense [N/y]"
      read $ANSWER
      if [ "$ANSWER" == "y" ] || [ "$ANSWER" == "Y" ]
      then
        echo $i
        exit 0
      fi
    fi
  fi
  #clean up re-encoded file
  rm -f $SINK
done

echo "None of the encondings worked. You're stuck."
exit 3

Microsoft Visual C++ Compiler for Python 3.4

Visual Studio Community 2015 suffices to build extensions for Python 3.5. It's free but a 6 GB download (overkill). On my computer it installed vcvarsall at C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat

For Python 3.4 you'd need Visual Studio 2010. I don't think there's any free edition. See https://matthew-brett.github.io/pydagogue/python_msvc.html

How to convert timestamps to dates in Bash?

You can use this simple awk script:

#!/bin/gawk -f   
{ print strftime("%c", $0); }

Sample usage:

$ echo '1098181096' | ./a.awk 
Tue 19 Oct 2004 03:18:16 AM PDT
$

Powershell: A positional parameter cannot be found that accepts argument "xxx"

In my case I had tried to make code more readable by putting:

"LONGTEXTSTRING " +
"LONGTEXTSTRING" +
"LONGTEXTSTRING"

Once I changed it to

LONGTEXTSTRING LONGTEXTSTRING LONGTEXTSTRING 

Then it worked

Scala list concatenation, ::: vs ++

Legacy. List was originally defined to be functional-languages-looking:

1 :: 2 :: Nil // a list
list1 ::: list2  // concatenation of two lists

list match {
  case head :: tail => "non-empty"
  case Nil          => "empty"
}

Of course, Scala evolved other collections, in an ad-hoc manner. When 2.8 came out, the collections were redesigned for maximum code reuse and consistent API, so that you can use ++ to concatenate any two collections -- and even iterators. List, however, got to keep its original operators, aside from one or two which got deprecated.

How to initialize weights in PyTorch?

If you want some extra flexibility, you can also set the weights manually.

Say you have input of all ones:

import torch
import torch.nn as nn

input = torch.ones((8, 8))
print(input)
tensor([[1., 1., 1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1., 1., 1.]])

And you want to make a dense layer with no bias (so we can visualize):

d = nn.Linear(8, 8, bias=False)

Set all the weights to 0.5 (or anything else):

d.weight.data = torch.full((8, 8), 0.5)
print(d.weight.data)

The weights:

Out[14]: 
tensor([[0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
        [0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
        [0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
        [0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
        [0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
        [0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
        [0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
        [0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000]])

All your weights are now 0.5. Pass the data through:

d(input)
Out[13]: 
tensor([[4., 4., 4., 4., 4., 4., 4., 4.],
        [4., 4., 4., 4., 4., 4., 4., 4.],
        [4., 4., 4., 4., 4., 4., 4., 4.],
        [4., 4., 4., 4., 4., 4., 4., 4.],
        [4., 4., 4., 4., 4., 4., 4., 4.],
        [4., 4., 4., 4., 4., 4., 4., 4.],
        [4., 4., 4., 4., 4., 4., 4., 4.],
        [4., 4., 4., 4., 4., 4., 4., 4.]], grad_fn=<MmBackward>)

Remember that each neuron receives 8 inputs, all of which have weight 0.5 and value of 1 (and no bias), so it sums up to 4 for each.

Create an ISO date object in javascript

This worked for me:

_x000D_
_x000D_
var start = new Date("2020-10-15T00:00:00.000+0000");
 //or
start = new date("2020-10-15T00:00:00.000Z");

collection.find({
    start_date:{
        $gte: start
    }
})...etc
_x000D_
_x000D_
_x000D_ new Date(2020,9,15,0,0,0,0) may lead to wrong date: i mean non ISO format (remember javascript count months from 0 to 11 so it's 9 for october)

How to convert time milliseconds to hours, min, sec format in JavaScript?

If you're using typescript, this could be a good thing for you

enum ETime {
  Seconds = 1000,
  Minutes = 60000,
  Hours = 3600000,
  SecInMin = 60,
  MinInHours = 60,
  HoursMod = 24,
  timeMin = 10,
}

interface ITime {
  millis: number
  modulo: number
}

const Times = {
  seconds: {
    millis: ETime.Seconds,
    modulo: ETime.SecInMin,
  },
  minutes: {
    millis: ETime.Minutes,
    modulo: ETime.MinInHours,
  },
  hours: {
    millis: ETime.Hours,
    modulo: ETime.HoursMod,
  },
}

const dots: string = ":"

const msToTime = (duration: number, needHours: boolean = true): string => {
  const getCorrectTime = (divider: ITime): string => {
    const timeStr: number = Math.floor(
      (duration / divider.millis) % divider.modulo,
    )

    return timeStr < ETime.timeMin ? "0" + timeStr : String(timeStr)
  }

  return (
    (needHours ? getCorrectTime(Times.hours) + dots : "") +
    getCorrectTime(Times.minutes) +
    dots +
    getCorrectTime(Times.seconds)
  )
}

What generates the "text file busy" message in Unix?

If trying to build phpredis on a Linux box you might need to give it time to complete modifying the file permissions, with a sleep command, before running the file:

chmod a+x /usr/bin/php/scripts/phpize \
  && sleep 1 \
  && /usr/bin/php/scripts/phpize

Create XML in Javascript

Simply use

var xmlString = '<?xml version="1.0" ?><root />';
var xml = jQuery.parseXML(xml);

It's jQuery.parseXML, so no need to worry about cross-browser tricks. Use jQuery as like HTML, it's using the native XML engine.

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

I have encountered this error while updating records from table which has trigger enabled. For example - I have trigger 'Trigger1' on table 'Table1'. When I tried to update the 'Table1' using the update query - it throws the same error. THis is because if you are updating more than 1 record in your query, then 'Trigger1' will throw this error as it doesn't support updating multiple entries if it is enabled on same table. I tried disabling trigger before update and then performed update operation and it was completed without any error.

DISABLE TRIGGER Trigger1 ON Table1;
Update query --------
Enable TRIGGER Trigger1 ON Table1;

"application blocked by security settings" prevent applets running using oracle SE 7 update 51 on firefox on Linux mint

Just start your browser with superuser rights, and don't forget to set Java's JRE security to medium.

Extracting just Month and Year separately from Pandas Datetime column

Extracting the Year say from ['2018-03-04']

df['Year'] = pd.DatetimeIndex(df['date']).year  

The df['Year'] creates a new column. While if you want to extract the month just use .month

How do you create a static class in C++?

One case where namespaces may not be so useful for achieving "static classes" is when using these classes to achieve composition over inheritance. Namespaces cannot be friends of classes and so cannot access private members of a class.

class Class {
 public:
  void foo() { Static::bar(*this); }    

 private:
  int member{0};
  friend class Static;
};    

class Static {
 public:
  template <typename T>
  static void bar(T& t) {
    t.member = 1;
  }
};

Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass

It happens when MAVEN is not installed locally on the system.

I faced the same issue when i cloned a Maven based Project from GIT and then as soon as I executed I got exception "Cannot Find Class In ClassPath : Class Name"

So i did a mvn clean test and found that maven is not installed locally.

After doing sudo apt install maven Maven got installed and i was able to Run the code

Removing carriage return and new-line from the end of a string in c#

String temp = s.Replace("\r\n","").Trim();

s being the original string. (Note capitals)

Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; }

Also, you can do this:

(this.DNATranscriber as any)[character];

Edit.

It's HIGHLY recommended that you cast the object with the proper type instead of any. Casting an object as any only help you to avoid type errors when compiling typescript but it doesn't help you to keep your code type-safe.

E.g.

interface DNA {
    G: "C",
    C: "G",
    T: "A",
    A: "U"
}

And then you cast it like this:

(this.DNATranscriber as DNA)[character];

IN Clause with NULL or IS NULL

Null refers to an absence of data. Null is formally defined as a value that is unavailable, unassigned, unknown or inapplicable (OCA Oracle Database 12c, SQL Fundamentals I Exam Guide, p87). So, you may not see records with columns containing null values when said columns are restricted using an "in" or "not in" clauses.

JavaScript, getting value of a td with id name

use the

innerHTML 

property and access the td using getElementById() as always.