Programs & Examples On #Xnu

xnu is the name of the operating system kernel that underpins Mac OS X/darwin and iOS.

Differences between arm64 and aarch64

AArch64 is the 64-bit state introduced in the Armv8-A architecture (https://en.wikipedia.org/wiki/ARM_architecture#ARMv8-A). The 32-bit state which is backwards compatible with Armv7-A and previous 32-bit Arm architectures is referred to as AArch32. Therefore the GNU triplet for the 64-bit ISA is aarch64. The Linux kernel community chose to call their port of the kernel to this architecture arm64 rather than aarch64, so that's where some of the arm64 usage comes from.

As far as I know the Apple backend for aarch64 was called arm64 whereas the LLVM community-developed backend was called aarch64 (as it is the canonical name for the 64-bit ISA) and later the two were merged and the backend now is called aarch64.

So AArch64 and ARM64 refer to the same thing.

Hadoop cluster setup - java.net.ConnectException: Connection refused

hduser@marta-komputer:/usr/local/hadoop$ jps

11696 ResourceManager

11842 NodeManager

11171 NameNode

11523 SecondaryNameNode

12167 Jps

Where is your DataNode? Connection refused problem might also be due to no active DataNode. Check datanode logs for issues.

UPDATED:

For this error:

15/03/01 00:59:34 INFO client.RMProxy: Connecting to ResourceManager at /0.0.0.0:8032 java.net.ConnectException: Call From marta-komputer.home/192.168.1.8 to marta-komputer:9000 failed on connection exception: java.net.ConnectException: Connection refused; For more details see: http://wiki.apache.org/hadoop/ConnectionRefused

Add these lines in yarn-site.xml:

<property>
<name>yarn.resourcemanager.address</name>
<value>192.168.1.8:8032</value>
</property>
<property>
<name>yarn.resourcemanager.scheduler.address</name>
<value>192.168.1.8:8030</value>
</property>
<property>
<name>yarn.resourcemanager.resource-tracker.address</name>
<value>192.168.1.8:8031</value>
</property>

Restart the hadoop processes.

how to set mongod --dbpath

You could also configure mongod to run on start up so that it is automatically running on start up and the dbpath is set upon configuration. To do this try:

mongod --smallfiles --config /etc/mongod.conf

The --smallfiles tag is there in case you get an error with size. It is, of course, optional. Doing this should solve your problem while also automating your mongodb setup.

Error: Expression must have integral or unscoped enum type

Your variable size is declared as: float size;

You can't use a floating point variable as the size of an array - it needs to be an integer value.

You could cast it to convert to an integer:

float *temp = new float[(int)size];

Your other problem is likely because you're writing outside of the bounds of the array:

   float *temp = new float[size];

    //Getting input from the user
    for (int x = 1; x <= size; x++){
        cout << "Enter temperature " << x << ": ";

        // cin >> temp[x];
        // This should be:
        cin >> temp[x - 1];
    }

Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.

ECONNREFUSED error when connecting to mongodb from node.js

you can go to mongoDB compass client and follow these steps: 1.Click Fill in connection fields individually: enter image description here

2.In hostname type : 127.0.0.1 enter image description here

3. Click CONNECT.

How to get column by number in Pandas?

The following is taken from http://pandas.pydata.org/pandas-docs/dev/indexing.html. There are a few more examples... you have to scroll down a little

In [816]: df1

           0         2         4         6
0   0.569605  0.875906 -2.211372  0.974466
2  -2.006747 -0.410001 -0.078638  0.545952
4  -1.219217 -1.226825  0.769804 -1.281247
6  -0.727707 -0.121306 -0.097883  0.695775
8   0.341734  0.959726 -1.110336 -0.619976
10  0.149748 -0.732339  0.687738  0.176444

Select via integer slicing

In [817]: df1.iloc[:3]

          0         2         4         6
0  0.569605  0.875906 -2.211372  0.974466
2 -2.006747 -0.410001 -0.078638  0.545952
4 -1.219217 -1.226825  0.769804 -1.281247

In [818]: df1.iloc[1:5,2:4]

          4         6
2 -0.078638  0.545952
4  0.769804 -1.281247
6 -0.097883  0.695775
8 -1.110336 -0.619976

Select via integer list

In [819]: df1.iloc[[1,3,5],[1,3]]

           2         6
2  -0.410001  0.545952
6  -0.121306  0.695775
10 -0.732339  0.176444

Determining type of an object in ruby

variable_name.class

Here variable name is "a" a.class

no matching function for call to ' '

You are trying to pass pointers (which you do not delete, thus leaking memory) where references are needed. You do not really need pointers here:

Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);

cout << "Numarul complex este: " << firstComplexNumber << endl;
//                                  ^^^^^^^^^^^^^^^^^^ No need to dereference now

// ...

Complex::distanta(firstComplexNumber, secondComplexNumber);

Creating a List of Lists in C#

I have been toying with this idea too, but I was trying to achieve a slightly different behavior. My idea was to make a list which inherits itself, thus creating a data structure that by nature allows you to embed lists within lists within lists within lists...infinitely!

Implementation

//InfiniteList<T> is a list of itself...
public class InfiniteList<T> : List<InfiniteList<T>>
{
    //This is necessary to allow your lists to store values (of type T).
    public T Value { set; get; }
}

T is a generic type parameter. It is there to ensure type safety in your class. When you create an instance of InfiniteList, you replace T with the type you want your list to be populated with, or in this instance, the type of the Value property.

Example

//The InfiniteList.Value property will be of type string
InfiniteList<string> list = new InfiniteList<string>();

A "working" example of this, where T is in itself, a List of type string!

//Create an instance of InfiniteList where T is List<string>
InfiniteList<List<string>> list = new InfiniteList<List<string>>();

//Add a new instance of InfiniteList<List<string>> to "list" instance.
list.Add(new InfiniteList<List<string>>());

//access the first element of "list". Access the Value property, and add a new string to it.
list[0].Value.Add("Hello World");

Javascript regular expression password validation having special characters

function validatePassword() {
    var p = document.getElementById('newPassword').value,
        errors = [];
    if (p.length < 8) {
        errors.push("Your password must be at least 8 characters"); 
    }
    if (p.search(/[a-z]/i) < 0) {
        errors.push("Your password must contain at least one letter.");
    }
    if (p.search(/[0-9]/) < 0) {
        errors.push("Your password must contain at least one digit."); 
    }
    if (errors.length > 0) {
        alert(errors.join("\n"));
        return false;
    }
    return true;
}

There is a certain issue in below answer as it is not checking whole string due to absence of [ ] while checking the characters and numerals, this is correct version

configure: error: C compiler cannot create executables

Make sure there are no spaces in your Xcode application name (can happen if you keep older versions around - for example renaming it 'Xcode 4.app'); build tools will be referenced within the Xcode bundle paths, and many scripts can't handle references with spaces properly.

what does this mean ? image/png;base64?

That data:image/png;base64 URL is cool, I’ve never run into it before. The long encrypted link is the actual image, i.e. no image call to the server. See RFC 2397 for details.

Side note: I have had trouble getting larger base64 images to render on IE8. I believe IE8 has a 32K limit that can be problematic for larger files. See this other StackOverflow thread for details.

No increment operator (++) in Ruby?

Ruby has no pre/post increment/decrement operator. For instance, x++ or x-- will fail to parse. More importantly, ++x or --x will do nothing! In fact, they behave as multiple unary prefix operators: -x == ---x == -----x == ...... To increment a number, simply write x += 1.

Taken from "Things That Newcomers to Ruby Should Know " (archive, mirror)

That explains it better than I ever could.

EDIT: and the reason from the language author himself (source):

  1. ++ and -- are NOT reserved operator in Ruby.
  2. C's increment/decrement operators are in fact hidden assignment. They affect variables, not objects. You cannot accomplish assignment via method. Ruby uses +=/-= operator instead.
  3. self cannot be a target of assignment. In addition, altering the value of integer 1 might cause severe confusion throughout the program.

Specifying maxlength for multiline textbox

Have a look at this. The only way to solve it is by javascript as you tried.

EDIT: Try changing the event to keypressup.

Parse v. TryParse

I know its a very old post but thought of sharing few more details on Parse vs TryParse.

I had a scenario where DateTime needs to be converted to String and if datevalue null or string.empty we were facing an exception. In order to overcome this, we have replaced Parse with TryParse and will get default date.

Old Code:

dTest[i].StartDate = DateTime.Parse(StartDate).ToString("MM/dd/yyyy");
dTest[i].EndDate = DateTime.Parse(EndDate).ToString("MM/dd/yyyy");

New Code:

DateTime startDate = default(DateTime);
DateTime endDate=default(DateTime);
DateTime.TryParse(dPolicyPaidHistories[i].StartDate, out startDate);
DateTime.TryParse(dPolicyPaidHistories[i].EndDate, out endDate);

Have to declare another variable and used as Out for TryParse.

What is the "continue" keyword and how does it work in Java?

A continue statement without a label will re-execute from the condition the innermost while or do loop, and from the update expression of the innermost for loop. It is often used to early-terminate a loop's processing and thereby avoid deeply-nested if statements. In the following example continue will get the next line, without processing the following statement in the loop.

while (getNext(line)) {
  if (line.isEmpty() || line.isComment())
    continue;
  // More code here
}

With a label, continue will re-execute from the loop with the corresponding label, rather than the innermost loop. This can be used to escape deeply-nested loops, or simply for clarity.

Sometimes continue is also used as a placeholder in order to make an empty loop body more clear.

for (count = 0; foo.moreData(); count++)
  continue;

The same statement without a label also exists in C and C++. The equivalent in Perl is next.

This type of control flow is not recommended, but if you so choose you can also use continue to simulate a limited form of goto. In the following example the continue will re-execute the empty for (;;) loop.

aLoopName: for (;;) {
  // ...
  while (someCondition)
  // ...
    if (otherCondition)
      continue aLoopName;

Setting Django up to use MySQL

Actually, there are many issues with different environments, python versions, so on. You might also need to install python dev files, so to 'brute-force' the installation I would run all of these:

sudo apt-get install python-dev python3-dev
sudo apt-get install libmysqlclient-dev
pip install MySQL-python
pip install pymysql
pip install mysqlclient

You should be good to go with the accepted answer. And can remove the unnecessary packages if that's important to you.

C# event with custom arguments

You need to declare a custom eventhandler.

public class MyEventArgs: EventArgs
{
  ...
}

public delegate void MyEventHandler(object sender, MyEventArgs e);

public class MyControl: UserControl
{
  public event MyEventHandler MyEvent;
   ...
}

ReferenceError: event is not defined error in Firefox

You're declaring (some of) your event handlers incorrectly:

$('.menuOption').click(function( event ){ // <---- "event" parameter here

    event.preventDefault();
    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();


});

You need "event" to be a parameter to the handlers. WebKit follows IE's old behavior of using a global symbol for "event", but Firefox doesn't. When you're using jQuery, that library normalizes the behavior and ensures that your event handlers are passed the event parameter.

edit — to clarify: you have to provide some parameter name; using event makes it clear what you intend, but you can call it e or cupcake or anything else.

Note also that the reason you probably should use the parameter passed in from jQuery instead of the "native" one (in Chrome and IE and Safari) is that that one (the parameter) is a jQuery wrapper around the native event object. The wrapper is what normalizes the event behavior across browsers. If you use the global version, you don't get that.

Evenly distributing n points on a sphere

What you are looking for is called a spherical covering. The spherical covering problem is very hard and solutions are unknown except for small numbers of points. One thing that is known for sure is that given n points on a sphere, there always exist two points of distance d = (4-csc^2(\pi n/6(n-2)))^(1/2) or closer.

If you want a probabilistic method for generating points uniformly distributed on a sphere, it's easy: generate points in space uniformly by Gaussian distribution (it's built into Java, not hard to find the code for other languages). So in 3-dimensional space, you need something like

Random r = new Random();
double[] p = { r.nextGaussian(), r.nextGaussian(), r.nextGaussian() };

Then project the point onto the sphere by normalizing its distance from the origin

double norm = Math.sqrt( (p[0])^2 + (p[1])^2 + (p[2])^2 ); 
double[] sphereRandomPoint = { p[0]/norm, p[1]/norm, p[2]/norm };

The Gaussian distribution in n dimensions is spherically symmetric so the projection onto the sphere is uniform.

Of course, there's no guarantee that the distance between any two points in a collection of uniformly generated points will be bounded below, so you can use rejection to enforce any such conditions that you might have: probably it's best to generate the whole collection and then reject the whole collection if necessary. (Or use "early rejection" to reject the whole collection you've generated so far; just don't keep some points and drop others.) You can use the formula for d given above, minus some slack, to determine the min distance between points below which you will reject a set of points. You'll have to calculate n choose 2 distances, and the probability of rejection will depend on the slack; it's hard to say how, so run a simulation to get a feel for the relevant statistics.

Sort array of objects by string property value

Way 1 :

You can use Underscore.js. Import underscore first.

 import * as _ from 'underscore';
 let SortedObjs = _.sortBy(objs, 'last_nom');

Way 2 : Use compare function.

function compare(first, second) {
     if (first.last_nom < second.last_nom)
         return -1;
     if (first.last_nom > second.last_nom)
       return 1;
    return 0;
 }

objs.sort(compare);

