Programs & Examples On #Responsetext

jquery ajax get responsetext from http url

Since jQuery AJAX requests fail if they are cross-domain, you can use cURL (in PHP) to set up a proxy server.

Suppose a PHP file responder.php has these contents:

$url = "https://www.google.com";
$ch      = curl_init( $url );
curl_set_opt($ch, CURLOPT_RETURNTRANSFER, "true")
$response= curl_exec( $ch );
curl_close( $ch );
return $response;

Your AJAX request should be to this responder.php file so that it executes the cross-domain request.

How can I restart a Java application?

Strictly speaking, a Java program cannot restart itself since to do so it must kill the JVM in which it is running and then start it again, but once the JVM is no longer running (killed) then no action can be taken.

You could do some tricks with custom classloaders to load, pack, and start the AWT components again but this will likely cause lots of headaches with regard to the GUI event loop.

Depending on how the application is launched, you could start the JVM in a wrapper script which contains a do/while loop, which continues while the JVM exits with a particular code, then the AWT app would have to call System.exit(RESTART_CODE). For example, in scripting pseudocode:

DO
  # Launch the awt program
  EXIT_CODE = # Get the exit code of the last process
WHILE (EXIT_CODE == RESTART_CODE)

The AWT app should exit the JVM with something other than the RESTART_CODE on "normal" termination which doesn't require restart.

Create tap-able "links" in the NSAttributedString of a UILabel?

I follow this version,

Swift 4:

import Foundation

class AELinkedClickableUILabel: UILabel {

    typealias YourCompletion = () -> Void

    var linkedRange: NSRange!
    var completion: YourCompletion?

    @objc func linkClicked(sender: UITapGestureRecognizer){

        if let completionBlock = completion {

            let textView = UITextView(frame: self.frame)
            textView.text = self.text
            textView.attributedText = self.attributedText
            let index = textView.layoutManager.characterIndex(for: sender.location(in: self),
                                                              in: textView.textContainer,
                                                              fractionOfDistanceBetweenInsertionPoints: nil)

            if linkedRange.lowerBound <= index && linkedRange.upperBound >= index {

                completionBlock()
            }
        }
    }

/**
 *  This method will be used to set an attributed text specifying the linked text with a
 *  handler when the link is clicked
 */
    public func setLinkedTextWithHandler(text:String, link: String, handler: @escaping ()->()) -> Bool {

        let attributextText = NSMutableAttributedString(string: text)
        let foundRange = attributextText.mutableString.range(of: link)

        if foundRange.location != NSNotFound {
            self.linkedRange = foundRange
            self.completion = handler
            attributextText.addAttribute(NSAttributedStringKey.link, value: text, range: foundRange)
            self.isUserInteractionEnabled = true
            self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(linkClicked(sender:))))
            return true
        }
        return false
    }
}

Call Example:

button.setLinkedTextWithHandler(text: "This website (stackoverflow.com) is awesome", link: "stackoverflow.com") 
{
    // show popup or open to link
}

Add Marker function with Google Maps API

<div id="map" style="width:100%;height:500px"></div>

