Programs & Examples On #Service provider

0

AngularJS : Factory and Service?

  • If you use a service you will get the instance of a function ("this" keyword).
  • If you use a factory you will get the value that is returned by invoking the function reference (the return statement in factory)

Factory and Service are the most commonly used recipes. The only difference between them is that Service recipe works better for objects of custom type, while Factory can produce JavaScript primitives and functions.

Reference

ImportError: No module named 'Queue'

You need install Queuelib either via the Python Package Index (PyPI) or from source.

To install using pip:-

$ pip install queuelib

To install using easy_install:-

$ easy_install queuelib

If you have downloaded a source tarball you can install it by running the following (as root):-

python setup.py install

Correct Way to Load Assembly, Find Class and Call Run() Method

If you do not have access to the TestRunner type information in the calling assembly (it sounds like you may not), you can call the method like this:

Assembly assembly = Assembly.LoadFile(@"C:\dyn.dll");
Type     type     = assembly.GetType("TestRunner");
var      obj      = Activator.CreateInstance(type);

// Alternately you could get the MethodInfo for the TestRunner.Run method
type.InvokeMember("Run", 
                  BindingFlags.Default | BindingFlags.InvokeMethod, 
                  null,
                  obj,
                  null);

If you have access to the IRunnable interface type, you can cast your instance to that (rather than the TestRunner type, which is implemented in the dynamically created or loaded assembly, right?):

  Assembly assembly  = Assembly.LoadFile(@"C:\dyn.dll");
  Type     type      = assembly.GetType("TestRunner");
  IRunnable runnable = Activator.CreateInstance(type) as IRunnable;
  if (runnable == null) throw new Exception("broke");
  runnable.Run();

onclick event function in JavaScript

Try this

<input type="button" onClick="return click();">button text</input>  

Pull all images from a specified directory and then display them

You need to change the loop from for ($i=1; $i<count($files); $i++) to for ($i=0; $i<count($files); $i++):

So the correct code is

<?php
$files = glob("images/*.*");

for ($i=0; $i<count($files); $i++) {
    $image = $files[$i];
    print $image ."<br />";
    echo '<img src="'.$image .'" alt="Random image" />'."<br /><br />";
}

?>

np.mean() vs np.average() in Python NumPy?

In addition to the differences already noted, there's another extremely important difference that I just now discovered the hard way: unlike np.mean, np.average doesn't allow the dtype keyword, which is essential for getting correct results in some cases. I have a very large single-precision array that is accessed from an h5 file. If I take the mean along axes 0 and 1, I get wildly incorrect results unless I specify dtype='float64':

>T.shape
(4096, 4096, 720)
>T.dtype
dtype('<f4')

m1 = np.average(T, axis=(0,1))                #  garbage
m2 = np.mean(T, axis=(0,1))                   #  the same garbage
m3 = np.mean(T, axis=(0,1), dtype='float64')  # correct results

Unfortunately, unless you know what to look for, you can't necessarily tell your results are wrong. I will never use np.average again for this reason but will always use np.mean(.., dtype='float64') on any large array. If I want a weighted average, I'll compute it explicitly using the product of the weight vector and the target array and then either np.sum or np.mean, as appropriate (with appropriate precision as well).

Get all inherited classes of an abstract class

typeof(AbstractDataExport).Assembly tells you an assembly your types are located in (assuming all are in the same).

assembly.GetTypes() gives you all types in that assembly or assembly.GetExportedTypes() gives you types that are public.

Iterating through the types and using type.IsAssignableFrom() gives you whether the type is derived.

PHP - Check if the page run on Mobile or Desktop browser

<?php //-- Very simple variant
$useragent = $_SERVER['HTTP_USER_AGENT']; 
$iPod = stripos($useragent, "iPod"); 
$iPad = stripos($useragent, "iPad"); 
$iPhone = stripos($useragent, "iPhone");
$Android = stripos($useragent, "Android"); 
$iOS = stripos($useragent, "iOS");
//-- You can add billion devices 

$DEVICE = ($iPod||$iPad||$iPhone||$Android||$iOS||$webOS||$Blackberry||$IEMobile||$OperaMini);

if ($DEVICE !=true) {?>

<!-- What you want for all non-mobile devices. Anything with all HTML codes-->

<?php }else{ ?> 

<!-- What you want for all mobile devices. Anything with all HTML codes --> 
<?php } ?>

Can you remove elements from a std::list while iterating through it?

Here's an example using a for loop that iterates the list and increments or revalidates the iterator in the event of an item being removed during traversal of the list.

for(auto i = items.begin(); i != items.end();)
{
    if(bool isActive = (*i)->update())
    {
        other_code_involving(*i);
        ++i;

    }
    else
    {
        i = items.erase(i);

    }

}

items.remove_if(CheckItemNotActive);

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

The ISO C99 standard specifies that these macros must only be defined if explicitly requested.

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

... now PRIu64 will work

Good font for code presentations?

I do a lot of such presentation and use Monaco for code and Chalkboard for text (within a template that, overall, has only small changes from the Blackboard one supplied with Keynote). Look at any of my presentations' PDFs (e.g. this one) and you can decide whether you like the effect.

SELECTING with multiple WHERE conditions on same column

Use this: For example:

select * from ACCOUNTS_DETAILS
where ACCOUNT_ID=1001
union
select * from ACCOUNTS_DETAILS
where ACCOUNT_ID=1002

How to convert uint8 Array to base64 Encoded String?

All solutions already proposed have severe problems. Some solutions fail to work on large arrays, some provide wrong output, some throw an error on btoa call if an intermediate string contains multibyte characters, some consume more memory than needed.

So I implemented a direct conversion function which just works regardless of the input. It converts about 5 million bytes per second on my machine.

https://gist.github.com/enepomnyaschih/72c423f727d395eeaa09697058238727

_x000D_
_x000D_
/*_x000D_
MIT License_x000D_
Copyright (c) 2020 Egor Nepomnyaschih_x000D_
Permission is hereby granted, free of charge, to any person obtaining a copy_x000D_
of this software and associated documentation files (the "Software"), to deal_x000D_
in the Software without restriction, including without limitation the rights_x000D_
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell_x000D_
copies of the Software, and to permit persons to whom the Software is_x000D_
furnished to do so, subject to the following conditions:_x000D_
The above copyright notice and this permission notice shall be included in all_x000D_
copies or substantial portions of the Software._x000D_
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR_x000D_
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,_x000D_
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE_x000D_
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER_x000D_
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,_x000D_
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE_x000D_
SOFTWARE._x000D_
*/_x000D_
_x000D_
/*_x000D_
// This constant can also be computed with the following algorithm:_x000D_
const base64abc = [],_x000D_
 A = "A".charCodeAt(0),_x000D_
 a = "a".charCodeAt(0),_x000D_
 n = "0".charCodeAt(0);_x000D_
for (let i = 0; i < 26; ++i) {_x000D_
 base64abc.push(String.fromCharCode(A + i));_x000D_
}_x000D_
for (let i = 0; i < 26; ++i) {_x000D_
 base64abc.push(String.fromCharCode(a + i));_x000D_
}_x000D_
for (let i = 0; i < 10; ++i) {_x000D_
 base64abc.push(String.fromCharCode(n + i));_x000D_
}_x000D_
base64abc.push("+");_x000D_
base64abc.push("/");_x000D_
*/_x000D_
const base64abc = [_x000D_
 "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",_x000D_
 "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",_x000D_
 "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",_x000D_
 "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",_x000D_
 "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/"_x000D_
];_x000D_
_x000D_
/*_x000D_
// This constant can also be computed with the following algorithm:_x000D_
const l = 256, base64codes = new Uint8Array(l);_x000D_
for (let i = 0; i < l; ++i) {_x000D_
 base64codes[i] = 255; // invalid character_x000D_
}_x000D_
base64abc.forEach((char, index) => {_x000D_
 base64codes[char.charCodeAt(0)] = index;_x000D_
});_x000D_
base64codes["=".charCodeAt(0)] = 0; // ignored anyway, so we just need to prevent an error_x000D_
*/_x000D_
const base64codes = [_x000D_
 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,_x000D_
 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,_x000D_
 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63,_x000D_
 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 255, 0, 255, 255,_x000D_
 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,_x000D_
 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255,_x000D_
 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,_x000D_
 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51_x000D_
];_x000D_
_x000D_
function getBase64Code(charCode) {_x000D_
 if (charCode >= base64codes.length) {_x000D_
  throw new Error("Unable to parse base64 string.");_x000D_
 }_x000D_
 const code = base64codes[charCode];_x000D_
 if (code === 255) {_x000D_
  throw new Error("Unable to parse base64 string.");_x000D_
 }_x000D_
 return code;_x000D_
}_x000D_
_x000D_
export function bytesToBase64(bytes) {_x000D_
 let result = '', i, l = bytes.length;_x000D_
 for (i = 2; i < l; i += 3) {_x000D_
  result += base64abc[bytes[i - 2] >> 2];_x000D_
  result += base64abc[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)];_x000D_
  result += base64abc[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)];_x000D_
  result += base64abc[bytes[i] & 0x3F];_x000D_
 }_x000D_
 if (i === l + 1) { // 1 octet yet to write_x000D_
  result += base64abc[bytes[i - 2] >> 2];_x000D_
  result += base64abc[(bytes[i - 2] & 0x03) << 4];_x000D_
  result += "==";_x000D_
 }_x000D_
 if (i === l) { // 2 octets yet to write_x000D_
  result += base64abc[bytes[i - 2] >> 2];_x000D_
  result += base64abc[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)];_x000D_
  result += base64abc[(bytes[i - 1] & 0x0F) << 2];_x000D_
  result += "=";_x000D_
 }_x000D_
 return result;_x000D_
}_x000D_
_x000D_
export function base64ToBytes(str) {_x000D_
 if (str.length % 4 !== 0) {_x000D_
  throw new Error("Unable to parse base64 string.");_x000D_
 }_x000D_
 const index = str.indexOf("=");_x000D_
 if (index !== -1 && index < str.length - 2) {_x000D_
  throw new Error("Unable to parse base64 string.");_x000D_
 }_x000D_
 let missingOctets = str.endsWith("==") ? 2 : str.endsWith("=") ? 1 : 0,_x000D_
  n = str.length,_x000D_
  result = new Uint8Array(3 * (n / 4)),_x000D_
  buffer;_x000D_
 for (let i = 0, j = 0; i < n; i += 4, j += 3) {_x000D_
  buffer =_x000D_
   getBase64Code(str.charCodeAt(i)) << 18 |_x000D_
   getBase64Code(str.charCodeAt(i + 1)) << 12 |_x000D_
   getBase64Code(str.charCodeAt(i + 2)) << 6 |_x000D_
   getBase64Code(str.charCodeAt(i + 3));_x000D_
  result[j] = buffer >> 16;_x000D_
  result[j + 1] = (buffer >> 8) & 0xFF;_x000D_
  result[j + 2] = buffer & 0xFF;_x000D_
 }_x000D_
 return result.subarray(0, result.length - missingOctets);_x000D_
}_x000D_
_x000D_
export function base64encode(str, encoder = new TextEncoder()) {_x000D_
 return bytesToBase64(encoder.encode(str));_x000D_
}_x000D_
_x000D_
export function base64decode(str, decoder = new TextDecoder()) {_x000D_
 return decoder.decode(base64ToBytes(str));_x000D_
}
_x000D_
_x000D_
_x000D_

git status shows fatal: bad object HEAD

This happened to me on a old simple project without branches. I made a lot of changes and when I was done, I couldn't commit. Nothing above worked so I ended up with:

  1. Copied all the code with my latest changes to a Backup-folder.
  2. Git clone to download the latest working code along with the working .git folder.
  3. Copied my code with latest changes from the backup and replaced the cloned code (not the .git folder).
  4. git add and commit works again and I have all my recent changes.

Unable to connect to any of the specified mysql hosts. C# MySQL

I was having the exact same error.

Here's what you need to do:

If you are using MAMP, close your server. Then click on the preferences button when you open up MAMP again (before restarting your server of course).

Then you will need to click on the ports tab, and click the button "Set Web and MySQL Ports to 80 & 3306".

In a Dockerfile, How to update PATH environment variable?

This is discouraged (if you want to create/distribute a clean Docker image), since the PATH variable is set by /etc/profile script, the value can be overridden.

head /etc/profile:

if [ "`id -u`" -eq 0 ]; then
  PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
else
  PATH="/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"
fi
export PATH

At the end of the Dockerfile, you could add:

RUN echo "export PATH=$PATH" > /etc/environment

So PATH is set for all users.

Secure FTP using Windows batch script

    ftps -a -z -e:on -pfxfile:"S-PID.p12" -pfxpwfile:"S-PID.p12.pwd" -user:<S-PID number> -s:script <RemoteServerName> 2121

S-PID.p12 => certificate file name ;
S-PID.p12.pwd => certificate password file name ; 
RemoteServerName =>  abcd123 ; 
2121 => port number ; 
ftps => command is part of ftps client software ; 

Abstract Class vs Interface in C++

I assume that with interface you mean a C++ class with only pure virtual methods (i.e. without any code), instead with abstract class you mean a C++ class with virtual methods that can be overridden, and some code, but at least one pure virtual method that makes the class not instantiable. e.g.:

class MyInterface
{
public:
  // Empty virtual destructor for proper cleanup
  virtual ~MyInterface() {}

  virtual void Method1() = 0;
  virtual void Method2() = 0;
};


class MyAbstractClass
{
public:
  virtual ~MyAbstractClass();

  virtual void Method1();
  virtual void Method2();
  void Method3();

  virtual void Method4() = 0; // make MyAbstractClass not instantiable
};

In Windows programming, interfaces are fundamental in COM. In fact, a COM component exports only interfaces (i.e. pointers to v-tables, i.e. pointers to set of function pointers). This helps defining an ABI (Application Binary Interface) that makes it possible to e.g. build a COM component in C++ and use it in Visual Basic, or build a COM component in C and use it in C++, or build a COM component with Visual C++ version X and use it with Visual C++ version Y. In other words, with interfaces you have high decoupling between client code and server code.

Moreover, when you want to build DLL's with a C++ object-oriented interface (instead of pure C DLL's), as described in this article, it's better to export interfaces (the "mature approach") instead of C++ classes (this is basically what COM does, but without the burden of COM infrastructure).

I'd use an interface if I want to define a set of rules using which a component can be programmed, without specifying a concrete particular behavior. Classes that implement this interface will provide some concrete behavior themselves.

Instead, I'd use an abstract class when I want to provide some default infrastructure code and behavior, and make it possible to client code to derive from this abstract class, overriding the pure virtual methods with some custom code, and complete this behavior with custom code. Think for example of an infrastructure for an OpenGL application. You can define an abstract class that initializes OpenGL, sets up the window environment, etc. and then you can derive from this class and implement custom code for e.g. the rendering process and handling user input:

// Abstract class for an OpenGL app.
// Creates rendering window, initializes OpenGL; 
// client code must derive from it 
// and implement rendering and user input.
class OpenGLApp
{
public:
  OpenGLApp();
  virtual ~OpenGLApp();
  ...

  // Run the app    
  void Run();


  // <---- This behavior must be implemented by the client ---->

  // Rendering
  virtual void Render() = 0;

  // Handle user input
  // (returns false to quit, true to continue looping)
  virtual bool HandleInput() = 0;

