Programs & Examples On #Rule engine

Rule engines are software components that allow application developers to externalize business rules and manage their lifecycle independently from the application code.

When should you NOT use a Rules Engine?

I don't really understand some points such as :
a) business people needs to understand business very well, or;
b) disagreement on business people don't need to know the rule.

For me, as a people just touching BRE, the benefit of BRE is so called to let system adapt to business change, hence it's focused on adaptive of change.
Does it matter if the rule set up at time x is different from the rule set up at time y because of:
a) business people don't understand business, or;
b) business people don't understand rules?

Generate Java classes from .XSD files...?

XMLBeans will do it. Specifically the "scomp" command.

EDIT: XMLBeans has been retired, check this stackoverflow post for more info.

File.Move Does Not Work - File Already Exists

Try Microsoft.VisualBasic.FileIO.FileSystem.MoveFile(Source, Destination, True). The last parameter is Overwrite switch, which System.IO.File.Move doesn't have.

Android ListView not refreshing after notifyDataSetChanged

adpter.notifyDataSetInvalidated();

Try this in onPause() method of Activity class.

How to set a header for a HTTP GET request, and trigger file download?

There are two ways to download a file where the HTTP request requires that a header be set.

The credit for the first goes to @guest271314, and credit for the second goes to @dandavis.

The first method is to use the HTML5 File API to create a temporary local file, and the second is to use base64 encoding in conjunction with a data URI.

The solution I used in my project uses the base64 encoding approach for small files, or when the File API is not available, otherwise using the the File API approach.

Solution:

        var id = 123;

        var req = ic.ajax.raw({
            type: 'GET',
            url: '/api/dowloads/'+id,
            beforeSend: function (request) {
                request.setRequestHeader('token', 'token for '+id);
            },
            processData: false
        });

        var maxSizeForBase64 = 1048576; //1024 * 1024

        req.then(
            function resolve(result) {
                var str = result.response;

                var anchor = $('.vcard-hyperlink');
                var windowUrl = window.URL || window.webkitURL;
                if (str.length > maxSizeForBase64 && typeof windowUrl.createObjectURL === 'function') {
                    var blob = new Blob([result.response], { type: 'text/bin' });
                    var url = windowUrl.createObjectURL(blob);
                    anchor.prop('href', url);
                    anchor.prop('download', id+'.bin');
                    anchor.get(0).click();
                    windowUrl.revokeObjectURL(url);
                }
                else {
                    //use base64 encoding when less than set limit or file API is not available
                    anchor.attr({
                        href: 'data:text/plain;base64,'+FormatUtils.utf8toBase64(result.response),
                        download: id+'.bin',
                    });
                    anchor.get(0).click();
                }

            }.bind(this),
            function reject(err) {
                console.log(err);
            }
        );

Note that I'm not using a raw XMLHttpRequest, and instead using ic-ajax, and should be quite similar to a jQuery.ajax solution.

Note also that you should substitute text/bin and .bin with whatever corresponds to the file type being downloaded.

The implementation of FormatUtils.utf8toBase64 can be found here

C string append

strcpy(str1+strlen(str1), str2);

What is float in Java?

In Java, when you type a decimal number as 3.6, its interpreted as a double. double is a 64-bit precision IEEE 754 floating point, while floatis a 32-bit precision IEEE 754 floating point. As a float is less precise than a double, the conversion cannot be performed implicitly.

If you want to create a float, you should end your number with f (i.e.: 3.6f).

For more explanation, see the primitive data types definition of the Java tutorial.

What Language is Used To Develop Using Unity

When you build for iPhone in Unity it does Ahead of Time (AOT) compilation of your mono assembly (written in C# or JavaScript) to native ARM code.

The authoring tool also creates a stub xcode project and references that compiled lib. You can add objective C code to this xcode project if there is native stuff you want to do that isn't exposed in Unity's environment yet (e.g. accessing the compass and/or gyroscope).

How different is Scrum practice from Agile Practice?

Scrum is a very specific set of practices. Agile describes a family of practices, everything from Extreme Programming to Scrum and almost anything else that uses short iterations can claim Agile. That may not have originally been the case when the term was coined, but it certainly is by now.

Java regex email

Don't. You will never end up with a valid expression.

For example these are all valid email addresses:

"Abc\@def"@example.com
"Fred Bloggs"@example.com
"Joe\\Blow"@example.com
"Abc@def"@example.com
customer/department=shipping@examp­ le.com
[email protected]
!def!xyz%[email protected]
[email protected]
matteo(this is a comment)[email protected]
root@[127.0.0.1]

Just to mention a few problems:

  • you don't consider the many forms of specifying a host (e.g, by the IP address)
  • you miss valid characters
  • you miss non ASCII domain names

Before even beginning check the corresponding RFCs

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

In your config.xml file add this line:

<preference name="loadUrlTimeoutValue" value="700000" />

Spring JPA selecting specific columns

You can set nativeQuery = true in the @Query annotation from a Repository class like this:

public static final String FIND_PROJECTS = "SELECT projectId, projectName FROM projects";

@Query(value = FIND_PROJECTS, nativeQuery = true)
public List<Object[]> findProjects();

Note that you will have to do the mapping yourself though. It's probably easier to just use the regular mapped lookup like this unless you really only need those two values:

public List<Project> findAll()

It's probably worth looking at the Spring data docs as well.

Explaining Python's '__enter__' and '__exit__'

Python calls __enter__ when execution enters the context of the with statement and it’s time to acquire the resource. When execution leaves the context again, Python calls __exit__ to free up the resource

Let's consider Context Managers and the “with” Statement in Python. Context Manager is a simple “protocol” (or interface) that your object needs to follow so it can be used with the with statement. Basically all you need to do is add enter and exit methods to an object if you want it to function as a context manager. Python will call these two methods at the appropriate times in the resource management cycle.

Let’s take a look at what this would look like in practical terms. Here’s how a simple implementation of the open() context manager might look like:

class ManagedFile:
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        self.file = open(self.name, 'w')
        return self.file

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.file:
            self.file.close()

Our ManagedFile class follows the context manager protocol and now supports the with statement.

>>> with ManagedFile('hello.txt') as f:
...    f.write('hello, world!')
...    f.write('bye now')`enter code here`

Python calls enter when execution enters the context of the with statement and it’s time to acquire the resource. When execution leaves the context again, Python calls exit to free up the resource.

Writing a class-based context manager isn’t the only way to support the with statement in Python. The contextlib utility module in the standard library provides a few more abstractions built on top of the basic context manager protocol. This can make your life a little easier if your use cases matches what’s offered by contextlib.

Extracting date from a string in Python

You could also try the dateparser module, which may be slower than datefinder on free text but which should cover more potential cases and date formats, as well as a significant number of languages.

Trouble using ROW_NUMBER() OVER (PARTITION BY ...)

I would do something like this:

;WITH x 
 AS (SELECT *, 
            Row_number() 
              OVER( 
                partition BY employeeid 
                ORDER BY datestart) rn 
     FROM   employeehistory) 
SELECT * 
FROM   x x1 
   LEFT OUTER JOIN x x2 
                ON x1.rn = x2.rn + 1 

Or maybe it would be x2.rn - 1. You'll have to see. In any case, you get the idea. Once you have the table joined on itself, you can filter, group, sort, etc. to get what you need.

Insert Multiple Rows Into Temp Table With SQL Server 2012

Yes, SQL Server 2012 supports multiple inserts - that feature was introduced in SQL Server 2008.

That makes me wonder if you have Management Studio 2012, but you're really connected to a SQL Server 2005 instance ...

What version of the SQL Server engine do you get from SELECT @@VERSION ??

How do I generate random integers within a specific range in Java?

You can achieve that concisely in Java 8:

Random random = new Random();

int max = 10;
int min = 5;
int totalNumber = 10;

IntStream stream = random.ints(totalNumber, min, max);
stream.forEach(System.out::println);

Convert java.time.LocalDate into java.util.Date type

    LocalDate date = LocalDate.now();
    DateFormat formatter = new SimpleDateFormat("dd-mm-yyyy");
    try {
        Date utilDate= formatter.parse(date.toString());
    } catch (ParseException e) {
        // handle exception
    }

What are pipe and tap methods in Angular tutorial?

You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

  /**
   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   *
   * @example
   *
   * import { map, filter, scan } from 'rxjs/operators';
   *
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))
   */

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().

How to forcefully set IE's Compatibility Mode off from the server-side?

Update: More useful information What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

Maybe this url can help you: Activating Browser Modes with Doctype

Edit: Today we were able to override the compatibility view with: <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />

What does the fpermissive flag do?

If you want a real-world use case for this, try compiling a very old version of X Windows-- say, either XFree86 or XOrg from aboout 2004, right around the split-- using a "modern" (cough) version of gcc, such as 4.9.3.

You'll notice the build CFLAGS specify both "-ansi" and "-pedantic". In theory, this means, "blow up if anything even slightly violates the language spec". In practice, the 3.x series of gcc didn't catch very much of that kind of stuff, and building it with 4.9.3 will leave a smoking hole in the ground unless you set CFLAGS and BOOTSTRAPCFLAGS to "-fpermissive".

Using that flag, most of those C files will actually build, leaving you free to move on to the version-dependent wreckage the lexer will generate. =]

Combine Date and Time columns using python pandas

Here is a one liner, to do it. You simply concatenate the two string in each of the column with a " " space in between.

Say df is your dataframe and columns are 'Time' and 'Date'. And your new column is DateAndTime.

df['DateAndTime'] = df['Date'].str.cat(df['Time'],sep=" ")

And if you also wanna handle entries like datetime objects, you can do this. You can tweak the formatting as per your needs.

df['DateAndTime'] = pd.to_datetime(df['DateAndTime'], format="%m/%d/%Y %I:%M:%S %p")

Cheers!! Happy Data Crunching.

How to compare times in Python?

Another way to do this without adding dependencies or using datetime is to simply do some math on the attributes of the time object. It has hours, minutes, seconds, milliseconds, and a timezone. For very simple comparisons, hours and minutes should be sufficient.

d = datetime.utcnow()
t = d.time()
print t.hour,t.minute,t.second

I don't recommend doing this unless you have an incredibly simple use-case. For anything requiring timezone awareness or awareness of dates, you should be using datetime.

How to print / echo environment variables?

On windows, you can print with this command in your CLI C:\Users\dir\env | more

You can view all environment variables set on your system with the env command. The list is long, so pipe the output through more to make it easier to read.

Convert JavaScript String to be all lower case?

I payed attention that lots of people are looking for strtolower() in JavaScript. They are expecting the same function name as in other languages, that's why this post is here.

I would recommend using native Javascript function

"SomE StriNg".toLowerCase()

Here's the function that behaves exactly the same as PHP's one (for those who are porting PHP code into js)

function strToLower (str) {
    return String(str).toLowerCase();
}

Simple 3x3 matrix inverse code (C++)

I would also recommend Ilmbase, which is part of OpenEXR. It's a good set of templated 2,3,4-vector and matrix routines.

How do I run pip on python for windows?

I have a Mac, but luckily this should work the same way:

pip is a command-line thing. You don't run it in python.

For example, on my Mac, I just say:

$pip install somelib

pretty easy!

Use curly braces to initialize a Set in Python

You need to do empty_set = set() to initialize an empty set. {} is an empty dict.

How do I check out a specific version of a submodule using 'git submodule'?

Submodule repositories stay in a detached HEAD state pointing to a specific commit. Changing that commit simply involves checking out a different tag or commit then adding the change to the parent repository.

$ cd submodule
$ git checkout v2.0
Previous HEAD position was 5c1277e... bumped version to 2.0.5
HEAD is now at f0a0036... version 2.0

git-status on the parent repository will now report a dirty tree:

# On branch dev [...]
#
#   modified:   submodule (new commits)

Add the submodule directory and commit to store the new pointer.

How to get IP address of running docker container

For my case, below worked on Mac:

I could not access container IPs directly on Mac. I need to use localhost with port forwarding, e.g. if the port is 8000, then http://localhost:8000

See https://docs.docker.com/docker-for-mac/networking/#known-limitations-use-cases-and-workarounds

The original answer was from: https://github.com/docker/for-mac/issues/2670#issuecomment-371249949

What are the proper permissions for an upload folder with PHP/Apache?

Based on the answer from @Ryan Ahearn, following is what I did on Ubuntu 16.04 to create a user front that only has permission for nginx's web dir /var/www/html.

Steps:

* pre-steps:
    * basic prepare of server,
    * create user 'dev'
        which will be the owner of "/var/www/html",
    * 
    * install nginx,
    * 
* 
* create user 'front'
    sudo useradd -d /home/front -s /bin/bash front
    sudo passwd front

    # create home folder, if not exists yet,
    sudo mkdir /home/front
    # set owner of new home folder,
    sudo chown -R front:front /home/front

    # switch to user,
    su - front

    # copy .bashrc, if not exists yet,
    cp /etc/skel/.bashrc ~front/
    cp /etc/skel/.profile ~front/

    # enable color,
    vi ~front/.bashrc
    # uncomment the line start with "force_color_prompt",

    # exit user
    exit
* 
* add to group 'dev',
    sudo usermod -a -G dev front
* change owner of web dir,
    sudo chown -R dev:dev /var/www
* change permission of web dir,
    chmod 775 $(find /var/www/html -type d)
    chmod 664 $(find /var/www/html -type f)
* 
* re-login as 'front'
    to make group take effect,
* 
* test
* 
* ok
* 

Windows 7 - Add Path

I think you are editing something in the windows registry but that has no effect on the path.

Try this:

How to Add, Remove or Edit Environment variables in Windows 7

the variable of interest is the PATH

also you can type on the command line:

Set PATH=%PATH%;(your new path);

How to align matching values in two columns in Excel, and bring along associated values in other columns

Skip all of this. Download Microsoft FUZZY LOOKUP add in. Create tables using your columns. Create a new worksheet. INPUT tables into the tool. Click all corresponding columns check boxes. Use slider for exact matches. HIT go and wait for the magic.

What does an exclamation mark before a cell reference mean?

If you use that forumla in the name manager you are creating a dynamic range which uses "this sheet" in place of a specific sheet.

As Jerry says, Sheet1!A1 refers to cell A1 on Sheet1. If you create a named range and omit the Sheet1 part you will reference cell A1 on the currently active sheet. (omitting the sheet reference and using it in a cell formula will error).

edit: my bad, I was using $A$1 which will lock it to the A1 cell as above, thanks pnuts :p

'const string' vs. 'static readonly string' in C#

When you use a const string, the compiler embeds the string's value at compile-time.
Therefore, if you use a const value in a different assembly, then update the original assembly and change the value, the other assembly won't see the change until you re-compile it.

A static readonly string is a normal field that gets looked up at runtime. Therefore, if the field's value is changed in a different assembly, the changes will be seen as soon as the assembly is loaded, without recompiling.

This also means that a static readonly string can use non-constant members, such as Environment.UserName or DateTime.Now.ToString(). A const string can only be initialized using other constants or literals.
Also, a static readonly string can be set in a static constructor; a const string can only be initialized inline.

Note that a static string can be modified; you should use static readonly instead.

Swift 3 - Comparing Date objects

I have tried this snippet (in Xcode 8 Beta 6), and it is working fine.

let date1 = Date()
let date2 = Date().addingTimeInterval(100)

if date1 == date2 { ... }
else if date1 > date2 { ... }
else if date1 < date2 { ... }

How to loop through an associative array and get the key?

You can do:

foreach ($arr as $key => $value) {
 echo $key;
}

