Programs & Examples On #Text driver

The Microsoft Text Driver is an ODBC Database Driver that allows access to Comma Seperated, Tab Delimited and Fixed Width data in text files.

How to test if a list contains another list?

If all items are unique, you can use sets.

>>> items = set([-1, 0, 1, 2])
>>> set([1, 2]).issubset(items)
True
>>> set([1, 3]).issubset(items)
False

How to debug Ruby scripts

I strongly recommend this video, in order to pick the proper tool at the moment to debug our code.

https://www.youtube.com/watch?v=GwgF8GcynV0

Personally, I'd highlight two big topics in this video.

  • Pry is awesome for debug data, "pry is a data explorer" (sic)
  • Debugger seems to be better to debug step by step.

That's my two cents!

How to print float to n decimal places including trailing 0s?

For Python versions in 2.6+ and 3.x

You can use the str.format method. Examples:

>>> print('{0:.16f}'.format(1.6))
1.6000000000000001

>>> print('{0:.15f}'.format(1.6))
1.600000000000000

Note the 1 at the end of the first example is rounding error; it happens because exact representation of the decimal number 1.6 requires an infinite number binary digits. Since floating-point numbers have a finite number of bits, the number is rounded to a nearby, but not equal, value.

For Python versions prior to 2.6 (at least back to 2.0)

You can use the "modulo-formatting" syntax (this works for Python 2.6 and 2.7 too):

>>> print '%.16f' % 1.6
1.6000000000000001

>>> print '%.15f' % 1.6
1.600000000000000

Set width of dropdown element in HTML select dropdown options

HTML:

<select class="shortenedSelect">
    <option value="0" disabled>Please select an item</option>
    <option value="1">Item text goes in here but it is way too long to fit inside a select option that has a fixed width adding more</option>
</select>

CSS:

.shortenedSelect {
    max-width: 350px;
}

Javascript:

// Shorten select option text if it stretches beyond max-width of select element
$.each($('.shortenedSelect option'), function(key, optionElement) {
    var curText = $(optionElement).text();
    $(this).attr('title', curText);

    // Tip: parseInt('350px', 10) removes the 'px' by forcing parseInt to use a base ten numbering system.
    var lengthToShortenTo = Math.round(parseInt($(this).parent('select').css('max-width'), 10) / 7.3);

    if (curText.length > lengthToShortenTo) {
        $(this).text('... ' + curText.substring((curText.length - lengthToShortenTo), curText.length));
    }
});

// Show full name in tooltip after choosing an option
$('.shortenedSelect').change(function() {
    $(this).attr('title', ($(this).find('option:eq('+$(this).get(0).selectedIndex +')').attr('title')));
});

Works perfectly. I had the same issue myself. Check out this JSFiddle http://jsfiddle.net/jNWS6/426/

How to remove multiple deleted files in Git repository

Update all changes you made:

git add -u

The deleted files should change from unstaged (usually red color) to staged (green). Then commit to remove the deleted files:

git commit -m "note"

Get nth character of a string in Swift programming language

Best way which worked for me is:

var firstName = "Olivia"
var lastName = "Pope"

var nameInitials.text = "\(firstName.prefix(1))" + "\    (lastName.prefix(1))"

Output:"OP"

How do I print output in new line in PL/SQL?

You can concatenate the CR and LF:

chr(13)||chr(10)

(on windows)

or just:

chr(10)

(otherwise)

dbms_output.put_line('Hi,'||chr(13)||chr(10) ||'good' || chr(13)||chr(10)|| 'morning' ||chr(13)||chr(10) || 'friends');

Add new row to dataframe, at specific row-index, not appended?

insertRow2 <- function(existingDF, newrow, r) {
  existingDF <- rbind(existingDF,newrow)
  existingDF <- existingDF[order(c(1:(nrow(existingDF)-1),r-0.5)),]
  row.names(existingDF) <- 1:nrow(existingDF)
  return(existingDF)  
}

insertRow2(existingDF,newrow,r)

  V1 V2 V3 V4
1  1  6 11 16
2  2  7 12 17
3  1  2  3  4
4  3  8 13 18
5  4  9 14 19
6  5 10 15 20

microbenchmark(
+   rbind(existingDF[1:r,],newrow,existingDF[-(1:r),]),
+   insertRow(existingDF,newrow,r),
+   insertRow2(existingDF,newrow,r)
+ )
Unit: microseconds
                                                    expr     min       lq   median       uq      max
1                       insertRow(existingDF, newrow, r) 513.157 525.6730 531.8715 544.4575 1409.553
2                      insertRow2(existingDF, newrow, r) 430.664 443.9010 450.0570 461.3415  499.988
3 rbind(existingDF[1:r, ], newrow, existingDF[-(1:r), ]) 606.822 625.2485 633.3710 653.1500 1489.216

Getting char from string at specified index

Getting one char from string at specified index

Dim pos As Integer
Dim outStr As String
pos = 2 
Dim outStr As String
outStr = Left(Mid("abcdef", pos), 1)

outStr="b"

Free space in a CMD shell

df.exe

Shows all your disks; total, used and free capacity. You can alter the output by various command-line options.

You can get it from http://www.paulsadowski.com/WSH/cmdprogs.htm, http://unxutils.sourceforge.net/ or somewhere else. It's a standard unix-util like du.

df -h will show all your drive's used and available disk space. For example:

M:\>df -h
Filesystem      Size  Used Avail Use% Mounted on
C:/cygwin/bin   932G   78G  855G   9% /usr/bin
C:/cygwin/lib   932G   78G  855G   9% /usr/lib
C:/cygwin       932G   78G  855G   9% /
C:              932G   78G  855G   9% /cygdrive/c
E:              1.9T  1.3T  621G  67% /cygdrive/e
F:              1.9T  201G  1.7T  11% /cygdrive/f
H:              1.5T  524G  938G  36% /cygdrive/h
M:              1.5T  524G  938G  36% /cygdrive/m
P:               98G   67G   31G  69% /cygdrive/p
R:               98G   14G   84G  15% /cygdrive/r

Cygwin is available for free from: https://www.cygwin.com/ It adds many powerful tools to the command prompt. To get just the available space on drive M (as mapped in windows to a shared drive), one could enter in:

M:\>df -h | grep M: | awk '{print $4}'

Resolving instances with ASP.NET Core DI from within ConfigureServices

The IServiceCollection interface is used for building a dependency injection container. After it's fully built, it gets composed to an IServiceProvider instance which you can use to resolve services. You can inject an IServiceProvider into any class. The IApplicationBuilder and HttpContext classes can provide the service provider as well, via their ApplicationServices or RequestServices properties respectively.

IServiceProvider defines a GetService(Type type) method to resolve a service:

var service = (IFooService)serviceProvider.GetService(typeof(IFooService));

There are also several convenience extension methods available, such as serviceProvider.GetService<IFooService>() (add a using for Microsoft.Extensions.DependencyInjection).

Resolving services inside the startup class

Injecting dependencies

The runtime's hosting service provider can inject certain services into the constructor of the Startup class, such as IConfiguration, IWebHostEnvironment (IHostingEnvironment in pre-3.0 versions), ILoggerFactory and IServiceProvider. Note that the latter is an instance built by the hosting layer and contains only the essential services for starting up an application.

The ConfigureServices() method does not allow injecting services, it only accepts an IServiceCollection argument. This makes sense because ConfigureServices() is where you register the services required by your application. However you can use services injected in the startup's constructor here, for example:

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
    // Use Configuration here
}

Any services registered in ConfigureServices() can then be injected into the Configure() method; you can add an arbitrary number of services after the IApplicationBuilder parameter:

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IFooService>();
}

public void Configure(IApplicationBuilder app, IFooService fooService)
{
    fooService.Bar();
}

Manually resolving dependencies

If you need to manually resolve services, you should preferably use the ApplicationServices provided by IApplicationBuilder in the Configure() method:

public void Configure(IApplicationBuilder app)
{
    var serviceProvider = app.ApplicationServices;
    var hostingEnv = serviceProvider.GetService<IHostingEnvironment>();
}

It is possible to pass and directly use an IServiceProvider in the constructor of your Startup class, but as above this will contain a limited subset of services, and thus has limited utility:

public Startup(IServiceProvider serviceProvider)
{
    var hostingEnv = serviceProvider.GetService<IWebHostEnvironment>();
}

If you must resolve services in the ConfigureServices() method, a different approach is required. You can build an intermediate IServiceProvider from the IServiceCollection instance which contains the services which have been registered up to that point:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IFooService, FooService>();

    // Build the intermediate service provider
    var sp = services.BuildServiceProvider();

    // This will succeed.
    var fooService = sp.GetService<IFooService>();
    // This will fail (return null), as IBarService hasn't been registered yet.
    var barService = sp.GetService<IBarService>();
}

Please note: Generally you should avoid resolving services inside the ConfigureServices() method, as this is actually the place where you're configuring the application services. Sometimes you just need access to an IOptions<MyOptions> instance. You can accomplish this by binding the values from the IConfiguration instance to an instance of MyOptions (which is essentially what the options framework does):

public void ConfigureServices(IServiceCollection services)
{
    var myOptions = new MyOptions();
    Configuration.GetSection("SomeSection").Bind(myOptions);
}

Manually resolving services (aka Service Locator) is generally considered an anti-pattern. While it has its use-cases (for frameworks and/or infrastructure layers), you should avoid it as much as possible.

Most efficient way to reverse a numpy array

I will expand on the earlier answer about np.fliplr(). Here is some code that demonstrates constructing a 1d array, transforming it into a 2d array, flipping it, then converting back into a 1d array. time.clock() will be used to keep time, which is presented in terms of seconds.

import time
import numpy as np

start = time.clock()
x = np.array(range(3))
#transform to 2d
x = np.atleast_2d(x)
#flip array
x = np.fliplr(x)
#take first (and only) element
x = x[0]
#print x
end = time.clock()
print end-start

With print statement uncommented:

[2 1 0]
0.00203907123594

With print statement commented out:

5.59799927506e-05

So, in terms of efficiency, I think that's decent. For those of you that love to do it in one line, here is that form.

np.fliplr(np.atleast_2d(np.array(range(3))))[0]

jQuery class within class selector

For this html:

<div class="outer">
     <div class="inner"></div>
</div>

This selector should work:

$('.outer > .inner')

Eclipse: How do you change the highlight color of the currently selected method/expression?

  1. right click the highlight whose color you want to change

  2. select "Preference"

  3. ->General->Editors->Text Editors->Annotations->Occurrences->Text as Hightlited->color.

  4. Select "Preference ->java->Editor->Restore Defaults

How to replace spaces in file names using a bash script

Recursive version of Naidim's Answers.

find . -name "* *" | awk '{ print length, $0 }' | sort -nr -s | cut -d" " -f2- | while read f; do base=$(basename "$f"); newbase="${base// /_}"; mv "$(dirname "$f")/$(basename "$f")" "$(dirname "$f")/$newbase"; done

How to justify a single flexbox item (override justify-content)

I solved a similar case by setting the inner item's style to margin: 0 auto.
Situation: My menu usually contains three buttons, in which case they need to be justify-content: space-between. But when there's only one button, it will now be center aligned instead of to the left.

How to convert enum value to int?

You'd need to make the enum expose value somehow, e.g.

public enum Tax {
    NONE(0), SALES(10), IMPORT(5);