  // <--------------------------------------------------------->


private:
  //
  // Some infrastructure code
  //
  ... 
  void CreateRenderingWindow();
  void CreateOpenGLContext();
  void SwapBuffers();
};


class MyOpenGLDemo : public OpenGLApp
{
public:
  MyOpenGLDemo();
  virtual ~MyOpenGLDemo();

  // Rendering
  virtual void Render();  // implements rendering code

  // Handle user input
  virtual bool HandleInput(); // implements user input handling


  //  ... some other stuff
};

Servlet Mapping using web.xml

It allows servlets to have multiple servlet mappings:

<servlet>
    <servlet-name>Servlet1</servlet-name>
    <servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/bill</url-pattern>
</servlet-mapping>

It allows filters to be mapped on the particular servlet:

<filter-mapping>
    <filter-name>Filter1</filter-name>
    <servlet-name>Servlet1</servlet-name>
</filter-mapping>

Your proposal would support neither of them. Note that the web.xml is read and parsed only once during application's startup, not on every HTTP request as you seem to think.

Since Servlet 3.0, there's the @WebServlet annotation which minimizes this boilerplate:

@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {

See also:

How do I get monitor resolution in Python?

On Windows 8.1 I am not getting the correct resolution from either ctypes or tk. Other people are having this same problem for ctypes: getsystemmetrics returns wrong screen size To get the correct full resolution of a high DPI monitor on windows 8.1, one must call SetProcessDPIAware and use the following code:

import ctypes
user32 = ctypes.windll.user32
user32.SetProcessDPIAware()
[w, h] = [user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)]

Full Details Below:

I found out that this is because windows is reporting a scaled resolution. It appears that python is by default a 'system dpi aware' application. Types of DPI aware applications are listed here: http://msdn.microsoft.com/en-us/library/windows/desktop/dn469266%28v=vs.85%29.aspx#dpi_and_the_desktop_scaling_factor

Basically, rather than displaying content the full monitor resolution, which would make fonts tiny, the content is scaled up until the fonts are big enough.

On my monitor I get:
Physical resolution: 2560 x 1440 (220 DPI)
Reported python resolution: 1555 x 875 (158 DPI)

Per this windows site: http://msdn.microsoft.com/en-us/library/aa770067%28v=vs.85%29.aspx The formula for reported system effective resolution is: (reported_px*current_dpi)/(96 dpi) = physical_px

I'm able to get the correct full screen resolution, and current DPI with the below code. Note that I call SetProcessDPIAware() to allow the program to see the real resolution.

import tkinter as tk
root = tk.Tk()

width_px = root.winfo_screenwidth()
height_px = root.winfo_screenheight() 
width_mm = root.winfo_screenmmwidth()
height_mm = root.winfo_screenmmheight() 
# 2.54 cm = in
width_in = width_mm / 25.4
height_in = height_mm / 25.4
width_dpi = width_px/width_in
height_dpi = height_px/height_in 

print('Width: %i px, Height: %i px' % (width_px, height_px))
print('Width: %i mm, Height: %i mm' % (width_mm, height_mm))
print('Width: %f in, Height: %f in' % (width_in, height_in))
print('Width: %f dpi, Height: %f dpi' % (width_dpi, height_dpi))

import ctypes
user32 = ctypes.windll.user32
user32.SetProcessDPIAware()
[w, h] = [user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)]
print('Size is %f %f' % (w, h))

curr_dpi = w*96/width_px
print('Current DPI is %f' % (curr_dpi))    

Which returned:

Width: 1555 px, Height: 875 px
Width: 411 mm, Height: 232 mm
Width: 16.181102 in, Height: 9.133858 in
Width: 96.099757 dpi, Height: 95.797414 dpi
Size is 2560.000000 1440.000000
Current DPI is 158.045016

I am running windows 8.1 with a 220 DPI capable monitor. My display scaling sets my current DPI to 158.

I'll use the 158 to make sure my matplotlib plots are the right size with: from pylab import rcParams rcParams['figure.dpi'] = curr_dpi

Check if value already exists within list of dictionaries?

Based on @Mark Byers great answer, and following @Florent question, just to indicate that it will also work with 2 conditions on list of dics with more than 2 keys:

names = []
names.append({'first': 'Nil', 'last': 'Elliot', 'suffix': 'III'})
names.append({'first': 'Max', 'last': 'Sam', 'suffix': 'IX'})
names.append({'first': 'Anthony', 'last': 'Mark', 'suffix': 'IX'})

if not any(d['first'] == 'Anthony' and d['last'] == 'Mark' for d in names):

    print('Not exists!')
else:
    print('Exists!')

Result:

Exists!

use regular expression in if-condition in bash

@OP,

Is glob pettern not only used for file names?

No, "glob" pattern is not only used for file names. you an use it to compare strings as well. In your examples, you can use case/esac to look for strings patterns.

 gg=svm-grid-ch 
 # looking for the word "grid" in the string $gg
 case "$gg" in
    *grid* ) echo "found";;
 esac

 # [[ $gg =~ ^....grid* ]]
 case "$gg" in ????grid*) echo "found";; esac 

 # [[ $gg =~ s...grid* ]]
 case "$gg" in s???grid*) echo "found";; esac

In bash, when to use glob pattern and when to use regular expression? Thanks!

Regex are more versatile and "convenient" than "glob patterns", however unless you are doing complex tasks that "globbing/extended globbing" cannot provide easily, then there's no need to use regex. Regex are not supported for version of bash <3.2 (as dennis mentioned), but you can still use extended globbing (by setting extglob ). for extended globbing, see here and some simple examples here.

Update for OP: Example to find files that start with 2 characters (the dots "." means 1 char) followed by "g" using regex

eg output

$ shopt -s dotglob
$ ls -1 *
abg
degree
..g

$ for file in *; do [[ $file =~ "..g" ]] && echo $file ; done
abg
degree
..g

In the above, the files are matched because their names contain 2 characters followed by "g". (ie ..g).

The equivalent with globbing will be something like this: (look at reference for meaning of ? and * )

$ for file in ??g*; do echo $file; done
abg
degree
..g

How do I clear inner HTML

Take a look at this. a clean and simple solution using jQuery.

http://jsfiddle.net/ma2Yd/

    <h1 onmouseover="go('The dog is in its shed')" onmouseout="clear()">lalala</h1>
    <div id="goy"></div>


    <script type="text/javascript">

    $(function() {
       $("h1").on('mouseover', function() {
          $("#goy").text('The dog is in its shed');
       }).on('mouseout', function() {
          $("#goy").text("");
       });
   });

React - clearing an input value after form submit

this.mainInput doesn't actually point to anything. Since you are using a controlled component (i.e. the value of the input is obtained from state) you can set this.state.city to null:

onHandleSubmit(e) {
  e.preventDefault();
  const city = this.state.city;
  this.props.onSearchTermChange(city);
  this.setState({ city: '' });
}

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

This is simple if you only use Selenium WebDriver, and forget the usage of Selenium-RC. I'd go like this.

WebDriver driver = new FirefoxDriver();
WebElement email = driver.findElement(By.id("email"));
email.sendKeys("[email protected]");

The reason for NullPointerException however is that your variable driver has never been started, you start FirefoxDriver in a variable wb thas is never being used.

space between divs - display table-cell

Make a new div with whatever name (I will just use table-split) and give it a width, without adding content to it, while placing it between necessary divs that need to be separated.

You can add whatever width you find necessary. I just used 0.6% because it's what I needed for when I had to do this.

_x000D_
_x000D_
.table-split {_x000D_
  display: table-cell;_x000D_
  width: 0.6%_x000D_
}
_x000D_
<div class="table-split"></div>
_x000D_
_x000D_
_x000D_

How to hash a password

Based on csharptest.net's great answer, I have written a Class for this:

public static class SecurePasswordHasher
{
    /// <summary>
    /// Size of salt.
    /// </summary>
    private const int SaltSize = 16;

    /// <summary>
    /// Size of hash.
    /// </summary>
    private const int HashSize = 20;

    /// <summary>
    /// Creates a hash from a password.
    /// </summary>
    /// <param name="password">The password.</param>
    /// <param name="iterations">Number of iterations.</param>
    /// <returns>The hash.</returns>
    public static string Hash(string password, int iterations)
    {
        // Create salt
        byte[] salt;
        new RNGCryptoServiceProvider().GetBytes(salt = new byte[SaltSize]);

        // Create hash
        var pbkdf2 = new Rfc2898DeriveBytes(password, salt, iterations);
        var hash = pbkdf2.GetBytes(HashSize);

        // Combine salt and hash
        var hashBytes = new byte[SaltSize + HashSize];
        Array.Copy(salt, 0, hashBytes, 0, SaltSize);
        Array.Copy(hash, 0, hashBytes, SaltSize, HashSize);

        // Convert to base64
        var base64Hash = Convert.ToBase64String(hashBytes);

        // Format hash with extra information
        return string.Format("$MYHASH$V1${0}${1}", iterations, base64Hash);
    }

    /// <summary>
    /// Creates a hash from a password with 10000 iterations
    /// </summary>
    /// <param name="password">The password.</param>
    /// <returns>The hash.</returns>
    public static string Hash(string password)
    {
        return Hash(password, 10000);
    }

    /// <summary>
    /// Checks if hash is supported.
    /// </summary>
    /// <param name="hashString">The hash.</param>
    /// <returns>Is supported?</returns>
    public static bool IsHashSupported(string hashString)
    {
        return hashString.Contains("$MYHASH$V1$");
    }

    /// <summary>
    /// Verifies a password against a hash.
    /// </summary>
    /// <param name="password">The password.</param>
    /// <param name="hashedPassword">The hash.</param>
    /// <returns>Could be verified?</returns>
    public static bool Verify(string password, string hashedPassword)
    {
        // Check hash
        if (!IsHashSupported(hashedPassword))
        {
            throw new NotSupportedException("The hashtype is not supported");
        }

        // Extract iteration and Base64 string
        var splittedHashString = hashedPassword.Replace("$MYHASH$V1$", "").Split('$');
        var iterations = int.Parse(splittedHashString[0]);
        var base64Hash = splittedHashString[1];

        // Get hash bytes
        var hashBytes = Convert.FromBase64String(base64Hash);

        // Get salt
        var salt = new byte[SaltSize];
        Array.Copy(hashBytes, 0, salt, 0, SaltSize);

        // Create hash with given salt
        var pbkdf2 = new Rfc2898DeriveBytes(password, salt, iterations);
        byte[] hash = pbkdf2.GetBytes(HashSize);

        // Get result
        for (var i = 0; i < HashSize; i++)
        {
            if (hashBytes[i + SaltSize] != hash[i])
            {
                return false;
            }
        }
        return true;
    }
}

Usage:

// Hash
var hash = SecurePasswordHasher.Hash("mypassword");

// Verify
var result = SecurePasswordHasher.Verify("mypassword", hash);

A sample hash could be this:

$MYHASH$V1$10000$Qhxzi6GNu/Lpy3iUqkeqR/J1hh8y/h5KPDjrv89KzfCVrubn

As you can see, I also have included the iterations in the hash for easy usage and the possibility to upgrade this, if we need to upgrade.


If you are interested in .net core, I also have a .net core version on Code Review.

Convert PEM to PPK file format

PuTTYgen for Ubuntu/Linux and PEM to PPK

sudo apt install putty-tools
puttygen -t rsa -b 2048 -C "user@host" -o keyfile.ppk

How to display an error message in an ASP.NET Web Application

All you need is a control that you can set the text of, and an UpdatePanel if the exception occurs during a postback.

If occurs during a postback: markup:

<ajax:UpdatePanel id="ErrorUpdatePanel" runat="server" UpdateMode="Coditional">
<ContentTemplate>
<asp:TextBox id="ErrorTextBox" runat="server" />
</ContentTemplate>
</ajax:UpdatePanel>

code:

try
{
do something
}

catch(YourException ex)
{
this.ErrorTextBox.Text = ex.Message;
this.ErrorUpdatePanel.Update();
}

Number of lines in a file in Java

The accepted answer has an off by one error for multi line files which don't end in newline. A one line file ending without a newline would return 1, but a two line file ending without a newline would return 1 too. Here's an implementation of the accepted solution which fixes this. The endsWithoutNewLine checks are wasteful for everything but the final read, but should be trivial time wise compared to the overall function.

public int count(String filename) throws IOException {
    InputStream is = new BufferedInputStream(new FileInputStream(filename));
    try {
        byte[] c = new byte[1024];
        int count = 0;
        int readChars = 0;
        boolean endsWithoutNewLine = false;
        while ((readChars = is.read(c)) != -1) {
            for (int i = 0; i < readChars; ++i) {
                if (c[i] == '\n')
                    ++count;
            }
            endsWithoutNewLine = (c[readChars - 1] != '\n');
        }
        if(endsWithoutNewLine) {
            ++count;
        } 
        return count;
    } finally {
        is.close();
    }
}

Detect Click into Iframe using JavaScript

see http://jsfiddle.net/Lcy797h2/ for my long winded solution that doesn't work reliably in IE

        $(window).on('blur',function(e) {    
            if($(this).data('mouseIn') != 'yes')return;
            $('iframe').filter(function(){
                return $(this).data('mouseIn') == 'yes';
            }).trigger('iframeclick');    
        });

        $(window).mouseenter(function(){
            $(this).data('mouseIn', 'yes');
        }).mouseleave(function(){
            $(this).data('mouseIn', 'no');
        });

        $('iframe').mouseenter(function(){
            $(this).data('mouseIn', 'yes');
            $(window).data('mouseIn', 'yes');
        }).mouseleave(function(){
            $(this).data('mouseIn', null);
        });

        $('iframe').on('iframeclick', function(){
            console.log('Clicked inside iframe');
            $('#result').text('Clicked inside iframe'); 
        });
        $(window).on('click', function(){
            console.log('Clicked inside window');
            $('#result').text('Clicked inside window'); 
        }).blur(function(){
            console.log('window blur');
        });

        $('<input type="text" style="position:absolute;opacity:0;height:0px;width:0px;"/>').appendTo(document.body).blur(function(){
                $(window).trigger('blur');
            }).focus();

Double value to round up in Java

double TotalPrice=90.98989898898;

  DecimalFormat format_2Places = new DecimalFormat("0.00");

    TotalPrice = Double.valueOf(format_2Places.format(TotalPrice));

phpMyAdmin mbstring error

check your php.ini file in the root directory of your php installation. In the extensions part of the configuration you should find:

;extension=php_mbstring.dll

remove the leading ';' to uncomment and enable the extension so it looks like this:

extension=php_mbstring.dll

restart your apache and it should work.

Edit: I just read that you are already using a webhost. Does your webhost have a interface where you can set php variables etc? Or a .ini file you can edit?

If not you may are forced to talk to the webhost and ask them to enable that particular extension.

Is it possible to include one CSS file in another?

yes it is possible using @import and providing the path of css file e.g.

@import url("mycssfile.css");

or

@import "mycssfile.css";

How to check for a Null value in VB.NET

I find the safest way is

If Not editTransactionRow.pay_id Is Nothing

It might read terribly, but the ISIL is actually very different from IsNot Nothing, and it doesn't try and evaluate the expression, which could give a null reference exception.

How to specify names of columns for x and y when joining in dplyr?