As described in PHP docs.

JavaScriptSerializer.Deserialize - how to change field names

There is no standard support for renaming properties in JavaScriptSerializer however you can quite easily add your own:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
using System.Reflection;

public class JsonConverter : JavaScriptConverter
{
    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        List<MemberInfo> members = new List<MemberInfo>();
        members.AddRange(type.GetFields());
        members.AddRange(type.GetProperties().Where(p => p.CanRead && p.CanWrite && p.GetIndexParameters().Length == 0));

        object obj = Activator.CreateInstance(type);

        foreach (MemberInfo member in members)
        {
            JsonPropertyAttribute jsonProperty = (JsonPropertyAttribute)Attribute.GetCustomAttribute(member, typeof(JsonPropertyAttribute));

            if (jsonProperty != null && dictionary.ContainsKey(jsonProperty.Name))
            {
                SetMemberValue(serializer, member, obj, dictionary[jsonProperty.Name]);
            }
            else if (dictionary.ContainsKey(member.Name))
            {
                SetMemberValue(serializer, member, obj, dictionary[member.Name]);
            }
            else
            {
                KeyValuePair<string, object> kvp = dictionary.FirstOrDefault(x => string.Equals(x.Key, member.Name, StringComparison.InvariantCultureIgnoreCase));

                if (!kvp.Equals(default(KeyValuePair<string, object>)))
                {
                    SetMemberValue(serializer, member, obj, kvp.Value);
                }
            }
        }

        return obj;
    }


    private void SetMemberValue(JavaScriptSerializer serializer, MemberInfo member, object obj, object value)
    {
        if (member is PropertyInfo)
        {
            PropertyInfo property = (PropertyInfo)member;                
            property.SetValue(obj, serializer.ConvertToType(value, property.PropertyType), null);
        }
        else if (member is FieldInfo)
        {
            FieldInfo field = (FieldInfo)member;
            field.SetValue(obj, serializer.ConvertToType(value, field.FieldType));
        }
    }


    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        Type type = obj.GetType();
        List<MemberInfo> members = new List<MemberInfo>();
        members.AddRange(type.GetFields());
        members.AddRange(type.GetProperties().Where(p => p.CanRead && p.CanWrite && p.GetIndexParameters().Length == 0));

        Dictionary<string, object> values = new Dictionary<string, object>();

        foreach (MemberInfo member in members)
        {
            JsonPropertyAttribute jsonProperty = (JsonPropertyAttribute)Attribute.GetCustomAttribute(member, typeof(JsonPropertyAttribute));

            if (jsonProperty != null)
            {
                values[jsonProperty.Name] = GetMemberValue(member, obj);
            }
            else
            {
                values[member.Name] = GetMemberValue(member, obj);
            }
        }

        return values;
    }

    private object GetMemberValue(MemberInfo member, object obj)
    {
        if (member is PropertyInfo)
        {
            PropertyInfo property = (PropertyInfo)member;
            return property.GetValue(obj, null);
        }
        else if (member is FieldInfo)
        {
            FieldInfo field = (FieldInfo)member;
            return field.GetValue(obj);
        }

        return null;
    }


    public override IEnumerable<Type> SupportedTypes
    {
        get 
        {
            return new[] { typeof(DataObject) };
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class JsonPropertyAttribute : Attribute
{
    public JsonPropertyAttribute(string name)
    {
        Name = name;
    }

    public string Name
    {
        get;
        set;
    }
}

The DataObject class then becomes:

public class DataObject
{
    [JsonProperty("user_id")]
    public int UserId { get; set; }

    [JsonProperty("detail_level")]
    public DetailLevel DetailLevel { get; set; }
}

I appreicate this might be a little late but thought other people wanting to use the JavaScriptSerializer rather than the DataContractJsonSerializer might appreciate it.

Convenient way to parse incoming multipart/form-data parameters in a Servlet

Not always there's a servlet before of an upload (I could use a filter for example). Or could be that the same controller ( again a filter or also a servelt ) can serve many actions, so I think that rely on that servlet configuration to use the getPart method (only for Servlet API >= 3.0), I don't know, I don't like.

In general, I prefer independent solutions, able to live alone, and in this case http://commons.apache.org/proper/commons-fileupload/ is one of that.

List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
    for (FileItem item : multiparts) {
        if (!item.isFormField()) {
            //your operations on file
        } else {
            String name = item.getFieldName();
            String value = item.getString();
            //you operations on paramters
        }
}

Is there a way to automatically build the package.json file for Node.js projects

You can now use Yeoman - Modern Web App Scaffolding Tool on node terminal using 3 easy steps.

First, you'll need to install yo and other required tools:

$ npm install -g yo bower grunt-cli gulp

To scaffold a web application, install the generator-webapp generator:

$ npm install -g generator-webapp  // create scaffolding 

Run yo and... you are all done:

$ yo webapp  // create scaffolding 

Yeoman can write boilerplate code for your entire web application or Controllers and Models. It can fire up a live-preview web server for edits and compile; not just that you can also run your unit tests, minimize and concatenate your code, optimize images, and more...

Yeoman (yo) - scaffolding tool that offers an ecosystem of framework-specific scaffolds, called generators, that can be used to perform some of the tedious tasks mentioned earlier.

Grunt / gulp - used to build, preview, and test your project.

Bower - is used for dependency management, so that you no longer have to manually download your front-end libraries.

Ansible: Set variable to file content

You can use fetch module to copy files from remote hosts to local, and lookup module to read the content of fetched files.

Java 8 Stream and operation on arrays

There are new methods added to java.util.Arrays to convert an array into a Java 8 stream which can then be used for summing etc.

int sum =  Arrays.stream(myIntArray)
                 .sum();

Multiplying two arrays is a little more difficult because I can't think of a way to get the value AND the index at the same time as a Stream operation. This means you probably have to stream over the indexes of the array.

//in this example a[] and b[] are same length
int[] a = ...
int[] b = ...

int[] result = new int[a.length];

IntStream.range(0, a.length)
         .forEach(i -> result[i] = a[i] * b[i]);

EDIT

Commenter @Holger points out you can use the map method instead of forEach like this:

int[] result = IntStream.range(0, a.length).map(i -> a[i] * b[i]).toArray();

How can I check if an array contains a specific value in php?

Use the in_array() function.

$array = array('kitchen', 'bedroom', 'living_room', 'dining_room');

if (in_array('kitchen', $array)) {
    echo 'this array contains kitchen';
}

SASS :not selector

I tried re-creating this, and .someclass.notip was being generated for me but .someclass:not(.notip) was not, for as long as I did not have the @mixin tip() defined. Once I had that, it all worked.

http://sassmeister.com/gist/9775949

$dropdown-width: 100px;
$comp-tip: true;

@mixin tip($pos:right) {

}

@mixin dropdown-pos($pos:right) {
  &:not(.notip) {
    @if $comp-tip == true{
      @if $pos == right {
        top:$dropdown-width * -0.6;
        background-color: #f00;
        @include tip($pos:$pos);
      }
    }
  }
  &.notip {
    @if $pos == right {
      top: 0;
      left:$dropdown-width * 0.8;
      background-color: #00f;
    }
  }
}

.someclass { @include dropdown-pos(); }

EDIT: http://sassmeister.com/ is a good place to debug your SASS because it gives you error messages. Undefined mixin 'tip'. it what I get when I remove @mixin tip($pos:right) { }

Get the last three chars from any string - Java

Here's some terse code that does the job using regex:

String last3 = str.replaceAll(".*?(.?.?.?)?$", "$1");

This code returns up to 3; if there are less than 3 it just returns the string.

This is how to do it safely without regex in one line:

String last3 = str == null || str.length() < 3 ? 
    str : str.substring(str.length() - 3);

By "safely", I mean without throwing an exception if the string is nulls or shorter than 3 characters (all the other answers are not "safe").


The above code is identical in effect to this code, if you prefer a more verbose, but potentially easier-to-read form:

String last3;
if (str == null || str.length() < 3) {
    last3 = str;
} else {
    last3 = str.substring(str.length() - 3);
}

How to commit and rollback transaction in sql server?

Don't use @@ERROR, use BEGIN TRY/BEGIN CATCH instead. See this article: Exception handling and nested transactions for a sample procedure:

create procedure [usp_my_procedure_name]
as
begin
    set nocount on;
    declare @trancount int;
    set @trancount = @@trancount;
    begin try
        if @trancount = 0
            begin transaction
        else
            save transaction usp_my_procedure_name;

        -- Do the actual work here

lbexit:
        if @trancount = 0   
            commit;
    end try
    begin catch
        declare @error int, @message varchar(4000), @xstate int;
        select @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
        if @xstate = -1
            rollback;
        if @xstate = 1 and @trancount = 0
            rollback
        if @xstate = 1 and @trancount > 0
            rollback transaction usp_my_procedure_name;

        raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
        return;
    end catch   
end

Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

Had the same problem i added compile 'com.google.android.gms:play-services-measurement:8.4.0' and deleted apply plugin: 'com.google.gms.google-services' I was using classpath 'com.google.gms:google-services:2.0.0-alpha6' in the build project.

How to solve time out in phpmyadmin?

I was having the issue previously in XAMPP localhost with phpmyadmin version 4.2.11.

Increasing the timeout in php.ini didn't helped either.

Then I edited xampp\phpMyAdmin\libraries\config.default.php to change the value of $cfg['ExecTimeLimit'], which was 300 by default.

That solved my issue.

How do I increase modal width in Angular UI Bootstrap?

I solved the problem using Dmitry Komin solution, but with different CSS syntax to make it works directly in browser.

CSS

@media(min-width: 1400px){
    .my-modal > .modal-lg {
        width: 1308px;
    }
}

JS is the same:

var modal = $modal.open({
    animation: true,
    templateUrl: 'modalTemplate.html',
    controller: 'modalController',
    size: 'lg',
    windowClass: 'my-modal'
});

Inherit CSS class

CSS "classes" are not OOP "classes". The inheritance works the other way around.
A DOM element can have many classes, either directly or inherited or otherwise associated, which will all be applied in order, overriding earlier defined properties:

<div class="foo bar">
.foo {
    color: blue;
    width: 200px;
}

.bar {
    color: red;
}

The div will be 200px wide and have the color red.

You override properties of DOM elements with different classes, not properties of CSS classes. CSS "classes" are rulesets, the same way ids or tags can be used as rulesets.

Note that the order in which the classes are applied depends on the precedence and specificity of the selector, which is a complex enough topic in itself.

How to use awk sort by column 3

How about just sort.

sort -t, -nk3 user.csv

where

  • -t, - defines your delimiter as ,.

  • -n - gives you numerical sort. Added since you added it in your attempt. If your user field is text only then you dont need it.

  • -k3 - defines the field (key). user is the third field.

Pass a data.frame column name to a function

You can just use the column name directly:

df <- data.frame(A=1:10, B=2:11, C=3:12)
fun1 <- function(x, column){
  max(x[,column])
}
fun1(df, "B")
fun1(df, c("B","A"))

There's no need to use substitute, eval, etc.

You can even pass the desired function as a parameter:

fun1 <- function(x, column, fn) {
  fn(x[,column])
}
fun1(df, "B", max)

Alternatively, using [[ also works for selecting a single column at a time:

df <- data.frame(A=1:10, B=2:11, C=3:12)
fun1 <- function(x, column){
  max(x[[column]])
}
fun1(df, "B")

Generating random, unique values C#

Depending on what you are really after you can do something like this:

using System;
using System.Collections.Generic;
using System.Linq;

namespace SO14473321
{
    class Program
    {
        static void Main()
        {
            UniqueRandom u = new UniqueRandom(Enumerable.Range(1,10));
            for (int i = 0; i < 10; i++)
            {
                Console.Write("{0} ",u.Next());
            }
        }
    }

    class UniqueRandom
    {
        private readonly List<int> _currentList;
        private readonly Random _random = new Random();

        public UniqueRandom(IEnumerable<int> seed)
        {
            _currentList = new List<int>(seed);
        }

        public int Next()
        {
            if (_currentList.Count == 0)
            {
                throw new ApplicationException("No more numbers");
            }

            int i = _random.Next(_currentList.Count);
            int result = _currentList[i];
            _currentList.RemoveAt(i);
            return result;
        }
    }
}

How to display a json array in table format?

var data = [
    {
        id : "001",
        name : "apple",
        category : "fruit",
        color : "red"
    },
    {
        id : "002",
        name : "melon",
        category : "fruit",
        color : "green"
    },
    {
        id : "003",
        name : "banana",
        category : "fruit",
        color : "yellow"
    }
];

for(var i = 0, len = data.length; i < length; i++) {
    var temp = '<tr><td>' + data[i].id + '</td>';
    temp+= '<td>' + data[i].name+ '</td>';
    temp+= '<td>' + data[i].category + '</td>';
    temp+= '<td>' + data[i].color + '</td></tr>';
    $('table tbody').append(temp));
}

Is there any way to start with a POST request using Selenium?

One very practical way to do this is to create a dummy start page for your tests that is simply a form with POST that has a single "start test" button and a bunch of <input type="hidden"... elements with the appropriate post data.

For example you might create a SeleniumTestStart.html page with these contents:

<body>
  <form action="/index.php" method="post">
    <input id="starttestbutton" type="submit" value="starttest"/>
    <input type="hidden" name="stageid" value="stage-you-need-your-test-to-start-at"/>
  </form>
</body>

In this example, index.php is where your normal web app is located.

The Selenium code at the start of your tests would then include:

open /SeleniumTestStart.html
clickAndWait starttestbutton

This is very similar to other mock and stub techniques used in automated testing. You are just mocking the entry point to the web app.

Obviously there are some limitations to this approach:

  1. data cannot be too large (e.g. image data)
  2. security might be an issue so you need to make sure that these test files don't end up on your production server
  3. you may need to make your entry points with something like php instead of html if you need to set cookies before the Selenium test gets going
  4. some web apps check the referrer to make sure someone isn't hacking the app - in this case this approach probably won't work - you may be able to loosen this checking in a dev environment so it allows referrers from trusted hosts (not self, but the actual test host)

Please consider reading my article about the Qualities of an Ideal Test

Function not defined javascript

I just went through the same problem. And found out once you have a syntax or any type of error in you javascript, the whole file don't get loaded so you cannot use any of the other functions at all.

How can I compare a date and a datetime in Python?

I am trying to compare date which are in string format like '20110930'

benchMark = datetime.datetime.strptime('20110701', "%Y%m%d") 

actualDate = datetime.datetime.strptime('20110930', "%Y%m%d")

if actualDate.date() < benchMark.date():
    print True

Clone only one branch

--single-branch” switch is your answer, but it only works if you have git version 1.8.X onwards, first check

#git --version 

If you already have git version 1.8.X installed then simply use "-b branch and --single branch" to clone a single branch

#git clone -b branch --single-branch git://github/repository.git

By default in Ubuntu 12.04/12.10/13.10 and Debian 7 the default git installation is for version 1.7.x only, where --single-branch is an unknown switch. In that case you need to install newer git first from a non-default ppa as below.

sudo add-apt-repository ppa:pdoes/ppa
sudo apt-get update
sudo apt-get install git
git --version

Once 1.8.X is installed now simply do:

git clone -b branch --single-branch git://github/repository.git

Git will now only download a single branch from the server.

Could not open ServletContext resource

Are you having Tomcat unpack the WAR file? It seems that the files cannot be found on the classpath when a WAR file is loaded and it is not being unpacked.

How to get exact browser name and version?

Use 51Degrees.com device detection solution to detect browser name, vendor and version.

First, follow the 4-step guide to incorporate device detector in to your project. When I say incorporate I mean download archive with PHP code and database file, extract them and include 2 files. That's all there is to do to incorporate.

Once that's done you can use the following properties to get browser information:
$_51d['BrowserName'] - Gives you the name of the browser (Safari, Molto, Motorola, MStarBrowser etc).
$_51d['BrowserVendor'] - Gives you the company who created browser.
$_51d['BrowserVersion'] - Version number of the browser

What's the difference between window.location= and window.location.replace()?

TLDR;

use location.href or better use window.location.href;

However if you read this you will gain undeniable proof.

The truth is it's fine to use but why do things that are questionable. You should take the higher road and just do it the way that it probably should be done.

location = "#/mypath/otherside"
var sections = location.split('/')

This code is perfectly correct syntax-wise, logic wise, type-wise you know the only thing wrong with it?

it has location instead of location.href

what about this

var mystring = location = "#/some/spa/route"

what is the value of mystring? does anyone really know without doing some test. No one knows what exactly will happen here. Hell I just wrote this and I don't even know what it does. location is an object but I am assigning a string will it pass the string or pass the location object. Lets say there is some answer to how this should be implemented. Can you guarantee all browsers will do the same thing?

This i can pretty much guess all browsers will handle the same.

var mystring = location.href = "#/some/spa/route"

What about if you place this into typescript will it break because the type compiler will say this is suppose to be an object?

This conversation is so much deeper than just the location object however. What this conversion is about what kind of programmer you want to be?

If you take this short-cut, yea it might be okay today, ye it might be okay tomorrow, hell it might be okay forever, but you sir are now a bad programmer. It won't be okay for you and it will fail you.

There will be more objects. There will be new syntax.

You might define a getter that takes only a string but returns an object and the worst part is you will think you are doing something correct, you might think you are brilliant for this clever method because people here have shamefully led you astray.

var Person.name = {first:"John":last:"Doe"}
console.log(Person.name) // "John Doe"

With getters and setters this code would actually work, but just because it can be done doesn't mean it's 'WISE' to do so.

Most people who are programming love to program and love to get better. Over the last few years I have gotten quite good and learn a lot. The most important thing I know now especially when you write Libraries is consistency and predictability.

Do the things that you can consistently do.

+"2" <-- this right here parses the string to a number. should you use it? or should you use parseInt("2")?

what about var num =+"2"?

From what you have learn, from the minds of stackoverflow i am not too hopefully.

If you start following these 2 words consistent and predictable. You will know the right answer to a ton of questions on stackoverflow.

Let me show you how this pays off. Normally I place ; on every line of javascript i write. I know it's more expressive. I know it's more clear. I have followed my rules. One day i decided not to. Why? Because so many people are telling me that it is not needed anymore and JavaScript can do without it. So what i decided to do this. Now because I have become sure of my self as a programmer (as you should enjoy the fruit of mastering a language) i wrote something very simple and i didn't check it. I erased one comma and I didn't think I needed to re-test for such a simple thing as removing one comma.

I wrote something similar to this in es6 and babel

var a = "hello world"
(async function(){
  //do work
})()

This code fail and took forever to figure out. For some reason what it saw was

var a = "hello world"(async function(){})()

hidden deep within the source code it was telling me "hello world" is not a function.

For more fun node doesn't show the source maps of transpiled code.

Wasted so much stupid time. I was presenting to someone as well about how ES6 is brilliant and then I had to start debugging and demonstrate how headache free and better ES6 is. Not convincing is it.

I hope this answered your question. This being an old question it's more for the future generation, people who are still learning.

Question when people say it doesn't matter either way works. Chances are a wiser more experienced person will tell you other wise.

what if someone overwrite the location object. They will do a shim for older browsers. It will get some new feature that needs to be shimmed and your 3 year old code will fail.

My last note to ponder upon.

Writing clean, clear purposeful code does something for your code that can't be answer with right or wrong. What it does is it make your code an enabler.

You can use more things plugins, Libraries with out fear of interruption between the codes.

for the record. use

window.location.href

Order discrete x scale by frequency/value

Hadley has been developing a package called forcats. This package makes the task so much easier. You can exploit fct_infreq() when you want to change the order of x-axis by the frequency of a factor. In the case of the mtcars example in this post, you want to reorder levels of cyl by the frequency of each level. The level which appears most frequently stays on the left side. All you need is the fct_infreq().

library(ggplot2)
library(forcats)

ggplot(mtcars, aes(fct_infreq(factor(cyl)))) +
geom_bar() +
labs(x = "cyl")

If you wanna go the other way around, you can use fct_rev() along with fct_infreq().

ggplot(mtcars, aes(fct_rev(fct_infreq(factor(cyl))))) +
geom_bar() +
labs(x = "cyl") 

enter image description here

What is the strict aliasing rule?

Technically in C++, the strict aliasing rule is probably never applicable.

Note the definition of indirection (* operator):

The unary * operator performs indirection: the expression to which it is applied shall be a pointer to an object type, or a pointer to a function type and the result is an lvalue referring to the object or function to which the expression points.

Also from the definition of glvalue

A glvalue is an expression whose evaluation determines the identity of an object, (...snip)

So in any well defined program trace, a glvalue refers to an object. So the so called strict aliasing rule doesn't apply, ever. This may not be what the designers wanted.

failed to find target with hash string android-23

Had the same issue with another number, this worked for me:

  1. Click the error message at top "Gradle project sync failed" where the text says ´Open message view´

  2. In the "Message Gradle Sync" window on the bottom left corner, click the provided solution "Install missing ... "

  3. Repeat 1 and 2 if necessary

23:08 Gradle sync failed: Failed to find target with hash string 'android-26' in: C:\Users\vik\AppData\Local\Android\Sdk

Android SDK providing a solution in the bottom left corner Android SDK providing a solution in the bottom left corner

How to get a Char from an ASCII Character Code in c#

Two options:

char c1 = '\u0001';
char c1 = (char) 1;

Jquery submit form

You can try like:

   $("#myformid").submit(function(){
        //perform anythng
   });

Or even you can try like

$(".nextbutton").click(function() { 
    $('#form1').submit();
});

yum error "Cannot retrieve metalink for repository: epel. Please verify its path and try again" updating ContextBroker

use this command:

sudo sed -i "s/mirrorlist=https/mirrorlist=http/" /etc/yum.repos.d/epel.repo

or alternatively use command

vi /etc/yum.repos.d/epel.repo

go to line number 4 and change the url from

mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-6&arch=$basearch

to

mirrorlist=http://mirrors.fedoraproject.org/metalink?repo=epel-6&arch=$basearch

CSS to set A4 paper size

I looked into this a bit more and the actual problem seems to be with assigning initial to page width under the print media rule. It seems like in Chrome width: initial on the .page element results in scaling of the page content if no specific length value is defined for width on any of the parent elements (width: initial in this case resolves to width: auto ... but actually any value smaller than the size defined under the @page rule causes the same issue).

So not only the content is now too long for the page (by about 2cm), but also the page padding will be slightly more than the initial 2cm and so on (it seems to render the contents under width: auto to the width of ~196mm and then scale the whole content up to the width of 210mm ~ but strangely exactly the same scaling factor is applied to contents with any width smaller than 210mm).

To fix this problem you can simply in the print media rule assign the A4 paper width and hight to html, body or directly to .page and in this case avoid the initial keyword.

DEMO

@page {
  size: A4;
  margin: 0;
}
@media print {
  html, body {
    width: 210mm;
    height: 297mm;
  }
  /* ... the rest of the rules ... */
}

This seems to keep everything else the way it is in your original CSS and fix the problem in Chrome (tested in different versions of Chrome under Windows, OS X and Ubuntu).

Undefined index with $_POST

Use:

if (isset($_POST['user'])) {
   //do something
}

But you probably should be using some more proper validation. Try a simple regex or a rock-solid implementation from Zend Framework or Symfony.

http://framework.zend.com/manual/en/zend.validate.introduction.html

http://symfony.com/doc/current/book/validation.html

Or even the built-in filter extension:

http://php.net/manual/en/function.filter-var.php

Never trust user input, be smart. Don't trust anything. Always make sure what you receive is really what you expect. If it should be a number, make SURE it's a number.

Much improved code:

$user = filter_var($_POST['user'], FILTER_SANITIZE_STRING);
$isValid = filter_var($user, FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => "/^[a-zA-Z0-9]+$/")));

if ($isValid) {
    // do something
}

Sanitization and validation.

How does "cat << EOF" work in bash?

Worth noting that here docs work in bash loops too. This example shows how-to get the column list of table:

export postgres_db_name='my_db'
export table_name='my_table_name'

# start copy 
while read -r c; do test -z "$c" || echo $table_name.$c , ; done < <(cat << EOF | psql -t -q -d $postgres_db_name -v table_name="${table_name:-}"
SELECT column_name
FROM information_schema.columns
WHERE 1=1
AND table_schema = 'public'
AND table_name   =:'table_name'  ;
EOF
)
# stop copy , now paste straight into the bash shell ...

output: 
my_table_name.guid ,
my_table_name.id ,
my_table_name.level ,
my_table_name.seq ,

or even without the new line

while read -r c; do test -z "$c" || echo $table_name.$c , | perl -ne 
's/\n//gm;print' ; done < <(cat << EOF | psql -t -q -d $postgres_db_name -v table_name="${table_name:-}"
 SELECT column_name
 FROM information_schema.columns
 WHERE 1=1
 AND table_schema = 'public'
 AND table_name   =:'table_name'  ;
 EOF
 )

 # output: daily_issues.guid ,daily_issues.id ,daily_issues.level ,daily_issues.seq ,daily_issues.prio ,daily_issues.weight ,daily_issues.status ,daily_issues.category ,daily_issues.name ,daily_issues.description ,daily_issues.type ,daily_issues.owner

How to find index of an object by key and value in an javascript array

function getIndexByAttribute(list, attr, val){
    var result = null;
    $.each(list, function(index, item){
        if(item[attr].toString() == val.toString()){
           result = index;
           return false;     // breaks the $.each() loop
        }
    });
    return result;
}

libpng warning: iCCP: known incorrect sRGB profile

Use pngcrush to remove the incorrect sRGB profile from the png file:

pngcrush -ow -rem allb -reduce file.png
  • -ow will overwrite the input file
  • -rem allb will remove all ancillary chunks except tRNS and gAMA
  • -reduce does lossless color-type or bit-depth reduction

In the console output you should see Removed the sRGB chunk, and possibly more messages about chunk removals. You will end up with a smaller, optimized PNG file. As the command will overwrite the original file, make sure to create a backup or use version control.

php exec() is not executing the command

I already said that I was new to exec() function. After doing some more digging, I came upon 2>&1 which needs to be added at the end of command in exec().

Thanks @mattosmat for pointing it out in the comments too. I did not try this at once because you said it is a Linux command, I am on Windows.

So, what I have discovered, the command is actually executing in the back-end. That is why I could not see it actually running, which I was expecting to happen.

For all of you, who had similar problem, my advise is to use that command. It will point out all the errors and also tell you info/details about execution.

exec('some_command 2>&1', $output);
print_r($output);  // to see the response to your command

Thanks for all the help guys, I appreciate it ;)

