Programs & Examples On #Bucket

how to delete files from amazon s3 bucket?

Below is code snippet you can use to delete the bucket,

import boto3, botocore
from botocore.exceptions import ClientError

s3 = boto3.resource("s3",aws_access_key_id='Your-Access-Key',aws_secret_access_key='Your-Secret-Key')
s3.Object('Bucket-Name', 'file-name as key').delete()

How to Configure SSL for Amazon S3 bucket

If you really need it, consider redirections.

For example, on request to assets.my-domain.example.com/path/to/file you could perform a 301 or 302 redirection to my-bucket-name.s3.amazonaws.com/path/to/file or s3.amazonaws.com/my-bucket-name/path/to/file (please remember that in the first case my-bucket-name cannot contain any dots, otherwise it won't match *.s3.amazonaws.com, s3.amazonaws.com stated in S3 certificate).

Not tested, but I believe it would work. I see few gotchas, however.

The first one is pretty obvious, an additional request to get this redirection. And I doubt you could use redirection server provided by your domain name registrar — you'd have to upload proper certificate there somehow — so you have to use your own server for this.

The second one is that you can have urls with your domain name in page source code, but when for example user opens the pic in separate tab, then address bar will display the target url.

How can I convert a string to a number in Perl?

$var += 0

probably what you want. Be warned however, if $var is string could not be converted to numeric, you'll get the error, and $var will be reset to 0:

my $var = 'abc123';
print "var = $var\n";
$var += 0;
print "var = $var\n";

logs

var = abc123
Argument "abc123" isn't numeric in addition (+) at test.pl line 7.
var = 0

What does elementFormDefault do in XSD?

New, detailed answer and explanation to an old, frequently asked question...

Short answer: If you don't add elementFormDefault="qualified" to xsd:schema, then the default unqualified value means that locally declared elements are in no namespace.

There's a lot of confusion regarding what elementFormDefault does, but this can be quickly clarified with a short example...

Streamlined version of your XSD:

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
        xmlns:target="http://www.levijackson.net/web340/ns"
        targetNamespace="http://www.levijackson.net/web340/ns">
  <element name="assignments">
    <complexType>
      <sequence>
        <element name="assignment" type="target:assignmentInfo" 
                 minOccurs="1" maxOccurs="unbounded"/>
      </sequence>
    </complexType>
  </element>
  <complexType name="assignmentInfo">
    <sequence>
      <element name="name" type="string"/>
    </sequence>
    <attribute name="id" type="string" use="required"/>
  </complexType>
</schema>

Key points:

  • The assignment element is locally defined.
  • Elements locally defined in XSD are in no namespace by default.
    • This is because the default value for elementFormDefault is unqualified.
    • This arguably is a design mistake by the creators of XSD.
    • Standard practice is to always use elementFormDefault="qualified" so that assignment is in the target namespace as one would expect.
  • It is a rarely used form attribute on xs:element declarations for which elementFormDefault establishes default values.

Seemingly Valid XML

This XML looks like it should be valid according to the above XSD:

<assignments xmlns="http://www.levijackson.net/web340/ns"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.levijackson.net/web340/ns try.xsd">
  <assignment id="a1">
    <name>John</name>
  </assignment>
</assignments>

Notice:

  • The default namespace on assignments places assignments and all of its descendents in the default namespace (http://www.levijackson.net/web340/ns).

Perplexing Validation Error

Despite looking valid, the above XML yields the following confusing validation error:

[Error] try.xml:4:23: cvc-complex-type.2.4.a: Invalid content was found starting with element 'assignment'. One of '{assignment}' is expected.

Notes:

  • You would not be the first developer to curse this diagnostic that seems to say that the content is invalid because it expected to find an assignment element but it actually found an assignment element. (WTF)
  • What this really means: The { and } around assignment means that validation was expecting assignment in no namespace here. Unfortunately, when it says that it found an assignment element, it doesn't mention that it found it in a default namespace which differs from no namespace.

Solution

  • Vast majority of the time: Add elementFormDefault="qualified" to the xsd:schema element of the XSD. This means valid XML must place elements in the target namespace when locally declared in the XSD; otherwise, valid XML must place locally declared elements in no namespace.
  • Tiny minority of the time: Change the XML to comply with the XSD's requirement that assignment be in no namespace. This can be achieved, for example, by adding xmlns="" to the assignment element.

Credits: Thanks to Michael Kay for helpful feedback on this answer.

How to hide Table Row Overflow?

If javascript is accepted as an answer, I made a jQuery plugin to address this issue (for more information about the issue see CSS: Truncate table cells, but fit as much as possible).

To use the plugin just type

$('selector').tableoverflow();

Plugin: https://github.com/marcogrcr/jquery-tableoverflow

Full example: http://jsfiddle.net/Cw7TD/3/embedded/result/

Detect Scroll Up & Scroll down in ListView

            ListView listView = getListView();
            listView.setOnScrollListener(new OnScrollListener() {

                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {

                    view.setOnTouchListener(new OnTouchListener() {
                        private float mInitialX;
                        private float mInitialY;

                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            switch (event.getAction()) {
                                case MotionEvent.ACTION_DOWN:
                                    mInitialX = event.getX();
                                    mInitialY = event.getY();
                                    return true;
                                case MotionEvent.ACTION_MOVE:
                                    final float x = event.getX();
                                    final float y = event.getY();
                                    final float yDiff = y - mInitialY;
                                    if (yDiff > 0.0) {
                                        Log.d(tag, "SCROLL DOWN");
                                        scrollDown = true;
                                        break;

                                    } else if (yDiff < 0.0) {
                                        Log.d(tag, "SCROLL up");
                                        scrollDown = true;
                                        break;

                                    }
                                    break;
                            }
                            return false;
                        }
                    });

Temporarily disable all foreign key constraints

not need to run queries to sidable FKs on sql. If you have a FK from table A to B, you should:

  • delete data from table A
  • delete data from table B
  • insert data on B
  • insert data on A

You can also tell the destination not to check constraints

enter image description here

What is the difference between rb and r+b modes in file objects

r opens for reading, whereas r+ opens for reading and writing. The b is for binary.

This is spelled out in the documentation:

The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position). If mode is omitted, it defaults to 'r'. The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append 'b' to the mode value to open the file in binary mode, which will improve portability. (Appending 'b' is useful even on systems that don’t treat binary and text files differently, where it serves as documentation.) See below for more possible values of mode.

Modes 'r+', 'w+' and 'a+' open the file for updating (note that 'w+' truncates the file). Append 'b' to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don’t have this distinction, adding the 'b' has no effect.

How to convert Excel values into buckets?

Maybe this could help you:

=IF(N6<10,"0-10",IF(N6<20,"10-20",IF(N6<30,"20-30",IF(N6<40,"30-40",IF(N6<50,"40-50")))))

Just replace the values and the text to small, medium and large.

Window vs Page vs UserControl for WPF navigation?

  • Window is like Windows.Forms.Form, so just a new window
  • Page is, according to online documentation:

    Encapsulates a page of content that can be navigated to and hosted by Windows Internet Explorer, NavigationWindow, and Frame.

    So you basically use this if going you visualize some HTML content

  • UserControl is for cases when you want to create some reusable component (but not standalone one) to use it in multiple different Windows

Mixing C# & VB In The Same Project

Although Visual Studio does not support this (you can do some tricks and get MSBuild to compile both, but not from within Visual Studio), SharpDevelop does. You can have both in the same solution (as long as you are running Visual Studio Professional and above), so the easiest solution if you want to keep using Visual Studio is to seperate your VB code into a different project and access it that way.

Rails update_attributes without save?

I believe what you are looking for is assign_attributes.

It's basically the same as update_attributes but it doesn't save the record:

class User < ActiveRecord::Base
  attr_accessible :name
  attr_accessible :name, :is_admin, :as => :admin
end

user = User.new
user.assign_attributes({ :name => 'Josh', :is_admin => true }) # Raises an ActiveModel::MassAssignmentSecurity::Error
user.assign_attributes({ :name => 'Bob'})
user.name        # => "Bob"
user.is_admin?   # => false
user.new_record? # => true

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Tensorflow gpu 2.2 and 2.3 nightly

(along CUDA Toolkit 11.0 RC)

To solve the same issue as OP, I just had to find cudart64_101.dll on my disk (in my case C:\Program Files\NVIDIA Corporation\NvStreamSrv) and add it as variable environment (that is add value C:\Program Files\NVIDIA\Corporation\NvStreamSrv)cudart64_101.dll to user's environment variable Path).

Converting an int to a binary string representation in Java?

public class BinaryConverter {

    public static String binaryConverter(int number) {
        String binary = "";
        if (number == 1){
            binary = "1";
            System.out.print(binary);
            return binary;
        }
        if (number == 0){
            binary = "0";
            System.out.print(binary);
            return binary;
        }
        if (number > 1) {
            String i = Integer.toString(number % 2);

            binary = binary + i;
            binaryConverter(number/2);
        }
        System.out.print(binary);
        return binary;
    }
}

Add php variable inside echo statement as href link address?

as simple as that: echo '<a href="'.$link_address.'">Link</a>';

How do you get the currently selected <option> in a <select> via JavaScript?

This will do it for you:

var yourSelect = document.getElementById( "your-select-id" );
alert( yourSelect.options[ yourSelect.selectedIndex ].value )

How can I make a DateTimePicker display an empty string?

Listen , Make Following changes in your code if you want to show empty datetimepicker and get null when no date is selected by user, else save date.

  1. Set datetimepicker FORMAT property to custom.
  2. set CUSTOM FORMAT property to empty string " ".
  3. set its TAG to 0 by default.
  4. Register Event for datetimepicker VALUECHANGED.

Now real work starts

if user will interact with datetimepicker its VALUECHANGED event will be called and there set its TAG property to 1.

Final Step

Now when saving, check if its TAG is zero, then save NULL date else if TAG is 1 then pick and save Datetime picker value.

It Works like a charm.

Now if you want its value be changed back to empty by user interaction, then add checkbox and show text "Clear" with this checkbox. if user wants to clear date, simply again set its CUSTOM FORMAT property to empty string " ", and set its TAG back to 0. Thats it..

How to cut first n and last n columns?

Try the following:

echo a#b#c | awk -F"#" '{$1 = ""; $NF = ""; print}' OFS=""

Docker CE on RHEL - Requires: container-selinux >= 2.9

I was getting the same error Requires: container-selinux >= 2.9 on amazon ec2 instance(Rhel7)

I tried to add extra package rmp repo by executing sudo yum-config-manager --enable rhui-REGION-rhel-server-extras
but it works. followed steps from https://installdocker.blogspot.com/ and I was able to install docker.

How can I get my webapp's base URL in ASP.NET MVC?

You can use the following script in view:

<script type="text/javascript">
    var BASE_URL = '<%= ResolveUrl("~/") %>';
</script>

AngularJS ng-class if-else expression

A workaround of mine is to manipulate a model variable just for the ng-class toggling:

For example, I want to toggle class according to the state of my list:

1) Whenever my list is empty, I update my model:

$scope.extract = function(removeItemId) {
    $scope.list= jQuery.grep($scope.list, function(item){return item.id != removeItemId});
    if (!$scope.list.length) {
        $scope.liststate = "empty";
    }
}

2) Whenever my list is not empty, I set another state

$scope.extract = function(item) {
    $scope.list.push(item);
    $scope.liststate = "notempty";
}

3) When my list is not ever touched, I want to give another class (this is where the page is initiated):

$scope.liststate = "init";

3) I use this additional model on my ng-class:

ng-class="{'bg-empty': liststate == 'empty', 'bg-notempty': liststate == 'notempty', 'bg-init': liststate = 'init'}"

What is the difference between json.dump() and json.dumps() in python?

One notable difference in Python 2 is that if you're using ensure_ascii=False, dump will properly write UTF-8 encoded data into the file (unless you used 8-bit strings with extended characters that are not UTF-8):

dumps on the other hand, with ensure_ascii=False can produce a str or unicode just depending on what types you used for strings:

Serialize obj to a JSON formatted str using this conversion table. If ensure_ascii is False, the result may contain non-ASCII characters and the return value may be a unicode instance.

(emphasis mine). Note that it may still be a str instance as well.

Thus you cannot use its return value to save the structure into file without checking which format was returned and possibly playing with unicode.encode.

This of course is not valid concern in Python 3 any more, since there is no more this 8-bit/Unicode confusion.


As for load vs loads, load considers the whole file to be one JSON document, so you cannot use it to read multiple newline limited JSON documents from a single file.

What is java pojo class, java bean, normal class?

  1. Normal Class: A Java class

  2. Java Beans:

    • All properties private (use getters/setters)
    • A public no-argument constructor
    • Implements Serializable.
  3. Pojo: Plain Old Java Object is a Java object not bound by any restriction other than those forced by the Java Language Specification. I.e., a POJO should not have to

    • Extend prespecified classes
    • Implement prespecified interface
    • Contain prespecified annotations

Regular Expression to select everything before and up to a particular text

((\n.*){0,3})(.*)\W*\.txt

This will select all the content before the particular word ".txt" including any context in different lines up to 3 lines

What does -XX:MaxPermSize do?

-XX:PermSize -XX:MaxPermSize are used to set size for Permanent Generation.

Permanent Generation: The Permanent Generation is where class files are kept. These are the result of compiled classes and JSP pages. If this space is full, it triggers a Full Garbage Collection. If the Full Garbage Collection cannot clean out old unreferenced classes and there is no room left to expand the Permanent Space, an Out-of- Memory error (OOME) is thrown and the JVM will crash.

how to use getSharedPreferences in android

After reading around alot, only this worked: In class to set Shared preferences:

 SharedPreferences userDetails = getApplicationContext().getSharedPreferences("test", MODE_PRIVATE);
                    SharedPreferences.Editor edit = userDetails.edit();
                    edit.clear();
                    edit.putString("test1", "1");
                    edit.putString("test2", "2");
                    edit.commit();

In AlarmReciever:

SharedPreferences userDetails = context.getSharedPreferences("test", Context.MODE_PRIVATE);
    String test1 = userDetails.getString("test1", "");
    String test2 = userDetails.getString("test2", "");

Can CSS force a line break after each word in an element?

In my case,

    word-break: break-all;

worked perfecly, hope it helps any other newcomer like me.

What does __FILE__ mean in Ruby?

It is a reference to the current file name. In the file foo.rb, __FILE__ would be interpreted as "foo.rb".

Edit: Ruby 1.9.2 and 1.9.3 appear to behave a little differently from what Luke Bayes said in his comment. With these files:

# test.rb
puts __FILE__
require './dir2/test.rb'
# dir2/test.rb
puts __FILE__

Running ruby test.rb will output

test.rb
/full/path/to/dir2/test.rb

What is a good naming convention for vars, methods, etc in C++?

It really doesn't matter. Just make sure you name your variables and functions descriptively. Also be consistent.

Nowt worse than seeing code like this:

int anInt;                  // Great name for a variable there ...
int myVar = Func( anInt );  // And on this line a great name for a function and myVar
                            // lacks the consistency already, poorly, laid out! 

Edit: As pointed out by my commenter that consistency needs to be maintained across an entire team. As such it doesn't matter WHAT method you chose, as long as that consistency is maintained. There is no right or wrong method, however. Every team I've worked in has had different ideas and I've adapted to those.

SQL Query Multiple Columns Using Distinct on One Column Only

I needed to do the same and had to query a query to get the result

I set my first query up to bring in all IDs from the table and all other information needed to filter:

SELECT tMAIN.tLOTS.NoContract, tMAIN.ID
FROM tMAIN INNER JOIN tLOTS ON tMAIN.ID = tLOTS.id
WHERE (((tLOTS.NoContract)=False));

Save this as Q04_1 -0 this returned 1229 results (there are 63 unique records to query - soime with multiple LOTs)

SELECT DISTINCT ID
FROM q04_1;

Saved that as q04_2

I then wrote another query which brought in the required information linked to the ID

SELECT q04_2.ID, tMAIN.Customer, tMAIN.Category
FROM q04_2 INNER JOIN tMAIN ON q04_2.ID = tMAIN.ID;

Worked a treat and got me exactly what I needed - 63 unique records returned with customer and category details.

This is how I worked around it as I couldn't get the Group By working at all - although I am rather "wet behind the ears" weith SQL (so please be gentle and constructive with feedback)

Extracting extension from filename in Python

Even this question is already answered I'd add the solution in Regex.

>>> import re
>>> file_suffix = ".*(\..*)"
>>> result = re.search(file_suffix, "somefile.ext")
>>> result.group(1)
'.ext'

How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?

I don't think the jar tool supports this natively, but you can just unzip a JAR file with "unzip" and specify the output directory with that with the "-d" option, so something like:

$ unzip -d /home/foo/bar/baz /home/foo/bar/Portal.ear Binaries.war

Press Keyboard keys using a batch file

Wow! Mean this that you must learn a different programming language just to send two keys to the keyboard? There are simpler ways for you to achieve the same thing. :-)

The Batch file below is an example that start another program (cmd.exe in this case), send a command to it and then send an Up Arrow key, that cause to recover the last executed command. The Batch file is simple enough to be understand with no problems, so you may modify it to fit your needs.