This is more a workaround than a real solution. You can create a new object test_data with another column name:

left_join("names<-"(test_data, "name"), kantrowitz, by = "name")

     name gender
1    john      M
2    bill either
3 madison      M
4    abby either
5     zzz   <NA>

How to print a string at a fixed width?

EDIT 2013-12-11 - This answer is very old. It is still valid and correct, but people looking at this should prefer the new format syntax.

You can use string formatting like this:

>>> print '%5s' % 'aa'
   aa
>>> print '%5s' % 'aaa'
  aaa
>>> print '%5s' % 'aaaa'
 aaaa
>>> print '%5s' % 'aaaaa'
aaaaa

Basically:

  • the % character informs python it will have to substitute something to a token
  • the s character informs python the token will be a string
  • the 5 (or whatever number you wish) informs python to pad the string with spaces up to 5 characters.

In your specific case a possible implementation could look like:

>>> dict_ = {'a': 1, 'ab': 1, 'abc': 1}
>>> for item in dict_.items():
...     print 'value %3s - num of occurances = %d' % item # %d is the token of integers
... 
value   a - num of occurances = 1
value  ab - num of occurances = 1
value abc - num of occurances = 1

SIDE NOTE: Just wondered if you are aware of the existence of the itertools module. For example you could obtain a list of all your combinations in one line with:

>>> [''.join(perm) for i in range(1, len(s)) for perm in it.permutations(s, i)]
['a', 'b', 'c', 'd', 'ab', 'ac', 'ad', 'ba', 'bc', 'bd', 'ca', 'cb', 'cd', 'da', 'db', 'dc', 'abc', 'abd', 'acb', 'acd', 'adb', 'adc', 'bac', 'bad', 'bca', 'bcd', 'bda', 'bdc', 'cab', 'cad', 'cba', 'cbd', 'cda', 'cdb', 'dab', 'dac', 'dba', 'dbc', 'dca', 'dcb']

and you could get the number of occurrences by using combinations in conjunction with count().

Row names & column names in R

And another expansion:

# create dummy matrix
set.seed(10)
m <- matrix(round(runif(25, 1, 5)), 5)
d <- as.data.frame(m)

If you want to assign new column names you can do following on data.frame:

# an identical effect can be achieved with colnames()   
names(d) <- LETTERS[1:5]
> d
  A B C D E
1 3 2 4 3 4
2 2 2 3 1 3
3 3 2 1 2 4
4 4 3 3 3 2
5 1 3 2 4 3

If you, however run previous command on matrix, you'll mess things up:

names(m) <- LETTERS[1:5]
> m
     [,1] [,2] [,3] [,4] [,5]
[1,]    3    2    4    3    4
[2,]    2    2    3    1    3
[3,]    3    2    1    2    4
[4,]    4    3    3    3    2
[5,]    1    3    2    4    3
attr(,"names")
 [1] "A" "B" "C" "D" "E" NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA 
[20] NA  NA  NA  NA  NA  NA 

Since matrix can be regarded as two-dimensional vector, you'll assign names only to first five values (you don't want to do that, do you?). In this case, you should stick with colnames().

So there...

What is the best way to get all the divisors of a number?

If your PC has tons of memory, a brute single line can be fast enough with numpy:

N = 10000000; tst = np.arange(1, N); tst[np.mod(N, tst) == 0]
Out: 
array([      1,       2,       4,       5,       8,      10,      16,
            20,      25,      32,      40,      50,      64,      80,
           100,     125,     128,     160,     200,     250,     320,
           400,     500,     625,     640,     800,    1000,    1250,
          1600,    2000,    2500,    3125,    3200,    4000,    5000,
          6250,    8000,   10000,   12500,   15625,   16000,   20000,
         25000,   31250,   40000,   50000,   62500,   78125,   80000,
        100000,  125000,  156250,  200000,  250000,  312500,  400000,
        500000,  625000, 1000000, 1250000, 2000000, 2500000, 5000000])

Takes less than 1s on my slow PC.

LINQ to SQL Left Outer Join

Take care of performance:

I experienced that at least with EF Core the different answers given here might result in different performance. I'm aware that the OP asked about Linq to SQL, but it seems to me that the same questions occur also with EF Core.

In a specific case I had to handle, the (syntactically nicer) suggestion by Marc Gravell resulted in left joins inside a cross apply -- similarly to what Mike U described -- which had the result that the estimated costs for this specific query were two times as high compared to a query with no cross joins. The server execution times differed by a factor of 3. [1]

The solution by Marc Gravell resulted in a query without cross joins.

Context: I essentially needed to perform two left joins on two tables each of which again required a join to another table. Furthermore, there I had to specify other where-conditions on the tables on which I needed to apply the left join. In addition, I had two inner joins on the main table.

Estimated operator costs:

  • with cross apply: 0.2534
  • without cross apply: 0.0991.

Server execution times in ms (queries executed 10 times; measured using SET STATISTICS TIME ON):

  • with cross apply: 5, 6, 6, 6, 6, 6, 6, 6, 6, 6
  • without cross apply: 2, 2, 2, 2, 2, 2, 2, 2, 2, 2

(The very first run was slower for both queries; seems that something is cached.)

Table sizes:

  • main table: 87 rows,
  • first table for left join: 179 rows;
  • second table for left join: 7 rows.

EF Core version: 2.2.1.

SQL Server version: MS SQL Server 2017 - 14... (on Windows 10).

All relevant tables had indexes on the primary keys only.

My conclusion: it's always recommended to look at the generated SQL since it can really differ.


[1] Interestingly enough, when setting the 'Client statistics' in MS SQL Server Management Studio on, I could see an opposite trend; namely that last run of the solution without cross apply took more than 1s. I suppose that something was going wrong here - maybe with my setup.

Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

/**
 * If $header is an array of headers
 * It will format and return the correct $header
 * $header = [
 *  'Accept' => 'application/json',
 *  'Content-Type' => 'application/x-www-form-urlencoded'
 * ];
 */
$i_header = $header;
if(is_array($i_header) === true){
    $header = [];
    foreach ($i_header as $param => $value) {
        $header[] = "$param: $value";
    }
}

Find in Files: Search all code in Team Foundation Server

Another solution is to use "ctrl+shift+F". You can change the search location to a local directory rather than a solution or project. This will just take the place of the desktop search and you'll still need to get the latest code, but it will allow you to remain within Visual Studio to do your searching.

What's the difference between ".equals" and "=="?

The equals( ) method and the == operator perform two different operations. The equals( ) method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance. The following program shows how two different String objects can contain the same characters, but references to these objects will not compare as equal:

// equals() vs ==
class EqualsNotEqualTo {
     public static void main(String args[]) {
          String s1 = "Hello";
          String s2 = new String(s1);
          System.out.println(s1 + " equals " + s2 + " -> " +
          s1.equals(s2));
          System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
     }
}

The variable s1 refers to the String instance created by “Hello”. The object referred to by s2 is created with s1 as an initializer. Thus, the contents of the two String objects are identical, but they are distinct objects. This means that s1 and s2 do not refer to the same objects and are, therefore, not ==, as is shown here by the output of the preceding example:

Hello equals Hello -> true
Hello == Hello -> false

How do you determine what SQL Tables have an identity column programmatically

sys.columns.is_identity = 1

e.g.,

select o.name, c.name
from sys.objects o inner join sys.columns c on o.object_id = c.object_id
where c.is_identity = 1

android.content.res.Resources$NotFoundException: String resource ID #0x0

When you try to set text in Edittext or textview you should pass only String format.

dateTime.setText(app.getTotalDl());

to

dateTime.setText(String.valueOf(app.getTotalDl()));

python replace single backslash with double backslash

Given the source string, manipulation with os.path might make more sense, but here's a string solution;

>>> s=r"C:\Users\Josh\Desktop\\20130216"
>>> '\\\\'.join(filter(bool, s.split('\\')))
'C:\\\\Users\\\\Josh\\\\Desktop\\\\20130216'

Note that split treats the \\ in the source string as a delimited empty string. Using filter gets rid of those empty strings so join won't double the already doubled backslashes. Unfortunately, if you have 3 or more, they get reduced to doubled backslashes, but I don't think that hurts you in a windows path expression.

How to install sklearn?

I would recommend you look at getting the anaconda package, it will install and configure Sklearn and its dependencies.

https://www.continuum.io

Hashing with SHA1 Algorithm in C#

public string Hash(byte [] temp)
{
    using (SHA1Managed sha1 = new SHA1Managed())
    {
        var hash = sha1.ComputeHash(temp);
        return Convert.ToBase64String(hash);
    }
}

EDIT:

You could also specify the encoding when converting the byte array to string as follows:

return System.Text.Encoding.UTF8.GetString(hash);

or

return System.Text.Encoding.Unicode.GetString(hash);

How to filter rows in pandas by regex

Using str slice

foo[foo.b.str[0]=='f']
Out[18]: 
   a    b
1  2  foo
2  3  fat

How to convert minutes to hours/minutes and add various time values together using jQuery?

As the above answer of ConnorLuddy can be slightly improved, there are a minor change to formula to convert minutes to hours:mins format

const convertMinsToHrsMins = (mins) => {
  let h = Math.floor(mins / 60);
  let m = Math.round(mins % 60);
  h = (h < 10) ? ('0' + h) : (h);
  m = (m < 10) ? ('0' + m) : (m);
  return `${h}:${m}`;
}

My theory is that we can not predict that `mins` value will always be an integer.
The added `Math.round` to function will correct the output.
For example: when the minutes=125.3245, the output will be 02:05 with this fix, and 02:05.3245000000000005 without the fix.

Hope that someone need this!

Codesign wants to access key "access" in your keychain, I put in my login password but keeps asking me

For me, the problem was caps lock. and it seems it may ask you a couple of times to input your password or you will have to enter a password once and press always allow.

Get all object attributes in Python?

What you probably want is dir().

The catch is that classes are able to override the special __dir__ method, which causes dir() to return whatever the class wants (though they are encouraged to return an accurate list, this is not enforced). Furthermore, some objects may implement dynamic attributes by overriding __getattr__, may be RPC proxy objects, or may be instances of C-extension classes. If your object is one these examples, they may not have a __dict__ or be able to provide a comprehensive list of attributes via __dir__: many of these objects may have so many dynamic attrs it doesn't won't actually know what it has until you try to access it.

In the short run, if dir() isn't sufficient, you could write a function which traverses __dict__ for an object, then __dict__ for all the classes in obj.__class__.__mro__; though this will only work for normal python objects. In the long run, you may have to use duck typing + assumptions - if it looks like a duck, cross your fingers, and hope it has .feathers.

Force Intellij IDEA to reread all maven dependencies

Go to File | Settings | Build, Execution, Deployment | Build Tools | Maven

Select "Always update snapshots"

Generate sha256 with OpenSSL and C++

Here's the function I personally use - I simply derived it from the function I used for sha-1 hashing:

char *str2sha256( const char *str, int length ) {
  int n;
  SHA256_CTX c;
  unsigned char digest[ SHA256_DIGEST_LENGTH ];
  char *out = (char*) malloc( 33 );

  SHA256_Init( &c );

  while ( length > 0 ) {
    if ( length > 512 ) SHA256_Update( &c, str, 512 );
    else SHA256_Update( &c, str, length );

    length -= 512;
    str += 512;
  }

  SHA256_Final ( digest, &c );

  for ( n = 0; n < SHA256_DIGEST_LENGTH; ++n )
    snprintf( &( out[ n*2 ] ), 16*2, "%02x", (unsigned int) digest[ n ] );

  return out;
}

Display a loading bar before the entire page is loaded

HTML

<div class="preload">
<img src="http://i.imgur.com/KUJoe.gif">
</div>

<div class="content">
I would like to display a loading bar before the entire page is loaded. 
</div>

JAVASCRIPT

$(function() {
    $(".preload").fadeOut(2000, function() {
        $(".content").fadeIn(1000);        
    });
});?

CSS

.content {display:none;}
.preload { 
    width:100px;
    height: 100px;
    position: fixed;
    top: 50%;
    left: 50%;
}
?

DEMO

Create a directory if it does not exist and then create the files in that directory as well

Java 8+ version:

Files.createDirectories(Paths.get("/Your/Path/Here"));

The Files.createDirectories() creates a new directory and parent directories that do not exist. This method does not throw an exception if the directory already exists.

List comprehension on a nested list?

I had a similar problem to solve so I came across this question. I did a performance comparison of Andrew Clark's and narayan's answer which I would like to share.

The primary difference between two answers is how they iterate over inner lists. One of them uses builtin map, while other is using list comprehension. Map function has slight performance advantage to its equivalent list comprehension if it doesn't require the use lambdas. So in context of this question map should perform slightly better than list comprehension.

Lets do a performance benchmark to see if it is actually true. I used python version 3.5.0 to perform all these tests. In first set of tests I would like to keep elements per list to be 10 and vary number of lists from 10-100,000

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,10))]*10]"
>>> 100000 loops, best of 3: 15.2 usec per loop   
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,10))]*10]"
>>> 10000 loops, best of 3: 19.6 usec per loop 

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,10))]*100]"
>>> 100000 loops, best of 3: 15.2 usec per loop
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,10))]*100]"
>>> 10000 loops, best of 3: 19.6 usec per loop 

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,10))]*1000]"
>>> 1000 loops, best of 3: 1.43 msec per loop   
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,10))]*1000]"
>>> 100 loops, best of 3: 1.91 msec per loop

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,10))]*10000]"
>>> 100 loops, best of 3: 13.6 msec per loop   
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,10))]*10000]"
>>> 10 loops, best of 3: 19.1 msec per loop

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,10))]*100000]"
>>> 10 loops, best of 3: 164 msec per loop
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,10))]*100000]"
>>> 10 loops, best of 3: 216 msec per loop

enter image description here

In the next set of tests I would like to raise number of elements per lists to 100.

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,100))]*10]"
>>> 10000 loops, best of 3: 110 usec per loop
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,100))]*10]"
>>> 10000 loops, best of 3: 151 usec per loop

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,100))]*100]"
>>> 1000 loops, best of 3: 1.11 msec per loop
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,100))]*100]"
>>> 1000 loops, best of 3: 1.5 msec per loop

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,100))]*1000]"
>>> 100 loops, best of 3: 11.2 msec per loop
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,100))]*1000]"
>>> 100 loops, best of 3: 16.7 msec per loop

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,100))]*10000]"
>>> 10 loops, best of 3: 134 msec per loop
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,100))]*10000]"
>>> 10 loops, best of 3: 171 msec per loop

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,100))]*100000]"
>>> 10 loops, best of 3: 1.32 sec per loop
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,100))]*100000]"
>>> 10 loops, best of 3: 1.7 sec per loop

enter image description here

Lets take a brave step and modify the number of elements in lists to be 1000

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,1000))]*10]"
>>> 1000 loops, best of 3: 800 usec per loop
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,1000))]*10]"
>>> 1000 loops, best of 3: 1.16 msec per loop

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,1000))]*100]"
>>> 100 loops, best of 3: 8.26 msec per loop
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,1000))]*100]"
>>> 100 loops, best of 3: 11.7 msec per loop

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,1000))]*1000]"
>>> 10 loops, best of 3: 83.8 msec per loop
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,1000))]*1000]"
>>> 10 loops, best of 3: 118 msec per loop

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,1000))]*10000]"
>>> 10 loops, best of 3: 868 msec per loop
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,1000))]*10000]"
>>> 10 loops, best of 3: 1.23 sec per loop

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,1000))]*100000]"
>>> 10 loops, best of 3: 9.2 sec per loop
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,1000))]*100000]"
>>> 10 loops, best of 3: 12.7 sec per loop