    private final int value;
    private Tax(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

...

public int getTaxValue() {
    Tax tax = Tax.NONE; // Or whatever
    return tax.getValue();
}

(I've changed the names to be a bit more conventional and readable, btw.)

This is assuming you want the value assigned in the constructor. If that's not what you want, you'll need to give us more information.

How to get previous month and year relative to today, using strtotime and date?

This is because the previous month has less days than the current month. I've fixed this by first checking if the previous month has less days that the current and changing the calculation based on it.

If it has less days get the last day of -1 month else get the current day -1 month:

if (date('d') > date('d', strtotime('last day of -1 month')))
{
    $first_end = date('Y-m-d', strtotime('last day of -1 month'));
}
else
{
    $first_end = date('Y-m-d', strtotime('-1 month'));
}

Javascript - get array of dates between 2 dates

You can do it easily using momentJS

Add moment to your dependencies

npm i moment

Then import that in your file

var moment = require("moment");

Then use the following code to get the list of all dates between two dates

let dates = [];
let currDate = moment.utc(new Date("06/30/2019")).startOf("day");
let lastDate = moment.utc(new Date("07/30/2019")).startOf("day");

do {
 dates.push(currDate.clone().toDate());
} while (currDate.add(1, "days").diff(lastDate) < 0);
dates.push(currDate.clone().toDate());

console.log(dates);

Configure hibernate to connect to database via JNDI Datasource

I was getting the same error in my IBM Websphere with c3p0 jar files. I have Oracle 10g database. I simply added the oraclejdbc.jar files in the Application server JVM in IBM Classpath using Websphere Console and the error was resolved.

The oraclejdbc.jar should be set with your C3P0 jar files in your Server Class path whatever it be tomcat, glassfish of IBM.

Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)

As written by Dave Butenhof himself:

"The biggest of all the big problems with recursive mutexes is that they encourage you to completely lose track of your locking scheme and scope. This is deadly. Evil. It's the "thread eater". You hold locks for the absolutely shortest possible time. Period. Always. If you're calling something with a lock held simply because you don't know it's held, or because you don't know whether the callee needs the mutex, then you're holding it too long. You're aiming a shotgun at your application and pulling the trigger. You presumably started using threads to get concurrency; but you've just PREVENTED concurrency."

Compiling with g++ using multiple cores

People have mentioned make but bjam also supports a similar concept. Using bjam -jx instructs bjam to build up to x concurrent commands.

We use the same build scripts on Windows and Linux and using this option halves our build times on both platforms. Nice.

Convert JavaScript string in dot notation into an object reference

Here is my implementation

Implementation 1

Object.prototype.access = function() {
    var ele = this[arguments[0]];
    if(arguments.length === 1) return ele;
    return ele.access.apply(ele, [].slice.call(arguments, 1));
}

Implementation 2 (using array reduce instead of slice)

Object.prototype.access = function() {
    var self = this;
    return [].reduce.call(arguments,function(prev,cur) {
        return prev[cur];
    }, self);
}

Examples:

var myobj = {'a':{'b':{'c':{'d':'abcd','e':[11,22,33]}}}};

myobj.access('a','b','c'); // returns: {'d':'abcd', e:[0,1,2,3]}
myobj.a.b.access('c','d'); // returns: 'abcd'
myobj.access('a','b','c','e',0); // returns: 11

it can also handle objects inside arrays as for

var myobj2 = {'a': {'b':[{'c':'ab0c'},{'d':'ab1d'}]}}
myobj2.access('a','b','1','d'); // returns: 'ab1d'

Laravel Request::all() Should Not Be Called Statically

use the request() helper instead. You don't have to worry about use statements and thus this sort of problem wont happen again.

$input = request()->all();

simple

How / can I display a console window in Intellij IDEA?

UPDATE: Console/Terminal feature was implemented in IDEA 13, PyCharm 3, RubyMine 6, WebStorm/PhpStorm 7.

There is a related feature request, please vote. Setting up an external tool to run a terminal can be used as a workaround.

Access restriction on class due to restriction on required library rt.jar?

for me this how I solve it:

  • go to the build path of the current project

under Libraries

  • select the "JRE System Library [jdk1.8xxx]"
  • click edit
  • and select either "Workspace default JRE(jdk1.8xx)" OR Alternate JRE
  • Click finish
  • Click OK

enter image description here

Note: make sure that in Eclipse / Preferences (NOT the project) / Java / Installed JRE ,that the jdk points to the JDK folder not the JRE C:\Program Files\Java\jdk1.8.0_74

enter image description here

Why does C# XmlDocument.LoadXml(string) fail when an XML header is included?

I figured it out. Read the MSDN documentation and it says to use .Load instead of LoadXml when reading from strings. Found out this works 100% of time. Oddly enough using StringReader causes problems. I think the main reason is that this is a Unicode encoded string and that could cause problems because StringReader is UTF-8 only.

MemoryStream stream = new MemoryStream();
            byte[] data = body.PayloadEncoding.GetBytes(body.Payload);
            stream.Write(data, 0, data.Length);
            stream.Seek(0, SeekOrigin.Begin);

            XmlTextReader reader = new XmlTextReader(stream);

            // MSDN reccomends we use Load instead of LoadXml when using in memory XML payloads
            bodyDoc.Load(reader);

File loading by getClass().getResource()

getClass().getResource() uses the class loader to load the resource. This means that the resource must be in the classpath to be loaded.

When doing it with Eclipse, everything you put in the source folder is "compiled" by Eclipse:

  • .java files are compiled into .class files that go the the bin directory (by default)
  • other files are copied to the bin directory (respecting the package/folder hirearchy)

When launching the program with Eclipse, the bin directory is thus in the classpath, and since it contains the Test.properties file, this file can be loaded by the class loader, using getResource() or getResourceAsStream().

If it doesn't work from the command line, it's thus because the file is not in the classpath.

Note that you should NOT do

FileInputStream inputStream = new FileInputStream(new File(getClass().getResource(url).toURI()));

to load a resource. Because that can work only if the file is loaded from the file system. If you package your app into a jar file, or if you load the classes over a network, it won't work. To get an InputStream, just use

getClass().getResourceAsStream("Test.properties")

And finally, as the documentation indicates,

Foo.class.getResourceAsStream("Test.properties")

will load a Test.properties file located in the same package as the class Foo.

Foo.class.getResourceAsStream("/com/foo/bar/Test.properties")

will load a Test.properties file located in the package com.foo.bar.

Error when using scp command "bash: scp: command not found"

Issue is with remote server, can you login to the remote server and check if "scp" works

probable causes: - scp is not in path - openssh client not installed correctly

for more details http://www.linuxquestions.org/questions/linux-newbie-8/bash-scp-command-not-found-920513/

Can't load IA 32-bit .dll on a AMD 64-bit platform

Short answer to first question: yes.

Longer answer: maybe; it depends on whether the build process for SVMLight behaves itself on 64-bit windows.

Final note: that call to System.loadLibrary is silly. Either call System.load with a full pathname or let it search java.library.path.

How to execute a raw update sql with dynamic binding in rails

ActiveRecord::Base.connection has a quote method that takes a string value (and optionally the column object). So you can say this:

ActiveRecord::Base.connection.execute(<<-EOQ)
  UPDATE  foo
  SET     bar = #{ActiveRecord::Base.connection.quote(baz)}
EOQ

Note if you're in a Rails migration or an ActiveRecord object you can shorten that to:

connection.execute(<<-EOQ)
  UPDATE  foo
  SET     bar = #{connection.quote(baz)}
EOQ

UPDATE: As @kolen points out, you should use exec_update instead. This will handle the quoting for you and also avoid leaking memory. The signature works a bit differently though:

connection.exec_update(<<-EOQ, "SQL", [[nil, baz]])
  UPDATE  foo
  SET     bar = $1
EOQ

Here the last param is a array of tuples representing bind parameters. In each tuple, the first entry is the column type and the second is the value. You can give nil for the column type and Rails will usually do the right thing though.

There are also exec_query, exec_insert, and exec_delete, depending on what you need.

Invalid column count in CSV input on line 1 Error

If your DB table already exists and you do NOT want to include all the table's columns in your CSV file, then when you run PHP Admin Import, you'll need fill in the Column Names field in the Format-Specific Options for CSV - Shown here at the bottom of the following screenshot.

In summary:

  • Choose a CSV file
  • Set the Format to CSV
  • Fill in the Column Names field with the names of the columns in your CSV
  • If your CSV file has the column names listed in row 1, set "Skip this number of queries (for SQL) or lines (for other formats), starting from the first one" to 1

enter image description here

Recursively list all files in a directory including files in symlink directories

find -L /var/www/ -type l

# man find
-L     Follow  symbolic links.  When find examines or prints information about files, the information used shall be taken from the

properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the subdirectory pointed to by the symbolic link will be searched.

How do I install cygwin components from the command line?

Dawid Ferenczy's answer is pretty complete but after I tried almost all of his options I've found that the Chocolatey’s cyg-get was the best (at least the only one that I could get to work).

I was wanting to install wget, the steps was this:

choco install cyg-get

Then:

cyg-get wget

Cannot use object of type stdClass as array?

When you try to access it as $result['context'], you treating it as an array, the error it's telling you that you are actually dealing with an object, then you should access it as $result->context

Windows.history.back() + location.reload() jquery

Try these ...

Option1

window.location=document.referrer;

Option2

window.location.reload(history.back());

How do I align a number like this in C?

Try converting to a string and then use "%4.4s" as the format specifier. This makes it a fixed width format.

Full Page <iframe>

This is what I have used in the past.

html, body {
  height: 100%;
  overflow: auto;
}

Also in the iframe add the following style

border: 0; position:fixed; top:0; left:0; right:0; bottom:0; width:100%; height:100%

permission denied - php unlink

// Path relative to where the php file is or absolute server path
chdir($FilePath); // Comment this out if you are on the same folder
chown($FileName,465); //Insert an Invalid UserId to set to Nobody Owner; for instance 465
$do = unlink($FileName);

if($do=="1"){ 
    echo "The file was deleted successfully."; 
} else { echo "There was an error trying to delete the file."; } 

Try this. Hope it helps.

PHP/regex: How to get the string value of HTML tag?

Since attribute values may contain a plain > character, try this regular expression:

$pattern = '/<'.preg_quote($tagname, '/').'(?:[^"'>]*|"[^"]*"|\'[^\']*\')*>(.*?)<\/'.preg_quote($tagname, '/').'>/s';

But regular expressions are not suitable for parsing non-regular languages like HTML. You should better use a parser like SimpleXML or DOMDocument.

jQuery click anywhere in the page except on 1 div

here is what i did. wanted to make sure i could click any of the children in my datepicker without closing it.

$('html').click(function(e){
    if (e.target.id == 'menu_content' || $(e.target).parents('#menu_content').length > 0) {
        // clicked menu content or children
    } else {
        // didnt click menu content
    }
});

my actual code:

$('html').click(function(e){
    if (e.target.id != 'datepicker'
        && $(e.target).parents('#datepicker').length == 0
        && !$(e.target).hasClass('datepicker')
    ) {
        $('#datepicker').remove();
    }
});

select data up to a space?

You can use a combiation of LEFT and CHARINDEX to find the index of the first space, and then grab everything to the left of that.

 SELECT LEFT(YourColumn, charindex(' ', YourColumn) - 1) 

And in case any of your columns don't have a space in them:

SELECT LEFT(YourColumn, CASE WHEN charindex(' ', YourColumn) = 0 THEN 
    LEN(YourColumn) ELSE charindex(' ', YourColumn) - 1 END)

jQuery disable a link

Here is an alternate css/jQuery solution that I prefer for its terseness and minimized scripting:

css:

a.disabled {
  opacity: 0.5;
  pointer-events: none;
  cursor: default;
}

jQuery:

$('.disableAfterClick').click(function (e) {
   $(this).addClass('disabled');
});

Mockito How to mock and assert a thrown exception?

Unrelated to mockito, one can catch the exception and assert its properties. To verify that the exception did happen, assert a false condition within the try block after the statement that throws the exception.

Eclipse+Maven src/main/java not visible in src folder in Package Explorer

I had the same problem, I changed my Eclipse project view from Package explorer to Project Explorer.

Case statement in MySQL

This should work:

select 
  id
  ,action_heading
  ,case when action_type='Income' then action_amount else 0 end
  ,case when action_type='Expense' then expense_amount else 0 end
from tbl_transaction

Copy an entire worksheet to a new worksheet in Excel 2010

It is simpler just to run an exact copy like below to put the copy in as the last sheet

Sub Test()
Dim ws1 As Worksheet
Set ws1 = ThisWorkbook.Worksheets("Master")
ws1.Copy ThisWorkbook.Sheets(Sheets.Count)
End Sub

Android: adbd cannot run as root in production builds

For those who rooted the Android device with Magisk, you can install adb_root from https://github.com/evdenis/adb_root. Then adb root can run smoothly.

mysql is not recognised as an internal or external command,operable program or batch

Simply type in command prompt :

set path=%PATH%;D:\xampp\mysql\bin;

Here my path started from D so I used D: , you can use C: or E:

enter image description here

C# Regex for Guid

In .NET Framework 4 there is enhancement System.Guid structure, These includes new TryParse and TryParseExact methods to Parse GUID. Here is example for this.

    //Generate New GUID
    Guid objGuid = Guid.NewGuid();
    //Take invalid guid format
    string strGUID = "aaa-a-a-a-a";

    Guid newGuid;

    if (Guid.TryParse(objGuid.ToString(), out newGuid) == true)
    {
        Response.Write(string.Format("<br/>{0} is Valid GUID.", objGuid.ToString()));
    }
    else
    {
        Response.Write(string.Format("<br/>{0} is InValid GUID.", objGuid.ToString()));
    }


    Guid newTmpGuid;

    if (Guid.TryParse(strGUID, out newTmpGuid) == true)
    {
        Response.Write(string.Format("<br/>{0} is Valid GUID.", strGUID));
    }
    else
    {
        Response.Write(string.Format("<br/>{0} is InValid GUID.", strGUID));
    }

In this example we create new guid object and also take one string variable which has invalid guid. After that we use TryParse method to validate that both variable has valid guid format or not. By running example you can see that string variable has not valid guid format and it gives message of "InValid guid". If string variable has valid guid than this will return true in TryParse method.

How to find a value in an array and remove it by using PHP array functions?

The unset array_search has some pretty terrible side effects because it can accidentally strip the first element off your array regardless of the value:

        // bad side effects
        $a = [0,1,2,3,4,5];
        unset($a[array_search(3, $a)]);
        unset($a[array_search(6, $a)]);
        $this->log_json($a);
        // result: [1,2,4,5]
        // what? where is 0?
        // it was removed because false is interpreted as 0

        // goodness
        $b = [0,1,2,3,4,5];
        $b = array_diff($b, [3,6]);
        $this->log_json($b);
        // result: [0,1,2,4,5]