Segmentation Fault - C

Your scanf("%s", s); is commented out. That means s is uninitialized, so when this line ln = strlen(s); executes, you get a seg fault.

It always helps to initialize a pointer to NULL, and then test for null before using the pointer.

encapsulation vs abstraction real world example

I guess an egg shell can be consider the encapsulation and the contents the abstraction. The shell protects the information. You cant have the contents of an egg without the shell.,,LOL

How to suppress Update Links warning?

Excel 2016 I had a similar problem when I created a workbook/file and then I changed the names but somehow the old workbook name was kept. After a lot of googling... well, didn't find any final answer there...

Go to DATA -> Edit Link -> Startup Prompt (at the bottom) Then choose the best option for you.

The program can’t start because MSVCR71.dll is missing from your computer. Try reinstalling the program to fix this program

MY SOLUTION!!!!!!! I fixed this problem when I was trying to install business objects. When the installer failed to register .dll's I inputted the MSVCR71.dll into both system32 and sysWOW64 then clicked retry. Installation finished. I did try adding this in before and after install but, install still failed.

Android textview outline text

Here's the trick I found that works better than MagicTextView's stroke IMO

@Override
protected void onDraw(Canvas pCanvas) {
    int textColor = getTextColors().getDefaultColor();
    setTextColor(mOutlineColor); // your stroke's color
    getPaint().setStrokeWidth(10);
    getPaint().setStyle(Paint.Style.STROKE);
    super.onDraw(pCanvas);
    setTextColor(textColor);
    getPaint().setStrokeWidth(0);
    getPaint().setStyle(Paint.Style.FILL);
    super.onDraw(pCanvas);
}

What are Unwind segues for and how do you use them?

Something that I didn't see mentioned in the other answers here is how you deal with unwinding when you don't know where the initial segue originated, which to me is an even more important use case. For example, say you have a help view controller (H) that you display modally from two different view controllers (A and B):

A ? H
B ? H

How do you set up the unwind segue so that you go back to the correct view controller? The answer is that you declare an unwind action in A and B with the same name, e.g.:

// put in AViewController.swift and BViewController.swift
@IBAction func unwindFromHelp(sender: UIStoryboardSegue) {
    // empty
}

This way, the unwind will find whichever view controller (A or B) initiated the segue and go back to it.

In other words, think of the unwind action as describing where the segue is coming from, rather than where it is going to.

Dropping a connected user from an Oracle 10g database schema

Make sure that you alter the system and enable restricted session before you kill them or they will quickly log back into the database before you get your work completed.

Eclipse : Failed to connect to remote VM. Connection refused.

when you have Failed to connect to remote VM Connection refused error, restart your eclipse

How to insert new row to database with AUTO_INCREMENT column without specifying column names?

Even better, use DEFAULT instead of NULL. You want to store the default value, not a NULL that might trigger a default value.

But you'd better name all columns, with a piece of SQL you can create all the INSERT, UPDATE and DELETE's you need. Just check the information_schema and construct the queries you need. There is no need to do it all by hand, SQL can help you out.

What are the differences between a HashMap and a Hashtable in Java?

HashTable is a legacy class in the jdk that shouldn't be used anymore. Replace usages of it with ConcurrentHashMap. If you don't require thread safety, use HashMap which isn't threadsafe but faster and uses less memory.

What is a classpath and how do I set it?

CLASSPATH is an environment variable (i.e., global variables of the operating system available to all the processes) needed for the Java compiler and runtime to locate the Java packages used in a Java program. (Why not call PACKAGEPATH?) This is similar to another environment variable PATH, which is used by the CMD shell to find the executable programs.

CLASSPATH can be set in one of the following ways:

CLASSPATH can be set permanently in the environment: In Windows, choose control panel ? System ? Advanced ? Environment Variables ? choose "System Variables" (for all the users) or "User Variables" (only the currently login user) ? choose "Edit" (if CLASSPATH already exists) or "New" ? Enter "CLASSPATH" as the variable name ? Enter the required directories and JAR files (separated by semicolons) as the value (e.g., ".;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar"). Take note that you need to include the current working directory (denoted by '.') in the CLASSPATH.

To check the current setting of the CLASSPATH, issue the following command:

> SET CLASSPATH

CLASSPATH can be set temporarily for that particular CMD shell session by issuing the following command:

> SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar

Instead of using the CLASSPATH environment variable, you can also use the command-line option -classpath or -cp of the javac and java commands, for example,