enter image description here

From these test we can conclude that map has a performance benefit over list comprehension in this case. This is also applicable if you are trying to cast to either int or str. For small number of lists with less elements per list, the difference is negligible. For larger lists with more elements per list one might like to use map instead of list comprehension, but it totally depends on application needs.

However I personally find list comprehension to be more readable and idiomatic than map. It is a de-facto standard in python. Usually people are more proficient and comfortable(specially beginner) in using list comprehension than map.

Remove scrollbars from textarea

Try the following, not sure which will work for all browsers or the browser you are working with, but it would be best to try all:

<textarea style="overflow:auto"></textarea>

Or

<textarea style="overflow:hidden"></textarea>

...As suggested above

You can also try adding this, I never used it before, just saw it posted on a site today:

<textarea style="resize:none"></textarea>

This last option would remove the ability to resize the textarea. You can find more information on the CSS resize property here

Initialize/reset struct to zero/null

If you have a C99 compliant compiler, you can use

mystruct = (struct x){0};

otherwise you should do what David Heffernan wrote, i.e. declare:

struct x empty = {0};

And in the loop:

mystruct = empty;

Does Enter key trigger a click event?

For angular 6 there is a new way of doing it. On your input tag add

(keyup.enter)="keyUpFunction($event)"

Where keyUpFunction($event) is your function.

instantiate a class from a variable in PHP?

Put the classname into a variable first:

$classname=$var.'Class';

$bar=new $classname("xyz");

This is often the sort of thing you'll see wrapped up in a Factory pattern.

See Namespaces and dynamic language features for further details.

Spring Boot: Cannot access REST Controller on localhost (404)

You can add inside the POM.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <version>XXXXXXXXX</version>
</dependency>

Linux command to list all available commands and aliases

maybe i'm misunderstanding but what if you press Escape until you got the Display All X possibilities ?

AJAX POST and Plus Sign ( + ) -- How to Encode?

To make it more interesting and to hopefully enable less hair pulling for someone else. Using python, built dictionary for a device which we can use curl to configure.

Problem: {"timezone":"+5"} //throws an error " 5"

Solution: {"timezone":"%2B"+"5"} //Works

So, in a nutshell:

var = {"timezone":"%2B"+"5"}
json = JSONEncoder().encode(var)
subprocess.call(["curl",ipaddress,"-XPUT","-d","data="+json])

Thanks to this post!

Pure CSS collapse/expand div

You just need to iterate the anchors in the two links.

<a href="#hide2" class="hide" id="hide2">+</a>
<a href="#show2" class="show" id="show2">-</a>

See this jsfiddle http://jsfiddle.net/eJX8z/

I also added some margin to the FAQ call to improve the format.

Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

Threading Model in UI

Please read the Threading Model in UI applications (old VB link is here) in order to understand basic concepts. The link navigates to page that describes the WPF threading model. However, Windows Forms utilizes the same idea.

The UI Thread

  • There is only one thread (UI thread), that is allowed to access System.Windows.Forms.Control and its subclasses members.
  • Attempt to access member of System.Windows.Forms.Control from different thread than UI thread will cause cross-thread exception.
  • Since there is only one thread, all UI operations are queued as work items into that thread:

enter image description here

enter image description here

BeginInvoke and Invoke methods

enter image description here

Invoke

enter image description here

BeginInvoke

enter image description here

Code solution

Read answers on question How to update the GUI from another thread in C#?. For C# 5.0 and .NET 4.5 the recommended solution is here.

Spring Data JPA find by embedded object property

This method name should do the trick:

Page<QueuedBook> findByBookIdRegion(Region region, Pageable pageable);

More info on that in the section about query derivation of the reference docs.

Enter key press in C#

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)Keys.Enter)
    {
        MessageBox.Show("Enter Key Pressed");
    }
}

This allows you to choose the specific Key you want, without finding the char value of the key.

How to use Python to execute a cURL command?

Some background: I went looking for exactly this question because I had to do something to retrieve content, but all I had available was an old version of python with inadequate SSL support. If you're on an older MacBook, you know what I'm talking about. In any case, curl runs fine from a shell (I suspect it has modern SSL support linked in) so sometimes you want to do this without using requests or urllib2.

You can use the subprocess module to execute curl and get at the retrieved content:

import subprocess

// 'response' contains a []byte with the retrieved content.
// use '-s' to keep curl quiet while it does its job, but
// it's useful to omit that while you're still writing code
// so you know if curl is working
response = subprocess.check_output(['curl', '-s', baseURL % page_num])

Python 3's subprocess module also contains .run() with a number of useful options. I'll leave it to someone who is actually running python 3 to provide that answer.

Wordpress keeps redirecting to install-php after migration

I experienced this issue today and started searching on internet. In my case there was no table in my DB. I forgot to import the tables on the online server. I did it and all works fine.

Sys is undefined

This is going to sound stupid but I had a similar problem with a site being developed in VS2010 and hosted in the VS Dev Server. The page in question had a scriptmanager to create the connection to a wcf service. I added an extra method to the service and this error started appearing.

What fixed it for me was changing from 'Auto-assign Port' to 'Specific port' with a different port number in the oroject Web settings.

I wish I knew why...

How to check if a given directory exists in Ruby

All the other answers are correct, however, you might have problems if you're trying to check directory in a user's home directory. Make sure you expand the relative path before checking:

File.exists? '~/exists'
=> false
File.directory? '~/exists'
=> false
File.exists? File.expand_path('~/exists')
=> true

How to communicate between Docker containers via "hostname"

The new networking feature allows you to connect to containers by their name, so if you create a new network, any container connected to that network can reach other containers by their name. Example:

1) Create new network

$ docker network create <network-name>       

2) Connect containers to network

$ docker run --net=<network-name> ...

or

$ docker network connect <network-name> <container-name>

3) Ping container by name

docker exec -ti <container-name-A> ping <container-name-B> 

64 bytes from c1 (172.18.0.4): icmp_seq=1 ttl=64 time=0.137 ms
64 bytes from c1 (172.18.0.4): icmp_seq=2 ttl=64 time=0.073 ms
64 bytes from c1 (172.18.0.4): icmp_seq=3 ttl=64 time=0.074 ms
64 bytes from c1 (172.18.0.4): icmp_seq=4 ttl=64 time=0.074 ms

See this section of the documentation;

Note: Unlike legacy links the new networking will not create environment variables, nor share environment variables with other containers.

This feature currently doesn't support aliases

First letter capitalization for EditText

For Capitalisation in EditText you can choose the below two input types:

  1. android:inputType="textCapSentences"
  2. android:inputType="textCapWords"

textCapSentences
This will let the first letter of the first word as Capital in every sentence.

textCapWords This will let the first letter of every word as Capital.

If you want both the attributes just use | sign with both the attributes

android:inputType="textCapSentences|textCapWords"

jQuery and TinyMCE: textarea value doesn't submit

That's because it's not a textarea any longer. It's replaced with an iframe (and whatnot), and the serialize function only gets data from form fields.

Add a hidden field to the form:

<input type="hidden" id="question_html" name="question_html" />

Before posting the form, get the data from the editor and put in the hidden field:

$('#question_html').val(tinyMCE.get('question_text').getContent());

(The editor would of course take care of this itself if you posted the form normally, but as you are scraping the form and sending the data yourself without using the form, the onsubmit event on the form is never triggered.)

jQuery AJAX form using mail() PHP script sends email, but POST data from HTML form is undefined

You code should be:

   <section id="right">
      <label for="form_msg">Message</label>
      <textarea name="form_msg" id="#msg_text"></textarea>
      <input id="submit" class="button" name="submit" type="submit" value="Send">
   </section>

Js

var data = {
    name: $("#form_name").val(),
    email: $("#form_email").val(),
    message: $("#msg_text").val()
};
$.ajax({
    type: "POST",
    url: "email.php",
    data: data,
    success: function(){
        $('.success').fadeIn(1000);
    }
});

The PHP:

<?php
if($_POST){
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['text'];

//send email
    mail("[email protected]","My Subject:",$email,$message);
}
?>

Send file using POST from a Python script

The only thing that stops you from using urlopen directly on a file object is the fact that the builtin file object lacks a len definition. A simple way is to create a subclass, which provides urlopen with the correct file. I have also modified the Content-Type header in the file below.

import os
import urllib2
class EnhancedFile(file):
    def __init__(self, *args, **keyws):
        file.__init__(self, *args, **keyws)

    def __len__(self):
        return int(os.fstat(self.fileno())[6])

theFile = EnhancedFile('a.xml', 'r')
theUrl = "http://example.com/abcde"
theHeaders= {'Content-Type': 'text/xml'}

theRequest = urllib2.Request(theUrl, theFile, theHeaders)

response = urllib2.urlopen(theRequest)

theFile.close()


for line in response:
    print line

How to get value of checked item from CheckedListBox?

To get the all selected Items in a CheckedListBox try this:

In this case ths value is a String but it's run with other type of Object:

for (int i = 0; i < myCheckedListBox.Items.Count; i++)
{
    if (myCheckedListBox.GetItemChecked(i) == true)
    {

        MessageBox.Show("This is the value of ceckhed Item " + myCheckedListBox.Items[i].ToString());

    }

}

How to vertically align text with icon font?

Adding to the spans

vertical-align:baseline;

Didn't work for me but

vertical-align:baseline;
vertical-align:-webkit-baseline-middle;

did work (tested on Chrome)

Access parent's parent from javascript object

With the following code you can access the parent of the object:

var Users = function(parent) {
    this.parent = parent;
};
Users.prototype.guys = function(){ 
    this.parent.nameAndDestroy(['test-name-and-destroy']);
};
Users.prototype.girls = function(){ 
    this.parent.kiss(['test-kiss']);
};

var list = {
    users : function() {
        return new Users(this);
    },
    nameAndDestroy : function(group){ console.log(group); },
    kiss : function(group){ console.log(group); }
};

list.users().guys(); // should output ["test-name-and-destroy"]
list.users().girls(); // should output ["test-kiss"]

I would recommend you read about javascript Objects to get to know how you can work with Objects, it helped me a lot. I even found out about functions that I didn't even knew they existed.

401 Unauthorized: Access is denied due to invalid credentials

I had this issue on IIS 10. This is how I fixed it.

  1. Open IIS
  2. Select The Site
  3. Open Authentication
  4. Edit Anonymous Authentication
  5. Select Application Pool Identity

How to create an AVD for Android 4.0

This answer is for creating AVD in Android Studio.

  1. First click on AVD button on your Android Studio top bar.

image 1

  1. In this window click on Create Virtual Device

image 2

  1. Now you will choose hardware profile for AVD and click Next.

image 3

  1. Choose Android Api Version you want in your AVD. Download if no api exist. Click next.

image 4

  1. This is now window for customizing some AVD feature like camera, network, memory and ram size etc. Just keep default and click Finish.

image 5

  1. You AVD is ready, now click on AVD button in Android Studio (same like 1st step). Then you will able to see created AVD in list. Click on Play button on your AVD.

image 6

  1. Your AVD will start soon.

image 7

Best way to convert strings to symbols in hash

Here's a better method, if you're using Rails:

params.symbolize_keys

The end.

If you're not, just rip off their code (it's also in the link):

myhash.keys.each do |key|
  myhash[(key.to_sym rescue key) || key] = myhash.delete(key)
end

Java get String CompareTo as a comparator object

Again, don't need the comparator for Arrays.binarySearch(Object[] a, Object key) so long as the types of objects are comparable, but with lambda expressions this is now way easier.

Simply replace the comparator with the method reference: String::compareTo

E.g.:

Arrays.binarySearch(someStringArray, "The String to find.", String::compareTo);

You could also use

Arrays.binarySearch(someStringArray, "The String to find.", (a,b) -> a.compareTo(b));

but even before lambdas, there were always anonymous classes:

Arrays.binarySearch(
                someStringArray,
                "The String to find.",
                new Comparator<String>() {
                    @Override
                    public int compare(String o1, String o2) {
                        return o1.compareTo(o2);
                    }
                });

How do I fix certificate errors when running wget on an HTTPS URL in Cygwin?

If the problem is that a known root CA is missing and when you are using ubuntu or debian, then you can solve the problem with this one line:

sudo apt-get install ca-certificates

How to include a class in PHP

Include a class example with the use keyword from Command Line Interface:

PHP Namespaces don't work on the commandline unless you also include or require the php file. When the php file is sitting in the webspace where it is interpreted by the php daemon then you don't need the require line. All you need is the 'use' line.

  1. Create a new directory /home/el/bin

  2. Make a new file called namespace_example.php and put this code in there:

    <?php
        require '/home/el/bin/mylib.php';
        use foobarwhatever\dingdong\penguinclass;
    
        $mypenguin = new penguinclass();
        echo $mypenguin->msg();
    ?>
    
  3. Make another file called mylib.php and put this code in there:

    <?php
    namespace foobarwhatever\dingdong;
    class penguinclass 
    {
        public function msg() {
            return "It's a beautiful day chris, come out and play! " . 
                   "NO!  *SLAM!*  taka taka taka taka."; 
        }   
    }
    ?>   
    
  4. Run it from commandline like this:

    el@apollo:~/bin$ php namespace_example.php 
    
  5. Which prints:

    It's a beautiful day chris, come out and play!
    NO!  *SLAM!*  taka taka taka taka
    

See notes on this in the comments here: http://php.net/manual/en/language.namespaces.importing.php

Oracle "SQL Error: Missing IN or OUT parameter at index:: 1"

I had a similar error on my side when I was using JDBC in Java code.

According to this website (the second awnser) it suggest that you are trying to execute the query with a missing parameter.

For instance :

exec SomeStoredProcedureThatReturnsASite( :L_kSite );

You are trying to execute the query without the last parameter.

Maybe in SQLPlus it doesn't have the same requirements, so it might have been a luck that it worked there.

How can I rebuild indexes and update stats in MySQL innoDB?

This is done with

ANALYZE TABLE table_name;

Read more about it here.

ANALYZE TABLE analyzes and stores the key distribution for a table. During the analysis, the table is locked with a read lock for MyISAM, BDB, and InnoDB. This statement works with MyISAM, BDB, InnoDB, and NDB tables.

Why doesn't [01-12] range work as expected?

A character class in regular expressions, denoted by the [...] syntax, specifies the rules to match a single character in the input. As such, everything you write between the brackets specify how to match a single character.

Your pattern, [01-12] is thus broken down as follows:

  • 0 - match the single digit 0
  • or, 1-1, match a single digit in the range of 1 through 1
  • or, 2, match a single digit 2

So basically all you're matching is 0, 1 or 2.

In order to do the matching you want, matching two digits, ranging from 01-12 as numbers, you need to think about how they will look as text.

You have:

  • 01-09 (ie. first digit is 0, second digit is 1-9)
  • 10-12 (ie. first digit is 1, second digit is 0-2)

You will then have to write a regular expression for that, which can look like this:

  +-- a 0 followed by 1-9
  |
  |      +-- a 1 followed by 0-2
  |      |