<script>
function myMap() {
  var myCenter = new google.maps.LatLng(51.508742,-0.120850);
  var mapCanvas = document.getElementById("map");
  var mapOptions = {center: myCenter, zoom: 5};
  var map = new google.maps.Map(mapCanvas, mapOptions);
  var marker = new google.maps.Marker({position:myCenter});
  marker.setMap(map);
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBu-916DdpKAjTmJNIgngS6HL_kDIKU0aU&callback=myMap"></script>

Checking from shell script if a directory contains files

The solutions so far use ls. Here's an all bash solution:

#!/bin/bash
shopt -s nullglob dotglob     # To include hidden files
files=(/some/dir/*)
if [ ${#files[@]} -gt 0 ]; then echo "huzzah"; fi

Get img src with PHP

There could be two easy solutions:

  1. HTML it self is an xml so you can use any XML parsing method if u load the tag as XML and get its attribute tottally dynamically even dom data attribute (like data-time or anything).....
  2. Use any html parser for php like http://mbe.ro/2009/06/21/php-html-to-array-working-one/ or php parse html to array Google this

How to save username and password in Git?

If you are using the Git Credential Manager on Windows...

git config -l should show:

credential.helper=manager

However, if you are not getting prompted for a credential then follow these steps:

  1. Open Control Panel from the Start menu
  2. Select User Accounts
  3. Select Manage your credentials in the left hand menu
  4. Delete any credentials related to Git or GitHub

Also ensure you have not set HTTP_PROXY, HTTPS_PROXY, NO_PROXY environmental variables if you have proxy and your Git server is on the internal network.

You can also test Git fetch/push/pull using git-gui which links to credential manager binaries in C:\Users\<username>\AppData\Local\Programs\Git\mingw64\libexec\git-core

What does the "$" sign mean in jQuery or JavaScript?

The $ symbol simply invokes the jQuery library's selector functionality. So $("#Text") returns the jQuery object for the Text div which can then be modified.

jquery find element by specific class when element has multiple classes

An element can have any number of classNames, however, it can only have one class attribute; only the first one will be read by jQuery.

Using the code you posted, $(".alert-box.warn") will work but $(".alert-box.dead") will not.

Calling class staticmethod within the class body?

This is due to staticmethod being a descriptor and requires a class-level attribute fetch to exercise the descriptor protocol and get the true callable.

From the source code:

It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()); the instance is ignored except for its class.

But not directly from inside the class while it is being defined.

But as one commenter mentioned, this is not really a "Pythonic" design at all. Just use a module level function instead.

Hibernate: get entity by id

Using EntityManager em;

public User getUserById(Long id) {
     return em.getReference(User.class, id);
}

Java method: Finding object in array list given a known attribute value

You have to loop through the entire array, there's no changing that. You can however, do it a little easier

for (Dog dog : list) {
  if (dog.getId() == id) {
    return dog; //gotcha!
  }
}
return null; // dog not found.

or without the new for loop

for (int i = 0; i < list.size(); i++) {
  if (list.get(i).getId() == id) {
    return list.get(i);
  }
}

Python function pointer

I ran into a similar problem while creating a library to handle authentication. I want the app owner using my library to be able to register a callback with the library for checking authorization against LDAP groups the authenticated person is in. The configuration is getting passed in as a config.py file that gets imported and contains a dict with all the config parameters.

I got this to work:

>>> class MyClass(object):
...     def target_func(self):
...         print "made it!"
...    
...     def __init__(self,config):
...         self.config = config
...         self.config['funcname'] = getattr(self,self.config['funcname'])
...         self.config['funcname']()
... 
>>> instance = MyClass({'funcname':'target_func'})
made it!

Is there a pythonic-er way to do this?

How to convert these strange characters? (ë, Ã, ì, ù, Ã)

I actually found something that worked for me. It converts the text to binary and then to UTF8.

Source Text that has encoding issues: If ‘Yes’, what was your last

SELECT CONVERT(CAST(CONVERT(
    (SELECT CONVERT(CAST(CONVERT(english_text USING LATIN1) AS BINARY) USING UTF8) AS res FROM m_translation WHERE id = 865) 
USING LATIN1) AS BINARY) USING UTF8) AS 'result';

Corrected Result text: If ‘Yes’, what was your last

My source was wrongly encoded twice so I had two do it twice. For one time you can use:

SELECT CONVERT(CAST(CONVERT(column_name USING latin1) AS BINARY) USING UTF8) AS res FROM m_translation WHERE id = 865;

Please excuse me for any formatting mistakes

How do you disable viewport zooming on Mobile Safari?

Using the CSS touch-action property is the most elegant solution. Tested on iOS 13.5 and iOS 14.

To disable pinch zoom gestures and and double-tap to zoom:

body {
  touch-action: pan-x pan-y;
}

If your app also has no need for panning, i.e. scrolling, use this:

body {
  touch-action: none;
}

Find the day of a week

start = as.POSIXct("2017-09-01")
end = as.POSIXct("2017-09-06")

dat = data.frame(Date = seq.POSIXt(from = start,
                                   to = end,
                                   by = "DSTday"))

# see ?strptime for details of formats you can extract

# day of the week as numeric (Monday is 1)
dat$weekday1 = as.numeric(format(dat$Date, format = "%u"))

# abbreviated weekday name
dat$weekday2 = format(dat$Date, format = "%a")

# full weekday name
dat$weekday3 = format(dat$Date, format = "%A")

dat
# returns
    Date       weekday1 weekday2  weekday3
1 2017-09-01        5      Fri    Friday
2 2017-09-02        6      Sat    Saturday
3 2017-09-03        7      Sun    Sunday
4 2017-09-04        1      Mon    Monday
5 2017-09-05        2      Tue    Tuesday
6 2017-09-06        3      Wed    Wednesday

Adjust table column width to content size

maybe problem with margin?

width:auto;
padding: 0px;
margin: 0px

.NET Events - What are object sender & EventArgs e?

Manually cast the sender to the type of your custom control, and then use it to delete or disable etc. Eg, something like this:

private void myCustomControl_Click(object sender, EventArgs e)
{
  ((MyCustomControl)sender).DoWhatever();
}

The 'sender' is just the object that was actioned (eg clicked).

The event args is subclassed for more complex controls, eg a treeview, so that you can know more details about the event, eg exactly where they clicked.

What is the difference between match_parent and fill_parent?

When you set layout width and height as match_parent in XML property, it will occupy the complete area that the parent view has, i.e. it will be as big as the parent.

<LinearLayout
    android:layout_width="300dp"
    android:layout_height="300dp"
    android:background="#f9b0b0">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#b0f9dc"/>

</LinearLayout>

Hare parent is red and child is green. Child occupy all area. Because it's width and height are match_parent.

enter image description here

Note : If parent is applied a padding then that space would not be included.

<LinearLayout
    android:layout_width="300dp"
    android:layout_height="300dp"
    android:background="#f9b0b0"
    android:paddingTop="20dp"
    android:paddingBottom="10dp">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#b0f9dc"/>

</LinearLayout>

enter image description here

So TextView hight = 300dp(parent hight) - (20(paddingTop)+10(paddingBottom)) = (300 - 30) dp = 270 dp

fill_parent Vs match_parent

fill_parent is previous name of match_parent

For API Level 8 and higher fill_parent renamed as match_parent and fill_parent is deprecated now.

So fill_parent and match_parent are same.

API Documentation for fill_parent

The view should be as big as its parent (minus padding). This constant is deprecated starting from API Level 8 and is replaced by {@code match_parent}.

Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

CLOCK_REALTIME represents the machine's best-guess as to the current wall-clock, time-of-day time. As Ignacio and MarkR say, this means that CLOCK_REALTIME can jump forwards and backwards as the system time-of-day clock is changed, including by NTP.

CLOCK_MONOTONIC represents the absolute elapsed wall-clock time since some arbitrary, fixed point in the past. It isn't affected by changes in the system time-of-day clock.

If you want to compute the elapsed time between two events observed on the one machine without an intervening reboot, CLOCK_MONOTONIC is the best option.

Note that on Linux, CLOCK_MONOTONIC does not measure time spent in suspend, although by the POSIX definition it should. You can use the Linux-specific CLOCK_BOOTTIME for a monotonic clock that keeps running during suspend.

CASE in WHERE, SQL Server

A few ways:

-- Do the comparison, OR'd with a check on the @Country=0 case
WHERE (a.Country = @Country OR @Country = 0)

-- compare the Country field to itself
WHERE a.Country = CASE WHEN @Country > 0 THEN @Country ELSE a.Country END

Or, use a dynamically generated statement and only add in the Country condition if appropriate. This should be most efficient in the sense that you only execute a query with the conditions that actually need to apply and can result in a better execution plan if supporting indices are in place. You would need to use parameterised SQL to prevent against SQL injection.

How to merge 2 List<T> and removing duplicate values from it in C#

Have you had a look at Enumerable.Union

This method excludes duplicates from the return set. This is different behavior to the Concat method, which returns all the elements in the input sequences including duplicates.

List<int> list1 = new List<int> { 1, 12, 12, 5};
List<int> list2 = new List<int> { 12, 5, 7, 9, 1 };
List<int> ulist = list1.Union(list2).ToList();

// ulist output : 1, 12, 5, 7, 9

Auto-redirect to another HTML page

One of these will work...

_x000D_
_x000D_
<head>_x000D_
  <meta http-equiv='refresh' content='0; URL=http://example.com/'>_x000D_
</head>
_x000D_
_x000D_
_x000D_

...or it can done with JavaScript:

_x000D_
_x000D_
window.location.href = 'https://example.com/';
_x000D_
_x000D_
_x000D_

npm throws error without sudo

This looks like a permissions issue in your home directory. To reclaim ownership of the .npm directory execute:

sudo chown -R $(whoami) ~/.npm

How do I resize an image using PIL and maintain its aspect ratio?

This script will resize an image (somepic.jpg) using PIL (Python Imaging Library) to a width of 300 pixels and a height proportional to the new width. It does this by determining what percentage 300 pixels is of the original width (img.size[0]) and then multiplying the original height (img.size[1]) by that percentage. Change "basewidth" to any other number to change the default width of your images.

from PIL import Image

basewidth = 300
img = Image.open('somepic.jpg')
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((basewidth,hsize), Image.ANTIALIAS)
img.save('somepic.jpg')

Carriage Return\Line feed in Java

Don't know who looks at your file, but if you open it in wordpad instead of notepad, the linebreaks will show correct. In case you're using a special file extension, associate it with wordpad and you're done with it. Or use any other more advanced text editor.

twig: IF with multiple conditions

If I recall correctly Twig doesn't support || and && operators, but requires or and and to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

Expressions

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

adb command not found

In my case, I was in the platform-tools directory but was using command in the wrong way:

adb install

instead of the right way:

./adb install

Entity Framework select distinct name

Try this:

var results = (from ta in context.TestAddresses
               select ta.Name).Distinct();

This will give you an IEnumerable<string> - you can call .ToList() on it to get a List<string>.

convert ArrayList<MyCustomClass> to JSONArray

Use Gson library to convert ArrayList to JsonArray.

Gson gson = new GsonBuilder().create();
JsonArray myCustomArray = gson.toJsonTree(myCustomList).getAsJsonArray();

Select elements by attribute

JQuery will return the attribute as a string. Therefore you can check the length of that string to determine if is set:

if ($("input#A").attr("myattr").length == 0)
 return null;
else
 return $("input#A").attr("myattr");

How to use FormData for AJAX file upload?

Better to use the native javascript to find the element by id like: document.getElementById("yourFormElementID").

$.ajax( {
      url: "http://yourlocationtopost/",
      type: 'POST',
      data: new FormData(document.getElementById("yourFormElementID")),
      processData: false,
      contentType: false
    } ).done(function(d) {
           console.log('done');
    });

What are the advantages and disadvantages of recursion?

Expressiveness

Most problems are naturally expressed by recursion such as Fibonacci, Merge sorting and quick sorting. In this respect, the code is written for humans, not machines.

Immutability

Iterative solutions often rely on varying temporary variables which makes the code hard to read. This can be avoided with recursion.

Performance

Recursion is not stack friendly. Stack can overflow when the recursion is not well designed or tail optimization is not supported.

How to convert Set<String> to String[]?

Use toArray(T[] a) method:

String[] array = set.toArray(new String[0]);

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Note that the mode of opening files is 'a' or some other have alphabet 'a' will also make error because of the overwritting.

pointer = open('makeaafile.txt', 'ab+')
tes = pickle.load(pointer, encoding='utf-8')

X11/Xlib.h not found in Ubuntu

Presume he's using the tutorial from http://www.arcsynthesis.org/gltut/ along with premake4.3 :-)

sudo apt-get install libx11-dev ................. for X11/Xlib.h
sudo apt-get install mesa-common-dev........ for GL/glx.h
sudo apt-get install libglu1-mesa-dev ..... for GL/glu.h
sudo apt-get install libxrandr-dev ........... for X11/extensions/Xrandr.h
sudo apt-get install libxi-dev ................... for X11/extensions/XInput.h

After which I could build glsdk_0.4.4 and examples without further issue.

Spring - @Transactional - What happens in background?

As a visual person, I like to weigh in with a sequence diagram of the proxy pattern. If you don't know how to read the arrows, I read the first one like this: Client executes Proxy.method().

  1. The client calls a method on the target from his perspective, and is silently intercepted by the proxy
  2. If a before aspect is defined, the proxy will execute it
  3. Then, the actual method (target) is executed
  4. After-returning and after-throwing are optional aspects that are executed after the method returns and/or if the method throws an exception
  5. After that, the proxy executes the after aspect (if defined)
  6. Finally the proxy returns to the calling client

Proxy Pattern Sequence Diagram (I was allowed to post the photo on condition that I mentioned its origins. Author: Noel Vaes, website: www.noelvaes.eu)

Round double in two decimal places in C#?

You should use

inputvalue=Math.Round(inputValue, 2, MidpointRounding.AwayFromZero)

Math.Round

Math.Round rounds a double-precision floating-point value to a specified number of fractional digits.

MidpointRounding

Specifies how mathematical rounding methods should process a number that is midway between two numbers.

Basically the function above will take your inputvalue and round it to 2 (or whichever number you specify) decimal places. With MidpointRounding.AwayFromZero when a number is halfway between two others, it is rounded toward the nearest number that is away from zero. There is also another option you can use that rounds towards the nearest even number.

json: cannot unmarshal object into Go value of type

You JSON doesn't match your struct fields: E.g. "district" in JSON and "District" as the field.

Also: Your Item is a slice type but your JSON is a dict value. Do not mix this up. Slices decode from arrays.

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 to add to the PYTHONPATH in Windows, so it finds my modules/packages?

To augment PYTHONPATH, run regedit and navigate to KEY_LOCAL_MACHINE \SOFTWARE\Python\PythonCore and then select the folder for the python version you wish to use. Inside this is a folder labelled PythonPath, with one entry that specifies the paths where the default install stores modules. Right-click on PythonPath and choose to create a new key. You may want to name the key after the project whose module locations it will specify; this way, you can easily compartmentalize and track your path modifications.

thanks

What is the difference between single-quoted and double-quoted strings in PHP?

Some might say that I'm a little off-topic, but here it is anyway:

You don't necessarily have to choose because of your string's content between:
echo "It's \"game\" time."; or echo 'It\'s "game" time.';

If you're familiar with the use of the english quotation marks, and the correct character for the apostrophe, you can use either double or single quotes, because it won't matter anymore:
echo "It’s “game” time."; and echo 'It’s “game” time.';

Of course you can also add variables if needed. Just don't forget that they get evaluated only when in double quotes!

How to pass "Null" (a real surname!) to a SOAP web service in ActionScript 3

Tracking it down

At first I thought this was a coercion bug where null was getting coerced to "null" and a test of "null" == null was passing. It's not. I was close, but so very, very wrong. Sorry about that!

I've since done lots of fiddling on wonderfl.net and tracing through the code in mx.rpc.xml.*. At line 1795 of XMLEncoder (in the 3.5 source), in setValue, all of the XMLEncoding boils down to

currentChild.appendChild(xmlSpecialCharsFilter(Object(value)));

which is essentially the same as:

currentChild.appendChild("null");

This code, according to my original fiddle, returns an empty XML element. But why?

Cause

According to commenter Justin Mclean on bug report FLEX-33664, the following is the culprit (see last two tests in my fiddle which verify this):

var thisIsNotNull:XML = <root>null</root>;
if(thisIsNotNull == null){
    // always branches here, as (thisIsNotNull == null) strangely returns true
    // despite the fact that thisIsNotNull is a valid instance of type XML
}

When currentChild.appendChild is passed the string "null", it first converts it to a root XML element with text null, and then tests that element against the null literal. This is a weak equality test, so either the XML containing null is coerced to the null type, or the null type is coerced to a root xml element containing the string "null", and the test passes where it arguably should fail. One fix might be to always use strict equality tests when checking XML (or anything, really) for "nullness."

Solution

The only reasonable workaround I can think of, short of fixing this bug in every damn version of ActionScript, is to test fields for "null" and escape them as CDATA values.

CDATA values are the most appropriate way to mutate an entire text value that would otherwise cause encoding/decoding problems. Hex encoding, for instance, is meant for individual characters. CDATA values are preferred when you're escaping the entire text of an element. The biggest reason for this is that it maintains human readability.

Best way to combine two or more byte arrays in C#

For primitive types (including bytes), use System.Buffer.BlockCopy instead of System.Array.Copy. It's faster.

I timed each of the suggested methods in a loop executed 1 million times using 3 arrays of 10 bytes each. Here are the results:

  1. New Byte Array using System.Array.Copy - 0.2187556 seconds
  2. New Byte Array using System.Buffer.BlockCopy - 0.1406286 seconds
  3. IEnumerable<byte> using C# yield operator - 0.0781270 seconds
  4. IEnumerable<byte> using LINQ's Concat<> - 0.0781270 seconds

I increased the size of each array to 100 elements and re-ran the test:

  1. New Byte Array using System.Array.Copy - 0.2812554 seconds
  2. New Byte Array using System.Buffer.BlockCopy - 0.2500048 seconds
  3. IEnumerable<byte> using C# yield operator - 0.0625012 seconds
  4. IEnumerable<byte> using LINQ's Concat<> - 0.0781265 seconds

I increased the size of each array to 1000 elements and re-ran the test:

  1. New Byte Array using System.Array.Copy - 1.0781457 seconds
  2. New Byte Array using System.Buffer.BlockCopy - 1.0156445 seconds
  3. IEnumerable<byte> using C# yield operator - 0.0625012 seconds
  4. IEnumerable<byte> using LINQ's Concat<> - 0.0781265 seconds

Finally, I increased the size of each array to 1 million elements and re-ran the test, executing each loop only 4000 times:

  1. New Byte Array using System.Array.Copy - 13.4533833 seconds
  2. New Byte Array using System.Buffer.BlockCopy - 13.1096267 seconds
  3. IEnumerable<byte> using C# yield operator - 0 seconds
  4. IEnumerable<byte> using LINQ's Concat<> - 0 seconds

So, if you need a new byte array, use

byte[] rv = new byte[a1.Length + a2.Length + a3.Length];
System.Buffer.BlockCopy(a1, 0, rv, 0, a1.Length);
System.Buffer.BlockCopy(a2, 0, rv, a1.Length, a2.Length);
System.Buffer.BlockCopy(a3, 0, rv, a1.Length + a2.Length, a3.Length);

But, if you can use an IEnumerable<byte>, DEFINITELY prefer LINQ's Concat<> method. It's only slightly slower than the C# yield operator, but is more concise and more elegant.

IEnumerable<byte> rv = a1.Concat(a2).Concat(a3);

If you have an arbitrary number of arrays and are using .NET 3.5, you can make the System.Buffer.BlockCopy solution more generic like this:

private byte[] Combine(params byte[][] arrays)
{
    byte[] rv = new byte[arrays.Sum(a => a.Length)];
    int offset = 0;
    foreach (byte[] array in arrays) {
        System.Buffer.BlockCopy(array, 0, rv, offset, array.Length);
        offset += array.Length;
    }
    return rv;
}

*Note: The above block requires you adding the following namespace at the the top for it to work.

using System.Linq;

To Jon Skeet's point regarding iteration of the subsequent data structures (byte array vs. IEnumerable<byte>), I re-ran the last timing test (1 million elements, 4000 iterations), adding a loop that iterates over the full array with each pass:

  1. New Byte Array using System.Array.Copy - 78.20550510 seconds
  2. New Byte Array using System.Buffer.BlockCopy - 77.89261900 seconds
  3. IEnumerable<byte> using C# yield operator - 551.7150161 seconds
  4. IEnumerable<byte> using LINQ's Concat<> - 448.1804799 seconds

The point is, it is VERY important to understand the efficiency of both the creation and the usage of the resulting data structure. Simply focusing on the efficiency of the creation may overlook the inefficiency associated with the usage. Kudos, Jon.

Passing parameters to addTarget:action:forControlEvents

There is another one way, in which you can get indexPath of the cell where your button was pressed:

using usual action selector like:

 UIButton *btn = ....;
    [btn addTarget:self action:@selector(yourFunction:) forControlEvents:UIControlEventTouchUpInside];

and then in in yourFunction:

   - (void) yourFunction:(id)sender {

    UIButton *button = sender;
    CGPoint center = button.center;
    CGPoint rootViewPoint = [button.superview convertPoint:center toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:rootViewPoint];
    //the rest of your code goes here
    ..
}

since you get an indexPath it becames much simplier.

How do I resolve a HTTP 414 "Request URI too long" error?

I got this error after using $.getJSON() from JQuery. I just changed to post:

data = getDataObjectByForm(form);
var jqxhr = $.post(url, data, function(){}, 'json')
    .done(function (response) {
        if (response instanceof Object)
            var json = response;
        else
            var json = $.parseJSON(response);
        // console.log(response);
        // console.log(json);
        jsonToDom(json);
        if (json.reload != undefined && json.reload)
            location.reload();
        $("body").delay(1000).css("cursor", "default");
    })
    .fail(function (jqxhr, textStatus, error) {
        var err = textStatus + ", " + error;
        console.log("Request Failed: " + err);
        alert("Fehler!");
    });

Keras, How to get the output of each layer?

This answer is based on: https://stackoverflow.com/a/59557567/2585501

To print the output of a single layer:

from tensorflow.keras import backend as K
layerIndex = 1
func = K.function([model.get_layer(index=0).input], model.get_layer(index=layerIndex).output)
layerOutput = func([input_data])  # input_data is a numpy array
print(layerOutput)

To print output of every layer:

from tensorflow.keras import backend as K
for layerIndex, layer in enumerate(model.layers):
    func = K.function([model.get_layer(index=0).input], layer.output)
    layerOutput = func([input_data])  # input_data is a numpy array
    print(layerOutput)

What is 'PermSize' in Java?

lace to store your loaded class definition and metadata. If a large code-base project is loaded, the insufficient Perm Gen size will cause the popular Java.Lang.OutOfMemoryError: PermGen.

How can I make a HTML a href hyperlink open a new window?

<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>

Easy as that.

Or without JS

<a href="http://yahoo.com" target="_blank">test</a>

Razor Views not seeing System.Web.Mvc.HtmlHelper

Having tried everything in vain, I discovered that in my case it wasn't working because an incorrect attribute value in Web Project csproj file. When I change ToolsVersion to 14, which matches my current IDE version (i.e. Visual Studio 2015), everything worked like a charm:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition=
  .....

Java - Writing strings to a CSV file

I see you already have a answer but here is another answer, maybe even faster A simple class to pass in a List of objects and retrieve either a csv or excel or password protected zip csv or excel. https://github.com/ernst223/spread-sheet-exporter

SpreadSheetExporter spreadSheetExporter = new SpreadSheetExporter(List<Object>, "Filename");
File fileCSV = spreadSheetExporter.getCSV();

Task not serializable: java.io.NotSerializableException when calling function outside closure only on classes not objects

I had a similar experience.

The error was triggered when I initialize a variable on the driver (master), but then tried to use it on one of the workers. When that happens, Spark Streaming will try to serialize the object to send it over to the worker, and fail if the object is not serializable.

I solved the error by making the variable static.

Previous non-working code

  private final PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();

Working code

  private static final PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();

Credits:

  1. https://docs.microsoft.com/en-us/answers/questions/35812/sparkexception-job-aborted-due-to-stage-failure-ta.html ( The answer of pradeepcheekatla-msft)
  2. https://databricks.gitbooks.io/databricks-spark-knowledge-base/content/troubleshooting/javaionotserializableexception.html

Error: [$injector:unpr] Unknown provider: $routeProvider

In angular 1.4 +, in addition to adding the dependency

angular.module('myApp', ['ngRoute'])

,we also need to reference the separate angular-route.js file

<script src="angular.js">
<script src="angular-route.js">

see https://docs.angularjs.org/api/ngRoute

How to access parameters in a RESTful POST method

Your @POST method should be accepting a JSON object instead of a string. Jersey uses JAXB to support marshaling and unmarshaling JSON objects (see the jersey docs for details). Create a class like:

@XmlRootElement
public class MyJaxBean {
    @XmlElement public String param1;
    @XmlElement public String param2;
}

Then your @POST method would look like the following:

@POST @Consumes("application/json")
@Path("/create")
public void create(final MyJaxBean input) {
    System.out.println("param1 = " + input.param1);
    System.out.println("param2 = " + input.param2);
}

This method expects to receive JSON object as the body of the HTTP POST. JAX-RS passes the content body of the HTTP message as an unannotated parameter -- input in this case. The actual message would look something like:

POST /create HTTP/1.1
Content-Type: application/json
Content-Length: 35
Host: www.example.com

{"param1":"hello","param2":"world"}

Using JSON in this way is quite common for obvious reasons. However, if you are generating or consuming it in something other than JavaScript, then you do have to be careful to properly escape the data. In JAX-RS, you would use a MessageBodyReader and MessageBodyWriter to implement this. I believe that Jersey already has implementations for the required types (e.g., Java primitives and JAXB wrapped classes) as well as for JSON. JAX-RS supports a number of other methods for passing data. These don't require the creation of a new class since the data is passed using simple argument passing.


HTML <FORM>

The parameters would be annotated using @FormParam:

@POST
@Path("/create")
public void create(@FormParam("param1") String param1,
                   @FormParam("param2") String param2) {
    ...
}

The browser will encode the form using "application/x-www-form-urlencoded". The JAX-RS runtime will take care of decoding the body and passing it to the method. Here's what you should see on the wire:

POST /create HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 25

param1=hello&param2=world

The content is URL encoded in this case.

If you do not know the names of the FormParam's you can do the following:

@POST @Consumes("application/x-www-form-urlencoded")
@Path("/create")
public void create(final MultivaluedMap<String, String> formParams) {
    ...
}

HTTP Headers

You can using the @HeaderParam annotation if you want to pass parameters via HTTP headers:

@POST
@Path("/create")
public void create(@HeaderParam("param1") String param1,
                   @HeaderParam("param2") String param2) {
    ...
}

Here's what the HTTP message would look like. Note that this POST does not have a body.

POST /create HTTP/1.1
Content-Length: 0
Host: www.example.com
param1: hello
param2: world

I wouldn't use this method for generalized parameter passing. It is really handy if you need to access the value of a particular HTTP header though.


HTTP Query Parameters

This method is primarily used with HTTP GETs but it is equally applicable to POSTs. It uses the @QueryParam annotation.

@POST
@Path("/create")
public void create(@QueryParam("param1") String param1,
                   @QueryParam("param2") String param2) {
    ...
}

Like the previous technique, passing parameters via the query string does not require a message body. Here's the HTTP message:

POST /create?param1=hello&param2=world HTTP/1.1
Content-Length: 0
Host: www.example.com

You do have to be particularly careful to properly encode query parameters on the client side. Using query parameters can be problematic due to URL length restrictions enforced by some proxies as well as problems associated with encoding them.


HTTP Path Parameters

Path parameters are similar to query parameters except that they are embedded in the HTTP resource path. This method seems to be in favor today. There are impacts with respect to HTTP caching since the path is what really defines the HTTP resource. The code looks a little different than the others since the @Path annotation is modified and it uses @PathParam:

@POST
@Path("/create/{param1}/{param2}")
public void create(@PathParam("param1") String param1,
                   @PathParam("param2") String param2) {
    ...
}

The message is similar to the query parameter version except that the names of the parameters are not included anywhere in the message.

POST /create/hello/world HTTP/1.1
Content-Length: 0
Host: www.example.com

This method shares the same encoding woes that the query parameter version. Path segments are encoded differently so you do have to be careful there as well.


As you can see, there are pros and cons to each method. The choice is usually decided by your clients. If you are serving FORM-based HTML pages, then use @FormParam. If your clients are JavaScript+HTML5-based, then you will probably want to use JAXB-based serialization and JSON objects. The MessageBodyReader/Writer implementations should take care of the necessary escaping for you so that is one fewer thing that can go wrong. If your client is Java based but does not have a good XML processor (e.g., Android), then I would probably use FORM encoding since a content body is easier to generate and encode properly than URLs are. Hopefully this mini-wiki entry sheds some light on the various methods that JAX-RS supports.

Note: in the interest of full disclosure, I haven't actually used this feature of Jersey yet. We were tinkering with it since we have a number of JAXB+JAX-RS applications deployed and are moving into the mobile client space. JSON is a much better fit that XML on HTML5 or jQuery-based solutions.

Rendering JSON in controller

What exactly do you want to know? ActiveRecord has methods that serialize records into JSON. For instance, open up your rails console and enter ModelName.all.to_json and you will see JSON output. render :json essentially calls to_json and returns the result to the browser with the correct headers. This is useful for AJAX calls in JavaScript where you want to return JavaScript objects to use. Additionally, you can use the callback option to specify the name of the callback you would like to call via JSONP.

For instance, lets say we have a User model that looks like this: {name: 'Max', email:' [email protected]'}

We also have a controller that looks like this:

class UsersController < ApplicationController
    def show
        @user = User.find(params[:id])
        render json: @user
    end
end

Now, if we do an AJAX call using jQuery like this:

$.ajax({
    type: "GET",
    url: "/users/5",
    dataType: "json",
    success: function(data){
        alert(data.name) // Will alert Max
    }        
});

As you can see, we managed to get the User with id 5 from our rails app and use it in our JavaScript code because it was returned as a JSON object. The callback option just calls a JavaScript function of the named passed with the JSON object as the first and only argument.

To give an example of the callback option, take a look at the following:

class UsersController < ApplicationController
    def show
        @user = User.find(params[:id])
        render json: @user, callback: "testFunction"
    end
end

Now we can crate a JSONP request as follows:

function testFunction(data) {
    alert(data.name); // Will alert Max
};

var script = document.createElement("script");
script.src = "/users/5";

document.getElementsByTagName("head")[0].appendChild(script);

The motivation for using such a callback is typically to circumvent the browser protections that limit cross origin resource sharing (CORS). JSONP isn't used that much anymore, however, because other techniques exist for circumventing CORS that are safer and easier.

Tar archiving that takes input from a list of files

Assuming GNU tar (as this is Linux), the -T or --files-from option is what you want.

Outline radius?

As others have said, only firefox supports this. Here is a work around that does the same thing, and even works with dashed outlines.

example

_x000D_
_x000D_
.has-outline {_x000D_
    display: inline-block;_x000D_
    background: #51ab9f;_x000D_
    border-radius: 10px;_x000D_
    padding: 5px;_x000D_
    position: relative;_x000D_
}_x000D_
.has-outline:after {_x000D_
  border-radius: 10px;_x000D_
  padding: 5px;_x000D_
  border: 2px dashed #9dd5cf;_x000D_
  position: absolute;_x000D_
  content: '';_x000D_
  top: -2px;_x000D_
  left: -2px;_x000D_
  bottom: -2px;_x000D_
  right: -2px;_x000D_
}
_x000D_
<div class="has-outline">_x000D_
  I can haz outline_x000D_
</div>
_x000D_
_x000D_
_x000D_

Converting string to date in mongodb

You can use the javascript in the second link provided by Ravi Khakhkhar or you are going to have to perform some string manipulation to convert your orginal string (as some of the special characters in your original format aren't being recognised as valid delimeters) but once you do that, you can use "new"

training:PRIMARY> Date()
Fri Jun 08 2012 13:53:03 GMT+0100 (IST)
training:PRIMARY> new Date()
ISODate("2012-06-08T12:53:06.831Z")

training:PRIMARY> var start = new Date("21/May/2012:16:35:33 -0400")        => doesn't work
training:PRIMARY> start
ISODate("0NaN-NaN-NaNTNaN:NaN:NaNZ")

training:PRIMARY> var start = new Date("21 May 2012:16:35:33 -0400")        => doesn't work    
training:PRIMARY> start
ISODate("0NaN-NaN-NaNTNaN:NaN:NaNZ")

training:PRIMARY> var start = new Date("21 May 2012 16:35:33 -0400")        => works
training:PRIMARY> start
ISODate("2012-05-21T20:35:33Z")

Here's some links that you may find useful (regarding modification of the data within the mongo shell) -

http://cookbook.mongodb.org/patterns/date_range/

http://www.mongodb.org/display/DOCS/Dates

http://www.mongodb.org/display/DOCS/Overview+-+The+MongoDB+Interactive+Shell

PowerShell Remoting giving "Access is Denied" error

Running the command prompt or Powershell ISE as an administrator fixed this for me.

Is there any boolean type in Oracle databases?

A common space-saving trick is storing boolean values as an Oracle CHAR, rather than NUMBER:

Artisan, creating tables in database

In order to give a value in the table, we need to give a command:

php artisan make:migration create_users_table

and after then this command line

php artisan migrate

......

Where do I find the line number in the Xcode editor?

If you don't want line numbers shown all the time another way to find the line number of a piece of code is to just click in the left-most margin and create a breakpoint (a small blue arrow appears) then go to the breakpoint navigator (?7) where it will list the breakpoint with its line number. You can delete the breakpoint by right clicking on it.

Can we open pdf file using UIWebView on iOS?

UIWebView *pdfWebView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];

NSURL *targetURL = [NSURL URLWithString:@"http://unec.edu.az/application/uploads/2014/12/pdf-sample.pdf"];
    NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
    [pdfWebView loadRequest:request];
    [self.view addSubview:pdfWebView];

Converting Numpy Array to OpenCV Array

The simplest solution would be to use Pillow lib:

from PIL import Image

image = Image.fromarray(<your_numpy_array>.astype(np.uint8))

And you can use it as an image.

CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column?

Try like this:

$data = array('current_login' => date('Y-m-d H:i:s'));
$this->db->set('last_login', 'current_login', false);
$this->db->where('id', 'some_id');
$this->db->update('login_table', $data);

Pay particular attention to the set() call's 3rd parameter. false prevents CodeIgniter from quoting the 2nd parameter -- this allows the value to be treated as a table column and not a string value. For any data that doesn't need to special treatment, you can lump all of those declarations into the $data array.

The query generated by above code:

UPDATE `login_table`
SET last_login = current_login, `current_login` = '2018-01-18 15:24:13'
WHERE `id` = 'some_id'

Windows Scheduled task succeeds but returns result 0x1

Just had the same problem here. In my case, the bat files had space " " After getting rid of spaces from filename and change into underscore, bat file worked

sample before it wont start

"x:\Update & pull.bat"

after rename

"x:\Update_and_pull.bat"

add to array if it isn't there already

With array_flip() it could look like this:

$flipped = array_flip($opts);
$flipped[$newValue] = 1;
$opts = array_keys($flipped);

With array_unique() - like this:

$opts[] = $newValue;
$opts = array_values(array_unique($opts));

Notice that array_values(...) — you need it if you're exporting array to JavaScript in JSON form. array_unique() alone would simply unset duplicate keys, without rebuilding the remaining elements'. So, after converting to JSON this would produce object, instead of array.

>>> json_encode(array_unique(['a','b','b','c']))
=> "{"0":"a","1":"b","3":"c"}"

>>> json_encode(array_values(array_unique(['a','b','b','c'])))
=> "["a","b","c"]"

javac option to compile all java files under a given directory recursively

I would also suggest using some kind of build tool (Ant or Maven, Ant is already suggested and is easier to start with) or an IDE that handles the compilation (Eclipse uses incremental compilation with reconciling strategy, and you don't even have to care to press any "Compile" buttons).

Using Javac

If you need to try something out for a larger project and don't have any proper build tools nearby, you can always use a small trick that javac offers: the classnames to compile can be specified in a file. You simply have to pass the name of the file to javac with the @ prefix.

If you can create a list of all the *.java files in your project, it's easy:

# Linux / MacOS
$ find -name "*.java" > sources.txt
$ javac @sources.txt

:: Windows
> dir /s /B *.java > sources.txt
> javac @sources.txt
  • The advantage is that is is a quick and easy solution.
  • The drawback is that you have to regenerate the sources.txt file each time you create a new source or rename an existing one file which is an easy to forget (thus error-prone) and tiresome task.

Using a build tool

On the long run it is better to use a tool that was designed to build software.

Using Ant

If you create a simple build.xml file that describes how to build the software:

<project default="compile">
    <target name="compile">
        <mkdir dir="bin"/>
        <javac srcdir="src" destdir="bin"/>
    </target>
</project>

you can compile the whole software by running the following command:

$ ant
  • The advantage is that you are using a standard build tool that is easy to extend.
  • The drawback is that you have to download, set up and learn an additional tool. Note that most of the IDEs (like NetBeans and Eclipse) offer great support for writing build files so you don't have to download anything in this case.

Using Maven

Maven is not that trivial to set up and work with, but learning it pays well. Here's a great tutorial to start a project within 5 minutes.

  • It's main advantage (for me) is that it handles dependencies too, so you won't need to download any more Jar files and manage them by hand and I found it more useful for building, packaging and testing larger projects.
  • The drawback is that it has a steep learning curve, and if Maven plugins like to suppress errors :-) Another thing is that quite a lot of tools also operate with Maven repositories (like Sbt for Scala, Ivy for Ant, Graddle for Groovy).

Using an IDE

Now that what could boost your development productivity. There are a few open source alternatives (like Eclipse and NetBeans, I prefer the former) and even commercial ones (like IntelliJ) which are quite popular and powerful.

They can manage the project building in the background so you don't have to deal with all the command line stuff. However, it always comes handy if you know what actually happens in the background so you can hunt down occasional errors like a ClassNotFoundException.

One additional note

For larger projects, it is always advised to use an IDE and a build tool. The former boosts your productivity, while the latter makes it possible to use different IDEs with the project (e.g., Maven can generate Eclipse project descriptors with a simple mvn eclipse:eclipse command). Moreover, having a project that can be tested/built with a single line command is easy to introduce to new colleagues and into a continuous integration server for example. Piece of cake :-)

How to update parent's state in React?

so, if you want to update parent component,

 class ParentComponent extends React.Component {
        constructor(props){
            super(props);
            this.state = {
               page:0
            }
        }

        handler(val){
            console.log(val) // 1
        }

        render(){
          return (
              <ChildComponent onChange={this.handler} />
           )
       }
   }


class ChildComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
             page:1
        };
    }

    someMethod = (page) => {
        this.setState({ page: page });
        this.props.onChange(page)
    }

    render() {
        return (
       <Button
            onClick={() => this.someMethod()} 
       > Click
        </Button>
      )
   }
}

Here onChange is an attribute with "handler" method bound to it's instance. we passed the method handler to the Child class component, to receive via onChange property in its props argument.

The attribute onChange will be set in a props object like this:

props ={
onChange : this.handler
}

and passed to the child component

So the Child component can access the value of name in the props object like this props.onChange

Its done through the use of render props.

Now the Child component has a button “Click” with an onclick event set to call the handler method passed to it via onChnge in its props argument object. So now this.props.onChange in Child holds the output method in the Parent class Reference and credits: Bits and Pieces

Remove Object from Array using JavaScript

This is what I use.

Array.prototype.delete = function(pos){
    this[pos] = undefined;
    var len = this.length - 1;
    for(var a = pos;a < this.length - 1;a++){
      this[a] = this[a+1];
    }
    this.pop();
  }

Then it is as simple as saying

var myArray = [1,2,3,4,5,6,7,8,9];
myArray.delete(3);

Replace any number in place of three. After the expected output should be:

console.log(myArray); //Expected output 1,2,3,5,6,7,8,9

How to force JS to do math instead of putting two strings together

Number()

dots = document.getElementById("txt").value;
dots = Number(dots) + 5;

// from MDN
Number('123')     // 123
Number('123') === 123 /// true
Number('12.3')    // 12.3
Number('12.00')   // 12
Number('123e-1')  // 12.3
Number('')        // 0
Number(null)      // 0
Number('0x11')    // 17
Number('0b11')    // 3
Number('0o11')    // 9
Number('foo')     // NaN
Number('100a')    // NaN
Number('-Infinity') //-Infinity

Transparent background on winforms?

What works for me is using a specific color instead of the real ability of .png to represent transparency.

So, what you can do is take your background image, and paint the transparent area with a specific color (Magenta always seemed appropriate to me...).

Set the image as the Form's BackgrounImage property, and set the color as the Form's TransparencyKey. No need for changes in the Control's style, and no need for BackColor.

I've tryed it right now and it worked for me...

How can I set the background color of <option> in a <select> element?

Just like normal background-color: #f0f

You just need a way to target it, eg: <option id="myPinkOption">blah</option>

How to initialize log4j properly?

You can set up the log level by using setLevel().

The levels are useful to easily set the kind of informations you want the program to display.

For example:

Logger.getRootLogger().setLevel(Level.WARN); //will not show debug messages

The set of possible levels are:

TRACE,

DEBUG,

INFO,

WARN,

ERROR and

FATAL

According to Logging Services manual

MySQL: Insert datetime into other datetime field

If you don't need the DATETIME value in the rest of your code, it'd be more efficient, simple and secure to use an UPDATE query with a sub-select, something like

UPDATE products SET t=(SELECT f FROM products WHERE id=17) WHERE id=42;

or in case it's in the same row in a single table, just

UPDATE products SET t=f WHERE id=42;

Connection Strings for Entity Framework

Instead of using config files you can use a configuration database with a scoped systemConfig table and add all your settings there.

CREATE TABLE [dbo].[SystemConfig]  
    (  
      [Id] [int] IDENTITY(1, 1)  
                 NOT NULL ,  
      [AppName] [varchar](128) NULL ,  
      [ScopeName] [varchar](128) NOT NULL ,  
      [Key] [varchar](256) NOT NULL ,  
      [Value] [varchar](MAX) NOT NULL ,  
      CONSTRAINT [PK_SystemConfig_ID] PRIMARY KEY NONCLUSTERED ( [Id] ASC )  
        WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,  
               IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,  
               ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]  
    )  
ON  [PRIMARY]  

GO  

SET ANSI_PADDING OFF  
GO  

ALTER TABLE [dbo].[SystemConfig] ADD  CONSTRAINT [DF_SystemConfig_ScopeName]  DEFAULT ('SystemConfig') FOR [ScopeName]  
GO 

With such configuration table you can create rows like such: enter image description here

Then from your your application dal(s) wrapping EF you can easily retrieve the scoped configuration.
If you are not using dal(s) and working in the wire directly with EF, you can make an Entity from the SystemConfig table and use the value depending on the application you are on.

docker-compose up for only certain containers

To start a particular service defined in your docker-compose file. for example if your have a docker-compose.yml

docker-compose start db  

given a compose file like as:

version: '3.3'

services:
   db:
     image: mysql:5.7
     ports:
       - "3306:3306"
     volumes:
       - ./db_data:/var/lib/mysql
     restart: always
     environment:
       MYSQL_ROOT_PASSWORD: yourPassword
       MYSQL_DATABASE: wordpress
       MYSQL_USER: wordpress
       MYSQL_PASSWORD: yourPassword

   wordpress:
     depends_on:
       - db
     image: wordpress:latest
     ports:
       - "80:80"
     volumes:
       - ./l3html:/var/www/html
     restart: always
     environment:
       WORDPRESS_DB_HOST: db:3306
       WORDPRESS_DB_USER: wordpress
       WORDPRESS_DB_PASSWORD: yourPassword
volumes:
    db_data:
    l3html:

Some times you want to start mySQL only (sometimes you just want to populate a database) before you start your entire suite.

jQuery CSS Opacity

Try with this :

jQuery('#main').css({ opacity: 0.6 });

Transfer data from one database to another database

if both databases are on same server and you want to transfer entire table (make copy of it) then use simple select into statement ...

select * into anotherDatabase..copyOfTable from oneDatabase..tableName

You can then write cursor top of sysobjects and copy entire set of tables that way.

If you want more complex data extraction & transformation, then use SSIS and build appropriate ETL in it.

Left join only selected columns in R with the merge() function

Nothing elegant but this could be another satisfactory answer.

merge(x = DF1, y = DF2, by = "Client", all.x=TRUE)[,c("Client","LO","CON")]

This will be useful especially when you don't need the keys that were used to join the tables in your results.

Access an arbitrary element in a dictionary in Python

If you only need to access one element (being the first by chance, since dicts do not guarantee ordering) you can simply do this in Python 2:

my_dict.keys()[0]     -> key of "first" element
my_dict.values()[0]   -> value of "first" element
my_dict.items()[0]    -> (key, value) tuple of "first" element

Please note that (at best of my knowledge) Python does not guarantee that 2 successive calls to any of these methods will return list with the same ordering. This is not supported with Python3.

in Python 3:

list(my_dict.keys())[0]     -> key of "first" element
list(my_dict.values())[0]   -> value of "first" element
list(my_dict.items())[0]    -> (key, value) tuple of "first" element

What's the easy way to auto create non existing dir in ansible

According to the latest document when state is set to be directory, you don't need to use parameter recurse to create parent directories, file module will take care of it.

- name: create directory with parent directories
  file:
    path: /data/test/foo
    state: directory

this is fare enough to create the parent directories data and test with foo

please refer the parameter description - "state" http://docs.ansible.com/ansible/latest/modules/file_module.html

Match multiline text using regular expression

str.matches(regex) behaves like Pattern.matches(regex, str) which attempts to match the entire input sequence against the pattern and returns

true if, and only if, the entire input sequence matches this matcher's pattern

Whereas matcher.find() attempts to find the next subsequence of the input sequence that matches the pattern and returns

true if, and only if, a subsequence of the input sequence matches this matcher's pattern

Thus the problem is with the regex. Try the following.

String test = "User Comments: This is \t a\ta \ntest\n\n message \n";

String pattern1 = "User Comments: [\\s\\S]*^test$[\\s\\S]*";
Pattern p = Pattern.compile(pattern1, Pattern.MULTILINE);
System.out.println(p.matcher(test).find());  //true

String pattern2 = "(?m)User Comments: [\\s\\S]*^test$[\\s\\S]*";
System.out.println(test.matches(pattern2));  //true

Thus in short, the (\\W)*(\\S)* portion in your first regex matches an empty string as * means zero or more occurrences and the real matched string is User Comments: and not the whole string as you'd expect. The second one fails as it tries to match the whole string but it can't as \\W matches a non word character, ie [^a-zA-Z0-9_] and the first character is T, a word character.

PHP check if url parameter exists

It is not quite clear what function you are talking about and if you need 2 separate branches or one. Assuming one:

Change your first line to

$slide = '';
if (isset($_GET["id"]))
{
    $slide = $_GET["id"];
}

What database does Google use?

Bigtable

A Distributed Storage System for Structured Data

Bigtable is a distributed storage system (built by Google) for managing structured data that is designed to scale to a very large size: petabytes of data across thousands of commodity servers.

Many projects at Google store data in Bigtable, including web indexing, Google Earth, and Google Finance. These applications place very different demands on Bigtable, both in terms of data size (from URLs to web pages to satellite imagery) and latency requirements (from backend bulk processing to real-time data serving).

Despite these varied demands, Bigtable has successfully provided a flexible, high-performance solution for all of these Google products.

Some features

  • fast and extremely large-scale DBMS
  • a sparse, distributed multi-dimensional sorted map, sharing characteristics of both row-oriented and column-oriented databases.
  • designed to scale into the petabyte range
  • it works across hundreds or thousands of machines
  • it is easy to add more machines to the system and automatically start taking advantage of those resources without any reconfiguration
  • each table has multiple dimensions (one of which is a field for time, allowing versioning)
  • tables are optimized for GFS (Google File System) by being split into multiple tablets - segments of the table as split along a row chosen such that the tablet will be ~200 megabytes in size.

Architecture

BigTable is not a relational database. It does not support joins nor does it support rich SQL-like queries. Each table is a multidimensional sparse map. Tables consist of rows and columns, and each cell has a time stamp. There can be multiple versions of a cell with different time stamps. The time stamp allows for operations such as "select 'n' versions of this Web page" or "delete cells that are older than a specific date/time."

In order to manage the huge tables, Bigtable splits tables at row boundaries and saves them as tablets. A tablet is around 200 MB, and each machine saves about 100 tablets. This setup allows tablets from a single table to be spread among many servers. It also allows for fine-grained load balancing. If one table is receiving many queries, it can shed other tablets or move the busy table to another machine that is not so busy. Also, if a machine goes down, a tablet may be spread across many other servers so that the performance impact on any given machine is minimal.

Tables are stored as immutable SSTables and a tail of logs (one log per machine). When a machine runs out of system memory, it compresses some tablets using Google proprietary compression techniques (BMDiff and Zippy). Minor compactions involve only a few tablets, while major compactions involve the whole table system and recover hard-disk space.

The locations of Bigtable tablets are stored in cells. The lookup of any particular tablet is handled by a three-tiered system. The clients get a point to a META0 table, of which there is only one. The META0 table keeps track of many META1 tablets that contain the locations of the tablets being looked up. Both META0 and META1 make heavy use of pre-fetching and caching to minimize bottlenecks in the system.

Implementation

BigTable is built on Google File System (GFS), which is used as a backing store for log and data files. GFS provides reliable storage for SSTables, a Google-proprietary file format used to persist table data.

Another service that BigTable makes heavy use of is Chubby, a highly-available, reliable distributed lock service. Chubby allows clients to take a lock, possibly associating it with some metadata, which it can renew by sending keep alive messages back to Chubby. The locks are stored in a filesystem-like hierarchical naming structure.

There are three primary server types of interest in the Bigtable system:

  1. Master servers: assign tablets to tablet servers, keeps track of where tablets are located and redistributes tasks as needed.
  2. Tablet servers: handle read/write requests for tablets and split tablets when they exceed size limits (usually 100MB - 200MB). If a tablet server fails, then a 100 tablet servers each pickup 1 new tablet and the system recovers.
  3. Lock servers: instances of the Chubby distributed lock service. Lots of actions within BigTable require acquisition of locks including opening tablets for writing, ensuring that there is no more than one active Master at a time, and access control checking.

Example from Google's research paper:

alt text

A slice of an example table that stores Web pages. The row name is a reversed URL. The contents column family contains the page contents, and the anchor column family contains the text of any anchors that reference the page. CNN's home page is referenced by both the Sports Illustrated and the MY-look home pages, so the row contains columns named anchor:cnnsi.com and anchor:my.look.ca. Each anchor cell has one version; the contents column has three versions, at timestamps t3, t5, and t6.

API

Typical operations to BigTable are creation and deletion of tables and column families, writing data and deleting columns from a row. BigTable provides this functions to application developers in an API. Transactions are supported at the row level, but not across several row keys.


Here is the link to the PDF of the research paper.

And here you can find a video showing Google's Jeff Dean in a lecture at the University of Washington, discussing the Bigtable content storage system used in Google's backend.

ActionController::UnknownFormat

This problem happened with me and sovled by just add

 respond_to :html, :json

to ApplicationController file

You can Check Devise issues on Github: https://github.com/plataformatec/devise/issues/2667

AngularJS Folder Structure

After building a few applications, some in Symfony-PHP, some .NET MVC, some ROR, i've found that the best way for me is to use Yeoman.io with the AngularJS generator.

That's the most popular and common structure and best maintained.

And most importantly, by keeping that structure, it helps you separate your client side code and to make it agnostic to the server-side technology (all kinds of different folder structures and different server-side templating engines).

That way you can easily duplicate and reuse yours and others code.

Here it is before grunt build: (but use the yeoman generator, don't just create it!)

/app
    /scripts
            /controllers
            /directives
            /services
            /filters
            app.js
    /views
    /styles
    /img
    /bower_components
    index.html
bower.json

And after grunt build (concat, uglify, rev, etc...):

    /scripts
        scripts.min.js (all JS concatenated, minified and grunt-rev)
        vendor.min.js  (all bower components concatenated, minified and grunt-rev)
    /views
    /styles
        mergedAndMinified.css  (grunt-cssmin)
    /images
    index.html  (grunt-htmlmin)

What possibilities can cause "Service Unavailable 503" error?

Your web pages are served by an application pool. If you disable/stop the application pool, and anyone tries to browse the application, you will get a Service Unavailable. It can happen due to multiple reasons...

  1. Your application may have crashed [check the event viewer and see if you can find event logs in your Application/System log]

  2. Your application may be crashing very frequently. If an app pool crashes for 5 times in 5 minutes [check your application pool settings for rapid fail], your application pool is disabled by IIS and you will end up getting this message.

In either case, the issue is that your worker process is failing and you should troubleshoot it from crash perspective.

What is a Crash (technically)... in ASP.NET and what to do if it happens?

Add space between cells (td) using css

Mine is:

border-spacing: 10px;
border-collapse: separate;

PHP remove all characters before specific string

You can use substring and strpos to accomplish this goal.

You could also use a regular expression to pattern match only what you want. Your mileage may vary on which of these approaches makes more sense.

Override browser form-filling and input highlighting with HTML/CSS

After trying a lot of things, I found working solutions that nuked the autofilled fields and replaced them with duplicated. Not to loose attached events, i came up with another (a bit lengthy) solution.

At each "input" event it swiftly attaches "change" events to all involved inputs. It tests if they have been autofilled. If yes, then dispatch a new text event that will trick the browser to think that the value has been changed by the user, thus allowing to remove the yellow background.

var initialFocusedElement = null
  , $inputs = $('input[type="text"]');

var removeAutofillStyle = function() {
  if($(this).is(':-webkit-autofill')) {
    var val = this.value;

    // Remove change event, we won't need it until next "input" event.
    $(this).off('change');

    // Dispatch a text event on the input field to trick the browser
    this.focus();
    event = document.createEvent('TextEvent');
    event.initTextEvent('textInput', true, true, window, '*');
    this.dispatchEvent(event);

    // Now the value has an asterisk appended, so restore it to the original
    this.value = val;

    // Always turn focus back to the element that received 
    // input that caused autofill
    initialFocusedElement.focus();
  }
};

var onChange = function() {
  // Testing if element has been autofilled doesn't 
  // work directly on change event.
  var self = this;
  setTimeout(function() {
    removeAutofillStyle.call(self);
  }, 1);
};

$inputs.on('input', function() {
  if(this === document.activeElement) {
    initialFocusedElement = this;

    // Autofilling will cause "change" event to be 
    // fired, so look for it
    $inputs.on('change', onChange);
  }
});

Add a month to a Date

"mondate" is somewhat similar to "Date" except that adding n adds n months rather than n days:

> library(mondate)
> d <- as.Date("2004-01-31")
> as.mondate(d) + 1
mondate: timeunits="months"
[1] 2004-02-29

Web-scraping JavaScript page with Python

We are not getting the correct results because any javascript generated content needs to be rendered on the DOM. When we fetch an HTML page, we fetch the initial, unmodified by javascript, DOM.

Therefore we need to render the javascript content before we crawl the page.

As selenium is already mentioned many times in this thread (and how slow it gets sometimes was mentioned also), I will list two other possible solutions.


Solution 1: This is a very nice tutorial on how to use Scrapy to crawl javascript generated content and we are going to follow just that.

What we will need:

  1. Docker installed in our machine. This is a plus over other solutions until this point, as it utilizes an OS-independent platform.

  2. Install Splash following the instruction listed for our corresponding OS.
    Quoting from splash documentation:

    Splash is a javascript rendering service. It’s a lightweight web browser with an HTTP API, implemented in Python 3 using Twisted and QT5.

    Essentially we are going to use Splash to render Javascript generated content.

  3. Run the splash server: sudo docker run -p 8050:8050 scrapinghub/splash.

  4. Install the scrapy-splash plugin: pip install scrapy-splash

  5. Assuming that we already have a Scrapy project created (if not, let's make one), we will follow the guide and update the settings.py:

    Then go to your scrapy project’s settings.py and set these middlewares:

    DOWNLOADER_MIDDLEWARES = {
          'scrapy_splash.SplashCookiesMiddleware': 723,
          'scrapy_splash.SplashMiddleware': 725,
          'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,
    }
    

    The URL of the Splash server(if you’re using Win or OSX this should be the URL of the docker machine: How to get a Docker container's IP address from the host?):

    SPLASH_URL = 'http://localhost:8050'
    

    And finally you need to set these values too:

    DUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter'
    HTTPCACHE_STORAGE = 'scrapy_splash.SplashAwareFSCacheStorage'
    
  6. Finally, we can use a SplashRequest:

    In a normal spider you have Request objects which you can use to open URLs. If the page you want to open contains JS generated data you have to use SplashRequest(or SplashFormRequest) to render the page. Here’s a simple example:

    class MySpider(scrapy.Spider):
        name = "jsscraper"
        start_urls = ["http://quotes.toscrape.com/js/"]
    
        def start_requests(self):
            for url in self.start_urls:
            yield SplashRequest(
                url=url, callback=self.parse, endpoint='render.html'
            )
    
        def parse(self, response):
            for q in response.css("div.quote"):
            quote = QuoteItem()
            quote["author"] = q.css(".author::text").extract_first()
            quote["quote"] = q.css(".text::text").extract_first()
            yield quote
    

    SplashRequest renders the URL as html and returns the response which you can use in the callback(parse) method.


Solution 2: Let's call this experimental at the moment (May 2018)...
This solution is for Python's version 3.6 only (at the moment).

Do you know the requests module (well who doesn't)?
Now it has a web crawling little sibling: requests-HTML:

This library intends to make parsing HTML (e.g. scraping the web) as simple and intuitive as possible.

  1. Install requests-html: pipenv install requests-html

  2. Make a request to the page's url:

    from requests_html import HTMLSession
    
    session = HTMLSession()
    r = session.get(a_page_url)
    
  3. Render the response to get the Javascript generated bits:

    r.html.render()
    

Finally, the module seems to offer scraping capabilities.
Alternatively, we can try the well-documented way of using BeautifulSoup with the r.html object we just rendered.

Simple Random Samples from a Sql database

There's a very interesting discussion of this type of issue here: http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/

I think with absolutely no assumptions about the table that your O(n lg n) solution is the best. Though actually with a good optimizer or a slightly different technique the query you list may be a bit better, O(m*n) where m is the number of random rows desired, as it wouldn't necesssarily have to sort the whole large array, it could just search for the smallest m times. But for the sort of numbers you posted, m is bigger than lg n anyway.

Three asumptions we might try out:

  1. there is a unique, indexed, primary key in the table

  2. the number of random rows you want to select (m) is much smaller than the number of rows in the table (n)

  3. the unique primary key is an integer that ranges from 1 to n with no gaps

With only assumptions 1 and 2 I think this can be done in O(n), though you'll need to write a whole index to the table to match assumption 3, so it's not necesarily a fast O(n). If we can ADDITIONALLY assume something else nice about the table, we can do the task in O(m log m). Assumption 3 would be an easy nice additional property to work with. With a nice random number generator that guaranteed no duplicates when generating m numbers in a row, an O(m) solution would be possible.

Given the three assumptions, the basic idea is to generate m unique random numbers between 1 and n, and then select the rows with those keys from the table. I don't have mysql or anything in front of me right now, so in slightly pseudocode this would look something like:


create table RandomKeys (RandomKey int)
create table RandomKeysAttempt (RandomKey int)

-- generate m random keys between 1 and n
for i = 1 to m
  insert RandomKeysAttempt select rand()*n + 1

-- eliminate duplicates
insert RandomKeys select distinct RandomKey from RandomKeysAttempt

-- as long as we don't have enough, keep generating new keys,
-- with luck (and m much less than n), this won't be necessary
while count(RandomKeys) < m
  NextAttempt = rand()*n + 1
  if not exists (select * from RandomKeys where RandomKey = NextAttempt)
    insert RandomKeys select NextAttempt

-- get our random rows
select *
from RandomKeys r
join table t ON r.RandomKey = t.UniqueKey

If you were really concerned about efficiency, you might consider doing the random key generation in some sort of procedural language and inserting the results in the database, as almost anything other than SQL would probably be better at the sort of looping and random number generation required.

Using `date` command to get previous, current and next month

the following will do:

date -d "$(date +%Y-%m-1) -1 month" +%-m
date -d "$(date +%Y-%m-1) 0 month" +%-m
date -d "$(date +%Y-%m-1) 1 month" +%-m

or as you need:

LAST_MONTH=`date -d "$(date +%Y-%m-1) -1 month" +%-m`
NEXT_MONTH=`date -d "$(date +%Y-%m-1) 1 month" +%-m`
THIS_MONTH=`date -d "$(date +%Y-%m-1) 0 month" +%-m`

you asked for output like 9,10,11, so I used the %-m

%m (without -) will produce output like 09,... (leading zero)

this also works for more/less than 12 months:

date -d "$(date +%Y-%m-1) -13 month" +%-m

just try

date -d "$(date +%Y-%m-1) -13 month"

to see full result

Array of char* should end at '\0' or "\0"?

The termination of an array of characters with a null character is just a convention that is specifically for strings in C. You are dealing with something completely different -- an array of character pointers -- so it really has no relation to the convention for C strings. Sure, you could choose to terminate it with a null pointer; that perhaps could be your convention for arrays of pointers. There are other ways to do it. You can't ask people how it "should" work, because you're assuming some convention that isn't there.

Native query with named parameter fails with "Not all named parameters have been set"

I use EclipseLink. This JPA allows the following way for the native queries:

Query q = em.createNativeQuery("SELECT * FROM mytable where username = ?username");
q.setParameter("username", "test");
q.getResultList();

How to set user environment variables in Windows Server 2008 R2 as a normal user?

You can also use this direct command line to open the Advanced System Properties:

sysdm.cpl

Then go to the Advanced Tab -> Environment Variables

Is there a "do ... until" in Python?

No there isn't. Instead use a while loop such as:

while 1:
 ...statements...
  if cond:
    break

How to use the gecko executable with Selenium

The solutions above work fine for local testing and firing up browsers from the java code.If you fancy firing up your selenium grid later then this parameter is a must have in order to tell the remote node where to find the geckodriver:

-Dwebdriver.gecko.driver="C:\geckodriver\geckodriver.exe"

The node cannot find the gecko driver when specified in the Automation Java code.

So the complete command for the node whould be (assuming node and hub for test purposes live on same machine) :

java -Dwebdriver.gecko.driver="C:\geckodriver\geckodriver.exe" -jar selenium-server-standalone-2.53.0.jar -role node -hub http://localhost:4444/grid/register

And you should expect to see in the node log :

00:35:44.383 INFO - Launching a Selenium Grid node
Setting system property webdriver.gecko.driver to C:\geckodriver\geckodriver.exe

What's the common practice for enums in Python?

I have no idea why Enums are not support natively by Python. The best way I've found to emulate them is by overridding _ str _ and _ eq _ so you can compare them and when you use print() you get the string instead of the numerical value.

class enumSeason():
    Spring = 0
    Summer = 1
    Fall = 2
    Winter = 3
    def __init__(self, Type):
        self.value = Type
    def __str__(self):
        if self.value == enumSeason.Spring:
            return 'Spring'
        if self.value == enumSeason.Summer:
            return 'Summer'
        if self.value == enumSeason.Fall:
            return 'Fall'
        if self.value == enumSeason.Winter:
            return 'Winter'
    def __eq__(self,y):
       return self.value==y.value

Usage:

>>> s = enumSeason(enumSeason.Spring)

>>> print(s)

Spring

How to Fill an array from user input C#?

It made a lot more sense to add this as an answer to arin's code than to keep doing it in comments...

1) Consider using decimal instead of double. It's more likely to give the answer the user expects. See http://pobox.com/~skeet/csharp/floatingpoint.html and http://pobox.com/~skeet/csharp/decimal.html for reasons why. Basically decimal works a lot closer to how humans think about numbers than double does. Double works more like how computers "naturally" think about numbers, which is why it's faster - but that's not relevant here.

2) For user input, it's usually worth using a method which doesn't throw an exception on bad input - e.g. decimal.TryParse and int.TryParse. These return a Boolean value to say whether or not the parse succeeded, and use an out parameter to give the result. If you haven't started learning about out parameters yet, it might be worth ignoring this point for the moment.

3) It's only a little point, but I think it's wise to have braces round all "for"/"if" (etc) bodies, so I'd change this:

for (int counter = 0; counter < 6; counter++)
    Console.WriteLine("{0,5}{1,8}", counter, array[counter]);

to this:

for (int counter = 0; counter < 6; counter++)
{
    Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
}

It makes the block clearer, and means you don't accidentally write:

for (int counter = 0; counter < 6; counter++)
    Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
    Console.WriteLine("----"); // This isn't part of the for loop!

4) Your switch statement doesn't have a default case - so if the user types anything other than "yes" or "no" it will just ignore them and quit. You might want to have something like:

bool keepGoing = true;
while (keepGoing)
{
    switch (answer)
    {
        case "yes":
            Console.WriteLine("===============================================");
            Console.WriteLine("please enter the array index you wish to get the value of it");
            int index = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("===============================================");
            Console.WriteLine("The Value of the selected index is:");
            Console.WriteLine(array[index]);
            keepGoing = false;
            break;

        case "no":
            Console.WriteLine("===============================================");
            Console.WriteLine("HAVE A NICE DAY SIR");
            keepGoing = false;
            break;

        default:
            Console.WriteLine("Sorry, I didn't understand that. Please enter yes or no");
            break;
    }
}

5) When you've started learning about LINQ, you might want to come back to this and replace your for loop which sums the input as just:

// Or decimal, of course, if you've made the earlier selected change
double sum = input.Sum();

Again, this is fairly advanced - don't worry about it for now!

Place a button right aligned

_x000D_
_x000D_
<div style = "display: flex; justify-content:flex-end">
    <button>Click me!</button>
</div>
_x000D_
_x000D_
_x000D_

<div style = "display: flex; justify-content: flex-end">
    <button>Click me!</button>
</div>

Unsuccessful append to an empty NumPy array

numpy.append always copies the array before appending the new values. Your code is equivalent to the following:

import numpy as np
result = np.zeros((2,0))
new_result = np.append([result[0]],[1,2])
result[0] = new_result # ERROR: has shape (2,0), new_result has shape (2,)

Perhaps you mean to do this?

import numpy as np
result = np.zeros((2,0))
result = np.append([result[0]],[1,2])

Best way to check for null values in Java?

In Java 7, you can use Objects.requireNonNull(). Add an import of Objects class from java.util.

public class FooClass {
    //...
    public void acceptFoo(Foo obj) {
        //If obj is null, NPE is thrown
        Objects.requireNonNull(obj).bar(); //or better requireNonNull(obj, "obj is null");
    }
    //...
}

Why do I get a SyntaxError for a Unicode escape in my file path?

All the three syntax work very well.

Another way is to first write

path = r'C:\user\...................' (whatever is the path for you)

and then passing it to os.chdir(path)

Search for a string in Enum and return the Enum

As mentioned in previous answers, you can cast directly to the underlying datatype (int -> enum type) or parse (string -> enum type).

but beware - there is no .TryParse for enums, so you WILL need a try/catch block around the parse to catch failures.

Convert List into Comma-Separated String

          @{  var result = string.Join(",", @user.UserRoles.Select(x => x.Role.RoleName));
              @result

           }

I used in MVC Razor View to evaluate and print all roles separated by commas.

How to include a font .ttf using CSS?

Only providing .ttf file for webfont won't be good enough for cross-browser support. The best possible combination at present is using the combination as :

@font-face {
  font-family: 'MyWebFont';
  src: url('webfont.eot'); /* IE9 Compat Modes */
  src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
       url('webfont.woff') format('woff'), /* Modern Browsers */
       url('webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
       url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}

This code assumes you have .eot , .woff , .ttf and svg format for you webfont. To automate all this process , you can use : Transfonter.org.

Also , modern browsers are shifting towards .woff font , so you can probably do this too : :

@font-face {
  font-family: 'MyWebFont';
  src: url('myfont.woff') format('woff'), /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
   url('myfont.ttf') format('truetype'); /* Chrome 4+, Firefox 3.5, Opera 10+, Safari 3—5 */
}  

Read more here : http://css-tricks.com/snippets/css/using-font-face/


Look for browser support : Can I Use fontface

Program does not contain a static 'Main' method suitable for an entry point

Maybe the "Output type" in properties->Application of the project must be a "Class Library" instead of console or windows application.

How can I determine the URL that a local Git repository was originally cloned from?

With Git 2.7 (release January 5th, 2015), you have a more coherent solution using git remote:

git remote get-url origin

(nice pendant of git remote set-url origin <newurl>)

See commit 96f78d3 (16 Sep 2015) by Ben Boeckel (mathstuf).
(Merged by Junio C Hamano -- gitster -- in commit e437cbd, 05 Oct 2015):

remote: add get-url subcommand

Expanding insteadOf is a part of ls-remote --url and there is no way to expand pushInsteadOf as well.
Add a get-url subcommand to be able to query both as well as a way to get all configured URLs.

get-url:

Retrieves the URLs for a remote.
Configurations for insteadOf and pushInsteadOf are expanded here.
By default, only the first URL is listed.

  • With '--push', push URLs are queried rather than fetch URLs.
  • With '--all', all URLs for the remote will be listed.

Before git 2.7, you had:

 git config --get remote.[REMOTE].url
 git ls-remote --get-url [REMOTE]
 git remote show [REMOTE]

Yes or No confirm box using jQuery

_x000D_
_x000D_
ConfirmDialog('Are you sure');_x000D_
_x000D_
function ConfirmDialog(message) {_x000D_
  $('<div></div>').appendTo('body')_x000D_
    .html('<div><h6>' + message + '?</h6></div>')_x000D_
    .dialog({_x000D_
      modal: true,_x000D_
      title: 'Delete message',_x000D_
      zIndex: 10000,_x000D_
      autoOpen: true,_x000D_
      width: 'auto',_x000D_
      resizable: false,_x000D_
      buttons: {_x000D_
        Yes: function() {_x000D_
          // $(obj).removeAttr('onclick');                                _x000D_
          // $(obj).parents('.Parent').remove();_x000D_
_x000D_
          $('body').append('<h1>Confirm Dialog Result: <i>Yes</i></h1>');_x000D_
_x000D_
          $(this).dialog("close");_x000D_
        },_x000D_
        No: function() {_x000D_
          $('body').append('<h1>Confirm Dialog Result: <i>No</i></h1>');_x000D_
_x000D_
          $(this).dialog("close");_x000D_
        }_x000D_
      },_x000D_
      close: function(event, ui) {_x000D_
        $(this).remove();_x000D_
      }_x000D_
    });_x000D_
};
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
_x000D_
_x000D_
_x000D_

How to read a file without newlines?

my_file = open("first_file.txt", "r")
for line in my_file.readlines():
    if line[-1:] == "\n":
        print(line[:-1])
    else:
        print(line)
my_file.close() 

AngularJS - Binding radio buttons to models with boolean values

The correct approach in Angularjs is to use ng-value for non-string values of models.

Modify your code like this:

<label data-ng-repeat="choice in question.choices">
  <input type="radio" name="response" data-ng-model="choice.isUserAnswer" data-ng-value="true" />
  {{choice.text}}
</label>

Ref: Straight from the horse's mouth

Programmatically trigger "select file" dialog box

Using jQuery you can call click() to simulate a click.

Serializing an object as UTF-8 XML in .NET

I found this blog post which explains the problem very well, and defines a few different solutions:

(dead link removed)

I've settled for the idea that the best way to do it is to completely omit the XML declaration when in memory. It actually is UTF-16 at that point anyway, but the XML declaration doesn't seem meaningful until it has been written to a file with a particular encoding; and even then the declaration is not required. It doesn't seem to break deserialization, at least.

As @Jon Hanna mentions, this can be done with an XmlWriter created like this:

XmlWriter writer = XmlWriter.Create (output, new XmlWriterSettings() { OmitXmlDeclaration = true });

What is the best way to check for Internet connectivity using .NET?

Try to avoid testing connections by catching the exception. because we really Expect that sometimes we may lose network connection.

 if (NetworkInterface.GetIsNetworkAvailable() &&
     new Ping().Send(new IPAddress(new byte[] { 8, 8, 8, 8 }),2000).Status == IPStatus.Success)
 //is online
 else
 //is offline

Parse string to date with moment.js

moment was perfect for what I needed. NOTE it ignores the hours and minutes and just does it's thing if you let it. This was perfect for me as my API call brings back the date and time but I only care about the date.

function momentTest() {

  var varDate = "2018-01-19 18:05:01.423";
  var myDate =  moment(varDate,"YYYY-MM-DD").format("DD-MM-YYYY");
  var todayDate = moment().format("DD-MM-YYYY");  
  var yesterdayDate = moment().subtract(1, 'days').format("DD-MM-YYYY");   
  var tomorrowDate = moment().add(1, 'days').format("DD-MM-YYYY");

  alert(todayDate);

  if (myDate == todayDate) {
    alert("date is today");
  } else if (myDate == yesterdayDate) {
    alert("date is yesterday");
  } else if (myDate == tomorrowDate) {
    alert("date is tomorrow");
  } else {
    alert("It's not today, tomorrow or yesterday!");
  }
}

Python 3 Building an array of bytes

Use a bytearray:

>>> frame = bytearray()
>>> frame.append(0xA2)
>>> frame.append(0x01)
>>> frame.append(0x02)
>>> frame.append(0x03)
>>> frame.append(0x04)
>>> frame
bytearray(b'\xa2\x01\x02\x03\x04')

or, using your code but fixing the errors:

frame = b""
frame += b'\xA2' 
frame += b'\x01' 
frame += b'\x02' 
frame += b'\x03'
frame += b'\x04'

Function for Factorial in Python

Another way to do it is to use np.prod shown below:

def factorial(n):
    if n == 0:
        return 1
    else:
         return np.prod(np.arange(1,n+1))

jQuery get textarea text

I have figured out that I can convert the keyCode of the event to a character by using the following function:

var char = String.fromCharCode(v_code);

From there I would then append the character to a string, and when the enter key is pressed send the string to the server. I'm sorry if my question seemed somewhat cryptic, and the title meaning something almost completely off-topic, it's early in the morning and I haven't had breakfast yet ;).

Thanks for all your help guys.

Serialize an object to string

I was unable to use the JSONConvert method suggested by xhafan

In .Net 4.5 even after adding the "System.Web.Extensions" assembly reference I was still unable to access the JSONConvert.

However, once you add the reference you can get the same string print out using:

JavaScriptSerializer js = new JavaScriptSerializer();
string jsonstring = js.Serialize(yourClassObject);

Determine on iPhone if user has enabled push notifications

To complete the answer, it could work something like this...

UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
switch (types) {
   case UIRemoteNotificationTypeAlert:
   case UIRemoteNotificationTypeBadge:
       // For enabled code
       break;
   case UIRemoteNotificationTypeSound:
   case UIRemoteNotificationTypeNone:
   default:
       // For disabled code
       break;
}

edit: This is not right. since these are bit-wise stuff, it wont work with a switch, so I ended using this:

UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
UIRemoteNotificationType typesset = (UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge);
if((types & typesset) == typesset)
{
    CeldaSwitch.chkSwitch.on = true;
}
else
{
    CeldaSwitch.chkSwitch.on = false;
}

Textarea onchange detection

You can listen to event on change of textarea and do the changes as per you want. Here is one example.

_x000D_
_x000D_
const textArea = document.getElementById('my_text_area');
textArea.addEventListener('input', () => {
    var textLn =  textArea.value.length;
    if(textLn >= 100) {
        textArea.style.fontSize = '10pt';
    }
})
_x000D_
<html>
    <textarea id='my_text_area' rows="4" cols="50" style="font-size:40pt">
This text will change font after 100.
    </textarea>
</html>
_x000D_
_x000D_
_x000D_

Can I get the name of the currently running function in JavaScript?

This should do it:

var fn = arguments.callee.toString().match(/function\s+([^\s\(]+)/);
alert(fn[1]);

For the caller, just use caller.toString().

Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running?

I had the same problem for gitlab CI running node:lts image:

  • I just restarted the docker daemon and restart the container, it worked for me.

What does "<>" mean in Oracle

In mysql extended version, <> gives out error. You are using mysql_query Eventually, you have to use extended version of my mysql. Old will be replaced in future browser. Rather use something like

$con = mysqli_connect("host", "username", "password", "databaseName");

mysqli_query($con, "select orderid != 650");

The definitive guide to form-based website authentication

I would like to add one very important comment: -

  • "In a corporate, intra- net setting," most if not all of the foregoing might not apply!

Many corporations deploy "internal use only" websites which are, effectively, "corporate applications" that happen to have been implemented through URLs. These URLs can (supposedly ...) only be resolved within "the company's internal network." (Which network magically includes all VPN-connected 'road warriors.')

When a user is dutifully-connected to the aforesaid network, their identity ("authentication") is [already ...] "conclusively known," as is their permission ("authorization") to do certain things ... such as ... "to access this website."

This "authentication + authorization" service can be provided by several different technologies, such as LDAP (Microsoft OpenDirectory), or Kerberos.

From your point-of-view, you simply know this: that anyone who legitimately winds-up at your website must be accompanied by [an environment-variable magically containing ...] a "token." (i.e. The absence of such a token must be immediate grounds for 404 Not Found.)

The token's value makes no sense to you, but, should the need arise, "appropriate means exist" by which your website can "[authoritatively] ask someone who knows (LDAP... etc.)" about any and every(!) question that you may have. In other words, you do not avail yourself of any "home-grown logic." Instead, you inquire of The Authority and implicitly trust its verdict.

Uh huh ... it's quite a mental-switch from the "wild-and-wooly Internet."

Eclipse Build Path Nesting Errors

Make two folders: final/src/ to store the source java code, and final/WebRoot/.

You cannot put the source and the webroot together. I think you may misunderstand your teacher.

NPM: npm-cli.js not found when running npm

On Windows 10:

  1. Press windows key, type edit the system environment variables then enter.
  2. Click environment variables...
  3. On the lower half of the window that opened with title Environment Variables there you will see a table titled System Variables, with two columns, the first one titled variable.
  4. Find the row with variable Path and click it.
  5. Click edit which will open a window titled Edit evironment variable.
  6. Here if you find

C:\Program Files\nodejs\node_modules\npm\bin

select it, and click edit button to your right, then edit the field to the path where you have the nodejs folder, in my case it was just shortening it to :

C:\Program Files\nodejs

Then I closed all my cmd or powershell terminals, opened them again and npm was working.

How to remove the last character from a string?

The described problem and proposed solutions sometimes relate to removing separators. If this is your case, then have a look at Apache Commons StringUtils, it has a method called removeEnd which is very elegant.

Example:

StringUtils.removeEnd("string 1|string 2|string 3|", "|");

Would result in: "string 1|string 2|string 3"

Pandas conditional creation of a series/dataframe column

If you're working with massive data, a memoized approach would be best:

# First create a dictionary of manually stored values
color_dict = {'Z':'red'}

# Second, build a dictionary of "other" values
color_dict_other = {x:'green' for x in df['Set'].unique() if x not in color_dict.keys()}

# Next, merge the two
color_dict.update(color_dict_other)

# Finally, map it to your column
df['color'] = df['Set'].map(color_dict)

This approach will be fastest when you have many repeated values. My general rule of thumb is to memoize when: data_size > 10**4 & n_distinct < data_size/4

E.x. Memoize in a case 10,000 rows with 2,500 or fewer distinct values.

How to set default value to the input[type="date"]

You can use this js code:

<input type="date" id="dateDefault" />

JS

function setInputDate(_id){
    var _dat = document.querySelector(_id);
    var hoy = new Date(),
        d = hoy.getDate(),
        m = hoy.getMonth()+1, 
        y = hoy.getFullYear(),
        data;

    if(d < 10){
        d = "0"+d;
    };
    if(m < 10){
        m = "0"+m;
    };

    data = y+"-"+m+"-"+d;
    console.log(data);
    _dat.value = data;
};

setInputDate("#dateDefault");

"Uncaught (in promise) undefined" error when using with=location in Facebook Graph API query

The reject actually takes one parameter: that's the exception that occurred in your code that caused the promise to be rejected. So, when you call reject() the exception value is undefined, hence the "undefined" part in the error that you get.

You do not show the code that uses the promise, but I reckon it is something like this:

var promise = doSth();
promise.then(function() { doSthHere(); });

Try adding an empty failure call, like this:

promise.then(function() { doSthHere(); }, function() {});

This will prevent the error to appear.

However, I would consider calling reject only in case of an actual error, and also... having empty exception handlers isn't the best programming practice.

Calling method using JavaScript prototype

Well one way to do it would be saving the base method and then calling it from the overriden method, like so

MyClass.prototype._do_base = MyClass.prototype.do;
MyClass.prototype.do = function(){  

    if (this.name === 'something'){

        //do something new

    }else{
        return this._do_base();
    }

};

String replacement in batch file

You can use !, but you must have the ENABLEDELAYEDEXPANSION switch set.

setlocal ENABLEDELAYEDEXPANSION
set word=table
set str="jump over the chair"
set str=%str:chair=!word!%

C++ - how to find the length of an integer

"I mean the number of digits in an integer, i.e. "123" has a length of 3"

int i = 123;

// the "length" of 0 is 1:
int len = 1;

// and for numbers greater than 0:
if (i > 0) {
    // we count how many times it can be divided by 10:
    // (how many times we can cut off the last digit until we end up with 0)
    for (len = 0; i > 0; len++) {
        i = i / 10;
    }
}

// and that's our "length":
std::cout << len;

outputs 3

Count the number of Occurrences of a Word in a String

using indexOf...

public static int count(String string, String substr) {
    int i;
    int last = 0;
    int count = 0;
    do {
        i = string.indexOf(substr, last);
        if (i != -1) count++;
        last = i+substr.length();
    } while(i != -1);
    return count;
}

public static void main (String[] args ){
    System.out.println(count("i have a male cat. the color of male cat is Black", "male cat"));
}

That will show: 2

Another implementation for count(), in just 1 line:

public static int count(String string, String substr) {
    return (string.length() - string.replaceAll(substr, "").length()) / substr.length() ;
}

How do I solve the "server DNS address could not be found" error on Windows 10?

There might be a problem with your DNS servers of the ISP. A computer by default uses the ISP's DNS servers. You can manually configure your DNS servers. It is free and usually better than your ISP.

  1. Go to Control Panel ? Network and Internet ? Network and Sharing Centre
  2. Click on Change Adapter settings.
  3. Right click on your connection icon (Wireless Network Connection or Local Area Connection) and select properties.
  4. Select Internet protocol version 4.
  5. Click on "Use the following DNS server address" and type either of the two DNS given below.

Google Public DNS

Preferred DNS server : 8.8.8.8
Alternate DNS server : 8.8.4.4

OpenDNS

Preferred DNS server : 208.67.222.222
Alternate DNS server : 208.67.220.220

How to add jQuery to an HTML page?

You need to wrap this in script tags:

<script type='text/javascript'> ... your code ... </script>

That being said, it's important WHEN you execute this code. If you put this in the page BEFORE the HTML elements that it is hooking into then the script will run BEFORE the HTML is actually rendered in the page, so it will fail.

It is common practice to wrap this type of code in a "document ready" block, like so:

<script type='text/javascript'>
$(document).ready(function() {

... your code...

}}
</script>

This ensures that the entire page has rendered in the browser BEFORE your code is executed. It is also a best practice to put the code in the <head> section of your page.

How to validate phone number using PHP?

I depends heavily on which number formats you aim to support, and how strict you want to enforce number grouping, use of whitespace and other separators etc....

Take a look at this similar question to get some ideas.

Then there is E.164 which is a numbering standard recommendation from ITU-T

How to change the size of the font of a JLabel to take the maximum size

 JLabel textLabel = new JLabel("<html><span style='font-size:20px'>"+Text+"</span></html>");

Difference between 3NF and BCNF in simple terms (must be able to explain to an 8-year old)

Answers by ‘smartnut007’, ‘Bill Karwin’, and ‘sqlvogel’ are excellent. Yet let me put an interesting perspective to it.

Well, we have prime and non-prime keys.

When we focus on how non-primes depend on primes, we see two cases:

Non-primes can be dependent or not.

  • When dependent: we see they must depend on a full candidate key. This is 2NF.
  • When not dependent: there can be no-dependency or transitive dependency

    • Not even transitive dependency: Not sure what normalization theory addresses this.
    • When transitively dependent: It is deemed undesirable. This is 3NF.

What about dependencies among primes?

Now you see, we’re not addressing the dependency relationship among primes by either 2nd or 3rd NF. Further such dependency, if any, is not desirable and thus we’ve a single rule to address that. This is BCNF.

Referring to the example from Bill Karwin's post here, you’ll notice that both ‘Topping’, and ‘Topping Type’ are prime keys and have a dependency. Had they been non-primes with dependency, then 3NF would have kicked in.

Note:

The definition of BCNF is very generic and without differentiating attributes between prime and non-prime. Yet, the above way of thinking helps to understand how some anomaly is percolated even after 2nd and 3rd NF.

Advanced Topic: Mapping generic BCNF to 2NF & 3NF

Now that we know BCNF provides a generic definition without reference to any prime/non-prime attribues, let's see how BCNF and 2/3 NF's are related.

First, BCNF requires (other than the trivial case) that for each functional dependency X -> Y (FD), X should be super-key. If you just consider any FD, then we've three cases - (1) Both X and Y non-prime, (2) Both prime and (3) X prime and Y non-prime, discarding the (nonsensical) case X non-prime and Y prime.

For case (1), 3NF takes care of.

For case (3), 2NF takes care of.

For case (2), we find the use of BCNF

Local variable referenced before assignment?

In order for you to modify test1 while inside a function you will need to do define test1 as a global variable, for example:

test1 = 0
def testFunc():
    global test1 
    test1 += 1
testFunc()

However, if you only need to read the global variable you can print it without using the keyword global, like so:

test1 = 0
def testFunc():
     print test1 
testFunc()

But whenever you need to modify a global variable you must use the keyword global.

How do you rotate a two dimensional array?

Great answers but for those who are looking for a DRY JavaScript code for this - both +90 Degrees and -90 Degrees:

_x000D_
_x000D_
          // Input: 1 2 3_x000D_
          //        4 5 6_x000D_
          //        7 8 9_x000D_
_x000D_
          // Transpose: _x000D_
          //       1 4 7_x000D_
          //       2 5 8_x000D_
          //       3 6 9_x000D_
_x000D_
          // Output: _x000D_
          // +90 Degree:_x000D_
          //       7 4 1_x000D_
          //       8 5 2_x000D_
          //       9 6 3_x000D_
_x000D_
          // -90 Degree:_x000D_
          //      3 6 9_x000D_
          //      2 5 8_x000D_
          //      1 4 7_x000D_
_x000D_
          // Rotate +90_x000D_
         function rotate90(matrix) {_x000D_
_x000D_
           matrix = transpose(matrix);_x000D_
           matrix.map(function(array) {_x000D_
             array.reverse();_x000D_
           });_x000D_
_x000D_
           return matrix;_x000D_
         }_x000D_
_x000D_
          // Rotate -90_x000D_
         function counterRotate90(matrix) {_x000D_
           var result = createEmptyMatrix(matrix.length);_x000D_
           matrix = transpose(matrix);_x000D_
           var counter = 0;_x000D_
_x000D_
           for (var i = matrix.length - 1; i >= 0; i--) {_x000D_
             result[counter] = matrix[i];_x000D_
             counter++;_x000D_
           }_x000D_
_x000D_
           return result;_x000D_
         }_x000D_
_x000D_
          // Create empty matrix_x000D_
         function createEmptyMatrix(len) {_x000D_
           var result = new Array();_x000D_
           for (var i = 0; i < len; i++) {_x000D_
             result.push([]);_x000D_
           }_x000D_
           return result;_x000D_
         }_x000D_
_x000D_
          // Transpose the matrix_x000D_
         function transpose(matrix) {_x000D_
           // make empty array_x000D_
           var len = matrix.length;_x000D_
           var result = createEmptyMatrix(len);_x000D_
_x000D_
           for (var i = 0; i < matrix.length; i++) {_x000D_
             for (var j = 0; j < matrix[i].length; j++) {_x000D_
               var temp = matrix[i][j];_x000D_
               result[j][i] = temp;_x000D_
             }_x000D_
           }_x000D_
           return result;_x000D_
         }_x000D_
_x000D_
_x000D_
_x000D_
          // Test Cases_x000D_
         var array1 = [_x000D_
           [1, 2],_x000D_
           [3, 4]_x000D_
         ];_x000D_
         var array2 = [_x000D_
           [1, 2, 3],_x000D_
           [4, 5, 6],_x000D_
           [7, 8, 9]_x000D_
         ];_x000D_
         var array3 = [_x000D_
           [1, 2, 3, 4],_x000D_
           [5, 6, 7, 8],_x000D_
           [9, 10, 11, 12],_x000D_
           [13, 14, 15, 16]_x000D_
         ];_x000D_
_x000D_
          // +90 degress Rotation Tests_x000D_
_x000D_
         var test1 = rotate90(array1);_x000D_
         var test2 = rotate90(array2);_x000D_
         var test3 = rotate90(array3);_x000D_
         console.log(test1);_x000D_
         console.log(test2);_x000D_
         console.log(test3);_x000D_
_x000D_
          // -90 degress Rotation Tests_x000D_
         var test1 = counterRotate90(array1);_x000D_
         var test2 = counterRotate90(array2);_x000D_
         var test3 = counterRotate90(array3);_x000D_
         console.log(test1);_x000D_
         console.log(test2);_x000D_
         console.log(test3);
_x000D_
_x000D_
_x000D_

img src SVG changing the styles with CSS

Why not create a webfont with your svg image or images, import the webfont in the css and then just change the color of the glyph using the css color attribute? No javascript needed

Groovy: How to check if a string contains any element of an array?

def valid = pointAddress.findAll { a ->
    validPointTypes.any { a.contains(it) }
}

Should do it

How to disable <br> tags inside <div> by css?

I used it like this:

@media (max-width: 450px) {
  br {
    display: none;
  }
}

nb: media query via Foundation nb2: this is useful if one of the editor intend to use
tags in his/her copy and you need to deal with it specifically under some conditions—on mobile for example.

Custom Input[type="submit"] style not working with jquerymobile button

I'm assume you cannot get css working for your button using anchor tag. So you need to override the css styles which are being overwritten by other elements using !important property.

HTML

<a href="#" class="selected_btn" data-role="button">Button name</a>

CSS

.selected_btn
{
    border:1px solid red;
    text-decoration:none;
    font-family:helvetica;
    color:red !important;            
    background:url('http://www.lessardstephens.com/layout/images/slideshow_big.png') repeat-x;
}

Here is the demo

How to create a jQuery function (a new jQuery method or plugin)?

Create a "colorize" method:

$.fn.colorize = function custom_colorize(some_color) {
    this.css('color', some_color);
    return this;
}

Use it:

$('#my_div').colorize('green');

This simple-ish example combines the best of How to Create a Basic Plugin in the jQuery docs, and answers from @Candide, @Michael.

How to detect the swipe left or Right in Android?

the best answer is @Gal Rom 's. there is more information about it: touch event return's to child views first. and if you define onClick or onTouch listener for them, parnt view (for example fragment) will not receive any touch listener. So if you want define swipe listener for fragment in this situation, you must implement it in a new class:

    package com.neganet.QRelations.fragments;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.FrameLayout;

public class SwipeListenerFragment extends FrameLayout {
    private float x1,x2;
    static final int MIN_DISTANCE=150;
    private onSwipeEventDetected mSwipeDetectedListener;


    public SwipeListenerFragment(Context context) {
        super(context);
    }

    public SwipeListenerFragment(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SwipeListenerFragment(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        boolean result=false;
        switch(ev.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                x1 = ev.getX();
                break;
            case MotionEvent.ACTION_UP:
                x2 = ev.getX();
                float deltaX = x2 - x1;
                if (Math.abs(deltaX) > MIN_DISTANCE)
                {
                    if(deltaX<0)
                    {
                        result=true;
                        if(mSwipeDetectedListener!=null)
                            mSwipeDetectedListener.swipeLeftDetected();

                    }else if(deltaX>0){
                        result=true;
                        if(mSwipeDetectedListener!=null)
                            mSwipeDetectedListener.swipeRightDetected();
                    }
                }
                break;
        }
        return result;
    }

    public interface onSwipeEventDetected
    {
        public void swipeLeftDetected();
        public void swipeRightDetected();

    }

    public void registerToSwipeEvents(onSwipeEventDetected listener)
    {
        this.mSwipeDetectedListener=listener;
    }
}

I changed @Gal Rom 's class. So it can detect both right and left swipe and specially it returns onInterceptTouchEvent true after detect. its important because if we dont do it some times child views maybe receive event and both of Swipe for fragment and onClick for child view (for example) runs and cause some issues. after making this class, you must change your fragment xml file:

    <com.neganet.QRelations.fragments.SwipeListenerFragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:id="@+id/main_list_layout"
    android:clickable="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:layout_height="match_parent" tools:context="com.neganet.QRelations.fragments.mainList"
    android:background="@color/main_frag_back">

    <!-- TODO: Update blank fragment layout -->
    <android.support.v7.widget.RecyclerView
        android:id="@+id/farazList"
        android:scrollbars="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="left|center_vertical" />
</com.neganet.QRelations.fragments.SwipeListenerFragment>

you see that begin tag is the class that we made. now in fragment class:

            View view=inflater.inflate(R.layout.fragment_main_list, container, false);
        SwipeListenerFragment tdView=(SwipeListenerFragment) view;
        tdView.registerToSwipeEvents(this);


and then Implement SwipeListenerFragment.onSwipeEventDetected in it:

        @Override
    public void swipeLeftDetected() {
        Toast.makeText(getActivity(), "left", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void swipeRightDetected() {
        Toast.makeText(getActivity(), "right", Toast.LENGTH_SHORT).show();
    }

It's a little complicated but works perfect :)

Check if a path represents a file or a folder

Please stick to the nio API to perform these checks

import java.nio.file.*;

static Boolean isDir(Path path) {
  if (path == null || !Files.exists(path)) return false;
  else return Files.isDirectory(path);
}

Find out where MySQL is installed on Mac OS X

To check MySQL version of MAMP , use the following command in Terminal:

/Applications/MAMP/Library/bin/mysql --version

Assume you have started MAMP .

Example output:

./mysql  Ver 14.14 Distrib 5.1.44, for apple-darwin8.11.1 (i386) using  EditLine wrapper

UPDATE: Moreover, if you want to find where does mysql installed in system, use the following command:

type -a mysql

type -a is an equivalent of tclsh built-in command where in OS X bash shell. If MySQL is found, it will show :

mysql is /usr/bin/mysql

If not found, it will show:

-bash: type: mysql: not found

By default , MySQL is not installed in Mac OS X.

Sidenote: For XAMPP, the command should be:

/Applications/XAMPP/xamppfiles/bin/mysql --version

How do I install Eclipse Marketplace in Eclipse Classic?

first Help then Install new Software then Switch to the Kepler Repository then General Purpose Tools finally Marketplace Client

Error Installing Homebrew - Brew Command Not Found

try this

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Linuxbrew/linuxbrew/go/install)"

mysql alphabetical order

MySQL solution:

select Name from Employee order by Name ;

Order by will order the names from a to z.

How can I turn a List of Lists into a List in Java 8?

I just want to explain one more scenario like List<Documents>, this list contains a few more lists of other documents like List<Excel>, List<Word>, List<PowerPoint>. So the structure is

class A {
  List<Documents> documentList;
}

class Documents {
  List<Excel> excels;
  List<Word> words;
  List<PowerPoint> ppt;
}

Now if you want to iterate Excel only from documents then do something like below..

So the code would be

 List<Documents> documentList = new A().getDocumentList();

 //check documentList as not null

 Optional<Excel> excelOptional = documentList.stream()
                         .map(doc -> doc.getExcel())
                         .flatMap(List::stream).findFirst();
 if(excelOptional.isPresent()){
   Excel exl = optionalExcel.get();
   // now get the value what you want.
 }

I hope this can solve someone's issue while coding...

rename the columns name after cbind the data

If you pass only vectors to cbind() it creates a matrix, not a dataframe. Read ?data.frame.

How to copy std::string into std::vector<char>?

You need a back inserter to copy into vectors:

std::copy(str.c_str(), str.c_str()+str.length(), back_inserter(data));

How to make a form close when pressing the escape key?

Paste this code into the "On Key Down" Property of your form, also make sure you set "Key Preview" Property to "Yes".

If KeyCode = vbKeyEscape Then DoCmd.Close acForm, "YOUR FORM NAME"

How to Use slideDown (or show) function on a table row?

Animations are not supported on table rows.

From "Learning jQuery" by Chaffer and Swedberg


Table rows present particular obstacles to animation, since browsers use different values (table-row and block) for their visible display property. The .hide() and .show() methods, without animation, are always safe to use with table rows. As of jQuery version 1.1.3, .fadeIn() and .fadeOut() can be used as well.


You can wrap your td contents in a div and use the slideDown on that. You need to decide if the animation is worth the extra markup.

ITextSharp HTML to PDF?

after doing some digging I found a good way to accomplish what I need with ITextSharp.

Here is some sample code if it will help anyone else in the future:

protected void Page_Load(object sender, EventArgs e)
{
    Document document = new Document();
    try
    {
        PdfWriter.GetInstance(document, new FileStream("c:\\my.pdf", FileMode.Create));
        document.Open();
        WebClient wc = new WebClient();
        string htmlText = wc.DownloadString("http://localhost:59500/my.html");
        Response.Write(htmlText);
        List<IElement> htmlarraylist = HTMLWorker.ParseToList(new StringReader(htmlText), null);
        for (int k = 0; k < htmlarraylist.Count; k++)
        {
            document.Add((IElement)htmlarraylist[k]);
        }

        document.Close();
    }
    catch
    {
    }
}

Determine direct shared object dependencies of a Linux binary?

If you want to find dependencies recursively (including dependencies of dependencies, dependencies of dependencies of dependencies and so on)…

You may use ldd command. ldd - print shared library dependencies

Getting session value in javascript

<script>
var someSession = '<%= Session["SessionName"].ToString() %>';
alert(someSession)
</script>

This code you can write in Aspx. If you want this in some js.file, you have two ways:

  1. Make aspx file which writes complete JS code, and set source of this file as Script src
  2. Make handler, to process JS file as aspx.

min and max value of data type in C

#include<stdio.h>

int main(void)
{
    printf("Minimum Signed Char %d\n",-(char)((unsigned char) ~0 >> 1) - 1);
    printf("Maximum Signed Char %d\n",(char) ((unsigned char) ~0 >> 1));

    printf("Minimum Signed Short %d\n",-(short)((unsigned short)~0 >>1) -1);
    printf("Maximum Signed Short %d\n",(short)((unsigned short)~0 >> 1));

    printf("Minimum Signed Int %d\n",-(int)((unsigned int)~0 >> 1) -1);
    printf("Maximum Signed Int %d\n",(int)((unsigned int)~0 >> 1));

    printf("Minimum Signed Long %ld\n",-(long)((unsigned long)~0 >>1) -1);
    printf("Maximum signed Long %ld\n",(long)((unsigned long)~0 >> 1));

    /* Unsigned Maximum Values */

    printf("Maximum Unsigned Char %d\n",(unsigned char)~0);
    printf("Maximum Unsigned Short %d\n",(unsigned short)~0);
    printf("Maximum Unsigned Int %u\n",(unsigned int)~0);
    printf("Maximum Unsigned Long %lu\n",(unsigned long)~0);

    return 0;
}

How to delete/truncate tables from Hadoop-Hive?

You need to drop the table and then recreate it and then load it again

Date Difference in php on days?

I would recommend to use date->diff function, as in example below:

   $dStart = new DateTime('2012-07-26');
   $dEnd  = new DateTime('2012-08-26');
   $dDiff = $dStart->diff($dEnd);
   echo $dDiff->format('%r%a'); // use for point out relation: smaller/greater

see http://www.php.net/manual/en/datetime.diff.php

How to add many functions in ONE ng-click?

A lot of people use (click) option so I will share this too.

<button (click)="function1()" (click)="function2()">Button</button>

delete a column with awk or sed

It seems you could simply go with

awk '{print $1 " " $2}' file

This prints the two first fields of each line in your input file, separated with a space.

Can regular JavaScript be mixed with jQuery?

You can, but be aware of the return types with jQuery functions. jQuery won't always use the exact same JavaScript object type, although generally they will return subclasses of what you would expect to be returned from a similar JavaScript function.

How do I implement onchange of <input type="text"> with jQuery?

You can use .change()

$('input[name=myInput]').change(function() { ... });

However, this event will only fire when the selector has lost focus, so you will need to click somewhere else to have this work.

If that's not quite right for you, you could use some of the other jQuery events like keyup, keydown or keypress - depending on the exact effect you want.

Getting Error 800a0e7a "Provider cannot be found. It may not be properly installed."

I got the same issue and It got solved by installing Oracle 11g client in my machine..

I have not installed any excclusive drivers for it. I am using windows7 with 64 bit. Interestignly, when I navigate into the path Start > Settings > Control Panel > Administrative Tools > DataSources(ODBC) > Drivers. I found only SQL server in it

Please Finc the attachment below for the same

PRINT statement in T-SQL

Query Analyzer buffers messages. The PRINT and RAISERROR statements both use this buffer, but the RAISERROR statement has a WITH NOWAIT option. To print a message immediately use the following:

RAISERROR ('Your message', 0, 1) WITH NOWAIT

RAISERROR will only display 400 characters of your message and uses a syntax similar to the C printf function for formatting text.

Please note that the use of RAISERROR with the WITH NOWAIT option will flush the message buffer, so all previously buffered information will be output also.

Open a selected file (image, pdf, ...) programmatically from my Android Application?

Try the following code.

File file = new File(path); // path = your file path
lastSlash = file.toString().lastIndexOf('/');

if (lastSlash >= 0)
{
    fileName = url.toString().substring(lastSlash + 1);
}


if (fileName.endsWith("pdf"))
{
    mimeType = "application/pdf";
}
else
{
    mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension
    (MimeTypeMap.getFileExtensionFromUrl(path));
}

Uri uri_path = Uri.fromFile(file);

Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.putExtra(PATH, path);
intent.putExtra(MIMETYPE, mimeType);
intent.setType(mimeType);
intent.setDataAndType(uri_path, mimeType);

startActivity(intent);

Change background of LinearLayout in Android

Use this code, where li is the LinearLayout: li.setBackgroundColor(Color.parseColor("#ffff00"));

mongodb: insert if not exists

In general, using update is better in MongoDB as it will just create the document if it doesn't exist yet, though I'm not sure how to work that with your python adapter.

Second, if you only need to know whether or not that document exists, count() which returns only a number will be a better option than find_one which supposedly transfer the whole document from your MongoDB causing unnecessary traffic.

jQuery UI DatePicker to show month year only

Use onSelect call back and remove the year portion manually and set the text in the field manually

How to get param from url in angular 4?

You can try this:

this.activatedRoute.paramMap.subscribe(x => {
    let id = x.get('id');
    console.log(id);  
});

Firefox 'Cross-Origin Request Blocked' despite headers

Just a word of warnings. I finally got around the problem with Firefox and CORS.

The solution for me was this post

Setting CORS (cross-origin resource sharing) on Apache with correct response headers allowing everything through | Benjamin Horn

However Firefox was behaving really, really strange after setting those headers on the Apache server (in the folder .htaccess).

I added a lot of console.log("Hi FF, you are here A") etc to see what was going on.

At first it looked like it hanged on xhr.send(). But then I discovered it did not get to the this statement. I placed another console.log right before it and did not get there - even though there was nothing between the last console.log and the new one. It just stopped between two console.log.

Reordering lines, deleting, to see if there was any strange character in the file. I found nothing.

Restarting Firefox fixed the trouble.

Yes, I should file a bug. It is just that it is so strange so don't know how to reproduce it.

NOTICE: And, oh, I just did the Header always set parts, not the Rewrite* part!

Good Hash Function for Strings

         public String hashString(String s) throws NoSuchAlgorithmException {
    byte[] hash = null;
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        hash = md.digest(s.getBytes());

    } catch (NoSuchAlgorithmException e) { e.printStackTrace(); }
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < hash.length; ++i) {
        String hex = Integer.toHexString(hash[i]);
        if (hex.length() == 1) {
            sb.append(0);
            sb.append(hex.charAt(hex.length() - 1));
        } else {
            sb.append(hex.substring(hex.length() - 2));
        }
    }
    return sb.toString();
}

Detecting Browser Autofill

In Chrome and Edge (2020) checking for :-webkit-autofill will tell you that the inputs have been filled. However, until the user interacts with the page in some way, your JavaScript cannot get the values in the inputs.

Using $('x').focus() and $('x').blur() or triggering a mouse event in code don't help.

See https://stackoverflow.com/a/35783761/32429

How to go to each directory and execute a command?

You can do the following, when your current directory is parent_directory:

for d in [0-9][0-9][0-9]
do
    ( cd "$d" && your-command-here )
done

The ( and ) create a subshell, so the current directory isn't changed in the main script.

Php, wait 5 seconds before executing an action

i use this

    $i = 1;
    $last_time = $_SERVER['REQUEST_TIME'];
    while($i > 0){
        $total = $_SERVER['REQUEST_TIME'] - $last_time;
        if($total >= 2){
            // Code Here
            $i = -1;
        }
    }

you can use

function WaitForSec($sec){
    $i = 1;
    $last_time = $_SERVER['REQUEST_TIME'];
    while($i > 0){
        $total = $_SERVER['REQUEST_TIME'] - $last_time;
        if($total >= 2){
            return 1;
            $i = -1;
        }
    }
}

and run code =>

WaitForSec(your_sec);

Example :

WaitForSec(5);

OR you can use sleep

Example :

sleep(5);

How can I change the default Mysql connection timeout when connecting through python?

You change default value in MySQL configuration file (option connect_timeout in mysqld section) -

[mysqld]
connect_timeout=100

If this file is not accessible for you, then you can set this value using this statement -

SET GLOBAL connect_timeout=100;

force Maven to copy dependencies into target/lib

You can use the the Shade Plugin to create an uber jar in which you can bundle all your 3rd party dependencies.

(Mac) -bash: __git_ps1: command not found

__git_ps1 for bash is now found in git-prompt.sh in /usr/local/etc/bash_completion.d on my brew installed git version 1.8.1.5

Access denied for user 'homestead'@'localhost' (using password: YES)

After change .env with the new configuration, you have to stop the server and run it again (php artisan serve). Cause laravel gets the environment when it's initialized the server. If you don't restart, you will change the .env asking yourself why the changes aren't taking place!!

How can I submit form on button click when using preventDefault()?

Ok, first e.preventDefault(); it's not a Jquery element, it's a method of javascript, now what it's true it's if you add this method you avoid the submit the event, now what you could do it's send the form by ajax something like this

$('#subscription_order_form').submit(function(e){
    $.ajax({
     url: $(this).attr('action'),
     data : $(this).serialize(),
     success : function (data){

      }
   });
    e.preventDefault();
});

Draw horizontal rule in React Native

I was able to draw a separator with flexbox properties even with a text in the center of line.

<View style={{flexDirection: 'row', alignItems: 'center'}}>
  <View style={{flex: 1, height: 1, backgroundColor: 'black'}} />
  <View>
    <Text style={{width: 50, textAlign: 'center'}}>Hello</Text>
  </View>
  <View style={{flex: 1, height: 1, backgroundColor: 'black'}} />
</View>

enter image description here

What happens if you don't commit a transaction to a database (say, SQL Server)?

Any uncomitted transaction will leave the server locked and other queries won't execute on the server. You either need to rollback the transaction or commit it. Closing out of SSMS will also terminate the transaction which will allow other queries to execute.

Get Folder Size from Windows Command Line

Easiest method to get just the total size is powershell, but still is limited by fact that pathnames longer than 260 characters are not included in the total

Create a List that contain each Line of a File

A file is almost a list of lines. You can trivially use it in a for loop.

myFile= open( "SomeFile.txt", "r" )
for x in myFile:
    print x
myFile.close()

Or, if you want an actual list of lines, simply create a list from the file.

myFile= open( "SomeFile.txt", "r" )
myLines = list( myFile )
myFile.close()
print len(myLines), myLines

You can't do someList[i] to put a new item at the end of a list. You must do someList.append(i).

Also, never start a simple variable name with an uppercase letter. List confuses folks who know Python.

Also, never use a built-in name as a variable. list is an existing data type, and using it as a variable confuses folks who know Python.

What is the difference between ManualResetEvent and AutoResetEvent in .NET?

Yes. This is absolutely correct.

You could see ManualResetEvent as a way to indicate state. Something is on (Set) or off (Reset). An occurrence with some duration. Any thread waiting for that state to happen can proceed.

An AutoResetEvent is more comparable to a signal. A one shot indication that something has happened. An occurrence without any duration. Typically but not necessarily the "something" that has happened is small and needs to be handled by a single thread - hence the automatic reset after a single thread have consumed the event.

How to detect if javascript files are loaded?

Like T.J. wrote: the order is defined (at least it's sequential when your browser is about to execute any JavaScript, even if it may download the scripts in parallel somehow). However, as apparently you're having trouble, maybe you're using third-party JavaScript libraries that yield some 404 Not Found or timeout? If so, then read Best way to use Google’s hosted jQuery, but fall back to my hosted library on Google fail.

What are the differences between B trees and B+ trees?

A B+tree is a balanced tree in which every path from the root of the tree to a leaf is of the same length, and each nonleaf node of the tree has between [n/2] and [n] children, where n is fixed for a particular tree. It contains index pages and data pages. Binary trees only have two children per parent node, B+ trees can have a variable number of children for each parent node

Is it possible to move/rename files in Git and maintain their history?

I make moving the files and then do

git add -A

which put in the sataging area all deleted/new files. Here git realizes that the file is moved.

git commit -m "my message"
git push

I do not know why but this works for me.

Git Cherry-pick vs Merge Workflow

Rebase and Cherry-pick is the only way you can keep clean commit history. Avoid using merge and avoid creating merge conflict. If you are using gerrit set one project to Merge if necessary and one project to cherry-pick mode and try yourself.

Why I get 411 Length required error?

When you're using HttpWebRequest and POST method, you have to set a content (or a body if you prefer) via the RequestStream. But, according to your code, using authRequest.Method = "GET" should be enough.

In case you're wondering about POST format, here's what you have to do :

ASCIIEncoding encoder = new ASCIIEncoding();
byte[] data = encoder.GetBytes(serializedObject); // a json object, or xml, whatever...

HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = data.Length;
request.Expect = "application/json";

request.GetRequestStream().Write(data, 0, data.Length);

HttpWebResponse response = request.GetResponse() as HttpWebResponse;