> java –classpath c:\javaproject\classes com.abc.project1.subproject2.MyClass3

How to Deserialize XML document

You have two possibilities.

Method 1. XSD tool


Suppose that you have your XML file in this location C:\path\to\xml\file.xml

  1. Open Developer Command Prompt
    You can find it in Start Menu > Programs > Microsoft Visual Studio 2012 > Visual Studio Tools Or if you have Windows 8 can just start typing Developer Command Prompt in Start screen
  2. Change location to your XML file directory by typing cd /D "C:\path\to\xml"
  3. Create XSD file from your xml file by typing xsd file.xml
  4. Create C# classes by typing xsd /c file.xsd

And that's it! You have generated C# classes from xml file in C:\path\to\xml\file.cs

Method 2 - Paste special


Required Visual Studio 2012+

  1. Copy content of your XML file to clipboard
  2. Add to your solution new, empty class file (Shift+Alt+C)
  3. Open that file and in menu click Edit > Paste special > Paste XML As Classes
    enter image description here

And that's it!

Usage


Usage is very simple with this helper class:

using System;
using System.IO;
using System.Web.Script.Serialization; // Add reference: System.Web.Extensions
using System.Xml;
using System.Xml.Serialization;

namespace Helpers
{
    internal static class ParseHelpers
    {
        private static JavaScriptSerializer json;
        private static JavaScriptSerializer JSON { get { return json ?? (json = new JavaScriptSerializer()); } }

        public static Stream ToStream(this string @this)
        {
            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);
            writer.Write(@this);
            writer.Flush();
            stream.Position = 0;
            return stream;
        }


        public static T ParseXML<T>(this string @this) where T : class
        {
            var reader = XmlReader.Create(@this.Trim().ToStream(), new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Document });
            return new XmlSerializer(typeof(T)).Deserialize(reader) as T;
        }

        public static T ParseJSON<T>(this string @this) where T : class
        {
            return JSON.Deserialize<T>(@this.Trim());
        }
    }
}

All you have to do now, is:

    public class JSONRoot
    {
        public catalog catalog { get; set; }
    }
    // ...

    string xml = File.ReadAllText(@"D:\file.xml");
    var catalog1 = xml.ParseXML<catalog>();

    string json = File.ReadAllText(@"D:\file.json");
    var catalog2 = json.ParseJSON<JSONRoot>();

How do I verify that an Android apk is signed with a release certificate?

    1. unzip apk
    1. keytool -printcert -file ANDROID_.RSA or keytool -list -printcert -jarfile app.apk to obtain the hash md5
  • keytool -list -v -keystore clave-release.jks
  • compare the md5

https://www.eovao.com/en/a/signature%20apk%20android/3/how-to-verify-signature-of-.apk-android-archive

How can I pass a reference to a function, with parameters?

What you are after is called partial function application.

Don't be fooled by those that don't understand the subtle difference between that and currying, they are different.

Partial function application can be used to implement, but is not currying. Here is a quote from a blog post on the difference:

Where partial application takes a function and from it builds a function which takes fewer arguments, currying builds functions which take multiple arguments by composition of functions which each take a single argument.

This has already been answered, see this question for your answer: How can I pre-set arguments in JavaScript function call?

Example:

var fr = partial(f, 1, 2, 3);

// now, when you invoke fr() it will invoke f(1,2,3)
fr();

Again, see that question for the details.

What is the difference between buffer and cache memory in Linux?

Seth Robertson's Link 2 said "For thorough understanding of those terms, refer to Linux kernel book like Linux Kernel Development by Robert M. Love."

I found some contents about 'buffer' in the 2nd edition of the book.

Although the physical device itself is addressable at the sector level, the kernel performs all disk operations in terms of blocks.

When a block is stored in memory (say, after a read or pending a write), it is stored in a 'buffer'. Each 'buffer' is associated with exactly one block. The 'buffer' serves as the object that represents a disk block in memory.

A 'buffer' is the in-memory representation of a single physical disk block.

Block I/O operations manipulate a single disk block at a time. A common block I/O operation is reading and writing inodes. The kernel provides the bread() function to perform a low-level read of a single block from disk. Via 'buffers', disk blocks are mapped to their associated in-memory pages. "

Extract year from date

if all your dates are the same width, you can put the dates in a vector and use substring

Date
a <- c("01/01/2009", "01/01/2010" , "01/01/2011")
substring(a,7,10) #This takes string and only keeps the characters beginning in position 7 to position 10

output

[1] "2009" "2010" "2011"

How to debug in Django, the good way?

I find Visual Studio Code is awesome for debugging Django apps. The standard python launch.json parameters run python manage.py with the debugger attached, so you can set breakpoints and step through your code as you like.

Multiplying across in a numpy array

Normal multiplication like you showed:

>>> import numpy as np
>>> m = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> c = np.array([0,1,2])
>>> m * c
array([[ 0,  2,  6],
       [ 0,  5, 12],
       [ 0,  8, 18]])

If you add an axis, it will multiply the way you want:

>>> m * c[:, np.newaxis]
array([[ 0,  0,  0],
       [ 4,  5,  6],
       [14, 16, 18]])

You could also transpose twice:

>>> (m.T * c).T
array([[ 0,  0,  0],
       [ 4,  5,  6],
       [14, 16, 18]])

Safari 3rd party cookie iframe trick no longer working?

I recently hit the same issue on Safari. The solution I figured out is based on the Local Storage HTML5 API. Using Local Storage you could emulate cookies.

Here's my blog post with details: http://log.scalemotion.com/2012/10/how-to-trick-safari-and-set-3rd-party.html

include antiforgerytoken in ajax post ASP.NET MVC

it is so simple! when you use @Html.AntiForgeryToken() in your html code it means that server has signed this page and each request that is sent to server from this particular page has a sign that is prevented to send a fake request by hackers. so for this page to be authenticated by the server you should go through two steps:

1.send a parameter named __RequestVerificationToken and to gets its value use codes below:

<script type="text/javascript">
    function gettoken() {
        var token = '@Html.AntiForgeryToken()';
        token = $(token).val();
        return token;
   }
</script>

for example take an ajax call

$.ajax({
    type: "POST",
    url: "/Account/Login",
    data: {
        __RequestVerificationToken: gettoken(),
        uname: uname,
        pass: pass
    },
    dataType: 'json',
    contentType: 'application/x-www-form-urlencoded; charset=utf-8',
    success: successFu,
});

and step 2 just decorate your action method by [ValidateAntiForgeryToken]

Hiding the R code in Rmarkdown/knit and just showing the results

Sure, just do

```{r someVar, echo=FALSE}
someVariable
```

to show some (previously computed) variable someVariable. Or run code that prints etc pp.

So for plotting, I have eg

### Impact of choice of ....
```{r somePlot, echo=FALSE}
plotResults(Res, Grid, "some text", "some more text")
```

where the plotting function plotResults is from a local package.

How to set the component size with GridLayout? Is there a better way?

Don't use GridLayout for something it wasn't meant to do. It sounds to me like GridBagLayout would be a better fit for you, either that or MigLayout (though you'll have to download that first since it's not part of standard Java). Either that or combine layout managers such as BoxLayout for the lines and GridLayout to hold all the rows.

For example, using GridBagLayout:

import java.awt.*;
import javax.swing.*;

public class LayoutEg1 extends JPanel{
    private static final int ROWS = 10;

    public LayoutEg1() {
        setLayout(new GridBagLayout());
        for (int i = 0; i < ROWS; i++) {
            GridBagConstraints gbc = makeGbc(0, i);
            JLabel label = new JLabel("Row Label " + (i + 1));
            add(label, gbc);

            JPanel panel = new JPanel();
            panel.add(new JCheckBox("check box"));
            panel.add(new JTextField(10));
            panel.add(new JButton("Button"));
            panel.setBorder(BorderFactory.createEtchedBorder());
            gbc = makeGbc(1, i);
            add(panel, gbc);
        }
    }

    private GridBagConstraints makeGbc(int x, int y) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = 1;
        gbc.gridheight = 1;
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.weightx = x;
        gbc.weighty = 1.0;
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = (x == 0) ? GridBagConstraints.LINE_START : GridBagConstraints.LINE_END;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        return gbc;
    }

    private static void createAndShowUI() {
        JFrame frame = new JFrame("Layout Eg1");
        frame.getContentPane().add(new LayoutEg1());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                createAndShowUI();
            }
        });
    }
}

Getting one value from a tuple

You can write

i = 5 + tup()[0]

Tuples can be indexed just like lists.

The main difference between tuples and lists is that tuples are immutable - you can't set the elements of a tuple to different values, or add or remove elements like you can from a list. But other than that, in most situations, they work pretty much the same.

ActiveModel::ForbiddenAttributesError when creating new user

I guess you are using Rails 4. If so, the needed parameters must be marked as required.

You might want to do it like this:

class UsersController < ApplicationController

  def create
    @user = User.new(user_params)
    # ...
  end

  private

  def user_params
    params.require(:user).permit(:username, :email, :password, :salt, :encrypted_password)
  end
end

Does it matter what extension is used for SQLite database files?

If you have settled on a particular set of tools to access / modify your databases, I would go with whatever extension they expect you to use. This will avoid needless friction when doing development tasks.

For instance, SQLiteStudio v3.1.1 defaults to looking for files with the following extensions:

enter image description here

(db|sdb|sqlite|db3|s3db|sqlite3|sl3|db2|s2db|sqlite2|sl2)

If necessary for deployment your installation mechanism could rename the file if obscuring the file type seems useful to you (as some other answers have suggested). Filename requirements for development and deployment can be different.

Convert regular Python string to raw string

I suppose repr function can help you:

s = 't\n'
repr(s)
"'t\\n'"
repr(s)[1:-1]
't\\n'

How do I apply the for-each loop to every character in a String?

If you use Java 8, you can use chars() on a String to get a Stream of characters, but you will need to cast the int back to a char as chars() returns an IntStream.

"xyz".chars().forEach(i -> System.out.print((char)i));

If you use Java 8 with Eclipse Collections, you can use the CharAdapter class forEach method with a lambda or method reference to iterate over all of the characters in a String.

Strings.asChars("xyz").forEach(c -> System.out.print(c));

This particular example could also use a method reference.

Strings.asChars("xyz").forEach(System.out::print)

Note: I am a committer for Eclipse Collections.

How to set the environmental variable LD_LIBRARY_PATH in linux

  1. Go to the home folder and edit .profile
  2. Place the following line at the end

    export LD_LIBRARY_PATH=<your path>

  3. Save and Exit.

  4. Execute this command

    sudo ldconfig

How to start and stop/pause setInterval?

(function(){
    var i = 0;
    function stop(){
        clearTimeout(i);
    }

    function start(){
        i = setTimeout( timed, 1000 );
    }

    function timed(){
       document.getElementById("input").value++;
       start();
    }

    window.stop = stop;
    window.start = start;
})()

http://jsfiddle.net/TE3Z2/

The I/O operation has been aborted because of either a thread exit or an application request

I had the same issue with RS232 communication. The reason, is that your program executes much faster than the comport (or slow serial communication).

To fix it, I had to check if the IAsyncResult.IsCompleted==true. If not completed, then IAsyncResult.AsyncWaitHandle.WaitOne()

Like this :

Stream s = this.GetStream();
IAsyncResult ar = s.BeginWrite(data, 0, data.Length, SendAsync, state);
if (!ar.IsCompleted)
    ar.AsyncWaitHandle.WaitOne();

Most of the time, ar.IsCompleted will be true.

C Linking Error: undefined reference to 'main'

You are overwriting your object file runexp.o by running this command :

 gcc -o runexp.o scd.o data_proc.o -lm -fopenmp

In fact, the -o is for the output file. You need to run :

gcc -o runexp.out runexp.o scd.o data_proc.o -lm -fopenmp

runexp.out will be you binary file.

Creating a Custom Event

Yes you can create events on objects, here is an example;

public class Foo
{
    public delegate void MyEvent(object sender, object param);
    event MyEvent OnMyEvent;

    public Foo()
    {
        this.OnMyEvent += new MyEvent(Foo_OnMyEvent);
    }

    void Foo_OnMyEvent(object sender, object param)
    {
        if (this.OnMyEvent != null)
        {
            //do something
        }
    }



    void RaiseEvent()
    {
        object param = new object();
        this.OnMyEvent(this,param);
    }
}

How to link an image and target a new window

you can do like this

<a href="http://www.w3c.org/" target="_blank">W3C Home Page</a>

find this page

http://www.corelangs.com/html/links/new-window.html

goreb

How to do a subquery in LINQ?

Ok, here's a basic join query that gets the correct records:

   int[] selectedRolesArr = GetSelectedRoles();
    if( selectedRolesArr != null && selectedRolesArr.Length > 0 ) 
    {

    //this join version requires the use of distinct to prevent muliple records
        //being returned for users with more than one company role.
    IQueryable retVal = (from u in context.Users
                        join c in context.CompanyRolesToUsers
                          on u.Id equals c.UserId
                        where u.LastName.Contains( "fra" ) &&
                            selectedRolesArr.Contains( c.CompanyRoleId )
                        select  u).Distinct();
}

But here's the code that most easily integrates with the algorithm that we already had in place:

int[] selectedRolesArr = GetSelectedRoles(); 
if ( useAnd ) 
       { 
          predicateAnd = predicateAnd.And( u => (from c in context.CompanyRolesToUsers 
                       where selectedRolesArr.Contains(c.CompanyRoleId) 
                       select c.UserId).Contains(u.Id)); 
        } 
        else 
        { 
           predicateOr = predicateOr.Or( u => (from c in context.CompanyRolesToUsers 
                          where selectedRolesArr.Contains(c.CompanyRoleId) 
                         select c.UserId).Contains(u.Id) ); 
        } 

which is thanks to a poster at the LINQtoSQL forum

AngularJS - Create a directive that uses ng-model

This is a little late answer, but I found this awesome post about NgModelController, which I think is exactly what you were looking for.

TL;DR - you can use require: 'ngModel' and then add NgModelController to your linking function:

link: function(scope, iElement, iAttrs, ngModelCtrl) {
  //TODO
}

This way, no hacks needed - you are using Angular's built-in ng-model

Commands out of sync; you can't run this command now

I had today the same problem, but only when working with a stored procedure. This make the query behave like a multi query, so you need to "consume" other results available before make another query.

while($this->mysql->more_results()){
    $this->mysql->next_result();
    $this->mysql->use_result();
}

Android WebView not loading an HTTPS URL

Remove the below code it will work

 super.onReceivedSslError(view, handler, error);

Get css top value as number not as string?

A jQuery plugin based on M4N's answer

jQuery.fn.cssNumber = function(prop){
    var v = parseInt(this.css(prop),10);
    return isNaN(v) ? 0 : v;
};

So then you just use this method to get number values

$("#logo").cssNumber("top")

REST HTTP status codes for failed validation or invalid duplicate

I recommend status code 422, "Unprocessable Entity".

11.2. 422 Unprocessable Entity

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

Reload nginx configuration

If your system has systemctl

sudo systemctl reload nginx

If your system supports service (using debian/ubuntu) try this

sudo service nginx reload

If not (using centos/fedora/etc) you can try the init script

sudo /etc/init.d/nginx reload

Setting width/height as percentage minus pixels

Another way to achieve the same goal: flex boxes. Make the container a column flex box, and then you have all freedom to allow some elements to have fixed-size (default behavior) or to fill-up/shrink-down to the container space (with flex-grow:1 and flex-shrink:1).