<-+--> <-+-->
0[1-9]|1[0-2]
      ^
      |
      +-- vertical bar, this roughly means "OR" in this context

Note that trying to combine them in order to get a shorter expression will fail, by giving false positive matches for invalid input.

For instance, the pattern [0-1][0-9] would basically match the numbers 00-19, which is a bit more than what you want.

I tried finding a definite source for more information about character classes, but for now all I can give you is this Google Query for Regex Character Classes. Hopefully you'll be able to find some more information there to help you.

Call a stored procedure with parameter in c#

Here is my technique I'd like to share. Works well so long as your clr property types are sql equivalent types eg. bool -> bit, long -> bigint, string -> nchar/char/varchar/nvarchar, decimal -> money

public void SaveTransaction(Transaction transaction) 
{
    using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString))
    {
        using (var cmd = new SqlCommand("spAddTransaction", con))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            foreach (var prop in transaction.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
                cmd.Parameters.AddWithValue("@" + prop.Name, prop.GetValue(transaction, null));
            con.Open();
            cmd.ExecuteNonQuery();
        }
    }
}

How to check if a registry value exists using C#?

For Registry Key you can check if it is null after getting it. It will be, if it doesn't exist.

For Registry Value you can get names of Values for the current key and check if this array contains the needed Value name.

Example:

public static bool checkMachineType()
{    
    RegistryKey winLogonKey = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\services\pcmcia", true);
    return (winLogonKey.GetValueNames().Contains("Start"));
}

Does C# have a String Tokenizer like Java's?

If you are using C# 3.5 you could write an extension method to System.String that does the splitting you need. You then can then use syntax:

string.SplitByMyTokens();

More info and a useful example from MS here http://msdn.microsoft.com/en-us/library/bb383977.aspx

Is jQuery $.browser Deprecated?

From the official documentation at http://api.jquery.com/jQuery.browser/:

This property was removed in jQuery 1.9 and is available only through the jQuery.migrate plugin.

You can use for example jquery-migrate-1.4.1.js to keep your existing code or plugins that use $.browser still working while you find a way to totally get rid of $.browser from your code in the future.

pandas read_csv and filter columns with usecols

If your csv file contains extra data, columns can be deleted from the DataFrame after import.

import pandas as pd
from StringIO import StringIO

csv = r"""dummy,date,loc,x
bar,20090101,a,1
bar,20090102,a,3
bar,20090103,a,5
bar,20090101,b,1
bar,20090102,b,3
bar,20090103,b,5"""

df = pd.read_csv(StringIO(csv),
        index_col=["date", "loc"], 
        usecols=["dummy", "date", "loc", "x"],
        parse_dates=["date"],
        header=0,
        names=["dummy", "date", "loc", "x"])
del df['dummy']

Which gives us:

                x
date       loc
2009-01-01 a    1
2009-01-02 a    3
2009-01-03 a    5
2009-01-01 b    1
2009-01-02 b    3
2009-01-03 b    5

Maven with Eclipse Juno