If you know that the value is guaranteed to be in the array, go for it, but I think the array_diff is far safer. (I'm using php7)

adding text to an existing text element in javascript via DOM

The method .appendChild() is used to add a new element NOT add text to an existing element.

Example:

var p = document.createElement("p");
document.body.appendChild(p);

Reference: Mozilla Developer Network

The standard approach for this is using .innerHTML(). But if you want a alternate solution you could try using element.textContent.

Example:

document.getElementById("foo").textContent = "This is som text";

Reference: Mozilla Developer Network

How ever this is only supported in IE 9+

Trust Store vs Key Store - creating with keytool

To explain in common usecase/purpose or layman way:

TrustStore : As the name indicates, its normally used to store the certificates of trusted entities. A process can maintain a store of certificates of all its trusted parties which it trusts.

keyStore : Used to store the server keys (both public and private) along with signed cert.

During the SSL handshake,

  1. A client tries to access https://

  2. And thus, Server responds by providing a SSL certificate (which is stored in its keyStore)

  3. Now, the client receives the SSL certificate and verifies it via trustStore (i.e the client's trustStore already has pre-defined set of certificates which it trusts.). Its like : Can I trust this server ? Is this the same server whom I am trying to talk to ? No middle man attacks ?

  4. Once, the client verifies that it is talking to server which it trusts, then SSL communication can happen over a shared secret key.

Note : I am not talking here anything about client authentication on server side. If a server wants to do a client authentication too, then the server also maintains a trustStore to verify client. Then it becomes mutual TLS

How to correctly display .csv files within Excel 2013?

The problem is from regional Options . The decimal separator in win 7 for european countries is coma . You have to open Control Panel -> Regional and Language Options -> Aditional Settings -> Decimal Separator : click to enter a dot (.) and to List Separator enter a coma (,) . This is !

How do I get the n-th level parent of an element in jQuery?

Just add :eq() selector like this:

$("#element").parents(":eq(2)")

You just specify index which parent: 0 for immediate parent, 1 for grand-parent, ...

Check if inputs form are empty jQuery

You could do it like this :

bool areFieldEmpty = YES;
//Label to leave the loops
outer_loop;

//For each input (except of submit) in your form
$('form input[type!=submit]').each(function(){
   //If the field's empty
   if($(this).val() != '')
   {
      //Mark it
      areFieldEmpty = NO;
      //Then leave all the loops
      break outer_loop;
   }
});

//Then test your bool 

Jquery, set value of td in a table?

$("#button_id").click(function(){ $("#detailInfo").html("WHAT YOU WANT") })

How do I mock a REST template exchange?

For me, I had to use Matchers.any(URI.class)

Mockito.when(restTemplate.exchange(Matchers.any(URI.class), Matchers.any(HttpMethod.class), Matchers.<HttpEntity<?>> any(), Matchers.<Class<Object>> any())).thenReturn(myEntity);

How do I use typedef and typedef enum in C?

typedef defines a new data type. So you can have:

typedef char* my_string;
typedef struct{
  int member1;
  int member2;
} my_struct;

So now you can declare variables with these new data types

my_string s;
my_struct x;

s = "welcome";
x.member1 = 10;

For enum, things are a bit different - consider the following examples:

enum Ranks {FIRST, SECOND};
int main()
{
   int data = 20;
   if (data == FIRST)
   {
      //do something
   }
}

using typedef enum creates an alias for a type:

typedef enum Ranks {FIRST, SECOND} Order;
int main()
{
   Order data = (Order)20;  // Must cast to defined type to prevent error

   if (data == FIRST)
   {
      //do something
   }
}

MySQL - Make an existing Field Unique

Just write this query in your db phpmyadmin.

ALTER TABLE TableName ADD UNIQUE (FieldName)

Eg: ALTER TABLE user ADD UNIQUE (email)

How can I get a side-by-side diff when I do "git diff"?

I personally really like icdiff !

If you're on Mac OS X with HomeBrew, just do brew install icdiff.

To get the file labels correctly, plus other cool features, I have in my ~/.gitconfig:

[pager]
    difftool = true
[diff]
    tool = icdiff
[difftool "icdiff"]
    cmd = icdiff --head=5000 --highlight --line-numbers -L \"$BASE\" -L \"$REMOTE\" \"$LOCAL\" \"$REMOTE\"

And I use it like: git difftool

How to check if a std::thread is still running?

Surely have a mutex-wrapped variable initialised to false, that the thread sets to true as the last thing it does before exiting. Is that atomic enough for your needs?

Bootstrap date and time picker

If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:

The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.

How can I convert a Word document to PDF?

I agree with posters listing OpenOffice as a high-fidelity import/export facility of word / pdf docs with a Java API and it also works across platforms. OpenOffice import/export filters are pretty powerful and preserve most formatting during conversion to various formats including PDF. Docmosis and JODReports value-add to make life easier than learning the OpenOffice API directly which can be challenging because of the style of the UNO api and the crash-related bugs.

How to change the default GCC compiler in Ubuntu?

This is the great description and step-by-step instruction how to create and manage master and slave (gcc and g++) alternatives.

Shortly it's:

sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.6 60 --slave /usr/bin/g++ g++ /usr/bin/g++-4.6
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.7 40 --slave /usr/bin/g++ g++ /usr/bin/g++-4.7
sudo update-alternatives --config gcc

Where can I download Spring Framework jars without using Maven?

Please edit to keep this list of mirrors current

I found this maven repo where you could download from directly a zip file containing all the jars you need.

Alternate solution: Maven

The solution I prefer is using Maven, it is easy and you don't have to download each jar alone. You can do it with the following steps:

  1. Create an empty folder anywhere with any name you prefer, for example spring-source

  2. Create a new file named pom.xml

  3. Copy the xml below into this file

  4. Open the spring-source folder in your console

  5. Run mvn install

  6. After download finished, you'll find spring jars in /spring-source/target/dependencies

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>spring-source-download</groupId>
      <artifactId>SpringDependencies</artifactId>
      <version>1.0</version>
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
      <dependencies>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>3.2.4.RELEASE</version>
        </dependency>
      </dependencies>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.8</version>
            <executions>
              <execution>
                <id>download-dependencies</id>
                <phase>generate-resources</phase>
                <goals>
                  <goal>copy-dependencies</goal>
                </goals>
                <configuration>
                  <outputDirectory>${project.build.directory}/dependencies</outputDirectory>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </project>
    

Also, if you need to download any other spring project, just copy the dependency configuration from its corresponding web page.

For example, if you want to download Spring Web Flow jars, go to its web page, and add its dependency configuration to the pom.xml dependencies, then run mvn install again.

<dependency>
  <groupId>org.springframework.webflow</groupId>
  <artifactId>spring-webflow</artifactId>
  <version>2.3.2.RELEASE</version>
</dependency>

TypeError: 'type' object is not subscriptable when indexing in to a dictionary

Normally Python throws NameError if the variable is not defined:

>>> d[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined

However, you've managed to stumble upon a name that already exists in Python.

Because dict is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.

The type of dict is a type. All types are objects in Python. Thus you are actually trying to index into the type object. This is why the error message says that the "'type' object is not subscriptable."

>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable

Note that you can blindly assign to the dict name, but you really don't want to do that. It's just going to cause you problems later.

>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'

The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:

d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))

How to get name of the computer in VBA?

Dim sHostName As String

' Get Host Name / Get Computer Name

sHostName = Environ$("computername")

Getting Integer value from a String using javascript/jquery

For parseInt to work, your string should have only numerical data. Something like this:

 str1 = "123.00";
 str2 = "50.00";
 total = parseInt(str1)+parseInt(str2);
 alert(total);

Can you split the string before you start processing them for a total?

How can I pipe stderr, and not stdout?

Or to swap the output from standard error and standard output over, use:

command 3>&1 1>&2 2>&3

This creates a new file descriptor (3) and assigns it to the same place as 1 (standard output), then assigns fd 1 (standard output) to the same place as fd 2 (standard error) and finally assigns fd 2 (standard error) to the same place as fd 3 (standard output).

Standard error is now available as standard output and the old standard output is preserved in standard error. This may be overkill, but it hopefully gives more details on Bash file descriptors (there are nine available to each process).

Mount current directory as a volume in Docker on Windows 10

  1. Open Settings on Docker Desktop (Docker for Windows).
  2. Select Shared Drives.
  3. Select the drive that you want to use inside your containers (e.g., C).
  4. Click Apply. You may be asked to provide user credentials. Enabling drives for containers on Windows

  5. The command below should now work on PowerShell (command prompt does not support ${PWD}):

    docker run --rm -v ${PWD}:/data alpine ls /data

IMPORTANT: if/when you change your Windows domain password, the mount will stop working silently, that is, -v will work but the container will not see your host folders and files. Solution: go back to Settings, uncheck the shared drives, Apply, check them again, Apply, and enter the new password when prompted.

In Java, how do you determine if a thread is running?

Thread.State enum class and the new getState() API are provided for querying the execution state of a thread.

A thread can be in only one state at a given point in time. These states are virtual machine states which do not reflect any operating system thread states [NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED].

enum Thread.State extends Enum implements Serializable, Comparable

  • getState()jdk5 - public State getState() {...} « Returns the state of this thread. This method is designed for use in monitoring of the system state, not for synchronization control.

  • isAlive() - public final native boolean isAlive(); « Returns true if the thread upon which it is called is still alive, otherwise it returns false. A thread is alive if it has been started and has not yet died.

Sample Source Code's of classes java.lang.Thread and sun.misc.VM.

package java.lang;
public class Thread implements Runnable {
    public final native boolean isAlive();

    // Java thread status value zero corresponds to state "NEW" - 'not yet started'.
    private volatile int threadStatus = 0;

    public enum State {
        NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED;
    }

    public State getState() {
        return sun.misc.VM.toThreadState(threadStatus);
    }
}

package sun.misc;
public class VM {
    // ...
    public static Thread.State toThreadState(int threadStatus) {
        if ((threadStatus & JVMTI_THREAD_STATE_RUNNABLE) != 0) {
            return Thread.State.RUNNABLE;
        } else if ((threadStatus & JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER) != 0) {
            return Thread.State.BLOCKED;
        } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_INDEFINITELY) != 0) {
            return Thread.State.WAITING;
        } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT) != 0) {
            return Thread.State.TIMED_WAITING;
        } else if ((threadStatus & JVMTI_THREAD_STATE_TERMINATED) != 0) {
            return Thread.State.TERMINATED;
        } else if ((threadStatus & JVMTI_THREAD_STATE_ALIVE) == 0) {
            return Thread.State.NEW;
        } else {
            return Thread.State.RUNNABLE;
        }
    }
}

Example with java.util.concurrent.CountDownLatch to execute multiple threads parallel, After completing all threads main thread execute. (until parallel threads complete their task main thread will be blocked.)

public class MainThread_Wait_TillWorkerThreadsComplete {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("Main Thread Started...");
        // countDown() should be called 4 time to make count 0. So, that await() will release the blocking threads.
        int latchGroupCount = 4;
        CountDownLatch latch = new CountDownLatch(latchGroupCount);
        new Thread(new Task(2, latch), "T1").start();
        new Thread(new Task(7, latch), "T2").start();
        new Thread(new Task(5, latch), "T3").start();
        new Thread(new Task(4, latch), "T4").start();

        //latch.countDown(); // Decrements the count of the latch group.

        // await() method block until the current count reaches to zero
        latch.await(); // block until latchGroupCount is 0
        System.out.println("Main Thread completed.");
    }
}
class Task extends Thread {
    CountDownLatch latch;
    int iterations = 10;
    public Task(int iterations, CountDownLatch latch) {
        this.iterations = iterations;
        this.latch = latch;
    }
    @Override
    public void run() {
        String threadName = Thread.currentThread().getName();
        System.out.println(threadName + " : Started Task...");
        for (int i = 0; i < iterations; i++) {
            System.out.println(threadName + " : "+ i);
            sleep(1);
        }
        System.out.println(threadName + " : Completed Task");
        latch.countDown(); // Decrements the count of the latch,
    }
    public void sleep(int sec) {
        try {
            Thread.sleep(1000 * sec);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

@See also

What Does This Mean in PHP -> or =>

->

calls/sets object variables. Ex:

$obj = new StdClass;
$obj->foo = 'bar';
var_dump($obj);

=> Sets key/value pairs for arrays. Ex:

$array = array(
    'foo' => 'bar'
);
var_dump($array);

How to compile a c++ program in Linux?

  1. To Compile your C++ code use:-

g++ file_name.cpp -o executable_file_name

(i) -o option is used to show error in the code (ii) if there is no error in the code_file, then it will generate an executable file.

  1. Now execute the generated executable file:

./executable_file_name

How to view .img files?

OSFMount , MagicDisc , Gizmo Director/Gizmo Drive , The Takeaway .

All these work well on .img files

Error: allowDefinition='MachineToApplication' beyond application level

I have just had this problem when building a second version of my website. It didn't happen when I built it the first time.

I have just deleted the bin and obj folders, run a Clean Solution and built it again, this time without any problem.

Python loop for inside lambda

anon and chepner's answers are on the right track. Python 3.x has a print function and this is what you will need if you want to embed print within a function (and, a fortiori, lambdas).

However, you can get the print function very easily in python 2.x by importing from the standard library's future module. Check it out:

>>>from __future__ import print_function
>>>
>>>iterable = ["a","b","c"]
>>>map(print, iterable)
a
b
c
[None, None, None]
>>>

I guess that looks kind of weird, so feel free to assign the return to _ if you would like to suppress [None, None, None]'s output (you are interested in the side-effects only, I assume):

>>>_ = map(print, iterable)
a
b
c
>>>

In Tensorflow, get the names of all the Tensors in a graph

You can do

[n.name for n in tf.get_default_graph().as_graph_def().node]

Also, if you are prototyping in an IPython notebook, you can show the graph directly in notebook, see show_graph function in Alexander's Deep Dream notebook

Store select query's output in one array in postgres

There are two ways. One is to aggregate:

SELECT array_agg(column_name::TEXT)
FROM information.schema.columns
WHERE table_name = 'aean'

The other is to use an array constructor:

SELECT ARRAY(
SELECT column_name 
FROM information.schema.columns 
WHERE table_name = 'aean')

I'm presuming this is for plpgsql. In that case you can assign it like this:

colnames := ARRAY(
SELECT column_name
FROM information.schema.columns
WHERE table_name='aean'
);

How to calculate the width of a text string of a specific font and font-size?

If you're struggling to get text width with multiline support, so you can use the next code (Swift 5):

func width(text: String, height: CGFloat) -> CGFloat {
    let attributes: [NSAttributedString.Key: Any] = [
        .font: UIFont.systemFont(ofSize: 17)
    ]
    let attributedText = NSAttributedString(string: text, attributes: attributes)
    let constraintBox = CGSize(width: .greatestFiniteMagnitude, height: height)
    let textWidth = attributedText.boundingRect(with: constraintBox, options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil).width.rounded(.up)

    return textWidth
}

And the same way you could find text height if you need to (just switch the constraintBox implementation):

let constraintBox = CGSize(width: maxWidth, height: .greatestFiniteMagnitude)

Or here's a unified function to get text size with multiline support:

func labelSize(for text: String, maxWidth: CGFloat, maxHeight: CGFloat) -> CGSize {
    let attributes: [NSAttributedString.Key: Any] = [
        .font: UIFont.systemFont(ofSize: 17)
    ]

    let attributedText = NSAttributedString(string: text, attributes: attributes)

    let constraintBox = CGSize(width: maxWidth, height: maxHeight)
    let rect = attributedText.boundingRect(with: constraintBox, options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil).integral

    return rect.size
}

Usage:

let textSize = labelSize(for: "SomeText", maxWidth: contentView.bounds.width, maxHeight: .greatestFiniteMagnitude)
let textHeight = textSize.height.rounded(.up)
let textWidth = textSize.width.rounded(.up)

Sorting a Data Table

After setting the sort expression on the DefaultView (table.DefaultView.Sort = "Town ASC, Cutomer ASC" ) you should loop over the table using the DefaultView not the DataTable instance itself

foreach(DataRowView r in table.DefaultView)
{
    //... here you get the rows in sorted order
    Console.WriteLine(r["Town"].ToString());
}

Using the Select method of the DataTable instead, produces an array of DataRow. This array is sorted as from your request, not the DataTable

DataRow[] rowList = table.Select("", "Town ASC, Cutomer ASC");
foreach(DataRow r in rowList)
{
    Console.WriteLine(r["Town"].ToString());
}

Difference between __getattr__ vs __getattribute__

New-style classes inherit from object, or from another new style class:

class SomeObject(object):
    pass

class SubObject(SomeObject):
    pass

Old-style classes don't:

class SomeObject:
    pass

This only applies to Python 2 - in Python 3 all the above will create new-style classes.

See 9. Classes (Python tutorial), NewClassVsClassicClass and What is the difference between old style and new style classes in Python? for details.

Default value in an asp.net mvc view model

Set this in the constructor:

public class SearchModel
{
    public bool IsMale { get; set; }
    public bool IsFemale { get; set; }

    public SearchModel()
    { 
        IsMale = true;
        IsFemale = true;
    }
}

Then pass it to the view in your GET action:

[HttpGet]
public ActionResult Search()
{
    return new View(new SearchModel());
}

JS how to cache a variable

You could possibly create a cookie if thats allowed in your requirment. If you choose to take the cookie route then the solution could be as follows. Also the benefit with cookie is after the user closes the Browser and Re-opens, if the cookie has not been deleted the value will be persisted.

Cookie *Create and Store a Cookie:*

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

The function which will return the specified cookie:

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

Display a welcome message if the cookie is set

function checkCookie()
{
var username=getCookie("username");
  if (username!=null && username!="")
  {
  alert("Welcome again " + username);
  }
else 
  {
  username=prompt("Please enter your name:","");
  if (username!=null && username!="")
    {
    setCookie("username",username,365);
    }
  }
}

The above solution is saving the value through cookies. Its a pretty standard way without storing the value on the server side.

Jquery

Set a value to the session storage.

Javascript:

$.sessionStorage( 'foo', {data:'bar'} );

Retrieve the value:

$.sessionStorage( 'foo', {data:'bar'} );

$.sessionStorage( 'foo' );Results:
{data:'bar'}

Local Storage Now lets take a look at Local storage. Lets say for example you have an array of variables that you are wanting to persist. You could do as follows:

var names=[];
names[0]=prompt("New name?");
localStorage['names']=JSON.stringify(names);

//...
var storedNames=JSON.parse(localStorage['names']);

Server Side Example using ASP.NET

Adding to Sesion

Session["FirstName"] = FirstNameTextBox.Text;
Session["LastName"] = LastNameTextBox.Text;

// When retrieving an object from session state, cast it to // the appropriate type.

ArrayList stockPicks = (ArrayList)Session["StockPicks"];

// Write the modified stock picks list back to session state.
Session["StockPicks"] = stockPicks;

I hope that answered your question.

How can I represent an 'Enum' in Python?

Python doesn't have a built-in equivalent to enum, and other answers have ideas for implementing your own (you may also be interested in the over the top version in the Python cookbook).

However, in situations where an enum would be called for in C, I usually end up just using simple strings: because of the way objects/attributes are implemented, (C)Python is optimized to work very fast with short strings anyway, so there wouldn't really be any performance benefit to using integers. To guard against typos / invalid values you can insert checks in selected places.

ANIMALS = ['cat', 'dog', 'python']

def take_for_a_walk(animal):
    assert animal in ANIMALS
    ...

(One disadvantage compared to using a class is that you lose the benefit of autocomplete)

Difference between ProcessBuilder and Runtime.exec()

There are no difference between ProcessBuilder.start() and Runtime.exec() because implementation of Runtime.exec() is:

public Process exec(String command) throws IOException {
    return exec(command, null, null);
}

public Process exec(String command, String[] envp, File dir)
    throws IOException {
    if (command.length() == 0)
        throw new IllegalArgumentException("Empty command");

    StringTokenizer st = new StringTokenizer(command);
    String[] cmdarray = new String[st.countTokens()];
    for (int i = 0; st.hasMoreTokens(); i++)
        cmdarray[i] = st.nextToken();
    return exec(cmdarray, envp, dir);
}

public Process exec(String[] cmdarray, String[] envp, File dir)
    throws IOException {
    return new ProcessBuilder(cmdarray)
        .environment(envp)
        .directory(dir)
        .start();
}

So code:

List<String> list = new ArrayList<>();
new StringTokenizer(command)
.asIterator()
.forEachRemaining(str -> list.add((String) str));
new ProcessBuilder(String[])list.toArray())
            .environment(envp)
            .directory(dir)
            .start();

should be the same as:

Runtime.exec(command)

Thanks dave_thompson_085 for comment

Webpack not excluding node_modules

This worked for me:

exclude: [/bower_components/, /node_modules/]

module.loaders

A array of automatically applied loaders.

Each item can have these properties:

test: A condition that must be met

exclude: A condition that must not be met

include: A condition that must be met

loader: A string of "!" separated loaders

loaders: A array of loaders as string

A condition can be a RegExp, an absolute path start, or an array of one of these combined with "and".

See http://webpack.github.io/docs/configuration.html#module-loaders

Maven- No plugin found for prefix 'spring-boot' in the current project and in the plugin groups

You should run the $ mvn spring-boot:run from the folder where your pom.xml file is located and refer to this answer https://stackoverflow.com/a/33602837/4918021

Joining pairs of elements of a list

You can use slice notation with steps:

>>> x = "abcdefghijklm"
>>> x[0::2] #0. 2. 4...
'acegikm'
>>> x[1::2] #1. 3. 5 ..
'bdfhjl'
>>> [i+j for i,j in zip(x[::2], x[1::2])] # zip makes (0,1),(2,3) ...
['ab', 'cd', 'ef', 'gh', 'ij', 'kl']

Same logic applies for lists too. String lenght doesn't matter, because you're simply adding two strings together.

newline in <td title="">

This should now work with Internet Explorer, Firefox v12+ and Chrome 28+

<img src="'../images/foo.gif'" 
  alt="line 1&#013;line 2" title="line 1&#013;line 2">

Try a JavaScript tooltip library for a better result, something like OverLib.

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

You will have to annotate your service with @Service since you have said I am using annotations for mapping

How to write subquery inside the OUTER JOIN Statement

I think you don't have to use sub query in this scenario.You can directly left outer join the DEPRMNT table .

While using Left Outer Join ,don't use columns in the RHS table of the join in the where condition, you ll get wrong output

Thin Black Border for a Table

Style the td and th instead

td, th {
    border: 1px solid black;
}

And also to make it so there is no spacing between cells use:

table {
    border-collapse: collapse;
}

(also note, you have border-style: none; which should be border-style: solid;)

See an example here: http://jsfiddle.net/KbjNr/

Efficiently replace all accented characters in a string?

A simple and easy way:

function remove-accents(p){
c='áàãâäéèêëíìîïóòõôöúùûüçÁÀÃÂÄÉÈÊËÍÌÎÏÓÒÕÖÔÚÙÛÜÇ';s='aaaaaeeeeiiiiooooouuuucAAAAAEEEEIIIIOOOOOUUUUC';n='';for(i=0;i<p.length;i++){if(c.search(p.substr(i,1))>=0){n+=s.substr(c.search(p.substr(i,1)),1);} else{n+=p.substr(i,1);}} return n;
}

So do this:

remove-accents("Thís ís ân accêntéd phráse");

Output:

"This is an accented phrase"

How to change an image on click using CSS alone?

Try this (but once clicked, it is not reversible):

HTML:

<a id="test"><img src="normal-image.png"/></a>

CSS:

a#test {
    border: 0;
}
a#test:visited img, a#test:active img {
    background-image: url(clicked-image.png);
}

