Programs & Examples On #Hotcocoa

HotCocoa simplifies the process of creating and configuring Cocoa objects when building native Mac apps in Ruby.

How to append one file to another in Linux from the shell?

cat can be the easy solution but that become very slow when we concat large files, find -print is to rescue you, though you have to use cat once.

amey@xps ~/work/python/tmp $ ls -lhtr
total 969M
-rw-r--r-- 1 amey amey 485M May 24 23:54 bigFile2.txt
-rw-r--r-- 1 amey amey 485M May 24 23:55 bigFile1.txt

 amey@xps ~/work/python/tmp $ time cat bigFile1.txt bigFile2.txt >> out.txt

real    0m3.084s
user    0m0.012s
sys     0m2.308s


amey@xps ~/work/python/tmp $ time find . -maxdepth 1 -type f -name 'bigFile*' -print0 | xargs -0 cat -- > outFile1

real    0m2.516s
user    0m0.028s
sys     0m2.204s

how to draw a rectangle in HTML or CSS?

I do the following in my eBay listings:

<p style="border:solid thick darkblue; border-radius: 1em; 
          border-width:3px; padding-left:9px; padding-top:6px; 
          padding-bottom:6px; margin:2px; width:980px;">

This produces a box border with rounded corners.You can play with the variables.

Data truncation: Data too long for column 'logo' at row 1

You are trying to insert data that is larger than allowed for the column logo.

Use following data types as per your need

TINYBLOB   :     maximum length of 255 bytes  
BLOB       :     maximum length of 65,535 bytes  
MEDIUMBLOB :     maximum length of 16,777,215 bytes  
LONGBLOB   :     maximum length of 4,294,967,295 bytes  

Use LONGBLOB to avoid this exception.

How to call jQuery function onclick?

JS

 $(function () {
    var url = $(location).attr('href');
    $('#spn_url').html('<strong>' + url + '</strong>');
    $("#submit").click(function () {
        alert('button clicked');
    });
});

html

<input id="submit" type="submit" value="submit" name="submit">

Best way to handle list.index(might-not-exist) in python?

I don't know why you should think it is dirty... because of the exception? if you want a oneliner, here it is:

thing_index = thing_list.index(elem) if thing_list.count(elem) else -1

but i would advise against using it; I think Ross Rogers solution is the best, use an object to encapsulate your desiderd behaviour, don't try pushing the language to its limits at the cost of readability.

asp.net mvc3 return raw html to view

What was working for me (ASP.NET Core), was to set return type ContentResult, then wrap the HMTL into it and set the ContentType to "text/html; charset=UTF-8". That is important, because, otherwise it will not be interpreted as HTML and the HTML language would be displayed as text.

Here's the example, part of a Controller class:

/// <summary>
/// Startup message displayed in browser.
/// </summary>
/// <returns>HTML result</returns>
[HttpGet]
public ContentResult Get()
{
    var result = Content("<html><title>DEMO</title><head><h2>Demo started successfully."
      + "<br/>Use <b><a href=\"http://localhost:5000/swagger\">Swagger</a></b>"
      + " to view API.</h2></head><body/></html>");
    result.ContentType = "text/html; charset=UTF-8";
    return result;
}

const to Non-const Conversion in C++

You can assign a const object to a non-const object just fine. Because you're copying and thus creating a new object, constness is not violated.

Like so:

int main() {
   const int a = 3;
   int b = a;
}

It's different if you want to obtain a pointer or reference to the original, const object:

int main() {
   const int a = 3;
   int& b = a;       // or int* b = &a;
}

//  error: invalid initialization of reference of type 'int&' from
//         expression of type 'const int'

You can use const_cast to hack around the type safety if you really must, but recall that you're doing exactly that: getting rid of the type safety. It's still undefined to modify a through b in the below example:

int main() {
   const int a = 3;
   int& b = const_cast<int&>(a);

   b = 3;
}

Although it compiles without errors, anything can happen including opening a black hole or transferring all your hard-earned savings into my bank account.

If you have arrived at what you think is a requirement to do this, I'd urgently revisit your design because something is very wrong with it.

Could not autowire field in spring. why?

When you get this error some annotation is missing. I was missing @service annotation on service. When I added that annotation it worked fine for me.

Saving and loading objects and using pickle

You didn't open the file in binary mode.

open("Fruits.obj",'rb')

Should work.

For your second error, the file is most likely empty, which mean you inadvertently emptied it or used the wrong filename or something.

(This is assuming you really did close your session. If not, then it's because you didn't close the file between the write and the read).

I tested your code, and it works.

Twitter Bootstrap tabs not working: when I click on them nothing happens

I just fixed this issue by adding data-toggle="tab" element in anchor tag

<div class="container">

<!-------->
  <div id="content">

   <ul class="nav nav-tabs">
<li class="active"><a data-toggle="tab" href="#red">Red</a></li>
<li><a data-toggle="tab"  href="#orange">Orange</a></li>
<li><a data-toggle="tab" href="#yellow">Yellow</a></li>
<li><a data-toggle="tab" href="#green">Green</a></li>
<li><a data-toggle="tab" href="#blue">Blue</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="red">
    <h1>Red</h1>
    <p>red red red red red red</p>
</div>
<div class="tab-pane" id="orange">
    <h1>Orange</h1>
    <p>orange orange orange orange orange</p>
</div>
<div class="tab-pane" id="yellow">
    <h1>Yellow</h1>
    <p>yellow yellow yellow yellow yellow</p>
</div>
<div class="tab-pane" id="green">
    <h1>Green</h1>
    <p>green green green green green</p>
</div>
<div class="tab-pane" id="blue">
    <h1>Blue</h1>
    <p>blue blue blue blue blue</p>

and added the following in head section http://code.jquery.com/jquery-1.7.1.js'>

How to approach a "Got minus one from a read call" error when connecting to an Amazon RDS Oracle instance

I would like to augment to Stephen C's answer, my case was on the first dot. So since we have DHCP to allocate IP addresses in the company, DHCP changed my machine's address without of course asking neither me nor Oracle. So out of the blue oracle refused to do anything and gave the minus one dreaded exception. So if you want to workaround this once and for ever, and since TCP.INVITED_NODES of SQLNET.ora file does not accept wildcards as stated here, you can add you machine's hostname instead of the IP address.

Setting the Textbox read only property to true using JavaScript

it depends on how you trigger the event. the key you are looking is textbox.clientid.

x.aspx code

<script type="text/javascript">

   function disable_textbox(tid) {
        var mytextbox = document.getElementById(tid);
         mytextbox.disabled=false
   }
</script>

code behind x.aspx.cs

    string frameScript = "<script language='javascript'>" + "disable_textbox(" + tx.ClientID  ");</script>";
    Page.ClientScript.RegisterStartupScript(Page.GetType(), "FrameScript", frameScript);

httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

So while this is answered and accepted it still came up as a top search result and the answers though laid out (after lots of research) left me scratching my head and digging a lot further. So here's a quick layout of how I resolved the issue.

Assuming my server is myserver.myhome.com and my static IP address is 192.168.1.150:

  1. Edit the hosts file

    $ sudo nano -w /etc/hosts
    
    127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
    
    127.0.0.1 myserver.myhome.com myserver
    
    192.168.1.150 myserver.myhome.com myserver
    
    ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
    ::1 myserver.myhome.com myserver
    
  2. Edit httpd.conf

    $ sudo nano -w /etc/apache2/httpd.conf
    
    ServerName myserver.myhome.com
    
  3. Edit network

    $ sudo nano -w /etc/sysconfig/network HOSTNAME=myserver.myhome.com
    
  4. Verify

    $ hostname
    
    (output) myserver.myhome.com
    
    $ hostname -f
    
    (output) myserver.myhome.com
    
  5. Restart Apache

    $ sudo /etc/init.d/apache2 restart
    

It appeared the difference was including myserver.myhome.com to both the 127.0.0.1 as well as the static IP address 192.168.1.150 in the hosts file. The same on Ubuntu Server and CentOS.

JQuery/Javascript: check if var exists

For your case, and 99.9% of all others elclanrs answer is correct.

But because undefined is a valid value, if someone were to test for an uninitialized variable

var pagetype; //== undefined
if (typeof pagetype === 'undefined') //true

the only 100% reliable way to determine if a var exists is to catch the exception;

var exists = false;
try { pagetype; exists = true;} catch(e) {}
if (exists && ...) {}

But I would never write it this way

How do I bottom-align grid elements in bootstrap fluid layout

Just set the parent to display:flex; and the child to margin-top:auto. This will place the child content at the bottom of the parent element, assuming the parent element has a height greater than the child element.

There is no need to try and calculate a value for margin-top when you have a height on your parent element or another element greater than your child element of interest within your parent element.

C# - Substring: index and length must refer to a location within the string

string newString = url.Substring(18, (url.LastIndexOf(".") - 18))

How to set xlim and ylim for a subplot in matplotlib

You should use the OO interface to matplotlib, rather than the state machine interface. Almost all of the plt.* function are thin wrappers that basically do gca().*.

plt.subplot returns an axes object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc.

import matplotlib.pyplot as plt

ax1 = plt.subplot(131)
ax1.scatter([1, 2], [3, 4])
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 5])


ax2 = plt.subplot(132)
ax2.scatter([1, 2],[3, 4])
ax2.set_xlim([0, 5])
ax2.set_ylim([0, 5])

and so on for as many axes as you want.

or better, wrap it all up in a loop:

import matplotlib.pyplot as plt

DATA_x = ([1, 2],
          [2, 3],
          [3, 4])

DATA_y = DATA_x[::-1]

XLIMS = [[0, 10]] * 3
YLIMS = [[0, 10]] * 3

for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)):
    ax = plt.subplot(1, 3, j + 1)
    ax.scatter(x, y)
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)

Will the IE9 WebBrowser Control Support all of IE9's features, including SVG?

The IE9 "version" of the WebBrowser control, like the IE8 version, is actually several browsers in one. Unlike the IE8 version, you do have a little more control over the rendering mode inside the page by changing the doctype. Of course, to change the browser mode you have to set your registry like the earlier answer. Here is a reg file fragment for FEATURE_BROWSER_EMULATION:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION]
"contoso.exe"=dword:00002328

Here is the complete set of codes:

  • 9999 (0x270F) - Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the !DOCTYPE directive.
  • 9000 (0x2328) - Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode.
  • 8888 (0x22B8) -Webpages are displayed in IE8 Standards mode, regardless of the !DOCTYPE directive.
  • 8000 (0x1F40) - Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode.
  • 7000 (0x1B58) - Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode.

The full docs:

http://msdn.microsoft.com/en-us/library/ee330730%28VS.85%29.aspx#browser_emulation

How do I run msbuild from the command line using Windows SDK 7.1?

The SetEnv.cmd script that the "SDK command prompt" shortcut runs checks for cl.exe in various places before setting up entries to add to PATH. So it fails to add anything if a native C compiler is not installed.

To fix that, apply the following patch to <SDK install dir>\Bin\SetEnv.cmd. This will also fix missing paths to other tools located in <SDK install dir>\Bin and subfolders. Of course, you can install the C compiler instead to work around this bug.