#wrap {        
  display:flex;
  flex-direction:column;
}
.extendOrShrink {
  flex-shrink:1;
  flex-grow:1;
  overflow:auto;
}

See https://jsfiddle.net/2Lmodwxk/ (try to extend or reduce the window to notice the effect)

Note: you may also use the shorthand property:

   flex:1 1 auto;

How do I check if a string contains another string in Objective-C?

An improved version of P i's solution, a category on NSString, that not only will tell, if a string is found within another string, but also takes a range by reference, is:

@interface NSString (Contains)
-(BOOL)containsString: (NSString*)substring
              atRange:(NSRange*)range;

-(BOOL)containsString:(NSString *)substring;
@end

@implementation NSString (Contains)

-(BOOL)containsString:(NSString *)substring
              atRange:(NSRange *)range{

    NSRange r = [self rangeOfString : substring];
    BOOL found = ( r.location != NSNotFound );
    if (range != NULL) *range = r;
    return found;
}

-(BOOL)containsString:(NSString *)substring
{
    return [self containsString:substring
                        atRange:NULL];
}

@end

Use it like:

NSString *string = @"Hello, World!";

//If you only want to ensure a string contains a certain substring
if ([string containsString:@"ello" atRange:NULL]) {
    NSLog(@"YES");
}

// Or simply
if ([string containsString:@"ello"]) {
    NSLog(@"YES");
}

//If you also want to know substring's range
NSRange range;
if ([string containsString:@"ello" atRange:&range]) {
    NSLog(@"%@", NSStringFromRange(range));
}

In Java, how to append a string more efficiently?

You should use the StringBuilder class.

StringBuilder stringBuilder = new StringBuilder();

stringBuilder.append("Some text");
stringBuilder.append("Some text");
stringBuilder.append("Some text");

String finalString = stringBuilder.toString();

In addition, please visit:

When to create variables (memory management)

So notice variables are on the stack, the values they refer to are on the heap. So having variables is not too bad but yes they do create references to other entities. However in the simple case you describe it's not really any consequence. If it is never read again and within a contained scope, the compiler will probably strip it out before runtime. Even if it didn't the garbage collector will be able to safely remove it after the stack squashes. If you are running into issues where you have too many stack variables, it's usually because you have really deep stacks. The amount of stack space needed per thread is a better place to adjust than to make your code unreadable. The setting to null is also no longer needed

How to Set Opacity (Alpha) for View in Android

android:background="@android:color/transparent"

The above is something that I know... I think creating a custom button class is the best idea

API Level 11
Recently I came across this android:alpha xml attribute which takes a value between 0 and 1. The corresponding method is setAlpha(float).

CSS: Hover one element, effect for multiple elements?

You'd need to use JavaScript to accomplish this, I think.

jQuery:

$(function(){
   $("#innerContainer").hover(
        function(){
            $("#innerContainer").css('border-color','#FFF');
            $("#outerContainer").css('border-color','#FFF');
        },
        function(){
            $("#innerContainer").css('border-color','#000');
            $("#outerContainer").css('border-color','#000');
        }
    );
});

Adjust the values and element id's accordingly :)

This declaration has no storage class or type specifier in C++

Calling m.check(side), meaning you are running actual code, but you can't run code outside main() - you can only define variables. In C++, code can only appear inside function bodies or in variable initializes.

Get img src with PHP

$str = '<img border="0" src=\'/images/image.jpg\' alt="Image" width="100" height="100"/>';

preg_match('/(src=["\'](.*?)["\'])/', $str, $match);  //find src="X" or src='X'
$split = preg_split('/["\']/', $match[0]); // split by quotes

$src = $split[1]; // X between quotes

echo $src;

Other regexp's can be used to determine if the pulled src tag is a picture like so:

if(preg_match('/([jpg]{3}$)|([gif]{3}$)|([jpeg]{3}$)|([bmp]{3}$)|([png]{3}$)/', $src) == 1) {
//its an image
}

What are ABAP and SAP?

In addition to all the regular confusion around SAP issues might also stem form the fact that SAP used to have their own DBMS ..

It used to be called Adabas (marketed originally by Nixdorf and then by Software AG) and was a quite popular DBMS for smaller SAP (the ERP solution) installations in Germany. At some point (AFAIK around 2000) SAP started to co-develop/support/take over Adabas and marketed it as SAP DB and later MaxDB under commercial and open-source licenses. There also was/is some agreement with MySQL.

But when people talk about SAP, they usually refer to the ERP solution as the other posters have noted.

How do you dynamically add elements to a ListView on Android?

instead of

listItems.add("New Item");
adapter.notifyDataSetChanged();

you can directly call

adapter.add("New Item");

What is Mocking?

Other answers explain what mocking is. Let me walk you through it with different examples. And believe me, it's actually far more simpler than you think.

tl;dr It's an instance of the original class. It has other data injected into so you avoid testing the injected parts and solely focus on testing the implementation details of your class/functions.

Simple example:

class Foo {
    func add (num1: Int, num2: Int) -> Int { // Line A 
        return num1 + num2 // Line B
    }
}

let unit = Foo() // unit under test
assertEqual(unit.add(1,5),6)

As you can see, I'm not testing LineA ie I'm not validating the input parameters. I'm not validating to see if num1, num2 are an Integer. I have no asserts against that.

I'm only testing to see if LineB (my implementation) given the mocked values 1 and 5 is doing as I expect.

Obviously in the real word this can become much more complex. The parameters can be a custom object like a Person, Address, or the implementation details can be more than a single +. But the logic of testing would be the same.

Non-coding Example:

Assume you're building a machine that identifies the type and brand name of electronic devices for an airport security. The machine does this by processing what it sees with its camera.

Now your manager walks in the door and asks you to unit-test it.

Then you as a developer you can either bring 1000 real objects, like a MacBook pro, Google Nexus, a banana, an iPad etc in front of it and test and see if it all works.

But you can also use mocked objects, like an identical looking MacBook pro (with no real internal parts) or a plastic banana in front of it. You can save yourself from investing in 1000 real laptops and rotting bananas.

The point is you're not trying to test if the banana is fake or not. Nor testing if the laptop is fake or not. All you're doing is testing if your machine once it sees a banana it would say not an electronic device and for a MacBook Pro it would say: Laptop, Apple. To the machine, the outcome of its detection should be the same for fake/mocked electronics and real electronics. If your machine also factored in the internals of a laptop (x-ray scan) or banana then your mocks' internals need to look the same as well. But you could also use a gadget with a friend motherboard. Had your machine tested whether or not devices can power on then well you'd need real devices.

The logic mentioned above applies to unit-testing of actual code as well. That is a function should work the same with real values you get from real input (and interactions) or mocked values you inject during unit-testing. And just as how you save yourself from using a real banana or MacBook, with unit-tests (and mocking) you save yourself from having to do something that causes your server to return a status code of 500, 403, 200, etc (forcing your server to trigger 500 is only when server is down, while 200 is when server is up. It gets difficult to run 100 network focused tests if you have to constantly wait 10 seconds between switching over server up and down). So instead you inject/mock a response with status code 500, 200, 403, etc and test your unit/function with a injected/mocked value.

Be aware:

Sometimes you don't correctly mock the actual object. Or you don't mock every possibility. E.g. your fake laptops are dark, and your machine accurately works with them, but then it doesn't work accurately with white fake laptops. Later when you ship this machine to customers they complain that it doesn't work all the time. You get random reports that it's not working. It takes you 3 months of time to finally figure out that the color of fake laptops need to be more varied so you can test your modules appropriately.

For a true coding example, your implementation may be different for status code 200 with image data returned vs 200 with image data not returned. For this reason it's good to use an IDE that provides code coverage e.g. the image below shows that your unit-tests don't ever go through the lines marked with brown.

enter image description here

image source

Real world coding Example:

Let's say you are writing an iOS application and have network calls.Your job is to test your application. To test/identify whether or not the network calls work as expected is NOT YOUR RESPONSIBILITY . It's another party's (server team) responsibility to test it. You must remove this (network) dependency and yet continue to test all your code that works around it.

A network call can return different status codes 404, 500, 200, 303, etc with a JSON response.

Your app is suppose to work for all of them (in case of errors, your app should throw its expected error). What you do with mocking is you create 'imaginary—similar to real' network responses (like a 200 code with a JSON file) and test your code without 'making the real network call and waiting for your network response'. You manually hardcode/return the network response for ALL kinds of network responses and see if your app is working as you expect. (you never assume/test a 200 with incorrect data, because that is not your responsibility, your responsibility is to test your app with a correct 200, or in case of a 400, 500, you test if your app throws the right error)

This creating imaginary—similar to real is known as mocking.

In order to do this, you can't use your original code (your original code doesn't have the pre-inserted responses, right?). You must add something to it, inject/insert that dummy data which isn't normally needed (or a part of your class).

So you create an instance the original class and add whatever (here being the network HTTPResponse, data OR in the case of failure, you pass the correct errorString, HTTPResponse) you need to it and then test the mocked class.

Long story short, mocking is to simplify and limit what you are testing and also make you feed what a class depends on. In this example you avoid testing the network calls themselves, and instead test whether or not your app works as you expect with the injected outputs/responses —— by mocking classes

Needless to say, you test each network response separately.


Now a question that I always had in my mind was: The contracts/end points and basically the JSON response of my APIs get updated constantly. How can I write unit tests which take this into consideration?

To elaborate more on this: let’s say model requires a key/field named username. You test this and your test passes. 2 weeks later backend changes the key's name to id. Your tests still passes. right? or not?

Is it the backend developer’s responsibility to update the mocks. Should it be part of our agreement that they provide updated mocks?

The answer to the above issue is that: unit tests + your development process as a client-side developer should/would catch outdated mocked response. If you ask me how? well the answer is:

Our actual app would fail (or not fail yet not have the desired behavior) without using updated APIs...hence if that fails...we will make changes on our development code. Which again leads to our tests failing....which we’ll have to correct it. (Actually if we are to do the TDD process correctly we are to not write any code about the field unless we write the test for it...and see it fail and then go and write the actual development code for it.)

This all means that backend doesn’t have to say: “hey we updated the mocks”...it eventually happens through your code development/debugging. ??Because it’s all part of the development process! Though if backend provides the mocked response for you then it's easier.

My whole point on this is that (if you can’t automate getting updated mocked API response then) some human interaction is required ie manual updates of JSONs and having short meetings to make sure their values are up to date will become part of your process

This section was written thanks to a slack discussion in our CocoaHead meetup group


For iOS devs only:

A very good example of mocking is this Practical Protocol-Oriented talk by Natasha Muraschev. Just skip to minute 18:30, though the slides may become out of sync with the actual video ???

I really like this part from the transcript:

Because this is testing...we do want to make sure that the get function from the Gettable is called, because it can return and the function could theoretically assign an array of food items from anywhere. We need to make sure that it is called;

How to determine the version of Gradle?

Option 1- From Studio

In Android Studio, go to File > Project Structure. Then select the "project" tab on the left.

Your Gradle version will be displayed here.

Option 2- gradle-wrapper.properties

If you are using the Gradle wrapper, then your project will have a gradle/wrapper/gradle-wrapper.properties folder.

This file should contain a line like this:

distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip

This determines which version of Gradle you are using. In this case, gradle-2.2.1-all.zip means I am using Gradle 2.2.1.

Option 3- Local Gradle distribution

If you are using a version of Gradle installed on your system instead of the wrapper, you can run gradle --version to check.

How to retrieve raw post data from HttpServletRequest in java

The request body is available as byte stream by HttpServletRequest#getInputStream():

InputStream body = request.getInputStream();
// ...

Or as character stream by HttpServletRequest#getReader():

Reader body = request.getReader();
// ...

Note that you can read it only once. The client ain't going to resend the same request multiple times. Calling getParameter() and so on will implicitly also read it. If you need to break down parameters later on, you've got to store the body somewhere and process yourself.

What is the difference between properties and attributes in HTML?

The answers already explain how attributes and properties are handled differently, but I really would like to point out how totally insane this is. Even if it is to some extent the spec.