@if (@CodeSection == @Batch) @then


@echo off

rem Use %SendKeys% to send keys to the keyboard buffer
set SendKeys=CScript //nologo //E:JScript "%~F0"

rem Start the other program in the same Window
start "" /B cmd

%SendKeys% "echo off{ENTER}"

set /P "=Wait and send a command: " < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "echo Hello, world!{ENTER}"

set /P "=Wait and send an Up Arrow key: [" < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "{UP}"

set /P "=] Wait and send an Enter key:" < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "{ENTER}"

%SendKeys% "exit{ENTER}"

goto :EOF


@end


// JScript section

var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(WScript.Arguments(0));

For a list of key names for SendKeys, see: http://msdn.microsoft.com/en-us/library/8c6yea83(v=vs.84).aspx

For example:

LEFT ARROW    {LEFT}
RIGHT ARROW   {RIGHT}

For a further explanation of this solution, see: GnuWin32 openssl s_client conn to WebSphere MQ server not closing at EOF, hangs

Abstraction vs Encapsulation in Java

OO Abstraction occurs during class level design, with the objective of hiding the implementation complexity of how the the features offered by an API / design / system were implemented, in a sense simplifying the 'interface' to access the underlying implementation.

The process of abstraction can be repeated at increasingly 'higher' levels (layers) of classes, which enables large systems to be built without increasing the complexity of code and understanding at each layer.

For example, a Java developer can make use of the high level features of FileInputStream without concern for how it works (i.e. file handles, file system security checks, memory allocation and buffering will be managed internally, and are hidden from consumers). This allows the implementation of FileInputStream to be changed, and as long as the API (interface) to FileInputStream remains consistent, code built against previous versions will still work.

Similarly, when designing your own classes, you will want to hide internal implementation details from others as far as possible.

In the Booch definition1, OO Encapsulation is achieved through Information Hiding, and specifically around hiding internal data (fields / members representing the state) owned by a class instance, by enforcing access to the internal data in a controlled manner, and preventing direct, external change to these fields, as well as hiding any internal implementation methods of the class (e.g. by making them private).

For example, the fields of a class can be made private by default, and only if external access to these was required, would a get() and/or set() (or Property) be exposed from the class. (In modern day OO languages, fields can be marked as readonly / final / immutable which further restricts change, even within the class).

Example where NO information hiding has been applied (Bad Practice):

class Foo {
   // BAD - NOT Encapsulated - code external to the class can change this field directly
   // Class Foo has no control over the range of values which could be set.
   public int notEncapsulated;
}

Example where field encapsulation has been applied:

class Bar {
   // Improvement - access restricted only to this class
   private int encapsulatedPercentageField;

   // The state of Bar (and its fields) can now be changed in a controlled manner
   public void setEncapsulatedField(int percentageValue) {
      if (percentageValue >= 0 && percentageValue <= 100) {
          encapsulatedPercentageField = percentageValue;
      }
      // else throw ... out of range
   }
}

Example of immutable / constructor-only initialization of a field:

class Baz {
   private final int immutableField;

   public void Baz(int onlyValue) {
      // ... As above, can also check that onlyValue is valid
      immutableField = onlyValue;
   }
   // Further change of `immutableField` outside of the constructor is NOT permitted, even within the same class 
}

Re : Abstraction vs Abstract Class

Abstract classes are classes which promote reuse of commonality between classes, but which themselves cannot directly be instantiated with new() - abstract classes must be subclassed, and only concrete (non abstract) subclasses may be instantiated. Possibly one source of confusion between Abstraction and an abstract class was that in the early days of OO, inheritance was more heavily used to achieve code reuse (e.g. with associated abstract base classes). Nowadays, composition is generally favoured over inheritance, and there are more tools available to achieve abstraction, such as through Interfaces, events / delegates / functions, traits / mixins etc.

Re : Encapsulation vs Information Hiding

The meaning of encapsulation appears to have evolved over time, and in recent times, encapsulation can commonly also used in a more general sense when determining which methods, fields, properties, events etc to bundle into a class.

Quoting Wikipedia:

In the more concrete setting of an object-oriented programming language, the notion is used to mean either an information hiding mechanism, a bundling mechanism, or the combination of the two.

For example, in the statement

I've encapsulated the data access code into its own class

.. the interpretation of encapsulation is roughly equivalent to the Separation of Concerns or the Single Responsibility Principal (the "S" in SOLID), and could arguably be used as a synonym for refactoring.


[1] Once you've seen Booch's encapsulation cat picture you'll never be able to forget encapsulation - p46 of Object Oriented Analysis and Design with Applications, 2nd Ed

Setting log level of message at runtime in slf4j

You can implement this using Java 8 lambdas.

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.event.Level;

public class LevelLogger {
    private static final Logger LOGGER = LoggerFactory.getLogger(LevelLogger.class);
    private static final Map<Level, LoggingFunction> map;

    static {
        map = new HashMap<>();
        map.put(Level.TRACE, (o) -> LOGGER.trace(o));
        map.put(Level.DEBUG, (o) -> LOGGER.debug(o));
        map.put(Level.INFO, (o) -> LOGGER.info(o));
        map.put(Level.WARN, (o) -> LOGGER.warn(o));
        map.put(Level.ERROR, (o) -> LOGGER.error(o));
    }

    public static void log(Level level, String s) {
        map.get(level).log(s);
    }

    @FunctionalInterface
    private interface LoggingFunction {
        public void log(String arg);
    }
}

PHP form - on submit stay on same page

Friend. Use this way, There will be no "Undefined variable message" and it will work fine.

<?php
    if(isset($_POST['SubmitButton'])){
        $price = $_POST["price"];
        $qty = $_POST["qty"];
        $message = $price*$qty;
    }

        ?>

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
    </head>
    <body>
        <form action="#" method="post">
            <input type="number" name="price"> <br>
            <input type="number" name="qty"><br>
            <input type="submit" name="SubmitButton">
        </form>
        <?php echo "The Answer is" .$message; ?>

    </body>
    </html>

Rename Excel Sheet with VBA Macro

This should do it:

WS.Name = WS.Name & "_v1"

Jquery button click() function is not working

After making the id unique across the document ,You have to use event delegation

$("#container").on("click", "buttonid", function () {
  alert("Hi");
});

What's a quick way to comment/uncomment lines in Vim?

I combined Phil and jqno's answer and made untoggle comments with spaces:

autocmd FileType c,cpp,java,scala let b:comment_leader = '//'
autocmd FileType sh,ruby,python   let b:comment_leader = '#'
autocmd FileType conf,fstab       let b:comment_leader = '#'
autocmd FileType tex              let b:comment_leader = '%'
autocmd FileType mail             let b:comment_leader = '>'
autocmd FileType vim              let b:comment_leader = '"'
function! CommentToggle()
    execute ':silent! s/\([^ ]\)/' . escape(b:comment_leader,'\/') . ' \1/'
    execute ':silent! s/^\( *\)' . escape(b:comment_leader,'\/') . ' \?' . escape(b:comment_leader,'\/') . ' \?/\1/'
endfunction
map <F7> :call CommentToggle()<CR>

how it works:

Lets assume we work with #-comments.

The first command s/\([^ ]\)/# \1/ searches for the first non-space character [^ ] and replaces that with # +itself. The itself-replacement is done by the \(..\) in the search-pattern and \1 in the replacement-pattern.

The second command s/^\( *\)# \?# \?/\1/ searches for lines starting with a double comment ^\( *\)# \?# \? (accepting 0 or 1 spaces in between comments) and replaces those simply with the non-comment part \( *\) (meaning the same number of preceeding spaces).

For more details about vim patterns check this out.

Is it possible to run CUDA on AMD GPUs?

I think it is going to be possible soon in AMD FirePro GPU's, see press release here but support is coming 2016 Q1 for the developing tools:

An early access program for the "Boltzmann Initiative" tools is planned for Q1 2016.

what is the use of annotations @Id and @GeneratedValue(strategy = GenerationType.IDENTITY)? Why the generationtype is identity?

Simply, @Id: This annotation specifies the primary key of the entity. 

@GeneratedValue: This annotation is used to specify the primary key generation strategy to use. i.e Instructs database to generate a value for this field automatically. If the strategy is not specified by default AUTO will be used. 

GenerationType enum defines four strategies: 
1. Generation Type . TABLE, 
2. Generation Type. SEQUENCE,
3. Generation Type. IDENTITY   
4. Generation Type. AUTO

GenerationType.SEQUENCE

With this strategy, underlying persistence provider must use a database sequence to get the next unique primary key for the entities. 

GenerationType.TABLE

With this strategy, underlying persistence provider must use a database table to generate/keep the next unique primary key for the entities. 

GenerationType.IDENTITY
This GenerationType indicates that the persistence provider must assign primary keys for the entity using a database identity column. IDENTITY column is typically used in SQL Server. This special type column is populated internally by the table itself without using a separate sequence. If underlying database doesn't support IDENTITY column or some similar variant then the persistence provider can choose an alternative appropriate strategy. In this examples we are using H2 database which doesn't support IDENTITY column.

GenerationType.AUTO
This GenerationType indicates that the persistence provider should automatically pick an appropriate strategy for the particular database. This is the default GenerationType, i.e. if we just use @GeneratedValue annotation then this value of GenerationType will be used. 

Reference:- https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/jpa-primary-key.html

"Comparison method violates its general contract!"

You can't compare object data like this:s1.getParent() == s2 - this will compare the object references. You should override equals function for Foo class and then compare them like this s1.getParent().equals(s2)

semaphore implementation

Your Fundamentals are wrong, the program won't work, so go through the basics and rewrite the program.

Some of the corrections you must make are:

1) You must make a variable of semaphore type

sem_t semvar;

2) The functions sem_wait(), sem_post() require the semaphore variable but you are passing the semaphore id, which makes no sense.

sem_wait(&semvar);
   //your critical section code
sem_post(&semvar);

3) You are passing the semaphore to sem_wait() and sem_post() without initializing it. You must initialize it to 1 (in your case) before using it, or you will have a deadlock.

ret = semctl( semid, 1, SETVAL, sem);
if (ret == 1)
     perror("Semaphore failed to initialize");

Study the semaphore API's from the man page and go through this example.

How to add line break for UILabel?

NSCharacterSet *charSet = NSCharacterSet.newlineCharacterSet;
NSString *formatted = [[unformatted componentsSeparatedByCharactersInSet:charSet] componentsJoinedByString:@"\n"];

How to convert an int to string in C?

This is old but here's another way.

#include <stdio.h>

#define atoa(x) #x

int main(int argc, char *argv[])
{
    char *string = atoa(1234567890);
    printf("%s\n", string);
    return 0;
}

Saving awk output to variable

variable=$(ps -ef | awk '/[p]ort 10/ {print $12}')

The [p] is a neat trick to remove the search from showing from ps

@Jeremy If you post the output of ps -ef | grep "port 10", and what you need from the line, it would be more easy to help you getting correct syntax

How do I close a tkinter window?

Code snippet below. I'm providing a small scenario.

import tkinter as tk
from tkinter import *

root = Tk()

def exit():
    if askokcancel("Quit", "Do you really want to quit?"):
        root.destroy()

menubar = Menu(root, background='#000099', foreground='white',
               activebackground='#004c99', activeforeground='white')

fileMenu = Menu(menubar,  tearoff=0, background="grey", foreground='black',
                activebackground='#004c99', activeforeground='white')
menubar.add_cascade(label='File', menu=fileMenu)

fileMenu.add_command(label='Exit', command=exit)

root.config(bg='#2A2C2B',menu=menubar)

if __name__ == '__main__':
    root.mainloop()

I have created a blank window here & add file menu option on the same window(root window), where I only add one option exit.

Then simply run mainloop for root.

Try to do it once

How do I manually configure a DataSource in Java?

One thing you might want to look at is the Commons DBCP project. It provides a BasicDataSource that is configured fairly similarly to your example. To use that you need the database vendor's JDBC JAR in your classpath and you have to specify the vendor's driver class name and the database URL in the proper format.

Edit:

If you want to configure a BasicDataSource for MySQL, you would do something like this:

BasicDataSource dataSource = new BasicDataSource();

dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUsername("username");
dataSource.setPassword("password");
dataSource.setUrl("jdbc:mysql://<host>:<port>/<database>");
dataSource.setMaxActive(10);
dataSource.setMaxIdle(5);
dataSource.setInitialSize(5);
dataSource.setValidationQuery("SELECT 1");

Code that needs a DataSource can then use that.

How to add Drop-Down list (<select>) programmatically?

_x000D_
_x000D_
const cars = ['Volvo', 'Saab', 'Mervedes', 'Audi'];_x000D_
_x000D_
let domSelect = document.createElement('select');_x000D_
domSelect.multiple = true;_x000D_
document.getElementsByTagName('body')[0].appendChild(domSelect);_x000D_
_x000D_
_x000D_
for (const i in cars) {_x000D_
  let optionSelect = document.createElement('option');_x000D_
_x000D_
  let optText = document.createTextNode(cars[i]);_x000D_
  optionSelect.appendChild(optText);_x000D_
_x000D_
  document.getElementsByTagName('select')[0].appendChild(optionSelect);_x000D_
}
_x000D_
_x000D_
_x000D_

Cannot install signed apk to device manually, got error "App not installed"

You don't have to uninstall the Google Play version if App Signing by Google Play is enabled for your app, follow the steps:
1. Make a signed version of your app with your release key
2. Go to Google Play Developer console
3. Create a closed track release (alpha or beta release) with the new signed version of your app
4. You can now download the apk signed by App Signing by Google Play, choose derived APKenter image description here

  1. Install the downloaded derived APK

The reason is App Signing by Google Play signs release apps with different keys, if you have an app installed from Play Store, and you want to test the new release version app (generated from Android Studio) in your phone, "App not installed" happens since the old version and the new version were signed by two different keys: one with App Signing by Google Play and one with your key.

Easiest way to copy a single file from host to Vagrant guest?

If someone wants to transfer file from windows host to vagrant, then this solution worked for me.

1. Make sure to install **winscp** on your windows system
2. run **vagrant up** command
3. run **vagrant ssh-config** command and note down below details
4. Enter Hostname, Port, Username: vagrant, Password: vagrant in winscp and select **SCP**, file protocol 
5. In most cases, hostname: 127.0.0.1, port: 2222, username: vagrant, password: vagrant.

You should be able to see directories in your vagrant machine.

Best way to get application folder path

For a web application, to get the current web application root directory, generally call by web page for the current incoming request:

HttpContext.Current.Server.MapPath();

System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;

Above code description

How to clear jQuery validation error messages?

I came across this issue myself. I had the need to conditionally validate parts of a form while the form was being constructed based on steps (i.e. certain inputs were dynamically appended during runtime). As a result, sometimes a select dropdown would need validation, and sometimes it would not. However, by the end of the ordeal, it needed to be validated. As a result, I needed a robust method which was not a workaround. I consulted the source code for jquery.validate.