--- SetEnv.Cmd_ 2010-04-27 19:52:00.000000000 +0400
+++ SetEnv.Cmd  2013-12-02 15:05:30.834400000 +0400
@@ -228,10 +228,10 @@

 IF "%CURRENT_CPU%" =="x64" (
   IF "%TARGET_CPU%" == "x64" (
+    SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
+    SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\x64;%WindowsSdkDir%Bin\x64;%WindowsSdkDir%Bin;"
     IF EXIST "%VCTools%\amd64\cl.exe" (
       SET "VCTools=%VCTools%\amd64;%VCTools%\VCPackages;"
-      SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\x64;%WindowsSdkDir%Bin\x64;%WindowsSdkDir%Bin;"
-      SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
     ) ELSE (
       SET VCTools=
       ECHO The x64 compilers are not currently installed.
@@ -239,10 +239,10 @@
       ECHO .
     )
   ) ELSE IF "%TARGET_CPU%" == "IA64" (
+    SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
+    SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\x64;%WindowsSdkDir%Bin\x64;%WindowsSdkDir%Bin;"
     IF EXIST "%VCTools%\x86_ia64\cl.exe" (
       SET "VCTools=%VCTools%\x86_ia64;%VCTools%\VCPackages;"
-      SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\x64;%WindowsSdkDir%Bin\x64;%WindowsSdkDir%Bin;"
-      SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
     ) ELSE (
       SET VCTools=
       ECHO The IA64 compilers are not currently installed.
@@ -250,10 +250,10 @@
       ECHO .
     )
   ) ELSE IF "%TARGET_CPU%" == "x86" (
+    SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
+    SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
     IF EXIST "%VCTools%\cl.exe" (
       SET "VCTools=%VCTools%;%VCTools%\VCPackages;"
-      SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
-      SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
     ) ELSE (
       SET VCTools=
       ECHO The x86 compilers are not currently installed.
@@ -263,10 +263,10 @@
   )
 ) ELSE IF "%CURRENT_CPU%" =="IA64" (
   IF "%TARGET_CPU%" == "IA64" (
+    SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
+    SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\IA64;%WindowsSdkDir%Bin\IA64;%WindowsSdkDir%Bin;"
     IF EXIST "%VCTools%\IA64\cl.exe" (
       SET "VCTools=%VCTools%\IA64;%VCTools%;%VCTools%\VCPackages;"
-      SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\IA64;%WindowsSdkDir%Bin\IA64;%WindowsSdkDir%Bin;"
-      SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
     ) ELSE (
       SET VCTools=
       ECHO The IA64 compilers are not currently installed.
@@ -274,10 +274,10 @@
       ECHO .
     )
   ) ELSE IF "%TARGET_CPU%" == "x64" (
+    SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
+    SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\IA64;%WindowsSdkDir%Bin\IA64;%WindowsSdkDir%Bin;"
     IF EXIST "%VCTools%\x86_amd64\cl.exe" (
       SET "VCTools=%VCTools%\x86_amd64;%VCTools%\VCPackages;"
-      SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\IA64;%WindowsSdkDir%Bin\IA64;%WindowsSdkDir%Bin;"
-      SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
     ) ELSE (
       SET VCTools=
       ECHO The VC compilers are not currently installed.
@@ -285,10 +285,10 @@
       ECHO .
     )
   ) ELSE IF "%TARGET_CPU%" == "x86" (
+    SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
+    SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
     IF EXIST "%VCTools%\cl.exe" (
       SET "VCTools=%VCTools%;%VCTools%\VCPackages;"
-      SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
-      SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
     ) ELSE (
       SET VCTools=
       ECHO The x86 compilers are not currently installed.
@@ -298,10 +298,10 @@
   )
 ) ELSE IF "%CURRENT_CPU%"=="x86" (
   IF "%TARGET_CPU%" == "x64" (
+    SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
+    SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
     IF EXIST "%VCTools%\x86_amd64\cl.exe" (
       SET "VCTools=%VCTools%\x86_amd64;%VCTools%\VCPackages;"
-      SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
-      SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
     ) ELSE (
       SET VCTools=
       ECHO The x64 cross compilers are not currently installed.
@@ -309,10 +309,10 @@
       ECHO .
     )
   ) ELSE IF "%TARGET_CPU%" == "IA64" (
+    SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
+    SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
     IF EXIST "%VCTools%\x86_IA64\cl.exe" (
       SET "VCTools=%VCTools%\x86_IA64;%VCTools%;%VCTools%\VCPackages;"
-      SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
-      SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
     ) ELSE (
       SET VCTools=
       ECHO The IA64 compilers are not currently installed.
@@ -320,10 +320,10 @@
       ECHO .
     )
   ) ELSE IF "%TARGET_CPU%" == "x86" (
+    SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
+    SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
     IF EXIST "%VCTools%\cl.exe" (
       SET "VCTools=%VCTools%;%VCTools%\VCPackages;"
-      SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
-      SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
     ) ELSE (
       SET VCTools=
       ECHO The x86 compilers are not currently installed. x86-x86
@@ -331,15 +331,17 @@
       ECHO .
     )
   )
-) ELSE IF EXIST "%VCTools%\cl.exe" (
-  SET "VCTools=%VCTools%;%VCTools%\VCPackages;"
-  SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
-  SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
 ) ELSE (
-  SET VCTools=
-  ECHO The x86 compilers are not currently installed. default
-  ECHO Please go to Add/Remove Programs to update your installation.
-  ECHO .
+  SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
+  SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
+  IF EXIST "%VCTools%\cl.exe" (
+    SET "VCTools=%VCTools%;%VCTools%\VCPackages;"
+  ) ELSE (
+    SET VCTools=
+    ECHO The x86 compilers are not currently installed. default
+    ECHO Please go to Add/Remove Programs to update your installation.
+    ECHO .
+  )
 )

 :: --------------------------------------------------------------------------------------------

Getting the docstring from a function

Interactively, you can display it with

help(my_func)

Or from code you can retrieve it with

my_func.__doc__

Get the current user, within an ApiController action, without passing the userID as a parameter

In .Net Core use User.Identity.Name to get the Name claim of the user.

Find files in a folder using Java

I know, this is an old question. But just for the sake of completeness, the lambda version.

File dir = new File(directory);
File[] files = dir.listFiles((dir1, name) -> name.startsWith("temp") && name.endsWith(".txt"));

How to read a text file directly from Internet using Java?

For an old school input stream, use this code:

  InputStream in = new URL("http://google.com/").openConnection().getInputStream();

Beautiful Soup and extracting a div and its contents by ID

have you tried soup.findAll("div", {"id": "articlebody"})?

sounds crazy, but if you're scraping stuff from the wild, you can't rule out multiple divs...

Python 101: Can't open file: No such file or directory

I resolved this problem by navigating to C:\Python27\Scripts folder and then run file.py file instead of C:\Python27 folder

__proto__ VS. prototype in JavaScript

Prototype or Object.prototype is a property of an object literal. It represents the Object prototype object which you can override to add more properties or methods further along the prototype chain.

__proto__ is an accessor property (get and set function) that exposes the internal prototype of an object thru which it is accessed.

References:

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype
  2. http://www.w3schools.com/js/js_object_prototypes.asp

  3. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto

Cross-Origin Request Blocked

@Egidius, when creating an XMLHttpRequest, you should use

var xhr = new XMLHttpRequest({mozSystem: true});

What is mozSystem?

mozSystem Boolean: Setting this flag to true allows making cross-site connections without requiring the server to opt-in using CORS. Requires setting mozAnon: true, i.e. this can't be combined with sending cookies or other user credentials. This only works in privileged (reviewed) apps; it does not work on arbitrary webpages loaded in Firefox.

Changes to your Manifest

On your manifest, do not forget to include this line on your permissions:

"permissions": {
       "systemXHR" : {},
}

How to disable EditText in Android

You can write edittext.setInputType(0) if you want to show the edittext but not input any values

My prerelease app has been "processing" for over a week in iTunes Connect, what gives?

I ran into this issue yesterday. I submitted multiple builds with a variety of different settings. What finally worked for me was submitting through Application Loader with no bitcode.

I hope this helps someone avoid the headache I went through. Its been 24 hours and the apps submitted through Xcode are all still "processing", the one submitted through Application Loader was available within an hour or so.

Cannot convert lambda expression to type 'string' because it is not a delegate type

I think you are missing using System.Linq; from this system class.

and also add using System.Data.Entity; to the code

Print a variable in hexadecimal in Python

You mean you have a string of bytes in my_hex which you want to print out as hex numbers, right? E.g., let's take your example:

>>> my_string = "deadbeef"
>>> my_hex = my_string.decode('hex')  # python 2 only
>>> print my_hex
Þ ­ ¾ ï

This construction only works on Python 2; but you could write the same string as a literal, in either Python 2 or Python 3, like this:

my_hex = "\xde\xad\xbe\xef"

So, to the answer. Here's one way to print the bytes as hex integers:

>>> print " ".join(hex(ord(n)) for n in my_hex)
0xde 0xad 0xbe 0xef

The comprehension breaks the string into bytes, ord() converts each byte to the corresponding integer, and hex() formats each integer in the from 0x##. Then we add spaces in between.

Bonus: If you use this method with unicode strings (or Python 3 strings), the comprehension will give you unicode characters (not bytes), and you'll get the appropriate hex values even if they're larger than two digits.

Addendum: Byte strings

In Python 3 it is more likely you'll want to do this with a byte string; in that case, the comprehension already returns ints, so you have to leave out the ord() part and simply call hex() on them:

>>> my_hex = b'\xde\xad\xbe\xef'
>>> print(" ".join(hex(n) for n in my_hex))
0xde 0xad 0xbe 0xef

How to trigger click event on href element

I was facing a similar issue how to click a button, instead of a link. It did not success in the methods .trigger('click') or [0].click(), and I did not know why. At last, the following was working for me:

$('#elementid').mousedown();

Invalid length for a Base-64 char array

My guess is that you simply need to URL-encode your Base64 string when you include it in the querystring.

Base64 encoding uses some characters which must be encoded if they're part of a querystring (namely + and /, and maybe = too). If the string isn't correctly encoded then you won't be able to decode it successfully at the other end, hence the errors.

You can use the HttpUtility.UrlEncode method to encode your Base64 string:

string msg = "Please click on the link below or paste it into a browser "
             + "to verify your email account.<br /><br /><a href=\""
             + _configuration.RootURL + "Accounts/VerifyEmail.aspx?a="
             + HttpUtility.UrlEncode(userName.Encrypt("verify")) + "\">"
             + _configuration.RootURL + "Accounts/VerifyEmail.aspx?a="
             + HttpUtility.UrlEncode(userName.Encrypt("verify")) + "</a>";

How to print the values of slices

I prefer fmt.Printf("%+q", arr) which will print

["some" "values" "list"]

https://play.golang.org/p/XHfkENNQAKb

How to check if a number is between two values?

It's an old question, however might be useful for someone like me.

lodash has _.inRange() function https://lodash.com/docs/4.17.4#inRange

Example:

_.inRange(3, 2, 4);
// => true

Please note that this method utilizes the Lodash utility library, and requires access to an installed version of Lodash.

Get GMT Time in Java

You can’t

First, you are asking the impossible. An old-fashioned Date object hasn’t got, as in cannot have a time zone or GMT offset.

But the date is always is interpreted in my local time zone.

I suppose that you have printed the Date or done something else that implicitly calls it toString method. I believe that this is the only time that the Date is interpreted in your time zone. More precisely in the current default time zone of your JVM. On the other hand this is unavoidable. Date.toString() does behave in that way, it picks up the JVM’s time zone setting and uses it for rendering the string to be returned.

You can with java.time

You shouldn’t use a Date, though. That class is poorly designed and fortunately long outdated. Also java.time, the modern Java date and time API that replaces it, has a class or two for dates and times with offset from GMT or UTC. I am considering GMT and UTC synonymous for now, strictly speaking they are not.

    OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
    System.out.println("Time now in UTC (GMT) is " + now);

When I ran this snippet just now, the output was:

Time now in UTC (GMT) is 2019-06-17T11:51:38.246188Z

The trailing Z of the output means UTC.

Links

How to update maven repository in Eclipse?

If Maven update snapshot doesn't work and if you have Spring Tooling, one interesting way is to remove

  • Right-click on your project then Maven > Disable Maven Nature
  • Right-click on your project then Spring Tools > Update Maven Dependencies
  • After "BUILD SUCCESS", Right-click on your project then Configure > Convert Maven Project

Note: Maven update snapshot sometimes stops working if you use anything else i.e. eclipse:eclipse or Spring Tooling

SET versus SELECT when assigning variables?

Quote, which summarizes from this article:

  1. SET is the ANSI standard for variable assignment, SELECT is not.
  2. SET can only assign one variable at a time, SELECT can make multiple assignments at once.
  3. If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
  4. When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from its previous value)
  5. As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.

convert iso date to milliseconds in javascript

if wants to convert UTC date to milliseconds
syntax : Date.UTC(year, month, ?day, ?hours, ?min, ?sec, ?milisec);
e.g :
date_in_mili = Date.UTC(2020, 07, 03, 03, 40, 40, 40);
console.log('miliseconds', date_in_mili);

Which HTTP methods match up to which CRUD methods?

The building blocks of REST are mainly the resources (and URI) and the hypermedia. In this context, GET is the way to get a representation of the resource (which can indeed be mapped to a SELECT in CRUD terms).

However, you shouldn't necessarily expect a one-to-one mapping between CRUD operations and HTTP verbs. The main difference between PUT and POST is about their idempotent property. POST is also more commonly used for partial updates, as PUT generally implies sending a full new representation of the resource.

I'd suggest reading this:

The HTTP specification is also a useful reference:

The PUT method requests that the enclosed entity be stored under the supplied Request-URI.

[...]

The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request -- the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires that the request be applied to a different URI,

Call Stored Procedure within Create Trigger in SQL Server

finally...

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON

GO
ALTER TRIGGER [dbo].[RA2Newsletter] 
   ON  [dbo].[Reiseagent] 
   AFTER INSERT
 AS
    declare
    @rAgent_Name nvarchar(50),
    @rAgent_Email nvarchar(50),
    @rAgent_IP nvarchar(50),
    @hotelID int,
    @retval int


BEGIN
    SET NOCOUNT ON;

    -- Insert statements for trigger here
    Select @rAgent_Name=rAgent_Name,@rAgent_Email=rAgent_Email,@rAgent_IP=rAgent_IP,@hotelID=hotelID  From Inserted
    EXEC insert2Newsletter '','',@rAgent_Name,@rAgent_Email,@rAgent_IP,@hotelID,'RA', @retval

END

CSS: Set Div height to 100% - Pixels

I'm guessing that you are trying to get sticky footer

How to refresh Gridview after pressed a button in asp.net

All you have to do is In your bLoanButton_Click , add a line to rebind the Grid to the SqlDataSource :

protected void bLoanButton_Click(object sender, EventArgs e)
{

//your same code
........

GridView1.DataBind();


}

regards

Copy files from one directory into an existing directory

If you want to copy something from one directory into the current directory, do this:

cp dir1/* .

This assumes you're not trying to copy hidden files.

Split string, convert ToList<int>() in one line

You can use new C# 6.0 Language Features:

  • replace delegate (s) => { return Convert.ToInt32(s); } with corresponding method group Convert.ToInt32
  • replace redundant constructor call: new Converter<string, int>(Convert.ToInt32) with: Convert.ToInt32

The result will be:

var intList = new List<int>(Array.ConvertAll(sNumbers.Split(','), Convert.ToInt32));

How can I decrypt MySQL passwords

If a proper encryption method was used, it's not going to be possible to easily retrieve them.

Just reset them with new passwords.

Edit: The string looks like it is using PASSWORD():

UPDATE user SET password = PASSWORD("newpassword");

How do I see what character set a MySQL database / table / column is?

For databases:

USE your_database_name;
show variables like "character_set_database";
-- or:
-- show variables like "collation_database";

Cf. this page. And check out the MySQL manual

Complexities of binary tree traversals

Consider a skewed binary tree with 3 nodes as 7, 3, 2. For any operation like for searching 2, we have to traverse 3 nodes, for deleting 2 also, we have to traverse 3 nodes and for for inserting 1 also, we have to traverse 3 nodes. So, binary tree has worst case complexity of O(n).

Changing image size in Markdown

The addition of relative dimensions to the source URL will be rendered in the majority of Markdown renderers.

We implemented this in Corilla as I think the pattern is one that follows expectations of existing workflows without pushing the user to rely on basic HTML. If your favourite tool doesn't follow a similar pattern it's worth raising a feature request.

Example of syntax:

![a-kitten.jpg](//corilla.com/a-kitten-2xU3C2.jpg =200x200)

Example of kitten:

kitten

jQuery vs. javascript?

Jquery VS javascript, I am completely against the OP in this question. Comparison happens with two similar things, not in such case.

Jquery is Javascript. A javascript library to reduce vague coding, collection commonly used javascript functions which has proven to help in efficient and fast coding.

Javascript is the source, the actual scripts that browser responds to.

What's the difference between HEAD, working tree and index, in Git?

The difference between HEAD (current branch or last committed state on current branch), index (aka. staging area) and working tree (the state of files in checkout) is described in "The Three States" section of the "1.3 Git Basics" chapter of Pro Git book by Scott Chacon (Creative Commons licensed).

Here is the image illustrating it from this chapter:

Local Operations - working directory vs. staging area (index) vs git repository (HEAD)

In the above image "working directory" is the same as "working tree", the "staging area" is an alternate name for git "index", and HEAD points to currently checked out branch, which tip points to last commit in the "git directory (repository)"

Note that git commit -a would stage changes and commit in one step.

How many bits is a "word"?

I'm not familiar with either of these books, but the second is closer to current reality. The first may be discussing a specific processor.

Processors have been made with quite a variety of word sizes, not always a multiple of 8.

The 8086 and 8087 processors used 16 bit words, and it's likely this is the machine the first author was writing about.

More recent processors commonly use 32 or 64 bit words.

In the 50's and 60's there were machines with words sizes that seem quite strange to us now, such as 4, 9 and 36. Since about the 70's word size has commonly been a power of 2 and a multiple of 8.

Putting a password to a user in PhpMyAdmin in Wamp

Search your installation of PhpMyAdmin for a file called Documentation.txt. This describes how to create a file called config.inc.php and how you can configure the username and password.

How to get the parents of a Python class?

If you want all the ancestors rather than just the immediate ones, use inspect.getmro:

import inspect
print inspect.getmro(cls)

Usefully, this gives you all ancestor classes in the "method resolution order" -- i.e. the order in which the ancestors will be checked when resolving a method (or, actually, any other attribute -- methods and other attributes live in the same namespace in Python, after all;-).

How to correctly use "section" tag in HTML5?

that’s just wrong: is not a wrapper. The element denotes a semantic section of your content to help construct a document outline. It should contain a heading. If you’re looking for a page wrapper element (for any flavour of HTML or XHTML), consider applying styles directly to the element as described by Kroc Camen. If you still need an additional element for styling, use a . As Dr Mike explains, div isn’t dead, and if there’s nothing else more appropriate, it’s probably where you really want to apply your CSS.

you can check this : http://html5doctor.com/avoiding-common-html5-mistakes/

How to make a char string from a C macro's value?

He who is Shy* gave you the germ of an answer, but only the germ. The basic technique for converting a value into a string in the C pre-processor is indeed via the '#' operator, but a simple transliteration of the proposed solution gets a compilation error:

#define TEST_FUNC test_func
#define TEST_FUNC_NAME #TEST_FUNC

#include <stdio.h>
int main(void)
{
    puts(TEST_FUNC_NAME);
    return(0);
}

The syntax error is on the 'puts()' line - the problem is a 'stray #' in the source.

In section 6.10.3.2 of the C standard, 'The # operator', it says:

Each # preprocessing token in the replacement list for a function-like macro shall be followed by a parameter as the next preprocessing token in the replacement list.

The trouble is that you can convert macro arguments to strings -- but you can't convert random items that are not macro arguments.

So, to achieve the effect you are after, you most certainly have to do some extra work.

#define FUNCTION_NAME(name) #name
#define TEST_FUNC_NAME  FUNCTION_NAME(test_func)

#include <stdio.h>

int main(void)
{
    puts(TEST_FUNC_NAME);
    return(0);
}

I'm not completely clear on how you plan to use the macros, and how you plan to avoid repetition altogether. This slightly more elaborate example might be more informative. The use of a macro equivalent to STR_VALUE is an idiom that is necessary to get the desired result.

#define STR_VALUE(arg)      #arg
#define FUNCTION_NAME(name) STR_VALUE(name)

#define TEST_FUNC      test_func
#define TEST_FUNC_NAME FUNCTION_NAME(TEST_FUNC)

#include <stdio.h>

static void TEST_FUNC(void)
{
    printf("In function %s\n", TEST_FUNC_NAME);
}

int main(void)
{
    puts(TEST_FUNC_NAME);
    TEST_FUNC();
    return(0);
}

* At the time when this answer was first written, shoosh's name used 'Shy' as part of the name.

How to handle the new window in Selenium WebDriver using Java?

i was having some issues with windowhandle and tried this one. this one works good for me.

String parentWindowHandler = driver.getWindowHandle(); 
String subWindowHandler = null;

Set<String> handles = driver.getWindowHandles();
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
    subWindowHandler = iterator.next();
    driver.switchTo().window(subWindowHandler);

    System.out.println(subWindowHandler);
}


driver.switchTo().window(parentWindowHandler); 

Delete multiple rows by selecting checkboxes using PHP

<?php $sql = "SELECT * FROM guest_book";
                            $res = mysql_query($sql);
                            if (mysql_num_rows($res)) {
                            $query = mysql_query("SELECT * FROM guest_book ORDER BY id");
                            $i=1;
                            while($row = mysql_fetch_assoc($query)){
                            ?>


<input type="checkbox" name="checkboxstatus[<?php echo $i; ?>]" value="<?php echo $row['id']; ?>"  />

<?php $i++; }} ?>


<input type="submit" value="Delete" name="Delete" />

if($_REQUEST['Delete'] != '')
{
    if(!empty($_REQUEST['checkboxstatus'])) {
        $checked_values = $_REQUEST['checkboxstatus'];
        foreach($checked_values as $val) {
            $sqldel = "DELETE from guest_book WHERE id = '$val'";
           mysql_query($sqldel);

        }
    }
} 

MySQL Server has gone away when importing large sql file

If you are running with default values then you have a lot of room to optimize your mysql configuration.

The first step I recommend is to increase the max_allowed_packet to 128M.

Then download the MySQL Tuning Primer script and run it. It will provide recommendations to several facets of your config for better performance.

Also look into adjusting your timeout values both in MySQL and PHP.

How big (file size) is the file you are importing and are you able to import the file using the mysql command line client instead of PHPMyAdmin?

Javascript onHover event

How about something like this?

<html>
<head>
<script type="text/javascript">

var HoverListener = {
  addElem: function( elem, callback, delay )
  {
    if ( delay === undefined )
    {
      delay = 1000;
    }

    var hoverTimer;

    addEvent( elem, 'mouseover', function()
    {
      hoverTimer = setTimeout( callback, delay );
    } );

    addEvent( elem, 'mouseout', function()
    {
      clearTimeout( hoverTimer );
    } );
  }
}

function tester()
{
  alert( 'hi' );
}

//  Generic event abstractor
function addEvent( obj, evt, fn )
{
  if ( 'undefined' != typeof obj.addEventListener )
  {
    obj.addEventListener( evt, fn, false );
  }
  else if ( 'undefined' != typeof obj.attachEvent )
  {
    obj.attachEvent( "on" + evt, fn );
  }
}

addEvent( window, 'load', function()
{
  HoverListener.addElem(
      document.getElementById( 'test' )
    , tester 
  );
  HoverListener.addElem(
      document.getElementById( 'test2' )
    , function()
      {
        alert( 'Hello World!' );
      }
    , 2300
  );
} );

</script>
</head>
<body>
<div id="test">Will alert "hi" on hover after one second</div>
<div id="test2">Will alert "Hello World!" on hover 2.3 seconds</div>
</body>
</html>

How to encrypt a large file in openssl using public key

To safely encrypt large files (>600MB) with openssl smime you'll have to split each file into small chunks:

# Splits large file into 500MB pieces
split -b 500M -d -a 4 INPUT_FILE_NAME input.part.

# Encrypts each piece
find -maxdepth 1 -type f -name 'input.part.*' | sort | xargs -I % openssl smime -encrypt -binary -aes-256-cbc -in % -out %.enc -outform DER PUBLIC_PEM_FILE

For the sake of information, here is how to decrypt and put all pieces together:

# Decrypts each piece
find -maxdepth 1 -type f -name 'input.part.*.enc' | sort | xargs -I % openssl smime -decrypt -in % -binary -inform DEM -inkey PRIVATE_PEM_FILE -out %.dec

# Puts all together again
find -maxdepth 1 -type f -name 'input.part.*.dec' | sort | xargs cat > RESTORED_FILE_NAME

Checking network connection

import urllib

def connected(host='http://google.com'):
    try:
        urllib.urlopen(host)
        return True
    except:
        return False

# test
print( 'connected' if connected() else 'no internet!' )

For python 3, use urllib.request.urlopen(host)

Stop executing further code in Java

Just do:

public void onClick() {
    if(condition == true) {
        return;
    }
    string.setText("This string should not change if condition = true");
}

It's redundant to write if(condition == true), just write if(condition) (This way, for example, you'll not write = by mistake).

How to validate white spaces/empty spaces? [Angular 2]

i have used form valueChanges function to prevent white spaces. every time it will trim all the fields after that required validation will work for blank string.

Like here:-

this.anyForm.valueChanges.subscribe(data => {
   for (var key in data) {
        if (data[key].trim() == "") {
          this.f[key].setValue("", { emitEvent: false });
        }
      }
    }

Edited --

if you work with any number/integer in you form control in that case trim function will not work directly use like :

this.anyForm.valueChanges.subscribe(data => {
  for (var key in data) {
        if (data[key] && data[key].toString().trim() == "") {
          this.f[key].setValue("", { emitEvent: false });
        }
      }  
  }

javascript - pass selected value from popup window to parent window input box

(parent window)

<html> 
<script language="javascript"> 
function openWindow() { 
  window.open("target.html","_blank","height=200,width=400, status=yes,toolbar=no,menubar=no,location=no"); 
} 
</script> 
<body> 
<form name=frm> 
<input id=text1 type=text> 
<input type=button onclick="javascript:openWindow()" value="Open window.."> 
</form> 
</body> 
</html>

(child window)

<html> 
<script language="javascript"> 
function changeParent() { 
  window.opener.document.getElementById('text1').value="Value changed..";
  window.close();
} 
</script> 
<body> 
<form> 
<input type=button onclick="javascript:changeParent()" value="Change opener's textbox's value.."> 
</form> 
</body> 
</html>

http://www.codehappiness.com/post/access-parent-window-from-child-window-or-access-child-window-from-parent-window-using-javascript.aspx

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

In the case you are sure that you should be able to access given class, than this can mean you added several jars to your project containing classes with identical names (or paths) but different content and they are overshadowing each other (typically an old custom build jar contains built-in older version of a 3rd party library).

For example when you add a jar implementing:

a.b.c.d1
a.b.c.d2

but also an older version implementing only:

a.b.c.d1
(d2 is missing altogether or has restricted access)

Everything works fine in the code editor but fails during the compilation if the "old" library overshadows the new one - d2 suddenly turns out "missing or inaccessible" even when it is there.

The solution is a to check the order of compile-time libraries and make sure that the one with correct implementation goes first.

SQLAlchemy ORDER BY DESCENDING?

You can use .desc() function in your query just like this

query = (model.Session.query(model.Entry)
        .join(model.ClassificationItem)
        .join(model.EnumerationValue)
        .filter_by(id=c.row.id)
        .order_by(model.Entry.amount.desc())
        )

This will order by amount in descending order or

query = session.query(
    model.Entry
).join(
    model.ClassificationItem
).join(
    model.EnumerationValue
).filter_by(
    id=c.row.id
).order_by(
    model.Entry.amount.desc()
)
)

Use of desc function of SQLAlchemy

from sqlalchemy import desc
query = session.query(
    model.Entry
).join(
    model.ClassificationItem
).join(
    model.EnumerationValue
).filter_by(
    id=c.row.id
).order_by(
    desc(model.Entry.amount)
)
)

For official docs please use the link or check below snippet

sqlalchemy.sql.expression.desc(column) Produce a descending ORDER BY clause element.

e.g.:

from sqlalchemy import desc

stmt = select([users_table]).order_by(desc(users_table.c.name))

will produce SQL as:

SELECT id, name FROM user ORDER BY name DESC

The desc() function is a standalone version of the ColumnElement.desc() method available on all SQL expressions, e.g.:

stmt = select([users_table]).order_by(users_table.c.name.desc())

Parameters column – A ColumnElement (e.g. scalar SQL expression) with which to apply the desc() operation.

See also

asc()

nullsfirst()

nullslast()

Select.order_by()

A keyboard shortcut to comment/uncomment the select text in Android Studio

From menu, Code -> Comment with Line Commment. So simple. enter image description here

Or, alternatively, add a shortcut as the following: enter image description here

enter image description here

Differences between action and actionListener

As BalusC indicated, the actionListener by default swallows exceptions, but in JSF 2.0 there is a little more to this. Namely, it doesn't just swallows and logs, but actually publishes the exception.

This happens through a call like this:

context.getApplication().publishEvent(context, ExceptionQueuedEvent.class,                                                          
    new ExceptionQueuedEventContext(context, exception, source, phaseId)
);

The default listener for this event is the ExceptionHandler which for Mojarra is set to com.sun.faces.context.ExceptionHandlerImpl. This implementation will basically rethrow any exception, except when it concerns an AbortProcessingException, which is logged. ActionListeners wrap the exception that is thrown by the client code in such an AbortProcessingException which explains why these are always logged.

This ExceptionHandler can be replaced however in faces-config.xml with a custom implementation:

<exception-handlerfactory>
   com.foo.myExceptionHandler
</exception-handlerfactory>

Instead of listening globally, a single bean can also listen to these events. The following is a proof of concept of this:

@ManagedBean
@RequestScoped
public class MyBean {

    public void actionMethod(ActionEvent event) {

        FacesContext.getCurrentInstance().getApplication().subscribeToEvent(ExceptionQueuedEvent.class, new SystemEventListener() {

        @Override
        public void processEvent(SystemEvent event) throws AbortProcessingException {
            ExceptionQueuedEventContext content = (ExceptionQueuedEventContext)event.getSource();
            throw new RuntimeException(content.getException());
        }

        @Override
        public boolean isListenerForSource(Object source) {
            return true;
        }
        });

        throw new RuntimeException("test");
    }

}

(note, this is not how one should normally code listeners, this is only for demonstration purposes!)

Calling this from a Facelet like this:

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">
    <h:body>
        <h:form>
            <h:commandButton value="test" actionListener="#{myBean.actionMethod}"/>
        </h:form>
    </h:body>
</html>

Will result in an error page being displayed.

Using Apache POI how to read a specific excel column

heikkim is right, here is some sample code adapted from some code I have:

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
...
for (int rowIndex = 0; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
  row = sheet.getRow(rowIndex);
  if (row != null) {
    Cell cell = row.getCell(colIndex);
    if (cell != null) {
      // Found column and there is value in the cell.
      cellValueMaybeNull = cell.getStringCellValue();
      // Do something with the cellValueMaybeNull here ...
      // break; ???
    }
  }
}

For the colCount use something like row.getPhysicalNumberOfCells()

How to compile C++ under Ubuntu Linux?

even you can compile your c++ code by gcc Sounds funny ?? Yes it is. try it

$  gcc avishay.cpp -lstdc++

enjoy

Declare an empty two-dimensional array in Javascript?

You can fill an array with arrays using a function:

var arr = [];
var rows = 11;
var columns = 12;

fill2DimensionsArray(arr, rows, columns);

function fill2DimensionsArray(arr, rows, columns){
    for (var i = 0; i < rows; i++) {
        arr.push([0])
        for (var j = 0; j < columns; j++) {
            arr[i][j] = 0;
        }
    }
}

The result is:

Array(11)
0:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
1:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
2:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
3:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
4:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
5:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
6:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
7:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
8:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
9:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
10:(12)[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Two dimensional array list

for (Project project : listOfLists) {
    String nama_project = project.getNama_project();
    if (project.getModelproject().size() > 1) {
        for (int i = 1; i < project.getModelproject().size(); i++) {
            DataModel model = project.getModelproject().get(i);
            int id_laporan = model.getId();
            String detail_pekerjaan = model.getAlamat();
        }
    }
}

How to Install pip for python 3.7 on Ubuntu 18?

I used apt-get to install python3.7 in ubuntu18.04. The installations are as follows.

  1. install python3.7
sudo apt-get install python3.7 
  1. install pip3. It should be noted that this may install pip3 for python3.6.
sudo apt-get install python3-pip 
  1. change the default of python3 for python3.7. This is where the magic is, which will make the pip3 refer to python3.7.
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.7 1

Hope it works for you.

AngularJS: Can't I set a variable value on ng-click?

If you are using latest versions of Angular (2/5/6) :

In your component.ts

//x.component.ts
prefs = false;

hidePrefs(){
   this.prefs = true;
}

How remove border around image in css?

I faced similar problem with img tag I had added following line with img tag.

<img class="my-class">

And this is the css class

.my-class{
    background-image: url('add.gif');
    background-repeat: no-repeat;
    display: inline-block;
    width: 27px;
    height: 27px;
}

I changed the img tag to span tag with same css class. Border is not visible now.

<span class="my-class"></span>

Assigning the return value of new by reference is deprecated

Nitin is correct - the issue is actually in the MDB2 code.

According to Replacement for PEAR: MDB2 on PHP 5.3 you can update to the SVN version of MDB2 for a version which is PHP5.3 compatible.

As that answer was given in March 2010, and http://pear.php.net/package/MDB2/ shows a release some months later, I expect the current version of MDB2 will solve the issue also.

c# how to add byte to byte array

Although internally it creates a new array and copies values into it, you can use Array.Resize<byte>() for more readable code. Also you might want to consider checking the MemoryStream class depending on what you're trying to achieve.

Matplotlib transparent line plots

It really depends on what functions you're using to plot the lines, but try see if the on you're using takes an alpha value and set it to something like 0.5. If that doesn't work, try get the line objects and set their alpha values directly.

Is it bad practice to use break to exit a loop in Java?

In my opinion a For loop should be used when a fixed amount of iterations will be done and they won't be stopped before every iteration has been completed. In the other case where you want to quit earlier I prefer to use a While loop. Even if you read those two little words it seems more logical. Some examples:

for (int i=0;i<10;i++) {
    System.out.println(i);
}

When I read this code quickly I will know for sure it will print out 10 lines and then go on.

for (int i=0;i<10;i++) {
    if (someCondition) break;
    System.out.println(i);
}

This one is already less clear to me. Why would you first state you will take 10 iterations, but then inside the loop add some extra conditions to stop sooner?

I prefer the previous example written in this way (even when it's a little more verbose, but that's only with 1 line more):

int i=0;
while (i<10 && !someCondition) {
    System.out.println(i);
    i++;
}

Everyone who will read this code will see immediatly that there is an extra condition that might terminate the loop earlier.

Ofcourse in very small loops you can always discuss that every programmer will notice the break statement. But I can tell from my own experience that in larger loops those breaks can be overseen. (And that brings us to another topic to start splitting up code in smaller chunks)

How can I "reset" an Arduino board?

If nothing helped then you should arrange one more board and try to flash it through the Arduino as ISP option as shown in Arduino as ISP and Arduino Bootloaders or From Arduino to a Microcontroller on a Breadboard.

Instead of a boot loader, you can select your own programs to flash via ISP.

Django - Static file not found

Another error can be not having your app listed in the INSTALLED_APPS listing like:

INSTALLED_APPS = [
    # ...
    'your_app',
]

Without having it in, you can face problems like not detecting your static files, basically all the files involving your app. Even though it can be correct as suggested in the correct answer by using:

STATICFILES_DIRS = (adding/path/of/your/app)

Can be one of the errors and should be reviewed if getting this error.

Git: Find the most recent common ancestor of two branches

You are looking for git merge-base. Usage:

$ git merge-base branch2 branch3
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

date format yyyy-MM-ddTHH:mm:ssZ

One option could be converting DateTime to ToUniversalTime() before converting to string using "o" format. For example,

var dt = DateTime.Now.ToUniversalTime();
Console.WriteLine(dt.ToString("o"));

It will output:

2016-01-31T20:16:01.9092348Z

How to retrieve element value of XML using Java?

Since you are using this for configuration, your best bet is apache commons-configuration. For simple files it's way easier to use than "raw" XML parsers.

See the XML how-to

Where Is Machine.Config?

It semi-depends though... mine is:

C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG

and

C:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG

Where is web.xml in Eclipse Dynamic Web Project

When you create a Dynamic Web Project you have the option to automatically create the web.xml file. If you don't mark that, the eclipse doesn't create it...

So, you have to add a new web.xml file in the WEB-INF folder.

To add a web.xml click on Next -> Next instead of Finish. You will find it on the final screen of the wizard.

Composer killed while updating

Here's how I succeeded in installing maatwebsite\excel package from composer in Laravel Framework:

  1. I download composer.json file and composer.lock file from my remote server.
  2. I run composer update from local command prompt (then wait until all the install process finished).
  3. Upload composer.lock file to remote server.
  4. run composer install on remote server (then wait until all process finished).
  5. DONE

Re-ordering columns in pandas dataframe based on column name

Don't forget to add "inplace=True" to Wes' answer or set the result to a new DataFrame.

df.sort_index(axis=1, inplace=True)

Resize Google Maps marker icon image

If the original size is 100 x 100 and you want to scale it to 50 x 50, use scaledSize instead of Size.

var icon = {
    url: "../res/sit_marron.png", // url
    scaledSize: new google.maps.Size(50, 50), // scaled size
    origin: new google.maps.Point(0,0), // origin
    anchor: new google.maps.Point(0, 0) // anchor
};

var marker = new google.maps.Marker({
    position: new google.maps.LatLng(lat, lng),
    map: map,
    icon: icon
});

How to append to a file in Node?

In addition to denysonique's answer, sometimes asynchronous type of appendFile and other async methods in NodeJS are used where promise returns instead of callback passing. To do it you need to wrap the function with promisify HOF or import async functions from promises namespace:

const { appendFile } = require('fs').promises;

await appendFile('path/to/file/to/append', dataToAppend, optionalOptions);

I hope it'll help

What exactly does the Access-Control-Allow-Credentials header do?

By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.

In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.

The client code must set the withCredentials property on the XMLHttpRequest to true in order to give permission.

However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials header. Responding with this header to true means that the server allows cookies (or other user credentials) to be included on cross-origin requests.

You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.

Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).

What does random.sample() method in python do?

According to documentation:

random.sample(population, k)

Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.

Basically, it picks k unique random elements, a sample, from a sequence:

>>> import random
>>> c = list(range(0, 15))
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> random.sample(c, 5)
[9, 2, 3, 14, 11]

random.sample works also directly from a range:

>>> c = range(0, 15)
>>> c
range(0, 15)
>>> random.sample(c, 5)
[12, 3, 6, 14, 10]

In addition to sequences, random.sample works with sets too:

>>> c = {1, 2, 4}
>>> random.sample(c, 2)
[4, 1]

However, random.sample doesn't work with arbitrary iterators:

>>> c = [1, 3]
>>> random.sample(iter(c), 5)
TypeError: Population must be a sequence or set.  For dicts, use list(d).

Bash loop ping successful

I liked paxdiablo's script, but wanted a version that ran indefinitely. This version runs ping until a connection is established and then prints a message saying so.

echo "Testing..."

PING_CMD="ping -t 3 -c 1 google.com > /dev/null 2>&1"

eval $PING_CMD

if [[ $? -eq 0 ]]; then
    echo "Already connected."
else
    echo -n "Waiting for connection..."

    while true; do
        eval $PING_CMD

        if [[ $? -eq 0 ]]; then
            echo
            echo Connected.
            break
        else
            sleep 0.5
            echo -n .
        fi
    done
fi

I also have a Gist of this script which I'll update with fixes and improvements as needed.

How to avoid 'undefined index' errors?

foreach($i=0; $i<10; $i++){
    $v = @(array)$v;   
    // this could help defining $v as an array. 
    //@ is to supress undefined variable $v

    array_push($v, $i);
}

Downloading video from YouTube

You can check out libvideo. It's much more up-to-date than YoutubeExtractor, and is fast and clean to use.

How can I force users to access my page over HTTPS instead of HTTP?

The way I've done it before is basically like what you wrote, but doesn't have any hardcoded values:

if($_SERVER["HTTPS"] != "on")
{
    header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
    exit();
}

Why is jquery's .ajax() method not sending my session cookie?

After trying out the other solutions and still not getting it to work, I found out what the problem was in my case. I changed contentType from "application/json" to "text/plain".

$.ajax(fullUrl, {
    type: "GET",
    contentType: "text/plain",
    xhrFields: {
         withCredentials: true
    },
    crossDomain: true
});

nginx upload client_max_body_size issue

From the documentation:

It is necessary to keep in mind that the browsers do not know how to correctly show this error.

I suspect this is what's happening, if you inspect the HTTP to-and-fro using tools such as Firebug or Live HTTP Headers (both Firefox extensions) you'll be able to see what's really going on.

Convert an array into an ArrayList

List<Card> list = new ArrayList<Card>(Arrays.asList(hand));

Python: What OS am I running on?

You can look at the code in pyOSinfo which is part of the pip-date package, to get the most relevant OS information, as seen from your Python distribution.

One of the most common reasons people want to check their OS is for terminal compatibility and if certain system commands are available. Unfortunately, the success of this checking is somewhat dependent on your python installation and OS. For example, uname is not available on most Windows python packages. The above python program will show you the output of the most commonly used built-in functions, already provided by os, sys, platform, site.

enter image description here

So the best way to get only the essential code is looking at that as an example. (I guess I could have just pasted it here, but that would not have been politically correct.)

How do I change a tab background color when using TabLayout?

You can have it in the xml.

<android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        app:tabTextColor="@color/colorGray"
        app:tabSelectedTextColor="@color/colorWhite"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

MSSQL Regular expression

As above the question was originally about MySQL

Use REGEXP, not LIKE:

SELECT * FROM `table` WHERE ([url] NOT REGEXP '^[-A-Za-z0-9/.]+$')

Why can't DateTime.Parse parse UTC date

Assuming you use the format "o" for your datetime so you have "2016-07-24T18:47:36Z", there is a very simple way to handle this.

Call DateTime.Parse("2016-07-24T18:47:36Z").ToUniversalTime().

What happens when you call DateTime.Parse("2016-07-24T18:47:36Z") is you get a DateTime set to the local timezone. So it converts it to the local time.

The ToUniversalTime() changes it to a UTC DateTime and converts it back to UTC time.

Generate 'n' unique random numbers within a range

You could use the random.sample function from the standard library to select k elements from a population:

import random
random.sample(range(low, high), n)

In case of a rather large range of possible numbers, you could use itertools.islice with an infinite random generator:

import itertools
import random

def random_gen(low, high):
    while True:
        yield random.randrange(low, high)

gen = random_gen(1, 100)
items = list(itertools.islice(gen, 10))  # Take first 10 random elements

After the question update it is now clear that you need n distinct (unique) numbers.

import itertools
import random

def random_gen(low, high):
    while True:
        yield random.randrange(low, high)

gen = random_gen(1, 100)

items = set()

# Try to add elem to set until set length is less than 10
for x in itertools.takewhile(lambda x: len(items) < 10, gen):
    items.add(x)

Use the XmlInclude or SoapInclude attribute to specify types that are not known statically

I agree with bizl

[XmlInclude(typeof(ParentOfTheItem))]
[Serializable]
public abstract class WarningsType{ }

also if you need to apply this included class to an object item you can do like that

[System.Xml.Serialization.XmlElementAttribute("Warnings", typeof(WarningsType))]
public object[] Items
{
    get
    {
        return this.itemsField;
    }
    set
    {
        this.itemsField = value;
    }
}

Truncate to three decimals in Python

Maybe python changed since this question, all of the below seem to work well

Python2.7

int(1324343032.324325235 * 1000) / 1000.0
float(int(1324343032.324325235 * 1000)) / 1000
round(int(1324343032.324325235 * 1000) / 1000.0,3)
# result for all of the above is 1324343032.324

Getting DOM elements by classname

I think the accepted way is better, but I guess this might work as well

function getElementByClass(&$parentNode, $tagName, $className, $offset = 0) {
    $response = false;

    $childNodeList = $parentNode->getElementsByTagName($tagName);
    $tagCount = 0;
    for ($i = 0; $i < $childNodeList->length; $i++) {
        $temp = $childNodeList->item($i);
        if (stripos($temp->getAttribute('class'), $className) !== false) {
            if ($tagCount == $offset) {
                $response = $temp;
                break;
            }

            $tagCount++;
        }

    }

    return $response;
}

Scala: join an iterable of strings

How about mkString ?

theStrings.mkString(",")

A variant exists in which you can specify a prefix and suffix too.

See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.

How to scale images to screen size in Pygame

If you scale 1600x900 to 1280x720 you have

scale_x = 1280.0/1600
scale_y = 720.0/900

Then you can use it to find button size, and button position

button_width  = 300 * scale_x
button_height = 300 * scale_y

button_x = 1440 * scale_x
button_y = 860  * scale_y

If you scale 1280x720 to 1600x900 you have

scale_x = 1600.0/1280
scale_y = 900.0/720

and rest is the same.


I add .0 to value to make float - otherwise scale_x, scale_y will be rounded to integer - in this example to 0 (zero) (Python 2.x)

How to access the php.ini from my CPanel?

Search for "php version" at the bottom of the cpanel

Select PHP Version -> Switch to Php Options -> Change the Value -> save.

Android TextView padding between lines

This supplemental answer shows the effect of changing the line spacing.

enter image description here

You can set the multiplier and/or extra spacing with

textView.setLineSpacing(float add, float mult)

Or you can get the values with

int lineHeight = textView.getLineHeight();
float add = tvSampleText.getLineSpacingExtra();          // API 16+
float mult = tvSampleText.getLineSpacingMultiplier();    // API 16+

where the formula is

lineHeight = fontMetricsLineHeight * mult + add

The default multiplier is 1 and the default extra spacing is 0.

How to grep with a list of words

You need to use the option -f:

$ grep -f A B

The option -F does a fixed string search where as -f is for specifying a file of patterns. You may want both if the file only contains fixed strings and not regexps.

$ grep -Ff A B

You may also want the -w option for matching whole words only:

$ grep -wFf A B

Read man grep for a description of all the possible arguments and what they do.

Symfony2 : How to get form validation errors after binding the request to the form

I came up with this solution. It works solid with the latest Symfony 2.4.

I will try to give some explanations.

Using separate validator

I think it's a bad idea to use separate validation to validate entities and return constraint violation messages, like suggested by other writers.

  1. You will need to manually validate all the entities, specify validation groups, etc, etc. With complex hierarchical forms it's not practical at all and will get out of hands quickly.

  2. This way you will be validating form twice: once with form and once with separate validator. This is a bad idea from the performance perspective.

I suggest to recursively iterate form type with it's children to collect error messages.

Using some suggested methods with exclusive IF statement

Some answers suggested by another authors contain mutually exclusive IF statements like this: if ($form->count() > 0) or if ($form->hasChildren()).

As far as I can see, every form can have errors as well as children. I'm not expert with Symfony Forms component, but in practice you will not get some errors of the form itself, like CSRF protection error or extra fields error. I suggest to remove this separation.

Using denormalized result structure

Some authors suggest to put all errors inside of a plain array. So all the error messages of the form itself and of it's children will be added to the same array with different indexing strategies: number-based for type's own errors and name-based for children errors. I suggest to use normalized data structure of the form:

errors:
    - "Self error"
    - "Another self error"

children
    - "some_child":
        errors:
            - "Children error"
            - "Another children error"

        children
            - "deeper_child":
                errors:
                    - "Children error"
                    - "Another children error"

    - "another_child":
        errors:
            - "Children error"
            - "Another children error"

That way result can be easily iterated later.

My solution

So here's my solution to this problem:

use Symfony\Component\Form\Form;

/**
 * @param Form $form
 * @return array
 */
protected function getFormErrors(Form $form)
{
    $result = [];

    // No need for further processing if form is valid.
    if ($form->isValid()) {
        return $result;
    }

    // Looking for own errors.
    $errors = $form->getErrors();
    if (count($errors)) {
        $result['errors'] = [];
        foreach ($errors as $error) {
            $result['errors'][] = $error->getMessage();
        }
    }

    // Looking for invalid children and collecting errors recursively.
    if ($form->count()) {
        $childErrors = [];
        foreach ($form->all() as $child) {
            if (!$child->isValid()) {
                $childErrors[$child->getName()] = $this->getFormErrors($child);
            }
        }
        if (count($childErrors)) {
            $result['children'] = $childErrors;
        }
    }

    return $result;
}

I hope it'll help someone.

Javascript wait() function

You shouldn't edit it, you should completely scrap it.

Any attempt to make execution stop for a certain amount of time will lock up the browser and switch it to a Not Responding state. The only thing you can do is use setTimeout correctly.

Can dplyr join on multiple columns or composite key?

Updating to use tibble()

You can pass a named vector of length greater than 1 to the by argument of left_join():

library(dplyr)

d1 <- tibble(
  x = letters[1:3],
  y = LETTERS[1:3],
  a = rnorm(3)
  )

d2 <- tibble(
  x2 = letters[3:1],
  y2 = LETTERS[3:1],
  b = rnorm(3)
  )

left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))