It is crazy, to have some of the attributes (e.g. id, class, foo, bar) to retain only one kind of value in the DOM, while some attributes (e.g. checked, selected) to retain two values; that is, the value "when it was loaded" and the value of the "dynamic state". (Isn't the DOM supposed to be to represent the state of the document to its full extent?)

It is absolutely essential, that two input fields, e.g. a text and a checkbox behave the very same way. If the text input field does not retain a separate "when it was loaded" value and the "current, dynamic" value, why does the checkbox? If the checkbox does have two values for the checked attribute, why does it not have two for its class and id attributes? If you expect to change the value of a text *input* field, and you expect the DOM (i.e. the "serialized representation") to change, and reflect this change, why on earth would you not expect the same from an input field of type checkbox on the checked attribute?

The differentiation, of "it is a boolean attribute" just does not make any sense to me, or is, at least not a sufficient reason for this.

How to call another controller Action From a controller in Mvc

As @mxmissile says in the comments to the accepted answer, you shouldn't new up the controller because it will be missing dependencies set up for IoC and won't have the HttpContext.

Instead, you should get an instance of your controller like this:

var controller = DependencyResolver.Current.GetService<ControllerB>();
controller.ControllerContext = new ControllerContext(this.Request.RequestContext, controller);

Angular ngClass and click event for toggling class

So normally you would create a backing variable in the class and toggle it on click and tie a class binding to the variable. Something like:

@Component(
    selector:'foo',
    template:`<a (click)="onClick()"
                         [class.selected]="wasClicked">Link</a>
    `)
export class MyComponent {
    wasClicked = false;

    onClick() {
        this.wasClicked= !this.wasClicked;
    }
}

How do browser cookie domains work?

Although there is the RFC 2965 (Set-Cookie2, had already obsoleted RFC 2109) that should define the cookie nowadays, most browsers don’t fully support that but just comply to the original specification by Netscape.

There is a distinction between the Domain attribute value and the effective domain: the former is taken from the Set-Cookie header field and the latter is the interpretation of that attribute value. According to the RFC 2965, the following should apply:

  • If the Set-Cookie header field does not have a Domain attribute, the effective domain is the domain of the request.
  • If there is a Domain attribute present, its value will be used as effective domain (if the value does not start with a . it will be added by the client).

Having the effective domain it must also domain-match the current requested domain for being set; otherwise the cookie will be revised. The same rule applies for choosing the cookies to be sent in a request.


Mapping this knowledge onto your questions, the following should apply:

  • Cookie with Domain=.example.com will be available for www.example.com
  • Cookie with Domain=.example.com will be available for example.com
  • Cookie with Domain=example.com will be converted to .example.com and thus will also be available for www.example.com
  • Cookie with Domain=example.com will not be available for anotherexample.com
  • www.example.com will be able to set cookie for example.com
  • www.example.com will not be able to set cookie for www2.example.com
  • www.example.com will not be able to set cookie for .com

And to set and read a cookie for/by www.example.com and example.com, set it for .www.example.com and .example.com respectively. But the first (.www.example.com) will only be accessible for other domains below that domain (e.g. foo.www.example.com or bar.www.example.com) where .example.com can also be accessed by any other domain below example.com (e.g. foo.example.com or bar.example.com).

Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed

net use \\<host> /delete should work, but many times it does not.

net stop workstation as @DaveInCaz offered works in such cases.

I have some why and hows I couldn't fit into a comment.

  • It's not enough to restart the Workstation service (e.g. from services.msc console)
    The service probably needs to be disabled for some short period of time. If you do this restart from a script, might be better to add a 1 second delay.

  • In cases when net use \\<host> /delete does not work because another program is still using that share, you can identify such program and remove the blocking handle without closing it. Use Sysinternals Process Explorer, press Ctrl+F for search and enter the name of host machine owning such share. Click on each result, program window behind search dialog jumps to found program's handle. Right click that handle and select Close Handle. (or just close such program if you can) This works only in regular cases where there really is a program blocking the share disconnect. Not in those weird cases when it's blocked for no reason.

  • elevated account has it's own environment. This brings some unexpected behavior.
    If you do net use command in an elevated cmd/PS console, it will not affect which user will Windows Explorer use to access the share.
    And also other way around, if you run a program from the share and the program will ask and get elevated access, that program will loose connection to that share and any files it might need to run. You need to run net use from elevated cmd/PS to create an elevated share connection to that share.

  • Removing Recent folders from Quick Access in Windows Explorer (top of left panel) might help in certain cases.
    If the Host you are connecting to offers different access levels based on user, and/or has a Guest user (anonymous) share access, this is a situation you might often run into.
    When you access a share using your username, folder inside such share might get assigned to Quick Access panel as a Recent item. When you open Windows Explorer after restart, Recent items inside Quick Access will be checked and a connection will be made to the Host machine and will stay open in form of a MUP. If your share accepts both authorized and anonymous connections, just opening Windows Explorer will create anonymous connection and when you click on a share which needs authorization, you will not get credential dialog but an error.

Converting ISO 8601-compliant String to java.util.Date

The DatatypeConverter solution doesn't work in all VMs. The following works for me:

javax.xml.datatype.DatatypeFactory.newInstance().newXMLGregorianCalendar("2011-01-01Z").toGregorianCalendar().getTime()

I've found that joda does not work out of the box (specifically for the example I gave above with the timezone on a date, which should be valid)

In a javascript array, how do I get the last 5 elements, excluding the first element?

You can call:

arr.slice(Math.max(arr.length - 5, 1))

If you don't want to exclude the first element, use

arr.slice(Math.max(arr.length - 5, 0))

Database Structure for Tree Data Structure

If you have to use Relational DataBase to organize tree data structure then Postgresql has cool ltree module that provides data type for representing labels of data stored in a hierarchical tree-like structure. You can get the idea from there.(For more information see: http://www.postgresql.org/docs/9.0/static/ltree.html)

In common LDAP is used to organize records in hierarchical structure.

What is the difference between min SDK version/target SDK version vs. compile SDK version?

The formula is

minSdkVersion <= targetSdkVersion <= compileSdkVersion

minSdkVersion - is a marker that defines a minimum Android version on which application will be able to install. Also it is used by Lint to prevent calling API that doesn’t exist. Also it has impact on Build Time. So you can use build flavors to override minSdkVersion to maximum during the development. It will help to make build faster using all improvements that the Android team provides for us. For example some features Java 8 are available only from specific version of minSdkVersion.

targetSdkVersion - If AndroidOS version is >= targetSdkVersion it says Android system to turn on specific(new) behavior changes. *Please note that some of new behaviors will be turned on by default even if thought targetSdkVersion is <, you should read official doc.

For example:

  • Starting in Android 6.0 (API level 23) Runtime Permissions were introduced. If you set targetSdkVersion to 22 or lower your application does not ask a user for some permission in run time.

  • Starting in Android 8.0 (API level 26), all notifications must be assigned to a channel or it will not appear. On devices running Android 7.1 (API level 25) and lower, users can manage notifications on a per-app basis only (effectively each app only has one channel on Android 7.1 and lower).

  • Starting in Android 9 (API level 28), Web-based data directories separated by process. If targetSdkVersion is 28+ and you create several WebView in different processes you will get java.lang.RuntimeException

compileSdkVersion - actually it is SDK Platform version and tells Gradle which Android SDK use to compile. When you want to use new features or debug .java files from Android SDK you should take care of compileSdkVersion. One more example is using AndroidX that forces to use compileSdkVersion - level 28. compileSdkVersion is not included in your APK: it is purely used at compile time. Changing your compileSdkVersion does not change runtime behavior. It can generate for example new compiler warnings/errors. Therefore it is strongly recommended that you always compile with the latest SDK. You’ll get all the benefits of new compilation checks on existing code, avoid newly deprecated APIs, and be ready to use new APIs. One more fact is compileSdkVersion >= Support Library version

You can read more about it here. Also I would recommend you to take a look at the example of migration to Android 8.0.

[buildToolsVersion]

Drop unused factor levels in a subsetted data frame

Here's another way, which I believe is equivalent to the factor(..) approach:

> df <- data.frame(let=letters[1:5], num=1:5)
> subdf <- df[df$num <= 3, ]

> subdf$let <- subdf$let[ , drop=TRUE]

> levels(subdf$let)
[1] "a" "b" "c"

Change New Google Recaptcha (v2) Width

A bit late but I've got an easy workaround:

Just add this code to your "g-recaptcha" class:

width: desired_width;

border-radius: 4px;
border-right: 1px solid #d8d8d8;
overflow: hidden;

How to capture multiple repeated groups?

Just to provide additional example of paragraph 2 in the answer. I'm not sure how critical it is for you to get three groups in one match rather than three matches using one group. E.g., in groovy:

def subject = "HELLO,THERE,WORLD"
def pat = "([A-Z]+)"
def m = (subject =~ pat)
m.eachWithIndex{ g,i ->
  println "Match #$i: ${g[1]}"
}

Match #0: HELLO
Match #1: THERE
Match #2: WORLD

What is sys.maxint in Python 3?

As pointed out by others, Python 3's int does not have a maximum size, but if you just need something that's guaranteed to be higher than any other int value, then you can use the float value for Infinity, which you can get with float("inf").

IIS7 Cache-Control

That's not true Jeff.

You simply have to select a folder within your IIS 7 Manager UI (e.g. Images or event the Default Web Application folder) and then click on "HTTP Response Headers". Then you have to click on "Set Common Header.." in the right pane and select the "Expire Web content". There you can easily configure a max-age of 24 hours by choosing "After:", entering "24" in the Textbox and choose "Hours" in the combobox.

Your first paragraph regarding the web.config entry is right. I'd add the cacheControlCustom-attribute to set the cache control header to "public" or whatever is needed in that case.

You can, of course, achieve the same by providing web.config entries (or files) as needed.

Edit: removed a confusing sentence :)

How to make a GridLayout fit screen size

Note: The information below the horizontal line is no longer accurate with the introduction of Android 'Lollipop' 5, as GridLayout does accommodate the principle of weights since API level 21.

Quoted from the Javadoc:

Excess Space Distribution

As of API 21, GridLayout's distribution of excess space accomodates the principle of weight. In the event that no weights are specified, the previous conventions are respected and columns and rows are taken as flexible if their views specify some form of alignment within their groups. The flexibility of a view is therefore influenced by its alignment which is, in turn, typically defined by setting the gravity property of the child's layout parameters. If either a weight or alignment were defined along a given axis then the component is taken as flexible in that direction. If no weight or alignment was set, the component is instead assumed to be inflexible.

Multiple components in the same row or column group are considered to act in parallel. Such a group is flexible only if all of the components within it are flexible. Row and column groups that sit either side of a common boundary are instead considered to act in series. The composite group made of these two elements is flexible if one of its elements is flexible.

To make a column stretch, make sure all of the components inside it define a weight or a gravity. To prevent a column from stretching, ensure that one of the components in the column does not define a weight or a gravity.

When the principle of flexibility does not provide complete disambiguation, GridLayout's algorithms favour rows and columns that are closer to its right and bottom edges. To be more precise, GridLayout treats each of its layout parameters as a constraint in the a set of variables that define the grid-lines along a given axis. During layout, GridLayout solves the constraints so as to return the unique solution to those constraints for which all variables are less-than-or-equal-to the corresponding value in any other valid solution.

It's also worth noting that android.support.v7.widget.GridLayout contains the same information. Unfortunately it doesn't mention which version of the support library it was introduced with, but the commit that adds the functionality can be tracked back to July 2014. In November 2014, improvements in weight calculation and a bug was fixed.

To be safe, make sure to import the latest version of the gridlayout-v7 library.


The principle of 'weights', as you're describing it, does not exist with GridLayout. This limitation is clearly mentioned in the documentation; excerpt below. That being said, there are some possibilities to use 'gravity' for excess space distribution. I suggest you have read through the linked documentation.

Limitations

GridLayout does not provide support for the principle of weight, as defined in weight. In general, it is not therefore possible to configure a GridLayout to distribute excess space in non-trivial proportions between multiple rows or columns. Some common use-cases may nevertheless be accommodated as follows. To place equal amounts of space around a component in a cell group; use CENTER alignment (or gravity). For complete control over excess space distribution in a row or column; use a LinearLayout subview to hold the components in the associated cell group. When using either of these techniques, bear in mind that cell groups may be defined to overlap.

For an example and some practical pointers, take a look at last year's blog post introducing the GridLayout widget.


Edit: I don't think there's an xml-based approach to scaling the tiles like in the Google Play app to 'squares' or 'rectangles' twice the length of those squares. However, it is certainly possible if you build your layout programmatically. All you really need to know in order two accomplish that is the device's screen dimensions.

Below a (very!) quick 'n dirty approximation of the tiled layout in the Google Play app.

Point size = new Point();
getWindowManager().getDefaultDisplay().getSize(size);
int screenWidth = size.x;
int screenHeight = size.y;
int halfScreenWidth = (int)(screenWidth *0.5);
int quarterScreenWidth = (int)(halfScreenWidth * 0.5);

Spec row1 = GridLayout.spec(0, 2);
Spec row2 = GridLayout.spec(2);
Spec row3 = GridLayout.spec(3);
Spec row4 = GridLayout.spec(4, 2);

Spec col0 = GridLayout.spec(0);
Spec col1 = GridLayout.spec(1); 
Spec colspan2 = GridLayout.spec(0, 2);

GridLayout gridLayout = new GridLayout(this);
gridLayout.setColumnCount(2);
gridLayout.setRowCount(15);

TextView twoByTwo1 = new TextView(this);
GridLayout.LayoutParams first = new GridLayout.LayoutParams(row1, colspan2);
first.width = screenWidth;
first.height = quarterScreenWidth * 2;
twoByTwo1.setLayoutParams(first);
twoByTwo1.setGravity(Gravity.CENTER);
twoByTwo1.setBackgroundColor(Color.RED);
twoByTwo1.setText("TOP");
twoByTwo1.setTextAppearance(this, android.R.style.TextAppearance_Large);
gridLayout.addView(twoByTwo1, first);

TextView twoByOne1 = new TextView(this);
GridLayout.LayoutParams second = new GridLayout.LayoutParams(row2, col0);
second.width = halfScreenWidth;
second.height = quarterScreenWidth;
twoByOne1.setLayoutParams(second);
twoByOne1.setBackgroundColor(Color.BLUE);
twoByOne1.setText("Staff Choices");
twoByOne1.setTextAppearance(this, android.R.style.TextAppearance_Large);
gridLayout.addView(twoByOne1, second);

TextView twoByOne2 = new TextView(this);
GridLayout.LayoutParams third = new GridLayout.LayoutParams(row2, col1);
third.width = halfScreenWidth;
third.height = quarterScreenWidth;
twoByOne2.setLayoutParams(third);
twoByOne2.setBackgroundColor(Color.GREEN);
twoByOne2.setText("Games");
twoByOne2.setTextAppearance(this, android.R.style.TextAppearance_Large);
gridLayout.addView(twoByOne2, third);

TextView twoByOne3 = new TextView(this);
GridLayout.LayoutParams fourth = new GridLayout.LayoutParams(row3, col0);
fourth.width = halfScreenWidth;
fourth.height = quarterScreenWidth;
twoByOne3.setLayoutParams(fourth);
twoByOne3.setBackgroundColor(Color.YELLOW);
twoByOne3.setText("Editor's Choices");
twoByOne3.setTextAppearance(this, android.R.style.TextAppearance_Large_Inverse);
gridLayout.addView(twoByOne3, fourth);

TextView twoByOne4 = new TextView(this);
GridLayout.LayoutParams fifth = new GridLayout.LayoutParams(row3, col1);
fifth.width = halfScreenWidth;
fifth.height = quarterScreenWidth;
twoByOne4.setLayoutParams(fifth);
twoByOne4.setBackgroundColor(Color.MAGENTA);
twoByOne4.setText("Something Else");
twoByOne4.setTextAppearance(this, android.R.style.TextAppearance_Large);
gridLayout.addView(twoByOne4, fifth);

TextView twoByTwo2 = new TextView(this);
GridLayout.LayoutParams sixth = new GridLayout.LayoutParams(row4, colspan2);
sixth.width = screenWidth;
sixth.height = quarterScreenWidth * 2;
twoByTwo2.setLayoutParams(sixth);
twoByTwo2.setGravity(Gravity.CENTER);
twoByTwo2.setBackgroundColor(Color.WHITE);
twoByTwo2.setText("BOTOM");
twoByTwo2.setTextAppearance(this, android.R.style.TextAppearance_Large_Inverse);
gridLayout.addView(twoByTwo2, sixth);

The result will look somewhat like this (on my Galaxy Nexus):

Tiled layout using GridLayout

How to check if a number is between two values?

I just implemented this bit of jQuery to show and hide bootstrap modal values. Different fields are displayed based on the value range of a users textbox entry.

$(document).ready(function () {
    jQuery.noConflict();
    var Ammount = document.getElementById('Ammount');

    $("#addtocart").click(function () {

            if ($(Ammount).val() >= 250 && $(Ammount).val() <= 499) {
                {
                    $('#myModal').modal();
                    $("#myModalLabelbronze").show();
                    $("#myModalLabelsilver").hide();
                    $("#myModalLabelgold").hide();
                    $("#myModalPbronze").show();
                    $("#myModalPSilver").hide();
                    $("#myModalPGold").hide();
                }
            }
    });

Set a request header in JavaScript

@gnarf answer is right . wanted to add more information .

Mozilla Bug Reference : https://bugzilla.mozilla.org/show_bug.cgi?id=627942

Terminate these steps if header is a case-insensitive match for one of the following headers:

Accept-Charset
Accept-Encoding
Access-Control-Request-Headers
Access-Control-Request-Method
Connection
Content-Length
Cookie
Cookie2
Date
DNT
Expect
Host
Keep-Alive
Origin
Referer
TE
Trailer
Transfer-Encoding
Upgrade
User-Agent
Via

Source : https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-setrequestheader

Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio

Target parameters:

float width = 1024;
float height = 768;
var brush = new SolidBrush(Color.Black);

Your original file:

var image = new Bitmap(file);

Target sizing (scale factor):

float scale = Math.Min(width / image.Width, height / image.Height);

The resize including brushing canvas first:

var bmp = new Bitmap((int)width, (int)height);
var graph = Graphics.FromImage(bmp);

// uncomment for higher quality output
//graph.InterpolationMode = InterpolationMode.High;
//graph.CompositingQuality = CompositingQuality.HighQuality;
//graph.SmoothingMode = SmoothingMode.AntiAlias;

var scaleWidth = (int)(image.Width * scale);
var scaleHeight = (int)(image.Height * scale);

graph.FillRectangle(brush, new RectangleF(0, 0, width, height));
graph.DrawImage(image, ((int)width - scaleWidth)/2, ((int)height - scaleHeight)/2, scaleWidth, scaleHeight);

And don't forget to do a bmp.Save(filename) to save the resulting file.

Assert an object is a specific type

Solution for JUnit 5

The documentation says:

However, JUnit Jupiter’s org.junit.jupiter.Assertions class does not provide an assertThat() method like the one found in JUnit 4’s org.junit.Assert class which accepts a Hamcrest Matcher. Instead, developers are encouraged to use the built-in support for matchers provided by third-party assertion libraries.

Example for Hamcrest:

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.jupiter.api.Test;

class HamcrestAssertionDemo {

    @Test
    void assertWithHamcrestMatcher() {
        SubClass subClass = new SubClass();
        assertThat(subClass, instanceOf(BaseClass.class));
    }

}

Example for AssertJ:

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;

class AssertJDemo {

    @Test
    void assertWithAssertJ() {
        SubClass subClass = new SubClass();
        assertThat(subClass).isInstanceOf(BaseClass.class);
    }

}

Note that this assumes you want to test behaviors similar to instanceof (which accepts subclasses). If you want exact equal type, I don’t see a better way than asserting the two class to be equal like you mentioned in the question.

How to escape special characters of a string with single backslashes

Simply using re.sub might also work instead of str.maketrans. And this would also work in python 2.x

>>> print(re.sub(r'(\-|\]|\^|\$|\*|\.|\\)',lambda m:{'-':'\-',']':'\]','\\':'\\\\','^':'\^','$':'\$','*':'\*','.':'\.'}[m.group()],"^stack.*/overflo\w$arr=1"))
\^stack\.\*/overflo\\w\$arr=1

How to convert 2D float numpy array to 2D int numpy array?

you can use np.int_:

>>> x = np.array([[1.0, 2.3], [1.3, 2.9]])
>>> x
array([[ 1. ,  2.3],
       [ 1.3,  2.9]])
>>> np.int_(x)
array([[1, 2],
       [1, 2]])

Finding the max/min value in an array of primitives using Java

import java.util.Random;

public class Main {

public static void main(String[] args) {
   int a[] = new int [100];
   Random rnd = new Random ();

    for (int i = 0; i< a.length; i++) {
        a[i] = rnd.nextInt(99-0)+0;
        System.out.println(a[i]);
    }

    int max = 0;          

    for (int i = 0; i < a.length; i++) {
        a[i] = max;


        for (int j = i+1; j<a.length; j++) {
            if (a[j] > max) {
               max = a[j];
            }

        }
    }

    System.out.println("Max element: " + max);
}
}

Regex replace uppercase with lowercase letters

In BBEdit works this (ex.: changing the ID values to lowercase):

Search any value: <a id="(?P<x>.*?)"></a> Replace with the same in lowercase: <a id="\L\P<x>\E"></a>

Was: <a id="VALUE"></a> Became: <a id="value"></a>

Given URL is not permitted by the application configuration

Missing from the other answers is how to allow localhost(or 0.0.0.0 or whatever) as an oauth callback url. Here is the explanation. How can I add localhost:3000 to Facebook App for development

How to get Rails.logger printing to the console/stdout when running rspec?

Tail the log as a background job (&) and it will interleave with rspec output.

tail -f log/test.log &
bundle exec rspec

PHP append one array to another (not array_push or +)

Before PHP7 you can use:

array_splice($a, count($a), 0, $b);

array_splice() operates with reference to array (1st argument) and puts array (4th argument) values in place of list of values started from 2nd argument and number of 3rd argument. When we set 2nd argument as end of source array and 3rd as zero we append 4th argument values to 1st argument

The module ".dll" was loaded but the entry-point was not found

I had this problem and

dumpbin /exports mydll.dll

and

depends mydll.dll

showed 'DllRegisterServer'.

The problem was that there was another DLL in the system that had the same name. After renaming mydll the registration succeeded.

Centering floating divs within another div

The following solution does not use inline blocks. However, it requires two helper divs:

  1. The content is floated
  2. The inner helper is floated (it stretches as much as the content)
  3. The inner helper is pushed right 50% (its left aligns with center of outer helper)
  4. The content is pulled left 50% (its center aligns with left of inner helper)
  5. The outer helper is set to hide the overflow

_x000D_
_x000D_
.ca-outer {_x000D_
  overflow: hidden;_x000D_
  background: #FFC;_x000D_
}_x000D_
.ca-inner {_x000D_
  float: left;_x000D_
  position: relative;_x000D_
  left: 50%;_x000D_
  background: #FDD;_x000D_
}_x000D_
.content {_x000D_
  float: left;_x000D_
  position: relative;_x000D_
  left: -50%;_x000D_
  background: #080;_x000D_
}_x000D_
/* examples */_x000D_
div.content > div {_x000D_
  float: left;_x000D_
  margin: 10px;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: #FFF;_x000D_
}_x000D_
ul.content {_x000D_
  padding: 0;_x000D_
  list-style-type: none;_x000D_
}_x000D_
ul.content > li {_x000D_
  margin: 10px;_x000D_
  background: #FFF;_x000D_
}
_x000D_
<div class="ca-outer">_x000D_
  <div class="ca-inner">_x000D_
    <div class="content">_x000D_
      <div>Box 1</div>_x000D_
      <div>Box 2</div>_x000D_
      <div>Box 3</div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<hr>_x000D_
<div class="ca-outer">_x000D_
  <div class="ca-inner">_x000D_
    <ul class="content">_x000D_
      <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>_x000D_
      <li>Nullam efficitur nulla in libero consectetur dictum ac a sem.</li>_x000D_
      <li>Suspendisse iaculis risus ut dapibus cursus.</li>_x000D_
    </ul>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

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

It seems you are hitting a UTF-8 byte order mark (BOM). Try using this unicode string with BOM extracted out:

import codecs

content = unicode(q.content.strip(codecs.BOM_UTF8), 'utf-8')
parser.parse(StringIO.StringIO(content))

I used strip instead of lstrip because in your case you had multiple occurences of BOM, possibly due to concatenated file contents.

java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

I was facing the same Issue. When I saw into maven repository .m2 folder(....m2\repository\org\springframework\spring-webmvc) in my local I found two 3.2.0.RELEASE folders. SO I removed one. Then I went to project, right click->properties->deployment essembly-> add maven dependencies. clean build and then restart the server. Then the DispatcherServlet got loaded.

Python Hexadecimal

Use the format() function with a '02x' format.

>>> format(255, '02x')
'ff'
>>> format(2, '02x')
'02'

The 02 part tells format() to use at least 2 digits and to use zeros to pad it to length, x means lower-case hexadecimal.

The Format Specification Mini Language also gives you X for uppercase hex output, and you can prefix the field width with # to include a 0x or 0X prefix (depending on wether you used x or X as the formatter). Just take into account that you need to adjust the field width to allow for those extra 2 characters:

>>> format(255, '02X')
'FF'
>>> format(255, '#04x')
'0xff'
>>> format(255, '#04X')
'0XFF'

Change Oracle port from port 8080

Execute Exec DBMS_XDB.SETHTTPPORT(8181); as SYS/SYSTEM. Replace 8181 with the port you'd like changing to. Tested this with Oracle 10g.

Source : http://hodentekhelp.blogspot.com/2008/08/my-oracle-10g-xe-is-on-port-8080-can-i.html

pytest cannot import module while python can

I solved my problem by setting the PYTHONPATH in Environment Variables for the specific configuration I'm running my tests with.

While you're viewing the test file on PyCharm:

  1. Ctrl + Shift + A
  2. Type Edit Configurations
  3. Set your PYTHONPATH under Environment > Environment variables.

nginx error:"location" directive is not allowed here in /etc/nginx/nginx.conf:76

The server directive has to be in the http directive. It should not be outside of it.

Incase if you need detailed information, refer this.

Converting a JToken (or string) to a given Type

var i2 = JsonConvert.DeserializeObject(obj["id"].ToString(), type);

throws a parsing exception due to missing quotes around the first argument (I think). I got it to work by adding the quotes:

var i2 = JsonConvert.DeserializeObject("\"" + obj["id"].ToString() + "\"", type);

Maven dependencies are failing with a 501 error

I am facing the same problem. There are two solutions that I tried, and both works fine for me.

  • Update the Maven version repository (Maven version >= 3.2.3)
  • Restrict the current Maven version to use HTTPS links.

Update the Maven version repository:

Download the Apache Maven binary that includes the default https addresses (Apache Maven 3.6.3 binary). And open the Options dialog window in tools of NetBeans menu bar (Java Maven Dialog View). And select browse option in Maven Home List Box (Maven Home List Box View). After adding the Apache Maven newly downloaded version (Updated Maven Home List Box View), the project builds and runs successfully.

Restrict the current Maven version to use HTTPS links:

Include the following code in pom.xml of your project.

<project>
      ...
    <pluginRepositories>
        <pluginRepository>
            <id>central</id>
            <name>Central Repository</name>
            <url>https://repo.maven.apache.org/maven2</url>
            <layout>default</layout>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <releases>
                <updatePolicy>never</updatePolicy>
            </releases>
        </pluginRepository>
    </pluginRepositories>
    <repositories>
        <repository>
            <id>central</id>
            <name>Central Repository</name>
            <url>https://repo.maven.apache.org/maven2</url>
            <layout>default</layout>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
</project>

How to quickly test some javascript code?

If you want to edit some complex javascript I suggest you use JsFiddle. Alternatively, for smaller pieces of javascript you can just run it through your browser URL bar, here's an example:

javascript:alert("hello world");

And, as it was already suggested both Firebug and Chrome developer tools have Javascript console, in which you can type in your javascript to execute. So do Internet Explorer 8+, Opera, Safari and potentially other modern browsers.

in querySelector: how to get the first and get the last elements? what traversal order is used in the dom?

Example to get the last input element:

document.querySelector(".groups-container >div:last-child input")

SonarQube not picking up Unit Test Coverage

Jenkins does not show coverage results as it is a problem of version compatibilities between jenkins jacoco plugin and maven jacoco plugin. On my side I have fixed it by using a more recent version of maven jacoco plugin

<build>
   <pluginManagement>
     <plugins>
       <plugin>
         <groupId>org.jacoco</groupId>
         <artifactId>jacoco-maven-plugin</artifactId>
         <version>0.7.9</version>
       </plugin>
     <plugins>
   <pluginManagement>
<build>

Can anyone explain what JSONP is, in layman terms?

Preface:

This answer is over six years old. While the concepts and application of JSONP haven't changed (i.e. the details of the answer are still valid), you should look to use CORS where possible (i.e. your server or API supports it, and the browser support is adequate), as JSONP has inherent security risks.


JSONP (JSON with Padding) is a method commonly used to bypass the cross-domain policies in web browsers. (You are not allowed to make AJAX requests to a web page perceived to be on a different server by the browser.)

JSON and JSONP behave differently on the client and the server. JSONP requests are not dispatched using the XMLHTTPRequest and the associated browser methods. Instead a <script> tag is created, whose source is set to the target URL. This script tag is then added to the DOM (normally inside the <head> element).

JSON Request:

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
  if (xhr.readyState == 4 && xhr.status == 200) {
    // success
  };
};

xhr.open("GET", "somewhere.php", true);
xhr.send();

JSONP Request:

var tag = document.createElement("script");
tag.src = 'somewhere_else.php?callback=foo';

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

The difference between a JSON response and a JSONP response is that the JSONP response object is passed as an argument to a callback function.

JSON:

{ "bar": "baz" }

JSONP:

foo( { "bar": "baz" } );

This is why you see JSONP requests containing the callback parameter, so that the server knows the name of the function to wrap the response.

This function must exist in the global scope at the time the <script> tag is evaluated by the browser (once the request has completed).


Another difference to be aware of between the handling of a JSON response and a JSONP response is that any parse errors in a JSON response could be caught by wrapping the attempt to evaluate the responseText in a try/catch statement. Because of the nature of a JSONP response, parse errors in the response will cause an uncatchable JavaScript parse error.

Both formats can implement timeout errors by setting a timeout before initiating the request and clearing the timeout in the response handler.


Using jQuery

The usefulness of using jQuery to make JSONP requests, is that jQuery does all of the work for you in the background.

By default jQuery requires you to include &callback=? in the URL of your AJAX request. jQuery will take the success function you specify, assign it a unique name, and publish it in the global scope. It will then replace the question mark ? in &callback=? with the name it has assigned.


Comparable JSON/JSONP Implementations

The following assumes a response object { "bar" : "baz" }

JSON:

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
  if (xhr.readyState == 4 && xhr.status == 200) {
    document.getElementById("output").innerHTML = eval('(' + this.responseText + ')').bar;
  };
};

xhr.open("GET", "somewhere.php", true);
xhr.send();

JSONP:

function foo(response) {
  document.getElementById("output").innerHTML = response.bar;
};

var tag = document.createElement("script");
tag.src = 'somewhere_else.php?callback=foo';

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

Push method in React Hooks (useState)?

Most recommended method is using wrapper function and spread operator together. For example, if you have initialized a state called name like this,

const [names, setNames] = useState([])

You can push to this array like this,

setNames(names => [...names, newName])

Hope that helps.

Get scroll position using jquery

cross browser variant

$(document).scrollTop();

How to compare two List<String> to each other?

I discovered that SequenceEqual is not the most efficient way to compare two lists of strings (initially from http://www.dotnetperls.com/sequenceequal).

I wanted to test this myself so I created two methods:

    /// <summary>
    /// Compares two string lists using LINQ's SequenceEqual.
    /// </summary>
    public bool CompareLists1(List<string> list1, List<string> list2)
    {
        return list1.SequenceEqual(list2);
    }

    /// <summary>
    /// Compares two string lists using a loop.
    /// </summary>
    public bool CompareLists2(List<string> list1, List<string> list2)
    {
        if (list1.Count != list2.Count)
            return false;

        for (int i = 0; i < list1.Count; i++)
        {
            if (list1[i] != list2[i])
                return false;
        }

        return true;
    }

The second method is a bit of code I encountered and wondered if it could be refactored to be "easier to read." (And also wondered if LINQ optimization would be faster.)

As it turns out, with two lists containing 32k strings, over 100 executions:

  • Method 1 took an average of 6761.8 ticks
  • Method 2 took an average of 3268.4 ticks

I usually prefer LINQ for brevity, performance, and code readability; but in this case I think a loop-based method is preferred.

Edit:

I recompiled using optimized code, and ran the test for 1000 iterations. The results still favor the loop (even more so):

  • Method 1 took an average of 4227.2 ticks
  • Method 2 took an average of 1831.9 ticks

Tested using Visual Studio 2010, C# .NET 4 Client Profile on a Core i7-920

Increasing nesting function calls limit

Do you have Zend, IonCube, or xDebug installed? If so, that is probably where you are getting this error from.

I ran into this a few years ago, and it ended up being Zend putting that limit there, not PHP. Of course removing it will let you go past the 100 iterations, but you will eventually hit the memory limits.

How do I unload (reload) a Python module?

The accepted answer doesn't handle the from X import Y case. This code handles it and the standard import case as well:

def importOrReload(module_name, *names):
    import sys

    if module_name in sys.modules:
        reload(sys.modules[module_name])
    else:
        __import__(module_name, fromlist=names)

    for name in names:
        globals()[name] = getattr(sys.modules[module_name], name)

# use instead of: from dfly_parser import parseMessages
importOrReload("dfly_parser", "parseMessages")

In the reloading case, we reassign the top level names to the values stored in the newly reloaded module, which updates them.

SQLite DateTime comparison

My query I did as follows:

SELECT COUNT(carSold) 
FROM cars_sales_tbl
WHERE date
BETWEEN '2015-04-01' AND '2015-04-30'
AND carType = "Hybrid"

I got the hint by @ifredy's answer. The all I did is, I wanted this query to be run in iOS, using Objective-C. And it works!

Hope someone who does iOS Development, will get use out of this answer too!

Jquery to open Bootstrap v3 modal of remote url

So basically, in jquery what we can do is to load href attribute using the load function. This way we can use the url in <a> tag and load that in modal-body.

<a  href='/site/login' class='ls-modal'>Login</a>

//JS script
$('.ls-modal').on('click', function(e){
  e.preventDefault();
  $('#myModal').modal('show').find('.modal-body').load($(this).attr('href'));
});

Styling an anchor tag to look like a submit button

Why not just use a button and call the url with JavaScript?

<input type="button" value="Cancel" onclick="location.href='url.html';return false;" />

javascript get child by id

In modern browsers (IE8, Firefox, Chrome, Opera, Safari) you can use querySelector():

function test(el){
  el.querySelector("#child").style.display = "none";
}

For older browsers (<=IE7), you would have to use some sort of library, such as Sizzle or a framework, such as jQuery, to work with selectors.

As mentioned, IDs are supposed to be unique within a document, so it's easiest to just use document.getElementById("child").

Input size vs width

You'll get more consistency if you use width (your second example).

"int cannot be dereferenced" in Java

id is of primitive type int and not an Object. You cannot call methods on a primitive as you are doing here :

id.equals

Try replacing this:

        if (id.equals(list[pos].getItemNumber())){ //Getting error on "equals"

with

        if (id == list[pos].getItemNumber()){ //Getting error on "equals"

Where is database .bak file saved from SQL Server Management Studio?

Use the script below, and switch the DatabaseName with then name of the database that you've backed up. On the column physical_device_name, you'll have the full path of your backed-up database:

select a.backup_set_id, a.server_name, a.database_name, a.name, a.user_name, a.position, a.software_major_version, a.backup_start_date, backup_finish_date, a.backup_size, a.recovery_model, b.physical_device_name
from msdb.dbo.backupset a join msdb.dbo.backupmediafamily b
  on a.media_set_id = b.media_set_id
where a.database_name = 'DatabaseName'
order by a.backup_finish_date desc

How to fix docker: Got permission denied issue

Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.40/images/json: dial unix /var/run/docker.sock: connect: permission denied

sudo chmod 666 /var/run/docker.sock

This fix my problem.

How to deploy correctly when using Composer's develop / production switch?

I think is better automate the process:

Add the composer.lock file in your git repository, make sure you use composer.phar install --no-dev when you release, but in you dev machine you could use any composer command without concerns, this will no go to production, the production will base its dependencies in the lock file.

On the server you checkout this specific version or label, and run all the tests before replace the app, if the tests pass you continue the deployment.

If the test depend on dev dependencies, as composer do not have a test scope dependency, a not much elegant solution could be run the test with the dev dependencies (composer.phar install), remove the vendor library, run composer.phar install --no-dev again, this will use cached dependencies so is faster. But that is a hack if you know the concept of scopes in other build tools

Automate this and forget the rest, go drink a beer :-)

PS.: As in the @Sven comment bellow, is not a good idea not checkout the composer.lock file, because this will make composer install work as composer update.

You could do that automation with http://deployer.org/ it is a simple tool.

Why is it said that "HTTP is a stateless protocol"?

From Wikipedia:

HTTP is a stateless protocol. A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests.

But some web applications may have to track the user's progress from page to page, for example when a web server is required to customize the content of a web page for a user. Solutions for these cases include:

  • the use of HTTP cookies.
  • server side sessions,
  • hidden variables (when the current page contains a form), and
  • URL-rewriting using URI-encoded parameters, e.g., /index.php?session_id=some_unique_session_code.

What makes the protocol stateless is that the server is not required to track state over multiple requests, not that it cannot do so if it wants to. This simplifies the contract between client and server, and in many cases (for instance serving up static data over a CDN) minimizes the amount of data that needs to be transferred. If servers were required to maintain the state of clients' visits the structure of issuing and responding to requests would be more complex. As it is, the simplicity of the model is one of its greatest features.

How to get image size (height & width) using JavaScript?

Maybe this will help others. In my case, I have a File type (that is guaranteed to be an image) & I want the image dimensions without loading it on the DOM.

General strategy: Convert File to ArrayBuffer -> Convert ArrayBuffer to base64 string -> use this as the image source with an Image class -> use naturalHeight & naturalWidth to get dimensions.

const fr = new FileReader();
fr.readAsArrayBuffer(image); // image the the 'File' object
fr.onload = () => {
  const arrayBuffer: ArrayBuffer = fr.result as ArrayBuffer;

  // Convert to base64. String.fromCharCode can hit stack overflow error if you pass
  // the entire arrayBuffer in, iteration gets around this
  let binary = '';
  const bytes = new Uint8Array(arrayBuffer);
  bytes.forEach(b => binary += String.fromCharCode(b));
  const base64Data = window.btoa(binary);

  // Create image object. Note, a default width/height MUST be given to constructor (per 
  // the docs) or naturalWidth/Height will always return 0.
  const imageObj = new Image(100, 100);
  imageObj.src = `data:${image.type};base64,${base64Data}`;
  imageObj.onload = () => {
    console.log(imageObj.naturalWidth, imageObj.naturalHeight);
  }
}

This allows you to get the image dimensions & aspect ratio all from a File without rendering it. Can easily convert the onload functions to RxJS Observables using fromEvent for a better async experience:

// fr is the file reader, this is the same as fr.onload = () => { ... }
fromEvent(fr, 'load')

subquery in FROM must have an alias

add an ALIAS on the subquery,

SELECT  COUNT(made_only_recharge) AS made_only_recharge
FROM    
    (
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER = '0130'
        EXCEPT
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER != '0130'
    ) AS derivedTable                           -- <<== HERE

Convert Data URI to File then append to FormData

I had exactly the same problem as Ravinder Payal, and I've found the answer. Try this:

var dataURL = canvas.toDataURL("image/jpeg");

var name = "image.jpg";
var parseFile = new Parse.File(name, {base64: dataURL.substring(23)});

How to format a numeric column as phone number in SQL

Solutions that use SUBSTRING and concatenation + are nearly independent of RDBMS. Here is a short solution that is specific to SQL Server:

declare @x int = 123456789
select stuff(stuff(@x, 4, 0, '-'), 8, 0, '-')

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

I believe those comments refer specifically to the browsers, i.e., clicking links and submitting forms, not XMLHttpRequest. XMLHttpRequest is just a custom client that you wrote in JavaScript that uses the browser as a runtime.

UPDATE: To clarify, I did not mean (though I did write) that you wrote XMLHttpRequest; I meant that you wrote the code that uses XMLHttpRequest. The browsers do not natively support XMLHttpRequest. XMLHttpRequest comes from the JavaScript runtime, which may be hosted by a browser, although it isn't required to be (see Rhino). That's why people say browsers don't support PUT and DELETE—because it's actually JavaScript that is supporting them.

Can a java lambda have more than 1 parameter?

You could also use jOOL library - https://github.com/jOOQ/jOOL

It has already prepared function interfaces with different number of parameters. For instance, you could use org.jooq.lambda.function.Function3, etc from Function0 up to Function16.

View a specific Git commit

git show <revhash>

Documentation here. Or if that doesn't work, try Google Code's GIT Documentation

Inline labels in Matplotlib

@Jan Kuiken's answer is certainly well-thought and thorough, but there are some caveats:

  • it does not work in all cases
  • it requires a fair amount of extra code
  • it may vary considerably from one plot to the next

A much simpler approach is to annotate the last point of each plot. The point can also be circled, for emphasis. This can be accomplished with one extra line:

from matplotlib import pyplot as plt

for i, (x, y) in enumerate(samples):
    plt.plot(x, y)
    plt.text(x[-1], y[-1], 'sample {i}'.format(i=i))

A variant would be to use ax.annotate.

Pie chart with jQuery

Chart.js is quite useful, supporting numerous other types of charts as well.

It can be used both with jQuery and without.

When should the xlsm or xlsb formats be used?

They're all similar in that they're essentially zip files containing the actual file components. You can see the contents just by replacing the extension with .zip and opening them up. The difference with xlsb seems to be that the components are not XML-based but are in a binary format: supposedly this is beneficial when working with large files.

https://blogs.msdn.microsoft.com/dmahugh/2006/08/22/new-binary-file-format-for-spreadsheets/

Adding custom radio buttons in android

In order to hide the default radio button, I'd suggest to remove the button instead of making it transparent as all visual feedback is handled by the drawable background :

android:button="@null"

Also it would be better to use styles as there are several radio buttons :

<RadioButton style="@style/RadioButtonStyle" ... />

<style name="RadioButtonStyle" parent="@android:style/Widget.CompoundButton">
    <item name="android:background">@drawable/customButtonBackground</item>
    <item name="android:button">@null</item>
</style>

You'll need the Seslyn customButtonBackground drawable too.

Adjust icon size of Floating action button (fab)

Try to use app:maxImageSize="56dp" instead of the above answers after you update your support library to v28.0.0

Maximum filename length in NTFS (Windows XP and Windows Vista)?

Individual components of a filename (i.e. each subdirectory along the path, and the final filename) are limited to 255 characters, and the total path length is limited to approximately 32,000 characters.

However, on Windows, you can't exceed MAX_PATH value (259 characters for files, 248 for folders). See http://msdn.microsoft.com/en-us/library/aa365247.aspx for full details.

Oracle PL/SQL - Raise User-Defined Exception With Custom SQLERRM

I usually lose track of all of my -20001-type error codes, so I try to consolidate all my application errors into a nice package like such:

SET SERVEROUTPUT ON

CREATE OR REPLACE PACKAGE errors AS
  invalid_foo_err EXCEPTION;
  invalid_foo_num NUMBER := -20123;
  invalid_foo_msg VARCHAR2(32767) := 'Invalid Foo!';
  PRAGMA EXCEPTION_INIT(invalid_foo_err, -20123);  -- can't use var >:O

  illegal_bar_err EXCEPTION;
  illegal_bar_num NUMBER := -20156;
  illegal_bar_msg VARCHAR2(32767) := 'Illegal Bar!';
  PRAGMA EXCEPTION_INIT(illegal_bar_err, -20156);  -- can't use var >:O

  PROCEDURE raise_err(p_err NUMBER, p_msg VARCHAR2 DEFAULT NULL);
END;
/

CREATE OR REPLACE PACKAGE BODY errors AS
  unknown_err EXCEPTION;
  unknown_num NUMBER := -20001;
  unknown_msg VARCHAR2(32767) := 'Unknown Error Specified!';

  PROCEDURE raise_err(p_err NUMBER, p_msg VARCHAR2 DEFAULT NULL) AS
    v_msg VARCHAR2(32767);
  BEGIN
    IF p_err = unknown_num THEN
      v_msg := unknown_msg;
    ELSIF p_err = invalid_foo_num THEN
      v_msg := invalid_foo_msg;
    ELSIF p_err = illegal_bar_num THEN
      v_msg := illegal_bar_msg;
    ELSE
      raise_err(unknown_num, 'USR' || p_err || ': ' || p_msg);
    END IF;

    IF p_msg IS NOT NULL THEN
      v_msg := v_msg || ' - '||p_msg;
    END IF;

    RAISE_APPLICATION_ERROR(p_err, v_msg);
  END;
END;
/

Then call errors.raise_err(errors.invalid_foo_num, 'optional extra text') to use it, like such:

BEGIN
  BEGIN
    errors.raise_err(errors.invalid_foo_num, 'Insufficient Foo-age!');
  EXCEPTION
    WHEN errors.invalid_foo_err THEN
      dbms_output.put_line(SQLERRM);
  END;

  BEGIN
    errors.raise_err(errors.illegal_bar_num, 'Insufficient Bar-age!');
  EXCEPTION
    WHEN errors.illegal_bar_err THEN
      dbms_output.put_line(SQLERRM);
  END;

  BEGIN
    errors.raise_err(-10000, 'This Doesn''t Exist!!');
  EXCEPTION
    WHEN OTHERS THEN
      dbms_output.put_line(SQLERRM);
  END;
END;
/

produces this output:

ORA-20123: Invalid Foo! - Insufficient Foo-age!
ORA-20156: Illegal Bar! - Insufficient Bar-age!
ORA-20001: Unknown Error Specified! - USR-10000: This Doesn't Exist!!

Sockets - How to find out what port and address I'm assigned

The comment in your code is wrong. INADDR_ANY doesn't put server's IP automatically'. It essentially puts 0.0.0.0, for the reasons explained in mark4o's answer.

Error in <my code> : object of type 'closure' is not subsettable

In general this error message means that you have tried to use indexing on a function. You can reproduce this error message with, for example

mean[1]
## Error in mean[1] : object of type 'closure' is not subsettable
mean[[1]]
## Error in mean[[1]] : object of type 'closure' is not subsettable
mean$a
## Error in mean$a : object of type 'closure' is not subsettable

The closure mentioned in the error message is (loosely) the function and the environment that stores the variables when the function is called.


In this specific case, as Joshua mentioned, you are trying to access the url function as a variable. If you define a variable named url, then the error goes away.

As a matter of good practise, you should usually avoid naming variables after base-R functions. (Calling variables data is a common source of this error.)


There are several related errors for trying to subset operators or keywords.

`+`[1]
## Error in `+`[1] : object of type 'builtin' is not subsettable
`if`[1]
## Error in `if`[1] : object of type 'special' is not subsettable

If you're running into this problem in shiny, the most likely cause is that you're trying to work with a reactive expression without calling it as a function using parentheses.

library(shiny)
reactive_df <- reactive({
    data.frame(col1 = c(1,2,3),
               col2 = c(4,5,6))
})

While we often work with reactive expressions in shiny as if they were data frames, they are actually functions that return data frames (or other objects).

isolate({
    print(reactive_df())
    print(reactive_df()$col1)
})
  col1 col2
1    1    4
2    2    5
3    3    6
[1] 1 2 3

But if we try to subset it without parentheses, then we're actually trying to index a function, and we get an error:

isolate(
    reactive_df$col1
)
Error in reactive_df$col1 : object of type 'closure' is not subsettable

How can I get the behavior of GNU's readlink -f on a Mac?

Since my work is used by people with non-BSD Linux as well as macOS, I've opted for using these aliases in our build scripts (sed included since it has similar issues):

##
# If you're running macOS, use homebrew to install greadlink/gsed first:
#   brew install coreutils
#
# Example use:
#   # Gets the directory of the currently running script
#   dotfilesDir=$(dirname "$(globalReadlink -fm "$0")")
#   alias al='pico ${dotfilesDir}/aliases.local'
##

function globalReadlink () {
  # Use greadlink if on macOS; otherwise use normal readlink
  if [[ $OSTYPE == darwin* ]]; then
    greadlink "$@"
  else
    readlink "$@"
  fi
}

function globalSed () {
  # Use gsed if on macOS; otherwise use normal sed
  if [[ $OSTYPE == darwin* ]]; then
    gsed "$@"
  else
    sed "$@"
  fi
}

Optional check you could add to automatically install homebrew + coreutils dependencies:

if [[ "$OSTYPE" == "darwin"* ]]; then
  # Install brew if needed
  if [ -z "$(which brew)" ]; then 
    /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"; 
  fi
  # Check for coreutils
  if [ -z "$(brew ls coreutils)" ]; then
    brew install coreutils
  fi
fi

I suppose to be truly "global" it needs to check others...but that probably comes close to the 80/20 mark.