How do I deal with special characters like \^$.?*|+()[{ in my regex?

I think the easiest way to match the characters like

\^$.?*|+()[

are using character classes from within R. Consider the following to clean column headers from a data file, which could contain spaces, and punctuation characters:

> library(stringr)
> colnames(order_table) <- str_replace_all(colnames(order_table),"[:punct:]|[:space:]","")

This approach allows us to string character classes to match punctation characters, in addition to whitespace characters, something you would normally have to escape with \\ to detect. You can learn more about the character classes at this cheatsheet below, and you can also type in ?regexp to see more info about this.

https://www.rstudio.com/wp-content/uploads/2016/09/RegExCheatsheet.pdf

Basic text editor in command prompt?

In a pinch, just type 'notepad (filename)' and notepad will pop up with the file you want to edit in it. Otherwise Vim or some such will have to be installed.

How to search a string in String array

Well, something is going to have to look, and looping is more efficient than recursion (since tail-end recursion isn't fully implemented)... so if you just don't want to loop yourself, then either of:

bool has = arr.Contains(var); // .NET 3.5

or

bool has = Array.IndexOf(arr, var) >= 0;

For info: avoid names like var - this is a keyword in C# 3.0.

How to get file URL using Storage facade in laravel 5?

The Path to your Storage disk would be :

$storagePath  = Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix()

I don't know any shorter solutions to that...

You could share the $storagePath to your Views and then just call

$storagePath."/myImg.jpg";

How to get visitor's location (i.e. country) using geolocation?

You can use ip-api.io to get visitor's location. It supports IPv6.

As a bonus it allows to check whether ip address is a tor node, public proxy or spammer.

JavaScript Code:

function getIPDetails() {
    var ipAddress = document.getElementById("txtIP").value;

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            console.log(JSON.parse(xhttp.responseText));
        }
    };
    xhttp.open("GET", "http://ip-api.io/json/" + ipAddress, true);
    xhttp.send();
}

<input type="text" id="txtIP" placeholder="Enter the ip address" />
<button onclick="getIPDetails()">Get IP Details</button>

jQuery Code:

$(document).ready(function () {
        $('#btnGetIpDetail').click(function () {
            if ($('#txtIP').val() == '') {
                alert('IP address is reqired');
                return false;
            }
            $.getJSON("http://ip-api.io/json/" + $('#txtIP').val(),
                 function (result) {
                     alert('Country Name: ' + result.country_name)
                     console.log(result);
                 });
        });
    });

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div>
    <input type="text" id="txtIP" />
    <button id="btnGetIpDetail">Get Location of IP</button>
</div>

How to get single value of List<object>

You can access the fields by indexing the object array:

foreach (object[] item in selectedValues)
{
  idTextBox.Text = item[0];
  titleTextBox.Text = item[1];
  contentTextBox.Text = item[2];
}

That said, you'd be better off storing the fields in a small class of your own if the number of items is not dynamic:

public class MyObject
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
}

Then you can do:

foreach (MyObject item in selectedValues)
{
  idTextBox.Text = item.Id;
  titleTextBox.Text = item.Title;
  contentTextBox.Text = item.Content;
}

How to convert a UTF-8 string into Unicode?

If you have a UTF-8 string, where every byte is correct ('Ö' -> [195, 0] , [150, 0]), you can use the following:

public static string Utf8ToUtf16(string utf8String)
{
    /***************************************************************
     * Every .NET string will store text with the UTF-16 encoding, *
     * known as Encoding.Unicode. Other encodings may exist as     *
     * Byte-Array or incorrectly stored with the UTF-16 encoding.  *
     *                                                             *
     * UTF-8 = 1 bytes per char                                    *
     *    ["100" for the ansi 'd']                                 *
     *    ["206" and "186" for the russian '?']                    *
     *                                                             *
     * UTF-16 = 2 bytes per char                                   *
     *    ["100, 0" for the ansi 'd']                              *
     *    ["186, 3" for the russian '?']                           *
     *                                                             *
     * UTF-8 inside UTF-16                                         *
     *    ["100, 0" for the ansi 'd']                              *
     *    ["206, 0" and "186, 0" for the russian '?']              *
     *                                                             *
     * First we need to get the UTF-8 Byte-Array and remove all    *
     * 0 byte (binary 0) while doing so.                           *
     *                                                             *
     * Binary 0 means end of string on UTF-8 encoding while on     *
     * UTF-16 one binary 0 does not end the string. Only if there  *
     * are 2 binary 0, than the UTF-16 encoding will end the       *
     * string. Because of .NET we don't have to handle this.       *
     *                                                             *
     * After removing binary 0 and receiving the Byte-Array, we    *
     * can use the UTF-8 encoding to string method now to get a    *
     * UTF-16 string.                                              *
     *                                                             *
     ***************************************************************/

    // Get UTF-8 bytes and remove binary 0 bytes (filler)
    List<byte> utf8Bytes = new List<byte>(utf8String.Length);
    foreach (byte utf8Byte in utf8String)
    {
        // Remove binary 0 bytes (filler)
        if (utf8Byte > 0) {
            utf8Bytes.Add(utf8Byte);
        }
    }

    // Convert UTF-8 bytes to UTF-16 string
    return Encoding.UTF8.GetString(utf8Bytes.ToArray());
}

In my case the DLL result is a UTF-8 string too, but unfortunately the UTF-8 string is interpreted with UTF-16 encoding ('Ö' -> [195, 0], [19, 32]). So the ANSI '–' which is 150 was converted to the UTF-16 '–' which is 8211. If you have this case too, you can use the following instead:

public static string Utf8ToUtf16(string utf8String)
{
    // Get UTF-8 bytes by reading each byte with ANSI encoding
    byte[] utf8Bytes = Encoding.Default.GetBytes(utf8String);

    // Convert UTF-8 bytes to UTF-16 bytes
    byte[] utf16Bytes = Encoding.Convert(Encoding.UTF8, Encoding.Unicode, utf8Bytes);

    // Return UTF-16 bytes as UTF-16 string
    return Encoding.Unicode.GetString(utf16Bytes);
}

Or the Native-Method:

[DllImport("kernel32.dll")]
private static extern Int32 MultiByteToWideChar(UInt32 CodePage, UInt32 dwFlags, [MarshalAs(UnmanagedType.LPStr)] String lpMultiByteStr, Int32 cbMultiByte, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpWideCharStr, Int32 cchWideChar);

public static string Utf8ToUtf16(string utf8String)
{
    Int32 iNewDataLen = MultiByteToWideChar(Convert.ToUInt32(Encoding.UTF8.CodePage), 0, utf8String, -1, null, 0);
    if (iNewDataLen > 1)
    {
        StringBuilder utf16String = new StringBuilder(iNewDataLen);
        MultiByteToWideChar(Convert.ToUInt32(Encoding.UTF8.CodePage), 0, utf8String, -1, utf16String, utf16String.Capacity);

        return utf16String.ToString();
    }
    else
    {
        return String.Empty;
    }
}

If you need it the other way around, see Utf16ToUtf8. Hope I could be of help.

VBA Count cells in column containing specified value

This isn't exactly what you are looking for but here is how I've approached this problem in the past;

You can enter a formula like;

=COUNTIF(A1:A10,"Green")

...into a cell. This will count the Number of cells between A1 and A10 that contain the text "Green". You can then select this cell value in a VBA Macro and assign it to a variable as normal.

Where do I get servlet-api.jar from?

You may want to consider using Java EE, which includes the javax.servlet.* packages. If you require a specific version of the servlet api, for instance to target a specific web application server, you will probably want the Java EE version which matches, see this version table.

In Laravel, the best way to pass different types of flash messages in the session

You could use Laravel Macros.

You can create macros.php in app/helpers and include it routes.php.

if you wish to put your macros in a class file instead, you can look at this tutorial: http://chrishayes.ca/blog/code/laravel-4-object-oriented-form-html-macros-classes-service-provider

HTML::macro('alert', function($class='alert-danger', $value="",$show=false)
{

    $display = $show ? 'display:block' : 'display:none';

    return
        '<div class="alert '.$class.'" style="'.$display.'">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
            <strong><i class="fa fa-times"></i></strong>'.$value.'
        </div>';
});

In your controller:

Session::flash('message', 'This is so dangerous!'); 
Session::flash('alert', 'alert-danger');

In your View

@if(Session::has('message') && Session::has('alert') )
  {{HTML::alert($class=Session::get('alert'), $value=Session::get('message'), $show=true)}}
@endif

insert datetime value in sql database with c#

This is an older question with a proper answer (please use parameterized queries) which I'd like to extend with some timezone discussion. For my current project I was interested in how do the datetime columns handle timezones and this question is the one I found.

Turns out, they do not, at all.

datetime column stores the given DateTime as is, without any conversion. It does not matter if the given datetime is UTC or local.

You can see for yourself:

using (var connection = new SqlConnection(connectionString))
{
    connection.Open();
    using (var command = connection.CreateCommand())
    {
        command.CommandText = "SELECT * FROM (VALUES (@a, @b, @c)) example(a, b, c);";

        var local = DateTime.Now;
        var utc = local.ToUniversalTime();

        command.Parameters.AddWithValue("@a", utc);
        command.Parameters.AddWithValue("@b", local);
        command.Parameters.AddWithValue("@c", utc.ToLocalTime());

        using (var reader = command.ExecuteReader())
        {
            reader.Read();

            var localRendered = local.ToString("o");

            Console.WriteLine($"a = {utc.ToString("o").PadRight(localRendered.Length, ' ')} read = {reader.GetDateTime(0):o}, {reader.GetDateTime(0).Kind}");
            Console.WriteLine($"b = {local:o} read = {reader.GetDateTime(1):o}, {reader.GetDateTime(1).Kind}");
            Console.WriteLine($"{"".PadRight(localRendered.Length + 4, ' ')} read = {reader.GetDateTime(2):o}, {reader.GetDateTime(2).Kind}");
        }
    }
}

What this will print will of course depend on your time zone but most importantly the read values will all have Kind = Unspecified. The first and second output line will be different by your timezone offset. Second and third will be the same. Using the "o" format string (roundtrip) will not show any timezone specifiers for the read values.

Example output from GMT+02:00:

a = 2018-11-20T10:17:56.8710881Z      read = 2018-11-20T10:17:56.8700000, Unspecified
b = 2018-11-20T12:17:56.8710881+02:00 read = 2018-11-20T12:17:56.8700000, Unspecified
                                      read = 2018-11-20T12:17:56.8700000, Unspecified

Also note of how the data gets truncated (or rounded) to what seems like 10ms.

Inserting string at position x of another string

try

a.slice(0,position) + b + a.slice(position)

_x000D_
_x000D_
var a = "I want apple";_x000D_
var b = " an";_x000D_
var position = 6;_x000D_
_x000D_
var r= a.slice(0,position) + b + a.slice(position);_x000D_
_x000D_
console.log(r);
_x000D_
_x000D_
_x000D_

or regexp solution

"I want apple".replace(/^(.{6})/,"$1 an")

_x000D_
_x000D_
var a = "I want apple";_x000D_
var b = " an";_x000D_
var position = 6;_x000D_
_x000D_
var r= a.replace(new RegExp(`^(.{${position}})`),"$1"+b);_x000D_
_x000D_
console.log(r);_x000D_
console.log("I want apple".replace(/^(.{6})/,"$1 an"));
_x000D_
_x000D_
_x000D_

UIView bottom border?

Instead of using a UIView, as @ImreKelényi suggests, you can use a CALayer:

// Add a bottomBorder.
CALayer *bottomBorder = [CALayer layer];

bottomBorder.frame = CGRectMake(0.0f, 43.0f, toScrollView.frame.size.width, 1.0f);

bottomBorder.backgroundColor = [UIColor colorWithWhite:0.8f 
                                                 alpha:1.0f].CGColor;

[toScrollView.layer addSublayer:bottomBorder];

Can I change the fill color of an svg path with CSS?

It's possible to change the path fill color of the svg. See below for the CSS snippet:

  1. To apply the color for all the path: svg > path{ fill: red }

  2. To apply for the first d path: svg > path:nth-of-type(1){ fill: green }

  3. To apply for the second d path: svg > path:nth-of-type(2){ fill: green}

  4. To apply for the different d path, change only the path number:
    svg > path:nth-of-type(${path_number}){ fill: green}

  5. To support the CSS in Angular 2 to 8, use the encapsulation concept:

:host::ng-deep svg path:nth-of-type(1){
        fill:red;
    }

Can't escape the backslash with regex?

If you're putting this in a string within a program, you may actually need to use four backslashes (because the string parser will remove two of them when "de-escaping" it for the string, and then the regex needs two for an escaped regex backslash).

For instance:

regex("\\\\")

is interpreted as...

regex("\\" [escaped backslash] followed by "\\" [escaped backslash])

is interpreted as...

regex(\\)

is interpreted as a regex that matches a single backslash.


Depending on the language, you might be able to use a different form of quoting that doesn't parse escape sequences to avoid having to use as many - for instance, in Python:

re.compile(r'\\')

The r in front of the quotes makes it a raw string which doesn't parse backslash escapes.

PHP error: php_network_getaddresses: getaddrinfo failed: (while getting information from other site.)

Although this is a old thread, I have come across the same error recently while running nslookup in CentOS 7 and google search led me to some of the discussions in SO including this one. However, adding the nameservers entries to /etc/resolv.conf alone did not help as the nameserver values in resolv.conf were overwritten by the NetworkManager with the default DNS nameservers that are in the eth profile associated to the ethernet IP config.

As mentioned by @m-canvar, set the following entries in /etc/resolv.conf

search yourdomain.com
nameserver 8.8.8.8
nameserver 4.2.2.1
nameserver 8.8.4.4

To prevent overwriting these entries by NetworkManager, there are two two approaches:

Option 1: Either set NM_CONTROLLED=no in the eth profile associated to the IPv4/IPv6 profile.

Option 2: Disable NetworkManager service from running.

chkconfig NetworkManager off
service NetworkManager stop

More details can be referred in my post about this error and solution.

JSON forEach get Key and Value

Use index notation with the key.

Object.keys(obj).forEach(function(k){
    console.log(k + ' - ' + obj[k]);
});

What's the difference between lists enclosed by square brackets and parentheses in Python?

The first is a list, the second is a tuple. Lists are mutable, tuples are not.

Take a look at the Data Structures section of the tutorial, and the Sequence Types section of the documentation.

How unique is UUID?

If by "given enough time" you mean 100 years and you're creating them at a rate of a billion a second, then yes, you have a 50% chance of having a collision after 100 years.

Add a scrollbar to a <textarea>

Try adding below CSS

textarea
{
    overflow-y:scroll;
}

Calculate age based on date of birth

I hope you will find this useful.

$query1="SELECT TIMESTAMPDIFF (YEAR, YOUR_DOB_COLUMN, CURDATE()) AS age FROM your_table WHERE id='$user_id'";
$res1=mysql_query($query1);
$row=mysql_fetch_array($res1);
echo $row['age'];

How can I get table names from an MS Access Database?

You can use schemas in Access.

Sub ListAccessTables2(strDBPath)
   Dim cnnDB As ADODB.Connection
   Dim rstList As ADODB.Recordset

   Set cnnDB = New ADODB.Connection

   ' Open the connection.
   With cnnDB
      .Provider = "Microsoft.Jet.OLEDB.4.0"
      .Open strDBPath
   End With

   ' Open the tables schema rowset.
   Set rstList = cnnDB.OpenSchema(adSchemaTables)

   ' Loop through the results and print the
   ' names and types in the Immediate pane.
   With rstList
      Do While Not .EOF
         If .Fields("TABLE_TYPE") <> "VIEW" Then
            Debug.Print .Fields("TABLE_NAME") & vbTab & _
               .Fields("TABLE_TYPE")
         End If
         .MoveNext
      Loop
   End With
   cnnDB.Close
   Set cnnDB = Nothing
End Sub

From: http://msdn.microsoft.com/en-us/library/aa165325(office.10).aspx

How To Create Table with Identity Column

Unique key allows max 2 NULL values. Explaination:

create table teppp
(
id int identity(1,1) primary key,
name varchar(10 )unique,
addresss varchar(10)
)

insert into teppp ( name,addresss) values ('','address1')
insert into teppp ( name,addresss) values ('NULL','address2')
insert into teppp ( addresss) values ('address3')

select * from teppp
null string , address1
NULL,address2
NULL,address3

If you try inserting same values as below:

insert into teppp ( name,addresss) values ('','address4')
insert into teppp ( name,addresss) values ('NULL','address5')
insert into teppp ( addresss) values ('address6')

Every time you will get error like:

Violation of UNIQUE KEY constraint 'UQ__teppp__72E12F1B2E1BDC42'. Cannot insert duplicate key in object 'dbo.teppp'.
The statement has been terminated.

Can not get a simple bootstrap modal to work

Also,

If you're running your page from Visual Studio and have installed the bootstrap package you need to make sure of two things

  1. That you've also gotten the Bootsrap Modal Dialog package (very important)
  2. You've added it to bundle.config if you're using bundling.

The entity name must immediately follow the '&' in the entity reference

All answers posted so far are giving the right solutions, however no one answer was able to properly explain the underlying cause of the concrete problem.

Facelets is a XML based view technology which uses XHTML+XML to generate HTML output. XML has five special characters which has special treatment by the XML parser:

  • < the start of a tag.
  • > the end of a tag.
  • " the start and end of an attribute value.
  • ' the alternative start and end of an attribute value.
  • & the start of an entity (which ends with ;).

In case of & which is not followed by # (e.g. &#160;, &#xA0;, etc), the XML parser is implicitly looking for one of the five predefined entity names lt, gt, amp, quot and apos, or any manually defined entity name. However, in your particular case, you was using & as a JavaScript operator, not as an XML entity. This totally explains the XML parsing error you got:

The entity name must immediately follow the '&' in the entity reference

In essence, you're writing JavaScript code in the wrong place, a XML document instead of a JS file, so you should be escaping all XML special characters accordingly. The & must be escaped as &amp;.

So, in your particular case, the

if (Modernizr.canvas && Modernizr.localstorage && 

must become

if (Modernizr.canvas &amp;&amp; Modernizr.localstorage &amp;&amp;

to make it XML-valid.

However, this makes the JavaScript code harder to read and maintain. As stated in Mozilla Developer Network's excellent document Writing JavaScript for XHTML, you should be placing the JavaScript code in a character data (CDATA) block. Thus, in JSF terms, that would be:

<h:outputScript>
    <![CDATA[
        // ...
    ]]>
</h:outputScript>

The XML parser will interpret the block's contents as "plain vanilla" character data and not as XML and hence interpret the XML special characters "as-is".

But, much better is to just put the JS code in its own JS file which you include by <script src>, or in JSF terms, the <h:outputScript>.

<h:outputScript name="onload.js" target="body" />

(note the target="body"; this way JSF will automatically render the <script> at the very end of <body>, regardless of where <h:outputScript> itself is located, hereby achieving the same effect as with window.onload and $(document).ready(); so you don't need to use those anymore in that script)

This way you don't need to worry about XML-special characters in your JS code. As an additional bonus, this gives you the opportunity to let the browser cache the JS file so that total response size is smaller.

See also:

Global variables in AngularJS

I just found another method by mistake :

What I did was to declare a var db = null above app declaration and then modified it in the app.js then when I accessed it in the controller.js I was able to access it without any problem.There might be some issues with this method which I'm not aware of but It's a good solution I guess.

How to get jQuery to wait until an effect is finished?

if its something you wish to switch, fading one out and fading another in the same place, you can place a {position:absolute} attribute on the divs, so both the animations play on top of one another, and you don't have to wait for one animation to be over before starting up the next.

Run jar file with command line arguments

For the question

How can i run a jar file in command prompt but with arguments

.

To pass arguments to the jar file at the time of execution

java -jar myjar.jar arg1 arg2

In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:

String arg1 = args[0];
String arg2 = args[1];

Shell script variable not empty (-z option)

I think this is the syntax you are looking for:

if [ -z != $errorstatus ] 
then
commands
else
commands
fi

How do I use 3DES encryption/decryption in Java?

Here is a solution using the javax.crypto library and the apache commons codec library for encoding and decoding in Base64:

import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import org.apache.commons.codec.binary.Base64;

public class TrippleDes {

    private static final String UNICODE_FORMAT = "UTF8";
    public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
    private KeySpec ks;
    private SecretKeyFactory skf;
    private Cipher cipher;
    byte[] arrayBytes;
    private String myEncryptionKey;
    private String myEncryptionScheme;
    SecretKey key;

    public TrippleDes() throws Exception {
        myEncryptionKey = "ThisIsSpartaThisIsSparta";
        myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;
        arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
        ks = new DESedeKeySpec(arrayBytes);
        skf = SecretKeyFactory.getInstance(myEncryptionScheme);
        cipher = Cipher.getInstance(myEncryptionScheme);
        key = skf.generateSecret(ks);
    }


    public String encrypt(String unencryptedString) {
        String encryptedString = null;
        try {
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
            byte[] encryptedText = cipher.doFinal(plainText);
            encryptedString = new String(Base64.encodeBase64(encryptedText));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encryptedString;
    }


    public String decrypt(String encryptedString) {
        String decryptedText=null;
        try {
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] encryptedText = Base64.decodeBase64(encryptedString);
            byte[] plainText = cipher.doFinal(encryptedText);
            decryptedText= new String(plainText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return decryptedText;
    }


    public static void main(String args []) throws Exception
    {
        TrippleDes td= new TrippleDes();

        String target="imparator";
        String encrypted=td.encrypt(target);
        String decrypted=td.decrypt(encrypted);

        System.out.println("String To Encrypt: "+ target);
        System.out.println("Encrypted String:" + encrypted);
        System.out.println("Decrypted String:" + decrypted);

    }

}

Running the above program results with the following output:

String To Encrypt: imparator
Encrypted String:FdBNaYWfjpWN9eYghMpbRA==
Decrypted String:imparator

remove / reset inherited css from an element

As long as they are attributes like classes and ids you can remove them by javascript/jQuery class modifiers.

document.getElementById("MyElement").className = "";

There is no way to remove specific tag CSS other than overriding them (or using another element).

Javascript Print iframe contents only

I would not expect that to work

try instead

window.frames["printf"].focus();
window.frames["printf"].print();

and use

<iframe id="printf" name="printf"></iframe>

Alternatively try good old

var newWin = window.frames["printf"];
newWin.document.write('<body onload="window.print()">dddd</body>');
newWin.document.close();

if jQuery cannot hack it

Live Demo

Is there an equivalent of 'which' on the Windows command line?

Windows Server 2003 and later (i.e. anything after Windows XP 32 bit) provide the where.exe program which does some of what which does, though it matches all types of files, not just executable commands. (It does not match built-in shell commands like cd.) It will even accept wildcards, so where nt* finds all files in your %PATH% and current directory whose names start with nt.

Try where /? for help.

Note that Windows PowerShell defines where as an alias for the Where-Object cmdlet, so if you want where.exe, you need to type the full name instead of omitting the .exe extension.

Java 'file.delete()' Is not Deleting Specified File

I got the same problem! then realized that my directory was not empty. I found the solution in another thread: not able to delete the directory through Java

/**
 * Force deletion of directory
 * @param path
 * @return
 */
static public boolean deleteDirectory(File path) {
    if (path.exists()) {
        File[] files = path.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                deleteDirectory(files[i]);
            } else {
                files[i].delete();
            }
        }
    }
    return (path.delete());
}

SQL Developer with JDK (64 bit) cannot find JVM

Today I try to use oracle client 64 and failed connect Connection Identifier which is defined at tnsnames.ora file. I assume that try to connect Oracle 32 Bit Server using SQL Developer 64 bit. That is why I install new jdk x86 and trying to change jdk path but this error happened:

msvcr100.dll error

Trying to download SQL Developer 32 Bit, but at the site said that the bundle support both 32 bit and 64 bit depend on java installed.

Windows 32-bit/64-bit: This archive. will work on a 32 or 64 bit Windows OS. The bit level of the JDK you install will determine if it runs as a 32 or 64 bit application. This download does not include the required Oracle Java JDK. You will need to install it if it's not already on your machine.

My java home is 64 bit. New installed 32 bit jdk is not set at java home.

I need to open $User_dir\AppData\Roaming\sqldeveloper\version\product.conf

Remove line SetJavaHome C:\Program Files\Java\jdk1.8.0_201

Start sqldeveloper.exe instead of sqldeveloper64W.exe

New popup will shown and choose java home to new jdk version (32 bit mine) :

C:\Program Files (x86)\Java\jdk1.8.0_201

My fault, I pin sqldeveloper64W.exe to taskbar, why that error occured then after I move cursor and it was sqldeveloper64W.exe, I try to click sqldeveloper.exe, then I found that my setting is goes well.

So check it maybe it was happened on your system too. If sqldeveloper.exe does not working, try to choose sqldeveloper64W.exe.

Now I can call my Connection Identifier which is defined at tnsnames.ora using new setting SQL developer 32 bit mode.

Git command to display HEAD commit id?

Old thread, still for future reference...:) even following works

git show-ref --head

by default HEAD is filtered out. Be careful about following though ; plural "heads" with a 's' at the end. The following command shows branches under "refs/heads"

 git show-ref --heads

How can I temporarily disable a foreign key constraint in MySQL?

Try DISABLE KEYS or

SET FOREIGN_KEY_CHECKS=0;

Make sure to

SET FOREIGN_KEY_CHECKS=1;

after.

Compare two dates in Java

It's not clear to me what you want, but I'll mention that the Date class also has a compareTo method, which can be used to determine with one call if two Date objects are equal or (if they aren't equal) which occurs sooner. This allows you to do something like:

switch (today.compareTo(questionDate)) {
    case -1:  System.out.println("today is sooner than questionDate");  break;
    case 0:   System.out.println("today and questionDate are equal");  break;
    case 1:   System.out.println("today is later than questionDate");  break;
    default:  System.out.println("Invalid results from date comparison"); break;
}

It should be noted that the API docs don't guarantee the results to be -1, 0, and 1, so you may want to use if-elses rather than a switch in any production code. Also, if the second date is null, you'll get a NullPointerException, so wrapping your code in a try-catch may be useful.

R object identification

If I get 'someObject', say via

someObject <- myMagicFunction(...)

then I usually proceed by

class(someObject)
str(someObject)

which can be followed by head(), summary(), print(), ... depending on the class you have.

Group query results by month and year in postgresql

to_char actually lets you pull out the Year and month in one fell swoop!

select to_char(date('2014-05-10'),'Mon-YY') as year_month; --'May-14'
select to_char(date('2014-05-10'),'YYYY-MM') as year_month; --'2014-05'

or in the case of the user's example above:

select to_char(date,'YY-Mon') as year_month
       sum("Sales") as "Sales"
from some_table
group by 1;

getResourceAsStream returns null

Roughly speaking:

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

Suppose your project structure is like the following:

+-- src
¦   +-- main
¦   +-- test
¦   +-- test
¦       +-- java
¦       ¦   +-- com
¦       ¦       +-- github
¦       ¦           +-- xyz
¦       ¦               +-- proj
¦       ¦                   +-- MainTest.java
¦       ¦                   +-- TestBase.java
¦       +-- resources
¦           +-- abcd.txt
+-- target
    +-- test-classes
        +-- com
        +-- abcd.txt

// in MainClass.java
this.getClass.getResource("/") -> "~/proj_dir/target/test-classes/"
this.getClass.getResource(".") -> "~/proj_dir/target/test-classes/com/github/xyz/proj/"
Thread.currentThread().getContextClassLoader().getResources(".") -> "~/proj_dir/target/test-classes/"
Thread.currentThread().getContextClassLoader().getResources("/") ->  null

How can I hide a checkbox in html?

Try setting the checkbox's opacity to 0. If you want the checkbox to be out of flow try position:absolute and offset the checkbox by a large number.

HTML

<label class="checkbox"><input type="checkbox" value="valueofcheckbox" checked="checked" style="opacity:0; position:absolute; left:9999px;">Option Text</label>

Auto margins don't center image in page

In my case the problem was that I had set min and max width without width itself.

create a white rgba / CSS3

The code you have is a white with low opacity.

If something white with a low opacity is above something black, you end up with a lighter shade of gray. Above red? Lighter red, etc. That is how opacity works.

Here is a simple demo.

If you want it to look 'more white', make it less opaque:

background:rgba(255,255,255, 0.9);

Demo

How to cancel a Task in await?

One case which hasn't been covered is how to handle cancellation inside of an async method. Take for example a simple case where you need to upload some data to a service get it to calculate something and then return some results.

public async Task<Results> ProcessDataAsync(MyData data)
{
    var client = await GetClientAsync();
    await client.UploadDataAsync(data);
    await client.CalculateAsync();
    return await client.GetResultsAsync();
}

If you want to support cancellation then the easiest way would be to pass in a token and check if it has been cancelled between each async method call (or using ContinueWith). If they are very long running calls though you could be waiting a while to cancel. I created a little helper method to instead fail as soon as canceled.

public static class TaskExtensions
{
    public static async Task<T> WaitOrCancel<T>(this Task<T> task, CancellationToken token)
    {
        token.ThrowIfCancellationRequested();
        await Task.WhenAny(task, token.WhenCanceled());
        token.ThrowIfCancellationRequested();

        return await task;
    }

    public static Task WhenCanceled(this CancellationToken cancellationToken)
    {
        var tcs = new TaskCompletionSource<bool>();
        cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).SetResult(true), tcs);
        return tcs.Task;
    }
}

So to use it then just add .WaitOrCancel(token) to any async call:

public async Task<Results> ProcessDataAsync(MyData data, CancellationToken token)
{
    Client client;
    try
    {
        client = await GetClientAsync().WaitOrCancel(token);
        await client.UploadDataAsync(data).WaitOrCancel(token);
        await client.CalculateAsync().WaitOrCancel(token);
        return await client.GetResultsAsync().WaitOrCancel(token);
    }
    catch (OperationCanceledException)
    {
        if (client != null)
            await client.CancelAsync();
        throw;
    }
}

Note that this will not stop the Task you were waiting for and it will continue running. You'll need to use a different mechanism to stop it, such as the CancelAsync call in the example, or better yet pass in the same CancellationToken to the Task so that it can handle the cancellation eventually. Trying to abort the thread isn't recommended.

How can I find out the total physical memory (RAM) of my linux box suitable to be parsed by a shell script?

I find htop a useful tool.

sudo apt-get install htop

and then

free -m

will give the information you need.

Why is using the JavaScript eval function a bad idea?

It's not necessarily that bad provided you know what context you're using it in.

If your application is using eval() to create an object from some JSON which has come back from an XMLHttpRequest to your own site, created by your trusted server-side code, it's probably not a problem.

Untrusted client-side JavaScript code can't do that much anyway. Provided the thing you're executing eval() on has come from a reasonable source, you're fine.

Bloomberg BDH function with ISIN

The problem is that an isin does not identify the exchange, only an issuer.

Let's say your isin is US4592001014 (IBM), one way to do it would be:

  • get the ticker (in A1):

    =BDP("US4592001014 ISIN", "TICKER") => IBM
    
  • get a proper symbol (in A2)

    =BDP("US4592001014 ISIN", "PARSEKYABLE_DES") => IBM XX Equity
    

    where XX depends on your terminal settings, which you can check on CNDF <Go>.

  • get the main exchange composite ticker, or whatever suits your need (in A3):

    =BDP(A2,"EQY_PRIM_SECURITY_COMP_EXCH") => US
    
  • and finally:

    =BDP(A1&" "&A3&" Equity", "LAST_PRICE") => the last price of IBM US Equity
    

Getting "cannot find Symbol" in Java project in Intellij

This happened to me when I deleted a folder and then copy-pasted it back to the project.

Right-click project folder -> Rebuild worked for me.

How to change the server port from 3000?

You can change it inside bs-config.json file as mentioned in the docs https://github.com/johnpapa/lite-server#custom-configuration

For example,

{
  "port": 8000,
  "files": ["./src/**/*.{html,htm,css,js}"],
  "server": { "baseDir": "./src" }
}

httpd-xampp.conf: How to allow access to an external IP besides localhost?

<Directory "C:/xampp/">
    AllowOverride AuthConfig Limit
    Order allow,deny
    Allow from all
    Require all granted
</Directory>

This is what i added in the end of file \xampp\apache\conf\extra\httpd-xampp.conf file before tag

Which version of C# am I using

It depends upon the .NET Framework that you use. Check Jon Skeet's answer about Versions.

Here is short version of his answer.

C# 1.0 released with .NET 1.0

C# 1.2 (bizarrely enough); released with .NET 1.1

C# 2.0 released with .NET 2.0

C# 3.0 released with .NET 3.5

C# 4.0 released with .NET 4

C# 5.0 released with .NET 4.5

C# 6.0 released with .NET 4.6

C# 7.0 is released with .NET 4.6.2

C# 7.3 is released with .NET 4.7.2

C# 8.0 is released with NET Core 3.0

C# 9.0 is released with NET 5.0

Is it possible to import modules from all files in a directory, using a wildcard?

The current answers suggest a workaround but it's bugged me why this doesn't exist, so I've created a babel plugin which does this.

Install it using:

npm i --save-dev babel-plugin-wildcard

then add it to your .babelrc with:

{
    "plugins": ["wildcard"]
}

see the repo for detailed install info


This allows you to do this:

import * as Things from './lib/things';

// Do whatever you want with these :D
Things.ThingA;
Things.ThingB;
Things.ThingC;

again, the repo contains further information on what exactly it does, but doing it this way avoids creating index.js files and also happens at compile-time to avoid doing readdirs at runtime.

Also with a newer version you can do exactly like your example:

 import { ThingsA, ThingsB, ThingsC } from './lib/things/*';

works the same as the above.

Simulate a button click in Jest

Additionally to the solutions that were suggested in sibling comments, you may change your testing approach a little bit and test not the whole page all at once (with a deep children components tree), but do an isolated component testing. This will simplify testing of onClick() and similar events (see example below).

The idea is to test only one component at a time and not all of them together. In this case all children components will be mocked using the jest.mock() function.

Here is an example of how the onClick() event may be tested in an isolated SearchForm component using Jest and react-test-renderer.

import React from 'react';
import renderer from 'react-test-renderer';
import { SearchForm } from '../SearchForm';

describe('SearchForm', () => {
  it('should fire onSubmit form callback', () => {
    // Mock search form parameters.
    const searchQuery = 'kittens';
    const onSubmit = jest.fn();

    // Create test component instance.
    const testComponentInstance = renderer.create((
      <SearchForm query={searchQuery} onSearchSubmit={onSubmit} />
    )).root;

    // Try to find submit button inside the form.
    const submitButtonInstance = testComponentInstance.findByProps({
      type: 'submit',
    });
    expect(submitButtonInstance).toBeDefined();

    // Since we're not going to test the button component itself
    // we may just simulate its onClick event manually.
    const eventMock = { preventDefault: jest.fn() };
    submitButtonInstance.props.onClick(eventMock);

    expect(onSubmit).toHaveBeenCalledTimes(1);
    expect(onSubmit).toHaveBeenCalledWith(searchQuery);
  });
});

jQuery: Check if special characters exists in string

You could also use the whitelist method -

var str = $('#Search').val();
var regex = /[^\w\s]/gi;

if(regex.test(str) == true) {
    alert('Your search string contains illegal characters.');
}

The regex in this example is digits, word characters, underscores (\w) and whitespace (\s). The caret (^) indicates that we are to look for everything that is not in our regex, so look for things that are not word characters, underscores, digits and whitespace.

How can you determine a point is between two other points on a line segment?

Check if the cross product of b-a and c-a is0: that means all the points are collinear. If they are, check if c's coordinates are between a's and b's. Use either the x or the y coordinates, as long as a and b are separate on that axis (or they're the same on both).

def is_on(a, b, c):
    "Return true iff point c intersects the line segment from a to b."
    # (or the degenerate case that all 3 points are coincident)
    return (collinear(a, b, c)
            and (within(a.x, c.x, b.x) if a.x != b.x else 
                 within(a.y, c.y, b.y)))

def collinear(a, b, c):
    "Return true iff a, b, and c all lie on the same line."
    return (b.x - a.x) * (c.y - a.y) == (c.x - a.x) * (b.y - a.y)

def within(p, q, r):
    "Return true iff q is between p and r (inclusive)."
    return p <= q <= r or r <= q <= p

This answer used to be a mess of three updates. The worthwhile info from them: Brian Hayes's chapter in Beautiful Code covers the design space for a collinearity-test function -- useful background. Vincent's answer helped to improve this one. And it was Hayes who suggested testing only one of the x or the y coordinates; originally the code had and in place of if a.x != b.x else.

Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

This is the solution for my old question:

I implemented my own ContextResolver in order to enable the DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY feature.

package org.lig.hadas.services.mapper;

import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;

@Produces(MediaType.APPLICATION_JSON)
@Provider
public class ObjectMapperProvider implements ContextResolver<ObjectMapper>
{
   ObjectMapper mapper;

   public ObjectMapperProvider(){
       mapper = new ObjectMapper();
       mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
   }
   @Override
   public ObjectMapper getContext(Class<?> type) {
       return mapper;
   }
}

And in the web.xml I registered my package into the servlet definition...

<servlet>
    <servlet-name>...</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>...;org.lig.hadas.services.mapper</param-value>        
    </init-param>
    ...
</servlet>

... all the rest is transparently done by jersey/jackson.

converting date time to 24 hour format

import java.text.SimpleDateFormat;

import java.util.Date;

public class DateFormatExample {

public static void main(String args[]) {

    // This is how to get today's date in Java
    Date today = new Date();

    //If you print Date, you will get un formatted output
    System.out.println("Today is : " + today);

    //formatting date in Java using SimpleDateFormat
    SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy");
    String date = DATE_FORMAT.format(today);
    System.out.println("Today in dd-MM-yyyy format : " + date);

    //Another Example of formatting Date in Java using SimpleDateFormat
    DATE_FORMAT = new SimpleDateFormat("dd/MM/yy");
    date = DATE_FORMAT.format(today);
    System.out.println("Today in dd/MM/yy pattern : " + date);

    //formatting Date with time information
    DATE_FORMAT = new SimpleDateFormat("dd-MM-yy:HH:mm:SS");
    date = DATE_FORMAT.format(today);
    System.out.println("Today in dd-MM-yy:HH:mm:SS : " + date);

    //SimpleDateFormat example - Date with timezone information
    DATE_FORMAT = new SimpleDateFormat("dd-MM-yy:HH:mm:SS Z");
    date = DATE_FORMAT.format(today);
    System.out.println("Today in dd-MM-yy:HH:mm:SSZ : " + date);

} 

}

Output:

Today is : Fri Nov 02 16:11:27 IST 2012

Today in dd-MM-yyyy format : 02-11-2012

Today in dd/MM/yy pattern : 02/11/12

Today in dd-MM-yy:HH:mm:SS : 02-11-12:16:11:316

Today in dd-MM-yy:HH:mm:SSZ : 02-11-12:16:11:316 +0530

Mockito: Trying to spy on method is calling the original method

Bit late to the party but above solutions did not work for me , so sharing my 0.02$

Mokcito version: 1.10.19

MyClass.java

private int handleAction(List<String> argList, String action)

Test.java

MyClass spy = PowerMockito.spy(new MyClass());

Following did NOT work for me (actual method was being called):

1.

doReturn(0).when(spy , "handleAction", ListUtils.EMPTY_LIST, new String());

2.

doReturn(0).when(spy , "handleAction", any(), anyString());

3.

doReturn(0).when(spy , "handleAction", null, null);

Following WORKED:

doReturn(0).when(spy , "handleAction", any(List.class), anyString());

Verify External Script Is Loaded

I think it's better to use window.addEventListener('error') to capture the script load error and try to load it again. It's useful when we load scripts from a CDN server. If we can't load script from the CDN, we can load it from our server.

window.addEventListener('error', function(e) {
  if (e.target.nodeName === 'SCRIPT') {
    var scriptTag = document.createElement('script');
    scriptTag.src = e.target.src.replace('https://static.cdn.com/', '/our-server/static/');
    document.head.appendChild(scriptTag);
  }
}, true);

Convert date to day name e.g. Mon, Tue, Wed

This is what happens when you store your dates and times in a non-standard format. Working with them become problematic.

$datetime = DateTime::createFromFormat('YmdHi', '201308131830');
echo $datetime->format('D');

See it in action

Difference between text and varchar (character varying)

Somewhat OT: If you're using Rails, the standard formatting of webpages may be different. For data entry forms text boxes are scrollable, but character varying (Rails string) boxes are one-line. Show views are as long as needed.

sudo in php exec()

I had a similar situation trying to exec() a backend command and also getting no tty present and no askpass program specified in the web server error log. Original (bad) code:

$output = array();
$return_var = 0;
exec('sudo my_command', $output, $return_var);

A bash wrapper solved this issue, such as:

$output = array();
$return_var = 0;
exec('sudo bash -c "my_command"', $output, $return_var);

Not sure if this will work in every case. Also, be sure to apply the appropriate quoting/escaping rules on my_command portion.

Difference between Divide and Conquer Algo and Dynamic Programming

Divide and Conquer

Divide and Conquer works by dividing the problem into sub-problems, conquer each sub-problem recursively and combine these solutions.

Dynamic Programming

Dynamic Programming is a technique for solving problems with overlapping subproblems. Each sub-problem is solved only once and the result of each sub-problem is stored in a table ( generally implemented as an array or a hash table) for future references. These sub-solutions may be used to obtain the original solution and the technique of storing the sub-problem solutions is known as memoization.

You may think of DP = recursion + re-use

A classic example to understand the difference would be to see both these approaches towards obtaining the nth fibonacci number. Check this material from MIT.


Divide and Conquer approach Divide and Conquer approach

Dynamic Programming Approach enter image description here

Ajax success event not working

Put an alert() in your success callback to make sure it's being called at all.

If it's not, that's simply because the request wasn't successful at all, even though you manage to hit the server. Reasonable causes could be that a timeout expires, or something in your php code throws an exception.

Install the firebug addon for firefox, if you haven't already, and inspect the AJAX callback. You'll be able to see the response, and whether or not it receives a successful (200 OK) response. You can also put another alert() in the complete callback, which should definitely be invoked.

Show constraints on tables command

Simply query the INFORMATION_SCHEMA:

USE INFORMATION_SCHEMA;
SELECT TABLE_NAME,
       COLUMN_NAME,
       CONSTRAINT_NAME,
       REFERENCED_TABLE_NAME,
       REFERENCED_COLUMN_NAME
FROM KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = "<your_database_name>" 
      AND TABLE_NAME = "<your_table_name>" 
      AND REFERENCED_COLUMN_NAME IS NOT NULL;

Oracle date function for the previous month

Getting last nth months data retrieve

SELECT * FROM TABLE_NAME 
WHERE DATE_COLUMN BETWEEN '&STARTDATE' AND '&ENDDATE'; 

Delete all items from a c++ std::vector

Use v.clear() to empty the vector.

If your vector contains pointers, clear calls the destructor for the object but does not delete the memory referenced by the pointer.

vector<SomeClass*> v(0);

v.push_back( new SomeClass("one") );

v.clear();  //Memory leak where "one" instance of SomeClass is lost

What is the difference between procedural programming and functional programming?

Basically the two styles, are like Yin and Yang. One is organized, while the other chaotic. There are situations when Functional programming is the obvious choice, and other situations were Procedural programming is the better choice. This is why there are at least two languages that have recently come out with a new version, that embraces both programming styles. ( Perl 6 and D 2 )

#Procedural:#

  • The output of a routine does not always have a direct correlation with the input.
  • Everything is done in a specific order.
  • Execution of a routine may have side effects.
  • Tends to emphasize implementing solutions in a linear fashion.

##Perl 6 ##

sub factorial ( UInt:D $n is copy ) returns UInt {

  # modify "outside" state
  state $call-count++;
  # in this case it is rather pointless as
  # it can't even be accessed from outside

  my $result = 1;

  loop ( ; $n > 0 ; $n-- ){

    $result *= $n;

  }

  return $result;
}

##D 2##

int factorial( int n ){

  int result = 1;

  for( ; n > 0 ; n-- ){
    result *= n;
  }

  return result;
}

#Functional:#

  • Often recursive.
  • Always returns the same output for a given input.
  • Order of evaluation is usually undefined.
  • Must be stateless. i.e. No operation can have side effects.
  • Good fit for parallel execution
  • Tends to emphasize a divide and conquer approach.
  • May have the feature of Lazy Evaluation.

##Haskell## ( copied from Wikipedia );

fac :: Integer -> Integer

fac 0 = 1
fac n | n > 0 = n * fac (n-1)

or in one line:

fac n = if n > 0 then n * fac (n-1) else 1

##Perl 6 ##

proto sub factorial ( UInt:D $n ) returns UInt {*}

multi sub factorial (  0 ) { 1 }
multi sub factorial ( $n ) { $n * samewith $n-1 } # { $n * factorial $n-1 }

##D 2##

pure int factorial( invariant int n ){
  if( n <= 1 ){
    return 1;
  }else{
    return n * factorial( n-1 );
  }
}

#Side note:#

Factorial is actually a common example to show how easy it is to create new operators in Perl 6 the same way you would create a subroutine. This feature is so ingrained into Perl 6 that most operators in the Rakudo implementation are defined this way. It also allows you to add your own multi candidates to existing operators.

sub postfix:< ! > ( UInt:D $n --> UInt )
  is tighter(&infix:<*>)
  { [*] 2 .. $n }

say 5!; # 120?

This example also shows range creation (2..$n) and the list reduction meta-operator ([ OPERATOR ] LIST) combined with the numeric infix multiplication operator. (*)
It also shows that you can put --> UInt in the signature instead of returns UInt after it.

( You can get away with starting the range with 2 as the multiply "operator" will return 1 when called without any arguments )

print memory address of Python variable

There is no way to get the memory address of a value in Python 2.7 in general. In Jython or PyPy, the implementation doesn't even know your value's address (and there's not even a guarantee that it will stay in the same place—e.g., the garbage collector is allowed to move it around if it wants).

However, if you only care about CPython, id is already returning the address. If the only issue is how to format that integer in a certain way… it's the same as formatting any integer:

>>> hex(33)
0x21
>>> '{:#010x}'.format(33) # 32-bit
0x00000021
>>> '{:#018x}'.format(33) # 64-bit
0x0000000000000021

… and so on.

However, there's almost never a good reason for this. If you actually need the address of an object, it's presumably to pass it to ctypes or similar, in which case you should use ctypes.addressof or similar.

What is an AssertionError? In which case should I throw it from my own code?

I'm really late to party here, but most of the answers seem to be about the whys and whens of using assertions in general, rather than using AssertionError in particular.

assert and throw new AssertionError() are very similar and serve the same conceptual purpose, but there are differences.

  1. throw new AssertionError() will throw the exception regardless of whether assertions are enabled for the jvm (i.e., through the -ea switch).
  2. The compiler knows that throw new AssertionError() will exit the block, so using it will let you avoid certain compiler errors that assert will not.

For example:

    {
        boolean b = true;
        final int n;
        if ( b ) {
            n = 5;
        } else {
            throw new AssertionError();
        }
        System.out.println("n = " + n);
    }

    {
        boolean b = true;
        final int n;
        if ( b ) {
            n = 5;
        } else {
            assert false;
        }
        System.out.println("n = " + n);
    }

The first block, above, compiles just fine. The second block does not compile, because the compiler cannot guarantee that n has been initialized by the time the code tries to print it out.

Java: Simplest way to get last word in a string

String test =  "This is a sentence";
String lastWord = test.substring(test.lastIndexOf(" ")+1);

How to use KeyListener

Here is an SSCCE,

package experiment;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class KeyListenerTester extends JFrame implements KeyListener {

    JLabel label;

    public KeyListenerTester(String s) {
        super(s);
        JPanel p = new JPanel();
        label = new JLabel("Key Listener!");
        p.add(label);
        add(p);
        addKeyListener(this);
        setSize(200, 100);
        setVisible(true);

    }

    @Override
    public void keyTyped(KeyEvent e) {

        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key typed");
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key typed");
        }

    }

    @Override
    public void keyPressed(KeyEvent e) {

        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key pressed");
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key pressed");
        }

    }

    @Override
    public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key Released");
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key Released");
        }
    }

    public static void main(String[] args) {
        new KeyListenerTester("Key Listener Tester");
    }
}