Setting the number of map tasks and reduce tasks

The number of map tasks for a given job is driven by the number of input splits and not by the mapred.map.tasks parameter. For each input split a map task is spawned. So, over the lifetime of a mapreduce job the number of map tasks is equal to the number of input splits. mapred.map.tasks is just a hint to the InputFormat for the number of maps.

In your example Hadoop has determined there are 24 input splits and will spawn 24 map tasks in total. But, you can control how many map tasks can be executed in parallel by each of the task tracker.

Also, removing a space after -D might solve the problem for reduce.

For more information on the number of map and reduce tasks, please look at the below url

https://cwiki.apache.org/confluence/display/HADOOP2/HowManyMapsAndReduces

System.IO.FileNotFoundException: Could not load file or assembly 'X' or one of its dependencies when deploying the application

... Could not load file or assembly 'X' or one of its dependencies ...

Most likely it fails to load another dependency.

you could try to check the dependencies with a dependency walker.

I.e: https://www.dependencywalker.com/

Also check your build configuration (x86 / 64)

Edit: I also had this problem once when I was copying dlls in zip from a "untrusted" network share. The file was locked by Windows and the FileNotFoundException was raised.

See here: Detected DLLs that are from the internet and "blocked" by CASPOL

How to disable Paste (Ctrl+V) with jQuery?