Algorithm for solving Sudoku

There are four steps to solve a sudoku puzzle:

  1. Identify all possibilities for each cell (getting from the row, column and box) and try to develop a possible matrix. 2.Check for double pair, if it exists then remove these two values from all the cells in that row/column/box, wherever the pair exists If any cell is having single possiblity then assign that run step 1 again
  2. Check for each cell with each row, column and box. If the cell has one value which does not belong in the other possible values then assign that value to that cell. run step 1 again
  3. If the sudoku is still not solved, then we need to start the following assumption, Assume the first possible value and assign. Then run step 1–3 If still not solved then do it for next possible value and run it in recursion.
  4. If the sudoku is still not solved, then we need to start the following assumption, Assume the first possible value and assign. Then run step 1–3

If still not solved then do it for next possible value and run it in recursion.

import math
import sys


def is_solved(l):
    for x, i in enumerate(l):
        for y, j in enumerate(i):
            if j == 0:
                # Incomplete
                return None
            for p in range(9):
                if p != x and j == l[p][y]:
                    # Error
                    print('horizontal issue detected!', (x, y))
                    return False
                if p != y and j == l[x][p]:
                    # Error
                    print('vertical issue detected!', (x, y))
                    return False
            i_n, j_n = get_box_start_coordinate(x, y)
            for (i, j) in [(i, j) for p in range(i_n, i_n + 3) for q in range(j_n, j_n + 3)
                           if (p, q) != (x, y) and j == l[p][q]]:
                    # Error
                print('box issue detected!', (x, y))
                return False
    # Solved
    return True


def is_valid(l):
    for x, i in enumerate(l):
        for y, j in enumerate(i):
            if j != 0:
                for p in range(9):
                    if p != x and j == l[p][y]:
                        # Error
                        print('horizontal issue detected!', (x, y))
                        return False
                    if p != y and j == l[x][p]:
                        # Error
                        print('vertical issue detected!', (x, y))
                        return False
                i_n, j_n = get_box_start_coordinate(x, y)
                for (i, j) in [(i, j) for p in range(i_n, i_n + 3) for q in range(j_n, j_n + 3)
                               if (p, q) != (x, y) and j == l[p][q]]:
                        # Error
                    print('box issue detected!', (x, y))
                    return False
    # Solved
    return True


def get_box_start_coordinate(x, y):
    return 3 * int(math.floor(x/3)), 3 * int(math.floor(y/3))


def get_horizontal(x, y, l):
    return [l[x][i] for i in range(9) if l[x][i] > 0]


def get_vertical(x, y, l):
    return [l[i][y] for i in range(9) if l[i][y] > 0]


def get_box(x, y, l):
    existing = []
    i_n, j_n = get_box_start_coordinate(x, y)
    for (i, j) in [(i, j) for i in range(i_n, i_n + 3) for j in range(j_n, j_n + 3)]:
        existing.append(l[i][j]) if l[i][j] > 0 else None
    return existing


def detect_and_simplify_double_pairs(l, pl):
    for (i, j) in [(i, j) for i in range(9) for j in range(9) if len(pl[i][j]) == 2]:
        temp_pair = pl[i][j]
        for p in (p for p in range(j+1, 9) if len(pl[i][p]) == 2 and len(set(pl[i][p]) & set(temp_pair)) == 2):
            for q in (q for q in range(9) if q != j and q != p):
                pl[i][q] = list(set(pl[i][q]) - set(temp_pair))
                if len(pl[i][q]) == 1:
                    l[i][q] = pl[i][q].pop()
                    return True
        for p in (p for p in range(i+1, 9) if len(pl[p][j]) == 2 and len(set(pl[p][j]) & set(temp_pair)) == 2):
            for q in (q for q in range(9) if q != i and p != q):
                pl[q][j] = list(set(pl[q][j]) - set(temp_pair))
                if len(pl[q][j]) == 1:
                    l[q][j] = pl[q][j].pop()
                    return True
        i_n, j_n = get_box_start_coordinate(i, j)
        for (a, b) in [(a, b) for a in range(i_n, i_n+3) for b in range(j_n, j_n+3)
                       if (a, b) != (i, j) and len(pl[a][b]) == 2 and len(set(pl[a][b]) & set(temp_pair)) == 2]:
            for (c, d) in [(c, d) for c in range(i_n, i_n+3) for d in range(j_n, j_n+3)
                           if (c, d) != (a, b) and (c, d) != (i, j)]:
                pl[c][d] = list(set(pl[c][d]) - set(temp_pair))
                if len(pl[c][d]) == 1:
                    l[c][d] = pl[c][d].pop()
                    return True
    return False


def update_unique_horizontal(x, y, l, pl):
    tl = pl[x][y]
    for i in (i for i in range(9) if i != y):
        tl = list(set(tl) - set(pl[x][i]))
    if len(tl) == 1:
        l[x][y] = tl.pop()
        return True
    return False


def update_unique_vertical(x, y, l, pl):
    tl = pl[x][y]
    for i in (i for i in range(9) if i != x):
        tl = list(set(tl) - set(pl[i][y]))
    if len(tl) == 1:
        l[x][y] = tl.pop()
        return True
    return False


def update_unique_box(x, y, l, pl):
    tl = pl[x][y]
    i_n, j_n = get_box_start_coordinate(x, y)
    for (i, j) in [(i, j) for i in range(i_n, i_n+3) for j in range(j_n, j_n+3) if (i, j) != (x, y)]:
        tl = list(set(tl) - set(pl[i][j]))
    if len(tl) == 1:
        l[x][y] = tl.pop()
        return True
    return False


def find_and_place_possibles(l):
    while True:
        pl = populate_possibles(l)
        if pl != False:
            return pl


def populate_possibles(l):
    pl = [[[]for j in i] for i in l]
    for (i, j) in [(i, j) for i in range(9) for j in range(9) if l[i][j] == 0]:
        p = list(set(range(1, 10)) - set(get_horizontal(i, j, l) +
                                         get_vertical(i, j, l) + get_box(i, j, l)))
        if len(p) == 1:
            l[i][j] = p.pop()
            return False
        else:
            pl[i][j] = p
    return pl


def find_and_remove_uniques(l, pl):
    for (i, j) in [(i, j) for i in range(9) for j in range(9) if l[i][j] == 0]:
        if update_unique_horizontal(i, j, l, pl) == True:
            return True
        if update_unique_vertical(i, j, l, pl) == True:
            return True
        if update_unique_box(i, j, l, pl) == True:
            return True
    return False


def try_with_possibilities(l):
    while True:
        improv = False
        pl = find_and_place_possibles(l)
        if detect_and_simplify_double_pairs(
                l, pl) == True:
            continue
        if find_and_remove_uniques(
                l, pl) == True:
            continue
        if improv == False:
            break
    return pl


def get_first_conflict(pl):
    for (x, y) in [(x, y) for x, i in enumerate(pl) for y, j in enumerate(i) if len(j) > 0]:
        return (x, y)


def get_deep_copy(l):
    new_list = [i[:] for i in l]
    return new_list


def run_assumption(l, pl):
    try:
        c = get_first_conflict(pl)
        fl = pl[c[0]
                ][c[1]]
        # print('Assumption Index : ', c)
        # print('Assumption List: ',  fl)
    except:
        return False
    for i in fl:
        new_list = get_deep_copy(l)
        new_list[c[0]][c[1]] = i
        new_pl = try_with_possibilities(new_list)
        is_done = is_solved(new_list)
        if is_done == True:
            l = new_list
            return new_list
        else:
            new_list = run_assumption(new_list, new_pl)
            if new_list != False and is_solved(new_list) == True:
                return new_list
    return False


if __name__ == "__main__":
    l = [
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 8, 0, 0, 0, 0, 4, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 6, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [2, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 2, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0]
    ]
    # This puzzle copied from Hacked rank test case
    if is_valid(l) == False:
        print("Sorry! Invalid.")
        sys.exit()
    pl = try_with_possibilities(l)
    is_done = is_solved(l)
    if is_done == True:
        for i in l:
            print(i)
        print("Solved!!!")
        sys.exit()

    print("Unable to solve by traditional ways")
    print("Starting assumption based solving")
    new_list = run_assumption(l, pl)
    if new_list != False:
        is_done = is_solved(new_list)
        print('is solved ? - ', is_done)
        for i in new_list:
            print(i)
        if is_done == True:
            print("Solved!!! with assumptions.")
        sys.exit()
    print(l)
    print("Sorry! No Solution. Need to fix the valid function :(")
    sys.exit()

LINQ select one field from list of DTO objects to array

I think you're looking for;

  string[] skus = myLines.Select(x => x.Sku).ToArray();

However, if you're going to iterate over the sku's in subsequent code I recommend not using the ToArray() bit as it forces the queries execution prematurely and makes the applications performance worse. Instead you can just do;

  var skus = myLines.Select(x => x.Sku); // produce IEnumerable<string>

  foreach (string sku in skus) // forces execution of the query

Shadow Effect for a Text in Android?

put these in values/colors.xml

<resources>
    <color name="light_font">#FBFBFB</color>
    <color name="grey_font">#ff9e9e9e</color>
    <color name="text_shadow">#7F000000</color>
    <color name="text_shadow_white">#FFFFFF</color>
</resources>

Then in your layout xml here are some example TextView's

Example of Floating text on Light with Dark shadow

<TextView android:id="@+id/txt_example1"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:textSize="14sp"
                  android:textStyle="bold"
                  android:textColor="@color/light_font"
                  android:shadowColor="@color/text_shadow"
                  android:shadowDx="1"
                  android:shadowDy="1"
                  android:shadowRadius="2" />

enter image description here

Example of Etched text on Light with Dark shadow

<TextView android:id="@+id/txt_example2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="14sp"
                android:textStyle="bold"
                android:textColor="@color/light_font"
                android:shadowColor="@color/text_shadow"
                android:shadowDx="-1"
                android:shadowDy="-1"
                android:shadowRadius="1" />

enter image description here

Example of Crisp text on Light with Dark shadow

<TextView android:id="@+id/txt_example3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="14sp"
                android:textStyle="bold"
                android:textColor="@color/grey_font"
                android:shadowColor="@color/text_shadow_white"
                android:shadowDx="-2"
                android:shadowDy="-2"
                android:shadowRadius="1" />

enter image description here

Notice the positive and negative values... I suggest to play around with the colors/values yourself but ultimately you can adjust these settings to get the effect your looking for.

Text border using css (border around text)

The following will cover all browsers worth covering:

text-shadow: 0 0 2px #fff; /* Firefox 3.5+, Opera 9+, Safari 1+, Chrome, IE10 */
filter: progid:DXImageTransform.Microsoft.Glow(Color=#ffffff,Strength=1); /* IE<10 */

Path.Combine absolute with relative path strings

Be careful with Backslashes, don't forget them (neither use twice:)

string relativePath = "..\\bling.txt";
string baseDirectory = "C:\\blah\\";
//OR:
//string relativePath = "\\..\\bling.txt";
//string baseDirectory = "C:\\blah";
//THEN
string absolutePath = Path.GetFullPath(baseDirectory + relativePath);

datetimepicker is not a function jquery

It's all about the order of the scripts. Try to reorder them, place jquery.datetimepicker.js to be last of all scripts!

How can I count the number of elements with same class?

document.getElementsByClassName("classstringhere").length

The document.getElementsByClassName("classstringhere") method returns an array of all the elements with that class name, so .length gives you the amount of them.

position fixed header in html

The position :fixed is differ from the other layout. Once you fixed the position for your header, keep in mind that you have to set the margin-top for the content div.

Add data dynamically to an Array

just for fun...

$array_a = array('0'=>'foo', '1'=>'bar');
$array_b = array('foo'=>'0', 'bar'=>'1');

$array_c = array_merge($array_a,$array_b);

$i = 0; $j = 0;
foreach ($array_c as $key => $value) {
    if (is_numeric($key)) {$array_d[$i] = $value; $i++;}
    if (is_numeric($value)) {$array_e[$j] = $key; $j++;}
}

print_r($array_d);
print_r($array_e);

How to get text from EditText?

Place the following after the setContentView() method.

final EditText edit =  (EditText) findViewById(R.id.Your_Edit_ID);
String emailString = (String) edit.getText().toString();
Log.d("email",emailString);

How to run a program automatically as admin on Windows 7 at startup?

I think the task scheduler would be overkill (imho). There is a startup folder for win7.

C:\Users\miliu\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

Just create a shortcut for your autostart Applicaton, edit the properties of the shortcut and have it always run as administrator.

Your kids could close it of course, but if they are tech-savvy they always find a way to keep you out. I know i did when i was younger.

Good luck!

How can I set the initial value of Select2 when using AJAX?

You are doing most things correctly, it looks like the only problem you are hitting is that you are not triggering the change method after you are setting the new value. Without a change event, Select2 cannot know that the underlying value has changed so it will only display the placeholder. Changing your last part to

.val(initial_creditor_id).trigger('change');

Should fix your issue, and you should see the UI update right away.


This is assuming that you have an <option> already that has a value of initial_creditor_id. If you do not Select2, and the browser, will not actually be able to change the value, as there is no option to switch to, and Select2 will not detect the new value. I noticed that your <select> only contains a single option, the one for the placeholder, which means that you will need to create the new <option> manually.

var $option = $("<option selected></option>").val(initial_creditor_id).text("Whatever Select2 should display");

And then append it to the <select> that you initialized Select2 on. You may need to get the text from an external source, which is where initSelection used to come into play, which is still possible with Select2 4.0.0. Like a standard select, this means you are going to have to make the AJAX request to retrieve the value and then set the <option> text on the fly to adjust.

var $select = $('.creditor_select2');

$select.select2(/* ... */); // initialize Select2 and any events

var $option = $('<option selected>Loading...</option>').val(initial_creditor_id);

$select.append($option).trigger('change'); // append the option and update Select2

$.ajax({ // make the request for the selected data object
  type: 'GET',
  url: '/api/for/single/creditor/' + initial_creditor_id,
  dataType: 'json'
}).then(function (data) {
  // Here we should have the data object
  $option.text(data.text).val(data.id); // update the text that is displayed (and maybe even the value)
  $option.removeData(); // remove any caching data that might be associated
  $select.trigger('change'); // notify JavaScript components of possible changes
});

While this may look like a lot of code, this is exactly how you would do it for non-Select2 select boxes to ensure that all changes were made.

How to connect to a secure website using SSL in Java with a pkcs12 file?

I cannot comment because of the 50pts threshhold, but I don't think that the answer provided in https://stackoverflow.com/a/537344/1341220 is correct. What you are actually describing is how you insert server certificates into the systems default truststore:

$JAVA_HOME/jre/lib/security/cacerts, password: changeit)

This works, indeed, but it means that you did not really specify a trust store local to your project, but rather accepted the certificate universially in your system.

You actually never use your own truststore that you defined here:

System.setProperty("javax.net.ssl.trustStore", "myTrustStore");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");

How to add buttons dynamically to my form?

You can't add a Button to an empty list without creating a new instance of that Button. You are missing the

Button newButton = new Button();  

in your code plus get rid of the .Capacity

Importing xsd into wsdl

You have a couple of problems here.

First, the XSD has an issue where an element is both named or referenced; in your case should be referenced.

Change:

<xsd:element name="stock" ref="Stock" minOccurs="1" maxOccurs="unbounded"/> 

To:

<xsd:element name="stock" type="Stock" minOccurs="1" maxOccurs="unbounded"/> 

And:

  • Remove the declaration of the global element Stock
  • Create a complex type declaration for a type named Stock

So:

<xsd:element name="Stock">
    <xsd:complexType>

To:

<xsd:complexType name="Stock">

Make sure you fix the xml closing tags.

The second problem is that the correct way to reference an external XSD is to use XSD schema with import/include within a wsdl:types element. wsdl:import is reserved to referencing other WSDL files. More information is available by going through the WS-I specification, section WSDL and Schema Import. Based on WS-I, your case would be:

INCORRECT: (the way you showed it)

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <import namespace="http://stock.com/schemas/services/stock" location="Stock.xsd" />
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

CORRECT:

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <types>
        <schema xmlns="http://www.w3.org/2001/XMLSchema">
            <import namespace="http://stock.com/schemas/services/stock" schemaLocation="Stock.xsd" />             
        </schema>
    </types>
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

SOME processors may support both syntaxes. The XSD you put out shows issues, make sure you first validate the XSD.

It would be better if you go the WS-I way when it comes to WSDL authoring.

Other issues may be related to the use of relative vs. absolute URIs in locating external content.

How to write MySQL query where A contains ( "a" or "b" )

I user for searching the size of motorcycle :

For example : Data = "Tire cycle size 70 / 90 - 16"

i can search with "70 90 16"

$searchTerms = preg_split("/[\s,-\/?!]+/", $itemName);

foreach ($searchTerms as $term) {
        $term = trim($term);
            if (!empty($term)) {
            $searchTermBits[] = "name LIKE '%$term%'";
            }
        }

$query = "SELECT * FROM item WHERE " .implode(' AND ', $searchTermBits);

How do I import .sql files into SQLite 3?

You can also do:

sqlite3 database.db -init dump.sql

Receiving "fatal: Not a git repository" when attempting to remote add a Git repo

Below error seems like Gits didn't find .git file in current directory so throwing error message.

Therefore change to directory to repository directory where you have checkout the code from git and then run this command.

  • $ git checkout

Setting public class variables

You're "setting" the value of that variable/attribute. Not overriding or overloading it. Your code is very, very common and normal.

All of these terms ("set", "override", "overload") have specific meanings. Override and Overload are about polymorphism (subclassing).

From http://en.wikipedia.org/wiki/Object-oriented_programming :

Polymorphism allows the programmer to treat derived class members just like their parent class' members. More precisely, Polymorphism in object-oriented programming is the ability of objects belonging to different data types to respond to method calls of methods of the same name, each one according to an appropriate type-specific behavior. One method, or an operator such as +, -, or *, can be abstractly applied in many different situations. If a Dog is commanded to speak(), this may elicit a bark(). However, if a Pig is commanded to speak(), this may elicit an oink(). They both inherit speak() from Animal, but their derived class methods override the methods of the parent class; this is Overriding Polymorphism. Overloading Polymorphism is the use of one method signature, or one operator such as "+", to perform several different functions depending on the implementation. The "+" operator, for example, may be used to perform integer addition, float addition, list concatenation, or string concatenation. Any two subclasses of Number, such as Integer and Double, are expected to add together properly in an OOP language. The language must therefore overload the addition operator, "+", to work this way. This helps improve code readability. How this is implemented varies from language to language, but most OOP languages support at least some level of overloading polymorphism.

How do I get the path and name of the file that is currently executing?

I used the approach with __file__
os.path.abspath(__file__)
but there is a little trick, it returns the .py file when the code is run the first time, next runs give the name of *.pyc file
so I stayed with:
inspect.getfile(inspect.currentframe())
or
sys._getframe().f_code.co_filename

I want to show all tables that have specified column name

SELECT      T.TABLE_NAME, C.COLUMN_NAME
FROM        INFORMATION_SCHEMA.COLUMNS C
            INNER JOIN INFORMATION_SCHEMA.TABLES T ON T.TABLE_NAME = C.TABLE_NAME
WHERE       TABLE_TYPE = 'BASE TABLE'
            AND COLUMN_NAME = 'ColName'

This returns tables only and ignores views for anyone who is interested!

Adding a default value in dropdownlist after binding with database

You can do it programmatically:

ddlColor.DataSource = from p in db.ProductTypes
                                  where p.ProductID == pID
                                  orderby p.Color 
                                  select new { p.Color };
ddlColor.DataTextField = "Color";
ddlColor.DataBind();
ddlColor.Items.Insert(0, new ListItem("Select", "NA"));

Or add it in markup as:

<asp:DropDownList .. AppendDataBoundItems="true">
   <Items>
       <asp:ListItem Text="Select" Value="" />
   </Items>
</asp:DropDownList>

Select a Dictionary<T1, T2> with LINQ

A more explicit option is to project collection to an IEnumerable of KeyValuePair and then convert it to a Dictionary.

Dictionary<int, string> dictionary = objects
    .Select(x=> new KeyValuePair<int, string>(x.Id, x.Name))
    .ToDictionary(x=>x.Key, x=>x.Value);

Best way to style a TextBox in CSS

You could target all text boxes with input[type=text] and then explicitly define the class for the textboxes who need it.

You can code like below :

_x000D_
_x000D_
input[type=text] {_x000D_
  padding: 0;_x000D_
  height: 30px;_x000D_
  position: relative;_x000D_
  left: 0;_x000D_
  outline: none;_x000D_
  border: 1px solid #cdcdcd;_x000D_
  border-color: rgba(0, 0, 0, .15);_x000D_
  background-color: white;_x000D_
  font-size: 16px;_x000D_
}_x000D_
_x000D_
.advancedSearchTextbox {_x000D_
  width: 526px;_x000D_
  margin-right: -4px;_x000D_
}
_x000D_
<input type="text" class="advancedSearchTextBox" />
_x000D_
_x000D_
_x000D_

YouTube API to fetch all videos on a channel

To get channels list :

Get Channels list by forUserName:

https://www.googleapis.com/youtube/v3/channels?part=snippet,contentDetails,statistics&forUsername=Apple&key=

Get channels list by channel id:

https://www.googleapis.com/youtube/v3/channels/?part=snippet,contentDetails,statistics&id=UCE_M8A5yxnLfW0KghEeajjw&key=

Get Channel sections:

https://www.googleapis.com/youtube/v3/channelSections?part=snippet,contentDetails&channelId=UCE_M8A5yxnLfW0KghEeajjw&key=

To get Playlists :

Get Playlists by Channel ID:

https://www.googleapis.com/youtube/v3/playlists?part=snippet,contentDetails&channelId=UCq-Fj5jknLsUf-MWSy4_brA&maxResults=50&key=

Get Playlists by Channel ID with pageToken:

https://www.googleapis.com/youtube/v3/playlists?part=snippet,contentDetails&channelId=UCq-Fj5jknLsUf-MWSy4_brA&maxResults=50&key=&pageToken=CDIQAA

To get PlaylistItems :

Get PlaylistItems list by PlayListId:

https://www.googleapis.com/youtube/v3/playlistItems?part=snippet,contentDetails&maxResults=25&playlistId=PLHFlHpPjgk70Yv3kxQvkDEO5n5tMQia5I&key=

To get videos :

Get videos list by video id:

https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics&id=YxLCwfA1cLw&key=

Get videos list by multiple videos id:

https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics&id=YxLCwfA1cLw,Qgy6LaO3SB0,7yPJXGO2Dcw&key=

Get comments list

Get Comment list by video ID:

https://www.googleapis.com/youtube/v3/commentThreads?part=snippet,replies&videoId=el****kQak&key=A**********k

Get Comment list by channel ID:

https://www.googleapis.com/youtube/v3/commentThreads?part=snippet,replies&channelId=U*****Q&key=AI********k

Get Comment list by allThreadsRelatedToChannelId:

https://www.googleapis.com/youtube/v3/commentThreads?part=snippet,replies&allThreadsRelatedToChannelId=UC*****ntcQ&key=AI*****k

Here all api's are Get approach.

Based on channel id we con't get all videos directly, that's the important point here.

For integration https://developers.google.com/youtube/v3/quickstart/ios?ver=swift

How to deny access to a file in .htaccess

Place the below line in your .htaccess file and replace the file name as you wish

RewriteRule ^(test\.php) - [F,L,NC]

Changing image on hover with CSS/HTML

With everyones answer using the background-image option they're missing one attribute. The height and width will set the container size for the image but won't resize the image itself. background-size is needed to compress or stretch the image to fit this container. I've used the example from the 'best answer'

<div id="Library"></div>
#Library {
   background-image: url('LibraryTransparent.png');
   background-size: 120px;
   height: 70px;
   width: 120px;
}

#Library:hover {
   background-image: url('LibraryHoverTrans.png');
}

sh: 0: getcwd() failed: No such file or directory on cited drive

Even i was having the same problem with python virtualenv It got corrected by a simple restart

sudo shutdown -r now

How do I insert an image in an activity with android studio?

When you have image into yours drawable gallery then you just need to pick the option of image view pick and drag into app activity you want to show and select the required image.

Convert a number range to another range, maintaining ratio

Short-cut/simplified proposal

 NewRange/OldRange = Handy multiplicand or HM
 Convert OldValue in OldRange to NewValue in NewRange = 
 (OldValue - OldMin x HM) + NewMin

wayne

Formatting a float to 2 decimal places

This is for cases that you want to use interpolated strings. I'm actually posting this because I'm tired of trial and error and eventually scrolling through tons of docs every time I need to format some scalar.

$"{1234.5678:0.00}"        "1234.57"        2 decimal places, notice that value is rounded
$"{1234.5678,10:0.00}"     "   1234.57"     right-aligned
$"{1234.5678,-10:0.00}"    "1234.57   "     left-aligned
$"{1234.5678:0.#####}"     "1234.5678"      5 optional digits after the decimal point
$"{1234.5678:0.00000}"     "1234.56780"     5 forced digits AFTER the decimal point, notice the trailing zero
$"{1234.5678:00000.00}"    "01234.57"       5 forced digits BEFORE the decimal point, notice the leading zero
$"{1234.5612:0}"           "1235"           as integer, notice that value is rounded
$"{1234.5678:F2}"          "1234.57"        standard fixed-point
$"{1234.5678:F5}"          "1234.56780"     5 digits after the decimal point, notice the trailing zero
$"{1234.5678:g2}"          "1.2e+03"        standard general with 2 meaningful digits, notice "e"
$"{1234.5678:G2}"          "1.2E+03"        standard general with 2 meaningful digits, notice "E"
$"{1234.5678:G3}"          "1.23E+03"       standard general with 3 meaningful digits
$"{1234.5678:G5}"          "1234.6"         standard general with 5 meaningful digits
$"{1234.5678:e2}"          "1.23e+003"      standard exponential with 2 digits after the decimal point, notice "e"
$"{1234.5678:E3}"          "1.235E+003"     standard exponential with 3 digits after the decimal point, notice "E"
$"{1234.5678:N2}"          "1,234.57"       standard numeric, notice the comma
$"{1234.5678:C2}"          "$1,234.57"      standard currency, notice the dollar sign
$"{1234.5678:P2}"          "123,456.78 %"   standard percent, notice that value is multiplied by 100
$"{1234.5678:2}"           "2"              :)

Performance Warning

Interpolated strings are slow. In my experience this is the order (fast to slow):

  1. value.ToString(format)+" blah blah"
  2. string.Format("{0:format} blah blah", value)
  3. $"{value:format} blah blah"