Additionally read upon these links : How to Write a Key Listener and How to Use Key Bindings

Java Compare Two Lists

Using java 8 removeIf

public int getSimilarItems(){
    List<String> one = Arrays.asList("milan", "dingo", "elpha", "hafil", "meat", "iga", "neeta.peeta");
    List<String> two = new ArrayList<>(Arrays.asList("hafil", "iga", "binga", "mike", "dingo")); //Cannot remove directly from array backed collection
    int initial = two.size();

    two.removeIf(one::contains);
    return initial - two.size();
}

Loading custom functions in PowerShell

I kept using this all this time

Import-module .\build_functions.ps1 -Force

How to generate .json file with PHP?

Use PHP's json methods to create the json then write it to a file with fwrite.

500.21 Bad module "ManagedPipelineHandler" in its module list

I ran into this error on a fresh build of Windows Server 2012 R2. IIS and .NET 4.5 had been installed, but the ASP.NET Server Role (version 4.5 in my case) had not been added. Make sure that the version of ASP.NET you need has been added/installed like ASP.NET 4.5 is in this screenshot.

ASP.NET Server Role

Alter table to modify default value of column

For Sql Azure the following query works :

ALTER TABLE [TableName] ADD  DEFAULT 'DefaultValue' FOR ColumnName
GO