You should be able to install m2e (maven project for eclipse) using the Help -> Install New Software dialog. On that dialog open the Juno site (http://download.eclipse.org/releases/juno) and expand the Collaboration group (or type m2e into the filter). Select the two m2e options and follow the installation dialog

How do I lowercase a string in Python?

Don't try this, totally un-recommend, don't do this:

import string
s='ABCD'
print(''.join([string.ascii_lowercase[string.ascii_uppercase.index(i)] for i in s]))

Output:

abcd

Since no one wrote it yet you can use swapcase (so uppercase letters will become lowercase, and vice versa) (and this one you should use in cases where i just mentioned (convert upper to lower, lower to upper)):

s='ABCD'
print(s.swapcase())

Output:

abcd

How get value from URL

Website URL:

http://www.example.com/?id=2

Code:

$id = intval($_GET['id']);
$results = mysql_query("SELECT * FROM next WHERE id=$id");    
while ($row = mysql_fetch_array($results))     
{       
    $url = $row['url'];
    echo $url; //Outputs: 2
}

Define global constants

Below changes works for me on Angular 2 final version:

export class AppSettings {
   public static API_ENDPOINT='http://127.0.0.1:6666/api/';
}

And then in the service:

import {Http} from 'angular2/http';
import {Message} from '../models/message';
import {Injectable} from 'angular2/core';
import {Observable} from 'rxjs/Observable';
import {AppSettings} from '../appSettings';
import 'rxjs/add/operator/map';

@Injectable()
export class MessageService {

    constructor(private http: Http) { }

    getMessages(): Observable<Message[]> {
        return this.http.get(AppSettings.API_ENDPOINT+'/messages')
            .map(response => response.json())
            .map((messages: Object[]) => {
                return messages.map(message => this.parseData(message));
            });
    }

    private parseData(data): Message {
        return new Message(data);
    }
}

Difference between text and varchar (character varying)

In my opinion, varchar(n) has it's own advantages. Yes, they all use the same underlying type and all that. But, it should be pointed out that indexes in PostgreSQL has its size limit of 2712 bytes per row.

TL;DR: If you use text type without a constraint and have indexes on these columns, it is very possible that you hit this limit for some of your columns and get error when you try to insert data but with using varchar(n), you can prevent it.

Some more details: The problem here is that PostgreSQL doesn't give any exceptions when creating indexes for text type or varchar(n) where n is greater than 2712. However, it will give error when a record with compressed size of greater than 2712 is tried to be inserted. It means that you can insert 100.000 character of string which is composed by repetitive characters easily because it will be compressed far below 2712 but you may not be able to insert some string with 4000 characters because the compressed size is greater than 2712 bytes. Using varchar(n) where n is not too much greater than 2712, you're safe from these errors.

How to generate List<String> from SQL query?

Where the data returned is a string; you could cast to a different data type:

(from DataRow row in dataTable.Rows select row["columnName"].ToString()).ToList();

mongodb service is not starting up

Here's a weird one, make sure you have consistent spacing in the config file.

For example:

processManagement:
  timeZoneInfo: /usr/share/zoneinfo

security:
    authorization: 'enabled'

If the authorization key has 4 spaces before it, like above and the rest are 2 spaces then it won't work.

Storing Images in DB - Yea or Nay?

I once worked on an image processing application. We stored the uploaded images in a directory that was something like /images/[today's date]/[id number]. But we also extracted the metadata (exif data) from the images and stored that in the database, along with a timestamp and such.

How to pass password to scp?

just generate a ssh key like:

ssh-keygen -t rsa -C "[email protected]"

copy the content of ~/.ssh/id_rsa.pub and lastly add it to the remote machines ~/.ssh/authorized_keys

make sure remote machine have the permissions 0700 for ~./ssh folder and 0600 for ~/.ssh/authorized_keys

Populate one dropdown based on selection in another

_x000D_
_x000D_
function configureDropDownLists(ddl1, ddl2) {_x000D_
  var colours = ['Black', 'White', 'Blue'];_x000D_
  var shapes = ['Square', 'Circle', 'Triangle'];_x000D_
  var names = ['John', 'David', 'Sarah'];_x000D_
_x000D_
  switch (ddl1.value) {_x000D_
    case 'Colours':_x000D_
      ddl2.options.length = 0;_x000D_
      for (i = 0; i < colours.length; i++) {_x000D_
        createOption(ddl2, colours[i], colours[i]);_x000D_
      }_x000D_
      break;_x000D_
    case 'Shapes':_x000D_
      ddl2.options.length = 0;_x000D_
      for (i = 0; i < shapes.length; i++) {_x000D_
        createOption(ddl2, shapes[i], shapes[i]);_x000D_
      }_x000D_
      break;_x000D_
    case 'Names':_x000D_
      ddl2.options.length = 0;_x000D_
      for (i = 0; i < names.length; i++) {_x000D_
        createOption(ddl2, names[i], names[i]);_x000D_
      }_x000D_
      break;_x000D_
    default:_x000D_
      ddl2.options.length = 0;_x000D_
      break;_x000D_
  }_x000D_
_x000D_
}_x000D_
_x000D_
function createOption(ddl, text, value) {_x000D_
  var opt = document.createElement('option');_x000D_
  opt.value = value;_x000D_
  opt.text = text;_x000D_
  ddl.options.add(opt);_x000D_
}
_x000D_
<select id="ddl" onchange="configureDropDownLists(this,document.getElementById('ddl2'))">_x000D_
  <option value=""></option>_x000D_
  <option value="Colours">Colours</option>_x000D_
  <option value="Shapes">Shapes</option>_x000D_
  <option value="Names">Names</option>_x000D_
</select>_x000D_
_x000D_
<select id="ddl2">_x000D_
</select>
_x000D_
_x000D_
_x000D_

Verify External Script Is Loaded

This was very simple now that I realize how to do it, thanks to all the answers for leading me to the solution. I had to abandon $.getScript() in order to specify the source of the script...sometimes doing things manually is best.

Solution

//great suggestion @Jasper
var len = $('script[src*="Javascript/MyScript.js"]').length; 

if (len === 0) {
        alert('script not loaded');

        loadScript('Javascript/MyScript.js');

        if ($('script[src*="Javascript/MyScript.js"]').length === 0) {
            alert('still not loaded');
        }
        else {
            alert('loaded now');
        }
    }
    else {
        alert('script loaded');
    }


function loadScript(scriptLocationAndName) {
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = scriptLocationAndName;
    head.appendChild(script);
}

CodeIgniter Disallowed Key Characters

I had the same problem thanks to french specials characters. Here is my class in case anybody needs it. It has to be saved here : /application/core/MY_Input.php

(also this extension will report witch character is not allowed in the future)

class MY_Input extends CI_Input {

function __construct() { parent::__construct(); } /** * Clean Keys * * This is a helper function. To prevent malicious users * from trying to exploit keys we make sure that keys are * only named with alpha-numeric text and a few other items. * * @access private * @param string * @return string */ function _clean_input_keys($str) { if ( ! preg_match("/^[a-z0-9:_\/-àâçéèêëîôùû]+$/i", $str)) { exit('Disallowed Key Characters : '.$str); } // Clean UTF-8 if supported if (UTF8_ENABLED === TRUE) { $str = $this->uni->clean_string($str); } return $str; }

}

Read The Friendly Manual about core classes extension : http://ellislab.com/codeigniter/user-guide/general/core_classes.html

SyntaxError: expected expression, got '<'

I solved this problem with my authenticated ASPNET application by adding WebResource.axd as a location on the web.config so that it's authorized for anonymous users

<location path="WebResource.axd">
  <system.web>
    <authorization>
      <allow users="?"/>
    </authorization>
  </system.web>
</location>

Convert JSON String To C# Object

First you have to include library like:

using System.Runtime.Serialization.Json;

DataContractJsonSerializer desc = new DataContractJsonSerializer(typeof(BlogSite));
string json = "{\"Description\":\"Share knowledge\",\"Name\":\"zahid\"}";

using (var ms = new MemoryStream(ASCIIEncoding.ASCII.GetBytes(json)))
{
    BlogSite b = (BlogSite)desc.ReadObject(ms);
    Console.WriteLine(b.Name);
    Console.WriteLine(b.Description);
}

What is the most efficient way to create HTML elements using jQuery?

Question:

What is the most efficient way to create HTML elements using jQuery?

Answer:

Since it's about jQuery then I think it's better to use this (clean) approach (you are using)

$('<div/>', {
    'id':'myDiv',
    'class':'myClass',
    'text':'Text Only',
}).on('click', function(){
    alert(this.id); // myDiv
}).appendTo('body');

DEMO.

This way, you can even use event handlers for the specific element like

$('<div/>', {
    'id':'myDiv',
    'class':'myClass',
    'style':'cursor:pointer;font-weight:bold;',
    'html':'<span>For HTML</span>',
    'click':function(){ alert(this.id) },
    'mouseenter':function(){ $(this).css('color', 'red'); },
    'mouseleave':function(){ $(this).css('color', 'black'); }
}).appendTo('body');

DEMO.

But when you are dealing with lots of dynamic elements, you should avoid adding event handlers in particular element, instead, you should use a delegated event handler, like

$(document).on('click', '.myClass', function(){
    alert(this.innerHTML);
});

var i=1;
for(;i<=200;i++){
    $('<div/>', {
        'class':'myClass',
        'html':'<span>Element'+i+'</span>'
    }).appendTo('body');
}

DEMO.

So, if you create and append hundreds of elements with same class, i.e. (myClass) then less memory will be consumed for event handling, because only one handler will be there to do the job for all dynamically inserted elements.

Update : Since we can use following approach to create a dynamic element

$('<input/>', {
    'type': 'Text',
    'value':'Some Text',
    'size': '30'
}).appendTo("body");

But the size attribute can't be set using this approach using jQuery-1.8.0 or later and here is an old bug report, look at this example using jQuery-1.7.2 which shows that size attribute is set to 30 using above example but using same approach we can't set size attribute using jQuery-1.8.3, here is a non-working fiddle. So, to set the size attribute, we can use following approach

$('<input/>', {
    'type': 'Text',
    'value':'Some Text',
    attr: { size: "30" }
}).appendTo("body");

Or this one

$('<input/>', {
    'type': 'Text',
    'value':'Some Text',
    prop: { size: "30" }
}).appendTo("body");

We can pass attr/prop as a child object but it works in jQuery-1.8.0 and later versions check this example but it won't work in jQuery-1.7.2 or earlier (not tested in all earlier versions).

BTW, taken from jQuery bug report

There are several solutions. The first is to not use it at all, since it doesn't save you any space and this improves the clarity of the code:

They advised to use following approach (works in earlier ones as well, tested in 1.6.4)

$('<input/>')
.attr( { type:'text', size:50, autofocus:1 } )
.val("Some text").appendTo("body");

So, it is better to use this approach, IMO. This update is made after I read/found this answer and in this answer shows that if you use 'Size'(capital S) instead of 'size' then it will just work fine, even in version-2.0.2

$('<input>', {
    'type' : 'text',
    'Size' : '50', // size won't work
    'autofocus' : 'true'
}).appendTo('body');

Also read about prop, because there is a difference, Attributes vs. Properties, it varies through versions.

Random number generator only generating one random number

There are a lot of solutions, here one: if you want only number erase the letters and the method receives a random and the result length.

public String GenerateRandom(Random oRandom, int iLongitudPin)
{
    String sCharacters = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
    int iLength = sCharacters.Length;
    char cCharacter;
    int iLongitudNuevaCadena = iLongitudPin; 
    String sRandomResult = "";
    for (int i = 0; i < iLongitudNuevaCadena; i++)
    {
        cCharacter = sCharacters[oRandom.Next(iLength)];
        sRandomResult += cCharacter.ToString();
    }
    return (sRandomResult);
}

open link in iframe

Try this:

<iframe name="iframe1" src="target.html"></iframe>

<a href="link.html" target="iframe1">link</a>

The "target" attribute should open in the iframe.

Create autoincrement key in Java DB using NetBeans IDE

I couldn't get the accepted answer to work using the Netbeans IDE "Create Table" GUI, and I'm on Netbeans 8.2. To get it to working, create the id column with the following options e.g.

enter image description here

and then use 'New Entity Classes from Database' option to generate the entity for the table (I created a simple table called PERSON with an ID column created exactly as above and a NAME column which is simple varchar(255) column). These generated entities leave it to the user to add the auto generated id mechanism.

GENERATION.AUTO seems to try and use sequences which Derby doesn't seem to like (error stating failed to generate sequence/sequence does not exist), GENERATION.SEQUENCE therefore doesn't work either, GENERATION.IDENTITY doesn't work (get error stating ID is null), so that leaves GENERATION.TABLE.

Set your persistence unit's 'Table Generation Strategy' button to Create. This will create tables that don't exist in the DB when your jar is run (loaded?) i.e. the table your PU needs to create in order to store ID increments. In your entity replace the generated annotations above your id field with the following...

enter image description here

I also created a controller for my entity class using 'JPA Controller Classes from Entity Classes' option. I then create a simple main class to test the id was auto generated i.e.

enter image description here

The result is that the PERSON_ID_TABLE is generated correctly and my PERSON table has two PERSON entries in it with correct, auto generated ids.

How to start new activity on button click

You can try this code:

Intent myIntent = new Intent();
FirstActivity.this.SecondActivity(myIntent);

Visibility of global variables in imported modules

Since globals are module specific, you can add the following function to all imported modules, and then use it to:

  • Add singular variables (in dictionary format) as globals for those
  • Transfer your main module globals to it .

addglobals = lambda x: globals().update(x)

Then all you need to pass on current globals is:

import module

module.addglobals(globals())

Selenium and xPath - locating a link by containing text

@FindBy(xpath = "//span[@class='y2' and contains(text(), 'Your Text')] ") 
private WebElementFacade emailLinkToVerifyAccount;

This approach will work for you, hopefully.

onclick event pass <li> id or value

Try like this...

<script>
function getPaging(str) {
  $("#loading-content").load("dataSearch.php?"+str, hideLoader);
}
</script>

<li onclick="getPaging(this.id)" id="1">1</li>
<li onclick="getPaging(this.id)" id="2">2</li>

or unobtrusively

$(function() {
  $("li").on("click",function() {
    showLoader();
    $("#loading-content").load("dataSearch.php?"+this.id, hideLoader);
  });
});

using just

<li id="1">1</li>
<li id="2">2</li>

How to read files and stdout from a running Docker container

A bit late but this is what I'm doing with journald. It's pretty powerful.

You need to be running your docker containers on an OS with systemd-journald.

docker run -d --log-driver=journald myapp

This pipes the whole lot into host's journald which takes care of stuff like log pruning, storage format etc and gives you some cool options for viewing them:

journalctl CONTAINER_NAME=myapp -f

which will feed it to your console as it is logged,

journalctl CONTAINER_NAME=myapp > output.log

which gives you the whole lot in a file to take away, or

journalctl CONTAINER_NAME=myapp --since=17:45

Plus you can still see the logs via docker logs .... if that's your preference.

No more > my.log or -v "/apps/myapp/logs:/logs" etc

Push method in React Hooks (useState)?

I tried the above methods for pushing an object into an array of objects in useState but had the following error when using TypeScript:

Type 'TxBacklog[] | undefined' must have a 'Symbol.iterator' method that returns an iterator.ts(2488)

The setup for the tsconfig.json was apparently right:

{
   "compilerOptions": {
   "target": "es6",
   "lib": [
      "dom",
      "dom.iterable",
      "esnext",
      "es6",
],

This workaround solved the problem (my sample code):

Interface:

   interface TxBacklog {
      status: string,
      txHash: string,
   }

State variable:

    const [txBacklog, setTxBacklog] = React.useState<TxBacklog[]>();

Push new object into array:

    // Define new object to be added
    const newTx = {
       txHash: '0x368eb7269eb88ba86..',
       status: 'pending'
    };
    // Push new object into array
    (txBacklog) 
       ? setTxBacklog(prevState => [ ...prevState!, newTx ])
       : setTxBacklog([newTx]);

Bootstrap 4 img-circle class not working

It's now called rounded-circle as explained here in the BS4 docs

<img src="img/gallery2.JPG" class="rounded-circle">

Demo

Get driving directions using Google Maps API v2

You can also try the following project that aims to help use that api. It's here:https://github.com/MathiasSeguy-Android2EE/GDirectionsApiUtils

How it works, definitly simply:

public class MainActivity extends ActionBarActivity implements DCACallBack{
/**
 * Get the Google Direction between mDevice location and the touched location using the     Walk
 * @param point
 */
private void getDirections(LatLng point) {
     GDirectionsApiUtils.getDirection(this, mDeviceLatlong, point,     GDirectionsApiUtils.MODE_WALKING);
}

/*
 * The callback
 * When the direction is built from the google server and parsed, this method is called and give you the expected direction
 */
@Override
public void onDirectionLoaded(List<GDirection> directions) {        
    // Display the direction or use the DirectionsApiUtils
    for(GDirection direction:directions) {
        Log.e("MainActivity", "onDirectionLoaded : Draw GDirections Called with path " + directions);
        GDirectionsApiUtils.drawGDirection(direction, mMap);
    }
}

Groovy / grails how to determine a data type?

You can use the Membership Operator isCase() which is another groovy way:

assert Date.isCase(new Date())

Difference between adjustResize and adjustPan in android?

You can use android:windowSoftInputMode="stateAlwaysHidden|adjustResize" in AndroidManifest.xml for your current activity, and use android:fitsSystemWindows="true" in styles or rootLayout.

List of Java processes

Starting from Java 7, the simplest way and less error prone is to simply use the command jcmd that is part of the JDK such that it will work the same way on all OS.

Example:

> jcmd
5485 sun.tools.jcmd.JCmd
2125 MyProgram

jcmd allows to send diagnostic command requests to a running Java Virtual Machine (JVM).

More details about how to use jcmd.

See also the jcmd Utility

apt-get for Cygwin?

you can always make a bash alias to setup*.exe files in $home/.bashrc

cygwin 32bit

alias cyg-get="/cygdrive/c/cygwin/setup-x86.exe -q -P"

cygwin 64bit

alias cyg-get="/cygdrive/c/cygwin64/setup-x86_64.exe -q -P"

now you can install packages with

cyg-get <package>

mysqli_fetch_array while loop columns

I think this would be a more simpler way of outputting your results.

Sorry for using my own data should be easy to replace .

$query = "SELECT * FROM category ";

$result = mysqli_query($connection, $query);


    while($row = mysqli_fetch_assoc($result))
    {
        $cat_id = $row['cat_id'];
        $cat_title = $row['cat_title'];

        echo $cat_id . " " . $cat_title  ."<br>";
    }

This would output :

  • -ID Title
  • -1 Gary
  • -2 John
  • -3 Michaels

Focus Next Element In Tab Index

It seems that you can check the tabIndex property of an element to determine if it is focusable. An element that is not focusable has a tabindex of "-1".

Then you just need to know the rules for tab stops:

  • tabIndex="1" has the highest priorty.
  • tabIndex="2" has the next highest priority.
  • tabIndex="3" is next, and so on.
  • tabIndex="0" (or tabbable by default) has the lowest priority.
  • tabIndex="-1" (or not tabbable by default) does not act as a tab stop.
  • For two elements that have the same tabIndex, the one that appears first in the DOM has the higher priority.

Here is an example of how to build the list of tab stops, in sequence, using pure Javascript:

function getTabStops(o, a, el) {
    // Check if this element is a tab stop
    if (el.tabIndex > 0) {
        if (o[el.tabIndex]) {
            o[el.tabIndex].push(el);
        } else {
            o[el.tabIndex] = [el];
        }
    } else if (el.tabIndex === 0) {
        // Tab index "0" comes last so we accumulate it seperately
        a.push(el);
    }
    // Check if children are tab stops
    for (var i = 0, l = el.children.length; i < l; i++) {
        getTabStops(o, a, el.children[i]);
    }
}

var o = [],
    a = [],
    stops = [],
    active = document.activeElement;

getTabStops(o, a, document.body);

// Use simple loops for maximum browser support
for (var i = 0, l = o.length; i < l; i++) {
    if (o[i]) {
        for (var j = 0, m = o[i].length; j < m; j++) {
            stops.push(o[i][j]);
        }
    }
}
for (var i = 0, l = a.length; i < l; i++) {
    stops.push(a[i]);
}

We first walk the DOM, collecting up all tab stops in sequence with their index. We then assemble the final list. Notice that we add the items with tabIndex="0" at the very end of the list, after the items with a tabIndex of 1, 2, 3, etc.

For a fully working example, where you can tab around using the "enter" key, check out this fiddle.

Convert spark DataFrame column to python list

Let's create the dataframe in question

df_test = spark.createDataFrame(
    [
        (1, 5),
        (2, 9),
        (3, 3),
        (4, 1),
    ],
    ['mvv', 'count']
)
df_test.show()

Which gives

+---+-----+
|mvv|count|
+---+-----+
|  1|    5|
|  2|    9|
|  3|    3|
|  4|    1|
+---+-----+

and then apply rdd.flatMap(f).collect() to get the list

test_list = df_test.select("mvv").rdd.flatMap(list).collect()
print(type(test_list))
print(test_list)

which gives

<type 'list'>
[1, 2, 3, 4]

Where is my .vimrc file?

I tried everything in the previous answer and couldn't find a .vimrc file, so I had to make one.

I copied the example file, cp vimrc_example.vim ~/.vimrc.

I had to create the file, copying from /usr/share/vim/vim74/vimrc_example.vim to ~/.vimrc. Those were the instructions in the vimrc_example file.

My solution is for Unix for other operating systems. According to the Vim documentation, your destination path should be as follows:

    For Unix and OS/2   : ~/.vimrc
    For Amiga           : s:.vimrc
    For MS-DOS and Win32: $VIM\_vimrc
    For OpenVMS         : sys$login:.vimrc

How can I set the 'backend' in matplotlib in Python?

This can also be set in the configuration file matplotlibrc (as explained in the error message), for instance:

# The default backend; one of GTK GTKAgg GTKCairo GTK3Agg GTK3Cairo
# CocoaAgg MacOSX Qt4Agg Qt5Agg TkAgg WX WXAgg Agg Cairo GDK PS PDF SVG
backend : Agg

That way, the backend does not need to be hardcoded if the code is shared with other people. For more information, check the documentation.

How to get AM/PM from a datetime in PHP

It is quite easy. Assuming you have a field(dateposted) with the type "timestamp" in your database table already queried and you want to display it, have it formated and also have the AM/PM, all you need do is shown below.

     <?php
     echo date("F j, Y h:m:s A" ,strtotime($row_rshearing['dateposted'])); 


    ?>

Note: Your OUTPUT should look some what like this depending on the date posted

May 21, 2014 03:05:27 PM

regex string replace

Just change + to -:

str = str.replace(/[^a-z0-9-]/g, "");

You can read it as:

  1. [^ ]: match NOT from the set
  2. [^a-z0-9-]: match if not a-z, 0-9 or -
  3. / /g: do global match

More information:

Cannot bulk load. Operating system error code 5 (Access is denied.)

  1. Go to start run=>services.msc=>SQL SERVER(MSSQLSERVER) stop the service
  2. Right click on SQL SERVER(MSSQLSERVER)=> properties=>LogOn Tab=>Local System Account=>OK
  3. Restart the SQL server Management Studio.

HTML: how to force links to open in a new tab, not new window

The way the browser handles new windows vs new tab is set in the browser's options and can only be changed by the user.

Command to find information about CPUs on a UNIX machine

Firstly, it probably depends which version of Solaris you're running, but also what hardware you have.

On SPARC at least, you have psrinfo to show you processor information, which run on its own will show you the number of CPUs the machine sees. psrinfo -p shows you the number of physical processors installed. From that you can deduce the number of threads/cores per physical processors.

prtdiag will display a fair bit of info about the hardware in your machine. It looks like on a V240 you do get memory channel info from prtdiag, but you don't on a T2000. I guess that's an architecture issue between UltraSPARC IIIi and UltraSPARC T1.

What is the Java equivalent of PHP var_dump?

The apache commons lang package provides such a class which can be used to build up a default toString() method using reflection to get the values of fields. Just have a look at this.

Can we define min-margin and max-margin, max-padding and min-padding in css?

Ideally, margins in CSS containers should collapse, so you can define a parent container which sets its margins(s) to the minimum you want, and then use the margin(s) you want for the child, and the content of the child will use the larger margins between the parent and child margin:

  • if the child margin(s) are smaller than the parent margin(s)+its padding(s), then the child margins(s) will have no effect.

  • if the child margin(s) are larger than the parent margin(s)+its padding(s), then the parent padding(s) should be increased to fit.

This is still frequently not working as intended in CSS: currently CSS allows margin(s) of a child to collapse into the margin(s) of the parent (extending them if necesary), only if the parent defines NO padding and NO border and no intermediate sibling content exist in the parent between the child and the begining of the content box of the parent; however there may be floatting or positioned sibling elements, which are ignored for computing margins, unless they use "clear:" to also extend the parent's content-box and compltely fit their own content vertically in it (only the parent's height of the content-box is increased for the top-to-bottom or bottom-to-top block-direction of its content box, or only the parent's width for the left-to-right or right-to-left block-direction; the inline-direction of the parent's content-box plays no role) .

So if the parent defines only 1px of padding, or only 1px of border, then this stops the child from collapsing its margin into the parent's margin. Instead the child margins will take effect from the content box of the parent (or the border box of the intermediate sibling content if there's any one). This means that any non-null border or non-null padding in the parent is treated by the child as if this was a sibling content in the same parent.

So this simple solution should work: use an additional parent without any border or padding to set the minimum margin to nest the child element in it; you can still add borders or paddings to the child (if needed) where you'll defining its own secondary margin (collapsing into the parent(s) margins) !

Note that a child element may collapse its margin(s) into several levels of parents ! This means that you can define several minimums (e.g. for the minimum between 3 values, use two levels of parents to contain the child).

Sometimes 3 or more values are needed to account for: the viewport width, the document width, the section container width, the presence or absence of external floats stealing space in the container, and the minimum width needed for the child content itself. All these widths may be variable and may depend as well on the kind of browser used (including its accessibility settings, such as text zoom, or "Hi-DPI" adjustments of sizes in renderers depending on capabilities of the target viewing device, or sometimes because there's a user-tunable choice of layouts such as personal "skins" or other user's preferences, or the set of available fonts on the final rendering host, which means that exact font sizes are hard to predict safely, to match exact sizes in "pixels" for images or borders ; as well users have a wide variety of screen sizes or paper sizes if printing, and orientations ; scrolling is also not even available or possible to compensate, and truncation of overflowing contents is most often undesirable; as well using excessive "clears" is wasting space and makes the rendered document much less accessible).

We need to save space, without packing too much info and keeping clarity fore readers, and ease of navigation : a layout is a constant tradeoff, between saving space and showing more information at once to avoid additional scrolling or navigation to other pages, and keeping the packed info displayed easy to navigate or interact with).

But HTML is often not enough flexible for all goals, and even if it offers some advanced features, they becomes difficult to author or to maintain/change the documents (or the infos they contain), or readapt the content later for other goals or presentations. Keeping things simple avoids this issue and if we use these simple tricks that have nearly no cost and are easy to understand, we should use them (this will always save lot of precious time, including for web designers).

java.lang.IllegalAccessError: tried to access method

This happened to me when I had a class in one jar trying to access a private method in a class from another jar. I simply changed the private method to public, recompiled and deployed, and it worked ok afterwards.

Get Absolute URL from Relative path (refactored method)

check the following code to retrieve absolute Url :

Page.Request.Url.AbsoluteUri

I hope to be useful.

Detecting negative numbers

if ($profitloss < 0)
{
   echo "The profitloss is negative";
}

Edit: I feel like this was too simple an answer for the rep so here's something that you may also find helpful.

In PHP we can find the absolute value of an integer by using the abs() function. For example if I were trying to work out the difference between two figures I could do this:

$turnover = 10000;
$overheads = 12500;

$difference = abs($turnover-$overheads);

echo "The Difference is ".$difference;

This would produce The Difference is 2500.

How do I make a fully statically linked .exe with Visual Studio Express 2005?

For the C-runtime go to the project settings, choose C/C++ then 'Code Generation'. Change the 'runtime library' setting to 'multithreaded' instead of 'multithreaded dll'.

If you are using any other libraries you may need to tell the linker to ignore the dynamically linked CRT explicitly.

How do you fade in/out a background color using jquery?

I wrote a super simple jQuery plugin to accomplish something similar to this. I wanted something really light weight (it's 732 bytes minified), so including a big plugin or UI was out of the question for me. It's still a little rough around the edges, so feedback is welcome.

You can checkout the plugin here: https://gist.github.com/4569265.

Using the plugin, it would be a simple matter to create a highlight effect by changing the background color and then adding a setTimeout to fire the plugin to fade back to the original background color.

How to enter quotes in a Java string?

In Java, you can escape quotes with \:

String value = " \"ROM\" ";

Android 5.0 - Add header/footer to a RecyclerView

You can used this GitHub library allowing to add Header and/or Footer in your RecyclerView in the simplest way possible.

You need to add HFRecyclerView library in your project or you can also grab it from Gradle:

compile 'com.mikhaellopez:hfrecyclerview:1.0.0'

This is a result in image:

Preview

EDIT:

If you just want to add a margin at the top and/or bottom with this library: SimpleItemDecoration:

int offsetPx = 10;
recyclerView.addItemDecoration(new StartOffsetItemDecoration(offsetPx));
recyclerView.addItemDecoration(new EndOffsetItemDecoration(offsetPx));

W3WP.EXE using 100% CPU - where to start?

  1. Standard Windows performance counters (look for other correlated activity, such as many GET requests, excessive network or disk I/O, etc); you can read them from code as well as from perfmon (to trigger data collection if CPU use exceeds a threshold, for example)
  2. Custom performance counters (particularly to time for off-box requests and other calls where execution time is uncertain)
  3. Load testing, using tools such as Visual Studio Team Test or WCAT
  4. If you can test on or upgrade to IIS 7, you can configure Failed Request Tracing to generate a trace if requests take more a certain amount of time
  5. Use logparser to see which requests arrived at the time of the CPU spike
  6. Code reviews / walk-throughs (in particular, look for loops that may not terminate properly, such as if an error happens, as well as locks and potential threading issues, such as the use of statics)
  7. CPU and memory profiling (can be difficult on a production system)
  8. Process Explorer
  9. Windows Resource Monitor
  10. Detailed error logging
  11. Custom trace logging, including execution time details (perhaps conditional, based on the CPU-use perf counter)
  12. Are the errors happening when the AppPool recycles? If so, it could be a clue.

Hash table runtime complexity (insert, search and delete)

Perhaps you were looking at the space complexity? That is O(n). The other complexities are as expected on the hash table entry. The search complexity approaches O(1) as the number of buckets increases. If at the worst case you have only one bucket in the hash table, then the search complexity is O(n).

Edit in response to comment I don't think it is correct to say O(1) is the average case. It really is (as the wikipedia page says) O(1+n/k) where K is the hash table size. If K is large enough, then the result is effectively O(1). But suppose K is 10 and N is 100. In that case each bucket will have on average 10 entries, so the search time is definitely not O(1); it is a linear search through up to 10 entries.

How do I convert from int to String?

It's acceptable, but I've never written anything like that. I'd prefer this:

String strI = Integer.toString(i);

How can I load webpage content into a div on page load?

With jQuery, it is possible, however not using ajax.

function LoadPage(){
  $.get('http://a_site.com/a_page.html', function(data) {
    $('#siteloader').html(data);
  });
}

And then place onload="LoadPage()" in the body tag.

Although if you follow this route, a php version might be better:

echo htmlspecialchars(file_get_contents("some URL"));

How can I catch a ctrl-c event?

signal isn't the most reliable way as it differs in implementations. I would recommend using sigaction. Tom's code would now look like this :

#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

void my_handler(int s){
           printf("Caught signal %d\n",s);
           exit(1); 

}

int main(int argc,char** argv)
{

   struct sigaction sigIntHandler;

   sigIntHandler.sa_handler = my_handler;
   sigemptyset(&sigIntHandler.sa_mask);
   sigIntHandler.sa_flags = 0;

   sigaction(SIGINT, &sigIntHandler, NULL);

   pause();

   return 0;    
}

How do I generate random number for each row in a TSQL Select?

Update my_table set my_field = CEILING((RAND(CAST(NEWID() AS varbinary)) * 10))

Number between 1 and 10.

PHP Check for NULL

Make sure that the value of the column is really NULL and not an empty string or 0.

Should I use @EJB or @Inject

@Inject can inject any bean, while @EJB can only inject EJBs. You can use either to inject EJBs, but I'd prefer @Inject everywhere.

Detect element content changes with jQuery

Try the livequery plugin. That seems to work for something similar I am doing.

http://docs.jquery.com/Plugins/livequery

How do I create a custom Error in JavaScript?

This is my implementation:

class HttpError extends Error {
  constructor(message, code = null, status = null, stack = null, name = null) {
    super();
    this.message = message;
    this.status = 500;

    this.name = name || this.constructor.name;
    this.code = code || `E_${this.name.toUpperCase()}`;
    this.stack = stack || null;
  }

  static fromObject(error) {
    if (error instanceof HttpError) {
      return error;
    }
    else {
      const { message, code, status, stack } = error;
      return new ServerError(message, code, status, stack, error.constructor.name);
    }
  }

  expose() {
    if (this instanceof ClientError) {
      return { ...this };
    }
    else {
      return {
        name: this.name,
        code: this.code,
        status: this.status,
      }
    }
  }
}

class ServerError extends HttpError {}

class ClientError extends HttpError { }

class IncorrectCredentials extends ClientError {
  constructor(...args) {
    super(...args);
    this.status = 400;
  }
}

class ResourceNotFound extends ClientError {
  constructor(...args) {
    super(...args);
    this.status = 404;
  }
}

Example usage #1:

app.use((req, res, next) => {
  try {
    invalidFunction();
  }
  catch (err) {
    const error = HttpError.fromObject(err);
    return res.status(error.status).send(error.expose());
  }
});

Example usage #2:

router.post('/api/auth', async (req, res) => {
  try {
    const isLogged = await User.logIn(req.body.username, req.body.password);

    if (!isLogged) {
      throw new IncorrectCredentials('Incorrect username or password');
    }
    else {
      return res.status(200).send({
        token,
      });
    }
  }
  catch (err) {
    const error = HttpError.fromObject(err);
    return res.status(error.status).send(error.expose());
  }
});

How to thoroughly purge and reinstall postgresql on ubuntu?

Following ae the steps i followed to uninstall and reinstall. Which worked for me.

First remove the installed postgres :-

sudo apt-get purge postgr*

sudo apt-get autoremove

Then install 'synaptic':

sudo apt-get install synaptic

sudo apt-get update

Then install postgres

sudo apt-get install postgresql postgresql-contrib

Submitting a form on 'Enter' with jQuery?

I found out today the keypress event is not fired when hitting the Enter key, so you might want to switch to keydown() or keyup() instead.

My test script:

        $('.module input').keydown(function (e) {
            var keyCode = e.which;
            console.log("keydown ("+keyCode+")")
            if (keyCode == 13) {
                console.log("enter");
                return false;
            }
        });
        $('.module input').keyup(function (e) {
            var keyCode = e.which;
            console.log("keyup ("+keyCode+")")
            if (keyCode == 13) {
                console.log("enter");
                return false;
            }
        });
        $('.module input').keypress(function (e) {
            var keyCode = e.which;
            console.log("keypress ("+keyCode+")");
            if (keyCode == 13) {
                console.log("Enter");
                return false;
            }
        });

The output in the console when typing "A Enter B" on the keyboard:

keydown (65)
keypress (97)
keyup (65)

keydown (13)
enter
keyup (13)
enter

keydown (66)
keypress (98)
keyup (66)

You see in the second sequence the 'keypress' is missing, but keydown and keyup register code '13' as being pressed/released. As per jQuery documentation on the function keypress():

Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.

Tested on IE11 and FF61 on Server 2012 R2

java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient

I was facing the same issue. In my case, I had a dependency of httpclient with an older version while sendgrid required a newer version of httpclient. Just make sure that the version of httpclient is correct in your dependencies and it would work fine.

How to generate and validate a software license key?

I solved it by interfacing my program with a discord server, where it checks in a specific chat if the product key entered by the user exists and is still valid. In this way to receive a product key the user would be forced to hack discord and it is very difficult.

Git command to display HEAD commit id?

Play with Bash:

git show HEAD | sed -n 1p | cut -d " " -f 2

Why extend the Android Application class?

Introduction:

enter image description here

  1. If we consider an apk file in our mobile, it is comprised of multiple useful blocks such as, Activitys, Services and others.
  2. These components do not communicate with each other regularly and not forget they have their own life cycle. which indicate that they may be active at one time and inactive the other moment.

Requirements:

  1. Sometimes we may require a scenario where we need to access a variable and its states across the entire Application regardless of the Activity the user is using,
  2. An example is that a user might need to access a variable that holds his personnel information (e.g. name) that has to be accessed across the Application,
  3. We can use SQLite but creating a Cursor and closing it again and again is not good on performance,
  4. We could use Intents to pass the data but it's clumsy and activity itself may not exist at a certain scenario depending on the memory-availability.

Uses of Application Class:

  1. Access to variables across the Application,
  2. You can use the Application to start certain things like analytics etc. since the application class is started before Activitys or Servicess are being run,
  3. There is an overridden method called onConfigurationChanged() that is triggered when the application configuration is changed (horizontal to vertical & vice-versa),
  4. There is also an event called onLowMemory() that is triggered when the Android device is low on memory.

Inserting Data into Hive Table

I think the best way is:
a) Copy data into HDFS (if it is not already there)
b) Create external table over your CSV like this

CREATE EXTERNAL TABLE TableName (id int, name string)
ROW FORMAT DELIMITED   
FIELDS TERMINATED BY ',' 
LINES TERMINATED BY '\n'
STORED AS TEXTFILE
LOCATION 'place in HDFS';

c) You can start using TableName already by issuing queries to it.
d) if you want to insert data into other Hive table:

insert overwrite table finalTable select * from table name;

Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments

onActivityCreated() - Deprecated

onActivityCreated() is now deprecated as Fragments Version 1.3.0-alpha02

The onActivityCreated() method is now deprecated. Code touching the fragment's view should be done in onViewCreated() (which is called immediately before onActivityCreated()) and other initialization code should be in onCreate(). To receive a callback specifically when the activity's onCreate() is complete, a LifeCycleObserver should be registered on the activity's Lifecycle in onAttach(), and removed once the onCreate() callback is received.

Detailed information can be found here

ssl_error_rx_record_too_long and Apache SSL

In my case I had to change the <VirtualHost *> back to <VirtualHost *:80> (which is the default on Ubuntu). Otherwise, the port 443 wasn't using SSL and was sending plain HTML back to the browser.

You can check whether this is your case quite easily: just connect to your server http://www.example.com:443. If you see plain HTML, your Apache is not using SSL on port 443 at all, most probably due to a VirtualHost misconfiguration.

Cheers!

C# code to validate email address

For the simple email like [email protected], below code is sufficient. 

 public static bool ValidateEmail(string email)
        {
            System.Text.RegularExpressions.Regex emailRegex = new System.Text.RegularExpressions.Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
            System.Text.RegularExpressions.Match emailMatch = emailRegex.Match(email);
            return emailMatch.Success;
        }

ModelState.IsValid == false, why?

About "can it be that 0 errors and IsValid == false": here's MVC source code from https://github.com/Microsoft/referencesource/blob/master/System.Web/ModelBinding/ModelStateDictionary.cs#L37-L41

public bool IsValid {
    get {
        return Values.All(modelState => modelState.Errors.Count == 0);
    }
}

Now, it looks like it can't be. Well, that's for ASP.NET MVC v1.

creating Hashmap from a JSON String

Parse the JSONObject and create HashMap

public static void jsonToMap(String t) throws JSONException {

        HashMap<String, String> map = new HashMap<String, String>();
        JSONObject jObject = new JSONObject(t);
        Iterator<?> keys = jObject.keys();

        while( keys.hasNext() ){
            String key = (String)keys.next();
            String value = jObject.getString(key); 
            map.put(key, value);

        }

        System.out.println("json : "+jObject);
        System.out.println("map : "+map);
    }

Tested output:

json : {"phonetype":"N95","cat":"WP"}
map : {cat=WP, phonetype=N95}

How can I change CSS display none or block property using jQuery?

In case you want to hide and show an element, depending on whether it is already visible or not, you can use toggle instead of .hide() and .show()

$('elem').toggle();

Python 3 Float Decimal Points/Precision

The simple way to do this is by using the round buit-in.

round(2.6463636263,2) would be displayed as 2.65.

How to easily map c++ enums to strings

MSalters solution is a good one but basically re-implements boost::assign::map_list_of. If you have boost, you can use it directly:

#include <boost/assign/list_of.hpp>
#include <boost/unordered_map.hpp>
#include <iostream>

using boost::assign::map_list_of;

enum eee { AA,BB,CC };

const boost::unordered_map<eee,const char*> eeeToString = map_list_of
    (AA, "AA")
    (BB, "BB")
    (CC, "CC");

int main()
{
    std::cout << " enum AA = " << eeeToString.at(AA) << std::endl;
    return 0;
}

Setting Windows PATH for Postgres tools

Incase any one still wondering how to add environment variables then please use this link to add variables. Link: https://sqlbackupandftp.com/blog/setting-windows-path-for-postgres-tools

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

For users of SQL 2000, the actual command that will provide this information is:

select c.text
from sysobjects     o
join syscomments    c on c.id = o.id
where o.name = '<view_name_here>'
  and o.type      = 'V'

What does LayoutInflater in Android do?

What inflater does

It takes a xml layout as input (say) and converts it to View object.

Why needed

Let us think a scenario where we need to create a custom listview. Now each row should be custom. But how can we do it. Its not possible to assign a xml layout to a row of listview. So, we create a View object. Thus we can access the elements in it (textview,imageview etc) and also assign the object as row of listview

So, whenever we need to assign view type object somewhere and we have our custom xml design we just convert it to object by inflater and use it.

How do I change the background color of a plot made with ggplot2

Here's a custom theme to make the ggplot2 background white and a bunch of other changes that's good for publications and posters. Just tack on +mytheme. If you want to add or change options by +theme after +mytheme, it will just replace those options from +mytheme.

library(ggplot2)
library(cowplot)
theme_set(theme_cowplot())