C++ vector of char array

FFWD to 2019. Although this code worketh in 2011 too.

// g++ prog.cc -Wall -std=c++11
#include <iostream>
#include <vector>

 using namespace std;

 template<size_t N>
    inline 
      constexpr /* compile time */
      array<char,N> string_literal_to_array ( char const (&charrar)[N] )
 {
    return std::to_array( charrar) ;
 }

 template<size_t N>
    inline 
      /* run time */
      vector<char> string_literal_to_vector ( char const (&charrar)[N] )
 {
    return { charrar, charrar + N };
 }


int main()
{
   constexpr auto arr = string_literal_to_array("Compile Time");
   auto cv = string_literal_to_vector ("Run Time") ;
   return 42;
}

Advice: try optimizing the use of std::string. For char buffering std::array<char,N> is the fastest, std::vector<char> is faster.

https://wandbox.org/permlink/wcasstoY56MWbHqd

Is there an "exists" function for jQuery?

Inspired by hiway's answer I came up with the following:

$.fn.exists = function() {
    return $.contains( document.documentElement, this[0] );
}

jQuery.contains takes two DOM elements and checks whether the first one contains the second one.

Using document.documentElement as the first argument fulfills the semantics of the exists method when we want to apply it solely to check the existence of an element in the current document.

Below, I've put together a snippet that compares jQuery.exists() against the $(sel)[0] and $(sel).length approaches which both return truthy values for $(4) while $(4).exists() returns false. In the context of checking for existence of an element in the DOM this seems to be the desired result.

_x000D_
_x000D_
$.fn.exists = function() {_x000D_
    return $.contains(document.documentElement, this[0]); _x000D_
  }_x000D_
  _x000D_
  var testFuncs = [_x000D_
    function(jq) { return !!jq[0]; },_x000D_
    function(jq) { return !!jq.length; },_x000D_
    function(jq) { return jq.exists(); },_x000D_
  ];_x000D_
    _x000D_
  var inputs = [_x000D_
    ["$()",$()],_x000D_
    ["$(4)",$(4)],_x000D_
    ["$('#idoexist')",$('#idoexist')],_x000D_
    ["$('#idontexist')",$('#idontexist')]_x000D_
  ];_x000D_
  _x000D_
  for( var i = 0, l = inputs.length, tr, input; i < l; i++ ) {_x000D_
    input = inputs[i][1];_x000D_
    tr = "<tr><td>" + inputs[i][0] + "</td><td>"_x000D_
          + testFuncs[0](input) + "</td><td>"_x000D_
          + testFuncs[1](input) + "</td><td>"_x000D_
          + testFuncs[2](input) + "</td></tr>";_x000D_
    $("table").append(tr);_x000D_
  }
_x000D_
td { border: 1px solid black }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="idoexist">#idoexist</div>_x000D_
<table style>_x000D_
<tr>_x000D_
  <td>Input</td><td>!!$(sel)[0]</td><td>!!$(sel).length</td><td>$(sel).exists()</td>_x000D_
</tr>_x000D_
</table>_x000D_
<script>_x000D_
  _x000D_
  $.fn.exists = function() {_x000D_
    return $.contains(document.documentElement, this[0]); _x000D_
  }_x000D_
  _x000D_
</script>
_x000D_
_x000D_
_x000D_

Gradle build without tests

In The Java Plugin:

$ gradle tasks

Build tasks
-----------
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
testClasses - Assembles test classes.

Verification tasks
------------------
test - Runs the unit tests.

Gradle build without test you have two options:

$ gradle assemble
$ gradle build -x test

but if you want compile test:

$ gradle assemble testClasses
$ gradle testClasses

What is apache's maximum url length?

Allowed default size of URI is 8177 characters in GET request. Simple code in python for such testing.

#!/usr/bin/env python2

import sys
import socket

if __name__ == "__main__":
    string = sys.argv[1]
    buf_get = "x" * int(string)
    buf_size = 1024
    request = "HEAD %s HTTP/1.1\nHost:localhost\n\n" % buf_get
    print "===>", request

    sock_http = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock_http.connect(("localhost", 80))
    sock_http.send(request)
    while True:
       print "==>", sock_http.recv(buf_size)
       if not sock_http.recv(buf_size):
           break
    sock_http.close()

On 8178 characters you will get such message: HTTP/1.1 414 Request-URI Too Large

How to get all selected values from <select multiple=multiple>?

First, use Array.from to convert the HTMLCollection object to an array.

let selectElement = document.getElementById('categorySelect')
let selectedValues = Array.from(selectElement.selectedOptions)
        .map(option => option.value) // make sure you know what '.map' does

// you could also do: selectElement.options

What Does 'zoom' do in CSS?

Only IE and WebKit support zoom, and yes, in theory it does exactly what you're saying.

Try it out on an image to see it's full effect :)

Reading data from DataGridView in C#

If you wish, you can also use the column names instead of column numbers.

For example, if you want to read data from DataGridView on the 4. row and the "Name" column. It provides me a better understanding for which variable I am dealing with.

dataGridView.Rows[4].Cells["Name"].Value.ToString();

Hope it helps.

MySql ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

If you need to skip the password prompt for some reason, you can input the password in the command (Dangerous)

mysql -u root --password=secret

How to declare a structure in a header that is to be used by multiple files in c?

For a structure definition that is to be used across more than one source file, you should definitely put it in a header file. Then include that header file in any source file that needs the structure.

The extern declaration is not used for structure definitions, but is instead used for variable declarations (that is, some data value with a structure type that you have defined). If you want to use the same variable across more than one source file, declare it as extern in a header file like:

extern struct a myAValue;

Then, in one source file, define the actual variable:

struct a myAValue;

If you forget to do this or accidentally define it in two source files, the linker will let you know about this.

Xcode 4: How do you view the console?

for Xcode 5:

View->Debug Area->Activate Console

shift + cmd + c

Getting absolute URLs using ASP.NET Core

For ASP.NET Core 1.0 Onwards

/// <summary>
/// <see cref="IUrlHelper"/> extension methods.
/// </summary>
public static class UrlHelperExtensions
{
    /// <summary>
    /// Generates a fully qualified URL to an action method by using the specified action name, controller name and
    /// route values.
    /// </summary>
    /// <param name="url">The URL helper.</param>
    /// <param name="actionName">The name of the action method.</param>
    /// <param name="controllerName">The name of the controller.</param>
    /// <param name="routeValues">The route values.</param>
    /// <returns>The absolute URL.</returns>
    public static string AbsoluteAction(
        this IUrlHelper url,
        string actionName,
        string controllerName,
        object routeValues = null)
    {
        return url.Action(actionName, controllerName, routeValues, url.ActionContext.HttpContext.Request.Scheme);
    }

    /// <summary>
    /// Generates a fully qualified URL to the specified content by using the specified content path. Converts a
    /// virtual (relative) path to an application absolute path.
    /// </summary>
    /// <param name="url">The URL helper.</param>
    /// <param name="contentPath">The content path.</param>
    /// <returns>The absolute URL.</returns>
    public static string AbsoluteContent(
        this IUrlHelper url,
        string contentPath)
    {
        HttpRequest request = url.ActionContext.HttpContext.Request;
        return new Uri(new Uri(request.Scheme + "://" + request.Host.Value), url.Content(contentPath)).ToString();
    }

    /// <summary>
    /// Generates a fully qualified URL to the specified route by using the route name and route values.
    /// </summary>
    /// <param name="url">The URL helper.</param>
    /// <param name="routeName">Name of the route.</param>
    /// <param name="routeValues">The route values.</param>
    /// <returns>The absolute URL.</returns>
    public static string AbsoluteRouteUrl(
        this IUrlHelper url,
        string routeName,
        object routeValues = null)
    {
        return url.RouteUrl(routeName, routeValues, url.ActionContext.HttpContext.Request.Scheme);
    }
}

Bonus Tip

You can't directly register an IUrlHelper in the DI container. Resolving an instance of IUrlHelper requires you to use the IUrlHelperFactory and IActionContextAccessor. However, you can do the following as a shortcut:

services
    .AddSingleton<IActionContextAccessor, ActionContextAccessor>()
    .AddScoped<IUrlHelper>(x => x
        .GetRequiredService<IUrlHelperFactory>()
        .GetUrlHelper(x.GetRequiredService<IActionContextAccessor>().ActionContext));

ASP.NET Core Backlog

UPDATE: This won't make ASP.NET Core 5

There are indications that you will be able to use LinkGenerator to create absolute URL's without the need to provide a HttpContext (This was the biggest downside of LinkGenerator and why IUrlHelper although more complex to setup using the solution below was easier to use) See "Make it easy to configure a host/scheme for absolute URLs with LinkGenerator".

Get everything after and before certain character in SQL Server

use the following function

left(@test, charindex('/', @test) - 1)

CSS last-child(-1)

Unless you can get PHP to label that element with a class you are better to use jQuery.

jQuery(document).ready(function () {
  $count =  jQuery("ul li").size() - 1;
  alert($count);
  jQuery("ul li:nth-child("+$count+")").css("color","red");
});

Aesthetics must either be length one, or the same length as the dataProblems

The problem is that skew isn't being subsetted in colour=factor(skew), so it's the wrong length. Since subset(skew, product == 'p1') is the same as subset(skew, product == 'p3'), in this case it doesn't matter which subset is used. So you can solve your problem with:

p1 <- ggplot(df, aes(x=subset(price, product=='p1'),
                     y=subset(price, product=='p3'),
                     colour=factor(subset(skew, product == 'p1')))) +
              geom_point(size=2, shape=19)

Note that most R users would write this as the more concise:

p1 <- ggplot(df, aes(x=price[product=='p1'],
                     y=price[product=='p3'],
                     colour=factor(skew[product == 'p1']))) +
              geom_point(size=2, shape=19)

How to edit nginx.conf to increase file size upload

In case if one is using nginx proxy as a docker container (e.g. jwilder/nginx-proxy), there is the following way to configure client_max_body_size (or other properties):

  1. Create a custom config file e.g. /etc/nginx/proxy.conf with a right value for this property
  2. When running a container, add it as a volume e.g. -v /etc/nginx/proxy.conf:/etc/nginx/conf.d/my_proxy.conf:ro

Personally found this way rather convenient as there's no need to build a custom container to change configs. I'm not affiliated with jwilder/nginx-proxy, was just using it in my project, and the way described above helped me. Hope it helps someone else, too.

Given a DateTime object, how do I get an ISO 8601 date in string format?

Surprised that no one suggested it:

System.DateTime.UtcNow.ToString("u").Replace(' ','T')
# Using PowerShell Core to demo

# Lowercase "u" format
[System.DateTime]::UtcNow.ToString("u")
> 2020-02-06 01:00:32Z

# Lowercase "u" format with replacement
[System.DateTime]::UtcNow.ToString("u").Replace(' ','T')
> 2020-02-06T01:00:32Z

The UniversalSortableDateTimePattern gets you almost all the way to what you want (which is more an RFC 3339 representation).


Added: I decided to use the benchmarks that were in answer https://stackoverflow.com/a/43793679/653058 to compare how this performs.

tl:dr; it's at the expensive end but still just a little over half a millisecond on my crappy old laptop :-)

Implementation:

[Benchmark]
public string ReplaceU()
{
   var text = dateTime.ToUniversalTime().ToString("u").Replace(' ', 'T');
   return text;
}

Results:

// * Summary *

BenchmarkDotNet=v0.11.5, OS=Windows 10.0.19002
Intel Xeon CPU E3-1245 v3 3.40GHz, 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=3.0.100
  [Host]     : .NET Core 3.0.0 (CoreCLR 4.700.19.46205, CoreFX 4.700.19.46214), 64bit RyuJIT
  DefaultJob : .NET Core 3.0.0 (CoreCLR 4.700.19.46205, CoreFX 4.700.19.46214), 64bit RyuJIT


|               Method |     Mean |     Error |    StdDev |
|--------------------- |---------:|----------:|----------:|
|           CustomDev1 | 562.4 ns | 11.135 ns | 10.936 ns |
|           CustomDev2 | 525.3 ns |  3.322 ns |  3.107 ns |
|     CustomDev2WithMS | 609.9 ns |  9.427 ns |  8.356 ns |
|              FormatO | 356.6 ns |  6.008 ns |  5.620 ns |
|              FormatS | 589.3 ns |  7.012 ns |  6.216 ns |
|       FormatS_Verify | 599.8 ns | 12.054 ns | 11.275 ns |
|        CustomFormatK | 549.3 ns |  4.911 ns |  4.594 ns |
| CustomFormatK_Verify | 539.9 ns |  2.917 ns |  2.436 ns |
|             ReplaceU | 615.5 ns | 12.313 ns | 11.517 ns |

// * Hints *
Outliers
  BenchmarkDateTimeFormat.CustomDev2WithMS: Default     -> 1 outlier  was  removed (668.16 ns)
  BenchmarkDateTimeFormat.FormatS: Default              -> 1 outlier  was  removed (621.28 ns)
  BenchmarkDateTimeFormat.CustomFormatK: Default        -> 1 outlier  was  detected (542.55 ns)
  BenchmarkDateTimeFormat.CustomFormatK_Verify: Default -> 2 outliers were removed (557.07 ns, 560.95 ns)

// * Legends *
  Mean   : Arithmetic mean of all measurements
  Error  : Half of 99.9% confidence interval
  StdDev : Standard deviation of all measurements
  1 ns   : 1 Nanosecond (0.000000001 sec)

// ***** BenchmarkRunner: End *****

Bootstrap - dropdown menu not working?

put following code in your page

  Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequest);
    function EndRequest(sender, args) {
        if (args.get_error() == undefined) {
        $('.dropdown-toggle').dropdown();
        }
    }