Remove an item from a dictionary when its key is unknown

Be aware that you're currently testing for object identity (is only returns True if both operands are represented by the same object in memory - this is not always the case with two object that compare equal with ==). If you are doing this on purpose, then you could rewrite your code as

some_dict = {key: value for key, value in some_dict.items() 
             if value is not value_to_remove}

But this may not do what you want:

>>> some_dict = {1: "Hello", 2: "Goodbye", 3: "You say yes", 4: "I say no"}
>>> value_to_remove = "You say yes"
>>> some_dict = {key: value for key, value in some_dict.items() if value is not value_to_remove}
>>> some_dict
{1: 'Hello', 2: 'Goodbye', 3: 'You say yes', 4: 'I say no'}
>>> some_dict = {key: value for key, value in some_dict.items() if value != value_to_remove}
>>> some_dict
{1: 'Hello', 2: 'Goodbye', 4: 'I say no'}

So you probably want != instead of is not.

How to convert a String into an ArrayList?

This is using Gson in Kotlin

 val listString = "[uno,dos,tres,cuatro,cinco]"
 val gson = Gson()
 val lista = gson.fromJson(listString , Array<String>::class.java).toList()
 Log.e("GSON", lista[0])

How to pass a datetime parameter?

The problem is twofold:

1. The . in the route

By default, IIS treats all URI's with a dot in them as static resource, tries to return it and skip further processing (by Web API) altogether. This is configured in your Web.config in the section system.webServer.handlers: the default handler handles path="*.". You won't find much documentation regarding the strange syntax in this path attribute (regex would have made more sense), but what this apparently means is "anything that doesn't contain a dot" (and any character from point 2 below). Hence the 'Extensionless' in the name ExtensionlessUrlHandler-Integrated-4.0.

Multiple solutions are possible, in my opinion in the order of 'correctness':

  • Add a new handler specifically for the routes that must allow a dot. Be sure to add it before the default. To do this, make sure you remove the default handler first, and add it back after yours.
  • Change the path="*." attribute to path="*". It will then catch everything. Note that from then on, your web api will no longer interpret incoming calls with dots as static resources! If you are hosting static resources on your web api, this is therefor not advised!
  • Add the following to your Web.config to unconditionally handle all requests: under <system.webserver>: <modules runAllManagedModulesForAllRequests="true">

2. The : in the route

After you've changed the above, by default, you'd get the following error:

A potentially dangerous Request.Path value was detected from the client (:).

You can change the predefined disallowed/invalid characters in your Web.config. Under <system.web>, add the following: <httpRuntime requestPathInvalidCharacters="&lt;,&gt;,%,&amp;,*,\,?" />. I've removed the : from the standard list of invalid characters.

Easier/safer solutions

Although not an answer to your question, a safer and easier solution would be to change the request so that all this is not required. This can be done in two ways:

  1. Pass the date as a query string parameter, like ?date=2012-12-31T22:00:00.000Z.
  2. Strip the .000 from every request. You'd still need to allow :'s (cfr point 2).

How do I write dispatch_after GCD in Swift 3, 4, and 5?

This worked for me in Swift 3

let time1 = 8.23
let time2 = 3.42

// Delay 2 seconds


DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
    print("Sum of times: \(time1 + time2)")
}

What does flex: 1 mean?

Here is the explanation:

https://www.w3.org/TR/css-flexbox-1/#flex-common

flex: <positive-number>
Equivalent to flex: <positive-number> 1 0. Makes the flex item flexible and sets the flex basis to zero, resulting in an item that receives the specified proportion of the free space in the flex container. If all items in the flex container use this pattern, their sizes will be proportional to the specified flex factor.

Therefore flex:1 is equivalent to flex: 1 1 0

RecyclerView expand/collapse items

Do the following after you set the onClick listener to the ViewHolder class:

@Override
    public void onClick(View v) {
        final int originalHeight = yourLinearLayout.getHeight();
        animationDown(YourLinearLayout, originalHeight);//here put the name of you layout that have the options to expand.
    }

    //Animation for devices with kitkat and below
    public void animationDown(LinearLayout billChoices, int originalHeight){

        // Declare a ValueAnimator object
        ValueAnimator valueAnimator;
        if (!billChoices.isShown()) {
            billChoices.setVisibility(View.VISIBLE);
            billChoices.setEnabled(true);
            valueAnimator = ValueAnimator.ofInt(0, originalHeight+originalHeight); // These values in this method can be changed to expand however much you like
        } else {
            valueAnimator = ValueAnimator.ofInt(originalHeight+originalHeight, 0);

            Animation a = new AlphaAnimation(1.00f, 0.00f); // Fade out

            a.setDuration(200);
            // Set a listener to the animation and configure onAnimationEnd
            a.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    billChoices.setVisibility(View.INVISIBLE);
                    billChoices.setEnabled(false);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
            // Set the animation on the custom view
            billChoices.startAnimation(a);
        }
        valueAnimator.setDuration(200);
        valueAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            public void onAnimationUpdate(ValueAnimator animation) {
                Integer value = (Integer) animation.getAnimatedValue();
                billChoices.getLayoutParams().height = value.intValue();
                billChoices.requestLayout();
            }
        });


        valueAnimator.start();
    }
}

I think that should help, that's how I implemented and does the same google does in the recent call view.

Split array into chunks

I changed BlazeMonger's slightly to use for a jQuery object..

var $list = $('li'),
    $listRows = [];


for (var i = 0, len = $list.length, chunk = 4, n = 0; i < len; i += chunk, n++) {
   $listRows[n] = $list.slice(i, i + chunk);
}

What are the dark corners of Vim your mom never told you about?

:%!xxd

Make vim into a hex editor.

:%!xxd -r

Revert.

Warning: If you don't edit with binary (-b), you might damage the file. – Josh Lee in the comments.

Faking an RS232 Serial Port

I use com0com - With Signed Driver, on windows 7 x64 to emulate COM3 AND COM4 as a pair.

Then i use COM Dataport Emulator to recieve from COM4.