Here is what I came up with:

  • Clear errors by indicating validation success
  • Call handler for error display
  • Clear all storage of success or errors
  • Reset entire form validation

    Here is what it looks like in code:

    function clearValidation(formElement){
     //Internal $.validator is exposed through $(form).validate()
     var validator = $(formElement).validate();
     //Iterate through named elements inside of the form, and mark them as error free
     $('[name]',formElement).each(function(){
       validator.successList.push(this);//mark as error free
       validator.showErrors();//remove error messages if present
     });
     validator.resetForm();//remove error class on name elements and clear history
     validator.reset();//remove all error and success data
    }
    //used
    var myForm = document.getElementById("myFormId");
    clearValidation(myForm);
    

    minified as a jQuery extension:

    $.fn.clearValidation = function(){var v = $(this).validate();$('[name]',this).each(function(){v.successList.push(this);v.showErrors();});v.resetForm();v.reset();};
    //used:
    $("#formId").clearValidation();
    
  • In Ruby on Rails, what's the difference between DateTime, Timestamp, Time and Date?

    1. :datetime (8 bytes)

      • Stores Date and Time formatted YYYY-MM-DD HH:MM:SS
      • Useful for columns like birth_date
    2. :timestamp (4 bytes)

      • Stores number of seconds since 1970-01-01
      • Useful for columns like updated_at, created_at
    3. :date (3 bytes)
      • Stores Date
    4. :time (3 bytes)
      • Stores Time

    YAML mapping values are not allowed in this context

    This is valid YAML:

    jobs:
     - name: A
       schedule: "0 0/5 * 1/1 * ? *"
       type: mongodb.cluster
       config:
         host: mongodb://localhost:27017/admin?replicaSet=rs
         minSecondaries: 2
         minOplogHours: 100
         maxSecondaryDelay: 120
     - name: B
       schedule: "0 0/5 * 1/1 * ? *"
       type: mongodb.cluster
       config:
         host: mongodb://localhost:27017/admin?replicaSet=rs
         minSecondaries: 2
         minOplogHours: 100
         maxSecondaryDelay: 120
    

    Note, that every '-' starts new element in the sequence. Also, indentation of keys in the map should be exactly same.

    How do I update pip itself from inside my virtual environment?

    I had a similar problem on a raspberry pi.

    The problem was that http requires SSL and so I needed to force it to use https to get around this requirement.

    sudo pip install --upgrade pip --index-url=https://pypi.python.org/simple
    

    or

    sudo pip-3.2 --upgrade pip --index-url=https://pypi.python.org/simple/
    

    Mark error in form using Bootstrap

    (UPDATED with examples for Bootstrap v4, v3 and v3)

    Examples of forms with validation classes for the past few major versions of Bootstrap.

    Bootstrap v4

    See the live version on codepen

    bootstrap v4 form validation

    <div class="container">
      <form>
        <div class="form-group row">
          <label for="inputEmail" class="col-sm-2 col-form-label text-success">Email</label>
          <div class="col-sm-7">
            <input type="email" class="form-control is-valid" id="inputEmail" placeholder="Email">
          </div>
        </div>
    
        <div class="form-group row">
          <label for="inputPassword" class="col-sm-2 col-form-label text-danger">Password</label>
          <div class="col-sm-7">
            <input type="password" class="form-control is-invalid" id="inputPassword" placeholder="Password">
          </div>
          <div class="col-sm-3">
            <small id="passwordHelp" class="text-danger">
              Must be 8-20 characters long.
            </small>      
          </div>
        </div>
      </form>
    </div>
    

    Bootstrap v3

    See the live version on codepen

    bootstrap v3 form validation

    <form role="form">
      <div class="form-group has-warning">
        <label class="control-label" for="inputWarning">Input with warning</label>
        <input type="text" class="form-control" id="inputWarning">
        <span class="help-block">Something may have gone wrong</span>
      </div>
      <div class="form-group has-error">
        <label class="control-label" for="inputError">Input with error</label>
        <input type="text" class="form-control" id="inputError">
        <span class="help-block">Please correct the error</span>
      </div>
      <div class="form-group has-info">
        <label class="control-label" for="inputError">Input with info</label>
        <input type="text" class="form-control" id="inputError">
        <span class="help-block">Username is taken</span>
      </div>
      <div class="form-group has-success">
        <label class="control-label" for="inputSuccess">Input with success</label>
        <input type="text" class="form-control" id="inputSuccess" />
        <span class="help-block">Woohoo!</span>
      </div>
    </form>
    

    Bootstrap v2

    See the live version on jsfiddle

    bootstrap v2 form validation

    The .error, .success, .warning and .info classes are appended to the .control-group. This is standard Bootstrap markup and styling in v2. Just follow that and you're in good shape. Of course you can go beyond with your own styles to add a popup or "inline flash" if you prefer, but if you follow Bootstrap convention and hang those validation classes on the .control-group it will stay consistent and easy to manage (at least since you'll continue to have the benefit of Bootstrap docs and examples)

      <form class="form-horizontal">
        <div class="control-group warning">
          <label class="control-label" for="inputWarning">Input with warning</label>
          <div class="controls">
            <input type="text" id="inputWarning">
            <span class="help-inline">Something may have gone wrong</span>
          </div>
        </div>
        <div class="control-group error">
          <label class="control-label" for="inputError">Input with error</label>
          <div class="controls">
            <input type="text" id="inputError">
            <span class="help-inline">Please correct the error</span>
          </div>
        </div>
        <div class="control-group info">
          <label class="control-label" for="inputInfo">Input with info</label>
          <div class="controls">
            <input type="text" id="inputInfo">
            <span class="help-inline">Username is taken</span>
          </div>
        </div>
        <div class="control-group success">
          <label class="control-label" for="inputSuccess">Input with success</label>
          <div class="controls">
            <input type="text" id="inputSuccess">
            <span class="help-inline">Woohoo!</span>
          </div>
        </div>
      </form>
    

    postgresql duplicate key violates unique constraint

    From http://www.postgresql.org/docs/current/interactive/datatype.html

    Note: Prior to PostgreSQL 7.3, serial implied UNIQUE. This is no longer automatic. If you wish a serial column to be in a unique constraint or a primary key, it must now be specified, same as with any other data type.

    How to find a number in a string using JavaScript?

    var str = "you can enter maximum 500 choices";
    str.replace(/[^0-9]/g, "");
    console.log(str); // "500"
    

    Make <body> fill entire screen?

    On our site we have pages where the content is static, and pages where it is loaded in with AJAX. On one page (a search page), there were cases when the AJAX results would more than fill the page, and cases where it would return no results. In order for the background image to fill the page in all cases we had to apply the following CSS:

    html {
       margin: 0px;
       height: 100%;
       width: 100%;
    }
    
    body {
       margin: 0px;
       min-height: 100%;
       width: 100%;
    }
    

    height for the html and min-height for the body.

    How can I check if a string is null or empty in PowerShell?

    PowerShell 2.0 replacement for [string]::IsNullOrWhiteSpace() is string -notmatch "\S"

    ("\S" = any non-whitespace character)

    > $null  -notmatch "\S"
    True
    > "   "  -notmatch "\S"
    True
    > " x "  -notmatch "\S"
    False
    

    Performance is very close:

    > Measure-Command {1..1000000 |% {[string]::IsNullOrWhiteSpace("   ")}}
    TotalMilliseconds : 3641.2089
    
    > Measure-Command {1..1000000 |% {"   " -notmatch "\S"}}
    TotalMilliseconds : 4040.8453
    

    What is href="#" and why is it used?

    About hyperlinks:

    The main use of anchor tags - <a></a> - is as hyperlinks. That basically means that they take you somewhere. Hyperlinks require the href property, because it specifies a location.

    Hash:

    A hash - # within a hyperlink specifies an html element id to which the window should be scrolled.

    href="#some-id" would scroll to an element on the current page such as <div id="some-id">.

    href="//site.com/#some-id" would go to site.com and scroll to the id on that page.

    Scroll to Top:

    href="#" doesn't specify an id name, but does have a corresponding location - the top of the page. Clicking an anchor with href="#" will move the scroll position to the top.

    See this demo.

    This is the expected behavior according to the w3 documentation.

    Hyperlink placeholders:

    An example where a hyperlink placeholder makes sense is within template previews. On single page demos for templates, I have often seen <a href="#"> so that the anchor tag is a hyperlink, but doesn't go anywhere. Why not leave the href property blank? A blank href property is actually a hyperlink to the current page. In other words, it will cause a page refresh. As I discussed, href="#" is also a hyperlink, and causes scrolling. Therefore, the best solution for hyperlink placeholders is actually href="#!" The idea here is that there hopefully isn't an element on the page with id="!" (who does that!?) and the hyperlink therefore refers to nothing - so nothing happens.

    About anchor tags:

    Another question that you may be wondering is, "Why not just leave the href property off?". A common response I've heard is that the href property is required, so it "should" be present on anchors. This is FALSE! The href property is required only for an anchor to actually be a hyperlink! Read this from w3. So, why not just leave it off for placeholders? Browsers render default styles for elements and will change the default style of an anchor tag that doesn't have the href property. Instead, it will be considered like regular text. It even changes the browser's behavior regarding the element. The status bar (bottom of the screen) will not be displayed when hovering on an anchor without the href property. It is best to use a placeholder href value on an anchor to ensure it is treated as a hyperlink.

    See this demo demonstrating style and behavior differences.

    Returning the product of a list

    Python 3 result for the OP's tests: (best of 3 for each)

    with lambda: 18.978000981995137
    without lambda: 8.110567473006085
    for loop: 10.795806062000338
    with lambda (no 0): 26.612515013999655
    without lambda (no 0): 14.704098362999503
    for loop (no 0): 14.93075215499266
    

    Start and stop a timer PHP

    class Timer
    {
        private $startTime = null;
    
        public function __construct($showSeconds = true)
        {
            $this->startTime = microtime(true);
            echo 'Working - please wait...' . PHP_EOL;
        }
    
        public function __destruct()
        {
            $endTime = microtime(true);
            $time = $endTime - $this->startTime;
    
            $hours = (int)($time / 60 / 60);
            $minutes = (int)($time / 60) - $hours * 60;
            $seconds = (int)$time - $hours * 60 * 60 - $minutes * 60;
            $timeShow = ($hours == 0 ? "00" : $hours) . ":" . ($minutes == 0 ? "00" : ($minutes < 10 ? "0" . $minutes : $minutes)) . ":" . ($seconds == 0 ? "00" : ($seconds < 10 ? "0" . $seconds : $seconds));
    
            echo 'Job finished in ' . $timeShow . PHP_EOL;
        }
    }
    
    $t = new Timer(); // echoes "Working, please wait.."
    
    [some operations]
    
    unset($t);  // echoes "Job finished in h:m:s"
    

    JavaScript equivalent of PHP’s die

    you can try with :

    return 0;
    

    that work in case of stop process.

    'System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method

    Adding a reference to System.Net.Http.Formatting.dll may cause DLL mismatch issues. Right now, System.Net.Http.Formatting.dll appears to reference version 4.5.0.0 of Newtonsoft.Json.DLL, whereas the latest version is 6.0.0.0. That means you'll need to also add a binding redirect to avoid a .NET Assembly exception if you reference the latest Newtonsoft NuGet package or DLL:

    <dependentAssembly>
       <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
     </dependentAssembly> 
    

    So an alternative solution to adding a reference to System.Net.Http.Formatting.dll is to read the response as a string and then desearalize yourself with JsonConvert.DeserializeObject(responseAsString). The full method would be:

    public async Task<T> GetHttpResponseContentAsType(string baseUrl, string subUrl)
    {
         using (var client = new HttpClient())
         {
             client.BaseAddress = new Uri(baseUrl);
             client.DefaultRequestHeaders.Accept.Clear();
             client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
             HttpResponseMessage response = await client.GetAsync(subUrl);
             response.EnsureSuccessStatusCode();
             var responseAsString = await response.Content.ReadAsStringAsync();
             var responseAsConcreteType = JsonConvert.DeserializeObject<T>(responseAsString);
             return responseAsConcreteType;
          }
    }
    

    Bash: Strip trailing linebreak from output

    If your expected output is a single line, you can simply remove all newline characters from the output. It would not be uncommon to pipe to the tr utility, or to Perl if preferred:

    wc -l < log.txt | tr -d '\n'
    
    wc -l < log.txt | perl -pe 'chomp'
    

    You can also use command substitution to remove the trailing newline:

    echo -n "$(wc -l < log.txt)"
    
    printf "%s" "$(wc -l < log.txt)"
    

    If your expected output may contain multiple lines, you have another decision to make:

    If you want to remove MULTIPLE newline characters from the end of the file, again use cmd substitution:

    printf "%s" "$(< log.txt)"
    

    If you want to strictly remove THE LAST newline character from a file, use Perl:

    perl -pe 'chomp if eof' log.txt
    

    Note that if you are certain you have a trailing newline character you want to remove, you can use head from GNU coreutils to select everything except the last byte. This should be quite quick:

    head -c -1 log.txt
    

    Also, for completeness, you can quickly check where your newline (or other special) characters are in your file using cat and the 'show-all' flag -A. The dollar sign character will indicate the end of each line:

    cat -A log.txt
    

    Python pandas insert list into a cell

    Quick work around

    Simply enclose the list within a new list, as done for col2 in the data frame below. The reason it works is that python takes the outer list (of lists) and converts it into a column as if it were containing normal scalar items, which is lists in our case and not normal scalars.

    mydict={'col1':[1,2,3],'col2':[[1, 4], [2, 5], [3, 6]]}
    data=pd.DataFrame(mydict)
    data
    
    
       col1     col2
    0   1       [1, 4]
    1   2       [2, 5]
    2   3       [3, 6]
    

    Request format is unrecognized for URL unexpectedly ending in

    a WebMethod which requires a ContextKey,

    [WebMethod]
    public string[] GetValues(string prefixText, int count, string contextKey)
    

    when this key is not set, got the exception.

    Fixing it by assigning AutoCompleteExtender's key.

    ac.ContextKey = "myKey";
    

    HTML input arrays

    It's just PHP, not HTML.

    It parses all HTML fields with [] into an array.

    So you can have

    <input type="checkbox" name="food[]" value="apple" />
    <input type="checkbox" name="food[]" value="pear" />
    

    and when submitted, PHP will make $_POST['food'] an array, and you can access its elements like so:

    echo $_POST['food'][0]; // would output first checkbox selected
    

    or to see all values selected:

    foreach( $_POST['food'] as $value ) {
        print $value;
    }
    

    Anyhow, don't think there is a specific name for it

    JavaFX Location is not set error message

    I had faced he similar problem however it got resolved once i renamed the file , so i would suggest that you should

    "Just rename the file"

    How can I prevent java.lang.NumberFormatException: For input string: "N/A"?

    "N/A" is not an integer. It must throw NumberFormatException if you try to parse it to an integer.

    Check before parsing or handle Exception properly.

    1. Exception Handling

      try{
          int i = Integer.parseInt(input);
      } catch(NumberFormatException ex){ // handle your exception
          ...
      }
      

    or - Integer pattern matching -

    String input=...;
    String pattern ="-?\\d+";
    if(input.matches("-?\\d+")){ // any positive or negetive integer or not!
     ...
    }
    

    How to send Basic Auth with axios

    An example (axios_example.js) using Axios in Node.js:

    const axios = require('axios');
    const express = require('express');
    const app = express();
    const port = process.env.PORT || 5000;
    
    app.get('/search', function(req, res) {
        let query = req.query.queryStr;
        let url = `https://your.service.org?query=${query}`;
    
        axios({
            method:'get',
            url,
            auth: {
                username: 'xxxxxxxxxxxxx',
                password: 'xxxxxxxxxxxxx'
            }
        })
        .then(function (response) {
            res.send(JSON.stringify(response.data));
        })
        .catch(function (error) {
            console.log(error);
        });
    });
    
    var server = app.listen(port);
    

    Be sure in your project directory you do:

    npm init
    npm install express
    npm install axios
    node axios_example.js
    

    You can then test the Node.js REST API using your browser at: http://localhost:5000/search?queryStr=xxxxxxxxx

    Ref: https://github.com/axios/axios

    How to add a spinner icon to button when it's in the Loading state?

    A lazy way to do this is with the UTF-8 entity code for a half circle \25E0 (aka &#x25e0;), which looks like ? and then keyframe animate it. It's a simple as:

    _x000D_
    _x000D_
    .busy
    {
    animation: spin 1s infinite linear;
    display:inline-block;
    font-weight: bold;
    font-family: sans-serif;
    font-size: 35px;
    font-style:normal;
    color:#555;
    }
    
    .busy::before
    {
    content:"\25E0";
    }
    
    @keyframes spin
    {
    0% {transform: rotate(0deg);}
    100% {transform: rotate(359deg);}
    }
    _x000D_
    <i class="busy"></i>
    _x000D_
    _x000D_
    _x000D_

    Indirectly referenced from required .class file

    Have you Googled for "weblogic ExpressionMap"? Do you know what it is and what it does?

    Looks like you definitely need to be compiling alongside Weblogic and with Weblogic's jars included in your Eclipse classpath, if you're not already.

    If you're not already working with Weblogic, then you need to find out what in the world is referencing it. You might need to do some heavy-duty grepping on your jars, classfiles, and/or source files looking for which ones include the string "weblogic".

    If I had to include something that was relying on this Weblogic class, but couldn't use Weblogic, I'd be tempted to try to reverse-engineer a compatible class. Create your own weblogic.utils.expressions.ExpressionMap class; see if everything compiles; use any resultant errors or warnings at compile-time or runtime to give you clues as to what methods and other members need to be in this class. Make stub methods that do nothing or return null if possible.

    Div table-cell vertical align not working

    see this bin: http://jsbin.com/yacom/2/edit

    should set parent element to

    display:table-cell;
    vertical-align:middle;
    text-align:center;
    

    When to throw an exception?

    the main reason for avoiding throwing an exception is that there is a lot of overhead involved with throwing an exception.

    One thing the article below states is that an exception is for an exceptional conditions and errors.

    A wrong user name is not necessarily a program error but a user error...

    Here is a decent starting point for exceptions within .NET: http://msdn.microsoft.com/en-us/library/ms229030(VS.80).aspx

    graphing an equation with matplotlib

    To plot an equation that is not solved for a specific variable (like circle or hyperbola):

    import numpy as np  
    import matplotlib.pyplot as plt  
    plt.figure() # Create a new figure window
    xlist = np.linspace(-2.0, 2.0, 100) # Create 1-D arrays for x,y dimensions
    ylist = np.linspace(-2.0, 2.0, 100) 
    X,Y = np.meshgrid(xlist, ylist) # Create 2-D grid xlist,ylist values
    F = X**2 + Y**2 - 1  #  'Circle Equation
    plt.contour(X, Y, F, [0], colors = 'k', linestyles = 'solid')
    plt.show()
    

    More about it: http://courses.csail.mit.edu/6.867/wiki/images/3/3f/Plot-python.pdf

    How do I concatenate strings in Swift?

    You can concatenate strings a number of ways:

    let a = "Hello"
    let b = "World"
    
    let first = a + ", " + b
    let second = "\(a), \(b)"
    

    You could also do:

    var c = "Hello"
    c += ", World"
    

    I'm sure there are more ways too.

    Bit of description

    let creates a constant. (sort of like an NSString). You can't change its value once you have set it. You can still add it to other things and create new variables though.

    var creates a variable. (sort of like NSMutableString) so you can change the value of it. But this has been answered several times on Stack Overflow, (see difference between let and var).

    Note

    In reality let and var are very different from NSString and NSMutableString but it helps the analogy.

    Display XML content in HTML page

    If you treat the content as text, not HTML, then DOM operations should cause the data to be properly encoded. Here's how you'd do it in jQuery:

    $('#container').text(xmlString);
    

    Here's how you'd do it with standard DOM methods:

    document.getElementById('container')
            .appendChild(document.createTextNode(xmlString));
    

    If you're placing the XML inside of HTML through server-side scripting, there are bound to be encoding functions to allow you to do that (if you add what your server-side technology is, we can give you specific examples of how you'd do it).

    Get Absolute Position of element within the window in wpf

    To get the absolute position of an UI element within the window you can use:

    Point position = desiredElement.PointToScreen(new Point(0d, 0d));
    

    If you are within an User Control, and simply want relative position of the UI element within that control, simply use:

    Point position = desiredElement.PointToScreen(new Point(0d, 0d)),
    controlPosition = this.PointToScreen(new Point(0d, 0d));
    
    position.X -= controlPosition.X;
    position.Y -= controlPosition.Y;
    

    How do I configure Apache 2 to run Perl CGI scripts?

    (Google search brought me to this question even though I did not ask for perl)

    I had a problem with running scripts (albeit bash not perl). Apache had a config of ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ however Apache error log showed File does not exist: /var/www/cgi-bin/test.html.

    Tried putting the script in both /usr/lib/cgi-bin/ and /var/www/cgi-bin/ but neither were working.

    After a prolonged googling session what cracked it for me was sudo a2enmod cgi and everything fell into place using /usr/lib/cgi-bin/.

    Determine .NET Framework version for dll

    Decompile it with ILDASM, and look at the version of mscorlib that is being referenced (should be pretty much right at the top).

    How can I select the record with the 2nd highest salary in database Oracle?

    select Max(Salary) as SecondHighestSalary from Employee where Salary not in (select max(Salary) from Employee)

    onClick not working on mobile (touch)

    better to use touchstart event with .on() jQuery method:

    $(window).load(function() { // better to use $(document).ready(function(){
        $('.List li').on('click touchstart', function() {
            $('.Div').slideDown('500');
        });
    });
    

    And i don't understand why you are using $(window).load() method because it waits for everything on a page to be loaded, this tend to be slow, while you can use $(document).ready() method which does not wait for each element on the page to be loaded first.

    How do I get the web page contents from a WebView?

    This is an answer based on jluckyiv's, but I think it is better and simpler to change Javascript as follows.

    browser.loadUrl("javascript:HTMLOUT.processHTML(document.documentElement.outerHTML);");
    

    Is JavaScript guaranteed to be single-threaded?

    I would say that the specification does not prevent someone from creating an engine that runs javascript on multiple threads, requiring the code to perform synchronization for accessing shared object state.

    I think the single-threaded non-blocking paradigm came out of the need to run javascript in browsers where ui should never block.

    Nodejs has followed the browsers' approach.

    Rhino engine however, supports running js code in different threads. The executions cannot share context, but they can share scope. For this specific case the documentation states:

    ..."Rhino guarantees that accesses to properties of JavaScript objects are atomic across threads, but doesn't make any more guarantees for scripts executing in the same scope at the same time.If two scripts use the same scope simultaneously, the scripts are responsible for coordinating any accesses to shared variables."

    From reading Rhino documentation I conclude that that it can be possible for someone to write a javascript api that also spawns new javascript threads, but the api would be rhino-specific (e.g. node can only spawn a new process).

    I imagine that even for an engine that supports multiple threads in javascript there should be compatibility with scripts that do not consider multi-threading or blocking.

    Concearning browsers and nodejs the way I see it is:

      1. Is all js code executed in a single thread? : Yes.
      1. Can js code cause other threads to run? : Yes.
      1. Can these threads mutate js execution context?: No. But they can (directly/indirectly(?)) append to the event queue from which listeners can mutate execution context. But don't be fooled, listeners run atomically on the main thread again.

    So, in case of browsers and nodejs (and probably a lot of other engines) javascript is not multithreaded but the engines themselves are.


    Update about web-workers:

    The presence of web-workers justifies further that javascript can be multi-threaded, in the sense that someone can create code in javascript that will run on a separate thread.

    However: web-workers do not curry the problems of traditional threads who can share execution context. Rules 2 and 3 above still apply, but this time the threaded code is created by the user (js code writer) in javascript.

    The only thing to consider is the number of spawned threads, from an efficiency (and not concurrency) point of view. See below:

    About thread safety:

    The Worker interface spawns real OS-level threads, and mindful programmers may be concerned that concurrency can cause “interesting” effects in your code if you aren't careful.

    However, since web workers have carefully controlled communication points with other threads, it's actually very hard to cause concurrency problems. There's no access to non-threadsafe components or the DOM. And you have to pass specific data in and out of a thread through serialized objects. So you have to work really hard to cause problems in your code.


    P.S.

    Besides theory, always be prepared about possible corner cases and bugs described on the accepted answer

    How to apply two CSS classes to a single element

    _x000D_
    _x000D_
    .color_x000D_
    {background-color:#21B286;}_x000D_
    .box_x000D_
    {_x000D_
      width:"100%";_x000D_
      height:"100px";_x000D_
      font-size: 16px;_x000D_
      text-align:center;_x000D_
      line-height:1.19em;_x000D_
    }_x000D_
    .box.color_x000D_
    {_x000D_
    width:"100%";_x000D_
    height:"100px";_x000D_
    font-size:16px;_x000D_
    color:#000000;_x000D_
    text-align:center;_x000D_
    }
    _x000D_
    <div class="box color">orderlist</div>
    _x000D_
    _x000D_
    _x000D_

    _x000D_
    _x000D_
    .color_x000D_
    {background-color:#21B286;}_x000D_
    .box_x000D_
    {_x000D_
      width:"100%";_x000D_
      height:"100px";_x000D_
      font-size: 16px;_x000D_
      text-align:center;_x000D_
      line-height:1.19em;_x000D_
    }_x000D_
    .box.color_x000D_
    {_x000D_
    width:"100%";_x000D_
    height:"100px";_x000D_
    font-size:16px;_x000D_
    color:#000000;_x000D_
    text-align:center;_x000D_
    }
    _x000D_
    <div class="box color">orderlist</div>
    _x000D_
    _x000D_
    _x000D_

    _x000D_
    _x000D_
    .color_x000D_
    {background-color:#21B286;}_x000D_
    .box_x000D_
    {_x000D_
      width:"100%";_x000D_
      height:"100px";_x000D_
      font-size: 16px;_x000D_
      text-align:center;_x000D_
      line-height:1.19em;_x000D_
    }_x000D_
    .box.color_x000D_
    {_x000D_
    width:"100%";_x000D_
    height:"100px";_x000D_
    font-size:16px;_x000D_
    color:#000000;_x000D_
    text-align:center;_x000D_
    }
    _x000D_
    <div class="box color">orderlist</div>
    _x000D_
    _x000D_
    _x000D_

    How do I get my C# program to sleep for 50 msec?

    Thread.Sleep(50);
    

    The thread will not be scheduled for execution by the operating system for the amount of time specified. This method changes the state of the thread to include WaitSleepJoin.

    This method does not perform standard COM and SendMessage pumping. If you need to sleep on a thread that has STAThreadAttribute, but you want to perform standard COM and SendMessage pumping, consider using one of the overloads of the Join method that specifies a timeout interval.

    Thread.Join
    

    Using PowerShell to remove lines from a text file if it contains a string

    Suppose you want to write that in the same file, you can do as follows:

    Set-Content -Path "C:\temp\Newtext.txt" -Value (get-content -Path "c:\Temp\Newtext.txt" | Select-String -Pattern 'H\|159' -NotMatch)
    

    scp (secure copy) to ec2 instance without password

    I've used below command to copy from local linux Centos 7 to AWS EC2.

    scp -i user_key.pem file.txt [email protected]:/home/ec2-user
    

    Encrypt and decrypt a string in C#?

    using System;
    using System.IO;
    using System.Security.Cryptography;
    using System.Text;
    
    public class Program
    {
        public static void Main()
        {
            var key = Encoding.UTF8.GetBytes("SUkbqO2ycDo7QwpR25kfgmC7f8CoyrZy");
            var data = Encoding.UTF8.GetBytes("testData");
    
            //Encrypt data
            var encrypted = CryptoHelper.EncryptData(data,key);
    
            //Decrypt data
            var decrypted = CryptoHelper.DecryptData(encrypted,key);
    
            //Display result
            Console.WriteLine(Encoding.UTF8.GetString(decrypted));
        }
    }
    
    public static class CryptoHelper
    {
        public static byte[] EncryptData(byte[] data, byte[] key)
        {
            using (var aesAlg = Aes.Create())
            {
                aesAlg.Mode = CipherMode.CBC;
                using (var encryptor = aesAlg.CreateEncryptor(key, aesAlg.IV))
                {
                    using (var msEncrypt = new MemoryStream())
                    {
                        msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
    
                        using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                            csEncrypt.Write(data, 0, data.Length);
    
                        return msEncrypt.ToArray();
                    }
                }
            }
    
        }
    
        public static byte[] DecryptData(byte[] encrypted, byte[] key)
        {
            var iv = new byte[16];
            Buffer.BlockCopy(encrypted, 0, iv, 0, iv.Length);
            using (var aesAlg = Aes.Create())
            {
                aesAlg.Mode = CipherMode.CBC;
                using (var decryptor = aesAlg.CreateDecryptor(key, iv))
                {
                    using (var msDecrypt = new MemoryStream(encrypted, iv.Length, encrypted.Length - iv.Length))
                    {
                        using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        {
                            using (var resultStream = new MemoryStream())
                            {
                                csDecrypt.CopyTo(resultStream);
                                return resultStream.ToArray();
                            }
                        }
                    }
                }
            }
        }
    }
    

    GridLayout and Row/Column Span Woe

    Starting from API 21, the GridLayout now supports the weight like LinearLayout. For details please see the link below:

    https://stackoverflow.com/a/31089200/1296944

    Regex for string contains?

    Just don't anchor your pattern:

    /Test/
    

    The above regex will check for the literal string "Test" being found somewhere within it.

    Removing header column from pandas dataframe

    I think you cant remove column names, only reset them by range with shape:

    print df.shape[1]
    2
    
    print range(df.shape[1])
    [0, 1]
    
    df.columns = range(df.shape[1])
    print df
        0   1
    0  23  12
    1  21  44
    2  98  21
    

    This is same as using to_csv and read_csv:

    print df.to_csv(header=None,index=False)
    23,12
    21,44
    98,21
    
    print pd.read_csv(io.StringIO(u""+df.to_csv(header=None,index=False)), header=None)
        0   1
    0  23  12
    1  21  44
    2  98  21
    

    Next solution with skiprows:

    print df.to_csv(index=False)
    A,B
    23,12
    21,44
    98,21
    
    print pd.read_csv(io.StringIO(u""+df.to_csv(index=False)), header=None, skiprows=1)
        0   1
    0  23  12
    1  21  44
    2  98  21
    

    Setting background colour of Android layout element

    You can use android:background="#DC143C", or any other RGB values for your color. I have no problem using it this way, as stated here

    java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of

    I was testing my application with the Android emulator and I solved this by turning off and turning on the Wi-Fi on the Android emulator device! It worked perfectly.

    Sqlite primary key on multiple columns

    The following code creates a table with 2 column as a primary key in SQLite.

    SOLUTION:

    CREATE TABLE IF NOT EXISTS users (
        id TEXT NOT NULL, 
        name TEXT NOT NULL, 
        pet_name TEXT, 
        PRIMARY KEY (id, name)
    )
    

    Get unique values from arraylist in java

    When I was doing the same query, I had hard time adjusting the solutions to my case, though all the previous answers have good insights.

    Here is a solution when one has to acquire a list of unique objects, NOT strings. Let's say, one has a list of Record object. Record class has only properties of type String, NO property of type int. Here implementing hashCode() becomes difficult as hashCode() needs to return an int.

    The following is a sample Record Class.

    public class Record{
    
        String employeeName;
        String employeeGroup;
    
        Record(String name, String group){  
            employeeName= name;
            employeeGroup = group;    
        }
        public String getEmployeeName(){
            return employeeName;
        }
        public String getEmployeeGroup(){
            return employeeGroup;
        }
    
      @Override
        public boolean equals(Object o){
             if(o instanceof Record){
                if (((Record) o).employeeGroup.equals(employeeGroup) &&
                      ((Record) o).employeeName.equals(employeeName)){
                    return true;
                }
             }
             return false;
        }
    
        @Override
        public int hashCode() { //this should return a unique code
            int hash = 3; //this could be anything, but I would chose a prime(e.g. 5, 7, 11 )
            //again, the multiplier could be anything like 59,79,89, any prime
            hash = 89 * hash + Objects.hashCode(this.employeeGroup); 
            return hash;
        }
    

    As suggested earlier by others, the class needs to override both the equals() and the hashCode() method to be able to use HashSet.

    Now, let's say, the list of Records is allRecord(List<Record> allRecord).

    Set<Record> distinctRecords = new HashSet<>();
    
    for(Record rc: allRecord){
        distinctRecords.add(rc);
    }
    

    This will only add the distinct Records to the Hashset, distinctRecords.

    Hope this helps.

    CSS - display: none; not working

    Remove display: block; in the div #tfl style property

    <div id="tfl" style="display: block; width: 187px; height: 260px;
    

    Inline style take priority then css file

    How to add System.Windows.Interactivity to project?

    Sometimes, when you add a new library, in introduces a clashing version of System.Windows.Interactivity.dll.

    For example, the NuGet package MVVM light might require v4.2 of System.Windows.Interactivity.dll, but the NuGet package Rx-XAML might require v4.5 of System.Windows.Interactivity.dll. This will prevent the the project from working, because no matter which version of System.Windows.Interactivity.dll you include, one of the libraries will refuse to compile.

    To fix, add an Assembly Binding Redirect by editing your app.config to look something like this:

    <?xml version="1.0"?>
    <configuration>
    <runtime>
      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <dependentAssembly>
          <assemblyIdentity name="System.Windows.Interactivity"
                            publicKeyToken="31bf3856ad364e35"
                            culture="neutral"/>
          <bindingRedirect oldVersion="4.0.0.0"
                           newVersion="4.5.0.0" />
        </dependentAssembly>
      </assemblyBinding>
    </runtime>
    <startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/></startup>
    <appSettings>
      <add key="TestKey" value="true"/>
    </appSettings>
    

    Don't worry about changing the PublicKeyToken, that's constant across all versions, as it depends on the name of the .dll, not the version.

    Ensure that you match the newVersion in your appConfig to the actual version that you end up pointing at:

    enter image description here

    JSON find in JavaScript

    General Solution

    We use object-scan for a lot of data processing. It has some nice properties, especially traversing in delete safe order. Here is how one could implement find, delete and replace for your question.

    _x000D_
    _x000D_
    // const objectScan = require('object-scan');
    
    const tool = (() => {
      const scanner = objectScan(['[*]'], {
        abort: true,
        rtn: 'bool',
        filterFn: ({
          value, parent, property, context
        }) => {
          if (value.id === context.id) {
            context.fn({ value, parent, property });
            return true;
          }
          return false;
        }
      });
      return {
        add: (data, id, obj) => scanner(data, { id, fn: ({ parent, property }) => parent.splice(property + 1, 0, obj) }),
        del: (data, id) => scanner(data, { id, fn: ({ parent, property }) => parent.splice(property, 1) }),
        mod: (data, id, prop, v = undefined) => scanner(data, {
          id,
          fn: ({ value }) => {
            if (value !== undefined) {
              value[prop] = v;
            } else {
              delete value[prop];
            }
          }
        })
      };
    })();
    
    // -------------------------------
    
    const data = [ { id: 'one', pId: 'foo1', cId: 'bar1' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ];
    const toAdd = { id: 'two', pId: 'foo2', cId: 'bar2' };
    
    const exec = (fn) => {
      console.log('---------------');
      console.log(fn.toString());
      console.log(fn());
      console.log(data);
    };
    
    exec(() => tool.add(data, 'one', toAdd));
    exec(() => tool.mod(data, 'one', 'pId', 'zzz'));
    exec(() => tool.mod(data, 'one', 'other', 'test'));
    exec(() => tool.mod(data, 'one', 'gone', 'delete me'));
    exec(() => tool.mod(data, 'one', 'gone'));
    exec(() => tool.del(data, 'three'));
    
    // => ---------------
    // => () => tool.add(data, 'one', toAdd)
    // => true
    // => [ { id: 'one', pId: 'foo1', cId: 'bar1' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
    // => ---------------
    // => () => tool.mod(data, 'one', 'pId', 'zzz')
    // => true
    // => [ { id: 'one', pId: 'zzz', cId: 'bar1' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
    // => ---------------
    // => () => tool.mod(data, 'one', 'other', 'test')
    // => true
    // => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
    // => ---------------
    // => () => tool.mod(data, 'one', 'gone', 'delete me')
    // => true
    // => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: 'delete me' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
    // => ---------------
    // => () => tool.mod(data, 'one', 'gone')
    // => true
    // => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: undefined }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
    // => ---------------
    // => () => tool.del(data, 'three')
    // => true
    // => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: undefined }, { id: 'two', pId: 'foo2', cId: 'bar2' } ]
    _x000D_
    .as-console-wrapper {max-height: 100% !important; top: 0}
    _x000D_
    <script src="https://bundle.run/[email protected]"></script>
    _x000D_
    _x000D_
    _x000D_

    Disclaimer: I'm the author of object-scan

    How to ignore parent css style

    It must be overridden. You could use:

    <!-- Add a class name to override -->
    <select name="funTimes" class="funTimes" size="5">
    
    #elementId select.funTimes {
       /* Override styles here */
    }
    

    Make sure you use !important flag in css style e.g. margin-top: 0px !important What does !important mean in CSS?

    You could use an attribute selector, but since that isn't supported by legacy browsers (read IE6 etc), it's better to add a class name

    How to pick just one item from a generator?

    For picking just one element of a generator use break in a for statement, or list(itertools.islice(gen, 1))

    According to your example (literally) you can do something like:

    while True:
      ...
      if something:
          for my_element in myfunct():
              dostuff(my_element)
              break
          else:
              do_generator_empty()
    

    If you want "get just one element from the [once generated] generator whenever I like" (I suppose 50% thats the original intention, and the most common intention) then:

    gen = myfunct()
    while True:
      ...
      if something:
          for my_element in gen:
              dostuff(my_element)
              break
          else:
              do_generator_empty()
    

    This way explicit use of generator.next() can be avoided, and end-of-input handling doesn't require (cryptic) StopIteration exception handling or extra default value comparisons.

    The else: of for statement section is only needed if you want do something special in case of end-of-generator.

    Note on next() / .next():

    In Python3 the .next() method was renamed to .__next__() for good reason: its considered low-level (PEP 3114). Before Python 2.6 the builtin function next() did not exist. And it was even discussed to move next() to the operator module (which would have been wise), because of its rare need and questionable inflation of builtin names.

    Using next() without default is still very low-level practice - throwing the cryptic StopIteration like a bolt out of the blue in normal application code openly. And using next() with default sentinel - which best should be the only option for a next() directly in builtins - is limited and often gives reason to odd non-pythonic logic/readablity.

    Bottom line: Using next() should be very rare - like using functions of operator module. Using for x in iterator , islice, list(iterator) and other functions accepting an iterator seamlessly is the natural way of using iterators on application level - and quite always possible. next() is low-level, an extra concept, unobvious - as the question of this thread shows. While e.g. using break in for is conventional.

    Notepad++ cached files location

    I lost somehow my temporary notepad++ files, they weren't showing in tabs. So I did some search in appdata folder, and I found all my temporary files there. It seems that they are stored there for a long time.

    C:\Users\USER\AppData\Roaming\Notepad++\backup
    

    or

    %AppData%\Notepad++\backup
    

    How can I convert an HTML element to a canvas element?

    You could spare yourself the transformations, you could use CSS3 Transitions to flip <div>'s and <ol>'s and any HTML tag you want. Here are some demos with source code explain to see and learn: http://www.webdesignerwall.com/trends/47-amazing-css3-animation-demos/

    What is polymorphism, what is it for, and how is it used?

    Let's use an analogy. For a given musical script every musician which plays it gives her own touch in the interpretation.

    Musician can be abstracted with interfaces, genre to which musician belongs can be an abstrac class which defines some global rules of interpretation and every musician who plays can be modeled with a concrete class.

    If you are a listener of the musical work, you have a reference to the script e.g. Bach's 'Fuga and Tocata' and every musician who performs it does it polymorphicaly in her own way.

    This is just an example of a possible design (in Java):

    public interface Musician {
      public void play(Work work);
    }
    
    public interface Work {
      public String getScript();
    }
    
    public class FugaAndToccata implements Work {
      public String getScript() {
        return Bach.getFugaAndToccataScript();
      }
    }
    
    public class AnnHalloway implements Musician {
      public void play(Work work) {
        // plays in her own style, strict, disciplined
        String script = work.getScript()
      }
    }
    
    public class VictorBorga implements Musician {
      public void play(Work work) {
        // goofing while playing with superb style
        String script = work.getScript()
      }
    }
    
    public class Listener {
      public void main(String[] args) {
        Musician musician;
        if (args!=null && args.length > 0 && args[0].equals("C")) {
          musician = new AnnHalloway();
        } else {
          musician = new TerryGilliam();
        }
        musician.play(new FugaAndToccata());
    }
    

    How to compare numbers in bash?

    If you have floats you can write a function and then use that e.g.

    #!/bin/bash
    
    function float_gt() {
        perl -e "{if($1>$2){print 1} else {print 0}}"
    }
    
    x=3.14
    y=5.20
    if [ $(float_gt $x $y) == 1 ] ; then
        echo "do stuff with x"
    else
        echo "do stuff with y"
    fi
    

    Don't reload application when orientation changes

    I dont know if the a best solution, but i describe it here:

    First of all, you need certificate with you class Application of your app is in your manifest of this:

    <application
        android:name=".App"
        ...
    

    Second, in my class App i did like this:

    public class App extends Application {
        public static boolean isOrientationChanged = false;
    
        @Override
        public void onCreate() {
            super.onCreate();
        }
    
        @Override
        public void onConfigurationChanged(@NotNull Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
            if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE ||
                    newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
                isOrientationChanged = true;
            }
        }
    
    }
    

    Third, you need to set a flag to Orientation Change, in my case, I always set it when the previous activity within the app navigation is called, so only calling once when the later activity is created.

    isOrientationChanged = false;
    

    So every time I change the orientation of my screen in that context, I set it every time it changes this setting, it checks if there is a change in orientation, if so, it validates it based on the value of that flag.

    Basically, I had to use it whenever I made an asynchronous retrofit request, which he called every moment that changed orientation, constantly crashing the application:

    if (!isOrientationChanged) {
        presenter.retrieveAddress(this, idClient, TYPE_ADDRESS);
    }
    

    I don't know if it's the most elegant and beautiful solution, but at least here it's functional :)

    What is the difference between match_parent and fill_parent?

    Google changed the name to avoid confusion.

    Problem with the old name fill parent was that it implies its affecting the dimensions of the parent, while match parent better describes the resulting behavior - match the dimension with the parent.

    Both constants resolve to -1 in the end, and so result in the identical behavior in the app. Ironically enough, this name change made to clarify things seems to have added confusion rather than eliminating it.

    SQL Error: ORA-00942 table or view does not exist

    Case sensitive Tables (table names created with double-quotes) can throw this same error as well. See this answer for more information.

    Simply wrap the table in double quotes:

    INSERT INTO "customer" (c_id,name,surname) VALUES ('1','Micheal','Jackson')
    

    The provider is not compatible with the version of Oracle client

    This issue could by happen while using unmanaged oracle reference if you have more than one oracle client , or sometimes if you reference different version
    There is two way to solve it :

    1. First and fast solution is to remove unmanaged reference and use the managed one from NuGet see this before to go with this option Differences between the ODP.NET Managed Driver and Unmanaged Driver

    2. Second solution is to fix project unmanaged target version like the below :

    • First Check oracle project reference version (from project references/(dependencies > assemblies ) > Oracle.DataAccess right click > properties):

      enter image description here

      enter image description here

    Then check oracle GAC version

    • got to gac from run (Win+R) "%windir%\Microsoft.NET\assembly"
      enter image description here

    • Check the platform that matches with you project platform

      enter image description here

    • to check you target platform (right click on your project > properties)

      enter image description here

    • From gac folder search to Oracle.DataAccess

      enter image description here

    • Right Click on Oracle.DataAccess > properties > details and check version

      enter image description here

    • if you notice the versions are different this is an the issue and to fix it we need to redirect assembly version (in startup project go to config file and add the below section )

    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="Oracle.DataAccess" publicKeyToken="89b483f429c47342" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="4.121.2.0" />
          </dependentAssembly>
    </assemblyBinding>
    
    

    like this enter image description here

    oldVersion : should be cover your project version newVersion : GAC version publicKeyToken : From GAC

    enter image description here

    How to Set Selected value in Multi-Value Select in Jquery-Select2.?

    This is with reference to the original question
    $('select').val(['a','c']);
    $('select').trigger('change');
    

    How to open child forms positioned within MDI parent in VB.NET?

    Try adding a button on mdi parent and add this code' to set your mdi child inside the mdi parent. change the yourchildformname to your MDI Child's form name and see if this works.

        Dim NewMDIChild As New yourchildformname()
        'Set the Parent Form of the Child window.
        NewMDIChild.MdiParent = Me
        'Display the new form.
        NewMDIChild.Show()
    

    What does the "@" symbol do in SQL?

    @ is used as a prefix denoting stored procedure and function parameter names, and also variable names

    Location of the mongodb database on mac

    If mongodb is installed via Homebrew the default location is:

    /usr/local/var/mongodb

    See the answer from @simonbogarde for the location of other interesting files that are different when using Homebrew.

    How to print spaces in Python?

    Any of the following will work:

    print 'Hello\nWorld'
    
    print 'Hello'
    print 'World'
    

    Additionally, if you want to print a blank line (not make a new line), print or print() will work.

    Convert a string into an int

    I had to do something like this but wanted to use a getter/setter for mine. In particular I wanted to return a long from a textfield. The other answers all worked well also, I just ended up adapting mine a little as my school project evolved.

    long ms = [self.textfield.text longLongValue];
    return ms;
    

    PHP Remove elements from associative array

    Try this:

    $keys = array_keys($array, "Completed");
    

    /edit As mentioned by JohnP, this method only works for non-nested arrays.

    When to use LinkedList over ArrayList in Java?

    Correct or Incorrect: Please execute test locally and decide for yourself!

    Edit/Remove is faster in LinkedList than ArrayList.

    ArrayList, backed by Array, which needs to be double the size, is worse in large volume application.

    Below is the unit test result for each operation.Timing is given in Nanoseconds.


    Operation                       ArrayList                      LinkedList  
    
    AddAll   (Insert)               101,16719                      2623,29291 
    
    Add      (Insert-Sequentially)  152,46840                      966,62216
    
    Add      (insert-randomly)      36527                          29193
    
    remove   (Delete)               20,56,9095                     20,45,4904
    
    contains (Search)               186,15,704                     189,64,981
    

    Here's the code:

    import org.junit.Assert;
    import org.junit.Test;
    
    import java.util.*;
    
    public class ArrayListVsLinkedList {
        private static final int MAX = 500000;
        String[] strings = maxArray();
    
        ////////////// ADD ALL ////////////////////////////////////////
        @Test
        public void arrayListAddAll() {
            Watch watch = new Watch();
            List<String> stringList = Arrays.asList(strings);
            List<String> arrayList = new ArrayList<String>(MAX);
    
            watch.start();
            arrayList.addAll(stringList);
            watch.totalTime("Array List addAll() = ");//101,16719 Nanoseconds
        }
    
        @Test
        public void linkedListAddAll() throws Exception {
            Watch watch = new Watch();
            List<String> stringList = Arrays.asList(strings);
    
            watch.start();
            List<String> linkedList = new LinkedList<String>();
            linkedList.addAll(stringList);
            watch.totalTime("Linked List addAll() = ");  //2623,29291 Nanoseconds
        }
    
        //Note: ArrayList is 26 time faster here than LinkedList for addAll()
    
        ///////////////// INSERT /////////////////////////////////////////////
        @Test
        public void arrayListAdd() {
            Watch watch = new Watch();
            List<String> arrayList = new ArrayList<String>(MAX);
    
            watch.start();
            for (String string : strings)
                arrayList.add(string);
            watch.totalTime("Array List add() = ");//152,46840 Nanoseconds
        }
    
        @Test
        public void linkedListAdd() {
            Watch watch = new Watch();
    
            List<String> linkedList = new LinkedList<String>();
            watch.start();
            for (String string : strings)
                linkedList.add(string);
            watch.totalTime("Linked List add() = ");  //966,62216 Nanoseconds
        }
    
        //Note: ArrayList is 9 times faster than LinkedList for add sequentially
    
        /////////////////// INSERT IN BETWEEN ///////////////////////////////////////
    
        @Test
        public void arrayListInsertOne() {
            Watch watch = new Watch();
            List<String> stringList = Arrays.asList(strings);
            List<String> arrayList = new ArrayList<String>(MAX + MAX / 10);
            arrayList.addAll(stringList);
    
            String insertString0 = getString(true, MAX / 2 + 10);
            String insertString1 = getString(true, MAX / 2 + 20);
            String insertString2 = getString(true, MAX / 2 + 30);
            String insertString3 = getString(true, MAX / 2 + 40);
    
            watch.start();
    
            arrayList.add(insertString0);
            arrayList.add(insertString1);
            arrayList.add(insertString2);
            arrayList.add(insertString3);
    
            watch.totalTime("Array List add() = ");//36527
        }
    
        @Test
        public void linkedListInsertOne() {
            Watch watch = new Watch();
            List<String> stringList = Arrays.asList(strings);
            List<String> linkedList = new LinkedList<String>();
            linkedList.addAll(stringList);
    
            String insertString0 = getString(true, MAX / 2 + 10);
            String insertString1 = getString(true, MAX / 2 + 20);
            String insertString2 = getString(true, MAX / 2 + 30);
            String insertString3 = getString(true, MAX / 2 + 40);
    
            watch.start();
    
            linkedList.add(insertString0);
            linkedList.add(insertString1);
            linkedList.add(insertString2);
            linkedList.add(insertString3);
    
            watch.totalTime("Linked List add = ");//29193
        }
    
    
        //Note: LinkedList is 3000 nanosecond faster than ArrayList for insert randomly.
    
        ////////////////// DELETE //////////////////////////////////////////////////////
        @Test
        public void arrayListRemove() throws Exception {
            Watch watch = new Watch();
            List<String> stringList = Arrays.asList(strings);
            List<String> arrayList = new ArrayList<String>(MAX);
    
            arrayList.addAll(stringList);
            String searchString0 = getString(true, MAX / 2 + 10);
            String searchString1 = getString(true, MAX / 2 + 20);
    
            watch.start();
            arrayList.remove(searchString0);
            arrayList.remove(searchString1);
            watch.totalTime("Array List remove() = ");//20,56,9095 Nanoseconds
        }
    
        @Test
        public void linkedListRemove() throws Exception {
            Watch watch = new Watch();
            List<String> linkedList = new LinkedList<String>();
            linkedList.addAll(Arrays.asList(strings));
    
            String searchString0 = getString(true, MAX / 2 + 10);
            String searchString1 = getString(true, MAX / 2 + 20);
    
            watch.start();
            linkedList.remove(searchString0);
            linkedList.remove(searchString1);
            watch.totalTime("Linked List remove = ");//20,45,4904 Nanoseconds
        }
    
        //Note: LinkedList is 10 millisecond faster than ArrayList while removing item.
    
        ///////////////////// SEARCH ///////////////////////////////////////////
        @Test
        public void arrayListSearch() throws Exception {
            Watch watch = new Watch();
            List<String> stringList = Arrays.asList(strings);
            List<String> arrayList = new ArrayList<String>(MAX);
    
            arrayList.addAll(stringList);
            String searchString0 = getString(true, MAX / 2 + 10);
            String searchString1 = getString(true, MAX / 2 + 20);
    
            watch.start();
            arrayList.contains(searchString0);
            arrayList.contains(searchString1);
            watch.totalTime("Array List addAll() time = ");//186,15,704
        }
    
        @Test
        public void linkedListSearch() throws Exception {
            Watch watch = new Watch();
            List<String> linkedList = new LinkedList<String>();
            linkedList.addAll(Arrays.asList(strings));
    
            String searchString0 = getString(true, MAX / 2 + 10);
            String searchString1 = getString(true, MAX / 2 + 20);
    
            watch.start();
            linkedList.contains(searchString0);
            linkedList.contains(searchString1);
            watch.totalTime("Linked List addAll() time = ");//189,64,981
        }
    
        //Note: Linked List is 500 Milliseconds faster than ArrayList
    
        class Watch {
            private long startTime;
            private long endTime;
    
            public void start() {
                startTime = System.nanoTime();
            }
    
            private void stop() {
                endTime = System.nanoTime();
            }
    
            public void totalTime(String s) {
                stop();
                System.out.println(s + (endTime - startTime));
            }
        }
    
    
        private String[] maxArray() {
            String[] strings = new String[MAX];
            Boolean result = Boolean.TRUE;
            for (int i = 0; i < MAX; i++) {
                strings[i] = getString(result, i);
                result = !result;
            }
            return strings;
        }
    
        private String getString(Boolean result, int i) {
            return String.valueOf(result) + i + String.valueOf(!result);
        }
    }
    

    Moment.js with ReactJS (ES6)

     import moment from 'moment';
     .....
    
      render() {
       return (
        <div>
            { 
            this.props.data.map((post,key) => 
                <div key={key} className="post-detail">
                    <h1>{post.title}</h1>
                    <p>{moment(post.date).calendar()}</p>
                    <p dangerouslySetInnerHTML={{__html: post.content}}></p>
                    <hr />
                </div>
            )}
        </div>
       );
      }
    

    How to compile C++ under Ubuntu Linux?

    To compile source.cpp, run

    g++ source.cpp
    

    This command will compile source.cpp to file a.out in the same directory. To run the compiled file, run

    ./a.out
    

    If you compile another source file, with g++ source2.cpp, the new compiled file a.out will overwrite the a.out generated with source.cpp

    If you want to compile source.cpp to a specific file, say compiledfile, run

    g++ source.cpp -o compiledfile
    

    or

    g++ -o compiledfile source.cpp
    

    This will create the compiledfile which is the compiled binary file. to run the compiledfile, run

    ./compiledfile
    

    If g++ is not in your $PATH, replace g++ with /usr/bin/g++.

    estimating of testing effort as a percentage of development time

    The only time I factor in extra time for testing is if I'm unfamiliar with the testing technology I'll be using (e.g. using Selenium tests for the first time). Then I factor in maybe 10-20% for getting up to speed on the tools and getting the test infrastructure in place.

    Otherwise testing is just an innate part of development and doesn't warrant an extra estimate. In fact, I'd probably increase the estimate for code done without tests.

    EDIT: Note that I'm usually writing code test-first. If I have to come in after the fact and write tests for existing code that's going to slow things down. I don't find that test-first development slows me down at all except for very exploratory (read: throw-away) coding.

    Why doesn't JavaScript have a last method?

    Another option, especially if you're already using UnderscoreJS, would be:

    _.last([1, 2, 3, 4]); // Will return 4
    

    How to iterate through XML in Powershell?

    You can also do it without the [xml] cast. (Although xpath is a world unto itself. https://www.w3schools.com/xml/xml_xpath.asp)

    $xml = (select-xml -xpath / -path stack.xml).node
    $xml.objects.object.property
    

    Or just this, xpath is case sensitive. Both have the same output:

    $xml = (select-xml -xpath /Objects/Object/Property -path stack.xml).node
    $xml
    
    
    Name         Type                                                #text
    ----         ----                                                -----
    DisplayName  System.String                                       SQL Server (MSSQLSERVER)
    ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Running
    DisplayName  System.String                                       SQL Server Agent (MSSQLSERVER)
    ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Stopped
    

    If/else else if in Jquery for a condition

    A few more things in addition to the existing answers. Have a look at this:

    var seatsValid = true;
    // cache the selector
    var seatsVal = $("#seats").val();
    if(seatsVal!=''){
        seatsValid = false;
        alert("Not a valid character")
        // convert seatsVal to an integer for comparison
    }else if(parseInt(seatsVal) < 99999){
        seatsValid = false;
        alert("Not a valid Number");
    }
    

    The variable name setFlag is very generic, if your only using it in conjunction with the number of seats you should rename it (I called it seatsValid). I also initialized it to true which gets rid of the need for the final else in your original code. Next, I put the selector and call to .val() in a variable. It's good practice to cache your selectors so jquery doesn't need to traverse the DOM more than it needs to. Lastly when comparing two values you should try to make sure they are the same type, in this case seatsVal is a string so in order to properly compare it to 99999 you should use parseInt() on it.

    glob exclude pattern

    More generally, to exclude files that don't comply with some shell regexp, you could use module fnmatch:

    import fnmatch
    
    file_list = glob('somepath')    
    for ind, ii in enumerate(file_list):
        if not fnmatch.fnmatch(ii, 'bash_regexp_with_exclude'):
            file_list.pop(ind)
    

    The above will first generate a list from a given path and next pop out the files that won't satisfy the regular expression with the desired constraint.

    Invalid column name sql error

    con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Yna Maningding-Dula\Documents\Visual Studio 2010\Projects\LuxuryHotel\LuxuryHotel\ClientsRecords.mdf;Integrated Security=True;User Instance=True");
            con.Open();
            cmd = new SqlCommand("INSERT INTO ClientData ([Last Name], [First Name], [Middle Name], Address, [Email Address], [Contact Number], Nationality, [Arrival Date], [Check-out Date], [Room Type], [Daily Rate], [No of Guests], [No of Rooms]) VALUES (@[Last Name], @[First Name], @[Middle Name], @Address, @[Email Address], @[Contact Number], @Nationality, @[Arrival Date], @[Check-out Date], @[Room Type], @[Daily Rate], @[No of Guests], @[No of Rooms]", con);
            cmd.Parameters.Add("@[Last Name]", txtLName.Text);
            cmd.Parameters.Add("@[First Name]", txtFName.Text);
            cmd.Parameters.Add("@[Middle Name]", txtMName.Text);
            cmd.Parameters.Add("@Address", txtAdd.Text);
            cmd.Parameters.Add("@[Email Address]", txtEmail.Text);
            cmd.Parameters.Add("@[Contact Number]", txtNumber.Text);
            cmd.Parameters.Add("@Nationality", txtNational.Text);
            cmd.Parameters.Add("@[Arrival Date]", txtArrive.Text);
            cmd.Parameters.Add("@[Check-out Date]", txtOut.Text);
            cmd.Parameters.Add("@[Room Type]", txtType.Text);
            cmd.Parameters.Add("@[Daily Rate]", txtRate.Text);
            cmd.Parameters.Add("@[No of Guests]", txtGuest.Text);
            cmd.Parameters.Add("@[No of Rooms]", txtRoom.Text);
            cmd.ExecuteNonQuery();
    

    UL has margin on the left

    I don't see any margin or margin-left declarations for #footer-wrap li.

    This ought to do the trick:

    #footer-wrap ul,
    #footer-wrap li {
        margin-left: 0;
        list-style-type: none;
    }
    

    Razor View Engine : An expression tree may not contain a dynamic operation

    This error happened to me because I had @@model instead of @model... copy & paste error in my case. Changing to @model fixed it for me.

    Can we pass model as a parameter in RedirectToAction?

    i did find something like this, helps get rid of hardcoded tempdata tags

    public class AccountController : Controller
    {
        [HttpGet]
        public ActionResult Index(IndexPresentationModel model)
        {
            return View(model);
        }
    
        [HttpPost]
        public ActionResult Save(SaveUpdateModel model)
        {
            // save the information
    
            var presentationModel = new IndexPresentationModel();
    
            presentationModel.Message = model.Message;
    
            return this.RedirectToAction(c => c.Index(presentationModel));
        }
    }
    

    'do...while' vs. 'while'

    If you always want the loop to execute at least once. It's not common, but I do use it from time to time. One case where you might want to use it is trying to access a resource that could require a retry, e.g.

    do
    {
       try to access resource...
       put up message box with retry option
    
    } while (user says retry);
    

    Center image in div horizontally

    A very simple and elegant solution to this is provided by W3C. Simply use the margin:0 auto declaration as follows:

    .top_image img { margin:0 auto; }
    

    More information and examples from W3C.

    How to dump raw RTSP stream to file?

    You can use mplayer.

    mencoder -nocache -rtsp-stream-over-tcp rtsp://192.168.XXX.XXX/test.sdp -oac copy -ovc copy -o test.avi
    

    The "copy" codec is just a dumb copy of the stream. Mencoder adds a header and stuff you probably want.

    In the mplayer source file "stream/stream_rtsp.c" is a prebuffer_size setting of 640k and no option to change the size other then recompile. The result is that writing the stream is always delayed, which can be annoying for things like cameras, but besides this, you get an output file, and can play it back most places without a problem.

    How to load a UIView using a nib file created with Interface Builder

    After spending many hours, I forged out following solution. Follow these steps to create custom UIView.

    1) Create class myCustomView inherited from UIView.
    enter image description here

    2) Create .xib with name myCustomView.
    enter image description here

    3) Change Class of UIView inside your .xib file, assign myCustomView Class there.
    enter image description here

    4) Create IBOutlets
    enter image description here

    5) Load .xib in myCustomView * customView. Use following sample code.

    myCustomView * myView = [[[NSBundle mainBundle] loadNibNamed:@"myCustomView" owner:self options:nil] objectAtIndex:0];
    [myView.description setText:@"description"];
    

    Note: For those who still face issue can comment, I will provide them link of sample project with myCustomView

    How to destroy a JavaScript object?

    You could put all of your code under one namespace like this:

    var namespace = {};
    
    namespace.someClassObj = {};
    
    delete namespace.someClassObj;
    

    Using the delete keyword will delete the reference to the property, but on the low level the JavaScript garbage collector (GC) will get more information about which objects to be reclaimed.

    You could also use Chrome Developer Tools to get a memory profile of your app, and which objects in your app are needing to be scaled down.

    Best practices for copying files with Maven

    I can only assume that your ${project.server.config} property is something custom defined and is outside of the standard directory layout.

    If so, then I'd use the copy task.

    String replace method is not replacing characters

    Strings are immutable, meaning their contents cannot change. When you call replace(this,that) you end up with a totally new String. If you want to keep this new copy, you need to assign it to a variable. You can overwrite the old reference (a la sentence = sentence.replace(this,that) or a new reference as seen below:

    public class Test{
    
        public static void main(String[] args) {
    
            String sentence = "Define, Measure, Analyze, Design and Verify";
    
            String replaced = sentence.replace("and", "");
            System.out.println(replaced);
    
        }
    }
    

    As an aside, note that I've removed the contains() check, as it is an unnecessary call here. If it didn't contain it, the replace will just fail to make any replacements. You'd only want that contains method if what you're replacing was different than the actual condition you're checking.

    Check whether a variable is a string in Ruby

    You can do:

    foo.instance_of?(String)
    

    And the more general:

    foo.kind_of?(String)
    

    Can jQuery get all CSS styles associated with an element?

    Two years late, but I have the solution you're looking for. Not intending to take credit form the original author, here's a plugin which I found works exceptionally well for what you need, but gets all possible styles in all browsers, even IE.

    Warning: This code generates a lot of output, and should be used sparingly. It not only copies all standard CSS properties, but also all vendor CSS properties for that browser.

    jquery.getStyleObject.js:

    /*
     * getStyleObject Plugin for jQuery JavaScript Library
     * From: http://upshots.org/?p=112
     */
    
    (function($){
        $.fn.getStyleObject = function(){
            var dom = this.get(0);
            var style;
            var returns = {};
            if(window.getComputedStyle){
                var camelize = function(a,b){
                    return b.toUpperCase();
                };
                style = window.getComputedStyle(dom, null);
                for(var i = 0, l = style.length; i < l; i++){
                    var prop = style[i];
                    var camel = prop.replace(/\-([a-z])/g, camelize);
                    var val = style.getPropertyValue(prop);
                    returns[camel] = val;
                };
                return returns;
            };
            if(style = dom.currentStyle){
                for(var prop in style){
                    returns[prop] = style[prop];
                };
                return returns;
            };
            return this.css();
        }
    })(jQuery);
    

    Basic usage is pretty simple, but he's written a function for that as well:

    $.fn.copyCSS = function(source){
      var styles = $(source).getStyleObject();
      this.css(styles);
    }
    

    Hope that helps.

    Linux command: How to 'find' only text files?

    How about this:

    $ grep -rl "needle text" my_folder | tr '\n' '\0' | xargs -r -0 file | grep -e ':[^:]*text[^:]*$' | grep -v -e 'executable'
    

    If you want the filenames without the file types, just add a final sed filter.

    $ grep -rl "needle text" my_folder | tr '\n' '\0' | xargs -r -0 file | grep -e ':[^:]*text[^:]*$' | grep -v -e 'executable' | sed 's|:[^:]*$||'
    

    You can filter-out unneeded file types by adding more -e 'type' options to the last grep command.

    EDIT:

    If your xargs version supports the -d option, the commands above become simpler:

    $ grep -rl "needle text" my_folder | xargs -d '\n' -r file | grep -e ':[^:]*text[^:]*$' | grep -v -e 'executable' | sed 's|:[^:]*$||'
    

    CSS list-style-image size

    Thanks to Chris for the starting point here is a improvement which addresses the resizing of the images used, the use of first-child is just to indicate you could use a variety of icons within the list to give you full control.

    ul li:first-child:before {
        content: '';
        display: inline-block;
        height: 25px;
        width: 35px;
        background-image: url('../images/Money.png');
        background-size: contain;
        background-repeat: no-repeat;
        margin-left: -35px;
    }
    

    This seems to work well in all modern browsers, you will need to ensure that the width and the negative margin left have the same value, hope it helps

    What is the difference between a deep copy and a shallow copy?

    Deep Copy

    A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.

    Shallow Copy

    Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.

    Draggable div without jQuery UI

    $(document).ready(function() {
        var $startAt = null;
    
        $(document.body).live("mousemove", function(e) {
            if ($startAt) {
                $("#someDiv").offset({
                    top: e.pageY,
                    left: $("#someDiv").position().left-$startAt+e.pageX
                });
                $startAt = e.pageX; 
            }
        });
    
        $("#someDiv").live("mousedown", function (e) {$startAt = e.pageX;});
        $(document.body).live("mouseup", function (e) {$startAt = null;});
    });
    

    LISTAGG function: "result of string concatenation is too long"

    We were able to solve a similar issue here using Oracle LISTAGG. There was a point where what we were grouping on exceeded the 4K limit but this was easily solved by having the first dataset take the first 15 items to aggregate, each of which have a 256K limit.

    More info: We have projects, which have change orders, which in turn have explanations. Why the database is set up to take change text in chunks of 256K limits is not known but its one of the design constraints. So the application that feeds change explanations into the table stops at 254K and inserts, then gets the next set of text and if > 254K generates another row, etc. So we have a project to a change order, a 1:1. Then we have these as 1:n for explanations. LISTAGG concatenates all these. We have RMRKS_SN values, 1 for each remark and/or for each 254K of characters.

    The largest RMRKS_SN was found to be 31, so I did the first dataset pulling SN 0 to 15, the 2nd dataset 16 to 30 and the last dataset 31 to 45 -- hey, let's plan on someone adding a LOT of explanation to some change orders!

    In the SQL report, the Tablix ties to the first dataset. To get the other data, here's the expression:

    =First(Fields!NON_STD_TXT.Value, "DataSet_EXPLAN") & First(Fields!NON_STD_TXT.Value, "ds_EXPLAN_SN_16_TO_30") & First(Fields!NON_STD_TXT.Value, "ds_EXPLAN_SN_31_TO_45")

    For us, we have to have DB Group create functions, etc. because of security constraints. So with a bit of creativity, we didn't have to do a User Aggregate or a UDF.

    If your application has some sort of SN to aggregate by, this method should work. I don't know what the equivalent TSQL is -- we're fortunate to be dealing with Oracle for this report, for which LISTAGG is a Godsend.

    The code is:

    SELECT
    LT.C_O_NBR AS LT_CO_NUM,
    RT.C_O_NBR AS RT_CO_NUM,
    LT.STD_LN_ITM_NBR, 
    RT.NON_STD_LN_ITM_NBR,
    RT.NON_STD_PRJ_NBR, 
    LT.STD_PRJ_NBR, 
    NVL(LT.PRPSL_LN_NBR, RT.PRPSL_LN_NBR) AS PRPSL_LN_NBR,
    LT.STD_CO_EXPL_TXT AS STD_TXT,
    LT.STD_CO_EXPLN_T, 
    LT.STD_CO_EXPL_SN, 
    RT.NON_STD_CO_EXPLN_T,
    LISTAGG(RT.RMRKS_TXT_FLD, '') 
        WITHIN GROUP(ORDER BY RT.RMRKS_SN) AS NON_STD_TXT
    
    FROM ...
    
        WHERE RT.RMRKS_SN BETWEEN 0 AND 15
    
    GROUP BY 
        LT.C_O_NBR,
        RT.C_O_NBR,
        ...
    

    And in the other 2 datasets just select the LISTAGG only for the subqueries in the FROM:

    SELECT
    LISTAGG(RT.RMRKS_TXT_FLD, '') 
        WITHIN GROUP(ORDER BY RT.RMRKS_SN) AS NON_STD_TXT
    

    FROM ...

    WHERE RT.RMRKS_SN BETWEEN 31 AND 45
    

    ...

    ... and so on.

    How do I replace a character at a particular index in JavaScript?

    I know this is old but the solution does not work for negative index so I add a patch to it. hope it helps someone

    String.prototype.replaceAt=function(index, character) {
        if(index>-1) return this.substr(0, index) + character + this.substr(index+character.length);
        else return this.substr(0, this.length+index) + character + this.substr(index+character.length);
    
    }
    

    Inserting data into a temporary table

    SELECT  ID , Date , Name into #temp from [TableName]
    

    How much overhead does SSL impose?

    Order of magnitude: zero.

    In other words, you won't see your throughput cut in half, or anything like it, when you add TLS. Answers to the "duplicate" question focus heavily on application performance, and how that compares to SSL overhead. This question specifically excludes application processing, and seeks to compare non-SSL to SSL only. While it makes sense to take a global view of performance when optimizing, that is not what this question is asking.

    The main overhead of SSL is the handshake. That's where the expensive asymmetric cryptography happens. After negotiation, relatively efficient symmetric ciphers are used. That's why it can be very helpful to enable SSL sessions for your HTTPS service, where many connections are made. For a long-lived connection, this "end-effect" isn't as significant, and sessions aren't as useful.


    Here's an interesting anecdote. When Google switched Gmail to use HTTPS, no additional resources were required; no network hardware, no new hosts. It only increased CPU load by about 1%.

    ASP.NET Forms Authentication failed for the request. Reason: The ticket supplied has expired

    Sounds like an error you would get when your forms authentication ticket has expired. What is the timeout period for your ticket? Is it set to sliding or absolute expiration?

    I believe the default for the timeout is 20 minutes with sliding expiration so if a user gets authenticated and at some point doesn't hit your site for 20 minutes their ticket would be expired. If it is set to absolute expiration it will expire X number of minutes after it was issued where X is your timeout setting.

    You can set the timeout and expiration policy (e.g. sliding, absolute) in your web/machine.config under /configuration/system.web/authentication/forms

    How do I unset an element in an array in javascript?

    http://www.internetdoc.info/javascript-function/remove-key-from-array.htm

    removeKey(arrayName,key);
    
    function removeKey(arrayName,key)
    {
     var x;
     var tmpArray = new Array();
     for(x in arrayName)
     {
      if(x!=key) { tmpArray[x] = arrayName[x]; }
     }
     return tmpArray;
    }
    

    JavaScript array to CSV

    The following code were written in ES6 and it will work in most of the browsers without an issue.

    _x000D_
    _x000D_
    var test_array = [["name1", 2, 3], ["name2", 4, 5], ["name3", 6, 7], ["name4", 8, 9], ["name5", 10, 11]];_x000D_
    _x000D_
    // Construct the comma seperated string_x000D_
    // If a column values contains a comma then surround the column value by double quotes_x000D_
    const csv = test_array.map(row => row.map(item => (typeof item === 'string' && item.indexOf(',') >= 0) ? `"${item}"`: String(item)).join(',')).join('\n');_x000D_
    _x000D_
    // Format the CSV string_x000D_
    const data = encodeURI('data:text/csv;charset=utf-8,' + csv);_x000D_
    _x000D_
    // Create a virtual Anchor tag_x000D_
    const link = document.createElement('a');_x000D_
    link.setAttribute('href', data);_x000D_
    link.setAttribute('download', 'export.csv');_x000D_
    _x000D_
    // Append the Anchor tag in the actual web page or application_x000D_
    document.body.appendChild(link);_x000D_
    _x000D_
    // Trigger the click event of the Anchor link_x000D_
    link.click();_x000D_
    _x000D_
    // Remove the Anchor link form the web page or application_x000D_
    document.body.removeChild(link);
    _x000D_
    _x000D_
    _x000D_

    Change image source in code behind - Wpf

    The pack syntax you are using here is for an image that is contained as a Resource within your application, not for a loose file in the file system.

    You simply want to pass the actual path to the UriSource:

    logo.UriSource = new Uri(@"\\myserver\folder1\Customer Data\sample.png");
    

    Get random item from array

    Use PHP Rand function

    <?php
      $input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
      $rand_keys = array_rand($input, 2);
      echo $input[$rand_keys[0]] . "\n";
      echo $input[$rand_keys[1]] . "\n";
    ?>
    

    More Help

    Is there a css cross-browser value for "width: -moz-fit-content;"?

    I use these:

    .right {display:table; margin:-18px 0 0 auto;}
    .center {display:table; margin:-18px auto 0 auto;}
    

    How To Define a JPA Repository Query with a Join

    You are experiencing this issue for two reasons.

    • The JPQL Query is not valid.
    • You have not created an association between your entities that the underlying JPQL query can utilize.

    When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)

    User.java

    @Entity
    @Table(name="user")
    public class User {
    
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        @Column(name="iduser")
        private Long idUser;
    
        @Column(name="user_name")
        private String userName;
    
        @OneToOne()
        @JoinColumn(name="idarea")
        private Area area;
    
        public Long getIdUser() {
            return idUser;
        }
    
        public void setIdUser(Long idUser) {
            this.idUser = idUser;
        }
    
        public String getUserName() {
            return userName;
        }
    
        public void setUserName(String userName) {
            this.userName = userName;
        }
    
        public Area getArea() {
            return area;
        }
    
        public void setArea(Area area) {
            this.area = area;
        }
    }
    

    Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:

    @Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")
    

    While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.

    Area.java

    @Entity
    @Table(name = "area")
    public class Area {
    
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        @Column(name="idarea")
        private Long idArea;
    
        @Column(name="area_name")
        private String areaName;
    
        @OneToOne(fetch=FetchType.LAZY, mappedBy="area")
        private User user;
    
        public Long getIdArea() {
            return idArea;
        }
    
        public void setIdArea(Long idArea) {
            this.idArea = idArea;
        }
    
        public String getAreaName() {
            return areaName;
        }
    
        public void setAreaName(String areaName) {
            this.areaName = areaName;
        }
    
        public User getUser() {
            return user;
        }
    
        public void setUser(User user) {
            this.user = user;
        }
    }
    

    Angularjs error Unknown provider

    Make sure you are loading those modules (myApp.services and myApp.directives) as dependencies of your main app module, like this:

    angular.module('myApp', ['myApp.directives', 'myApp.services']);
    

    plunker: http://plnkr.co/edit/wxuFx6qOMfbuwPq1HqeM?p=preview

    Origin http://localhost is not allowed by Access-Control-Allow-Origin

    If you want everyone to be able to access the Node app, then try using

    res.header('Access-Control-Allow-Origin', "*")
    

    That will allow requests from any origin. The CORS enable site has a lot of information on the different Access-Control-Allow headers and how to use them.

    I you are using Chrome, please look at this bug bug regarding localhost and Access-Control-Allow-Origin. There is another StackOverflow question here that details the issue.

    Lodash .clone and .cloneDeep behaviors

    Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.

    As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:

    var clone = _.clone(data, true);
    
    data[1].values.d = 'x';
    

    I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.

    Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).

    Windows Explorer "Command Prompt Here"

    Inside your current folder, simply press Shift+Alt+F --then--> Enter.

    The prompt will appear with your current folder's path set.

    Note: That works only in Windows 7 / Vista. What it does is that drops the "File" menu down for you, because the "Shift" key is pressed the option "Open command window here" is enabled and focused as the first available option of "File" menu. Pressing enter starts the focused option therefor the command window.

    Edit:

    In case you are in a folder and you already selected some of its contents (file/folder) this wont work. In that case Click on the empty area inside the folder to deselect any previously selected files and repeat.

    Edit2:

    Another way you can open terminal in current directory is to type cmd on file browser navigation bar where the path of current folder is written.

    In order to focus with your keyboard on the navigation bar Ctrl+L. Then you can type cmd and hit Enter

    Creating a batch file, for simple javac and java command execution

    Am i understanding your question only? You need .bat file to compile and execute java class files?

    if its a .bat file. you can just double click.

    and in your .bat file, you just need to javac Main.java ((make sure your bat has the path to ur Main.java) java Main

    If you want to echo compilation warnings/statements, that would need something else. But since, you want that to be automated, maybe you eventually don't need that.

    href="tel:" and mobile numbers

    The BlackBerry browser and Safari for iOS (iPhone/iPod/iPad) automatically detect phone numbers and email addresses and convert them to links. If you don’t want this feature, you should use the following meta tags.

    For Safari:

    <meta name="format-detection" content="telephone=no">
    

    For BlackBerry:

    <meta http-equiv="x-rim-auto-match" content="none">
    

    Source: mobilexweb.com

    MySQL stored procedure return value

    Update your SP and handle exception in it using declare handler with get diagnostics so that you will know if there is an exception. e.g.

    CREATE DEFINER=`root`@`localhost` PROCEDURE `validar_egreso`(
    IN codigo_producto VARCHAR(100),
    IN cantidad INT,
    OUT valido INT(11)
    )
    BEGIN
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
        GET DIAGNOSTICS CONDITION 1
        @p1 = RETURNED_SQLSTATE, @p2 = MESSAGE_TEXT;
        SELECT @p1, @p2;
    END
    DECLARE resta INT(11);
    SET resta = 0;
    
    SELECT (s.stock - cantidad) INTO resta
    FROM stock AS s
    WHERE codigo_producto = s.codigo;
    
    IF (resta > s.stock_minimo) THEN
        SET valido = 1;
    ELSE
        SET valido = -1;
    END IF;
    SELECT valido;
    END
    

    Should I use JSLint or JSHint JavaScript validation?

    tl;dr takeaway:

    If you're looking for a very high standard for yourself or team, JSLint. But its not necessarily THE standard, just A standard, some of which comes to us dogmatically from a javascript god named Doug Crockford. If you want to be a bit more flexible, or have some old pros on your team that don't buy into JSLint's opinions, or are going back and forth between JS and other C-family languages on a regular basis, try JSHint.

    long version:

    The reasoning behind the fork explains pretty well why JSHint exists:

    http://badassjs.com/post/3364925033/jshint-an-community-driven-fork-of-jslint http://anton.kovalyov.net/2011/02/20/why-i-forked-jslint-to-jshint/

    So I guess the idea is that it's "community-driven" rather than Crockford-driven. In practicality, JSHint is generally a bit more lenient (or at least configurable or agnostic) on a few stylistic and minor syntactical "opinions" that JSLint is a stickler on.

    As an example, if you think both the A and B below are fine, or if you want to write code with one or more of the aspects of A that aren't available in B, JSHint is for you. If you think B is the only correct option... JSLint. I'm sure there are other differences, but this highlights a few.

    A) Passes JSHint out of the box - fails JSLint

    (function() {
      "use strict";
      var x=0, y=2;
      function add(val1, val2){
        return val1 + val2;
      }
      var z;
      for (var i=0; i<2; i++){
        z = add(y, x+i);
      }
    })();
    

    B) Passes Both JSHint and JSLint

    (function () {
        "use strict";
        var x = 0, y = 2, i, z;
        function add(val1, val2) {
           return val1 + val2;
        }
        for (i = 0; i < 2; i += 1) {
            z = add(y, x + i);
        }
    }());
    

    Personally I find JSLint code very nice to look at, and the only hard features of it that I disagree with are its hatred of more than one var declaration in a function and of for-loop var i = 0 declarations, and some of the whitespace enforcements for function declarations.

    A few of the whitespace things that JSLint enforces, I find to be not necessarily bad, but out of sync with some pretty standard whitespace conventions for other languages in the family (C, Java, Python, etc...), which are often followed as conventions in Javascript as well. Since I'm writing in various of these languages throughout the day, and working with team members who don't like Lint-style whitespace in our code, I find JSHint to be a good balance. It catches stuff that's a legitimate bug or really bad form, but doesn't bark at me like JSLint does (sometimes, in ways I can't disable) for the stylistic opinions or syntactic nitpicks that I don't care for.

    A lot of good libraries aren't Lint'able, which to me demonstrates that there's some truth to the idea that some of JSLint is simply just about pushing 1 version of "good code" (which is, indeed, good code). But then again, the same libraries (or other good ones) probably aren't Hint'able either, so, touché.

    Type of expression is ambiguous without more context Swift

    Explicitly declaring the inputs for that mapping function should do the trick:

    let imageToDeleteParameters  = imagesToDelete.map {
        (whatever : WhateverClass) -> Dictionary<String, Any> in
        ["id": whatever.id, "url": whatever.url.absoluteString, "_destroy": true]
    }
    

    Substitute the real class of "$0" for "WhateverClass" in that code snippet, and it should work.

    Parsing boolean values with argparse

    Simplest & most correct way is:

    from distutils.util import strtobool
    
    parser.add_argument('--feature', dest='feature', 
                        type=lambda x: bool(strtobool(x)))
    

    Do note that True values are y, yes, t, true, on and 1; false values are n, no, f, false, off and 0. Raises ValueError if val is anything else.

    How to save an image locally using Python whose URL address I already know?

    Version for Python 3

    I adjusted the code of @madprops for Python 3

    # getem.py
    # python2 script to download all images in a given url
    # use: python getem.py http://url.where.images.are
    
    from bs4 import BeautifulSoup
    import urllib.request
    import shutil
    import requests
    from urllib.parse import urljoin
    import sys
    import time
    
    def make_soup(url):
        req = urllib.request.Request(url, headers={'User-Agent' : "Magic Browser"}) 
        html = urllib.request.urlopen(req)
        return BeautifulSoup(html, 'html.parser')
    
    def get_images(url):
        soup = make_soup(url)
        images = [img for img in soup.findAll('img')]
        print (str(len(images)) + " images found.")
        print('Downloading images to current working directory.')
        image_links = [each.get('src') for each in images]
        for each in image_links:
            try:
                filename = each.strip().split('/')[-1].strip()
                src = urljoin(url, each)
                print('Getting: ' + filename)
                response = requests.get(src, stream=True)
                # delay to avoid corrupted previews
                time.sleep(1)
                with open(filename, 'wb') as out_file:
                    shutil.copyfileobj(response.raw, out_file)
            except:
                print('  An error occured. Continuing.')
        print('Done.')
    
    if __name__ == '__main__':
        get_images('http://www.wookmark.com')
    

    Is there a way to @Autowire a bean that requires constructor arguments?

    An alternative would be instead of passing the parameters to the constructor you might have them as getter and setters and then in a @PostConstruct initialize the values as you want. In this case Spring will create the bean using the default constructor. An example is below

    @Component
    public class MyConstructorClass{
    
      String var;
    
      public void setVar(String var){
         this.var = var;
      }
    
      public void getVar(){
        return var;
      }
    
      @PostConstruct
      public void init(){
         setVar("var");
      }
    ...
    }
    
    
    @Service
    public class MyBeanService{
      //field autowiring
      @Autowired
      MyConstructorClass myConstructorClass;
    
      ....
    }
    

    Calling another method java GUI

    I'm not sure what you're trying to do, but here's something to consider: c(); won't do anything. c is an instance of the class checkbox and not a method to be called. So consider this:

    public class FirstWindow extends JFrame {      public FirstWindow() {         checkbox c = new checkbox();         c.yourMethod(yourParameters); // call the method you made in checkbox     } }  public class checkbox extends JFrame {      public checkbox(yourParameters) {          // this is the constructor method used to initialize instance variables     }      public void yourMethod() // doesn't have to be void     {         // put your code here     } } 

    How to define an optional field in protobuf 3

    To expand on @cybersnoopy 's suggestion here

    if you had a .proto file with a message like so:

    message Request {
        oneof option {
            int64 option_value = 1;
        }
    }
    

    You can make use of the case options provided (java generated code):

    So we can now write some code as follows:

    Request.OptionCase optionCase = request.getOptionCase();
    OptionCase optionNotSet = OPTION_NOT_SET;
    
    if (optionNotSet.equals(optionCase)){
        // value not set
    } else {
        // value set
    }
    

    What's the difference between TRUNCATE and DELETE in SQL

    DROP

    The DROP command removes a table from the database. All the tables' rows, indexes and privileges will also be removed. No DML triggers will be fired. The operation cannot be rolled back.

    TRUNCATE

    TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be fired. As such, TRUNCATE is faster and doesn't use as much undo space as a DELETE. Table level lock will be added when Truncating.

    DELETE

    The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it. Note that this operation will cause all DELETE triggers on the table to fire. Row level lock will be added when deleting.

    From: http://www.orafaq.com/faq/difference_between_truncate_delete_and_drop_commands

    Joining two table entities in Spring Data JPA

    This has been an old question but solution is very simple to that. If you are ever unsure about how to write criterias, joins etc in hibernate then best way is using native queries. This doesn't slow the performance and very useful. Eq. below

        @Query(nativeQuery = true, value = "your sql query")
    returnTypeOfMethod methodName(arg1, arg2);
    

    Hive load CSV with commas in quoted fields

    If you can re-create or parse your input data, you can specify an escape character for the CREATE TABLE:

    ROW FORMAT DELIMITED FIELDS TERMINATED BY "," ESCAPED BY '\\';
    

    Will accept this line as 4 fields

    1,some text\, with comma in it,123,more text
    

    return query based on date

    You can also try:

    {
        "dateProp": { $gt: new Date('06/15/2016').getTime() }
    }
    

    What is the difference between String and StringBuffer in Java?

    A StringBuffer is used to create a single string from many strings, e.g. when you want to append parts of a String in a loop.

    You should use a StringBuilder instead of a StringBuffer when you have only a single Thread accessing the StringBuffer, since the StringBuilder is not synchronized and thus faster.

    AFAIK there is no upper limit for String size in Java as a language, but the JVMs probably have an upper limit.

    How to read integer values from text file

    use FileInputStream's readLine() method to read and parse the returned String to int using Integer.parseInt() method.

    How do I check if a variable exists?

    Using try/except is the best way to test for a variable's existence. But there's almost certainly a better way of doing whatever it is you're doing than setting/testing global variables.

    For example, if you want to initialize a module-level variable the first time you call some function, you're better off with code something like this:

    my_variable = None
    
    def InitMyVariable():
      global my_variable
      if my_variable is None:
        my_variable = ...
    

    How to easily map c++ enums to strings

    I suggest a mix of using X-macros are the best solution and the following template functions:

    To borrow off marcinkoziukmyopenidcom and extended

    enum Colours {
    #   define X(a) a,
    #   include "colours.def"
    #   undef X
        ColoursCount
    };
    
    char const* const colours_str[] = {
    #   define X(a) #a,
    #   include "colours.def"
    #   undef X
        0
    };
    
    template <class T> T str2enum( const char* );
    template <class T> const char* enum2str( T );
    
    #define STR2ENUM(TYPE,ARRAY) \
    template <> \
    TYPE str2enum<TYPE>( const char* str ) \
        { \
        for( int i = 0; i < (sizeof(ARRAY)/sizeof(ARRAY[0])); i++ ) \
            if( !strcmp( ARRAY[i], str ) ) \
                return TYPE(i); \
        return TYPE(0); \
        }
    
    #define ENUM2STR(TYPE,ARRAY) \
    template <> \
    const char* enum2str<TYPE>( TYPE v ) \
        { \
        return ARRAY[v]; \
        }
    
    #define ENUMANDSTR(TYPE,ARRAY)\
        STR2ENUM(TYPE,ARRAY) \
        ENUM2STR(TYPE,ARRAY)
    
    ENUMANDSTR(Colours,colours_str)
    

    colour.def

    X(Red)
    X(Green)
    X(Blue)
    X(Cyan)
    X(Yellow)
    X(Magenta)
    

    Visual Studio replace tab with 4 spaces?

    None of these answer were working for me on my macbook pro. So what i had to do was go to:

    Preferences -> Source Code -> Code Formatting -> C# source code.

    From here I could change my style and spacing tabs etc. This is the only project i have where the lead developer has different formatting than i do. It was a pain in the butt that my IDE would format my code different than theirs.

    How to set timer in android?

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

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

    Accessing a class' member variables in Python?

    Implement the return statement like the example below! You should be good. I hope it helps someone..

    class Example(object):
        def the_example(self):
            itsProblem = "problem"
            return itsProblem 
    
    
    theExample = Example()
    print theExample.the_example()
    

    Declaring static constants in ES6 classes?

    I'm using babel and the following syntax is working for me:

    class MyClass {
        static constant1 = 33;
        static constant2 = {
           case1: 1,
           case2: 2,
        };
        // ...
    }
    
    MyClass.constant1 === 33
    MyClass.constant2.case1 === 1
    

    Please consider that you need the preset "stage-0".
    To install it:

    npm install --save-dev babel-preset-stage-0
    
    // in .babelrc
    {
        "presets": ["stage-0"]
    }
    

    Update:

    currently use stage-3

    How do I check in JavaScript if a value exists at a certain array index?

    Short and universal approach

    If you want to check any array if it has falsy values (like false, undefined, null or empty strings) you can just use every() method like this:

    array.every(function(element) {return !!element;}); // returns true or false
    

    For example:

    ['23', null, 2, {key: 'value'}].every(function(element) {return !!element;}); // returns false
    
    ['23', '', 2, {key: 'value'}].every(function(element) {return !!element;}); // returns false
    
    ['23', true, 2, {key: 'value'}].every(function(element) {return !!element;}); // returns true
    

    If you need to get a first index of falsy value, you can do it like this:

    let falsyIndex; 
    
    if(!['23', true, 2, null, {key: 'value'}].every(function(element, index) {falsyIndex = index; return !!element;})) {
      console.log(falsyIndex);
    } // logs 3
    

    If you just need to check a falsy value of an array for a given index you can just do it like this:

    if (!!array[index]) {
      // array[index] is a correct value
    }
    else {
      // array[index] is a falsy value
    }
    

    getResourceAsStream returns null

    Roughly speaking:

    getClass().getResource("/") ~= Thread.currentThread().getContextClassLoader().getResource(".")

    Suppose your project structure is like the following:

    +-- src
    ¦   +-- main
    ¦   +-- test
    ¦   +-- test
    ¦       +-- java
    ¦       ¦   +-- com
    ¦       ¦       +-- github
    ¦       ¦           +-- xyz
    ¦       ¦               +-- proj
    ¦       ¦                   +-- MainTest.java
    ¦       ¦                   +-- TestBase.java
    ¦       +-- resources
    ¦           +-- abcd.txt
    +-- target
        +-- test-classes
            +-- com
            +-- abcd.txt
    
    
    // in MainClass.java
    this.getClass.getResource("/") -> "~/proj_dir/target/test-classes/"
    this.getClass.getResource(".") -> "~/proj_dir/target/test-classes/com/github/xyz/proj/"
    Thread.currentThread().getContextClassLoader().getResources(".") -> "~/proj_dir/target/test-classes/"
    Thread.currentThread().getContextClassLoader().getResources("/") ->  null
    
    

    How to leave a message for a github.com user

    Github said on April 3rd 2012 :

    Today we're removing two features. They've been gathering dust for a while and it's time to throw them out : Fork Queue & Private Messaging

    Source

    How to permanently add a private key with ssh-add on Ubuntu?

    In my case the solution was:

    Permissions on the config file should be 600. chmod 600 config

    As mentioned in the comments above by generalopinion

    No need to touch the config file contents.

    Unique constraint violation during insert: why? (Oracle)

    It looks like you are not providing a value for the primary key field DB_ID. If that is a primary key, you must provide a unique value for that column. The only way not to provide it would be to create a database trigger that, on insert, would provide a value, most likely derived from a sequence.

    If this is a restoration from another database and there is a sequence on this new instance, it might be trying to reuse a value. If the old data had unique keys from 1 - 1000 and your current sequence is at 500, it would be generating values that already exist. If a sequence does exist for this table and it is trying to use it, you would need to reconcile the values in your table with the current value of the sequence.

    You can use SEQUENCE_NAME.CURRVAL to see the current value of the sequence (if it exists of course)

    How to create a blank/empty column with SELECT query in oracle?

    I guess you will get ORA-01741: illegal zero-length identifier if you use the following

    SELECT "" AS Contact  FROM Customers;
    

    And if you use the following 2 statements, you will be getting the same null value populated in the column.

    SELECT '' AS Contact FROM Customers; OR SELECT null AS Contact FROM Customers;
    

    C#: Waiting for all threads to complete

    This may not be an option for you, but if you can use the Parallel Extension for .NET then you could use Tasks instead of raw threads and then use Task.WaitAll() to wait for them to complete.

    curl -GET and -X GET

    -X [your method]
    X lets you override the default 'Get'

    ** corrected lowercase x to uppercase X

    TortoiseGit-git did not exit cleanly (exit code 1)

    I was heard that, one of the reasons is , the project is too large, so increasing the post buffer could solve the problem. so open the editSystemWideGitConfig, and add the following statements under [http] , postBuffer = 524288000. maybe work.

    Factorial in numpy and scipy

    You can import them like this:

    In [7]: import scipy, numpy, math                                                          
    
    In [8]: scipy.math.factorial, numpy.math.factorial, math.factorial
    Out[8]: 
    (<function math.factorial>,                                                                
     <function math.factorial>,                                                                
     <function math.factorial>)
    

    scipy.math.factorial and numpy.math.factorial seem to simply be aliases/references for/to math.factorial, that is scipy.math.factorial is math.factorial and numpy.math.factorial is math.factorial should both give True.

    How I add Headers to http.get or http.post in Typescript and angular 2?

    if someone facing issue of CORS not working in mobile browser or mobile applications, you can set ALLOWED_HOSTS = ["your host ip"] in backend servers where your rest api exists, here your host ip is external ip to access ionic , like External: http://192.168.1.120:8100

    After that in ionic type script make post or get using IP of backened server

    in my case i used django rest framwork and i started server as:- python manage.py runserver 192.168.1.120:8000

    and used this ip in ionic get and post calls of rest api

    The EXECUTE permission was denied on the object 'xxxxxxx', database 'zzzzzzz', schema 'dbo'

    If you have issues like the question ask above regarding the exception thrown when the solution is executed, the problem is permission, not properly granted to the users of that group to access the database/stored procedure. All you need do is to do something like what i have below, replacing mine with your database name, stored procedures (function)and the type of permission or role or who you are granting the access to.

    USE [StableEmployee]
    GO
    GRANT EXEC ON dbo.GetAllEmployees TO PUBLIC
    

    /****** Object: StoredProcedure [dbo].[GetAllEmployees] Script Date: 01/27/2016 16:27:27 ******/

    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    ALTER procedure [dbo].[GetAllEmployees]
    as
    Begin
    Select EmployeeId, Name, Gender, City, DepartmentId
    From tblEmployee
    
    End
    

    How do I make entire div a link?

    You need to assign display: block; property to the wrapping anchor. Otherwise it won't wrap correctly.

    <a style="display:block" href="http://justinbieber.com">
      <div class="xyz">My div contents</div>
    </a>
    

    Set environment variables on Mac OS X Lion

    I had problem with Eclipse (started as GUI, not from script) on Maverics that it did not take custom PATH. I tried all the methods mentioned above to no avail. Finally I found the simplest working answer based on hints from here:

    1. Go to /Applications/eclipse/Eclipse.app/Contents folder

    2. Edit Info.plist file with text editor (or XCode), add LSEnvironment dictionary for environment variable with full path. Note that it includes also /usr/bin etc:

      <dict>
        <key>LSEnvironment</key>
        <dict>
              <key>PATH</key>
              <string>/usr/bin:/bin:/usr/sbin:/sbin:/dev/android-ndk-r9b</string>
        </dict>
        <key>CFBundleDisplayName</key>
        <string>Eclipse</string>
        ...
      
    3. Reload parameters for app with

      /System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.fra??mework/Support/lsregister -v -f /Applications/eclipse/Eclipse.app
      
    4. Restart Eclipse

    Set margins in a LinearLayout programmatically

    I have set up margins directly using below code

    LinearLayout layout = (LinearLayout)findViewById(R.id.yourrelative_layout);
    LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);            
    params.setMargins(3, 300, 3, 3); 
    layout.setLayoutParams(params);
    

    Only thing here is to notice that LayoutParams should be imported for following package android.widget.RelativeLayout.LayoutParams, or else there will be an error.

    How to run Spyder in virtual environment?

    To do without reinstalling spyder in all environments follow official reference here.

    In summary (tested with conda):

    • Spyder should be installed in the base environment

    From the system prompt:

    • Create an new environment. Note that depending on how you create it (conda, virtualenv) the environment folder will be located at different place on your system)

    • Activate the environment (e.g., conda activate [yourEnvName])

    • Install spyder-kernels inside the environment (e.g., conda install spyder-kernels)

    • Find and copy the path for the python executable inside the environment. Finding this path can be done using from the prompt this command python -c "import sys; print(sys.executable)"

    • Deactivate the environment (i.e., return to base conda deactivate)

    • run spyder (spyder3)

    • Finally in spyder Tool menu go to Preferences > Python Interpreter > Use the following interpreter and paste the environment python executable path

    • Restart the ipython console

    PS: in spyder you should see at the bottom something like thisenter image description here

    Voila

    Create a Bitmap/Drawable from file path

    Well, using the static Drawable.createFromPath(String pathName) seems a bit more straightforward to me than decoding it yourself... :-)

    If your mImg is a simple ImageView, you don't even need it, use mImg.setImageUri(Uri uri) directly.

    @property retain, assign, copy, nonatomic in Objective-C

    After reading many articles I decided to put all the attributes information together:

    1. atomic //default
    2. nonatomic
    3. strong=retain //default
    4. weak= unsafe_unretained
    5. retain
    6. assign //default
    7. unsafe_unretained
    8. copy
    9. readonly
    10. readwrite //default

    Below is a link to the detailed article where you can find these attributes.

    Many thanks to all the people who give best answers here!!

    Variable property attributes or Modifiers in iOS

    Here is the Sample Description from Article

    1. atomic -Atomic means only one thread access the variable(static type). -Atomic is thread safe. -but it is slow in performance -atomic is default behavior -Atomic accessors in a non garbage collected environment (i.e. when using retain/release/autorelease) will use a lock to ensure that another thread doesn't interfere with the correct setting/getting of the value. -it is not actually a keyword.

    Example :

    @property (retain) NSString *name;
    
    @synthesize name;
    
    1. nonatomic -Nonatomic means multiple thread access the variable(dynamic type). -Nonatomic is thread unsafe. -but it is fast in performance -Nonatomic is NOT default behavior,we need to add nonatomic keyword in property attribute. -it may result in unexpected behavior, when two different process (threads) access the same variable at the same time.

    Example:

    @property (nonatomic, retain) NSString *name;
    
    @synthesize name;
    

    Explain:

    Suppose there is an atomic string property called "name", and if you call [self setName:@"A"] from thread A, call [self setName:@"B"] from thread B, and call [self name] from thread C, then all operation on different thread will be performed serially which means if one thread is executing setter or getter, then other threads will wait. This makes property "name" read/write safe but if another thread D calls [name release] simultaneously then this operation might produce a crash because there is no setter/getter call involved here. Which means an object is read/write safe (ATOMIC) but not thread safe as another threads can simultaneously send any type of messages to the object. Developer should ensure thread safety for such objects.

    If the property "name" was nonatomic, then all threads in above example - A,B, C and D will execute simultaneously producing any unpredictable result. In case of atomic, Either one of A, B or C will execute first but D can still execute in parallel.

    1. strong (iOS4 = retain ) -it says "keep this in the heap until I don't point to it anymore" -in other words " I'am the owner, you cannot dealloc this before aim fine with that same as retain" -You use strong only if you need to retain the object. -By default all instance variables and local variables are strong pointers. -We generally use strong for UIViewControllers (UI item's parents) -strong is used with ARC and it basically helps you , by not having to worry about the retain count of an object. ARC automatically releases it for you when you are done with it.Using the keyword strong means that you own the object.

    Example:

    @property (strong, nonatomic) ViewController *viewController;
    
    @synthesize viewController;
    
    1. weak (iOS4 = unsafe_unretained ) -it says "keep this as long as someone else points to it strongly" -the same thing as assign, no retain or release -A "weak" reference is a reference that you do not retain. -We generally use weak for IBOutlets (UIViewController's Childs).This works because the child object only needs to exist as long as the parent object does. -a weak reference is a reference that does not protect the referenced object from collection by a garbage collector. -Weak is essentially assign, a unretained property. Except the when the object is deallocated the weak pointer is automatically set to nil

    Example :

    @property (weak, nonatomic) IBOutlet UIButton *myButton;
    
    @synthesize myButton;
    

    Strong & Weak Explanation, Thanks to BJ Homer:

    Imagine our object is a dog, and that the dog wants to run away (be deallocated). Strong pointers are like a leash on the dog. As long as you have the leash attached to the dog, the dog will not run away. If five people attach their leash to one dog, (five strong pointers to one object), then the dog will not run away until all five leashes are detached. Weak pointers, on the other hand, are like little kids pointing at the dog and saying "Look! A dog!" As long as the dog is still on the leash, the little kids can still see the dog, and they'll still point to it. As soon as all the leashes are detached, though, the dog runs away no matter how many little kids are pointing to it. As soon as the last strong pointer (leash) no longer points to an object, the object will be deallocated, and all weak pointers will be zeroed out. When we use weak? The only time you would want to use weak, is if you wanted to avoid retain cycles (e.g. the parent retains the child and the child retains the parent so neither is ever released).

    1. retain = strong -it is retained, old value is released and it is assigned -retain specifies the new value should be sent -retain on assignment and the old value sent -release -retain is the same as strong. -apple says if you write retain it will auto converted/work like strong only. -methods like "alloc" include an implicit "retain"

    Example:

    @property (nonatomic, retain) NSString *name;
    
    @synthesize name;
    
    1. assign -assign is the default and simply performs a variable assignment -assign is a property attribute that tells the compiler how to synthesize the property's setter implementation -I would use assign for C primitive properties and weak for weak references to Objective-C objects.

    Example:

    @property (nonatomic, assign) NSString *address;
    
    @synthesize address;
    
    1. unsafe_unretained

      -unsafe_unretained is an ownership qualifier that tells ARC how to insert retain/release calls -unsafe_unretained is the ARC version of assign.

    Example:

    @property (nonatomic, unsafe_unretained) NSString *nickName;
    
    @synthesize nickName;
    
    1. copy -copy is required when the object is mutable. -copy specifies the new value should be sent -copy on assignment and the old value sent -release. -copy is like retain returns an object which you must explicitly release (e.g., in dealloc) in non-garbage collected environments. -if you use copy then you still need to release that in dealloc. -Use this if you need the value of the object as it is at this moment, and you don't want that value to reflect any changes made by other owners of the object. You will need to release the object when you are finished with it because you are retaining the copy.

    Example:

    @property (nonatomic, copy) NSArray *myArray;
    
    @synthesize myArray;
    

    Spring @ContextConfiguration how to put the right location for the xml

    This is a maven specific problem I think. Maven does not copy the files form /src/main/resources to the target-test folder. You will have to do this yourself by configuring the resources plugin, if you absolutely want to go this way.

    An easier way is to instead put a test specific context definition in the /src/test/resources directory and load via:

    @ContextConfiguration(locations = { "classpath:mycontext.xml" })