mytheme = list(
    theme_classic()+
        theme(panel.background = element_blank(),strip.background = element_rect(colour=NA, fill=NA),panel.border = element_rect(fill = NA, color = "black"),
              legend.title = element_blank(),legend.position="bottom", strip.text = element_text(face="bold", size=9),
              axis.text=element_text(face="bold"),axis.title = element_text(face="bold"),plot.title = element_text(face = "bold", hjust = 0.5,size=13))
)

ggplot(data=data.frame(a=c(1,2,3), b=c(2,3,4)), aes(x=a, y=b)) + mytheme + geom_line()

custom ggplot theme

Spark dataframe: collect () vs select ()

Actions vs Transformations

  • Collect (Action) - Return all the elements of the dataset as an array at the driver program. This is usually useful after a filter or other operation that returns a sufficiently small subset of the data.

spark-sql doc

select(*cols) (transformation) - Projects a set of expressions and returns a new DataFrame.

Parameters: cols – list of column names (string) or expressions (Column). If one of the column names is ‘*’, that column is expanded to include all columns in the current DataFrame.**

df.select('*').collect()
[Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')]
df.select('name', 'age').collect()
[Row(name=u'Alice', age=2), Row(name=u'Bob', age=5)]
df.select(df.name, (df.age + 10).alias('age')).collect()
[Row(name=u'Alice', age=12), Row(name=u'Bob', age=15)]

Execution select(column-name1,column-name2,etc) method on a dataframe, returns a new dataframe which holds only the columns which were selected in the select() function.

e.g. assuming df has several columns including "name" and "value" and some others.

df2 = df.select("name","value")

df2 will hold only two columns ("name" and "value") out of the entire columns of df

df2 as the result of select will be in the executors and not in the driver (as in the case of using collect())

sql-programming-guide

df.printSchema()
# root
# |-- age: long (nullable = true)
# |-- name: string (nullable = true)

# Select only the "name" column
df.select("name").show()
# +-------+
# |   name|
# +-------+
# |Michael|
# |   Andy|
# | Justin|
# +-------+

You can running collect() on a dataframe (spark docs)

>>> l = [('Alice', 1)]
>>> spark.createDataFrame(l).collect()
[Row(_1=u'Alice', _2=1)]
>>> spark.createDataFrame(l, ['name', 'age']).collect()
[Row(name=u'Alice', age=1)]

spark docs

To print all elements on the driver, one can use the collect() method to first bring the RDD to the driver node thus: rdd.collect().foreach(println). This can cause the driver to run out of memory, though, because collect() fetches the entire RDD to a single machine; if you only need to print a few elements of the RDD, a safer approach is to use the take(): rdd.take(100).foreach(println).

Float a div right, without impacting on design

If you don't want the image to affect the layout at all (and float on top of other content) you can apply the following CSS to the image:

position:absolute;
right:0;
top:0;

If you want it to float at the right of a particular parent section, you can add position: relative to that section.

jQuery.getJSON - Access-Control-Allow-Origin Issue

You may well want to use JSON-P instead (see below). First a quick explanation.

The header you've mentioned is from the Cross Origin Resource Sharing standard. Beware that it is not supported by some browsers people actually use, and on other browsers (Microsoft's, sigh) it requires using a special object (XDomainRequest) rather than the standard XMLHttpRequest that jQuery uses. It also requires that you change server-side resources to explicitly allow the other origin (www.xxxx.com).

To get the JSON data you're requesting, you basically have three options:

  1. If possible, you can be maximally-compatible by correcting the location of the files you're loading so they have the same origin as the document you're loading them into. (I assume you must be loading them via Ajax, hence the Same Origin Policy issue showing up.)

  2. Use JSON-P, which isn't subject to the SOP. jQuery has built-in support for it in its ajax call (just set dataType to "jsonp" and jQuery will do all the client-side work). This requires server side changes, but not very big ones; basically whatever you have that's generating the JSON response just looks for a query string parameter called "callback" and wraps the JSON in JavaScript code that would call that function. E.g., if your current JSON response is:

    {"weather": "Dreary start but soon brightening into a fine summer day."}
    

    Your script would look for the "callback" query string parameter (let's say that the parameter's value is "jsop123") and wraps that JSON in the syntax for a JavaScript function call:

    jsonp123({"weather": "Dreary start but soon brightening into a fine summer day."});
    

    That's it. JSON-P is very broadly compatible (because it works via JavaScript script tags). JSON-P is only for GET, though, not POST (again because it works via script tags).

  3. Use CORS (the mechanism related to the header you quoted). Details in the specification linked above, but basically:

    A. The browser will send your server a "preflight" message using the OPTIONS HTTP verb (method). It will contain the various headers it would send with the GET or POST as well as the headers "Origin", "Access-Control-Request-Method" (e.g., GET or POST), and "Access-Control-Request-Headers" (the headers it wants to send).

    B. Your PHP decides, based on that information, whether the request is okay and if so responds with the "Access-Control-Allow-Origin", "Access-Control-Allow-Methods", and "Access-Control-Allow-Headers" headers with the values it will allow. You don't send any body (page) with that response.

    C. The browser will look at your response and see whether it's allowed to send you the actual GET or POST. If so, it will send that request, again with the "Origin" and various "Access-Control-Request-xyz" headers.

    D. Your PHP examines those headers again to make sure they're still okay, and if so responds to the request.

    In pseudo-code (I haven't done much PHP, so I'm not trying to do PHP syntax here):

    // Find out what the request is asking for
    corsOrigin = get_request_header("Origin")
    corsMethod = get_request_header("Access-Control-Request-Method")
    corsHeaders = get_request_header("Access-Control-Request-Headers")
    if corsOrigin is null or "null" {
        // Requests from a `file://` path seem to come through without an
        // origin or with "null" (literally) as the origin.
        // In my case, for testing, I wanted to allow those and so I output
        // "*", but you may want to go another way.
        corsOrigin = "*"
    }
    
    // Decide whether to accept that request with those headers
    // If so:
    
    // Respond with headers saying what's allowed (here we're just echoing what they
    // asked for, except we may be using "*" [all] instead of the actual origin for
    // the "Access-Control-Allow-Origin" one)
    set_response_header("Access-Control-Allow-Origin", corsOrigin)
    set_response_header("Access-Control-Allow-Methods", corsMethod)
    set_response_header("Access-Control-Allow-Headers", corsHeaders)
    if the HTTP request method is "OPTIONS" {
        // Done, no body in response to OPTIONS
        stop
    }
    // Process the GET or POST here; output the body of the response
    

    Again stressing that this is pseudo-code.

Error: fix the version conflict (google-services plugin)

All google services should be of same version, try matching every versions.

Correct one is :

  implementation 'com.google.firebase:firebase-auth:11.6.0'
  implementation 'com.google.firebase:firebase-database:11.6.0'

Incorrect Config is :

 implementation 'com.google.firebase:firebase-auth:11.6.0'
 implementation 'com.google.firebase:firebase-database:11.8.0'

installing JDK8 on Windows XP - advapi32.dll error

There is also an alternate solution for those who aren't afraid of using hex editors (e.g. XVI32) [thanks to Trevor for this]: in the unpacked 1 installer executable (jdk-8uXX-windows-i586.exe in case of JDK) simply replace all occurrences of RegDeleteKeyExA (the name of API found in "new" ADVAPI32.DLL) with RegDeleteKeyA (legacy API name), followed by two hex '00's (to preserve padding/segmentation boundaries). The installer will complain about unsupported Windows version, but will work nevertheless.

For reference, the raw hex strings will be:

52 65 67 44 65 6C 65 74 65 4B 65 79 45 78 41

replaced with

52 65 67 44 65 6C 65 74 65 4B 65 79 41 00 00

Note: this procedure applies to both offline (standalone) and online (downloader) package.

1: some newer installer versions are packed with UPX - you'd need to unpack them first, otherwise you simply won't be able to find the hex string required

BehaviorSubject vs Observable?

One thing I don't see in examples is that when you cast BehaviorSubject to Observable via asObservable, it inherits behaviour of returning last value on subscription.

It's the tricky bit, as often libraries will expose fields as observable (i.e. params in ActivatedRoute in Angular2), but may use Subject or BehaviorSubject behind the scenes. What they use would affect behaviour of subscribing.

See here http://jsbin.com/ziquxapubo/edit?html,js,console

let A = new Rx.Subject();
let B = new Rx.BehaviorSubject(0);

A.next(1);
B.next(1);

A.asObservable().subscribe(n => console.log('A', n));
B.asObservable().subscribe(n => console.log('B', n));

A.next(2);
B.next(2);

Injection of autowired dependencies failed;

Do you have a bean declared in your context file that has an id of "articleService"? I believe that autowiring matches the id of a bean in your context files with the variable name that you are attempting to Autowire.

Remove all the elements that occur in one list from another

Expanding on Donut's answer and the other answers here, you can get even better results by using a generator comprehension instead of a list comprehension, and by using a set data structure (since the in operator is O(n) on a list but O(1) on a set).

So here's a function that would work for you:

def filter_list(full_list, excludes):
    s = set(excludes)
    return (x for x in full_list if x not in s)

The result will be an iterable that will lazily fetch the filtered list. If you need a real list object (e.g. if you need to do a len() on the result), then you can easily build a list like so:

filtered_list = list(filter_list(full_list, excludes))

Jackson: how to prevent field serialization

set variable as

@JsonIgnore

This allows variable to get skipped by json serializer

Angular JS update input field after change

Create a directive and put a watch on it.

app.directive("myApp", function(){
link:function(scope){

    function:getTotal(){
    ..do your maths here

    }
    scope.$watch('one', getTotals());
    scope.$watch('two', getTotals());
   }

})

Correct MIME Type for favicon.ico?

I have noticed that when using type="image/vnd.microsoft.icon", the favicon fails to appear when the browser is not connected to the internet. But type="image/x-icon" works whether the browser can connect to the internet, or not. When developing, at times I am not connected to the internet.

Is there an Eclipse plugin to run system shell in the Console?

You can also use the Termial view to ssh/telnet to your local machine. Doesn't have that funny input box for commands.

How to get the size of a string in Python?

Do you want to find the length of the string in python language ? If you want to find the length of the word, you can use the len function.

string = input("Enter the string : ")

print("The string length is : ",len(string))

OUTPUT : -

Enter the string : viral

The string length is : 5

How to find tags with only certain attributes - BeautifulSoup

find using an attribute in any tag

<th class="team" data-sort="team">Team</th>    
soup.find_all(attrs={"class": "team"}) 

<th data-sort="team">Team</th>  
soup.find_all(attrs={"data-sort": "team"}) 
 

How to write std::string to file?

Assuming you're using a std::ofstream to write to file, the following snippet will write a std::string to file in human readable form:

std::ofstream file("filename");
std::string my_string = "Hello text in file\n";
file << my_string;

CSS filter: make color image with transparency white

You can use

filter: brightness(0) invert(1);

_x000D_
_x000D_
html {_x000D_
  background: red;_x000D_
}_x000D_
p {_x000D_
  float: left;_x000D_
  max-width: 50%;_x000D_
  text-align: center;_x000D_
}_x000D_
img {_x000D_
  display: block;_x000D_
  max-width: 100%;_x000D_
}_x000D_
.filter {_x000D_
  -webkit-filter: brightness(0) invert(1);_x000D_
  filter: brightness(0) invert(1);_x000D_
}
_x000D_
<p>_x000D_
  Original:_x000D_
  <img src="http://i.stack.imgur.com/jO8jP.gif" />_x000D_
</p>_x000D_
<p>_x000D_
  Filter:_x000D_
  <img src="http://i.stack.imgur.com/jO8jP.gif" class="filter" />_x000D_
</p>
_x000D_
_x000D_
_x000D_

First, brightness(0) makes all image black, except transparent parts, which remain transparent.

Then, invert(1) makes the black parts white.

OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow

Simply use an image extension like .jpeg or .png.

C++ equivalent of java's instanceof

Depending on what you want to do you could do this:

template<typename Base, typename T>
inline bool instanceof(const T*) {
    return std::is_base_of<Base, T>::value;
}

Use:

if (instanceof<BaseClass>(ptr)) { ... }

However, this purely operates on the types as known by the compiler.

Edit:

This code should work for polymorphic pointers:

template<typename Base, typename T>
inline bool instanceof(const T *ptr) {
    return dynamic_cast<const Base*>(ptr) != nullptr;
}

Example: http://cpp.sh/6qir

String compare in Perl with "eq" vs "=="

Did you try to chomp the $str1 and $str2?

I found a similar issue with using (another) $str1 eq 'Y' and it only went away when I first did:

chomp($str1);
if ($str1 eq 'Y') {
....
}

works after that.

Hope that helps.

How to do a "Save As" in vba code, saving my current Excel workbook with datestamp?

Easiest way to use this function is to start by 'Recording a Macro'. Once you start recording, save the file to the location you want, with the name you want, and then of course set the file type, most likely 'Excel Macro Enabled Workbook' ~ 'XLSM'

Stop recording and you can start inspecting your code.

I wrote the code below which allows you to save a workbook using the path where the file was originally located, naming it as "Event [date in cell "A1"]"

Option Explicit

Sub SaveFile()

Dim fdate As Date
Dim fname As String
Dim path As String

fdate = Range("A1").Value
path = Application.ActiveWorkbook.path

If fdate > 0 Then
    fname = "Event " & fdate
    Application.ActiveWorkbook.SaveAs Filename:=path & "\" & fname, _
        FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
Else
    MsgBox "Chose a date for the event", vbOKOnly
End If

End Sub

Copy the code into a new module and then write a date in cell "A1" e.g. 01-01-2016 -> assign the sub to a button and run. [Note] you need to make a save file before this script will work, because a new workbook is saved to the default autosave location!

How to get phpmyadmin username and password

 Step 1:

    Locate phpMyAdmin installation path.

    Step 2:

    Open phpMyAdmin>config.inc.php in your favourite text editor.

    Step 3:

    $cfg['Servers'][$i]['auth_type'] = 'config';
    $cfg['Servers'][$i]['user'] = 'root';
    $cfg['Servers'][$i]['password'] = '';
    $cfg['Servers'][$i]['extension'] = 'mysqli';
    $cfg['Servers'][$i]['AllowNoPassword'] = true;
    $cfg['Lang'] = '';

how to install apk application from my pc to my mobile android

To install an APK on your mobile, you can either:

  1. Use ADB from the Android SDK, and do the following command: adb install filename.apk. Note, you'll need to enable USB debugging for this to work.
  2. Transfer the file to your device, then open it with a file manager, such as Linda File Manager.

Note, that you'll have to enable installing packages from Unknown Sources in your Applications settings.

As for getting USB to work, I suggest consulting the Android StackExchange for advice.

undefined reference to boost::system::system_category() when compiling

...and in case you wanted to link your main statically, in your Jamfile add the following to requirements:

<link>static
<library>/boost/system//boost_system

and perhaps also:

<linkflags>-static-libgcc
<linkflags>-static-libstdc++

Capture Video of Android's Screen

If you are on a PC then you can run My Phone Explorer on the PC, the MyPhoneExplorer Client on the phone, set the screen capture to refresh continuously, and use Wink to capture a custom rectangular area of your screen over the My Phone Explorer window with your own capture rate. Then convert to a FLV in Wink, then convert from Flash video to MPG with WinFF.

How to convert Calendar to java.sql.Date in Java?

Did you try cal.getTime()? This gets the date representation.

You might also want to look at the javadoc.