Then i open COM3 with the app im developping (c#) and send data to COM3.

The data sent thru COM3 is received by COM4 and shown by 'COM Dataport Emulator' who can also send back a response (not automated).

So with this 2 great programs i managed to emulate Serial RS-232 comunication.

Hope it helps.

Both programs are free!!!!!

How to increment a datetime by one day?

All of the current answers are wrong in some cases as they do not consider that timezones change their offset relative to UTC. So in some cases adding 24h is different from adding a calendar day.

Proposed solution

The following solution works for Samoa and keeps the local time constant.

def add_day(today):
    """
    Add a day to the current day.

    This takes care of historic offset changes and DST.

    Parameters
    ----------
    today : timezone-aware datetime object

    Returns
    -------
    tomorrow : timezone-aware datetime object
    """
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    tomorrow_utc_tz = tomorrow_utc_tz.replace(hour=today.hour,
                                              minute=today.minute,
                                              second=today.second)
    return tomorrow_utc_tz

Tested Code

# core modules
import datetime

# 3rd party modules
import pytz


# add_day methods
def add_day(today):
    """
    Add a day to the current day.

    This takes care of historic offset changes and DST.

    Parameters
    ----------
    today : timezone-aware datetime object

    Returns
    -------
    tomorrow : timezone-aware datetime object
    """
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    tomorrow_utc_tz = tomorrow_utc_tz.replace(hour=today.hour,
                                              minute=today.minute,
                                              second=today.second)
    return tomorrow_utc_tz


def add_day_datetime_timedelta_conversion(today):
    # Correct for Samoa, but dst shift
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    return tomorrow_utc_tz


def add_day_dateutil_relativedelta(today):
    # WRONG!
    from dateutil.relativedelta import relativedelta
    return today + relativedelta(days=1)


def add_day_datetime_timedelta(today):
    # WRONG!
    return today + datetime.timedelta(days=1)


# Test cases
def test_samoa(add_day):
    """
    Test if add_day properly increases the calendar day for Samoa.

    Due to economic considerations, Samoa went from 2011-12-30 10:00-11:00
    to 2011-12-30 10:00+13:00. Hence the country skipped 2011-12-30 in its
    local time.

    See https://stackoverflow.com/q/52084423/562769

    A common wrong result here is 2011-12-30T23:59:00-10:00. This date never
    happened in Samoa.
    """
    tz = pytz.timezone('Pacific/Apia')
    today_utc = datetime.datetime(2011, 12, 30, 9, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2011-12-29T23:59:00-10:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2011-12-31T23:59:00+14:00'


def test_dst(add_day):
    """Test if add_day properly increases the calendar day if DST happens."""
    tz = pytz.timezone('Europe/Berlin')
    today_utc = datetime.datetime(2018, 3, 25, 0, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2018-03-25T01:59:00+01:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2018-03-26T01:59:00+02:00'


to_test = [(add_day_dateutil_relativedelta, 'relativedelta'),
           (add_day_datetime_timedelta, 'timedelta'),
           (add_day_datetime_timedelta_conversion, 'timedelta+conversion'),
           (add_day, 'timedelta+conversion+dst')]
print('{:<25}: {:>5} {:>5}'.format('Method', 'Samoa', 'DST'))
for method, name in to_test:
    print('{:<25}: {:>5} {:>5}'
          .format(name,
                  test_samoa(method),
                  test_dst(method)))

Test results

Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1

Find Process Name by its Process ID

Using only "native" Windows utilities, try the following, where "516" is the process ID that you want the image name for:

for /f "delims=," %a in ( 'tasklist /fi "PID eq 516" /nh /fo:csv' ) do ( echo %~a )
for /f %a in ( 'tasklist /fi "PID eq 516" ^| findstr "516"' ) do ( echo %a )

Or you could use wmic (the Windows Management Instrumentation Command-line tool) and get the full path to the executable:

wmic process where processId=516 get name
wmic process where processId=516 get ExecutablePath

Or you could download Microsoft PsTools, or specifically download just the pslist utility, and use PsList:

for /f %a in ( 'pslist 516 ^| findstr "516"' ) do ( echo %a )

What's the difference between Sender, From and Return-Path?

A minor update to this: a sender should never set the Return-Path: header. There's no such thing as a Return-Path: header for a message in transit. That header is set by the MTA that makes final delivery, and is generally set to the value of the 5321.From unless the local system needs some kind of quirky routing.

It's a common misunderstanding because users rarely see an email without a Return-Path: header in their mailboxes. This is because they always see delivered messages, but an MTA should never see a Return-Path: header on a message in transit. See http://tools.ietf.org/html/rfc5321#section-4.4

Could not find or load main class org.gradle.wrapper.GradleWrapperMain

In addition to @RaGe's answer may be the situation I faced where i had a global git ignore that was ignoring .jar files and so the gradle wrapper jar was never being committed. Thus I was getting that error on the Jenkins server after an attempted /var/lib/jenkins/my_project/gradlew build. I had to explicitly force an add of the jar and then commit:

git add -f gradle/wrapper/gradle-wrapper.jar

How to build and run Maven projects after importing into Eclipse IDE

Dependencies can be updated by using "Maven --> Update Project.." in Eclipse using m2e plugin, after pom.xml file modification. Maven Project Update based on changes on pom.xml

Using PowerShell credentials without being prompted for a password

Solution

$userName = 'test-domain\test-login'
$password = 'test-password'

$pwdSecureString = ConvertTo-SecureString -Force -AsPlainText $password
$credential = New-Object -TypeName System.Management.Automation.PSCredential `
    -ArgumentList $userName, $pwdSecureString

For Build Machines
In the previous code replace user name and password values by secret ("hidden from logs") environment variables of your build-machine

Test results by

'# Results'
$credential.GetNetworkCredential().Domain
$credential.GetNetworkCredential().UserName
$credential.GetNetworkCredential().Password

and you'll see

# Results
test-domain
test-login
test-password

How to empty the message in a text area with jquery?

A comment to jarijira

Well I have had many issues with .html and .empty() methods for inputs o. If the id represents an input and not another type of html selector like

or use the .val() function to manipulate.

For example: this is the proper way to manipulate input values

<textarea class="form-control" id="someInput"></textarea>

$(document).ready(function () {
     var newVal='test'
     $('#someInput').val('') //clear input value
     $('#someInput').val(newVal) //override w/ the new value
     $('#someInput').val('test2) 
     newVal= $('#someInput').val(newVal) //get input value

}

For improper, but sometimes works For example: this is the proper way to manipulate input values

<textarea class="form-control" id="someInput"></textarea>

$(document).ready(function () {
     var newVal='test'
     $('#someInput').html('') //clear input value
     $('#someInput').empty() //clear html inside of the id
     $('#someInput').html(newVal) //override the html inside of text area w/ string could be '<div>test3</div>
     really overriding with a string manipulates the value, but this is not the best practice as you do not put things besides strings or values inside of an input. 
     newVal= $('#someInput').val(newVal) //get input value

}

An issue that I had was I was using the $getJson method and I was indeed able to use .html calls to manipulate my inputs. However, whenever I had an error or fail on the getJSON I could no longer change my inputs using the .clear and .html calls. I could still return the .val(). After some experimentation and research I discovered that you should only use the .val() function to make changes to input fields.

How to use double or single brackets, parentheses, curly braces

I just wanted to add these from TLDP:

~:$ echo $SHELL
/bin/bash

~:$ echo ${#SHELL}
9

~:$ ARRAY=(one two three)

~:$ echo ${#ARRAY}
3

~:$ echo ${TEST:-test}
test

~:$ echo $TEST


~:$ export TEST=a_string

~:$ echo ${TEST:-test}
a_string

~:$ echo ${TEST2:-$TEST}
a_string

~:$ echo $TEST2


~:$ echo ${TEST2:=$TEST}
a_string

~:$ echo $TEST2
a_string

~:$ export STRING="thisisaverylongname"

~:$ echo ${STRING:4}
isaverylongname

~:$ echo ${STRING:6:5}
avery

~:$ echo ${ARRAY[*]}
one two one three one four

~:$ echo ${ARRAY[*]#one}
two three four

~:$ echo ${ARRAY[*]#t}
one wo one hree one four

~:$ echo ${ARRAY[*]#t*}
one wo one hree one four

~:$ echo ${ARRAY[*]##t*}
one one one four

~:$ echo $STRING
thisisaverylongname

~:$ echo ${STRING%name}
thisisaverylong

~:$ echo ${STRING/name/string}
thisisaverylongstring

if variable contains

You can use a regex:

if (/ST1/i.test(code))

Reloading/refreshing Kendo Grid

What you have to do is just add an event .Events(events => events.Sync("KendoGridRefresh")) in your kendoGrid binding code.No need to write the refresh code in ajax result.

@(Html.Kendo().Grid<Models.DocumentDetail>().Name("document")
    .DataSource(dataSource => dataSource
    .Ajax()
    .PageSize(20)
    .Model(model => model.Id(m => m.Id))        
    .Events(events => events.Sync("KendoGridRefresh"))    
    )
      .Columns(columns =>
      {
          columns.Bound(c => c.Id).Hidden();              
          columns.Bound(c => c.UserName).Title(@Resources.Resource.lblAddedBy);                           
      }).Events(e => e.DataBound("onRowBound"))
          .ToolBar(toolbar => toolbar.Create().Text(@Resources.Resource.lblNewDocument))
          .Sortable()          
          .HtmlAttributes(new { style = "height:260px" })          
  )

And you can add the following Global function in any of your .js file. so, you can call it for all the kendo grids in your project to refresh the kendoGrid.

function KendoGridRefresh() {
    var grid = $('#document').data('kendoGrid');
    grid.dataSource.read();
}

How do you check if a string is not equal to an object or other string value in java?

you'll want to use && to see that it is not equal to "AM" AND not equal to "PM"

if(!TimeOfDayStringQ.equals("AM") && !TimeOfDayStringQ.equals("PM")) {
    System.out.println("Sorry, incorrect input.");
    System.exit(1);
}

to be clear you can also do

if(!(TimeOfDayStringQ.equals("AM") || TimeOfDayStringQ.equals("PM"))){
    System.out.println("Sorry, incorrect input.");
    System.exit(1);
}

to have the not (one or the other) phrase in the code (remember the (silent) brackets)

What is the T-SQL To grant read and write access to tables in a database in SQL Server?

It will be better to Create a New role, then grant execute, select ... etc permissions to this role and finally assign users to this role.

Create role

CREATE ROLE [db_SomeExecutor] 
GO

Grant Permission to this role

GRANT EXECUTE TO db_SomeExecutor
GRANT INSERT  TO db_SomeExecutor

to Add users database>security> > roles > databaseroles>Properties > Add ( bottom right ) you can search AD users and add then

OR

   EXEC sp_addrolemember 'db_SomeExecutor', 'domainName\UserName'

Please refer this post

jQuery : select all element with custom attribute

As described by the link I've given in comment, this

$('p[MyTag]').each(function(index) {
  document.write(index + ': ' + $(this).text() + "<br>");});

works (playable example).

Select dropdown with fixed width cutting off content in IE

A pure css solution : http://bavotasan.com/2011/style-select-box-using-only-css/

_x000D_
_x000D_
.styled-select select {_x000D_
   background: transparent;_x000D_
   width: 268px;_x000D_
   padding: 5px;_x000D_
   font-size: 16px;_x000D_
   line-height: 1;_x000D_
   border: 0;_x000D_
   border-radius: 0;_x000D_
   height: 34px;_x000D_
   -webkit-appearance: none;_x000D_
   }_x000D_
_x000D_
.styled-select {_x000D_
   width: 240px;_x000D_
   height: 34px;_x000D_
   overflow: hidden;_x000D_
   background: url(http://cdn.bavotasan.com/wp-content/uploads/2011/05/down_arrow_select.jpg) no-repeat right #ddd;_x000D_
   border: 1px solid #ccc;_x000D_
   }
_x000D_
<div class="styled-select">_x000D_
   <select>_x000D_
      <option>Here is the first option</option>_x000D_
      <option>The second option</option>_x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Read file from aws s3 bucket using node fs

If you are looking to avoid the callbacks you can take advantage of the sdk .promise() function like this:

const s3 = new AWS.S3();
const params = {Bucket: 'myBucket', Key: 'myKey.csv'}
const response = await s3.getObject(params).promise() // await the promise
const fileContent = getObjectResult.Body.toString('utf-8'); // can also do 'base64' here if desired

I'm sure the other ways mentioned here have their advantages but this works great for me. Sourced from this thread (see the last response from AWS): https://forums.aws.amazon.com/thread.jspa?threadID=116788

Chrome: console.log, console.debug are not working

Selecting verbose fixed it for meVerbose

What in the world are Spring beans?

Spring beans are just instance objects that are managed by the Spring container, namely, they are created and wired by the framework and put into a "bag of objects" (the container) from where you can get them later.

The "wiring" part there is what dependency injection is all about, what it means is that you can just say "I will need this thing" and the framework will follow some rules to get you the proper instance.

For someone who isn't used to Spring, I think Wikipedia Spring's article has a nice description:

Central to the Spring Framework is its inversion of control container, which provides a consistent means of configuring and managing Java objects using reflection. The container is responsible for managing object lifecycles of specific objects: creating these objects, calling their initialization methods, and configuring these objects by wiring them together.

Objects created by the container are also called managed objects or beans. The container can be configured by loading XML files or detecting specific Java annotations on configuration classes. These data sources contain the bean definitions which provide the information required to create the beans.

Objects can be obtained by means of either dependency lookup or dependency injection. Dependency lookup is a pattern where a caller asks the container object for an object with a specific name or of a specific type. Dependency injection is a pattern where the container passes objects by name to other objects, via either constructors, properties, or factory methods.

Center Oversized Image in Div

Late to the game, but I found this method is extremely intuitive. https://codepen.io/adamchenwei/pen/BRNxJr

CSS

.imageContainer {
  border: 1px black solid;

  width: 450px;
  height: 200px;
  overflow: hidden;
}
.imageHolder {
  border: 1px red dotted;

  height: 100%;
  display:flex;
  align-items: center;
}
.imageItself {
  height: auto;
  width: 100%;
  align-self: center;

}

HTML

<div class="imageContainer">
  <div class="imageHolder">
    <img class="imageItself" src="http://www.fiorieconfetti.com/sites/default/files/styles/product_thumbnail__300x360_/public/fiore_viola%20-%202.jpg" />
  </div>
</div>

Git: Installing Git in PATH with GitHub client for Windows

If you are using vscode's terminal then it might not work even if you do the environment variable thing, test by typing git

Restart vscode, it should work.

Assign value from successful promise resolve to external variable

This could be updated to ES6 with arrow functions and look like:

getFeed().then(data => vm.feed = data);

If you wish to use the async function, you could also do like that:

async function myFunction(){
    vm.feed = await getFeed();
    // do whatever you need with vm.feed below
 }

"Integer number too large" error message for 600851475143

600851475143 cannot be represented as a 32-bit integer (type int). It can be represented as a 64-bit integer (type long). long literals in Java end with an "L": 600851475143L

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

You should install python 3.6 version because python 3.7 version doesn't support pyaudio 1 step : Then download the .whl file
according to your python version and the configuration of your machine in your python folder which is newly installed. For me it is python 3.6 and 64 bit machine. Download the file from here (https://www.lfd.uci.edu/~gohlke/pythonlibs/) 2 step : run your cmd and type " pip install your downloaded file name here "

Oracle: If Table Exists

The best and most efficient way is to catch the "table not found" exception: this avoids the overhead of checking if the table exists twice; and doesn't suffer from the problem that if the DROP fails for some other reason (that might be important) the exception is still raised to the caller:

BEGIN
   EXECUTE IMMEDIATE 'DROP TABLE ' || table_name;
EXCEPTION
   WHEN OTHERS THEN
      IF SQLCODE != -942 THEN
         RAISE;
      END IF;
END;

ADDENDUM For reference, here are the equivalent blocks for other object types:

Sequence

BEGIN
  EXECUTE IMMEDIATE 'DROP SEQUENCE ' || sequence_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -2289 THEN
      RAISE;
    END IF;
END;

View

BEGIN
  EXECUTE IMMEDIATE 'DROP VIEW ' || view_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -942 THEN
      RAISE;
    END IF;
END;

Trigger

BEGIN
  EXECUTE IMMEDIATE 'DROP TRIGGER ' || trigger_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -4080 THEN
      RAISE;
    END IF;
END;

Index

BEGIN
  EXECUTE IMMEDIATE 'DROP INDEX ' || index_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -1418 THEN
      RAISE;
    END IF;
END;

Column

BEGIN
  EXECUTE IMMEDIATE 'ALTER TABLE ' || table_name
                || ' DROP COLUMN ' || column_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -904 AND SQLCODE != -942 THEN
      RAISE;
    END IF;
END;

Database Link

BEGIN
  EXECUTE IMMEDIATE 'DROP DATABASE LINK ' || dblink_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -2024 THEN
      RAISE;
    END IF;
END;

Materialized View

BEGIN
  EXECUTE IMMEDIATE 'DROP MATERIALIZED VIEW ' || mview_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -12003 THEN
      RAISE;
    END IF;
END;

Type

BEGIN
  EXECUTE IMMEDIATE 'DROP TYPE ' || type_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -4043 THEN
      RAISE;
    END IF;
END;

Constraint

BEGIN
  EXECUTE IMMEDIATE 'ALTER TABLE ' || table_name
            || ' DROP CONSTRAINT ' || constraint_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -2443 AND SQLCODE != -942 THEN
      RAISE;
    END IF;
END;

Scheduler Job

BEGIN
  DBMS_SCHEDULER.drop_job(job_name);
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -27475 THEN
      RAISE;
    END IF;
END;

User / Schema

BEGIN
  EXECUTE IMMEDIATE 'DROP USER ' || user_name;
  /* you may or may not want to add CASCADE */
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -1918 THEN
      RAISE;
    END IF;
END;

Package

BEGIN
  EXECUTE IMMEDIATE 'DROP PACKAGE ' || package_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -4043 THEN
      RAISE;
    END IF;
END;

Procedure

BEGIN
  EXECUTE IMMEDIATE 'DROP PROCEDURE ' || procedure_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -4043 THEN
      RAISE;
    END IF;
END;

Function

BEGIN
  EXECUTE IMMEDIATE 'DROP FUNCTION ' || function_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -4043 THEN
      RAISE;
    END IF;
END;

Tablespace

BEGIN
  EXECUTE IMMEDIATE 'DROP TABLESPACE' || tablespace_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -959 THEN
      RAISE;
    END IF;
END;

Synonym

BEGIN
  EXECUTE IMMEDIATE 'DROP SYNONYM ' || synonym_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -1434 THEN
      RAISE;
    END IF;
END;

How can I count the number of matches for a regex?

matcher.find() does not find all matches, only the next match.

Solution for Java 9+

long matches = matcher.results().count();

Solution for Java 8 and older

You'll have to do the following. (Starting from Java 9, there is a nicer solution)

int count = 0;
while (matcher.find())
    count++;

Btw, matcher.groupCount() is something completely different.

Complete example:

import java.util.regex.*;

class Test {
    public static void main(String[] args) {
        String hello = "HelloxxxHelloxxxHello";
        Pattern pattern = Pattern.compile("Hello");
        Matcher matcher = pattern.matcher(hello);

        int count = 0;
        while (matcher.find())
            count++;

        System.out.println(count);    // prints 3
    }
}

Handling overlapping matches

When counting matches of aa in aaaa the above snippet will give you 2.

aaaa
aa
  aa

To get 3 matches, i.e. this behavior:

aaaa
aa
 aa
  aa

You have to search for a match at index <start of last match> + 1 as follows:

String hello = "aaaa";
Pattern pattern = Pattern.compile("aa");
Matcher matcher = pattern.matcher(hello);

int count = 0;
int i = 0;
while (matcher.find(i)) {
    count++;
    i = matcher.start() + 1;
}

System.out.println(count);    // prints 3

Add colorbar to existing axis

The colorbar has to have its own axes. However, you can create an axes that overlaps with the previous one. Then use the cax kwarg to tell fig.colorbar to use the new axes.

For example:

import numpy as np
import matplotlib.pyplot as plt

data = np.arange(100, 0, -1).reshape(10, 10)

fig, ax = plt.subplots()
cax = fig.add_axes([0.27, 0.8, 0.5, 0.05])

im = ax.imshow(data, cmap='gist_earth')
fig.colorbar(im, cax=cax, orientation='horizontal')
plt.show()

enter image description here

Property 'value' does not exist on type 'EventTarget'

fromEvent<KeyboardEvent>(document.querySelector('#searcha') as HTMLInputElement , 'keyup')
    .pipe(
      debounceTime(500),
      distinctUntilChanged(),
      map(e  => {
            return e.target['value']; // <-- target does not exist on {}
        })
    ).subscribe(k => console.log(k));

Maybe something like the above could help. Change it based on the real code. The issue is ........ target['value']

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

What is the difference between Java RMI and RPC?

The main difference between RPC and RMI is that RMI involves objects. Instead of calling procedures remotely by use of a proxy function, we instead use a proxy object.

There is greater transparency with RMI, namely due the exploitation of objects, references, inheritance, polymorphism, and exceptions as the technology is integrated into the language.

RMI is also more advanced than RPC, allowing for dynamic invocation, where interfaces can change at runtime, and object adaption, which provides an additional layer of abstraction.

Content Security Policy: The page's settings blocked the loading of a resource

I managed to allow all my requisite sites with this header:

header("Content-Security-Policy: default-src *; style-src 'self' 'unsafe-inline'; font-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval' stackexchange.com");                    

Razor MVC Populating Javascript array with Model Array

This is possible, you just need to loop through the razor collection

<script type="text/javascript">

    var myArray = [];

    @foreach (var d in Model.data)
    {
        @:myArray.push("@d");
    }

    alert(myArray);

</script>

Hope this helps

Inconsistent accessibility: property type is less accessible

Your Delivery class is internal (the default visibility for classes), however the property (and presumably the containing class) are public, so the property is more accessible than the Delivery class. You need to either make Delivery public, or restrict the visibility of the thelivery property.

When should I use the Visitor Design Pattern?

In my opinion, the amount of work to add a new operation is more or less the same using Visitor Pattern or direct modification of each element structure. Also, if I were to add new element class, say Cow, the Operation interface will be affected and this propagates to all existing class of elements, therefore requiring recompilation of all element classes. So what is the point?

Escape quote in web.config connection string

Odeds answer is almost complete. Just one thing to add.

  1. Escape xml special chars like Emanuele Greco said.
  2. Put the password in single quotes like Oded said
  3. (this one is new) Escape single ticks with another single tick (ref)

having this password="'; this sould be a valid connection string:

connectionString='Server=dbsrv;User ID=myDbUser;Password='&quot;&amp;&amp;;'

How to use basic authorization in PHP curl

Can you try this,

 $ch = curl_init($url);
 ...
 curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);  
 ...

REF: http://php.net/manual/en/function.curl-setopt.php

How to fix 'Microsoft Excel cannot open or save any more documents'

Go to this key on Registry Editor (Run | Regedit) HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders

change key Cache to something like C:\Windows\Temp

My similar problem was solved like this.

Regards,

Ripley

Proper way to concatenate variable strings

Good question. But I think there is no good answer which fits your criteria. The best I can think of is to use an extra vars file.

A task like this:

- include_vars: concat.yml

And in concat.yml you have your definition:

newvar: "{{ var1 }}-{{ var2 }}-{{ var3 }}"

How do I open a new window using jQuery?

This works:

myWindow = window.open('http://www.yahoo.com','myWindow', "width=200, height=200");

How do you format code on save in VS Code

As of September 2016 (VSCode 1.6), this is now officially supported.

Add the following to your settings.json file:

"editor.formatOnSave": true

How do I get SUM function in MySQL to return '0' if no values are found?

Can't get exactly what you are asking but if you are using an aggregate SUM function which implies that you are grouping the table.

The query goes for MYSQL like this

Select IFNULL(SUM(COLUMN1),0) as total from mytable group by condition

How to output in CLI during execution of PHP Unit tests?

Here are few methods useful for printing debug messages in PHPUnit 4.x:

  • syslog(LOG_DEBUG, "Debug: Message 1!");

    More practical example:

    syslog(LOG_DEBUG, sprintf("%s: Value: %s", __METHOD__, var_export($_GET, TRUE)));
    

    Calling syslog() will generate a system log message (see: man syslog.conf).

    Note: Possible levels: LOG_DEBUG, LOG_INFO, LOG_NOTICE, LOG_WARNING, LOG_ERR, etc.

    On macOS, to stream the syslog messages in realtime, run:

    log stream --level debug --predicate 'processImagePath contains "php"'
    
  • fwrite(STDERR, "LOG: Message 2!\n");

    Note: The STDERR constant is not available if reading the PHP script from stdin. Here is the workaround.

    Note: Instead of STDERR, you can also specify a filename.

  • file_put_contents('php://stderr', "LOG: Message 3!\n", FILE_APPEND);

    Note: Use this method, if you don't have STDERR constant defined.

  • register_shutdown_function('file_put_contents', 'php://stderr', "LOG: Message 4!\n", FILE_APPEND);

    Note: Use this method, if you'd like to print something at the very end without affecting the tests.

To dump the variable, use var_export(), e.g. "Value: " . var_export($some_var, TRUE) . "\n".

To print above messages only during verbose or debug mode, see: Is there a way to tell if --debug or --verbose was passed to PHPUnit in a test?


Although if testing the output is part of the test it-self, check out: Testing Output docs page.

Easiest way to make lua script wait/pause/sleep/block for a few seconds?

[I was going to post this as a comment on John Cromartie's post, but didn't realize you couldn't use formatting in a comment.]

I agree. Dropping it to a shell with os.execute() will definitely work but in general making shell calls is expensive. Wrapping some C code will be much quicker at run-time. In C/C++ on a Linux system, you could use:

static int lua_sleep(lua_State *L)
{
    int m = static_cast<int> (luaL_checknumber(L,1));
    usleep(m * 1000); 
    // usleep takes microseconds. This converts the parameter to milliseconds. 
    // Change this as necessary. 
    // Alternatively, use 'sleep()' to treat the parameter as whole seconds. 
    return 0;
}

Then, in main, do:

lua_pushcfunction(L, lua_sleep);
lua_setglobal(L, "sleep");

where "L" is your lua_State. Then, in your Lua script called from C/C++, you can use your function by calling:

sleep(1000) -- Sleeps for one second

How do I handle Database Connections with Dapper in .NET?

I do it like this:

internal class Repository : IRepository {

    private readonly Func<IDbConnection> _connectionFactory;

    public Repository(Func<IDbConnection> connectionFactory) 
    {
        _connectionFactory = connectionFactory;
    }

    public IWidget Get(string key) {
        using(var conn = _connectionFactory()) 
        {
            return conn.Query<Widget>(
               "select * from widgets with(nolock) where widgetkey=@WidgetKey", new { WidgetKey=key });
        }
    }
}

Then, wherever I wire-up my dependencies (ex: Global.asax.cs or Startup.cs), I do something like:

var connectionFactory = new Func<IDbConnection>(() => {
    var conn = new SqlConnection(
        ConfigurationManager.ConnectionStrings["connectionString-name"];
    conn.Open();
    return conn;
});

how to declare global variable in SQL Server..?

You can get a similar result by creating scalar-valued functions that return the variable values. Of course, function calls can be expensive if you use them in queries that return a large number of results, but if you're limiting the result-set you should be fine. Here I'm using a database created just to hold these semi-static values, but you can create them on a per-database basis, too. As you can see, there are no input variables, just a well-named function that returns a static value: if you change that value in the function, it will instantly change anywhere it's used (the next time it's called).

USE [globalDatabase]
GO

CREATE FUNCTION dbo.global_GetStandardFonts ()
RETURNS NVARCHAR(255)
AS
BEGIN
    RETURN 'font-family:"Calibri Light","sans-serif";'
END
GO

--  Usage: 
SELECT '<html><head><style>body{' + globalDatabase.dbo.global_GetStandardFonts() + '}</style></head><body>...'

--  Result: <html><head><style>body{font-family:"Calibri Light","sans-serif";}</style></head><body>...

Concatenate chars to form String in java

Use the Character.toString(char) method.

Get value of div content using jquery

You can simply use the method text() of jQuery to get all the content of the text contained in the element. The text() method also returns the textual content of the child elements.

HTML Code:

<div id="box">
  <p>Lorem ipsum elit sit ut, consectetur adipiscing dolor.</p> 
</div>

JQuery Code:

  $(document).ready(function(){
    $("button").click(function(){
      var divContent = $('#box').text();
      alert(divContent);
    });
  });

You can see an example here: How to get the text content of an element with jQuery

What is the difference between 'git pull' and 'git fetch'?

Git allows chronologically older commits to be applied after newer commits. Because of this, the act of transferring commits between repositories is split into two steps:

  1. Copying new commits from remote branch to copy of this remote branch inside local repo.

    (repo to repo operation) master@remote >> remote/origin/master@local

  2. Integrating new commits to local branch

    (inside-repo operation) remote/origin/master@local >> master@local

There are two ways of doing step 2. You can:

  1. Fork local branch after last common ancestor and add new commits parallel to commits which are unique to local repository, finalized by merging commit, closing the fork.
  2. Insert new commits after last common ancestor and reapply commits unique to local repository.

In git terminology, step 1 is git fetch, step 2 is git merge or git rebase

git pull is git fetch and git merge

Remove an array element and shift the remaining ones

Programming Hub randomly provided a code snippet which in fact does reduce the length of an array

for (i = position_to_remove; i < length_of_array; ++i) {
        inputarray[i] = inputarray[i + 1];
}

Not sure if it's behaviour that was added only later. It does the trick though.

HTML5 video - show/hide controls programmatically

CARL LANGE also showed how to get hidden, autoplaying audio in html5 on a iOS device. Works for me.

In HTML,

<div id="hideme">
    <audio id="audioTag" controls>
        <source src="/path/to/audio.mp3">
    </audio>
</div>

with JS

<script type="text/javascript">
window.onload = function() {
    var audioEl = document.getElementById("audioTag");
    audioEl.load();
    audioEl.play();
};
</script>

In CSS,

#hideme {display: none;}

Delete last N characters from field in a SQL Server database

You could do it using SUBSTRING() function:

UPDATE table SET column = SUBSTRING(column, 0, LEN(column) + 1 - N)

Removes the last N characters from every row in the column

how to get domain name from URL

#!/usr/bin/perl -w
use strict;

my $url = $ARGV[0];
if($url =~ /([^:]*:\/\/)?([^\/]*\.)*([^\/\.]+)\.[^\/]+/g) {
  print $3;
}

Git on Windows: How do you set up a mergetool?

To setup p4merge, installed using chocolatey on windows for both merge and diff, take a look here: https://gist.github.com/CamW/88e95ea8d9f0786d746a

Regex for parsing directory and filename

What about this?

[/]{0,1}([^/]+[/])*([^/]*)

Deterministic :

((/)|())([^/]+/)*([^/]*)

Strict :

^[/]{0,1}([^/]+[/])*([^/]*)$
^((/)|())([^/]+/)*([^/]*)$

Pass parameter from a batch file to a PowerShell script

The answer from @Emiliano is excellent. You can also pass named parameters like so:

powershell.exe -Command 'G:\Karan\PowerShell_Scripts\START_DEV.ps1' -NamedParam1 "SomeDataA" -NamedParam2 "SomeData2"

Note the parameters are outside the command call, and you'll use:

[parameter(Mandatory=$false)]
  [string]$NamedParam1,
[parameter(Mandatory=$false)]
  [string]$NamedParam2

Python element-wise tuple operations like sum

import operator
tuple(map(operator.add, a, b))

How to randomly select an item from a list?

If you also need the index, use random.randrange

from random import randrange
random_index = randrange(len(foo))
print(foo[random_index])

convert UIImage to NSData

Solution in Swift 4

extension UIImage {
    var data : Data? {
      return cgImage?.dataProvider?.data as Data?
    }
}

How to remove underline from a link in HTML?

This will remove all underlines from all links:

a {text-decoration: none; }

If you have specific links that you want to apply this to, give them a class name, like nounderline and do this:

a.nounderline {text-decoration: none; }

That will apply only to those links and leave all others unaffected.

This code belongs in the <head> of your document or in a stylesheet:

<head>
    <style type="text/css">
        a.nounderline {text-decoration: none; }
    </style>
</head>

And in the body:

<a href="#" class="nounderline">Link</a>

How to check whether a given string is valid JSON in Java

Using Playframework 2.6, the Json library found in the java api can also be used to simply parse the string. The string can either be a json element of json array. Since the returned value is not of importance here we just catch the parse error to determine that the string is a correct json string or not.

    import play.libs.Json;

    public static Boolean isValidJson(String value) {
        try{
            Json.parse(value);
            return true;
        } catch(final Exception e){
            return false;
        }
    }

How to implement a lock in JavaScript

Some addition to JoshRiver's answer according to my case;

var functionCallbacks = [];
    var functionLock = false;
    var getData = function (url, callback) {
                   if (functionLock) {
                        functionCallbacks.push(callback);
                   } else {
                       functionLock = true;
                       functionCallbacks.push(callback);
                        $.getJSON(url, function (data) {
                            while (functionCallbacks.length) {
                                var thisCallback = functionCallbacks.pop();
                                thisCallback(data);
                            }
                            functionLock = false;
                        });
                    }
                };

// Usage
getData("api/orders",function(data){
    barChart(data);
});
getData("api/orders",function(data){
  lineChart(data);
});

There will be just one api call and these two function will consume same result.

Capture screenshot of active window?

If you want to use managed code: This will capture any window via the ProcessId.

I used the following to make the window active.

Microsoft.VisualBasic.Interaction.AppActivate(ProcessId);
Threading.Thread.Sleep(20);

I used the print screen to capture a window.

SendKeys.SendWait("%{PRTSC}");
Threading.Thread.Sleep(40);
IDataObject objData = Clipboard.GetDataObject();

Set specific precision of a BigDecimal

 BigDecimal decPrec = (BigDecimal)yo.get("Avg");
 decPrec = decPrec.setScale(5, RoundingMode.CEILING);
 String value= String.valueOf(decPrec);

This way you can set specific precision of a BigDecimal.

The value of decPrec was 1.5726903423607562595809913132345426 which is rounded off to 1.57267.

How do I get the path of the assembly the code is in?

As far as I can tell, most of the other answers have a few problems.

The correct way to do this for a disk-based (as opposed to web-based), non-GACed assembly is to use the currently executing assembly's CodeBase property.

This returns a URL (file://). Instead of messing around with string manipulation or UnescapeDataString, this can be converted with minimal fuss by leveraging the LocalPath property of Uri.

var codeBaseUrl = Assembly.GetExecutingAssembly().CodeBase;
var filePathToCodeBase = new Uri(codeBaseUrl).LocalPath;
var directoryPath = Path.GetDirectoryName(filePathToCodeBase);

Use CASE statement to check if column exists in table - SQL Server

select case
         when exists (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Tags' AND COLUMN_NAME = 'ModifiedByUser')
         then 0
         else 1
       end

What is the best/simplest way to read in an XML file in Java application?

This is what I use. http://marketmovers.blogspot.com/2014/02/the-easy-way-to-read-xml-in-java.html It sits on top of the standard JDK tools, so if it's missing some feature you can always use the JDK version.

This really makes things easier for me. It's especially nice when I'm reading a config file that was saved by and older version of the software, or was manually edited by a user. It's very robust and won't throw an exception if some data is not exactly in the format you expect.

How to calculate Average Waiting Time and average Turn-around time in SJF Scheduling?

SJF are two type - i) non preemptive SJF ii)pre-emptive SJF

I have re-arranged the processes according to Arrival time. here is the non preemptive SJF

A.T= Arrival Time

B.T= Burst Time

C.T= Completion Time

T.T = Turn around Time = C.T - A.T

W.T = Waiting Time = T.T - B.T

enter image description here

Here is the preemptive SJF Note: each process will preempt at time a new process arrives.Then it will compare the burst times and will allocate the process which have shortest burst time. But if two process have same burst time then the process which came first that will be allocated first just like FCFS.

enter image description here

Load JSON text into class object in c#

copy your Json and paste at textbox on http://json2csharp.com/ and click on Generate button,

A cs class will be generated use that cs file as below:

var generatedcsResponce = JsonConvert.DeserializeObject(yourJson);

where RootObject is the name of the generated cs file;

Difference between Arrays.asList(array) and new ArrayList<Integer>(Arrays.asList(array))

Arrays.asList()

this method returns its own implementation of List.It takes an array as an argument and builds methods and attributes on top of it, since it is not copying any data from an array but using the original array this causes alteration in original array when you modify list returned by the Arrays.asList() method.

on the other hand.
ArrayList(Arrays.asList()); is a constructor of ArrayList class which takes a list as argument and returns an ArrayList that is independent of list ie. Arrays.asList() in this case passed as an argument. that is why you see these results;

How to properly validate input values with React.JS?

You can use npm install --save redux-form

Im writing a simple email and submit button form, which validates email and submits form. with redux-form, form by default runs event.preventDefault() on html onSubmit action.

import React, {Component} from 'react';
import {reduxForm} from 'redux-form';

class LoginForm extends Component {
  onSubmit(props) {
    //do your submit stuff
  }


  render() {
    const {fields: {email}, handleSubmit} = this.props;

    return (
      <form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
        <input type="text" placeholder="Email"
               className={`form-control ${email.touched && email.invalid ? 'has-error' : '' }`}
          {...email}
        />
          <span className="text-help">
            {email.touched ? email.error : ''}
          </span>
        <input type="submit"/>
      </form>
    );
  }
}

function validation(values) {
  const errors = {};
  const emailPattern = /(.+)@(.+){2,}\.(.+){2,}/;
  if (!emailPattern.test(values.email)) {
    errors.email = 'Enter a valid email';
  }

  return errors;
}

LoginForm = reduxForm({
  form: 'LoginForm',
  fields: ['email'],
  validate: validation
}, null, null)(LoginForm);

export default LoginForm;

Get full path of a file with FileUpload Control

Path.GetFullPath(fileUpload.PostedFile.FileName);

Sorry this 'll get your program file directory + your file name.

How do I create a list of random numbers without duplicates?

If you wish to ensure that the numbers being added are unique, you could use a Set object

if using 2.7 or greater, or import the sets module if not.

As others have mentioned, this means the numbers are not truly random.

"No X11 DISPLAY variable" - what does it mean?

you must enable X11 forwarding in you PuTTy

to do so open PuTTy, go to Connection => SSH => Tunnels and check mark the Enable X11 forwarding

Also sudo to server and export the below variable here IP is your local machine's IP

export DISPLAY=10.75.75.75:0.0

enter image description here

javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

Issue resolved.!!! Below are the solutions.

For Java 6: Add below jars into {JAVA_HOME}/jre/lib/ext. 1. bcprov-ext-jdk15on-154.jar 2. bcprov-jdk15on-154.jar

Add property into {JAVA_HOME}/jre/lib/security/java.security security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider

Java 7:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

Java 8:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

Issue is that it is failed to decrypt 256 bits of encryption.

MySQL - Replace Character in Columns

Replace below characters

~ ! @ # $ % ^ & * ( ) _ +
` - = 
{ } |
[ ] \
: " 
; '

< > ?
, . 

with this SQL

SELECT note as note_original, 

    REPLACE(
        REPLACE(
            REPLACE(
                REPLACE(
                    REPLACE(
                        REPLACE(
                            REPLACE(
                                REPLACE(
                                    REPLACE(
                                        REPLACE(
                                            REPLACE(
                                                REPLACE(
                                                    REPLACE(
                                                        REPLACE(
                                                            REPLACE(
                                                                REPLACE(
                                                                    REPLACE(
                                                                        REPLACE(
                                                                            REPLACE(
                                                                                REPLACE(
                                                                                    REPLACE(
                                                                                        REPLACE(
                                                                                            REPLACE(
                                                                                                REPLACE(
                                                                                                    REPLACE(
                                                                                                        REPLACE(
                                                                    REPLACE(
                                                                        REPLACE(
                                                                            REPLACE(
                                                                                REPLACE(
                                                                                    REPLACE(
                                                                                        REPLACE(
                                                                                            REPLACE(note, '\"', ''),
                                                                                        '.', ''),
                                                                                    '?', ''),
                                                                                '`', ''),
                                                                            '<', ''),
                                                                        '=', ''),
                                                                    '{', ''),
                                                                                                        '}', ''),
                                                                                                    '[', ''),
                                                                                                ']', ''),
                                                                                            '|', ''),
                                                                                        '\'', ''),
                                                                                    ':', ''),
                                                                                ';', ''),
                                                                            '~', ''),
                                                                        '!', ''),
                                                                    '@', ''),
                                                                '#', ''),
                                                            '$', ''),
                                                        '%', ''),
                                                    '^', ''),
                                                '&', ''),
                                            '*', ''),
                                        '_', ''),
                                    '+', ''),
                                ',', ''),
                            '/', ''),
                        '(', ''),
                    ')', ''),
                '-', ''),
            '>', ''),
        ' ', '-'),
    '--', '-') as note_changed FROM invheader

How to get table list in database, using MS SQL 2008?

This query will get you all the tables in the database

USE [DatabaseName];

SELECT * FROM information_schema.tables;

What is the python keyword "with" used for?

Explanation from the Preshing on Programming blog:

It’s handy when you have two related operations which you’d like to execute as a pair, with a block of code in between. The classic example is opening a file, manipulating the file, then closing it:

 with open('output.txt', 'w') as f:
     f.write('Hi there!')

The above with statement will automatically close the file after the nested block of code. (Continue reading to see exactly how the close occurs.) The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler. If the nested block were to contain a return statement, or a continue or break statement, the with statement would automatically close the file in those cases, too.

Why isn't ProjectName-Prefix.pch created automatically in Xcode 6?

If you decide to add a .pch file manually and you want to use Objective-C just like before xCode 6 you will also have to import UIKit and Foundation frameworks in the .pch file. Otherwise you will have to import these frameworks manually in each header file. You can add the following code anyway as it tests for the language used:

#ifdef __OBJC__
    #import <UIKit/UIKit.h>
    #import <Foundation/Foundation.h>
#endif

JS jQuery - check if value is in array

The Array.prototype property represents the prototype for the Array constructor and allows you to add new properties and methods to all Array objects. we can create a prototype for this purpose

Array.prototype.has_element = function(element) {
    return $.inArray( element, this) !== -1;
};

And then use it like this

var numbers= [1, 2, 3, 4];
numbers.has_element(3) => true
numbers.has_element(10) => false

See the Demo below

_x000D_
_x000D_
Array.prototype.has_element = function(element) {_x000D_
  return $.inArray(element, this) !== -1;_x000D_
};_x000D_
_x000D_
_x000D_
_x000D_
var numbers = [1, 2, 3, 4];_x000D_
console.log(numbers.has_element(3));_x000D_
console.log(numbers.has_element(10));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Cannot instantiate the type List<Product>

List is an interface. Interfaces cannot be instantiated. Only concrete types can be instantiated. You probably want to use an ArrayList, which is an implementation of the List interface.

List<Product> products = new ArrayList<Product>();

Make a div fill up the remaining width

Use the CSS Flexbox flex-grow property to achieve this.

_x000D_
_x000D_
.main {
  display: flex;
}
.col-1, .col-3 {
  width: 100px;
}
.col-2 {
  flex-grow: 1;
}
_x000D_
<div class="main">
  <div class="col-1" style="background: #fc9;">Left column</div>
  <div class="col-2" style="background: #eee;">Middle column</div>
  <div class="col-3" style="background: #fc9;">Right column</div>
</div>
_x000D_
_x000D_
_x000D_

Making a cURL call in C#

Or in restSharp:

var client = new RestClient("https://example.com/?urlparam=true");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("header1", "headerval");
request.AddParameter("application/x-www-form-urlencoded", "bodykey=bodyval", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

Moving from JDK 1.7 to JDK 1.8 on Ubuntu

Most of the answers for this question can not helped me in 2020.

This notification from download site of Oracle may be the reason:

Important Oracle JDK License Update

The Oracle JDK License has changed for releases starting April 16, 2019.

I try to google a little bit and those tutorials below helped me a lot.

  1. Remove completely the previous version of JVM installed on your PC.

    sudo update-alternatives --remove-all java
    sudo update-alternatives --remove-all javac
    sudo update-alternatives --remove-all javaws
    
    # /usr/lib/jvm/jdk1.7.0 is the path you installed the previous version of JVM on your PC
    sudo rm -rf /usr/lib/jvm/jdk1.7.0 
    

    Check to see whether java is uninstalled or not

    java -version
    
  2. Install Java 8 JDK.

    • Download Java 8 from Oracle's website. The version being used is 1.8.0_251. Pay attention to this value, you may need it to edit commands in this answer when Java 8 is upgraded to another version.
    • Extract the compressed file to the place where you want to install.

    cd /usr/lib/jvm
    sudo tar xzf ~/Downloads/jdk-8u251-linux-x64.tar.gz
    
    • Edit environment file

    sudo gedit /etc/environment
    
    • Edit the PATH's value by appending the string below to the current value

    :/usr/lib/jvm/jdk1.8.0_251/bin:/usr/lib/jvm/jdk1.8.0_251/jre/bin
    
    • Append those strings to the environment file

    J2SDKDIR="/usr/lib/jvm/jdk1.8.0_251"
    J2REDIR="/usr/lib/jvm/jdk1.8.0_251/jre"
    JAVA_HOME="/usr/lib/jvm/jdk1.8.0_251"
    
    • Complete the installation by running commands below

    sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.8.0_251/bin/java" 0
    sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.8.0_251/bin/javac" 0
    sudo update-alternatives --set java /usr/lib/jvm/jdk1.8.0_251/bin/java
    sudo update-alternatives --set javac /usr/lib/jvm/jdk1.8.0_251/bin/javac
    
    update-alternatives --list java
    update-alternatives --list javac
    

What is JNDI? What is its basic use? When is it used?

What is JNDI ?

The Java Naming and Directory InterfaceTM (JNDI) is an application programming interface (API) that provides naming and directory functionality to applications written using the JavaTM programming language. It is defined to be independent of any specific directory service implementation. Thus a variety of directories(new, emerging, and already deployed) can be accessed in a common way.

What is its basic use?

Most of it is covered in the above answer but I would like to provide architecture here so that above will make more sense.

enter image description here

To use the JNDI, you must have the JNDI classes and one or more service providers. The Java 2 SDK, v1.3 includes three service providers for the following naming/directory services:

  1. Lightweight Directory Access Protocol (LDAP)
  2. Common Object Request Broker Architecture (CORBA) Common Object Services (COS) name service
  3. Java Remote Method Invocation (RMI) Registry

So basically you create objects and register them on the directory services which you can later do lookup and execute operation on.

How can I disable all views inside the layout?

this one is recursive for ViewGroups

private void disableEnableControls(boolean enable, ViewGroup vg){
    for (int i = 0; i < vg.getChildCount(); i++){
       View child = vg.getChildAt(i);
       child.setEnabled(enable);
       if (child instanceof ViewGroup){ 
          disableEnableControls(enable, (ViewGroup)child);
       }
    }
}

visual c++: #include files from other projects in the same solution

Settings for compiler

In the project where you want to #include the header file from another project, you will need to add the path of the header file into the Additional Include Directories section in the project configuration.

To access the project configuration:

  1. Right-click on the project, and select Properties.
  2. Select Configuration Properties->C/C++->General.
  3. Set the path under Additional Include Directories.

How to include

To include the header file, simply write the following in your code:

#include "filename.h"

Note that you don't need to specify the path here, because you include the directory in the Additional Include Directories already, so Visual Studio will know where to look for it.

If you don't want to add every header file location in the project settings, you could just include a directory up to a point, and then #include relative to that point:

// In project settings
Additional Include Directories    ..\..\libroot

// In code
#include "lib1/lib1.h"    // path is relative to libroot
#include "lib2/lib2.h"    // path is relative to libroot

Setting for linker

If using static libraries (i.e. .lib file), you will also need to add the library to the linker input, so that at linkage time the symbols can be linked against (otherwise you'll get an unresolved symbol):

  1. Right-click on the project, and select Properties.
  2. Select Configuration Properties->Linker->Input
  3. Enter the library under Additional Dependencies.

Correct format specifier to print pointer or address?

The simplest answer, assuming you don't mind the vagaries and variations in format between different platforms, is the standard %p notation.

The C99 standard (ISO/IEC 9899:1999) says in §7.19.6.1 ¶8:

p The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.

(In C11 — ISO/IEC 9899:2011 — the information is in §7.21.6.1 ¶8.)

On some platforms, that will include a leading 0x and on others it won't, and the letters could be in lower-case or upper-case, and the C standard doesn't even define that it shall be hexadecimal output though I know of no implementation where it is not.

It is somewhat open to debate whether you should explicitly convert the pointers with a (void *) cast. It is being explicit, which is usually good (so it is what I do), and the standard says 'the argument shall be a pointer to void'. On most machines, you would get away with omitting an explicit cast. However, it would matter on a machine where the bit representation of a char * address for a given memory location is different from the 'anything else pointer' address for the same memory location. This would be a word-addressed, instead of byte-addressed, machine. Such machines are not common (probably not available) these days, but the first machine I worked on after university was one such (ICL Perq).

If you aren't happy with the implementation-defined behaviour of %p, then use C99 <inttypes.h> and uintptr_t instead:

printf("0x%" PRIXPTR "\n", (uintptr_t)your_pointer);

This allows you to fine-tune the representation to suit yourself. I chose to have the hex digits in upper-case so that the number is uniformly the same height and the characteristic dip at the start of 0xA1B2CDEF appears thus, not like 0xa1b2cdef which dips up and down along the number too. Your choice though, within very broad limits. The (uintptr_t) cast is unambiguously recommended by GCC when it can read the format string at compile time. I think it is correct to request the cast, though I'm sure there are some who would ignore the warning and get away with it most of the time.


Kerrek asks in the comments:

I'm a bit confused about standard promotions and variadic arguments. Do all pointers get standard-promoted to void*? Otherwise, if int* were, say, two bytes, and void* were 4 bytes, then it'd clearly be an error to read four bytes from the argument, non?

I was under the illusion that the C standard says that all object pointers must be the same size, so void * and int * cannot be different sizes. However, what I think is the relevant section of the C99 standard is not so emphatic (though I don't know of an implementation where what I suggested is true is actually false):

§6.2.5 Types

¶26 A pointer to void shall have the same representation and alignment requirements as a pointer to a character type.39) Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements. All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements.

39) The same representation and alignment requirements are meant to imply interchangeability as arguments to functions, return values from functions, and members of unions.

(C11 says exactly the same in the section §6.2.5, ¶28, and footnote 48.)

So, all pointers to structures must be the same size as each other, and must share the same alignment requirements, even though the structures the pointers point at may have different alignment requirements. Similarly for unions. Character pointers and void pointers must have the same size and alignment requirements. Pointers to variations on int (meaning unsigned int and signed int) must have the same size and alignment requirements as each other; similarly for other types. But the C standard doesn't formally say that sizeof(int *) == sizeof(void *). Oh well, SO is good for making you inspect your assumptions.

The C standard definitively does not require function pointers to be the same size as object pointers. That was necessary not to break the different memory models on DOS-like systems. There you could have 16-bit data pointers but 32-bit function pointers, or vice versa. This is why the C standard does not mandate that function pointers can be converted to object pointers and vice versa.

Fortunately (for programmers targetting POSIX), POSIX steps into the breach and does mandate that function pointers and data pointers are the same size:

§2.12.3 Pointer Types

All function pointer types shall have the same representation as the type pointer to void. Conversion of a function pointer to void * shall not alter the representation. A void * value resulting from such a conversion can be converted back to the original function pointer type, using an explicit cast, without loss of information.

Note: The ISO C standard does not require this, but it is required for POSIX conformance.

So, it does seem that explicit casts to void * are strongly advisable for maximum reliability in the code when passing a pointer to a variadic function such as printf(). On POSIX systems, it is safe to cast a function pointer to a void pointer for printing. On other systems, it is not necessarily safe to do that, nor is it necessarily safe to pass pointers other than void * without a cast.

Where is debug.keystore in Android Studio

You can use this command and will fetch all your key-stores, go to your terminal and in your android root directory run this:

./gradlew signingReport

it will give you something like this a list of key-store and their information:

enter image description here

Fixed size div?

As reply to Jonathan Sampson, this is the best way to do it, without a clearing div:

.container { width:450px; overflow:hidden }
.cube { width:150px; height:150px; float:left }

<div class="container">
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
</div>

How can I change Eclipse theme?

Update December 2012 (19 months later):

The blog post "Jin Mingjian: Eclipse Darker Theme" mentions this GitHub repo "eclipse themes - darker":

enter image description here

The big fun is that, the codes are minimized by using Eclipse4 platform technologies like dependency injection.
It proves that again, the concise codes and advanced features could be achieved by contributing or extending with the external form (like library, framework).
New language is not necessary just for this kind of purpose.


Update July 2012 (14 months later):

With the latest Eclipse4.2 (June 2012, "Juno") release, you can implement what I originally described below: a CSS-based fully dark theme for Eclipse.
See the article by Lars Vogel in "Eclipse 4 is beautiful – Create your own Eclipse 4 theme":

Eclipse fully dark theme

If you want to play with it, you only need to write a plug-in, create a CSS file and use the org.eclipse.e4.ui.css.swt.theme extension point to point to your file.
If you export your plug-in, place it in the “dropins” folder of your Eclipse installation and your styling is available.


Original answer: August 2011

With Eclipse 3.x, theme is only for the editors, as you can see in the site "Eclipse Color Themes".
Anything around that is managed by windows system colors.
That is what you need to change to have any influence on Eclipse global colors around editors.

Eclipse 4 will provide much advance theme options: See "Eclipse 4.0 – So you can theme me Part 1" and "Eclipse 4.0 RCP: Dynamic CSS Theme Switching".

dark theme

Can I send a ctrl-C (SIGINT) to an application on Windows?

I have done some research around this topic, which turned out to be more popular than I anticipated. KindDragon's reply was one of the pivotal points.

I wrote a longer blog post on the topic and created a working demo program, which demonstrates using this type of system to close a command line application in a couple of nice fashions. That post also lists external links that I used in my research.

In short, those demo programs do the following:

  • Start a program with a visible window using .Net, hide with pinvoke, run for 6 seconds, show with pinvoke, stop with .Net.
  • Start a program without a window using .Net, run for 6 seconds, stop by attaching console and issuing ConsoleCtrlEvent

Edit: The amended solution from KindDragon for those who are interested in the code here and now. If you plan to start other programs after stopping the first one, you should re-enable Ctrl-C handling, otherwise the next process will inherit the parent's disabled state and will not respond to Ctrl-C.

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool AttachConsole(uint dwProcessId);

[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern bool FreeConsole();

[DllImport("kernel32.dll")]
static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate HandlerRoutine, bool Add);

delegate bool ConsoleCtrlDelegate(CtrlTypes CtrlType);

// Enumerated type for the control messages sent to the handler routine
enum CtrlTypes : uint
{
  CTRL_C_EVENT = 0,
  CTRL_BREAK_EVENT,
  CTRL_CLOSE_EVENT,
  CTRL_LOGOFF_EVENT = 5,
  CTRL_SHUTDOWN_EVENT
}

[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GenerateConsoleCtrlEvent(CtrlTypes dwCtrlEvent, uint dwProcessGroupId);

public void StopProgram(Process proc)
{
  //This does not require the console window to be visible.
  if (AttachConsole((uint)proc.Id))
  {
    // Disable Ctrl-C handling for our program
    SetConsoleCtrlHandler(null, true); 
    GenerateConsoleCtrlEvent(CtrlTypes.CTRL_C_EVENT, 0);

    //Moved this command up on suggestion from Timothy Jannace (see comments below)
    FreeConsole();

    // Must wait here. If we don't and re-enable Ctrl-C
    // handling below too fast, we might terminate ourselves.
    proc.WaitForExit(2000);

    //Re-enable Ctrl-C handling or any subsequently started
    //programs will inherit the disabled state.
    SetConsoleCtrlHandler(null, false); 
  }
}

Also, plan for a contingency solution if AttachConsole() or the sent signal should fail, for instance sleeping then this:

if (!proc.HasExited)
{
  try
  {
    proc.Kill();
  }
  catch (InvalidOperationException e){}
}

ComboBox: Adding Text and Value to an Item (no Binding Source)

You can use Dictionary Object instead of creating a custom class for adding text and value in a Combobox.

Add keys and values in a Dictionary Object:

Dictionary<string, string> comboSource = new Dictionary<string, string>();
comboSource.Add("1", "Sunday");
comboSource.Add("2", "Monday");

Bind the source Dictionary object to Combobox:

comboBox1.DataSource = new BindingSource(comboSource, null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";

Retrieve Key and value:

string key = ((KeyValuePair<string,string>)comboBox1.SelectedItem).Key;
string value = ((KeyValuePair<string,string>)comboBox1.SelectedItem).Value;

Full Source : Combobox Text nd Value

Combination of async function + await + setTimeout

Since Node 7.6, you can combine the functions promisify function from the utils module with setTimeout() .

Node.js

const sleep = require('util').promisify(setTimeout)

Javascript

const sleep = m => new Promise(r => setTimeout(r, m))

Usage

(async () => {
    console.time("Slept for")
    await sleep(3000)
    console.timeEnd("Slept for")
})()

How to decode viewstate

You can ignore the URL field and simply paste the viewstate into the Viewstate string box.

It does look like you have an old version; the serialisation methods changed in ASP.NET 2.0, so grab the 2.0 version

How to convert array to SimpleXML

You can do this through DOM also. Please see below code.

<?php

$el = array();
$command = array();

$dom = new DOMDocument('1.0', 'utf-8');
$dom->formatOutput = true;

$xml_array = [
    'root'=>[
    'Good guy' => [
        'name' => [
            '_cdata' => 'Luke Skywalker'
        ],
        'weapon' => 'Lightsaber'
    ],
    'Bad guy' => [
        'name' => 'Sauron',
        'weapon' => 'Evil Eye'
    ]
        ]
];

convert_xml($xml_array);

if(!empty($el))
{
    $dom->appendChild(end($el));
}

echo $dom->saveXML();

?>

<?php

 function convert_xml($Xml)
{
    global $el, $dom;

        foreach($Xml as $id=>$val)
        {
            if(is_numeric($id))
            {
                $id = "Item".($id);
            }

            $id = str_replace(' ', '-', strtolower($id));

            if(is_array($val))
            {
                $ele = $dom->createElement($id);
                array_push($el, $ele);
                convert_xml($val);
            }
            else
            {
                $ele = $dom->createElement($id, $val);

                if(!empty($el))
                {
                    $com = end($el)->appendChild($ele);
                }
                else
                {
                    $dom->appendChild($ele);
                }

            }
        }

        if(sizeof($el) > 1)
        {
            $child = end($el);
            $com = prev($el)->appendChild($child);
            array_pop($el);
        }
}

?>

Vibrate and Sound defaults on notification

For Kotlin you can Try this.

var builder = NotificationCompat.Builder(this,CHANNEL_ID)
     .setVibrate(longArrayOf(1000, 1000, 1000, 1000, 1000))
     .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)

C# static class constructor

You can use static constructor to initialization static variable. Static constructor will be entry point for your class

public class MyClass
{

    static MyClass()
    {

        //write your initialization code here
    }

}

Location of the android sdk has not been setup in the preferences in mac os?

Hope this helps:

Step 1.) Go to https://www.eclipse.org/downloads/index-developer.php?release=kepler and download appropriate Eclipse version.

Step 2.) Extract downloaded zip file in appropriate location. In this tutorial, I have downloaded and installed it under program files.

Step 3.) Right click on eclipse.exe file and send shortcut to desktop.

Step 4.) Double click on eclipse shortcut from desktop and select appropriate location to create your workspace.

Step 5.) Navigate to Window > Preferences. This should open Preferences window.