Usage of the backtick character (`) in JavaScript

This is a feature called template literals.

They were called "template strings" in prior editions of the ECMAScript 2015 specification.

Template literals are supported by Firefox 34, Chrome 41, and Edge 12 and above, but not by Internet Explorer.

Template literals can be used to represent multi-line strings and may use "interpolation" to insert variables:

var a = 123, str = `---
   a is: ${a}
---`;
console.log(str);

Output:

---
   a is: 123
---

What is more important, they can contain not just a variable name, but any JavaScript expression:

var a = 3, b = 3.1415;

console.log(`PI is nearly ${Math.max(a, b)}`);

Getting the base url of the website and globally passing it to twig in Symfony 2

This is now available for free in twig templates (tested on sf2 version 2.0.14)

{{ app.request.getBaseURL() }}

In later Symfony versions (tested on 2.5), try :

{{ app.request.getSchemeAndHttpHost() }}

Server.Mappath in C# classlibrary

Architecturally, System.web should not be referred in Business Logic Layer (BLL). Employ BLL into the solution structure to follow the separate of concern principle so refer System.Web is a bad practice. BLL should not load/run in Asp.net context. Because of the reason you should consider using of System.AppDomain.CurrentDomain.BaseDirectory instead of System.Web.HttpContext.Current.Server.MapPath

SET NAMES utf8 in MySQL?

Getting encoding right is really tricky - there are too many layers:

  • Browser
  • Page
  • PHP
  • MySQL

The SQL command "SET CHARSET utf8" from PHP will ensure that the client side (PHP) will get the data in utf8, no matter how they are stored in the database. Of course, they need to be stored correctly first.

DDL definition vs. real data

Encoding defined for a table/column doesn't really mean that the data are in that encoding. If you happened to have a table defined as utf8 but stored as differtent encoding, then MySQL will treat them as utf8 and you're in trouble. Which means you have to fix this first.

What to check

You need to check in what encoding the data flow at each layer.

  • Check HTTP headers, headers.
  • Check what's really sent in body of the request.
  • Don't forget that MySQL has encoding almost everywhere:
    • Database
    • Tables
    • Columns
    • Server as a whole
    • Client
      Make sure that there's the right one everywhere.

Conversion

If you receive data in e.g. windows-1250, and want to store in utf-8, then use this SQL before storing:

SET NAMES 'cp1250';

If you have data in DB as windows-1250 and want to retreive utf8, use:

SET CHARSET 'utf8';

Few more notes:

  • Don't rely on too "smart" tools to show the data. E.g. phpMyAdmin does (was doing when I was using it) encoding really bad. And it goes through all the layers so it's hard to find out.
  • Also, Internet Explorer had really stupid behavior of "guessing" the encoding based on weird rules.
  • Use simple editors where you can switch encoding. I recommend MySQL Workbench.

Alert handling in Selenium WebDriver (selenium 2) with Java

try 
    {
        //Handle the alert pop-up using seithTO alert statement
        Alert alert = driver.switchTo().alert();

        //Print alert is present
        System.out.println("Alert is present");

        //get the message which is present on pop-up
        String message = alert.getText();

        //print the pop-up message
        System.out.println(message);

        alert.sendKeys("");
        //Click on OK button on pop-up
        alert.accept();
    } 
    catch (NoAlertPresentException e) 
    {
        //if alert is not present print message
        System.out.println("alert is not present");
    }

gpg decryption fails with no secret key error

This error will arise when using the utility pass if the terminal window is too small!

Just make the terminal window a few lines taller.

Very confusing.

Concatenate a NumPy array to another NumPy array

Actually one can always create an ordinary list of numpy arrays and convert it later.

In [1]: import numpy as np

In [2]: a = np.array([[1,2],[3,4]])

In [3]: b = np.array([[1,2],[3,4]])

In [4]: l = [a]

In [5]: l.append(b)

In [6]: l = np.array(l)

In [7]: l.shape
Out[7]: (2, 2, 2)

In [8]: l
Out[8]: 
array([[[1, 2],
        [3, 4]],

       [[1, 2],
        [3, 4]]])

Modify SVG fill color when being served as Background-Image

One way to do this is to serve your svg from some server side mechanism. Simply create a resource server side that outputs your svg according to GET parameters, and you serve it on a certain url.

Then you just use that url in your css.

Because as a background img, it isn't part of the DOM and you can't manipulate it. Another possibility would be to use it regularly, embed it in a page in a normal way, but position it absolutely, make it full width & height of a page and then use z-index css property to put it behind all the other DOM elements on a page.

Error while sending QUERY packet

You guessed right MySQL have limitation for size of data, you need to break your query in small group of records or you can Change your max_allowed_packet by using SET GLOBAL max_allowed_packet=524288000;

How can I align text in columns using Console.WriteLine?

You could use tabs instead of spaces between columns, and/or set maximum size for a column in format strings ...

HttpServletRequest to complete URL

// http://hostname.com/mywebapp/servlet/MyServlet/a/b;c=123?d=789

public static String getUrl(HttpServletRequest req) {
    String reqUrl = req.getRequestURL().toString();
    String queryString = req.getQueryString();   // d=789
    if (queryString != null) {
        reqUrl += "?"+queryString;
    }
    return reqUrl;
}

Add text at the end of each line

Concise version of the sed command:

sed -i s/$/:80/ file.txt

Explanation:

  • sed stream editor
    • -i in-place (edit file in place)
    • s substitution command
    • /replacement_from_reg_exp/replacement_to_text/ statement
    • $ matches the end of line (replacement_from_reg_exp)
    • :80 text you want to add at the end of every line (replacement_to_text)
  • file.txt the file name

How to split a string and assign it to variables

As a side note, you can include the separators while splitting the string in Go. To do so, use strings.SplitAfter as in the example below.

package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Printf("%q\n", strings.SplitAfter("z,o,r,r,o", ","))
}

How do I iterate through lines in an external file with shell?

I know the purists will hate this method, but you can cat the file.

NAMES=`cat scripts/names.txt` #names from names.txt file
for NAME in $NAMES; do
   echo "$NAME"
done

Cannot open solution file in Visual Studio Code

When you open a folder in VSCode, it will automatically scan the folder for typical project artifacts like project.json or solution files. From the status bar in the lower left side you can switch between solutions and projects.

WebSocket with SSL

You can't use WebSockets over HTTPS, but you can use WebSockets over TLS (HTTPS is HTTP over TLS). Just use "wss://" in the URI.

I believe recent version of Firefox won't let you use non-TLS WebSockets from an HTTPS page, but the reverse shouldn't be a problem.

Intel's HAXM equivalent for AMD on Windows OS

From the Android docs (March 2016):

Before attempting to use this type of acceleration, you should first determine if your development system’s CPU supports one of the following virtualization extensions technologies:

  • Intel Virtualization Technology (VT, VT-x, vmx) extensions
  • AMD Virtualization (AMD-V, SVM) extensions (only supported for Linux)

The specifications from the manufacturer of your CPU should indicate if it supports virtualization extensions. If your CPU does not support one of these virtualization technologies, then you cannot use virtual machine acceleration.

Note: Virtualization extensions are typically enabled through your computer's BIOS and are frequently turned off by default. Check the documentation for your system's motherboard to find out how to enable virtualization extensions.

Most people talk about Genymotion being faster, and I have never heard anyone say it's slower. I definitely think it's faster, and it will be worth the ~20 minutes it will take to set up just to try it.

Python csv string to array

Simple - the csv module works with lists, too:

>>> a=["1,2,3","4,5,6"]  # or a = "1,2,3\n4,5,6".split('\n')
>>> import csv
>>> x = csv.reader(a)
>>> list(x)
[['1', '2', '3'], ['4', '5', '6']]

How to register multiple implementations of the same interface in Asp.Net Core?

I did a simple workaround using Func when I found myself in this situation.

Firstly declare a shared delegate:

public delegate IService ServiceResolver(string key);

Then in your Startup.cs, setup the multiple concrete registrations and a manual mapping of those types:

services.AddTransient<ServiceA>();
services.AddTransient<ServiceB>();
services.AddTransient<ServiceC>();

services.AddTransient<ServiceResolver>(serviceProvider => key =>
{
    switch (key)
    {
        case "A":
            return serviceProvider.GetService<ServiceA>();
        case "B":
            return serviceProvider.GetService<ServiceB>();
        case "C":
            return serviceProvider.GetService<ServiceC>();
        default:
            throw new KeyNotFoundException(); // or maybe return null, up to you
    }
});

And use it from any class registered with DI:

public class Consumer
{
    private readonly IService _aService;

    public Consumer(ServiceResolver serviceAccessor)
    {
        _aService = serviceAccessor("A");
    }

    public void UseServiceA()
    {
        _aService.DoTheThing();
    }
}

Keep in mind that in this example the key for resolution is a string, for the sake of simplicity and because OP was asking for this case in particular.

But you could use any custom resolution type as key, as you do not usually want a huge n-case switch rotting your code. Depends on how your app scales.

What is the difference between required and ng-required?

The HTML attribute required="required" is a statement telling the browser that this field is required in order for the form to be valid. (required="required" is the XHTML form, just using required is equivalent)

The Angular attribute ng-required="yourCondition" means 'isRequired(yourCondition)' and sets the HTML attribute dynamically for you depending on your condition.

Also note that the HTML version is confusing, it is not possible to write something conditional like required="true" or required="false", only the presence of the attribute matters (present means true) ! This is where Angular helps you out with ng-required.

SQL query to find Nth highest salary from a salary table

This is salary table

enter image description here

SELECT  amount FROM  salary 
GROUP by amount
ORDER BY  amount DESC 
LIMIT n-1 , 1

Or

SELECT DISTINCT amount
FROM  salary 
ORDER BY  amount DESC 
LIMIT n-1 , 1

Why is it said that "HTTP is a stateless protocol"?

Even though multiple requests can be sent over the same HTTP connection, the server does not attach any special meaning to their arriving over the same socket. That is solely a performance thing, intended to minimize the time/bandwidth that'd otherwise be spent reestablishing a connection for each request.

As far as HTTP is concerned, they are all still separate requests and must contain enough information on their own to fulfill the request. That is the essence of "statelessness". Requests will not be associated with each other absent some shared info the server knows about, which in most cases is a session ID in a cookie.

How to compare the contents of two string objects in PowerShell

You want to do $arrayOfString[0].Title -eq $myPbiject.item(0).Title

-match is for regex matching ( the second argument is a regex )

Text blinking jQuery

$.fn.blink = function (delay) {
  delay = delay || 500;
  return this.each(function () {
    var element = $(this);
    var interval = setInterval(function () {
      element.fadeOut((delay / 3), function() {
        element.fadeIn(delay / 3);
      })
    }, delay);
    element.data('blinkInterval', interval);
  });
};

$.fn.stopBlinking = function() {
  return this.each(function() {
    var element = $(this);
    element.stop(true, true);
    clearInterval(element.data('blinkInterval'));
  });
};

Which .NET Dependency Injection frameworks are worth looking into?

It depends on what you are looking for, as they each have their pros and cons.

  1. Spring.NET is the most mature as it comes out of Spring from the Java world. Spring has a very rich set of framework libraries that extend it to support Web, Windows, etc.
  2. Castle Windsor is one of the most widely used in the .NET platform and has the largest ecosystem, is highly configurable / extensible, has custom lifetime management, AOP support, has inherent NHibernate support and is an all around awesome container. Windsor is part of an entire stack which includes Monorail, Active Record, etc. NHibernate itself builds on top of Windsor.
  3. Structure Map has very rich and fine grained configuration through an internal DSL.
  4. Autofac is an IoC container of the new age with all of it's inherent functional programming support. It also takes a different approach on managing lifetime than the others. Autofac is still very new, but it pushes the bar on what is possible with IoC.
  5. Ninject I have heard is more bare bones with a less is more approach (heard not experienced).
  6. The biggest discriminator of Unity is: it's from and supported by Microsoft (p&p). Unity has very good performance, and great documentation. It is also highly configurable. It doesn't have all the bells and whistles of say Castle / Structure Map.

So in summary, it really depends on what is important to you. I would agree with others on going and evaluating and seeing which one fits. The nice thing is you have a nice selection of donuts rather than just having to have a jelly one.

Determine if two rectangles overlap each other?

if (RectA.Left < RectB.Right && RectA.Right > RectB.Left &&
     RectA.Top > RectB.Bottom && RectA.Bottom < RectB.Top ) 

or, using Cartesian coordinates

(With X1 being left coord, X2 being right coord, increasing from left to right and Y1 being Top coord, and Y2 being Bottom coord, increasing from bottom to top -- if this is not how your coordinate system [e.g. most computers have the Y direction reversed], swap the comparisons below) ...

if (RectA.X1 < RectB.X2 && RectA.X2 > RectB.X1 &&
    RectA.Y1 > RectB.Y2 && RectA.Y2 < RectB.Y1) 

Say you have Rect A, and Rect B. Proof is by contradiction. Any one of four conditions guarantees that no overlap can exist:

  • Cond1. If A's left edge is to the right of the B's right edge, - then A is Totally to right Of B
  • Cond2. If A's right edge is to the left of the B's left edge, - then A is Totally to left Of B
  • Cond3. If A's top edge is below B's bottom edge, - then A is Totally below B
  • Cond4. If A's bottom edge is above B's top edge, - then A is Totally above B

So condition for Non-Overlap is

NON-Overlap => Cond1 Or Cond2 Or Cond3 Or Cond4

Therefore, a sufficient condition for Overlap is the opposite.

Overlap => NOT (Cond1 Or Cond2 Or Cond3 Or Cond4)

De Morgan's law says
Not (A or B or C or D) is the same as Not A And Not B And Not C And Not D
so using De Morgan, we have

Not Cond1 And Not Cond2 And Not Cond3 And Not Cond4

This is equivalent to:

  • A's Left Edge to left of B's right edge, [RectA.Left < RectB.Right], and
  • A's right edge to right of B's left edge, [RectA.Right > RectB.Left], and
  • A's top above B's bottom, [RectA.Top > RectB.Bottom], and
  • A's bottom below B's Top [RectA.Bottom < RectB.Top]

Note 1: It is fairly obvious this same principle can be extended to any number of dimensions.
Note 2: It should also be fairly obvious to count overlaps of just one pixel, change the < and/or the > on that boundary to a <= or a >=.
Note 3: This answer, when utilizing Cartesian coordinates (X, Y) is based on standard algebraic Cartesian coordinates (x increases left to right, and Y increases bottom to top). Obviously, where a computer system might mechanize screen coordinates differently, (e.g., increasing Y from top to bottom, or X From right to left), the syntax will need to be adjusted accordingly/

CentOS 64 bit bad ELF interpreter

In general, when you get an error like this, just do

yum provides ld-linux.so.2

then you'll see something like:

glibc-2.20-5.fc21.i686 : The GNU libc libraries
Repo        : fedora
Matched from:
Provides    : ld-linux.so.2

and then you just run the following like BRPocock wrote (in case you were wondering what the logic was...):

yum install glibc.i686

Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction

None of the suggested solutions worked for me but this did.

Something is blocking the execution of the query. Most likely another query updating, inserting or deleting from one of the tables in your query. You have to find out what that is:

SHOW PROCESSLIST;

Once you locate the blocking process, find its id and run :

KILL {id};

Re-run your initial query.

How do I stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?

Also, you can use event.preventDefault inside onclick attribute.

<a href="#" onclick="event.preventDefault(); doSmth();">doSmth</a>

No need to write exstra click event.

I can't understand why this JAXB IllegalAnnotationException is thrown

I can't understand why this JAXB IllegalAnnotationException is thrown

I also was getting the ### counts of IllegalAnnotationExceptions exception and it seemed to be due to an improper dependency hierarchy in my Spring wiring.

I figured it out by putting a breakpoint in the JAXB code when it does the throw. For me this was at com.sun.xml.bind.v2.runtime.IllegalAnnotationsException$Builder.check(). Then I dumped the list variable which gives something like:

[org.mortbay.jetty.Handler is an interface, and JAXB can't handle interfaces.
this problem is related to the following location:
    at org.mortbay.jetty.Handler
    at public org.mortbay.jetty.Handler[] org.mortbay.jetty.handler.HandlerCollection.getHandlers()
    at org.mortbay.jetty.handler.HandlerCollection
    at org.mortbay.jetty.handler.ContextHandlerCollection
    at com.mprew.ec2.commons.server.LocalContextHandlerCollection
    at private com.mprew.ec2.commons.server.LocalContextHandlerCollection com.mprew.ec2.commons.services.jaxws_asm.SetLocalContextHandlerCollection.arg0
    at com.mprew.ec2.commons.services.jaxws_asm.SetLocalContextHandlerCollection,
org.mortbay.jetty.Handler does not have a no-arg default constructor.]
....

The does not have a no-arg default constructor seemed to me to be misleading. Maybe I wasn't understanding what the exception was saying. But it did indicate that there was a problem with my LocalContextHandlerCollection. I removed a dependency loop and the error cleared.

Hopefully this will be helpful to others.

Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request?

HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
response = client.execute(httppost, localContext);

doesn't work in 4.5 version without

cookie.setDomain(".domain.com");
cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");

Decode UTF-8 with Javascript

Update @Albert's answer adding condition for emoji.

function Utf8ArrayToStr(array) {
    var out, i, len, c;
    var char2, char3, char4;

    out = "";
    len = array.length;
    i = 0;
    while(i < len) {
    c = array[i++];
    switch(c >> 4)
    { 
      case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
        // 0xxxxxxx
        out += String.fromCharCode(c);
        break;
      case 12: case 13:
        // 110x xxxx   10xx xxxx
        char2 = array[i++];
        out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
        break;
      case 14:
        // 1110 xxxx  10xx xxxx  10xx xxxx
        char2 = array[i++];
        char3 = array[i++];
        out += String.fromCharCode(((c & 0x0F) << 12) |
                       ((char2 & 0x3F) << 6) |
                       ((char3 & 0x3F) << 0));
        break;
     case 15:
        // 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx
        char2 = array[i++];
        char3 = array[i++];
        char4 = array[i++];
        out += String.fromCodePoint(((c & 0x07) << 18) | ((char2 & 0x3F) << 12) | ((char3 & 0x3F) << 6) | (char4 & 0x3F));

        break;
    }

    return out;
}

SSL Error When installing rubygems, Unable to pull data from 'https://rubygems.org/

For Illumos / Solaris using OpenCSW pkgutil:

Install CSWcacertificates prior to 'gem install'

pkgutil -yi CSWcacertificates

If you're using a ruby kit that's not from OpenCSW, your ruby version may expect to find the certificate file in another place. In this case, I simply symlinked OpenCSW's /etc/opt/csw/ssl/cert.pem to the expected place.

Check where ruby expects to find it :

export cf=`ruby -ropenssl -e 'puts OpenSSL::X509::DEFAULT_CERT_FILE'` && echo $cf

Then, if there's a discrepancy, link it:

ln -s /etc/opt/csw/ssl/cert.pem $cf && file $cf

Code not running in IE 11, works fine in Chrome

String.prototype.startsWith is a standard method in the most recent version of JavaScript, ES6.

Looking at the compatibility table below, we can see that it is supported on all current major platforms, except versions of Internet Explorer.

+-------------------------------------------------------------------------------+
¦    Feature    ¦ Chrome ¦ Firefox ¦ Edge  ¦ Internet Explorer ¦ Opera ¦ Safari ¦
¦---------------+--------+---------+-------+-------------------+-------+--------¦
¦ Basic Support ¦    41+ ¦     17+ ¦ (Yes) ¦ No Support        ¦    28 ¦      9 ¦
+-------------------------------------------------------------------------------+

You'll need to implement .startsWith yourself. Here is the polyfill:

if (!String.prototype.startsWith) {
  String.prototype.startsWith = function(searchString, position) {
    position = position || 0;
    return this.indexOf(searchString, position) === position;
  };
}

Copy Paste in Bash on Ubuntu on Windows

Alternate solution over here, my windows home version Windows Subsystem Linux terminal doesn't have the property to use Shift+Ctrl (C|V)

Use an actual linux terminal![enter image description here]1

  • Install an X-server in Windows (like X-Ming)
  • sudo apt install <your_favorite_terminal>
  • export DISPLAY=:0
  • fire your terminal app, I tested with xfce4-terminal and gnome-terminal

windows #ubuntu #development

UITableViewCell, show delete button on swipe

If you're adopting diffable data sources, you'll have to move the delegate callbacks to a UITableViewDiffableDataSource subclass. For example:

class DataSource: UITableViewDiffableDataSource<SectionType, ItemType> {

    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            if let identifierToDelete = itemIdentifier(for: indexPath) {
                var snapshot = self.snapshot()
                snapshot.deleteItems([identifierToDelete])
                apply(snapshot)
            }
        }
    }
}

Apache Server (xampp) doesn't run on Windows 10 (Port 80)

I had the same problem on windows 10, IIS/10.0 was using port 80

To solve that:

  • find service "W3SVC"
  • disable it, or set it to "manual"

French name is: "Service de publication World Wide Web"

English name is: "World Wide Web Publishing Service"

german name is: "WWW-Publishingdienst" – thanks @fiffy

Polish name is: "Usluga publikowania w sieci WWW" - thanks @KrzysDan

Russian name is "?????? ???-??????????" – thanks @Kreozot

Italian name is "Servizio Pubblicazione sul Web" – thanks @Claudio-Venturini

Español name is "Servicio de publicación World Wide Web" - thanks @Daniel-Santarriaga

Portuguese (Brazil) name is "Serviço de publicação da World Wide Web" - thanks @thiago-born


Alternatives :


Edit 07 oct 2015: For more details, see Matthew Stumphy's answer Apache Server (xampp) doesn't run on Windows 10 (Port 80)

How to replace existing value of ArrayList element in Java

You must use

list.remove(indexYouWantToReplace);

first.

Your elements will become like this. [zero, one, three]

then add this

list.add(indexYouWantedToReplace, newElement)

Your elements will become like this. [zero, one, new, three]

An item with the same key has already been added

I have had the same error but b/c of diff reason. Using Entity framework. One more thing I need to add here before I share my code and solution, I had a break point on controller method but it was not breaking there, just throwing exception 500 internal server error.

I was posting data from view to controller through ajax (http post). The model I was expecting as a parameter was a class. It was inherited with some other class.

public class PurchaseOrder : CreateUpdateUserInfo
    {
        public PurchaseOrder()
        {
            this.Purchase_Order_Items = new List<clsItem>();
        }

        public int purchase_order_id { get; set; }
        public Nullable<int> purchase_quotation_id { get; set; }
        public int supplier_id { get; set; }
        public decimal flat_discount { get; set; }
        public decimal total { get; set; }
        public decimal net_payable { get; set; }
        public bool is_payment_complete { get; set; }
        public decimal sales_tax { get; set; }
        public DateTime CreatedOn { get; set; }
        public int CreatorUserID { get; set; }
        public DateTime UpdatedOn { get; set; }
        public int UpdatorUserID { get; set; }
        public bool IsDeleted { get; set; }
        public List<clsItem> Purchase_Order_Items { get; set; }
    }

 public class CreateUpdateUserInfo
    {
        public DateTime CreatedOn { get; set; }
        public int CreatorUserID { get; set; }
        public string CreatorUserName { get; set; }
        public DateTime UpdatedOn { get; set; }
        public int UpdatorUserID { get; set; }
        public string UpdatorUserName { get; set; }
        public bool IsDeleted { get; set; }
    }

and in view

                var model = {
                supplier_id : isNaN($scope.supplierID) || 0 ? null : $scope.supplierID,
                flat_discount : 0,
                total : $scope.total,
                net_payable :  $scope.total,
                is_payment_complete :  true,
                sales_tax:0,
                Purchase_Order_Item: $scope.items
            };
            var obj = {
                method: 'POST',
                url: 'Purchase/SaveOrder',
                dataType: 'json',
                data: JSON.stringify(model),
                headers: { "Content-Type": "application/json" }
            };

            var request = $rootScope.AjaxRequest(obj);
            request.then(function (response) {
                var isError = response.data.MessageType === 1;
                $rootScope.bindToaster(response.data.MessageType,response.data.Message);
                //$('html, body').animate({ scrollTop: 0 }, 'slow');
                if(!isError){
                    //$scope.supplierID =undefined;
                }
            }, function (response) {
                $rootScope.bindToaster(2,response.data);
                console.log(response);
            });

Simply removed duplicated fields from PurchaseOrder class and it worked like a charm.

What are the differences between the different saving methods in Hibernate?

Here's my understanding of the methods. Mainly these are based on the API though as I don't use all of these in practice.

saveOrUpdate Calls either save or update depending on some checks. E.g. if no identifier exists, save is called. Otherwise update is called.

save Persists an entity. Will assign an identifier if one doesn't exist. If one does, it's essentially doing an update. Returns the generated ID of the entity.

update Attempts to persist the entity using an existing identifier. If no identifier exists, I believe an exception is thrown.

saveOrUpdateCopy This is deprecated and should no longer be used. Instead there is...

merge Now this is where my knowledge starts to falter. The important thing here is the difference between transient, detached and persistent entities. For more info on the object states, take a look here. With save & update, you are dealing with persistent objects. They are linked to a Session so Hibernate knows what has changed. But when you have a transient object, there is no session involved. In these cases you need to use merge for updates and persist for saving.

persist As mentioned above, this is used on transient objects. It does not return the generated ID.

How do I set the background color of Excel cells using VBA?

You can use either:

ActiveCell.Interior.ColorIndex = 28

or

ActiveCell.Interior.Color = RGB(255,0,0)

Python 3 - ValueError: not enough values to unpack (expected 3, got 2)

ValueErrors :In Python, a value is the information that is stored within a certain object. To encounter a ValueError in Python means that is a problem with the content of the object you tried to assign the value to.

in your case name,lastname and email 3 parameters are there but unpaidmembers only contain 2 of them.

name, lastname, email in unpaidMembers.items() so you should refer data or your code might be
lastname, email in unpaidMembers.items() or name, email in unpaidMembers.items()

What does getActivity() mean?

getActivity()- Return the Activity this fragment is currently associated with.

Setting default checkbox value in Objective-C?

Documentation on UISwitch says:

[mySwitch setOn:NO]; 

In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.

How can I validate google reCAPTCHA v2 using javascript/jQuery?

Here's how we were able to validate the RECAPTCHA using .NET:

FRONT-END

<div id="rcaptcha" class="g-recaptcha" data-sitekey="[YOUR-KEY-GOES-HERE]" data-callback="onFepCaptchaSubmit"></div>

BACK-END:

    public static bool IsCaptchaValid(HttpRequestBase requestBase)
    {
        var recaptchaResponse = requestBase.Form["g-recaptcha-response"];
        if (string.IsNullOrEmpty(recaptchaResponse))
        {
            return false;
        }

        string postData = string.Format("secret={0}&response={1}&remoteip={2}", "[YOUR-KEY-GOES-HERE]", recaptchaResponse, requestBase.UserHostAddress);
        byte[] data = System.Text.Encoding.ASCII.GetBytes(postData);

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.google.com/recaptcha/api/siteverify");

        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = data.Length;

        using (var stream = request.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }

        var response = (HttpWebResponse)request.GetResponse();

        var responseString = "";

        using (var sr = new System.IO.StreamReader(response.GetResponseStream()))
        {
            responseString = sr.ReadToEnd();
        }

        return System.Text.RegularExpressions.Regex.IsMatch(responseString, "\"success\"(\\s*?):(\\s*?)true", System.Text.RegularExpressions.RegexOptions.Compiled);
    }

Call the above method within your Controller's POST action.

How to make button fill table cell

For starters:

<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.

This would be the optimal solution:

<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

socket.emit() vs. socket.send()

socket.send is implemented for compatibility with vanilla WebSocket interface. socket.emit is feature of Socket.IO only. They both do the same, but socket.emit is a bit more convenient in handling messages.

Checking whether a String contains a number value in Java

if(str.matches(".*\\d.*")){
   // contains a number
} else{
   // does not contain a number
}

Previous suggested solution, which does not work, but brought back because of @Eng.Fouad's request/suggestion.

Not working suggested solution

String strWithNumber = "This string has a 1 number";
String strWithoutNumber = "This string does not have a number";

System.out.println(strWithNumber.contains("\d"));
System.out.println(strWithoutNumber.contains("\d"));

Working solution

String strWithNumber = "This string has a 1 number";
if(strWithNumber.matches(".*\\d.*")){
    System.out.println("'"+strWithNumber+"' contains digit");
} else{
    System.out.println("'"+strWithNumber+"' does not contain a digit");
}

String strWithoutNumber = "This string does not have a number";
if(strWithoutNumber.matches(".*\\d.*")){
    System.out.println("'"+strWithoutNumber+"' contains digit");
} else{
    System.out.println("'"+strWithoutNumber+"' does not contain a digit");
}

Output

'This string has a 1 number' contains digit
'This string does not have a number' does not contain a digit

Sorting Directory.GetFiles()

In .NET 2.0, you'll need to use Array.Sort to sort the FileSystemInfos.

Additionally, you can use a Comparer delegate to avoid having to declare a class just for the comparison:

DirectoryInfo dir = new DirectoryInfo(path);
FileSystemInfo[] files = dir.GetFileSystemInfos();

// sort them by creation time
Array.Sort<FileSystemInfo>(files, delegate(FileSystemInfo a, FileSystemInfo b)
                                    {
                                        return a.LastWriteTime.CompareTo(b.LastWriteTime);
                                    });

ES6 exporting/importing in index file

Too late but I want to share the way that I resolve it.

Having model file which has two named export:

export { Schema, Model };

and having controller file which has the default export:

export default Controller;

I exposed in the index file in this way:

import { Schema, Model } from './model';
import Controller from './controller';

export { Schema, Model, Controller };

and assuming that I want import all of them:

import { Schema, Model, Controller } from '../../path/';

How to implode array with key and value without foreach in PHP

There is also var_export and print_r more commonly known for printing debug output but both functions can take an optional argument to return a string instead.

Using the example from the question as data.

$array = ["item1"=>"object1", "item2"=>"object2","item-n"=>"object-n"];

Using print_r to turn the array into a string

This will output a human readable representation of the variable.

$string = print_r($array, true);
echo $string;

Will output:

Array
(
    [item1] => object1
    [item2] => object2
    [item-n] => object-n
)

Using var_export to turn the array into a string

Which will output a php string representation of the variable.

$string = var_export($array, true);
echo $string;

Will output:

array (
  'item1' => 'object1',
  'item2' => 'object2',
  'item-n' => 'object-n',
)

Because it is valid php we can evaluate it.

eval('$array2 = ' . var_export($array, true) . ';');
var_dump($array2 === $array);

Outputs:

bool(true)

How do I scroll a row of a table into view (element.scrollintoView) using jQuery?

much simpler:

$("selector for element").get(0).scrollIntoView();

if more than one item returns in the selector, the get(0) will get only the first item.

Difference between map, applymap and apply methods in Pandas

FOMO:

The following example shows apply and applymap applied to a DataFrame.

map function is something you do apply on Series only. You cannot apply map on DataFrame.

The thing to remember is that apply can do anything applymap can, but apply has eXtra options.

The X factor options are: axis and result_type where result_type only works when axis=1 (for columns).

df = DataFrame(1, columns=list('abc'),
                  index=list('1234'))
print(df)

f = lambda x: np.log(x)
print(df.applymap(f)) # apply to the whole dataframe
print(np.log(df)) # applied to the whole dataframe
print(df.applymap(np.sum)) # reducing can be applied for rows only

# apply can take different options (vs. applymap cannot)
print(df.apply(f)) # same as applymap
print(df.apply(sum, axis=1))  # reducing example
print(df.apply(np.log, axis=1)) # cannot reduce
print(df.apply(lambda x: [1, 2, 3], axis=1, result_type='expand')) # expand result

As a sidenote, Series map function, should not be confused with the Python map function.

The first one is applied on Series, to map the values, and the second one to every item of an iterable.


Lastly don't confuse the dataframe apply method with groupby apply method.