Edit: It's almost 6 years later, looking at this now I wouldn't recommend this solution. The accepted answer is definitely much better. Go with that!


This seems to work.

You can listen to keyboard events with jQuery and prevent the event from completing if its the key combo you are looking for. Note, check 118 and 86 (V and v)

Working example here: http://jsfiddle.net/dannylane/9pRsx/4/

$(document).ready(function(){
    $(document).keydown(function(event) {
        if (event.ctrlKey==true && (event.which == '118' || event.which == '86')) {
            alert('thou. shalt. not. PASTE!');
            event.preventDefault();
         }
    });
});

Update: keypress doesn't fire in IE, use keydown instead.

Set icon for Android application

If you have an SVG icon, you can use this script to generate your android icon set.

How to read Data from Excel sheet in selenium webdriver

package com.test.utitlity;

import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class readExcel extends globalVariables {

    /**
     * @param args
     * @throws IOException 
     */
    public static void readExcel(int rowcounter) throws IOException{

        XSSFWorkbook srcBook = new XSSFWorkbook("./prop.xlsx");     
        XSSFSheet sourceSheet = srcBook.getSheetAt(0);
        int rownum=rowcounter;
        XSSFRow sourceRow = sourceSheet.getRow(rownum);
        XSSFCell cell1=sourceRow.getCell(0);
        XSSFCell cell2=sourceRow.getCell(1);
        XSSFCell cell3=sourceRow.getCell(2);
        System.out.println(cell1);
        System.out.println(cell2);
        System.out.println(cell3);



}

}