Step 6.) On the left hand side page expend “Java” and click on “Installed JREs”

Step 7.) Click Add. It will open “Add JRE” dialog. Select “Standard VM” and click Next.

Step 8.) For “JRE home” select “Direcotry…”. This will open “Browse for folder” dialog. Select the location where your JDK is installed. NOTE: MAKE SURE THAT ITS x64 AS WELL, AS WE ARE USING 64-BIT VERSION OF ECLIPSE.

Step 9.) If you have selected proper location, it will show JDK version in JRE name and it will display “JRE system libraries”.

Step 10.) Click finish. Now your JDK is properly pointed as “Installed JREs”.

Step 11.) Select checkbox unchecked before name of your JDK name.

Click ok and you’re done. You are now using JDK as “Installed JREs”

Read complete procedure at below location.

https://softwaretestingboard.com/qna/4/how-do-i-map-android-sdk-after-eclipse-plugin-is-installed#axzz4wM3UEZtq

How to exit an application properly

In a console application, just return from the main program, in a UI-Application Close() all active Forms.

Memory from managed objects will be handled by the .NET Framework, you don't need to care about this.

If you use classes which implement IDisposable (like database connections, for example), you should call Dispose() on them when you no longer need them (preferred way: a using-Statement).

If you use such resources globally (like private members in your form), your form should implement the IDisposable pattern to release these resources on the Close()-call. See this article for details.