Rotating videos with FFmpeg

For me it works like this

Rotate clockwise

 ffmpeg -i "path_source_video.mp4" -filter:v "transpose=1" "path_output_video.mp4"

Rotate counterclockwise

 ffmpeg -i "path_source_video.mp4" -filter:v "transpose=0,transpose=1,transpose=0" -acodec copy "path_output_video.mp4"

the package I use zeranoe

How to show android checkbox at right side?

Just copy this:

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Your text:"/>
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            />
    </LinearLayout>

Happy codding! :)

ValueError: object too deep for desired array while using convolution

np.convolve needs a flattened array as one of it's inputs, you can use numpy.ndarray.flatten() which is quite fast, find it here.

Indentation shortcuts in Visual Studio

Just hit Tab to push it over or on the menu bar Edit --> Advanced --> Format Selection and that will auto indent, the keyboard shortcut is also shown in the menu.

Fatal error: [] operator not supported for strings

I agree with Jeremy Young's comment on Phils answer:

I have found that this can be a problem associated with migrating from php 5 to php 7. php 5 was more tolerant of amibiguity in whether a variable was an array or not than php 7 is. In most cases the solution is to declare the array explicitly, as explained in this answer.

I was just trouble shooting a Wordpress plugin after the migration of php5 to php7. Since the plugin code was relying on user input, and it was intrinsically used in the code either as string, or as array, I added the following code in to prevent a fatal error:

if(is_array($variable_either_string_or_array)){
    // if it's an array, declaration is allowed:
    $variable_either_string_or_array[]=$additionalInfoData[$i];
}else{
    // if it's not an array, declaration it as follows:
    $variable_either_string_or_array=$additionalInfoData[$i];
}

This was the only modification I needed to add to make the plugin php7-proof. Obviously not "best practices", I'd rather read and understand the full code.. but a quick fix was needed.

How to disable text selection using jQuery?

I found this answer ( Prevent Highlight of Text Table ) most helpful, and perhaps it can be combined with another way of providing IE compatibility.

#yourTable
{
  -moz-user-select: none;
  -khtml-user-select: none;
  -webkit-user-select: none;
  user-select: none;
}

jQuery .get error response function?

If you want a generic error you can setup all $.ajax() (which $.get() uses underneath) requests jQuery makes to display an error using $.ajaxSetup(), for example:

$.ajaxSetup({
  error: function(xhr, status, error) {
    alert("An AJAX error occured: " + status + "\nError: " + error);
  }
});

Just run this once before making any AJAX calls (no changes to your current code, just stick this before somewhere). This sets the error option to default to the handler/function above, if you made a full $.ajax() call and specified the error handler then what you had would override the above.

Bootstrap trying to load map file. How to disable it? Do I need to do it?

For me, created an empty bootstrap.css.map together with bootstrap.css and the error stopped.

How Do I Convert an Integer to a String in Excel VBA?

Try the CStr() function

Dim myVal as String;
Dim myNum as Integer;

myVal = "My number is:"
myVal = myVal & CStr(myNum);

"starting Tomcat server 7 at localhost has encountered a prob"

Go to web.xml add <element> before <web-app> and close </element> after </web-app>

should be somethings like this

<?xml version="1.0" encoding="UTF-8"?>

<element>

<web-app>

....
</web-app>

</element>

How to line-break from css, without using <br />?

Use overflow-wrap: break-word; like :

.yourelement{
overflow-wrap: break-word;
}

C#/Linq: Apply a mapping function to each element in an IEnumerable?

You're looking for Select which can be used to transform\project the input sequence:

IEnumerable<string> strings = integers.Select(i => i.ToString());

What is the difference between cssSelector & Xpath and which is better with respect to performance for cross browser testing?

The debate between cssSelector vs XPath would remain as one of the most subjective debate in the Selenium Community. What we already know so far can be summarized as:

  • People in favor of cssSelector say that it is more readable and faster (especially when running against Internet Explorer).
  • While those in favor of XPath tout it's ability to transverse the page (while cssSelector cannot).
  • Traversing the DOM in older browsers like IE8 does not work with cssSelector but is fine with XPath.
  • XPath can walk up the DOM (e.g. from child to parent), whereas cssSelector can only traverse down the DOM (e.g. from parent to child)
  • However not being able to traverse the DOM with cssSelector in older browsers isn't necessarily a bad thing as it is more of an indicator that your page has poor design and could benefit from some helpful markup.
  • Ben Burton mentions you should use cssSelector because that's how applications are built. This makes the tests easier to write, talk about, and have others help maintain.
  • Adam Goucher says to adopt a more hybrid approach -- focusing first on IDs, then cssSelector, and leveraging XPath only when you need it (e.g. walking up the DOM) and that XPath will always be more powerful for advanced locators.

Dave Haeffner carried out a test on a page with two HTML data tables, one table is written without helpful attributes (ID and Class), and the other with them. I have analyzed the test procedure and the outcome of this experiment in details in the discussion Why should I ever use cssSelector selectors as opposed to XPath for automated testing?. While this experiment demonstrated that each Locator Strategy is reasonably equivalent across browsers, it didn't adequately paint the whole picture for us. Dave Haeffner in the other discussion Css Vs. X Path, Under a Microscope mentioned, in an an end-to-end test there were a lot of other variables at play Sauce startup, Browser start up, and latency to and from the application under test. The unfortunate takeaway from that experiment could be that one driver may be faster than the other (e.g. IE vs Firefox), when in fact, that's wasn't the case at all. To get a real taste of what the performance difference is between cssSelector and XPath, we needed to dig deeper. We did that by running everything from a local machine while using a performance benchmarking utility. We also focused on a specific Selenium action rather than the entire test run, and run things numerous times. I have analyzed the specific test procedure and the outcome of this experiment in details in the discussion cssSelector vs XPath for selenium. But the tests were still missing one aspect i.e. more browser coverage (e.g., Internet Explorer 9 and 10) and testing against a larger and deeper page.

Dave Haeffner in another discussion Css Vs. X Path, Under a Microscope (Part 2) mentions, in order to make sure the required benchmarks are covered in the best possible way we need to consider an example that demonstrates a large and deep page.


Test SetUp

To demonstrate this detailed example, a Windows XP virtual machine was setup and Ruby (1.9.3) was installed. All the available browsers and their equivalent browser drivers for Selenium was also installed. For benchmarking, Ruby's standard lib benchmark was used.


Test Code

require_relative 'base'
require 'benchmark'

class LargeDOM < Base

  LOCATORS = {
    nested_sibling_traversal: {
      css: "div#siblings > div:nth-of-type(1) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3)",
      xpath: "//div[@id='siblings']/div[1]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]"
    },
    nested_sibling_traversal_by_class: {
      css: "div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1",
      xpath: "//div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]"
    },
    table_header_id_and_class: {
      css: "table#large-table thead .column-50",
      xpath: "//table[@id='large-table']//thead//*[@class='column-50']"
    },
    table_header_id_class_and_direct_desc: {
      css: "table#large-table > thead .column-50",
      xpath: "//table[@id='large-table']/thead//*[@class='column-50']"
    },
    table_header_traversing: {
      css: "table#large-table thead tr th:nth-of-type(50)",
      xpath: "//table[@id='large-table']//thead//tr//th[50]"
    },
    table_header_traversing_and_direct_desc: {
      css: "table#large-table > thead > tr > th:nth-of-type(50)",
      xpath: "//table[@id='large-table']/thead/tr/th[50]"
    },
    table_cell_id_and_class: {
      css: "table#large-table tbody .column-50",
      xpath: "//table[@id='large-table']//tbody//*[@class='column-50']"
    },
    table_cell_id_class_and_direct_desc: {
      css: "table#large-table > tbody .column-50",
      xpath: "//table[@id='large-table']/tbody//*[@class='column-50']"
    },
    table_cell_traversing: {
      css: "table#large-table tbody tr td:nth-of-type(50)",
      xpath: "//table[@id='large-table']//tbody//tr//td[50]"
    },
    table_cell_traversing_and_direct_desc: {
      css: "table#large-table > tbody > tr > td:nth-of-type(50)",
      xpath: "//table[@id='large-table']/tbody/tr/td[50]"
    }
  }

  attr_reader :driver

  def initialize(driver)
    @driver = driver
    visit '/large'
    is_displayed?(id: 'siblings')
    super
  end

  # The benchmarking approach was borrowed from
  # http://rubylearning.com/blog/2013/06/19/how-do-i-benchmark-ruby-code/
  def benchmark
    Benchmark.bmbm(27) do |bm|
      LOCATORS.each do |example, data|
    data.each do |strategy, locator|
      bm.report(example.to_s + " using " + strategy.to_s) do
        begin
          ENV['iterations'].to_i.times do |count|
         find(strategy => locator)
          end
        rescue Selenium::WebDriver::Error::NoSuchElementError => error
          puts "( 0.0 )"
        end
      end
    end
      end
    end
  end

end

Results

NOTE: The output is in seconds, and the results are for the total run time of 100 executions.

In Table Form:

css_xpath_under_microscopev2

In Chart Form:

  • Chrome:

chart-chrome

  • Firefox:

chart-firefox

  • Internet Explorer 8:

chart-ie8

  • Internet Explorer 9:

chart-ie9

  • Internet Explorer 10:

chart-ie10

  • Opera:

chart-opera


Analyzing the Results

  • Chrome and Firefox are clearly tuned for faster cssSelector performance.
  • Internet Explorer 8 is a grab bag of cssSelector that won't work, an out of control XPath traversal that takes ~65 seconds, and a 38 second table traversal with no cssSelector result to compare it against.
  • In IE 9 and 10, XPath is faster overall. In Safari, it's a toss up, except for a couple of slower traversal runs with XPath. And across almost all browsers, the nested sibling traversal and table cell traversal done with XPath are an expensive operation.
  • These shouldn't be that surprising since the locators are brittle and inefficient and we need to avoid them.

Summary

  • Overall there are two circumstances where XPath is markedly slower than cssSelector. But they are easily avoidable.
  • The performance difference is slightly in favor of for non-IE browsers and slightly in favor of for IE browsers.

Trivia

You can perform the bench-marking on your own, using this library where Dave Haeffner wrapped up all the code.

Python : Trying to POST form using requests

Send a POST request with content type = 'form-data':

import requests
files = {
    'username': (None, 'myusername'),
    'password': (None, 'mypassword'),
}
response = requests.post('https://example.com/abc', files=files)

Pandas: Return Hour from Datetime Column Directly

Now we can use:

sales['time_hour'] = sales['timestamp'].apply(lambda x: x.hour)

How do I use popover from Twitter Bootstrap to display an image?

This is what I used.

$('#foo').popover({
    placement : 'bottom',
    title : 'Title',
    content : '<div id="popOverBox"><img src="http://i.telegraph.co.uk/multimedia/archive/01515/alGore_1515233c.jpg" /></div>'
});

and for the HTML

<b id="foo" rel="popover">text goes here</b>

how to make a whole row in a table clickable as a link?

Author's note I:

Please look at other answers below, especially ones that do not use jquery.

Author's note II:

Preserved for posterity but surely the wrong approach in 2020. (Was non idiomatic even back in 2017)

Original Answer

You are using Bootstrap which means you are using jQuery :^), so one way to do it is:

<tbody>
    <tr class='clickable-row' data-href='url://'>
        <td>Blah Blah</td> <td>1234567</td> <td>£158,000</td>
    </tr>
</tbody>


jQuery(document).ready(function($) {
    $(".clickable-row").click(function() {
        window.location = $(this).data("href");
    });
});

Of course you don't have to use href or switch locations, you can do whatever you like in the click handler function. Read up on jQuery and how to write handlers;

Advantage of using a class over id is that you can apply the solution to multiple rows:

<tbody>
    <tr class='clickable-row' data-href='url://link-for-first-row/'>
        <td>Blah Blah</td> <td>1234567</td> <td>£158,000</td>
    </tr>
    <tr class='clickable-row' data-href='url://some-other-link/'>
        <td>More money</td> <td>1234567</td> <td>£800,000</td>
    </tr>
</tbody>

and your code base doesn't change. The same handler would take care of all the rows.

Another option

You can use Bootstrap jQuery callbacks like this (in a document.ready callback):

$("#container").on('click-row.bs.table', function (e, row, $element) {
    window.location = $element.data('href');
});

This has the advantage of not being reset upon table sorting (which happens with the other option).


Note

Since this was posted window.document.location is obsolete (or deprecated at the very least) use window.location instead.

Using floats with sprintf() in embedded C

Yes of course, there is nothing special with floats. You can use the format strings as you use in printf() for floats and anyother datatypes.

EDIT I tried this sample code:

float x = 0.61;
char buf[10];
sprintf(buf, "Test=%.2f", x);
printf(buf);

Output was : Test=0.61

Getting "cannot find Symbol" in Java project in Intellij

recompiling the main Application.java class did it for me, right click on class > Recompile

keytool error Keystore was tampered with, or password was incorrect

If you are working on signing your Flutter App by following this guide Build and release an Android app and run in to this error. I hope this answer helps you.

In my case I changed the path to store my key.jks. This happened to me because I there was an existing file in that path.

keytool -genkey -v -keystore ~/key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias key

This command stores the key.jks file in your home directory. To store it elsewhere, change the argument you pass to the -keystore parameter.

In my case,

keytool -genkey -v -keystore /Users/Y/Desktop/X/key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias keyYour

i.e Y - Username and X - folder name

Then you will be prompted to Enter keystore password: and Re-enter new password:. Here you can use whatever password you want.

However, keep the keystore file private; don’t check it into public source control!

Is there 'byte' data type in C++?

if you are using windows, in WinDef.h you have:

typedef unsigned char BYTE;

How do I compare two strings in python?

If you just need to check if the two strings are exactly same,

text1 = 'apple'

text2 = 'apple'

text1 == text2

The result will be

True

If you need the matching percentage,

import difflib

text1 = 'Since 1958.'

text2 = 'Since 1958'

output = str(int(difflib.SequenceMatcher(None, text1, text2).ratio()*100))

Matching percentage output will be,

'95'

Python urllib2 Basic Auth Problem

I would suggest that the current solution is to use my package urllib2_prior_auth which solves this pretty nicely (I work on inclusion to the standard lib.

Convert string with commas to array

How to Convert Comma Separated String into an Array in JavaScript?

var string = 'hello, world, test, test2, rummy, words';
var arr = string.split(', '); // split string on comma space
console.log( arr );
 
//Output
["hello", "world", "test", "test2", "rummy", "words"]

For More Examples of convert string to array in javascript using the below ways:

  1. Split() – No Separator:

  2. Split() – Empty String Separator:

  3. Split() – Separator at Beginning/End:

  4. Regular Expression Separator:

  5. Capturing Parentheses:

  6. Split() with Limit Argument

    check out this link ==> https://www.tutsmake.com/javascript-convert-string-to-array-javascript/

svn over HTTP proxy

If you're using the standard SVN installation the svn:// connection will work on tcpip port 3690 and so it's basically impossible to connect unless you change your network configuration (you said only Http traffic is allowed) or you install the http module and Apache on the server hosting your SVN server.

How can I stop .gitignore from appearing in the list of untracked files?

Of course the .gitignore file is showing up on the status, because it's untracked, and git sees it as a tasty new file to eat!

Since .gitignore is an untracked file however, it is a candidate to be ignored by git when you put it in .gitignore!

So, the answer is simple: just add the line:

.gitignore # Ignore the hand that feeds!

to your .gitignore file!

And, contrary to August's response, I should say that it's not that the .gitignore file should be in your repository. It just happens that it can be, which is often convenient. And it's probably true that this is the reason .gitignore was created as an alternative to .git/info/exclude, which doesn't have the option to be tracked by the repository. At any rate, how you use your .gitignore file is totally up to you.

For reference, check out the gitignore(5) manpage on kernel.org.

How to unset (remove) a collection element after fetching it?

You would want to use ->forget()

$collection->forget($key);

Link to the forget method documentation

display: flex not working on Internet Explorer

Internet Explorer doesn't fully support Flexbox due to:

Partial support is due to large amount of bugs present (see known issues).

enter image description here Screenshot and infos taken from caniuse.com

Notes

Internet Explorer before 10 doesn't support Flexbox, while IE 11 only supports the 2012 syntax.

Known issues

  • IE 11 requires a unit to be added to the third argument, the flex-basis property see MSFT documentation.
  • In IE10 and IE11, containers with display: flex and flex-direction: column will not properly calculate their flexed childrens' sizes if the container has min-height but no explicit height property. See bug.
  • In IE10 the default value for flex is 0 0 auto rather than 0 1 auto as defined in the latest spec.
  • IE 11 does not vertically align items correctly when min-height is used. See bug.

Workarounds

Flexbugs is a community-curated list of Flexbox issues and cross-browser workarounds for them. Here's a list of all the bugs with a workaround available and the browsers that affect.

  1. Minimum content sizing of flex items not honored
  2. Column flex items set to align-items: center overflow their container
  3. min-height on a flex container won't apply to its flex items
  4. flex shorthand declarations with unitless flex-basis values are ignored
  5. Column flex items don't always preserve intrinsic aspect ratios
  6. The default flex value has changed
  7. flex-basis doesn't account for box-sizing: border-box
  8. flex-basis doesn't support calc()
  9. Some HTML elements can't be flex containers
  10. align-items: baseline doesn't work with nested flex containers
  11. Min and max size declarations are ignored when wrapping flex items
  12. Inline elements are not treated as flex-items
  13. Importance is ignored on flex-basis when using flex shorthand
  14. Shrink-to-fit containers with flex-flow: column wrap do not contain their items
  15. Column flex items ignore margin: auto on the cross axis
  16. flex-basis cannot be animated
  17. Flex items are not correctly justified when max-width is used

Change UITableView height dynamically

Use simple and easy code

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let myCell = tableView.dequeueReusableCellWithIdentifier("mannaCustumCell") as! CustomCell
        let heightForCell = myCell.bounds.size.height;

        return heightForCell;
    }

Can not get a simple bootstrap modal to work

For me the bootstrap modal was showing and disappearing when I clicked the button tag (in the markup the modal is shown and hidden using data attributes alone). In my gulpfile.js I added the bootstrap.js (which had the modal logic) and the modal.js file. So I think after the browser parses and executes both the files, two click event handlers are attached to the particular dom element (one for each of the files), so one shows the modal the other hides the modal. Hope this helps someone.

How do I redirect users after submit button click?

Using jquery you can do it this way

$("#order").click(function(e){
    e.preventDefault();
    window.location="login.php";
});

Also in HMTL you can do it this way

<form name="frm" action="login.php" method="POST">
...
</form>

Hope this helps

How can I style even and odd elements?

The :nth-child(n) selector matches every element that is the nth child, regardless of type, of its parent. Odd and even are keywords that can be used to match child elements whose index is odd or even (the index of the first child is 1).

this is what you want:

<html>
    <head>
        <style>
            li { color: blue }<br>
            li:nth-child(even) { color:red }
            li:nth-child(odd) { color:green}
        </style>
    </head>
    <body>
        <ul>
            <li>ho</li>
            <li>ho</li>
            <li>ho</li>
            <li>ho</li>
            <li>ho</li>
        </ul>
    </body>
</html>

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

You have a few typos in your select. It should be: input:not([disabled]):not([type="submit"]):focus

See this jsFiddle for a proof of concept. On a sidenote, if I removed the "background-color" property, then the box shadow no longer works. Not sure why.

How to cast ArrayList<> from List<>

Just try this :

ArrayList<SomeClass> arrayList;

 public SomeConstructor(List<SomeClass> listData) {
        arrayList.addAll(listData);
}

how to automatically scroll down a html page?

You can use .scrollIntoView() for this. It will bring a specific element into the viewport.

Example:

document.getElementById( 'bottom' ).scrollIntoView();

Demo: http://jsfiddle.net/ThinkingStiff/DG8yR/

Script:

function top() {
    document.getElementById( 'top' ).scrollIntoView();    
};

function bottom() {
    document.getElementById( 'bottom' ).scrollIntoView();
    window.setTimeout( function () { top(); }, 2000 );
};

bottom();

HTML:

<div id="top">top</div>
<div id="bottom">bottom</div>

CSS:

#top {
    border: 1px solid black;
    height: 3000px;
}

#bottom {
    border: 1px solid red;
}

How to debug JavaScript / jQuery event bindings with Firebug or similar tools?

With version 2.0 Firebug introduced an Events panel, which lists all events for the element currently selected within the HTML panel.

*Events* side panel in Firebug

It can also display event listeners wrapped into jQuery event bindings in case the option Show Wrapped Listeners is checked, which you can reach via the Events panel's options menu.

With that panel the workflow to debug an event handler is as follows:

  1. Select the element with the event listener you want to debug
  2. Inside the Events side panel right-click the function under the related event and choose Set Breakpoint
  3. Trigger the event

=> The script execution will stop at the first line of the event handler function and you can step debug it.

How to do a FULL OUTER JOIN in MySQL?

You can just convert a full outer join, e.g.

SELECT fields
FROM firsttable
FULL OUTER JOIN secondtable ON joincondition

into:

SELECT fields
FROM firsttable
LEFT JOIN secondtable ON joincondition
UNION ALL
SELECT fields (replacing any fields from firsttable with NULL)
FROM secondtable
WHERE NOT EXISTS (SELECT 1 FROM firsttable WHERE joincondition)

Or if you have at least one column, say foo, in firsttable that is NOT NULL, you can do:

SELECT fields
FROM firsttable
LEFT JOIN secondtable ON joincondition
UNION ALL
SELECT fields
FROM firsttable
RIGHT JOIN secondtable ON joincondition
WHERE firsttable.foo IS NULL

How to persist a property of type List<String> in JPA?

Thiago answer is correct, adding sample more specific to question, @ElementCollection will create new table in your database, but without mapping two tables, It means that the collection is not a collection of entities, but a collection of simple types (Strings, etc.) or a collection of embeddable elements (class annotated with @Embeddable).

Here is the sample to persist list of String

@ElementCollection
private Collection<String> options = new ArrayList<String>();

Here is the sample to persist list of Custom object

@Embedded
@ElementCollection
private Collection<Car> carList = new ArrayList<Car>();

For this case we need to make class Embeddable

@Embeddable
public class Car {
}

How to access the contents of a vector from a pointer to the vector in C++?

vector <int> numbers {10,20,30,40};
vector <int> *ptr {nullptr};

ptr = &numbers;

for(auto num: *ptr){
 cout << num << endl;
}


cout << (*ptr).at(2) << endl; // 20

cout << "-------" << endl;

cout << ptr -> at(2) << endl; // 20

How do I configure the proxy settings so that Eclipse can download new plugins?

For me, I go to \eclipse\configuration.settings\org.eclipse.core.net.prefs set the property systemProxiesEnabled to true manually and restart eclipse.

How can I set the current working directory to the directory of the script in Bash?

The accepted answer works well for scripts that have not been symlinked elsewhere, such as into $PATH.

#!/bin/bash
cd "$(dirname "$0")"

However if the script is run via a symlink,

ln -sv ~/project/script.sh ~/bin/; 
~/bin/script.sh

This will cd into the ~/bin/ directory and not the ~/project/ directory, which will probably break your script if the purpose of the cd is to include dependencies relative to ~/project/

The symlink safe answer is below:

#!/bin/bash
cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"

readlink -f is required to resolve the absolute path of the potentially symlinked file.