Remove characters after specific character in string, then remove substring?

you can use .NET's built in method to remove the QueryString. i.e., Request.QueryString.Remove["whatever"];

here whatever in the [ ] is name of the querystring which you want to remove.

Try this... I hope this will help.

jQuery & CSS - Remove/Add display:none

Use toggle to show and hide.

$('#mydiv').toggle()

Check working example at http://jsfiddle.net/jNqTa/

How to refresh table contents in div using jquery/ajax

You can load HTML page partial, in your case is everything inside div#mytable.

setTimeout(function(){
   $( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds

more information read this http://api.jquery.com/load/

Update Code (if you don't want it auto-refresh)

<button id="refresh-btn">Refresh Table</button>

<script>
$(document).ready(function() {

   function RefreshTable() {
       $( "#mytable" ).load( "your-current-page.html #mytable" );
   }

   $("#refresh-btn").on("click", RefreshTable);

   // OR CAN THIS WAY
   //
   // $("#refresh-btn").on("click", function() {
   //    $( "#mytable" ).load( "your-current-page.html #mytable" );
   // });


});
</script>

PHP Unset Session Variable

If you completely want to clear the session you can use this:

session_unset();
session_destroy();

Actually both are not neccessary but it does not hurt.

If you want to clear only a specific part I think you need this:

unset($_SESSION['Products']);
//or
$_SESSION['Products'] = "";

depending on what you need.

Richtextbox wpf binding

Here's a VB.Net version of Lolo's answer:

Public Class RichTextBoxHelper
Inherits DependencyObject

Private Shared _recursionProtection As New HashSet(Of System.Threading.Thread)()

Public Shared Function GetDocumentXaml(ByVal depObj As DependencyObject) As String
    Return DirectCast(depObj.GetValue(DocumentXamlProperty), String)
End Function

Public Shared Sub SetDocumentXaml(ByVal depObj As DependencyObject, ByVal value As String)
    _recursionProtection.Add(System.Threading.Thread.CurrentThread)
    depObj.SetValue(DocumentXamlProperty, value)
    _recursionProtection.Remove(System.Threading.Thread.CurrentThread)
End Sub

Public Shared ReadOnly DocumentXamlProperty As DependencyProperty = DependencyProperty.RegisterAttached("DocumentXaml", GetType(String), GetType(RichTextBoxHelper), New FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.AffectsRender Or FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, Sub(depObj, e)
                                                                                                                                                                                                                                                                                                                    RegisterIt(depObj, e)
                                                                                                                                                                                                                                                                                                                End Sub))

Private Shared Sub RegisterIt(ByVal depObj As System.Windows.DependencyObject, ByVal e As System.Windows.DependencyPropertyChangedEventArgs)
    If _recursionProtection.Contains(System.Threading.Thread.CurrentThread) Then
        Return
    End If
    Dim rtb As RichTextBox = DirectCast(depObj, RichTextBox)
    Try
        rtb.Document = Markup.XamlReader.Parse(GetDocumentXaml(rtb))
    Catch
        rtb.Document = New FlowDocument()
    End Try
    ' When the document changes update the source
    AddHandler rtb.TextChanged, AddressOf TextChanged
End Sub

Private Shared Sub TextChanged(ByVal sender As Object, ByVal e As TextChangedEventArgs)
    Dim rtb As RichTextBox = TryCast(sender, RichTextBox)
    If rtb IsNot Nothing Then
        SetDocumentXaml(sender, Markup.XamlWriter.Save(rtb.Document))
    End If
End Sub

End Class

What Are Some Good .NET Profilers?

I've found plenty of problems in a big C# app using this.

Usually the problem occurs during startup or shutdown as plugins are being loaded, and big data structures are being created, destroyed, serialized, or deserialized. Often they are created and initialized more than once, and change handlers get added multiple times, further compounding the problem.

In cases like this, the program can be so sluggish that only 2 samples are sufficient to pinpoint the guilty method / function / property call sites.

Creating a new empty branch for a new project

On base this answer from Hiery Nomus.

You can create a branch as an orphan:

git checkout --orphan <branchname>

This will create a new branch with no parents. Then, you can clear the working directory with:

git rm --cached -r .

And then you just commit branch with empty commit and then push

git commit -m <commit message> --allow-empty
git push origin <newbranch>