The quotes are required to support filepaths that could potentially contain whitespace (bad practice, but its not safe to assume this won't be the case)

Error: EPERM: operation not permitted, unlink 'D:\Sources\**\node_modules\fsevents\node_modules\abbrev\package.json'

I simply completely shutdown , NOT hibernated, my machine and restarted it. Ran the CMD as admin and used npm install command. It worked.

What does "@" mean in Windows batch scripts

Another useful time to include @ is when you use FOR in the command line. For example:

FOR %F IN (*.*) DO ECHO %F

Previous line show for every file: the command prompt, the ECHO command, and the result of ECHO command. This way:

FOR %F IN (*.*) DO @ECHO %F

Just the result of ECHO command is shown.

Difference between a virtual function and a pure virtual function

You can actually provide implementations of pure virtual functions in C++. The only difference is all pure virtual functions must be implemented by derived classes before the class can be instantiated.

Filtering Table rows using Jquery

Have a look at this jsfiddle.

The idea is to filter rows with function which will loop through words.

jo.filter(function (i, v) {
    var $t = $(this);
    for (var d = 0; d < data.length; ++d) {
        if ($t.is(":contains('" + data[d] + "')")) {
            return true;
        }
    }
    return false;
})
//show the rows that match.
.show();

EDIT: Note that case insensitive filtering cannot be achieved using :contains() selector but luckily there's text() function so filter string should be uppercased and condition changed to if ($t.text().toUpperCase().indexOf(data[d]) > -1). Look at this jsfiddle.

How to do a deep comparison between 2 objects with lodash?

This is my solution to the problem

const _ = require('lodash');

var objects = [{ 'x': 1, 'y': 2, 'z':3, a:{b:1, c:2, d:{n:0}}, p:[1, 2, 3]  }, { 'x': 2, 'y': 1, z:3, a:{b:2, c:2,d:{n:1}}, p:[1,3], m:3  }];

const diffFn=(a,b, path='')=>_.reduce(a, function(result, value, key) {

    if(_.isObjectLike(value)){
      if(_.isEqual(value, b[key])){
        return result;
      }else{

return result.concat(diffFn(value, b[key], path?(`${path}.${key}`):key))
      }
    }else{
return _.isEqual(value, b[key]) ?
        result : result.concat(path?(`${path}.${key}`):key);
    }
    
}, []);

const diffKeys1=diffFn(objects[0], objects[1])
const diffKeys2=diffFn(objects[1], objects[0])
const diffKeys=_.union(diffKeys1, diffKeys2)
const res={};

_.forEach(diffKeys, (key)=>_.assign(res, {[key]:{ old: _.get(objects[0], key), new:_.get(objects[1], key)} }))

res
/*
Returns
{
  x: { old: 1, new: 2 },
  y: { old: 2, new: 1 },
  'a.b': { old: 1, new: 2 },
  'a.d.n': { old: 0, new: 1 },
  'p.1': { old: 2, new: 3 },
  'p.2': { old: 3, new: undefined },
  m: { old: undefined, new: 3 }
}
*/

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

Can't find the libpq-fe.h header

i had success on CentOS 7.0.1406 running the following commands:

~ % psql --version # => psql (PostgreSQL) 9.4.1
yum install libpqxx-devel
gem install pg -- --with-pg-config=/usr/pgsql-9.4/bin/pg_config

Alternatively, you can configure bundler to always install pg with these options (helpful for running bundler in deploy environments),

  • bundle config build.pg --with-pg-config=/usr/pgsql-9.4/bin/pg_config

Why can't I find SQL Server Management Studio after installation?

Generally if the installation went smoothly, it will create the desktop icons/folders. Maybe check the installation summary log to see if there's any underlying errors.

It should be located C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log(date stamp)\

How does += (plus equal) work?

You have to know that:

  • Assignment operators syntax is: variable = expression;

    For this reason 1 += 2 -> 1 = 1 + 2 is not a valid syntax as the left operand isn't a variable. The error in this case is ReferenceError: invalid assignment left-hand side.

  • x += y is the short form for x = x + y, where x is the variable and x + y the expression.

    The result of the sum is 15.

      sum = 0;
      sum = sum + 1; // 1
      sum = sum + 2; // 3
      sum = sum + 3; // 6
      sum = sum + 4; // 10
      sum = sum + 5; // 15

Other assignment operator shortcuts works the same way (relatively to the standard operations they refer to). .

Error importing Seaborn module in Python

Problem may not be associated with Seaborn but Utils package which may not be installed

sudo pip uninstall requests

and reinstalling, it no longer would work at all. Luckily, dnf install python-requests fixed the whole thing...

Also check for utils package is installed or not

You can install package using

sudo pip install utils

Check this link Python ImportError: cannot import name utils

Symbol for any number of any characters in regex?

Yes, there is one, it's the asterisk: *

a* // looks for 0 or more instances of "a"

This should be covered in any Java regex tutorial or documentation that you look up.

How to blur background images in Android

You can have a view with Background color as black and set alpha for the view as 0.7 or whatever as per your requirement.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/onboardingimg1">
    <View
        android:id="@+id/opacityFilter"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/black"
        android:layout_alignParentBottom="true"
        android:alpha="0.7">
    </View>


</RelativeLayout>

How to remove all white spaces in java

package com.infy.test;

import java.util.Scanner ;
import java.lang.String ;

public class Test1 {


    public static void main (String[]args)
    {

        String a  =null;


        Scanner scan = new Scanner(System.in);
        System.out.println("*********White Space Remover Program************\n");
        System.out.println("Enter your string\n");
    a = scan.nextLine();
        System.out.println("Input String is  :\n"+a);


        String b= a.replaceAll("\\s+","");

        System.out.println("\nOutput String is  :\n"+b);


    }
}

What is the difference between a database and a data warehouse?

A Data Warehousing (DW) is process for collecting and managing data from varied sources to provide meaningful business insights. A Data warehouse is typically used to connect and analyze business data from heterogeneous sources. The data warehouse is the core of the BI system which is built for data analysis and reporting.

How can you search Google Programmatically Java API

Indeed there is an API to search google programmatically. The API is called google custom search. For using this API, you will need an Google Developer API key and a cx key. A simple procedure for accessing google search from java program is explained in my blog.

Now dead, here is the Wayback Machine link.

Sort a two dimensional array based on one column

Check out the ColumnComparator. It is basically the same solution as proposed by Costi, but it also supports sorting on columns in a List and has a few more sort properties.

Get device information (such as product, model) from adb command

Why don't you try to grep the return of your command ? Something like :

adb devices -l | grep 123abc12

It should return only the line you want to.

' << ' operator in verilog

<< is the left-shift operator, as it is in many other languages.

Here RAM_DEPTH will be 1 left-shifted by 8 bits, which is equivalent to 2^8, or 256.

How do I use dataReceived event of the SerialPort Port Object in C#?

I think your issue is the line:**

sp.DataReceived += port_OnReceiveDatazz;

Shouldn't it be:

sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);

**Nevermind, the syntax is fine (didn't realize the shortcut at the time I originally answered this question).

I've also seen suggestions that you should turn the following options on for your serial port:

sp.DtrEnable = true;    // Data-terminal-ready
sp.RtsEnable = true;    // Request-to-send

You may also have to set the handshake to RequestToSend (via the handshake enumeration).


UPDATE:

Found a suggestion that says you should open your port first, then assign the event handler. Maybe it's a bug?

So instead of this:

sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);
sp.Open();

Do this:

sp.Open();
sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);

Let me know how that goes.

Linq with group by having count

Like this:

from c in db.Company
group c by c.Name into grp
where grp.Count() > 1
select grp.Key

Or, using the method syntax:

Company
    .GroupBy(c => c.Name)
    .Where(grp => grp.Count() > 1)
    .Select(grp => grp.Key);

Get list of passed arguments in Windows batch script (.bat)

The way to retrieve all the args to a script is here:

@ECHO off
ECHO The %~nx0 script args are...
for %%I IN (%*) DO ECHO %%I
pause

Use stored procedure to insert some data into a table

If you are trying to return back the ID within the scope, using the SCOPE_IDENTITY() would be a better approach. I would not advice to use @@IDENTITY, as this can return any ID.

CREATE PROC [dbo].[sp_Test] (
  @myID int output,
  @myFirstName nvarchar(50),
  @myLastName nvarchar(50),
  @myAddress nvarchar(50),
  @myPort int
) AS
BEGIN
    INSERT INTO Dvds (myFirstName, myLastName, myAddress, myPort)
    VALUES (@myFirstName, @myLastName, @myAddress, @myPort);

    SET @myID = SCOPE_IDENTITY();
END
GO

For..In loops in JavaScript - key value pairs

for...in will work for you.

for( var key in obj ) {
  var value = obj[key];
}

In modern JavaScript you can also do this:

for ( const [key,value] of Object.entries( obj ) ) {

}

How to get first record in each group using Linq

var result = input.GroupBy(x=>x.F1,(key,g)=>g.OrderBy(e=>e.F2).First());

How do I check if the user is pressing a key?

Try this:

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Main {

    public static void main(String[] argv) throws Exception {

    JTextField textField = new JTextField();

    textField.addKeyListener(new Keychecker());

    JFrame jframe = new JFrame();

    jframe.add(textField);

    jframe.setSize(400, 350);

    jframe.setVisible(true);

}

class Keychecker extends KeyAdapter {

    @Override
    public void keyPressed(KeyEvent event) {

        char ch = event.getKeyChar();

        System.out.println(event.getKeyChar());

    }

}

How can I convert byte size into a human-readable format in Java?

Create an interface:

public interface IUnits {
    public String format(long size, String pattern);
    public long getUnitSize();
}

Create the StorageUnits class:

import java.text.DecimalFormat;

public class StorageUnits {

    private static final long K = 1024;
    private static final long M = K * K;
    private static final long G = M * K;
    private static final long T = G * K;

    enum Unit implements IUnits {

        TERA_BYTE {
            @Override
            public String format(long size, String pattern) {
                return format(size, getUnitSize(), "TB", pattern);
            }
            @Override
            public long getUnitSize() {
                return T;
            }
            @Override
            public String toString() {
                return "Terabytes";
            }
        },
        GIGA_BYTE {
            @Override
            public String format(long size, String pattern) {
                return format(size, getUnitSize(), "GB", pattern);
            }
            @Override
            public long getUnitSize() {
                return G;
            }
            @Override
            public String toString() {
                return "Gigabytes";
            }
        },
        MEGA_BYTE {
            @Override
            public String format(long size, String pattern) {
                return format(size, getUnitSize(), "MB", pattern);
            }
            @Override
            public long getUnitSize() {
                return M;
            }
            @Override
            public String toString() {
                return "Megabytes";
            }
        },
        KILO_BYTE {
            @Override
            public String format(long size, String pattern) {
                return format(size, getUnitSize(), "kB", pattern);
            }
            @Override
            public long getUnitSize() {
                return K;
            }
            @Override
            public String toString() {
                return "Kilobytes";
            }

        };

        String format(long size, long base, String unit, String pattern) {
            return new DecimalFormat(pattern).format(
                           Long.valueOf(size).doubleValue() /
                           Long.valueOf(base).doubleValue()
            ) + unit;
        }
    }

    public static String format(long size, String pattern) {
        for(Unit unit : Unit.values()) {
            if(size >= unit.getUnitSize()) {
                return unit.format(size, pattern);
            }
        }
        return ("???(" + size + ")???");
    }

    public static String format(long size) {
        return format(size, "#,##0.#");
    }
}

Call it:

class Main {
    public static void main(String... args) {
        System.out.println(StorageUnits.format(21885));
        System.out.println(StorageUnits.format(2188121545L));
    }
}

Output:

21.4kB
2GB

Show percent % instead of counts in charts of categorical variables

Here is a workaround for faceted data. (The accepted answer by @Andrew does not work in this case.) The idea is to calculate the percentage value using dplyr and then to use geom_col to create the plot.

library(ggplot2)
library(scales)
library(magrittr)
library(dplyr)

binwidth <- 30

mtcars.stats <- mtcars %>%
  group_by(cyl) %>%
  mutate(bin = cut(hp, breaks=seq(0,400, binwidth), 
               labels= seq(0+binwidth,400, binwidth)-(binwidth/2)),
         n = n()) %>%
  group_by(cyl, bin) %>%
  summarise(p = n()/n[1]) %>%
  ungroup() %>%
  mutate(bin = as.numeric(as.character(bin)))

ggplot(mtcars.stats, aes(x = bin, y= p)) +  
  geom_col() + 
  scale_y_continuous(labels = percent) +
  facet_grid(cyl~.)

This is the plot:

enter image description here

MS Access: how to compact current database in VBA

If you want to compact/repair an external mdb file (not the one you are working in just now):

Application.compactRepair sourecFile, destinationFile

If you want to compact the database you are working with:

Application.SetOption "Auto compact", True

In this last case, your app will be compacted when closing the file.

My opinion: writting a few lines of code in an extra MDB "compacter" file that you can call when you want to compact/repair an mdb file is very usefull: in most situations the file that needs to be compacted cannot be opened normally anymore, so you need to call the method from outside the file.

Otherwise, the autocompact shall by default be set to true in each main module of an Access app.

In case of a disaster, create a new mdb file and import all objects from the buggy file. You will usually find a faulty object (form, module, etc) that you will not be able to import.

How to fix "The ConnectionString property has not been initialized"

The connection string is not in AppSettings.

What you're looking for is in:

System.Configuration.ConfigurationManager.ConnectionStrings["MyDB"]...

What is the Angular equivalent to an AngularJS $watch?

Here is another approach using getter and setter functions for the model.

@Component({
  selector: 'input-language',
  template: `
  …
  <input 
    type="text" 
    placeholder="Language" 
    [(ngModel)]="query" 
  />
  `,
})
export class InputLanguageComponent {

  set query(value) {
    this._query = value;
    console.log('query set to :', value)
  }

  get query() {
    return this._query;
  }
}

Creating threads - Task.Factory.StartNew vs new Thread()

The task gives you all the goodness of the task API:

  • Adding continuations (Task.ContinueWith)
  • Waiting for multiple tasks to complete (either all or any)
  • Capturing errors in the task and interrogating them later
  • Capturing cancellation (and allowing you to specify cancellation to start with)
  • Potentially having a return value
  • Using await in C# 5
  • Better control over scheduling (if it's going to be long-running, say so when you create the task so the task scheduler can take that into account)

Note that in both cases you can make your code slightly simpler with method group conversions:

DataInThread = new Thread(ThreadProcedure);
// Or...
Task t = Task.Factory.StartNew(ThreadProcedure);

import an array in python

(I know the question is old, but I think this might be good as a reference for people with similar questions)

If you want to load data from an ASCII/text file (which has the benefit or being more or less human-readable and easy to parse in other software), numpy.loadtxt is probably what you want:

If you just want to quickly save and load numpy arrays/matrices to and from a file, take a look at numpy.save and numpy.load:

How to stick <footer> element at the bottom of the page (HTML5 and CSS3)?

For footer change from position: relative; to position:fixed;

 footer {
            background-color: #333;
            width: 100%;
            bottom: 0;
            position: fixed;
        }

Example: http://jsfiddle.net/a6RBm/

How do I enumerate through a JObject?

The answer did not work for me. I dont know how it got so many votes. Though it helped in pointing me in a direction.

This is the answer that worked for me:

foreach (var x in jobj)
{
    var key = ((JProperty) (x)).Name;
    var jvalue = ((JProperty)(x)).Value ;
}

"multiple target patterns" Makefile error

I just want to add, if you get this error because you are using Cygwin make and auto-generated files, you can fix it with the following sed,

sed -e 's@\\\([^ ]\)@/\1@g' -e 's@[cC]:@/cygdrive/c@' -i filename.d

You may need to add more characters than just space to the escape list in the first substitution but you get the idea. The concept here is that /cygdrive/c is an alias for c: that cygwin's make will recognize.

And may as well throw in

-e 's@^ \+@\t@'

just in case you did start with spaces on accident (although I /think/ this will usually be a "missing separator" error).

How to set Bullet colors in UL/LI html lists via CSS without using any images or span tags

I know it's a bit of a late answer for this post, but for reference...

CSS

ul {
    color: red;
}

li {
    color: black;
}

The bullet colour is defined on the ul tag and then we switch the li colour back.