Programs & Examples On #Acts as ferret

This ActiveRecord mixin adds full text search capabilities to any Rails model.

Composer: file_put_contents(./composer.json): failed to open stream: Permission denied

In my case I don't have issues with ~/.composer.
So being inside Laravel app root folder, I did sudo chown -R $USER composer.lock and it was helpful.

Casting interfaces for deserialization in JSON.NET

(Copied from this question)

In cases where I have not had control over the incoming JSON (and so cannot ensure that it includes a $type property) I have written a custom converter that just allows you to explicitly specify the concrete type:

public class Model
{
    [JsonConverter(typeof(ConcreteTypeConverter<Something>))]
    public ISomething TheThing { get; set; }
}

This just uses the default serializer implementation from Json.Net whilst explicitly specifying the concrete type.

An overview are available on this blog post. Source code is below:

public class ConcreteTypeConverter<TConcrete> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        //assume we can convert to anything for now
        return true;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        //explicitly specify the concrete type we want to create
        return serializer.Deserialize<TConcrete>(reader);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        //use the default serialization - it works fine
        serializer.Serialize(writer, value);
    }
}

How to get Locale from its String representation in Java?

Because I have just implemented it:

In Groovy/Grails it would be:

def locale = Locale.getAvailableLocales().find { availableLocale ->
      return availableLocale.toString().equals(searchedLocale)
}

Database Structure for Tree Data Structure

Have a look at Managing Hierarchical Data in MySQL. It discusses two approaches for storing and managing hierarchical (tree-like) data in a relational database.

The first approach is the adjacency list model, which is what you essentially describe: having a foreign key that refers to the table itself. While this approach is simple, it can be very inefficient for certain queries, like building the whole tree.

The second approach discussed in the article is the nested set model. This approach is far more efficient and flexible. Refer to the article for detailed explanation and example queries.

Disabling same-origin policy in Safari

Later versions of Safari allow you to Disable Cross-Origin Restrictions. Just enable the developer menu from Preferences >> Advanced, and select "Disable Cross-Origin Restrictions" from the develop menu.

If you want local only, then you only need to enable the developer menu, and select "Disable local file restrictions" from the develop menu.

Should IBOutlets be strong or weak under ARC?

One thing I wish to point out here, and that is, despite what the Apple engineers have stated in their own WWDC 2015 video here:

https://developer.apple.com/videos/play/wwdc2015/407/

Apple keeps changing their mind on the subject, which tells us that there is no single right answer to this question. To show that even Apple engineers are split on this subject, take a look at Apple's most recent sample code, and you'll see some people use weak, and some don't.

This Apple Pay example uses weak: https://developer.apple.com/library/ios/samplecode/Emporium/Listings/Emporium_ProductTableViewController_swift.html#//apple_ref/doc/uid/TP40016175-Emporium_ProductTableViewController_swift-DontLinkElementID_8

As does this picture-in-picture example: https://developer.apple.com/library/ios/samplecode/AVFoundationPiPPlayer/Listings/AVFoundationPiPPlayer_PlayerViewController_swift.html#//apple_ref/doc/uid/TP40016166-AVFoundationPiPPlayer_PlayerViewController_swift-DontLinkElementID_4

As does the Lister example: https://developer.apple.com/library/ios/samplecode/Lister/Listings/Lister_ListCell_swift.html#//apple_ref/doc/uid/TP40014701-Lister_ListCell_swift-DontLinkElementID_57

As does the Core Location example: https://developer.apple.com/library/ios/samplecode/PotLoc/Listings/Potloc_PotlocViewController_swift.html#//apple_ref/doc/uid/TP40016176-Potloc_PotlocViewController_swift-DontLinkElementID_6

As does the view controller previewing example: https://developer.apple.com/library/ios/samplecode/ViewControllerPreviews/Listings/Projects_PreviewUsingDelegate_PreviewUsingDelegate_DetailViewController_swift.html#//apple_ref/doc/uid/TP40016546-Projects_PreviewUsingDelegate_PreviewUsingDelegate_DetailViewController_swift-DontLinkElementID_5

As does the HomeKit example: https://developer.apple.com/library/ios/samplecode/HomeKitCatalog/Listings/HMCatalog_Homes_Action_Sets_ActionSetViewController_swift.html#//apple_ref/doc/uid/TP40015048-HMCatalog_Homes_Action_Sets_ActionSetViewController_swift-DontLinkElementID_23

All those are fully updated for iOS 9, and all use weak outlets. From this we learn that A. The issue is not as simple as some people make it out to be. B. Apple has changed their mind repeatedly, and C. You can use whatever makes you happy :)

Special thanks to Paul Hudson (author of www.hackingwithsift.com) who gave me the clarification, and references for this answer.

I hope this clarifies the subject a bit better!

Take care.

Query comparing dates in SQL

Try to use "#" before and after of the date and be sure of your system date format. maybe "YYYYMMDD O YYYY-MM-DD O MM-DD-YYYY O USING '/ O \' "

Ex:

 select id,numbers_from,created_date,amount_numbers,SMS_text 
 from Test_Table
 where 
 created_date <= #2013-04-12#

Populating a database in a Laravel migration file

I tried this DB insert method, but as it does not use the model, it ignored a sluggable trait I had on the model. So, given the Model for this table exists, as soon as its migrated, I figured the model would be available to use to insert data. And I came up with this:

public function up() {
        Schema::create('parent_categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('slug');
            $table->timestamps();
        });
        ParentCategory::create(
            [
                'id' => 1,
                'name' => 'Occasions',
            ],
        );
    }

This worked correctly, and also took into account the sluggable trait on my Model to automatically generate a slug for this entry, and uses the timestamps too. NB. Adding the ID was no neccesary, however, I wanted specific IDs for my categories in this example. Tested working on Laravel 5.8

Can a JSON value contain a multiline string

Per the specification, the JSON grammar's char production can take the following values:

  • any-Unicode-character-except-"-or-\-or-control-character
  • \"
  • \\
  • \/
  • \b
  • \f
  • \n
  • \r
  • \t
  • \u four-hex-digits

Newlines are "control characters", so no, you may not have a literal newline within your string. However, you may encode it using whatever combination of \n and \r you require.

The JSONLint tool confirms that your JSON is invalid.


And, if you want to write newlines inside your JSON syntax without actually including newlines in the data, then you're doubly out of luck. While JSON is intended to be human-friendly to a degree, it is still data and you're trying to apply arbitrary formatting to that data. That is absolutely not what JSON is about.

Moment.js - tomorrow, today and yesterday

So this is what I ended up doing

var dateText = moment(someDate).from(new Date());
var startOfToday = moment().startOf('day');
var startOfDate = moment(someDate).startOf('day');
var daysDiff = startOfDate.diff(startOfToday, 'days');
var days = {
  '0': 'today',
  '-1': 'yesterday',
  '1': 'tomorrow'
};

if (Math.abs(daysDiff) <= 1) {
  dateText = days[daysDiff];
}

TypeError("'bool' object is not iterable",) when trying to return a Boolean

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

Make git automatically remove trailing whitespace before committing

I found a git pre-commit hook that removes trailing whitespace.

#!/bin/sh

if git-rev-parse --verify HEAD >/dev/null 2>&1 ; then
   against=HEAD
else
   # Initial commit: diff against an empty tree object
   against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
# Find files with trailing whitespace
for FILE in `exec git diff-index --check --cached $against -- | sed '/^[+-]/d' | sed -r 's/:[0-9]+:.*//' | uniq` ; do
   # Fix them!
   sed -i 's/[[:space:]]*$//' "$FILE"
   git add "$FILE"
done
exit

Find which rows have different values for a given column in Teradata SQL

This works for PL/SQL:

select count(*), id,address from table group by id,address having count(*)<2

Using python map and other functional tools

>>> from itertools import repeat
>>> for foo, bars in zip(foos, repeat(bars)):
...     print foo, bars
... 
1.0 [1, 2, 3]
2.0 [1, 2, 3]
3.0 [1, 2, 3]
4.0 [1, 2, 3]
5.0 [1, 2, 3]

How to generate Javadoc HTML files in Eclipse?

To quickly add a Javadoc use following shortcut:

Windows: alt + shift + J

Mac: ? + Alt + J

Depending on selected context, a Javadoc will be printed. To create Javadoc written by OP, select corresponding method and hit the shotcut keys.

How to identify platform/compiler from preprocessor macros?

If you're writing C++, I can't recommend using the Boost libraries strongly enough.

The latest version (1.55) includes a new Predef library which covers exactly what you're looking for, along with dozens of other platform and architecture recognition macros.

#include <boost/predef.h>

// ...

#if BOOST_OS_WINDOWS

#elif BOOST_OS_LINUX

#elif BOOST_OS_MACOS

#endif

How to make picturebox transparent?

you can set the PictureBox BackColor proprty to Transparent

How to implement a lock in JavaScript

JavaScript is, with a very few exceptions (XMLHttpRequest onreadystatechange handlers in some versions of Firefox) event-loop concurrent. So you needn't worry about locking in this case.

JavaScript has a concurrency model based on an "event loop". This model is quite different than the model in other languages like C or Java.

...

A JavaScript runtime contains a message queue, which is a list of messages to be processed. To each message is associated a function. When the stack is empty, a message is taken out of the queue and processed. The processing consists of calling the associated function (and thus creating an initial stack frame) The message processing ends when the stack becomes empty again.

...

Each message is processed completely before any other message is processed. This offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be pre-empted and will run entirely before any other code runs (and can modify data the function manipulates). This differs from C, for instance, where if a function runs in a thread, it can be stopped at any point to run some other code in another thread.

A downside of this model is that if a message takes too long to complete, the web application is unable to process user interactions like click or scroll. The browser mitigates this with the "a script is taking too long to run" dialog. A good practice to follow is to make message processing short and if possible cut down one message into several messages.

For more links on event-loop concurrency, see E

Optimal way to DELETE specified rows from Oracle

Store all the to be deleted ID's into a table. Then there are 3 ways. 1) loop through all the ID's in the table, then delete one row at a time for X commit interval. X can be a 100 or 1000. It works on OLTP environment and you can control the locks.

2) Use Oracle Bulk Delete

3) Use correlated delete query.

Single query is usually faster than multiple queries because of less context switching, and possibly less parsing.

Insert text into textarea with jQuery

I think this would be better

$(function() {
$('#myAnchorId').click(function() { 
    var areaValue = $('#area').val();
    $('#area').val(areaValue + 'Whatever you want to enter');
});
});

Embed ruby within URL : Middleman Blog

<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %>   <i class="fa fa-facebook">     Facebook Share    </i> <%end%> 

I am assuming that current_article_url is http://0.0.0.0:4567/link_to_title

How can I run a program from a batch file without leaving the console open after the program starts?

From my own question:

start /b myProgram.exe params...

works if you start the program from an existing DOS session.

If not, call a vb script

wscript.exe invis.vbs myProgram.exe %*

The Windows Script Host Run() method takes:

  • intWindowStyle : 0 means "invisible windows"
  • bWaitOnReturn : false means your first script does not need to wait for your second script to finish

Here is invis.vbs:

set args = WScript.Arguments
num = args.Count

if num = 0 then
    WScript.Echo "Usage: [CScript | WScript] invis.vbs aScript.bat <some script arguments>"
    WScript.Quit 1
end if

sargs = ""
if num > 1 then
    sargs = " "
    for k = 1 to num - 1
        anArg = args.Item(k)
        sargs = sargs & anArg & " "
    next
end if

Set WshShell = WScript.CreateObject("WScript.Shell")

WshShell.Run """" & WScript.Arguments(0) & """" & sargs, 0, False

How to append elements at the end of ArrayList in Java?

Here is the syntax, along with some other methods you might find useful:

    //add to the end of the list
    stringList.add(random);

    //add to the beginning of the list
    stringList.add(0,  random);

    //replace the element at index 4 with random
    stringList.set(4, random);

    //remove the element at index 5
    stringList.remove(5);

    //remove all elements from the list
    stringList.clear();

Remove non-numeric characters (except periods and commas) from a string

I'm surprised there's been no mention of filter_var here for this being such an old question...

PHP has a built in method of doing this using sanitization filters. Specifically, the one to use in this situation is FILTER_SANITIZE_NUMBER_FLOAT with the FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND flags. Like so:

$numeric_filtered = filter_var("AR3,373.31", FILTER_SANITIZE_NUMBER_FLOAT,
    FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);
echo $numeric_filtered; // Will print "3,373.31"

It might also be worthwhile to note that because it's built-in to PHP, it's slightly faster than using regex with PHP's current libraries (albeit literally in nanoseconds).

How do I create variable variables?

Use globals()

You can actually assign variables to global scope dynamically, for instance, if you want 10 variables that can be accessed on a global scope i_1, i_2 ... i_10:

for i in range(10):
    globals()['i_{}'.format(i)] = 'a'

This will assign 'a' to all of these 10 variables, of course you can change the value dynamically as well. All of these variables can be accessed now like other globally declared variable:

>>> i_5
'a'

Magento: Set LIMIT on collection

You can Implement this also:- setPage(1, n); where, n = any number.

$products = Mage::getResourceModel('catalog/product_collection')
                ->addAttributeToSelect('*')
                ->addAttributeToSelect(array('name', 'price', 'small_image'))
                ->addFieldToFilter('visibility', Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) //visible only catalog & searchable product
                ->addAttributeToFilter('status', 1) // enabled
                ->setStoreId($storeId)
                ->setOrder('created_at', 'desc')
                ->setPage(1, 6);

access key and value of object using *ngFor

change demo type to array or iterate over your object and push to another array

public details =[];   
Object.keys(demo).forEach(key => {
      this.details.push({"key":key,"value":demo[key]);
    });

and from html:

<div *ngFor="obj of details">
  <p>{{obj.key}}</p>
  <p>{{obj.value}}</p>
  <p></p>
</div>

How to use PHP string in mySQL LIKE query?

DO it like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$yourPHPVAR%'");

Do not forget the % at the end

Fastest way to serialize and deserialize .NET objects

I removed the bugs in above code and got below results: Also I am unsure given how NetSerializer requires you to register the types you are serializing, what kind of compatibility or performance differences that could potentially make.

Generating 100000 arrays of data...
Test data generated.
Testing BinarySerializer...
BinaryFormatter: Serializing took 508.9773ms.
BinaryFormatter: Deserializing took 371.8499ms.

Testing ProtoBuf serializer...
ProtoBuf: Serializing took 3280.9185ms.
ProtoBuf: Deserializing took 3190.7899ms.

Testing NetSerializer serializer...
NetSerializer: Serializing took 427.1241ms.
NetSerializer: Deserializing took 78.954ms.
Press any key to end.

Modified Code

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace SerializationTests
{
    class Program
    {
        static void Main(string[] args)
        {
            var count = 100000;
            var rnd = new Random((int)DateTime.UtcNow.Ticks & 0xFF);
            Console.WriteLine("Generating {0} arrays of data...", count);
            var arrays = new List<int[]>();
            for (int i = 0; i < count; i++)
            {
                var elements = rnd.Next(1, 100);
                var array = new int[elements];
                for (int j = 0; j < elements; j++)
                {
                    array[j] = rnd.Next();
                }
                arrays.Add(array);
            }
            Console.WriteLine("Test data generated.");
            var stopWatch = new Stopwatch();

            Console.WriteLine("Testing BinarySerializer...");
            var binarySerializer = new BinarySerializer();
            var binarySerialized = new List<byte[]>();
            var binaryDeserialized = new List<int[]>();

            stopWatch.Reset();
            stopWatch.Start();
            foreach (var array in arrays)
            {
                binarySerialized.Add(binarySerializer.Serialize(array));
            }
            stopWatch.Stop();
            Console.WriteLine("BinaryFormatter: Serializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);

            stopWatch.Reset();
            stopWatch.Start();
            foreach (var serialized in binarySerialized)
            {
                binaryDeserialized.Add(binarySerializer.Deserialize<int[]>(serialized));
            }
            stopWatch.Stop();
            Console.WriteLine("BinaryFormatter: Deserializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);


            Console.WriteLine();
            Console.WriteLine("Testing ProtoBuf serializer...");
            var protobufSerializer = new ProtoBufSerializer();
            var protobufSerialized = new List<byte[]>();
            var protobufDeserialized = new List<int[]>();

            stopWatch.Reset();
            stopWatch.Start();
            foreach (var array in arrays)
            {
                protobufSerialized.Add(protobufSerializer.Serialize(array));
            }
            stopWatch.Stop();
            Console.WriteLine("ProtoBuf: Serializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);

            stopWatch.Reset();
            stopWatch.Start();
            foreach (var serialized in protobufSerialized)
            {
                protobufDeserialized.Add(protobufSerializer.Deserialize<int[]>(serialized));
            }
            stopWatch.Stop();
            Console.WriteLine("ProtoBuf: Deserializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);

            Console.WriteLine();
            Console.WriteLine("Testing NetSerializer serializer...");
            var netSerializerSerialized = new List<byte[]>();
            var netSerializerDeserialized = new List<int[]>();

            stopWatch.Reset();
            stopWatch.Start();
            var netSerializerSerializer = new NS();
            foreach (var array in arrays)
            {
                netSerializerSerialized.Add(netSerializerSerializer.Serialize(array));
            }
            stopWatch.Stop();
            Console.WriteLine("NetSerializer: Serializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);

            stopWatch.Reset();
            stopWatch.Start();
            foreach (var serialized in netSerializerSerialized)
            {
                netSerializerDeserialized.Add(netSerializerSerializer.Deserialize<int[]>(serialized));
            }
            stopWatch.Stop();
            Console.WriteLine("NetSerializer: Deserializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);

            Console.WriteLine("Press any key to end.");
            Console.ReadKey();
        }

        public class BinarySerializer
        {
            private static readonly BinaryFormatter Formatter = new BinaryFormatter();

            public byte[] Serialize(object toSerialize)
            {
                using (var stream = new MemoryStream())
                {
                    Formatter.Serialize(stream, toSerialize);
                    return stream.ToArray();
                }
            }

            public T Deserialize<T>(byte[] serialized)
            {
                using (var stream = new MemoryStream(serialized))
                {
                    var result = (T)Formatter.Deserialize(stream);
                    return result;
                }
            }
        }

        public class ProtoBufSerializer
        {
            public byte[] Serialize(object toSerialize)
            {
                using (var stream = new MemoryStream())
                {
                    ProtoBuf.Serializer.Serialize(stream, toSerialize);
                    return stream.ToArray();
                }
            }

            public T Deserialize<T>(byte[] serialized)
            {
                using (var stream = new MemoryStream(serialized))
                {
                    var result = ProtoBuf.Serializer.Deserialize<T>(stream);
                    return result;
                }
            }
        }

        public class NS
        {
            NetSerializer.Serializer Serializer = new NetSerializer.Serializer(new Type[] { typeof(int), typeof(int[]) });

            public byte[] Serialize(object toSerialize)
            {
                using (var stream = new MemoryStream())
                {
                    Serializer.Serialize(stream, toSerialize);
                    return stream.ToArray();
                }
            }

            public T Deserialize<T>(byte[] serialized)
            {
                using (var stream = new MemoryStream(serialized))
                {
                    Serializer.Deserialize(stream, out var result);
                    return (T)result;
                }
            }
        }
    }
}

ToList().ForEach in Linq

As xanatos said, this is a misuse of ForEach.

If you are going to use linq to handle this, I would do it like this:

var departments = employees.SelectMany(x => x.Departments);
foreach (var item in departments)
{
    item.SomeProperty = null;
}
collection.AddRange(departments);

However, the Loop approach is more readable and therefore more maintainable.

how to find 2d array size in c++

int arr[5][4];

For the row subscript(4 raise to 2, include cmath to use pow):

sizeof(arr1)/pow(4,2)   

Column subscript:

sizeof(*arr1)/4

4 means 4 bytes, size of int.

PowerShell on Windows 7: Set-ExecutionPolicy for regular users

This should solve your problem, you should try to run the following below:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser 

How to get a Static property with Reflection

Just wanted to clarify this for myself, while using the new reflection API based on TypeInfo - where BindingFlags is not available reliably (depending on target framework).

In the 'new' reflection, to get the static properties for a type (not including base class(es)) you have to do something like:

IEnumerable<PropertyInfo> props = 
  type.GetTypeInfo().DeclaredProperties.Where(p => 
    (p.GetMethod != null && p.GetMethod.IsStatic) ||
    (p.SetMethod != null && p.SetMethod.IsStatic));

Caters for both read-only or write-only properties (despite write-only being a terrible idea).

The DeclaredProperties member, too doesn't distinguish between properties with public/private accessors - so to filter around visibility, you then need to do it based on the accessor you need to use. E.g - assuming the above call has returned, you could do:

var publicStaticReadable = props.Where(p => p.GetMethod != null && p.GetMethod.IsPublic);

There are some shortcut methods available - but ultimately we're all going to be writing a lot more extension methods around the TypeInfo query methods/properties in the future. Also, the new API forces us to think about exactly what we think of as a 'private' or 'public' property from now on - because we must filter ourselves based on individual accessors.

Initialize Array of Objects using NSArray

This way you can Create NSArray, NSMutableArray.

NSArray keys =[NSArray arrayWithObjects:@"key1",@"key2",@"key3",nil];

NSArray objects =[NSArray arrayWithObjects:@"value1",@"value2",@"value3",nil];

'React' must be in scope when using JSX react/react-in-jsx-scope?

import React, { Component } from 'react';

This is a spelling error, you need to type React instead of react.

laravel throwing MethodNotAllowedHttpException

In my case, I was sending a POST request over HTTP to a server where I had set up Nginx to redirect all requests to port 80 to port 443 where I was serving the app over HTTPS.

Making the request to the correct port directly fixed the problem. In my case, all I had to do is replace http:// in the request URL to https:// since I was using the default ports 80 and 443 respectively.

Variable interpolation in the shell

In Bash:

tail -1 ${filepath}_newstap.sh

Python subprocess/Popen with a modified environment

The env parameter accepts a dictionary. You can simply take os.environ, add a key (your desired variable) (to a copy of the dict if you must) to that and use it as a parameter to Popen.

Running CMake on Windows

The default generator for Windows seems to be set to NMAKE. Try to use:

cmake -G "MinGW Makefiles"

Or use the GUI, and select MinGW Makefiles when prompted for a generator. Don't forget to cleanup the directory where you tried to run CMake, or delete the cache in the GUI. Otherwise, it will try again with NMAKE.

A default document is not configured for the requested URL, and directory browsing is not enabled on the server

The culprit might lie in the fact that Global.asax has been placed in the wrong directory inside the mvc project. In my case it was placed under /Views but I had to move it should have been placed under the root folder of the project.

In your case you might be the exact opposite - run some tests and see for yourself.

https://stackoverflow.com/a/41467885/863651

Encrypt and decrypt a string in C#?

If you are using ASP.Net you can now use built in functionality in .Net 4.0 onwards.

System.Web.Security.MachineKey

.Net 4.5 has MachineKey.Protect() and MachineKey.Unprotect().

.Net 4.0 has MachineKey.Encode() and MachineKey.Decode(). You should just set the MachineKeyProtection to 'All'.

Outside of ASP.Net this class seems to generate a new key with every app restart so doesn't work. With a quick peek in ILSpy it looks to me like it generates its own defaults if the appropriate app.settings are missing. So you may actually be able to set it up outside ASP.Net.

I haven't been able to find a non-ASP.Net equivalent outside the System.Web namespace.

form action with javascript

I always include the js files in the head of the html document and them in the action just call the javascript function. Something like this:

action="javascript:checkout()"

You try this?

Don't forget include the script reference in the html head.

I don't know cause of that works in firefox. Regards.

What's the difference between utf8_general_ci and utf8_unicode_ci?

For those people still arriving at this question in 2020 or later, there are newer options that may be better than both of these. For example, utf8mb4_0900_ai_ci.

All these collations are for the UTF-8 character encoding. The differences are in how text is sorted and compared.

_unicode_ci and _general_ci are two different sets of rules for sorting and comparing text according to the way we expect. Newer versions of MySQL introduce new sets of rules, too, such as _0900_ai_ci for equivalent rules based on Unicode 9.0 - and with no equivalent _general_ci variant. People reading this now should probably use one of these newer collations instead of either _unicode_ci or _general_ci. The description of those older collations below is provided for interest only.

MySQL is currently transitioning away from an older, flawed UTF-8 implementation. For now, you need to use utf8mb4 instead of utf8 for the character encoding part, to ensure you are getting the fixed version. The flawed version remains for backward compatibility, though it is being deprecated.

Key differences

  • utf8mb4_unicode_ci is based on the official Unicode rules for universal sorting and comparison, which sorts accurately in a wide range of languages.

  • utf8mb4_general_ci is a simplified set of sorting rules which aims to do as well as it can while taking many short-cuts designed to improve speed. It does not follow the Unicode rules and will result in undesirable sorting or comparison in some situations, such as when using particular languages or characters.

    On modern servers, this performance boost will be all but negligible. It was devised in a time when servers had a tiny fraction of the CPU performance of today's computers.

Benefits of utf8mb4_unicode_ci over utf8mb4_general_ci

utf8mb4_unicode_ci, which uses the Unicode rules for sorting and comparison, employs a fairly complex algorithm for correct sorting in a wide range of languages and when using a wide range of special characters. These rules need to take into account language-specific conventions; not everybody sorts their characters in what we would call 'alphabetical order'.

As far as Latin (ie "European") languages go, there is not much difference between the Unicode sorting and the simplified utf8mb4_general_ci sorting in MySQL, but there are still a few differences:

  • For examples, the Unicode collation sorts "ß" like "ss", and "Œ" like "OE" as people using those characters would normally want, whereas utf8mb4_general_ci sorts them as single characters (presumably like "s" and "e" respectively).

  • Some Unicode characters are defined as ignorable, which means they shouldn't count toward the sort order and the comparison should move on to the next character instead. utf8mb4_unicode_ci handles these properly.

In non-latin languages, such as Asian languages or languages with different alphabets, there may be a lot more differences between Unicode sorting and the simplified utf8mb4_general_ci sorting. The suitability of utf8mb4_general_ci will depend heavily on the language used. For some languages, it'll be quite inadequate.

What should you use?

There is almost certainly no reason to use utf8mb4_general_ci anymore, as we have left behind the point where CPU speed is low enough that the performance difference would be important. Your database will almost certainly be limited by other bottlenecks than this.

In the past, some people recommended to use utf8mb4_general_ci except when accurate sorting was going to be important enough to justify the performance cost. Today, that performance cost has all but disappeared, and developers are treating internationalization more seriously.

There's an argument to be made that if speed is more important to you than accuracy, you may as well not do any sorting at all. It's trivial to make an algorithm faster if you do not need it to be accurate. So, utf8mb4_general_ci is a compromise that's probably not needed for speed reasons and probably also not suitable for accuracy reasons.

One other thing I'll add is that even if you know your application only supports the English language, it may still need to deal with people's names, which can often contain characters used in other languages in which it is just as important to sort correctly. Using the Unicode rules for everything helps add peace of mind that the very smart Unicode people have worked very hard to make sorting work properly.

What the parts mean

Firstly, ci is for case-insensitive sorting and comparison. This means it's suitable for textual data, and case is not important. The other types of collation are cs (case-sensitive) for textual data where case is important, and bin, for where the encoding needs to match, bit for bit, which is suitable for fields which are really encoded binary data (including, for example, Base64). Case-sensitive sorting leads to some weird results and case-sensitive comparison can result in duplicate values differing only in letter case, so case-sensitive collations are falling out of favor for textual data - if case is significant to you, then otherwise ignorable punctuation and so on is probably also significant, and a binary collation might be more appropriate.

Next, unicode or general refers to the specific sorting and comparison rules - in particular, the way text is normalized or compared. There are many different sets of rules for the utf8mb4 character encoding, with unicode and general being two that attempt to work well in all possible languages rather than one specific one. The differences between these two sets of rules are the subject of this answer. Note that unicode uses rules from Unicode 4.0. Recent versions of MySQL add the rulesets unicode_520 using rules from Unicode 5.2, and 0900 (dropping the "unicode_" part) using rules from Unicode 9.0.

And lastly, utf8mb4 is of course the character encoding used internally. In this answer I'm talking only about Unicode based encodings.

What is the maximum characters for the NVARCHAR(MAX)?

I think actually nvarchar(MAX) can store approximately 1070000000 chars.

Create aar file in Android Studio

If your library is set up as an Android library (i.e. it uses the apply plugin: 'com.android.library' statement in its build.gradle file), it will output an .aar when it's built. It will show up in the build/outputs/aar/ directory in your module's directory.

You can choose the "Android Library" type in File > New Module to create a new Android Library.

Getting NetworkCredential for current user (C#)

If the web service being invoked uses windows integrated security, creating a NetworkCredential from the current WindowsIdentity should be sufficient to allow the web service to use the current users windows login. However, if the web service uses a different security model, there isn't any way to extract a users password from the current identity ... that in and of itself would be insecure, allowing you, the developer, to steal your users passwords. You will likely need to provide some way for your user to provide their password, and keep it in some secure cache if you don't want them to have to repeatedly provide it.

Edit: To get the credentials for the current identity, use the following:

Uri uri = new Uri("http://tempuri.org/");
ICredentials credentials = CredentialCache.DefaultCredentials;
NetworkCredential credential = credentials.GetCredential(uri, "Basic");

Git: Recover deleted (remote) branch

If the delete is recent enough (Like an Oh-NO! moment) you should still have a message:

Deleted branch <branch name> (was abcdefghi).

you can still run:

git checkout abcdefghi

git checkout -b <some new branch name or the old one>

Create SQL identity as primary key?

If you're using T-SQL, the only thing wrong with your code is that you used braces {} instead of parentheses ().

PS: Both IDENTITY and PRIMARY KEY imply NOT NULL, so you can omit that if you wish.

Connecting to Microsoft SQL server using Python

This is how I do it...

import pyodbc 
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=server_name;"
                      "Database=db_name;"
                      "Trusted_Connection=yes;")


cursor = cnxn.cursor()
cursor.execute('SELECT * FROM Table')

for row in cursor:
    print('row = %r' % (row,))

Relevant resources:

Importing a long list of constants to a Python file

create constant file with any name like my_constants.py declare constant like that

CONSTANT_NAME = "SOME VALUE"

For accessing constant in your code import file like that

import my_constants as constant

and access the constant value as -

constant.CONSTANT_NAME

INSERT INTO...SELECT for all MySQL columns

Addition to Mark Byers answer :

Sometimes you also want to insert Hardcoded details else there may be Unique constraint fail etc. So use following in such situation where you override some values of the columns.

INSERT INTO matrimony_domain_details (domain, type, logo_path)
SELECT 'www.example.com', type, logo_path
FROM matrimony_domain_details
WHERE id = 367

Here domain value is added by me me in Hardcoded way to get rid from Unique constraint.

Free Online Team Foundation Server

Readify used to run their TFSNow hosted TFS service, but I don't think it's going any longer. The only others I've heard of, apart from CodePlex, aren't free:

Attribute Error: 'list' object has no attribute 'split'

what i did was a quick fix by converting readlines to string but i do not recommencement it but it works and i dont know if there are limitations or not

`def getQuakeData():
    filename = input("Please enter the quake file: ")
    readfile = open(filename, "r")
    readlines = str(readfile.readlines())

    Type = readlines.split(",")
    x = Type[1]
    y = Type[2]
    for points in Type:
        print(x,y)
getQuakeData()`

Use and meaning of "in" in an if statement?

the reserved word "in" is used to look inside an object that can be iterated over.

list_obj = ['a', 'b', 'c']
tuple_obj = ('a', 1, 2.0)
dict_obj = {'a': 1, 'b': 2.0}
obj_to_find = 'c'
if obj_to_find in list_obj:
    print('Object {0} is in {1}'.format(obj_to_find, list_obj))
obj_to_find = 2.0
if obj_to_find in tuple_obj:
    print('Object {0} is in {1}'.format(obj_to_find, tuple_obj))
obj_to_find = 'b'
if obj_to_find in dict_obj:
    print('Object {0} is in {1}'.format(obj_to_find, dict_obj))

Output:

Object c is in ['a', 'b', 'c']
Object 2.0 is in ('a', 1, 2.0)
Object b is in {'a': 1, 'b': 2.0}

However

cannot_iterate_over = 5.5
obj_to_find = 5.5
if obj_to_find in cannot_iterate_over:
    print('Object {0} is in {1}'.format(obj_to_find, cannot_iterate_over))

will throw

Traceback (most recent call last):
File "/home/jgranger/workspace/sandbox/src/csv_file_creator.py", line 43, in <module>
if obj_to_find in cannot_iterate_over:
TypeError: argument of type 'float' is not iterable

In your case, raw_input("> ") returns iterable object or it will throw TypeError

Install a module using pip for specific python version

Have tried this on a Windows machine and it works

If you wanna install opencv for python version 3.7, heres how you do it!

py -3.7 -m pip install opencv-python

T-SQL: Deleting all duplicate rows but keeping one

Here's my twist on it, with a runnable example. Note this will only work in the situation where Id is unique, and you have duplicate values in other columns.

DECLARE @SampleData AS TABLE (Id int, Duplicate varchar(20))

INSERT INTO @SampleData
SELECT 1, 'ABC' UNION ALL
SELECT 2, 'ABC' UNION ALL
SELECT 3, 'LMN' UNION ALL
SELECT 4, 'XYZ' UNION ALL
SELECT 5, 'XYZ'

DELETE FROM @SampleData WHERE Id IN (
    SELECT Id FROM (
        SELECT 
            Id
            ,ROW_NUMBER() OVER (PARTITION BY [Duplicate] ORDER BY Id) AS [ItemNumber]
            -- Change the partition columns to include the ones that make the row distinct
        FROM 
            @SampleData
    ) a WHERE ItemNumber > 1 -- Keep only the first unique item
)

SELECT * FROM @SampleData

And the results:

Id          Duplicate
----------- ---------
1           ABC
3           LMN
4           XYZ

Not sure why that's what I thought of first... definitely not the simplest way to go but it works.

Javascript - remove an array item by value

You'll want to use .indexOf() and .splice(). Something like:

tag_story.splice(tag_story.indexOf(90),1);

How to add a TextView to a LinearLayout dynamically in Android?

If you are using Linearlayout. its params should be "wrap_content" to add dynamic data in your layout xml. if you use match or fill parent then you cannot see the output.

It Should be like this.

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content" android:layout_height="wrap_content">
        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
        </ListView>
    </LinearLayout>

How to launch an Activity from another Application in Android

// in onCreate method
String appName = "Gmail";
String packageName = "com.google.android.gm";
openApp(context, appName, packageName);

public static void openApp(Context context, String appName, String packageName) {
    if (isAppInstalled(context, packageName))
        if (isAppEnabled(context, packageName))
            context.startActivity(context.getPackageManager().getLaunchIntentForPackage(packageName));
        else Toast.makeText(context, appName + " app is not enabled.", Toast.LENGTH_SHORT).show();
    else Toast.makeText(context, appName + " app is not installed.", Toast.LENGTH_SHORT).show();
}

private static boolean isAppInstalled(Context context, String packageName) {
    PackageManager pm = context.getPackageManager();
    try {
        pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
        return true;
    } catch (PackageManager.NameNotFoundException ignored) {
    }
    return false;
}

private static boolean isAppEnabled(Context context, String packageName) {
    boolean appStatus = false;
    try {
        ApplicationInfo ai = context.getPackageManager().getApplicationInfo(packageName, 0);
        if (ai != null) {
            appStatus = ai.enabled;
        }
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return appStatus;
}

ReactJS: "Uncaught SyntaxError: Unexpected token <"

Add type="text/babel" to the script that includes the .jsx file and add this: <script src="https://npmcdn.com/[email protected]/browser.min.js"></script>

Replace all occurrences of a String using StringBuilder?

Look at JavaDoc of replaceAll method of String class:

Replaces each substring of this string that matches the given regular expression with the given replacement. An invocation of this method of the form str.replaceAll(regex, repl) yields exactly the same result as the expression

java.util.regex.Pattern.compile(regex).matcher(str).replaceAll(repl)

As you can see you can use Pattern and Matcher to do that.

POST: sending a post request in a url itself

In Java you can use GET which shows requested data on URL.But POST method cannot , because POST has body but GET donot have body.

How to select all elements with a particular ID in jQuery?

Though there are other correct answers here (such as using classes), from an academic point of view it is of course possible to have multiple divs with the same ID, and it is possible to select them with jQuery.

When you use

jQuery("#elemid") 

it selects only the first element with the given ID.

However, when you select by attribute (e.g. id in your case), it returns all matching elements, like so:

jQuery("[id=elemid]") 

This of course works for selection on any attribute, and you could further refine your selection by specifying the tag in question (e.g. div in your case)

jQuery("div[id=elemid]") 

How to draw border on just one side of a linear layout?

There is no mention about nine-patch files here. Yes, you have to create the file, however it's quite easy job and it's really "cross-version and transparency supporting" solution. If the file is placed to the drawable-nodpi directory, it works px based, and in the drawable-mdpi works approximately as dp base (thanks to resample).

Example file for the original question (border-right:1px solid red;) is here:

http://ge.tt/517ZIFC2/v/3?c

Just place it to the drawable-nodpi directory.

Padding is invalid and cannot be removed?

For the benefit of people searching, it may be worth checking the input being decrypted. In my case, the info being sent for decryption was (wrongly) going in as an empty string. It resulted in the padding error.

This may relate to rossum's answer, but thought it worth mentioning.

Get type of a generic parameter in Java with reflection

No it isn't possible.

You can get a generic type of a field given a class is the only exception to that rule and even that's a bit of a hack.

See Knowing type of generic in Java for an example of that.

VIM Disable Automatic Newline At End Of File

OK, you being on Windows complicates things ;)

As the 'binary' option resets the 'fileformat' option (and writing with 'binary' set always writes with unix line endings), let's take out the big hammer and do it externally!

How about defining an autocommand (:help autocommand) for the BufWritePost event? This autocommand is executed after every time you write a whole buffer. In this autocommand call a small external tool (php, perl or whatever script) that strips off the last newline of the just written file.

So this would look something like this and would go into your .vimrc file:

autocmd!   "Remove all autocmds (for current group), see below"
autocmd BufWritePost *.php !your-script <afile>

Be sure to read the whole vim documentation about autocommands if this is your first time dealing with autocommands. There are some caveats, e.g. it's recommended to remove all autocmds in your .vimrc in case your .vimrc might get sourced multiple times.

Reset the Value of a Select Box

I presume you only want to reset a single element. Resetting an entire form is simple: call its reset method.

The easiest way to "reset" a select element is to set its selectedIndex property to the default value. If you know that no option is the default selected option, just set the select elemen'ts selectedIndex property to an appropriate value:

function resetSelectElement(selectElement) {
    selecElement.selectedIndex = 0;  // first option is selected, or
                                     // -1 for no option selected
}

However, since one option may have the selected attribtue or otherwise be set to the default selected option, you may need to do:

function resetSelectElement(selectElement) {
    var options = selectElement.options;

    // Look for a default selected option
    for (var i=0, iLen=options.length; i<iLen; i++) {

        if (options[i].defaultSelected) {
            selectElement.selectedIndex = i;
            return;
        }
    }

    // If no option is the default, select first or none as appropriate
    selectElement.selectedIndex = 0; // or -1 for no option selected
}

And beware of setting attributes rather than properties, they have different effects in different browsers.

Invalid column count in CSV input on line 1 Error

I had a similar problem with phpmyAdmin. The column count in the file to be imported matched the columns in the target database table. I tried importing files in both .csv and .ods format to no avail, getting a variety of errors including one arguing that the column count was wrong.

Both the .csv and .ods files were created with LibreOffice 5.204. Based on a bit of experience with import issues in years past, I decided to remake the files with the gnumeric spreadsheet, exporting the .ods in compliance with the "strict" format standard. Voila! No more import problem. While I haven't had time to investigate the issue further, I suspect that something has changed in the internal structure of LibreOffice's file output.

Transparent image - background color

If I understand you right, you can do this:

<img src="image.png" style="background-color:red;" />

In fact, you can even apply a whole background-image to the image, resulting in two "layers" without the need for multi-background support in the browser ;)

jQuery disable/enable submit button

Here's the solution for file input field.

To disable a submit button for file field when a file is not chosen, then enable after the user chooses a file to upload:

$(document).ready(function(){
    $("#submitButtonId").attr("disabled", "disabled");
    $("#fileFieldId").change(function(){
        $("#submitButtonId").removeAttr("disabled");
    });
});

Html:

<%= form_tag your_method_path, :multipart => true do %><%= file_field_tag :file, :accept => "text/csv", :id => "fileFieldId" %><%= submit_tag "Upload", :id => "submitButtonId" %><% end %>

Module 'tensorflow' has no attribute 'contrib'

I used google colab to run my models and everything was perfect untill i used inline tesorboard. With tensorboard inline, I had the same issue of "Module 'tensorflow' has no attribute 'contrib'".

It was able to run training when rebuild and reinstall the model using setup.py(research folder) after initialising tensorboard.

Rendering JSON in controller

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

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

We also have a controller that looks like this:

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

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

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

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

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

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

Now we can crate a JSONP request as follows:

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

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

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

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

Should I return EXIT_SUCCESS or 0 from main()?

It does not matter. Both are the same.

C++ Standard Quotes:

If the value of status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned.

How to fix error ::Format of the initialization string does not conform to specification starting at index 0::

I originally was calling the connection string value as shown below (VB.NET) and got the error being mentioned

 Using connection As New SqlConnection("connectionStringName") 
  '// more code would go here...
 End Using

adding a reference to System.Configuration and updating my code as shown below was my solution. The connection string was not the problem since others controls used it without any issues (SqlDataSource)

Using connection As New SqlConnection(ConfigurationManager.ConnectionStrings("connectionStringName").ConnectionString)
    '// more code would go here...
End Using

Cut Corners using CSS

CSS Clip-Path

Using a clip-path is a new, up and coming alternative. Its starting to get supported more and more and is now becoming well documented. Since it uses SVG to create the shape, it is responsive straight out of the box.

_x000D_
_x000D_
div {_x000D_
  width: 200px;_x000D_
  min-height: 200px;_x000D_
  -webkit-clip-path: polygon(0 0, 0 100%, 100% 100%, 100% 25%, 75% 0);_x000D_
  clip-path: polygon(0 0, 0 100%, 100% 100%, 100% 25%, 75% 0);_x000D_
  background: lightblue;_x000D_
}
_x000D_
<div>_x000D_
  <p>Some Text</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

CSS Transform

I have an alternative to web-tiki's transform answer.

_x000D_
_x000D_
body {_x000D_
  background: lightgreen;_x000D_
}_x000D_
div {_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  background: transparent;_x000D_
  position: relative;_x000D_
  overflow: hidden;_x000D_
}_x000D_
div.bg {_x000D_
  width: 200%;_x000D_
  height: 200%;_x000D_
  background: lightblue;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: -75%;_x000D_
  transform-origin: 50% 50%;_x000D_
  transform: rotate(45deg);_x000D_
  z-index: -1;_x000D_
}
_x000D_
<div>_x000D_
  <div class="bg"></div>_x000D_
  <p>Some Text</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In SQL Server, what does "SET ANSI_NULLS ON" mean?

SET ANSI_NULLS ON

IT Returns all values including null values in the table

SET ANSI_NULLS off

it Ends when columns contains null values

Create 3D array using Python

There are many ways to address your problem.

  1. First one as accepted answer by @robert. Here is the generalised solution for it:
def multi_dimensional_list(value, *args):
  #args dimensions as many you like. EG: [*args = 4,3,2 => x=4, y=3, z=2]
  #value can only be of immutable type. So, don't pass a list here. Acceptable value = 0, -1, 'X', etc.
  if len(args) > 1:
    return [ multi_dimensional_list(value, *args[1:]) for col in range(args[0])]
  elif len(args) == 1: #base case of recursion
    return [ value for col in range(args[0])]
  else: #edge case when no values of dimensions is specified.
    return None

Eg:

>>> multi_dimensional_list(-1, 3, 4)  #2D list
[[-1, -1, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1]]
>>> multi_dimensional_list(-1, 4, 3, 2)  #3D list
[[[-1, -1], [-1, -1], [-1, -1]], [[-1, -1], [-1, -1], [-1, -1]], [[-1, -1], [-1, -1], [-1, -1]], [[-1, -1], [-1, -1], [-1, -1]]]
>>> multi_dimensional_list(-1, 2, 3, 2, 2 )  #4D list
[[[[-1, -1], [-1, -1]], [[-1, -1], [-1, -1]], [[-1, -1], [-1, -1]]], [[[-1, -1], [-1, -1]], [[-1, -1], [-1, -1]], [[-1, -1], [-1, -1]]]]

P.S If you are keen to do validation for correct values for args i.e. only natural numbers, then you can write a wrapper function before calling this function.

  1. Secondly, any multidimensional dimensional array can be written as single dimension array. This means you don't need a multidimensional array. Here are the function for indexes conversion:
def convert_single_to_multi(value, max_dim):
  dim_count = len(max_dim)
  values = [0]*dim_count
  for i in range(dim_count-1, -1, -1): #reverse iteration
    values[i] = value%max_dim[i]
    value /= max_dim[i]
  return values


def convert_multi_to_single(values, max_dim):
  dim_count = len(max_dim)
  value = 0
  length_of_dimension = 1
  for i in range(dim_count-1, -1, -1): #reverse iteration
    value += values[i]*length_of_dimension
    length_of_dimension *= max_dim[i]
  return value

Since, these functions are inverse of each other, here is the output:

>>> convert_single_to_multi(convert_multi_to_single([1,4,6,7],[23,45,32,14]),[23,45,32,14])
[1, 4, 6, 7]
>>> convert_multi_to_single(convert_single_to_multi(21343,[23,45,32,14]),[23,45,32,14])
21343
  1. If you are concerned about performance issues then you can use some libraries like pandas, numpy, etc.

Working with INTERVAL and CURDATE in MySQL

You need DATE_ADD/DATE_SUB:

AND v.date > (DATE_SUB(CURDATE(), INTERVAL 2 MONTH))
AND v.date < (DATE_SUB(CURDATE(), INTERVAL 1 MONTH))

should work.

Count number of 1's in binary representation

The following is a C solution using bit operators:

int numberOfOneBitsInInteger(int input) {
  int numOneBits = 0;

  int currNum = input;
  while (currNum != 0) {
    if ((currNum & 1) == 1) {
      numOneBits++;
    }
    currNum = currNum >> 1;
  }
  return numOneBits;
}

The following is a Java solution using powers of 2:

public static int numOnesInBinary(int n) {

  if (n < 0) return -1;

  int j = 0;
  while ( n > Math.pow(2, j)) j++;

  int result = 0;
  for (int i=j; i >=0; i--){
    if (n >= Math.pow(2, i)) {
        n = (int) (n - Math.pow(2,i));
        result++;    
    }
  }

  return result;
}

PHP + MySQL transactions examples

As this is the first result on google for "php mysql transaction", I thought I'd add an answer that explicitly demonstrates how to do this with mysqli (as the original author wanted examples). Here's a simplified example of transactions with PHP/mysqli:

// let's pretend that a user wants to create a new "group". we will do so
// while at the same time creating a "membership" for the group which
// consists solely of the user themselves (at first). accordingly, the group
// and membership records should be created together, or not at all.
// this sounds like a job for: TRANSACTIONS! (*cue music*)

$group_name = "The Thursday Thumpers";
$member_name = "EleventyOne";
$conn = new mysqli($db_host,$db_user,$db_passwd,$db_name); // error-check this

// note: this is meant for InnoDB tables. won't work with MyISAM tables.

try {

    $conn->autocommit(FALSE); // i.e., start transaction

    // assume that the TABLE groups has an auto_increment id field
    $query = "INSERT INTO groups (name) ";
    $query .= "VALUES ('$group_name')";
    $result = $conn->query($query);
    if ( !$result ) {
        $result->free();
        throw new Exception($conn->error);
    }

    $group_id = $conn->insert_id; // last auto_inc id from *this* connection

    $query = "INSERT INTO group_membership (group_id,name) ";
    $query .= "VALUES ('$group_id','$member_name')";
    $result = $conn->query($query);
    if ( !$result ) {
        $result->free();
        throw new Exception($conn->error);
    }

    // our SQL queries have been successful. commit them
    // and go back to non-transaction mode.

    $conn->commit();
    $conn->autocommit(TRUE); // i.e., end transaction
}
catch ( Exception $e ) {

    // before rolling back the transaction, you'd want
    // to make sure that the exception was db-related
    $conn->rollback(); 
    $conn->autocommit(TRUE); // i.e., end transaction   
}

Also, keep in mind that PHP 5.5 has a new method mysqli::begin_transaction. However, this has not been documented yet by the PHP team, and I'm still stuck in PHP 5.3, so I can't comment on it.

What is the maximum length of a Push Notification alert text?

see my test here

I could send up to 33 Chinese characters and 13 bytes of custom values.

Javascript: formatting a rounded number to N decimals

PHP-Like rounding Method

The code below can be used to add your own version of Math.round to your own namespace which takes a precision parameter. Unlike Decimal rounding in the example above, this performs no conversion to and from strings, and the precision parameter works same way as PHP and Excel whereby a positive 1 would round to 1 decimal place and -1 would round to the tens.

var myNamespace = {};
myNamespace.round = function(number, precision) {
    var factor = Math.pow(10, precision);
    var tempNumber = number * factor;
    var roundedTempNumber = Math.round(tempNumber);
    return roundedTempNumber / factor;
};

myNamespace.round(1234.5678, 1); // 1234.6
myNamespace.round(1234.5678, -1); // 1230

from Mozilla Developer reference for Math.round()

What does += mean in Python?

Google 'python += operator' leads you to http://docs.python.org/library/operator.html

Search for += once the page loads up for a more detailed answer.

The type or namespace name 'System' could not be found

I attempted to re-create your issue and came up with a similar error when the solution was created in visual studio 2013 and then tried building it in in vs 2015.

I was able to get a successful build once I reinstalled NuGet Package Manager (and closed, then reopened VS 2015).

References / Credit

There are several SO questions relating to build issues via with earlier version of NPM for VS 2015 (i.e. I'm just passing along what I've tried and worked out). Recurring resolution is usually update / reinstall NPM or change execution policy in power shell. I tend to like the update + restart approach to avoid tinkering with the black boxes in windows. one source: https://stackoverflow.com/a/32251092/1158842 There may also be an issue of MSBuild Integrated solutions, in which case migrating away from the NuGet resources in the solution could do the trick.

Source: https://stackoverflow.com/a/31811461/1158842

The number of method references in a .dex file cannot exceed 64k API 17

**

For Unity Game Developers

**

If anyone comes here because this error showed up in their Unity project, Go to File->Build Settings -> Player Settings -> Player. go to Publishing Settings and under the Build tab, enable "Custom Launcher Gradle Template". a path will be shown under that text. go to the path and add multiDexEnabled true like this:

defaultConfig {
    minSdkVersion **MINSDKVERSION**
    targetSdkVersion **TARGETSDKVERSION**
    applicationId '**APPLICATIONID**'
    ndk {
        abiFilters **ABIFILTERS**
    }
    versionCode **VERSIONCODE**
    versionName '**VERSIONNAME**'
    multiDexEnabled true
}

Column/Vertical selection with Keyboard in SublimeText 3

Commenting just so people can have a solution to the intended question.

You can do what you are wanting but it isn't quite as nice as Notepad++ but it may work for small solutions decently enough.

In sublime if you hold ctrl, or mac equiv., and select the word/characters you want on a single line with the mouse and still holding ctrl go to another line and select the word/characters you want on that line it will be additive and you will build your selection. I mainly use notepadd++ as my extractor and data cleanup and sublime for actual development.

The other way is if your columns are in perfect alignment you can simply middle click on windows or option + click on mac and this enables you to select text in a square like fashion, Columns, inside the lines of text.

How to read the output from git diff?

On my mac:

info diff then select: Output formats -> Context -> Unified format -> Detailed Unified :

Or online man diff on gnu following the same path to the same section:

File: diff.info, Node: Detailed Unified, Next: Example Unified, Up: Unified Format

Detailed Description of Unified Format ......................................

The unified output format starts with a two-line header, which looks like this:

 --- FROM-FILE FROM-FILE-MODIFICATION-TIME
 +++ TO-FILE TO-FILE-MODIFICATION-TIME

The time stamp looks like `2002-02-21 23:30:39.942229878 -0800' to indicate the date, time with fractional seconds, and time zone.

You can change the header's content with the `--label=LABEL' option; see *Note Alternate Names::.

Next come one or more hunks of differences; each hunk shows one area where the files differ. Unified format hunks look like this:

 @@ FROM-FILE-RANGE TO-FILE-RANGE @@
  LINE-FROM-EITHER-FILE
  LINE-FROM-EITHER-FILE...

The lines common to both files begin with a space character. The lines that actually differ between the two files have one of the following indicator characters in the left print column:

`+' A line was added here to the first file.

`-' A line was removed here from the first file.

Is there a way to make mv create the directory to be moved to if it doesn't exist?

Making use of the tricks in "Getting the last argument passed to a shell script" we can make a simple shell function that should work no matter how many files you want to move:

# Bash only
mvdir() { mkdir -p "${@: -1}" && mv "$@"; }

# Other shells may need to search for the last argument
mvdir() { for last; do true; done; mkdir -p "$last" && mv "$@"; }

PHP code to get selected text of a combo box

if you fetching it from database then

<select id="cmbMake" name="Make" >
<option value="">Select Manufacturer</option>
<?php $s2="select * from <tablename>"; 
$q2=mysql_query($s2); 
while($rw2=mysql_fetch_array($q2)) { 
?>
<option value="<?php echo $rw2['id']; ?>"><?php echo $rw2['carname']; ?></option><?php } ?>
</select>

Is there an addHeaderView equivalent for RecyclerView?

Easy and reusable ItemDecoration

Static headers can easily be added with an ItemDecoration and without any further changes.

// add the decoration. done.
HeaderDecoration headerDecoration = new HeaderDecoration(/* init */);
recyclerView.addItemDecoration(headerDecoration);

The decoration is also reusable since there is no need to modify the adapter or the RecyclerView at all.

The sample code provided below will require a view to add to the top which can just be inflated like everything else. It can look like this:

HeaderDecoration sample

Why static?

If you just have to display text and images this solution is for you—there is no possibility for user interaction like buttons or view pagers, since it will just be drawn to top of your list.

Empty list handling

If there is no view to decorate, the decoration will not be drawn. You will still have to handle an empty list yourself. (One possible workaround would be to add a dummy item to the adapter.)

The code

You can find the full source code here on GitHub including a Builder to help with the initialization of the decorator, or just use the code below and supply your own values to the constructor.

Please be sure to set a correct layout_height for your view. e.g. match_parent might not work properly.

public class HeaderDecoration extends RecyclerView.ItemDecoration {

    private final View mView;
    private final boolean mHorizontal;
    private final float mParallax;
    private final float mShadowSize;
    private final int mColumns;
    private final Paint mShadowPaint;

    public HeaderDecoration(View view, boolean scrollsHorizontally, float parallax, float shadowSize, int columns) {
        mView = view;
        mHorizontal = scrollsHorizontally;
        mParallax = parallax;
        mShadowSize = shadowSize;
        mColumns = columns;

        if (mShadowSize > 0) {
            mShadowPaint = new Paint();
            mShadowPaint.setShader(mHorizontal ?
                    new LinearGradient(mShadowSize, 0, 0, 0,
                            new int[]{Color.argb(55, 0, 0, 0), Color.argb(55, 0, 0, 0), Color.argb(3, 0, 0, 0)},
                            new float[]{0f, .5f, 1f},
                            Shader.TileMode.CLAMP) :
                    new LinearGradient(0, mShadowSize, 0, 0,
                            new int[]{Color.argb(55, 0, 0, 0), Color.argb(55, 0, 0, 0), Color.argb(3, 0, 0, 0)},
                            new float[]{0f, .5f, 1f},
                            Shader.TileMode.CLAMP));
        } else {
            mShadowPaint = null;
        }
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
        // layout basically just gets drawn on the reserved space on top of the first view
        mView.layout(parent.getLeft(), 0, parent.getRight(), mView.getMeasuredHeight());

        for (int i = 0; i < parent.getChildCount(); i++) {
            View view = parent.getChildAt(i);
            if (parent.getChildAdapterPosition(view) == 0) {
                c.save();
                if (mHorizontal) {
                    c.clipRect(parent.getLeft(), parent.getTop(), view.getLeft(), parent.getBottom());
                    final int width = mView.getMeasuredWidth();
                    final float left = (view.getLeft() - width) * mParallax;
                    c.translate(left, 0);
                    mView.draw(c);
                    if (mShadowSize > 0) {
                        c.translate(view.getLeft() - left - mShadowSize, 0);
                        c.drawRect(parent.getLeft(), parent.getTop(), mShadowSize, parent.getBottom(), mShadowPaint);
                    }
                } else {
                    c.clipRect(parent.getLeft(), parent.getTop(), parent.getRight(), view.getTop());
                    final int height = mView.getMeasuredHeight();
                    final float top = (view.getTop() - height) * mParallax;
                    c.translate(0, top);
                    mView.draw(c);
                    if (mShadowSize > 0) {
                        c.translate(0, view.getTop() - top - mShadowSize);
                        c.drawRect(parent.getLeft(), parent.getTop(), parent.getRight(), mShadowSize, mShadowPaint);
                    }
                }
                c.restore();
                break;
            }
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        if (parent.getChildAdapterPosition(view) < mColumns) {
            if (mHorizontal) {
                if (mView.getMeasuredWidth() <= 0) {
                    mView.measure(View.MeasureSpec.makeMeasureSpec(parent.getMeasuredWidth(), View.MeasureSpec.AT_MOST),
                            View.MeasureSpec.makeMeasureSpec(parent.getMeasuredHeight(), View.MeasureSpec.AT_MOST));
                }
                outRect.set(mView.getMeasuredWidth(), 0, 0, 0);
            } else {
                if (mView.getMeasuredHeight() <= 0) {
                    mView.measure(View.MeasureSpec.makeMeasureSpec(parent.getMeasuredWidth(), View.MeasureSpec.AT_MOST),
                            View.MeasureSpec.makeMeasureSpec(parent.getMeasuredHeight(), View.MeasureSpec.AT_MOST));
                }
                outRect.set(0, mView.getMeasuredHeight(), 0, 0);
            }
        } else {
            outRect.setEmpty();
        }
    }
}

Please note: The GitHub project is my personal playground. It is not thorougly tested, which is why there is no library yet.

What does it do?

An ItemDecoration is additional drawing to an item of a list. In this case, a decoration is drawn to the top of the first item.

The view gets measured and laid out, then it is drawn to the top of the first item. If a parallax effect is added it will also be clipped to the correct bounds.

How to convert column with dtype as object to string in Pandas Dataframe

Not answering the question directly, but it might help someone else.

I have a column called Volume, having both - (invalid/NaN) and numbers formatted with ,

df['Volume'] = df['Volume'].astype('str')
df['Volume'] = df['Volume'].str.replace(',', '')
df['Volume'] = pd.to_numeric(df['Volume'], errors='coerce')

Casting to string is required for it to apply to str.replace

pandas.Series.str.replace
pandas.to_numeric

How can I write to the console in PHP?

I find this helpful:

function console($data, $priority, $debug)
{
    if ($priority <= $debug)
    {
        $output = '<script>console.log("' . str_repeat(" ", $priority-1) . (is_array($data) ? implode(",", $data) : $data) . '");</script>';

        echo $output;
    }
}

And use it like:

<?php
    $debug = 5; // All lower and equal priority logs will be displayed
    console('Important', 1 , $debug);
    console('Less Important', 2 , $debug);
    console('Even Less Important', 5 , $debug);
    console('Again Important', 1 , $debug);
?>

Which outputs in console:

Important
 Less Important
     Even Less Important
Again Important

And you can switch off less important logs by limiting them using the $debug value.

Split string into array of characters?

the problem is that there is no built in method (or at least none of us could find one) to do this in vb. However, there is one to split a string on the spaces, so I just rebuild the string and added in spaces....

Private Function characterArray(ByVal my_string As String) As String()
  'create a temporary string to store a new string of the same characters with spaces
  Dim tempString As String = ""
  'cycle through the characters and rebuild my_string as a string with spaces 
  'and assign the result to tempString.  
  For Each c In my_string
     tempString &= c & " "
  Next
  'return return tempString as a character array.  
  Return tempString.Split()
End Function

How to create a cron job using Bash automatically without the interactive editor?

Chances are you are automating this, and you don't want a single job added twice. In that case use:

__cron="1 2 3 4 5 /root/bin/backup.sh"
cat <(crontab -l) |grep -v "${__cron}" <(echo "${__cron}")

This only works if you're using BASH. I'm not aware of the correct DASH (sh) syntax.

Update: This doesn't work if the user doesn't have a crontab yet. A more reliable way would be:

(crontab -l ; echo "1 2 3 4 5 /root/bin/backup.sh") | sort - | uniq - | crontab - 

Alternatively, if your distro supports it, you could also use a separate file:

echo "1 2 3 4 5 /root/bin/backup.sh" |sudo tee /etc/crond.d/backup

Found those in another SO question.

complex if statement in python

It is possible to write like this:

elif var1 in [80, 443] or 1024 < var1 < 65535

This way you check if var1 appears in that a list, then you make just 1 check, didn't repeat the "var1" one extra time, and looks clear:

if var1 in [80, 443] or 1024 < var1 < 65535: print 'good' else: print 'bad' ....:
good

jquery - check length of input field?

If you mean that you want to enable the submit after the user has typed at least one character, then you need to attach a key event that will check it for you.

Something like:

$("#fbss").keypress(function() {
    if($(this).val().length > 1) {
         // Enable submit button
    } else {
         // Disable submit button
    }
});

Twitter API returns error 215, Bad Authentication Data

I'm using HybridAuth and was running into this error connecting to Twitter. I tracked it down to (me) sending Twitter an incorrectly cased request type (get/post instead of GET/POST).

This would cause a 215:

$call = '/search/tweets.json';
$call_type = 'get';
$call_args = array(
    'q'           => 'pancakes',
    'count'       => 5,
);
$response = $provider_api->api( $call, $call_type, $call_args );

This would not:

$call = '/search/tweets.json';
$call_type = 'GET';
$call_args = array(
    'q'           => 'pancakes',
    'count'       => 5,
);
$response = $provider_api->api( $call, $call_type, $call_args );

Side note: In the case of HybridAuth the following also would not (because HA internally provides the correctly-cased value for the request type):

$call = '/search/tweets.json';
$call_args = array(
    'q'           => 'pancakes',
    'count'       => 5,
);
$response = $providers['Twitter']->get( $call, $call_args );

cartesian product in pandas

With method chaining:

product = (
    df1.assign(key=1)
    .merge(df2.assign(key=1), on="key")
    .drop("key", axis=1)
)

Difference between Inheritance and Composition

I think this example explains clearly the differences between inheritance and composition.

In this exmple, the problem is solved using inheritance and composition. The author pays attention to the fact that ; in inheritance, a change in superclass might cause problems in derived class, that inherit it.

There you can also see the difference in representation when you use a UML for inheritance or composition.

http://www.javaworld.com/article/2076814/core-java/inheritance-versus-composition--which-one-should-you-choose-.html

What parameters should I use in a Google Maps URL to go to a lat-lon?

This should help with the new Google Maps:

http://maps.google.com/maps/place/<name>/@<lat>,<long>,15z/data=<mode-value>
  • The 'place' adds a marker.
  • 'name' could be a search term like "realtors"/"lawyers".
  • lat and long are the coordinates in decimal format and in that order.
  • 15z sets zoom level to 15 (between 1 ~ 20).
  • You can enforce a particular view mode (map is default) - earth or terrain by adding these: Terrain: /data=!5m1!1e4
    Earth: /data=!3m1!1e3

E.g.: https://www.google.com/maps/place/Lawyer/@48.8187768,2.3792362,15z/data=!3m1!1e3

References:
https://moz.com/blog/new-google-maps-url-parameters http://dddavemaps.blogspot.in/2015/07/google-maps-url-tricks.html

How to Lock Android App's Orientation to Portrait in Phones and Landscape in Tablets?

You have to add the android:screenOrientation="portrait" directive in your AndroidManifest.xml. This is to be done in your <activity> tag.

In addition, the Android Developers guide states that :

[...] you should also explicitly declare that your application requires either portrait or landscape orientation with the element. For example, <uses-feature android:name="android.hardware.screen.portrait" />.

Error 500: Premature end of script headers

In my case I had to change

#!/usr/bin/php

to

#!/usr/bin/php-cgi

Laravel 4 with Sentry 2 add user to a group on Registration

Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.

Do you have this:

use Cartalyst\Sentry\Sentry; 

In your code?

Ok, but if this line is working for you:

$user = $this->sentry->register(array(     'username' => e($data['username']),     'email' => e($data['email']),      'password' => e($data['password'])     )); 

So you already have it instantiated and you can surely do:

$adminGroup = $this->sentry->findGroupById(5); 

How can I execute Python scripts using Anaconda's version of Python?

I know this is old, but none of the answers here is a real solution if you want to be able to double-click Python files and have the correct interpreter used without modifying your PYTHONPATH or PATH every time you want to use a different interpreter. Sure, from the command line, activate my-environment works, but OP specifically asked about double-clicking.

In this case, the correct thing to do is use the Python launcher for Windows. Then, all you have to do is add #! path\to\interpreter\python.exe to the top of your script. Unfortunately, although the launcher comes standard with Python 3.3+, it is not included with Anaconda (see Python & Windows: Where is the python launcher?), and the simplest thing to do is to install it separately from here.

Find files in a folder using Java

For list out Json files from your given directory.

import java.io.File;
    import java.io.FilenameFilter;

    public class ListOutFilesInDir {
        public static void main(String[] args) throws Exception {

            File[] fileList = getFileList("directory path");

            for(File file : fileList) {
                System.out.println(file.getName());
            }
        }

        private static File[] getFileList(String dirPath) {
            File dir = new File(dirPath);   

            File[] fileList = dir.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.endsWith(".json");
                }
            });
            return fileList;
        }
    }

How to add meta tag in JavaScript

$('head').append('<meta http-equiv="X-UA-Compatible" content="IE=Edge" />');

or

var meta = document.createElement('meta');
meta.httpEquiv = "X-UA-Compatible";
meta.content = "IE=edge";
document.getElementsByTagName('head')[0].appendChild(meta);

Though I'm not certain it will have an affect as it will be generated after the page is loaded

If you want to add meta data tags for page description, use the SETTINGS of your DNN page to add Description and Keywords. Beyond that, the best way to go when modifying the HEAD is to dynamically inject your code into the HEAD via a third party module.

Found at http://www.dotnetnuke.com/Resources/Forums/forumid/7/threadid/298385/scope/posts.aspx

This may allow other meta tags, if you're lucky

Additional HEAD tags can be placed into Page Settings > Advanced Settings > Page Header Tags.

Found at http://www.dotnetnuke.com/Resources/Forums/forumid/-1/postid/223250/scope/posts.aspx

How to extract a substring using regex

you can use this i use while loop to store all matches substring in the array if you use

if (matcher.find()) { System.out.println(matcher.group(1)); }

you will get on matches substring so you can use this to get all matches substring

Matcher m = Pattern.compile("[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+").matcher(text);
   // Matcher  mat = pattern.matcher(text);
    ArrayList<String>matchesEmail = new ArrayList<>();
        while (m.find()){
            String s = m.group();
            if(!matchesEmail.contains(s))
                matchesEmail.add(s);
        }

    Log.d(TAG, "emails: "+matchesEmail);

How do you specify a debugger program in Code::Blocks 12.11?

  • In the Code::Blocks IDE, navigate Settings -> Debugger

  • In the tree control at the right, select Common -> GDB/CDB debugger -> Common.

  • Then in the dialog at the left you can enter Executable path and choose Debugger type = GDB or CDB, as well as configuring various other options.

Type List vs type ArrayList in Java

It is considered good style to store a reference to a HashSet or TreeSet in a variable of type Set.

Set<String> names = new HashSet<String>();

This way, you have to change only one line if you decide to use a TreeSet instead.

Also, methods that operate on sets should specify parameters of type Set:

public static void print(Set<String> s)

Then the method can be used for all set implementations.

In theory, we should make the same recommendation for linked lists, namely to save LinkedList references in variables of type List. However, in the Java library, the List interface is common to both the ArrayList and the LinkedList class. In particular, it has get and set methods for random access, even though these methods are very inefficient for linked lists.

You can’t write efficient code if you don’t know whether random access is efficient or not.

This is plainly a serious design error in the standard library, and I cannot recommend using the List interface for that reason.

To see just how embarrassing that error is, have a look at the source code for the binarySearch method of the Collections class. That method takes a List parameter, but binary search makes no sense for a linked list. The code then clumsily tries to discover whether the list is a linked list, and then switches to a linear search!

The Set interface and the Map interface, are well designed, and you should use them.

How to customize the background color of a UITableViewCell?

This will work in the latest Xcode.

-(UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath {
    cell.backgroundColor = [UIColor grayColor];
}

wp-admin shows blank page, how to fix it?

All your problem is solved right now just follow this instruction:

  1. go to your themes then de activate your current theme, just put "x" in the the first letter of your theme name.

for example this is your theme folder name: "mytheme" just put "x" in the first letter like this "xmytheme" tho di activate.

  1. Then after that go back to your wp-admin panel then BOOM! wp-admin accessable.

  2. When you access your wp-admin panel or you are on your dashboard, again activate your theme again, but before that. REMOVE THE "X" letter you putted in your theme name. example: "xmytheme" just remove "x", output like this: "mytheme"

  3. then activate it in your dashboard.

hope this help!.

subquery in codeigniter active record

->where() support passing any string to it and it will use it in the query.

You can try using this:

$this->db->select('*')->from('certs');
$this->db->where('`id` NOT IN (SELECT `id_cer` FROM `revokace`)', NULL, FALSE);

The ,NULL,FALSE in the where() tells CodeIgniter not to escape the query, which may mess it up.

UPDATE: You can also check out the subquery library I wrote.

$this->db->select('*')->from('certs');
$sub = $this->subquery->start_subquery('where_in');
$sub->select('id_cer')->from('revokace');
$this->subquery->end_subquery('id', FALSE);

Undefined index with $_POST

Try this:

I use this everywhere where there is a $_POST request.

$username=isset($_POST['username']) ? $_POST['username'] : "";

This is just a short hand boolean, if isset it will set it to $_POST['username'], if not then it will set it to an empty string.

Usage example:

if($username===""){ echo "Field is blank" } else { echo "Success" };

Setting format and value in input type="date"

The format is YYYY-MM-DD. You cannot change it.

$('#myinput').val('2013-12-31'); sets value

How can VBA connect to MySQL database in Excel?

Updating this topic with a more recent answer, solution that worked for me with version 8.0 of MySQL Connector/ODBC (downloaded at https://downloads.mysql.com/archives/c-odbc/):

Public oConn As ADODB.Connection
Sub MySqlInit()
    If oConn Is Nothing Then
        Dim str As String
        str = "Driver={MySQL ODBC 8.0 Unicode Driver};SERVER=xxxxx;DATABASE=xxxxx;PORT=3306;UID=xxxxx;PWD=xxxxx;"
        Set oConn = New ADODB.Connection
        oConn.Open str
    End If
End Sub

The most important thing on this matter is to check the proper name and version of the installed driver at: HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers\

Embedding a media player in a website using HTML

I found the that either IE or Chrome choked on most of these, or they required external libraries. I just wanted to play an MP3, and I found the page http://www.w3schools.com/html/html_sounds.asp very helpful.

<audio controls>
  <source src="horse.mp3" type="audio/mpeg">
  <embed height="50" width="100" src="horse.mp3">
</audio>

Worked for me in the browsers I tried, but I didn't have some of the old ones around at this time.

Select first and last row from grouped data

There is probably a faster way:

df %>%
  group_by(id) %>%
  arrange(stopSequence) %>%
  filter(row_number()==1 | row_number()==n())

Injecting $scope into an angular service function()

The $scope that you see being injected into controllers is not some service (like the rest of the injectable stuff), but is a Scope object. Many scope objects can be created (usually prototypically inheriting from a parent scope). The root of all scopes is the $rootScope and you can create a new child-scope using the $new() method of any scope (including the $rootScope).

The purpose of a Scope is to "glue together" the presentation and the business logic of your app. It does not make much sense to pass a $scope into a service.

Services are singleton objects used (among other things) to share data (e.g. among several controllers) and generally encapsulate reusable pieces of code (since they can be injected and offer their "services" in any part of your app that needs them: controllers, directives, filters, other services etc).

I am sure, various approaches would work for you. One is this:
Since the StudentService is in charge of dealing with student data, you can have the StudentService keep an array of students and let it "share" it with whoever might be interested (e.g. your $scope). This makes even more sense, if there are other views/controllers/filters/services that need to have access to that info (if there aren't any right now, don't be surprised if they start popping up soon).
Every time a new student is added (using the service's save() method), the service's own array of students will be updated and every other object sharing that array will get automatically updated as well.

Based on the approach described above, your code could look like this:

angular.
  module('cfd', []).

  factory('StudentService', ['$http', '$q', function ($http, $q) {
    var path = 'data/people/students.json';
    var students = [];

    // In the real app, instead of just updating the students array
    // (which will be probably already done from the controller)
    // this method should send the student data to the server and
    // wait for a response.
    // This method returns a promise to emulate what would happen 
    // when actually communicating with the server.
    var save = function (student) {
      if (student.id === null) {
        students.push(student);
      } else {
        for (var i = 0; i < students.length; i++) {
          if (students[i].id === student.id) {
            students[i] = student;
            break;
          }
        }
      }

      return $q.resolve(student);
    };

    // Populate the students array with students from the server.
    $http.get(path).then(function (response) {
      response.data.forEach(function (student) {
        students.push(student);
      });
    });

    return {
      students: students,
      save: save
    };     
  }]).

  controller('someCtrl', ['$scope', 'StudentService', 
    function ($scope, StudentService) {
      $scope.students = StudentService.students;
      $scope.saveStudent = function (student) {
        // Do some $scope-specific stuff...

        // Do the actual saving using the StudentService.
        // Once the operation is completed, the $scope's `students`
        // array will be automatically updated, since it references
        // the StudentService's `students` array.
        StudentService.save(student).then(function () {
          // Do some more $scope-specific stuff, 
          // e.g. show a notification.
        }, function (err) {
          // Handle the error.
        });
      };
    }
]);

One thing you should be careful about when using this approach is to never re-assign the service's array, because then any other components (e.g. scopes) will be still referencing the original array and your app will break.
E.g. to clear the array in StudentService:

/* DON'T DO THAT   */  
var clear = function () { students = []; }

/* DO THIS INSTEAD */  
var clear = function () { students.splice(0, students.length); }

See, also, this short demo.


LITTLE UPDATE:

A few words to avoid the confusion that may arise while talking about using a service, but not creating it with the service() function.

Quoting the docs on $provide:

An Angular service is a singleton object created by a service factory. These service factories are functions which, in turn, are created by a service provider. The service providers are constructor functions. When instantiated they must contain a property called $get, which holds the service factory function.
[...]
...the $provide service has additional helper methods to register services without specifying a provider:

  • provider(provider) - registers a service provider with the $injector
  • constant(obj) - registers a value/object that can be accessed by providers and services.
  • value(obj) - registers a value/object that can only be accessed by services, not providers.
  • factory(fn) - registers a service factory function, fn, that will be wrapped in a service provider object, whose $get property will contain the given factory function.
  • service(class) - registers a constructor function, class that will be wrapped in a service provider object, whose $get property will instantiate a new object using the given constructor function.

Basically, what it says is that every Angular service is registered using $provide.provider(), but there are "shortcut" methods for simpler services (two of which are service() and factory()).
It all "boils down" to a service, so it doesn't make much difference which method you use (as long as the requirements for your service can be covered by that method).

BTW, provider vs service vs factory is one of the most confusing concepts for Angular new-comers, but fortunately there are plenty of resources (here on SO) to make things easier. (Just search around.)

(I hope that clears it up - let me know if it doesn't.)

Why does modulus division (%) only work with integers?

The constraints are in the standards:

C11(ISO/IEC 9899:201x) §6.5.5 Multiplicative operators

Each of the operands shall have arithmetic type. The operands of the % operator shall have integer type.

C++11(ISO/IEC 14882:2011) §5.6 Multiplicative operators

The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. The usual arithmetic conversions are performed on the operands and determine the type of the result.

The solution is to use fmod, which is exactly why the operands of % are limited to integer type in the first place, according to C99 Rationale §6.5.5 Multiplicative operators:

The C89 Committee rejected extending the % operator to work on floating types as such usage would duplicate the facility provided by fmod

Ruby: How to post a file via HTTP as multipart/form-data?

Well the solution with NetHttp has a drawback that is when posting big files it loads the whole file into memory first.

After playing a bit with it I came up with the following solution:

class Multipart

  def initialize( file_names )
    @file_names = file_names
  end

  def post( to_url )
    boundary = '----RubyMultipartClient' + rand(1000000).to_s + 'ZZZZZ'

    parts = []
    streams = []
    @file_names.each do |param_name, filepath|
      pos = filepath.rindex('/')
      filename = filepath[pos + 1, filepath.length - pos]
      parts << StringPart.new ( "--" + boundary + "\r\n" +
      "Content-Disposition: form-data; name=\"" + param_name.to_s + "\"; filename=\"" + filename + "\"\r\n" +
      "Content-Type: video/x-msvideo\r\n\r\n")
      stream = File.open(filepath, "rb")
      streams << stream
      parts << StreamPart.new (stream, File.size(filepath))
    end
    parts << StringPart.new ( "\r\n--" + boundary + "--\r\n" )

    post_stream = MultipartStream.new( parts )

    url = URI.parse( to_url )
    req = Net::HTTP::Post.new(url.path)
    req.content_length = post_stream.size
    req.content_type = 'multipart/form-data; boundary=' + boundary
    req.body_stream = post_stream
    res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }

    streams.each do |stream|
      stream.close();
    end

    res
  end

end

class StreamPart
  def initialize( stream, size )
    @stream, @size = stream, size
  end

  def size
    @size
  end

  def read ( offset, how_much )
    @stream.read ( how_much )
  end
end

class StringPart
  def initialize ( str )
    @str = str
  end

  def size
    @str.length
  end

  def read ( offset, how_much )
    @str[offset, how_much]
  end
end

class MultipartStream
  def initialize( parts )
    @parts = parts
    @part_no = 0;
    @part_offset = 0;
  end

  def size
    total = 0
    @parts.each do |part|
      total += part.size
    end
    total
  end

  def read ( how_much )

    if @part_no >= @parts.size
      return nil;
    end

    how_much_current_part = @parts[@part_no].size - @part_offset

    how_much_current_part = if how_much_current_part > how_much
      how_much
    else
      how_much_current_part
    end

    how_much_next_part = how_much - how_much_current_part

    current_part = @parts[@part_no].read(@part_offset, how_much_current_part )

    if how_much_next_part > 0
      @part_no += 1
      @part_offset = 0
      next_part = read ( how_much_next_part  )
      current_part + if next_part
        next_part
      else
        ''
      end
    else
      @part_offset += how_much_current_part
      current_part
    end
  end
end

Python urllib2: Receive JSON response from url

This is another simpler solution to your question

pd.read_json(data)

where data is the str output from the following code

response = urlopen("https://data.nasa.gov/resource/y77d-th95.json")
json_data = response.read().decode('utf-8', 'replace')

How to verify a Text present in the loaded page through WebDriver

As zmorris points driver.getPageSource().contains("input"); is not the proper solution because it searches in all the html, not only the texts on it. I suggest to check this question: how can I check if some text exist or not in the page? and the recomended way explained by Slanec:

String bodyText = driver.findElement(By.tagName("body")).getText();
Assert.assertTrue("Text not found!", bodyText.contains(text));

How to use RANK() in SQL Server

SELECT contendernum,totals, RANK() OVER (ORDER BY totals ASC) AS xRank FROM
(
SELECT ContenderNum ,SUM(Criteria1+Criteria2+Criteria3+Criteria4) AS totals
FROM dbo.Cat1GroupImpersonation
 GROUP BY ContenderNum
) AS a

Error: "Input is not proper UTF-8, indicate encoding !" using PHP's simplexml_load_string

I solved this using

$content = utf8_encode(file_get_contents('http://example.com/rss.xml'));
$xml = simplexml_load_string($content);

Unicode character as bullet for list-item in CSS

A more complete example of 222's answer:

ul {
    list-style:none;
    padding: 0 0 0 2em;     /* padding includes space for character and its margin */

    /* IE7 and lower use default */
    *list-style: disc;
    *padding: 0 0 0 1em;
}
ul li:before {
    content: '\25BA';
    font-family: "Courier New", courier, "Lucida Sans Typewriter", "Lucida Typewriter", monospace;
    margin: 0 1em 0 -1em;   /* right margin defines spacing between bullet and text. negative left margin pushes back to the edge of the parent <ul> */

    /* IE7 and lower use default */
    *content: none;
    *margin: 0;
}
ul li {
    text-indent: -1em;      /* negative text indent brings first line back inline with the others */

    /* IE7 and lower use default */
    *text-indent: 0;
}

I have included star-hack properties to restore the default list styles in older IE versions. You could pull these out and include them in a conditional include if desired, or replace with a background-image based solution. My humble opinion is that special bullet styles implemented in this manner should degrade gracefully on the few browsers that don't support pseudoselectors.

Tested in Firefox, Chrome, Safari and IE8-10 and renders correctly in all.

how can I display tooltip or item information on mouse over?

Use the title attribute while alt is important for SEO stuff.

Failed to load c++ bson extension

Followint @user1548357 I decided to change the module file itself. So as to avoid the problems pointed out by the valid comments below I included my changes in a postinstall script so that I can set it and forget it and be assured that it will run when my modules are installed.

// package.json
"scripts": {
    // other scripts
    "postinstall": "node ./bson.fix.js"
},

and the script is:

// bson.fix.js
var fs = require('fs');
var file = './node_modules/bson/ext/index.js'
fs.readFile(file, 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }
  var result = data.replace(/\.\.\/build\/Release\/bson/g, 'bson');
  fs.writeFile(file, result, 'utf8', function (err) {
     if (err) return console.log(err);
     console.log('Fixed bson module so as to use JS version');
  });
});

How to get folder path from file path with CMD

In case anyone wants an alternative method...

If it is the last subdirectory in the path, you can use this one-liner:

cd "c:\directory\subdirectory\filename.exe\..\.." && dir /ad /b /s

This would return the following:

c:\directory\subdirectory

The .... drops back to the previous directory. /ad shows only directories /b is a bare format listing /s includes all subdirectories. This is used to get the full path of the directory to print.

Create GUI using Eclipse (Java)

Yes. Use WindowBuilder Pro (provided by Google). It supports SWT and Swing as well with multiple layouts (Group layout, MiGLayout etc.) It's integrated out of the box with Eclipse Indigo, but you can install plugin on previous versions (3.4/3.5/3.6):

enter image description here

Convert column classes in data.table

I provide a more general and safer way to do this stuff,

".." <- function (x) 
{
  stopifnot(inherits(x, "character"))
  stopifnot(length(x) == 1)
  get(x, parent.frame(4))
}


set_colclass <- function(x, class){
  stopifnot(all(class %in% c("integer", "numeric", "double","factor","character")))
  for(i in intersect(names(class), names(x))){
    f <- get(paste0("as.", class[i]))
    x[, (..("i")):=..("f")(get(..("i")))]
  }
  invisible(x)
}

The function .. makes sure we get a variable out of the scope of data.table; set_colclass will set the classes of your cols. You can use it like this:

dt <- data.table(i=1:3,f=3:1)
set_colclass(dt, c(i="character"))
class(dt$i)

read string from .resx file in C#

Followed by @JeffH answer, I recommend to use typeof() than string assembly name.

    var rm = new ResourceManager(typeof(YourAssembly.Properties.Resources));
    string message = rm.GetString("NameOfKey", CultureInfo.CreateSpecificCulture("ja-JP"));

How to disable Home and other system buttons in Android?

First create a method :

public void hideNavigationBar() {
        final View decorView = this.getWindow().getDecorView();
        final int uiOptions =
                View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;

        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                YourActivityName.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        decorView.setSystemUiVisibility(uiOptions);

                    }
                });
            }
        };

        timer.scheduleAtFixedRate(task, 1, 2);

    }

Then you call it on onCreate() method of your activity. Call it again on the onResume() method. Then you may add another method in your activity like this:

@Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        hideNavigationBar();
    }

That will be it. Do remember it will lock the screen till the next time user touches the screen, in Timer class you can change the delay and it will allow you change things for that instance.Then it will lock the screen again.

XPath:: Get following Sibling

You can go for identifying a list of elements with xPath:

//td[text() = ' Color Digest ']/following-sibling::td[1]

This will give you a list of two elements, than you can use the 2nd element as your intended one. For example:

List<WebElement> elements = driver.findElements(By.xpath("//td[text() = ' Color Digest ']/following-sibling::td[1]"))

Now, you can use the 2nd element as your intended element, which is elements.get(1)

How to set ChartJS Y axis title?

For me it works like this:

    options : {
      scales: {
        yAxes: [{
          scaleLabel: {
            display: true,
            labelString: 'probability'
          }
        }]
      }
    }

SQL 'like' vs '=' performance

A personal example using mysql 5.5: I had an inner join between 2 tables, one of 3 million rows and one of 10 thousand rows.

When using a like on an index as below(no wildcards), it took about 30 seconds:

where login like '12345678'

using 'explain' I get:

enter image description here

When using an '=' on the same query, it took about 0.1 seconds:

where login ='600009'

Using 'explain' I get:

enter image description here

As you can see, the like completely cancelled the index seek, so query took 300 times more time.

Align printf output in Java

You can try the below example. Do use '-' before the width to ensure left indentation. By default they will be right indented; which may not suit your purpose.

System.out.printf("%2d. %-20s $%.2f%n",  i + 1, BOOK_TYPE[i], COST[i]);

Format String Syntax: http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax

Formatting Numeric Print Output: https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

PS: This could go as a comment to DwB's answer, but i still don't have permissions to comment and so answering it.

How to increase an array's length

Arrays in Java are of fixed size that is specified when they are declared. To increase the size of the array you have to create a new array with a larger size and copy all of the old values into the new array.

ex:

char[] copyFrom  = { 'a', 'b', 'c', 'd', 'e' };
char[] copyTo    = new char[7];

System.out.println(Arrays.toString(copyFrom));
System.arraycopy(copyFrom, 0, copyTo, 0, copyFrom.length);
System.out.println(Arrays.toString(copyTo));

Alternatively you could use a dynamic data structure like a List.

Convert varchar2 to Date ('MM/DD/YYYY') in PL/SQL

First you convert VARCHAR to DATE and then back to CHAR. I do this almost every day and never found any better way.

select TO_CHAR(TO_DATE(DOJ,'MM/DD/YYYY'), 'MM/DD/YYYY') from EmpTable

Create table in SQLite only if it doesn't exist already

From http://www.sqlite.org/lang_createtable.html:

CREATE TABLE IF NOT EXISTS some_table (id INTEGER PRIMARY KEY AUTOINCREMENT, ...);

How can I get a list of all classes within current module in Python?

I frequently find myself writing command line utilities wherein the first argument is meant to refer to one of many different classes. For example ./something.py feature command —-arguments, where Feature is a class and command is a method on that class. Here's a base class that makes this easy.

The assumption is that this base class resides in a directory alongside all of its subclasses. You can then call ArgBaseClass(foo = bar).load_subclasses() which will return a dictionary. For example, if the directory looks like this:

  • arg_base_class.py
  • feature.py

Assuming feature.py implements class Feature(ArgBaseClass), then the above invocation of load_subclasses will return { 'feature' : <Feature object> }. The same kwargs (foo = bar) will be passed into the Feature class.

#!/usr/bin/env python3
import os, pkgutil, importlib, inspect

class ArgBaseClass():
    # Assign all keyword arguments as properties on self, and keep the kwargs for later.
    def __init__(self, **kwargs):
        self._kwargs = kwargs
        for (k, v) in kwargs.items():
            setattr(self, k, v)
        ms = inspect.getmembers(self, predicate=inspect.ismethod)
        self.methods = dict([(n, m) for (n, m) in ms if not n.startswith('_')])

    # Add the names of the methods to a parser object.
    def _parse_arguments(self, parser):
        parser.add_argument('method', choices=list(self.methods))
        return parser

    # Instantiate one of each of the subclasses of this class.
    def load_subclasses(self):
        module_dir = os.path.dirname(__file__)
        module_name = os.path.basename(os.path.normpath(module_dir))
        parent_class = self.__class__
        modules = {}
        # Load all the modules it the package:
        for (module_loader, name, ispkg) in pkgutil.iter_modules([module_dir]):
            modules[name] = importlib.import_module('.' + name, module_name)

        # Instantiate one of each class, passing the keyword arguments.
        ret = {}
        for cls in parent_class.__subclasses__():
            path = cls.__module__.split('.')
            ret[path[-1]] = cls(**self._kwargs)
        return ret

Cannot call getSupportFragmentManager() from activity

I used FragmentActivity

TabAdapter = new TabPagerAdapter(((FragmentActivity) getActivity()).getSupportFragmentManager());

How to force a view refresh without having it trigger automatically from an observable?

In some circumstances it might be useful to simply remove the bindings and then re-apply:

ko.cleanNode(document.getElementById(element_id))
ko.applyBindings(viewModel, document.getElementById(element_id))

How can I use break or continue within for loop in Twig template?

A way to be able to use {% break %} or {% continue %} is to write TokenParsers for them.

I did it for the {% break %} token in the code below. You can, without much modifications, do the same thing for the {% continue %}.

  • AppBundle\Twig\AppExtension.php:

    namespace AppBundle\Twig;
    
    class AppExtension extends \Twig_Extension
    {
        function getTokenParsers() {
            return array(
                new BreakToken(),
            );
        }
    
        public function getName()
        {
            return 'app_extension';
        }
    }
    
  • AppBundle\Twig\BreakToken.php:

    namespace AppBundle\Twig;
    
    class BreakToken extends \Twig_TokenParser
    {
        public function parse(\Twig_Token $token)
        {
            $stream = $this->parser->getStream();
            $stream->expect(\Twig_Token::BLOCK_END_TYPE);
    
            // Trick to check if we are currently in a loop.
            $currentForLoop = 0;
    
            for ($i = 1; true; $i++) {
                try {
                    // if we look before the beginning of the stream
                    // the stream will throw a \Twig_Error_Syntax
                    $token = $stream->look(-$i);
                } catch (\Twig_Error_Syntax $e) {
                    break;
                }
    
                if ($token->test(\Twig_Token::NAME_TYPE, 'for')) {
                    $currentForLoop++;
                } else if ($token->test(\Twig_Token::NAME_TYPE, 'endfor')) {
                    $currentForLoop--;
                }
            }
    
    
            if ($currentForLoop < 1) {
                throw new \Twig_Error_Syntax(
                    'Break tag is only allowed in \'for\' loops.',
                    $stream->getCurrent()->getLine(),
                    $stream->getSourceContext()->getName()
                );
            }
    
            return new BreakNode();
        }
    
        public function getTag()
        {
            return 'break';
        }
    }
    
  • AppBundle\Twig\BreakNode.php:

    namespace AppBundle\Twig;
    
    class BreakNode extends \Twig_Node
    {
        public function compile(\Twig_Compiler $compiler)
        {
            $compiler
                ->write("break;\n")
            ;
        }
    }
    

Then you can simply use {% break %} to get out of loops like this:

{% for post in posts %}
    {% if post.id == 10 %}
        {% break %}
    {% endif %}
    <h2>{{ post.heading }}</h2>
{% endfor %}

To go even further, you may write token parsers for {% continue X %} and {% break X %} (where X is an integer >= 1) to get out/continue multiple loops like in PHP.

Get original URL referer with PHP?

As Johnathan Suggested, you would either want to save it in a cookie or a session.

The easier way would be to use a Session variable.

session_start();
if(!isset($_SESSION['org_referer']))
{
    $_SESSION['org_referer'] = $_SERVER['HTTP_REFERER'];
}

Put that at the top of the page, and you will always be able to access the first referer that the site visitor was directed by.

How to check if div element is empty

var empty = $("#cartContent").html().trim().length == 0;

Clearing the terminal screen?

You could try:

Serial.write(13);

Which will provide a carriage return, returning to the start of the line every iteration - which should do what you're chasing? (Especially if everything is fixed width).

search in java ArrayList

Personally I rarely write loops myself now when I can get away with it... I use the Jakarta commons libs:

Customer findCustomerByid(final int id){
    return (Customer) CollectionUtils.find(customers, new Predicate() {
        public boolean evaluate(Object arg0) {
            return ((Customer) arg0).getId()==id;
        }
    });
}

Yay! I saved one line!

jQuery: How to get the event object in an event handler function without passing it as an argument?

If you call your event handler on markup, as you're doing now, you can't (x-browser). But if you bind the click event with jquery, it's possible the following way:

Markup:

  <a href="#" id="link1" >click</a>

Javascript:

  $(document).ready(function(){
      $("#link1").click(clickWithEvent);  //Bind the click event to the link
  });
  function clickWithEvent(evt){
     myFunc('p1', 'p2', 'p3');
     function myFunc(p1,p2,p3){  //Defined as local function, but has access to evt
        alert(evt.type);        
     }
  }

Since the event ob

How to read html from a url in python 3

For python 2

import urllib
some_url = 'https://docs.python.org/2/library/urllib.html'
filehandle = urllib.urlopen(some_url)
print filehandle.read()

Structuring online documentation for a REST API

That's a very complex question for a simple answer.

You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.

Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.

At the very top level I think quality REST API docs require at least the following:

  • a list of all your API endpoints (base/relative URLs)
  • corresponding HTTP GET/POST/... method type for each endpoint
  • request/response MIME-type (how to encode params and parse replies)
  • a sample request/response, including HTTP headers
  • type and format specified for all params, including those in the URL, body and headers
  • a brief text description and important notes
  • a short code snippet showing the use of the endpoint in popular web programming languages

Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.

How to limit file upload type file size in PHP?

Hope This useful...

form:

<form action="check.php" method="post" enctype="multipart/form-data">
<label>Upload An Image</label>
<input type="file" name="file_upload" />
<input type="submit" name="upload"/>
</form>

check.php:

<?php 
    if(isset($_POST['upload'])){
        $maxsize=2097152;
        $format=array('image/jpeg');
    if($_FILES['file_upload']['size']>=$maxsize){
        $error_1='File Size too large';
        echo '<script>alert("'.$error_1.'")</script>';
    }
    elseif($_FILES['file_upload']['size']==0){
        $error_2='Invalid File';
        echo '<script>alert("'.$error_2.'")</script>';
    }
    elseif(!in_array($_FILES['file_upload']['type'],$format)){
        $error_3='Format Not Supported.Only .jpeg files are accepted';
        echo '<script>alert("'.$error_3.'")</script>';
        }

        else{
            $target_dir = "uploads/";
            $target_file = $target_dir . basename($_FILES["file_upload"]["name"]);
            if(move_uploaded_file($_FILES["file_upload"]["tmp_name"], $target_file)){ 
            echo "The file ". basename($_FILES["file_upload"]["name"]). " has been uploaded.";
            }
            else{
                echo "sorry";
                }
            }
    }
?>

What is an MvcHtmlString and when should I use it?

This is a late answer but if anyone reading this question is using razor, what you should remember is that razor encodes everything by default, but by using MvcHtmlString in your html helpers you can tell razor that it doesn't need to encode it.

If you want razor to not encode a string use

@Html.Raw("<span>hi</span>")

Decompiling Raw(), shows us that it's wrapping the string in a HtmlString

public IHtmlString Raw(string value) {
    return new HtmlString(value); 
}

"HtmlString only exists in ASP.NET 4.

MvcHtmlString was a compatibility shim added to MVC 2 to support both .NET 3.5 and .NET 4. Now that MVC 3 is .NET 4 only, it's a fairly trivial subclass of HtmlString presumably for MVC 2->3 for source compatibility." source

How to convert string date to Timestamp in java?

Use below code to convert String Date to Epoc Timestamp. Note : - Your input Date format should match with SimpleDateFormat.

String inputDateInString= "8/15/2017 12:00:00 AM";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyy hh:mm:ss");

Date parsedDate = dateFormat.parse("inputDateInString");

Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());

System.out.println("Timestamp "+ timestamp.getTime());

Android Drawing Separator/Divider Line in Layout?

Just write this :

 android:divider="?android:dividerHorizontal"
 android:showDividers="middle"

full example:

<LinearLayout
        android:id="@+id/llTipInformation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tvServiceRating"
        android:orientation="horizontal"
        android:divider="?android:dividerHorizontal"
        android:layout_marginTop="@dimen/activity_horizontal_margin"
        android:showDividers="middle">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="@string/main.msg.tippercent"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="@color/colorWhite"
            android:layout_marginTop="@dimen/activity_vertical_margin"/>
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="@string/main.msg.tiptotal"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="@color/colorWhite"
            android:layout_marginTop="@dimen/activity_vertical_margin"/>

</LinearLayout>

Setting default value in select drop-down using Angularjs

Some of the scenarios, object.item would not be loaded or will be undefined.

Use ng-init

<select ng-init="object.item=2" ng-model="object.item"
ng-options="item.id as item.name for item in list"

Calling Python in PHP

There's also a PHP extension: Pip - Python in PHP, which I've never tried but had it bookmarked for just such an occasion

Oracle pl-sql escape character (for a " ' ")

Here is a way to easily escape & char in oracle DB

set escape '\\'

and within query write like

'ERRORS &\\\ PERFORMANCE';

Simplest way to detect keypresses in javascript

KEYPRESS (enter key)
Click inside the snippet and press Enter key.

Vanilla

_x000D_
_x000D_
document.addEventListener("keypress", function(event) {
  if (event.keyCode == 13) {
    alert('hi.');
  }
});
_x000D_
_x000D_
_x000D_

Vanilla shorthand (ES6)

_x000D_
_x000D_
this.addEventListener('keypress', event => {
  if (event.keyCode == 13) {
    alert('hi.')
  }
})
_x000D_
_x000D_
_x000D_

jQuery

_x000D_
_x000D_
$(this).on('keypress', function(event) {
  if (event.keyCode == 13) {
    alert('hi.')
  }
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

jQuery classic

_x000D_
_x000D_
$(this).keypress(function(event) {
  if (event.keyCode == 13) {
    alert('hi.')
  }
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

jQuery shorthand (ES6)

_x000D_
_x000D_
$(this).keypress((e) => {
  if (e.keyCode == 13)
    alert('hi.')
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Even shorter (ES6)

_x000D_
_x000D_
$(this).keypress(e=>
  e.which==13?
  alert`hi.`:null
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Due some requests, here an explanation:

I rewrote this answer as things have become deprecated over time so I updated it.

I used this to focus on the window scope inside the results when document is ready and for the sake of brevity but it's not necessary.

Deprecated:
The .which and .keyCode methods are actually considered deprecated so I would recommend .code but I personally still use keyCode as the performance is much faster and only that counts for me. The jQuery classic version .keypress() is not officially deprecated as some people say but they are no more preferred like .on('keypress') as it has a lot more functionality(live state, multiple handlers, etc.). The 'keypress' event in the Vanilla version is also deprecated. People should prefer beforeinput or keydown today. (Note: It has nothing to do with jQuery's events, they are called the same but execute differently.)

All examples above are no biggies regarding deprecated or not. Consoles or any browser should be able to notify you with that if this happens. And if this ever does in future, just fix it.

Readablity:
Despite the ease making it too short and snippy isn't always good either. If you work in a team, your code must be readable and detailed. I recommend the jQuery version .on('keypress'), this is the way to go and understandable by most people.

Performance:
I always follow my phrase Performance over Effectiveness as anything can be more effective if there is the option but it just should function and execute only what I want, the faster the better. This is why I prefer .keyCode even if it's considered deprecated(in most cases). It's all up to you though.

Performance Test

Python using enumerate inside list comprehension

Here's a way to do it:

>>> mylist = ['a', 'b', 'c', 'd']
>>> [item for item in enumerate(mylist)]
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

Alternatively, you can do:

>>> [(i, j) for i, j in enumerate(mylist)]
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

The reason you got an error was that you were missing the () around i and j to make it a tuple.

Best radio-button implementation for IOS

Try DLRadioButton, works for both Swift and ObjC. You can also use images to indicate selection status or customize your own style.

Check it out at GitHub.

radio button for iOS

**Update: added the option for putting selection indicator on the right side.

**Update: added square button, IBDesignable, improved performance.

**Update: added multiple selection support.

import an array in python

Another option is numpy.genfromtxt, e.g:

import numpy as np
data = np.genfromtxt("myfile.dat",delimiter=",")

This will make data a numpy array with as many rows and columns as are in your file

How to send email by using javascript or jquery

The short answer is that you can't do it using JavaScript alone. You'd need a server-side handler to connect with the SMTP server to actually send the mail. There are many simple mail scripts online, such as this one for PHP:

Simple PHP mail script

Using a script like that, you'd POST the contents of your web form to the script, using a function like this:

jQuery.post

And then the script would take those values, plus a username and password for the mail server, and connect to the server to send the mail.

Disabling vertical scrolling in UIScrollView

yes, pt2ph8's answer is right,

but if for some strange reason your contentSize should be higher than the UIScrollView, you can disable the vertical scrolling implementing the UIScrollView protocol method

 -(void)scrollViewDidScroll:(UIScrollView *)aScrollView;

just add this in your UIViewController

float oldY; // here or better in .h interface

- (void)scrollViewDidScroll:(UIScrollView *)aScrollView
{
    [aScrollView setContentOffset: CGPointMake(aScrollView.contentOffset.x, oldY)];
    // or if you are sure you wanna it always on top:
    // [aScrollView setContentOffset: CGPointMake(aScrollView.contentOffset.x, 0)];
}

it's just the method called when the user scroll your UIScrollView, and doing so you force the content of it to have always the same .y

About catching ANY exception

There are multiple ways to do this in particular with Python 3.0 and above

Approach 1

This is simple approach but not recommended because you would not know exactly which line of code is actually throwing the exception:

def bad_method():
    try:
        sqrt = 0**-1
    except Exception as e:
        print(e)

bad_method()

Approach 2

This approach is recommended because it provides more detail about each exception. It includes:

  • Line number for your code
  • File name
  • The actual error in more verbose way

The only drawback is tracback needs to be imported.

import traceback

def bad_method():
    try:
        sqrt = 0**-1
    except Exception:
        print(traceback.print_exc())

bad_method()

Hide div element when screen size is smaller than a specific size

@media only screen and (max-width: 1026px) { 
  #fadeshow1 { 
    display: none; 
  } 
}

Any time the screen is less than 1026 pixels wide, anything inside the { } will apply.

Some browsers don't support media queries. You can get round this using a javascript library like Respond.JS

"google is not defined" when using Google Maps V3 in Firefox remotely

try this:

<script src="https://maps.googleapis.com/maps/api/js"></script>

it works for me... the point is, change HTTP to HTTPS

How can Bash execute a command in a different directory context?

Use cd in a subshell; the shorthand way to use this kind of subshell is parentheses.

(cd wherever; mycommand ...)

That said, if your command has an environment that it requires, it should really ensure that environment itself instead of putting the onus on anything that might want to use it (unless it's an internal command used in very specific circumstances in the context of a well defined larger system, such that any caller already needs to ensure the environment it requires). Usually this would be some kind of shell script wrapper.

How to get relative path from absolute path

I'm using this:

public static class StringExtensions
{
  /// <summary>
  /// Creates a relative path from one file or folder to another.
  /// </summary>
  /// <param name="absPath">Absolute path.</param>
  /// <param name="relTo">Directory that defines the start of the relative path.</param> 
  /// <returns>The relative path from the start directory to the end path.</returns>
  public static string MakeRelativePath(this string absPath, string relTo)
  {
      string[] absParts = absPath.Split(Path.DirectorySeparatorChar);
      string[] relParts = relTo.Split(Path.DirectorySeparatorChar);

      // Get the shortest of the two paths
      int len = absParts.Length < relParts.Length
          ? absParts.Length : relParts.Length;

      // Use to determine where in the loop we exited
      int lastCommonRoot = -1;
      int index;

      // Find common root
      for (index = 0; index < len; index++)
      {
          if (absParts[index].Equals(relParts[index], StringComparison.OrdinalIgnoreCase))
              lastCommonRoot = index;
          else 
            break;
      }

      // If we didn't find a common prefix then throw
      if (lastCommonRoot == -1)
          throw new ArgumentException("The path of the two files doesn't have any common base.");

      // Build up the relative path
      var relativePath = new StringBuilder();

      // Add on the ..
      for (index = lastCommonRoot + 1; index < relParts.Length; index++)
      {
        relativePath.Append("..");
        relativePath.Append(Path.DirectorySeparatorChar);
      }

      // Add on the folders
      for (index = lastCommonRoot + 1; index < absParts.Length - 1; index++)
      {
        relativePath.Append(absParts[index]);
        relativePath.Append(Path.DirectorySeparatorChar);
      }
      relativePath.Append(absParts[absParts.Length - 1]);

      return relativePath.ToString();
  }
}

Call a Vue.js component method from outside the component

Say you have a child_method() in the child component:

export default {
    methods: {
        child_method () {
            console.log('I got clicked')
        }
    }
}

Now you want to execute the child_method from parent component:

<template>
    <div>
        <button @click="exec">Execute child component</button>
        <child-cmp ref="child"></child_cmp> <!-- note the ref="child" here -->
    </div>
</template>

export default {
    methods: {
        exec () { //accessing the child component instance through $refs
            this.$refs.child.child_method() //execute the method belongs to the child component
        }
    }
}

If you want to execute a parent component method from child component:

this.$parent.name_of_method()

NOTE: It is not recommended to access the child and parent component like this.

Instead as best practice use Props & Events for parent-child communication.

If you want communication between components surely use vuex or event bus

Please read this very helpful article


Best way to require all files from a directory in ruby?

In Rails, you can do:

Dir[Rails.root.join('lib', 'ext', '*.rb')].each { |file| require file }

Update: Corrected with suggestion of @Jiggneshh Gohel to remove slashes.

tsc is not recognized as internal or external command

If you want to run the tsc command from the integrated terminal with the TypeScript module installed locally, you can add the following to your .vscode\settings.json file.

{
  "terminal.integrated.env.windows": { "PATH": "${workspaceFolder}\\node_modules\\.bin;${env:PATH}" }
}

This will prepend the locally installed node module's binary/executable directory (where tsc.cmd is located) to the $env.PATH variable.

string.Replace in AngularJs

var oldString = "stackoverflow";
var str=oldString.replace(/stackover/g,"NO");
$scope.newString= str;

It works for me. Use an intermediate variable.

Can I obtain method parameter name using Java reflection?

Parameter names are only useful to the compiler. When the compiler generates a class file, the parameter names are not included - a method's argument list only consists of the number and types of its arguments. So it would be impossible to retrieve the parameter name using reflection (as tagged in your question) - it doesn't exist anywhere.

However, if the use of reflection is not a hard requirement, you can retrieve this information directly from the source code (assuming you have it).

How to force page refreshes or reloads in jQuery?

Or better

window.location.assign("relative or absolute address");

that tends to work best across all browsers and mobile

Basic example of using .ajax() with JSONP?

<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>An JSONP example </title>
</head>
<body>
<!-- DIV FOR SHOWING IMAGES -->
<div id="images">
</div>
<!-- SCRIPT FOR GETTING IMAGES FROM FLICKER.COM USING JSONP -->
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
  format: "json"
},
//RETURNED RESPONSE DATA IS LOOPED AND ONLY IMAGE IS APPENDED TO IMAGE DIV
function(data) {
  $.each(data.items, function(i,item){
  $("<img/>").attr("src", item.media.m).appendTo("#images");

 });
});</script>
</body>
</html> 

The above code helps in getting images from the Flicker API. This uses the GET method for getting images using JSONP. It can be found in detail in here

Insert string in beginning of another string

import java.lang.StringBuilder;

public class Program {
    public static void main(String[] args) {

    // Create a new StringBuilder.
    StringBuilder builder = new StringBuilder();

    // Loop and append values.
    for (int i = 0; i < 5; i++) {
        builder.append("abc ");
    }
    // Convert to string.
    String result = builder.toString();

    // Print result.
    System.out.println(result);
    }
}

How to output messages to the Eclipse console when developing for Android

Log.v("blah", "blah blah");

You need to add the android Log view in eclipse to see them. There are also other methods depending on the severity of the message (error, verbose, warning, etc..).

What's the purpose of the LEA instruction?

LEA : just an "arithmetic" instruction..

MOV transfers data between operands but lea is just calculating

ng-if, not equal to?

Try below solution

ng-if="details.Payment[0].Status != '0'"

Use below condition(! prefix with true condition) instead of above

ng-if="!details.Payment[0].Status == '0'"

Install a Windows service using a Windows command prompt?

I must add one more point in this thread. To install/uninstall 64-bit version of assemblies one should use 64-bit version of tool. To install a service, the command should be:

"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe"
"C:\YourFolder\YourService.exe"

and to uninstall the command should be:

"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe" -u
"C:\YourFolder\YourService.exe"

How to randomize (or permute) a dataframe rowwise and columnwise?

Take a look at permatswap() in the vegan package. Here is an example maintaining both row and column totals, but you can relax that and fix only one of the row or column sums.

mat <- matrix(c(1,1,0,0,0,0,0,1,1,0,0,0,1,1,1,0,1,0,1,1), ncol = 5)
set.seed(4)
out <- permatswap(mat, times = 99, burnin = 20000, thin = 500, mtype = "prab")

This gives:

R> out$perm[[1]]
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    0    1    1    1
[2,]    0    1    0    1    0
[3,]    0    0    0    1    1
[4,]    1    0    0    0    1
R> out$perm[[2]]
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    0    1    1
[2,]    0    0    0    1    1
[3,]    1    0    0    1    0
[4,]    0    0    1    0    1

To explain the call:

out <- permatswap(mat, times = 99, burnin = 20000, thin = 500, mtype = "prab")
  1. times is the number of randomised matrices you want, here 99
  2. burnin is the number of swaps made before we start taking random samples. This allows the matrix from which we sample to be quite random before we start taking each of our randomised matrices
  3. thin says only take a random draw every thin swaps
  4. mtype = "prab" says treat the matrix as presence/absence, i.e. binary 0/1 data.

A couple of things to note, this doesn't guarantee that any column or row has been randomised, but if burnin is long enough there should be a good chance of that having happened. Also, you could draw more random matrices than you need and discard ones that don't match all your requirements.

Your requirement to have different numbers of changes per row, also isn't covered here. Again you could sample more matrices than you want and then discard the ones that don't meet this requirement also.

Why "Data at the root level is invalid. Line 1, position 1." for XML Document?

if you are using XDocument.Load(url); to fetch xml from another domain, it's possible that the host will reject the request and return and unexpected (non-xml) result, which results in the above XmlException

See my solution to this eventuality here: XDocument.Load(feedUrl) returns "Data at the root level is invalid. Line 1, position 1."

Docker container will automatically stop after "docker run -d"

execute command as follows :

docker run -t -d <image-name>

if you want to specify port then command as below:

docker run -t -d -p <port-no> <image-name>

verify the running container using following command:

docker ps

Print an ArrayList with a for-each loop

Your code works. If you don't have any output, you may have "forgotten" to add some values to the list:

// add values
list.add("one");
list.add("two");

// your code
for (String object: list) {
    System.out.println(object);
}

how to remove json object key and value.?

I had issues with trying to delete a returned JSON object and found that it was actually a string. If you JSON.parse() before deleting you can be sure your key will get deleted.

let obj;
console.log(this.getBody()); // {"AED":3.6729,"AZN":1.69805,"BRL":4.0851}
obj = this.getBody();
delete obj["BRL"];
console.log(obj) // {"AED":3.6729,"AZN":1.69805,"BRL":4.0851}
obj = JSON.parse(this.getBody());
delete obj["BRL"];
console.log(obj) // {"AED":3.6729,"AZN":1.69805}

jquery smooth scroll to an anchor?

jQuery.scrollTo will do everything you want and more!

You can pass it all kinds of different things:

  • A raw number
  • A string('44', '100px', '+=30px', etc )
  • A DOM element (logically, child of the scrollable element)
  • A selector, that will be relative to the scrollable element
  • The string 'max' to scroll to the end.
  • A string specifying a percentage to scroll to that part of the container (f.e: 50% goes to * to the middle).
  • A hash { top:x, left:y }, x and y can be any kind of number/string like above.

jQuery: Clearing Form Inputs

Took some searching and reading to find a method that suited my situation, on form submit, run ajax to a remote php script, on success/failure inform user, on complete clear the form.

I had some default values, all other methods involved .val('') thereby not resetting but clearing the form.

I got this too work by adding a reset button to the form, which had an id of myform:

$("#myform > input[type=reset]").trigger('click');

This for me had the correct outcome on resetting the form, oh and dont forget the

event.preventDefault();

to stop the form submitting in browser, like I did :).

Regards

Jacko

Reset Entity-Framework Migrations

UPDATE 2020 => Reset Entity-Framework Migrations

Add-Migration Initial -Context ApplicationDbContext

ApplicationDbContext => Your context.

But if you need only update a identity schema existent, try it: https://stackoverflow.com/a/59966100/4654957

Is it better to return null or empty collection?

Empty is much more consumer friendly.

There is a clear method of making up an empty enumerable:

Enumerable.Empty<Element>()

Find the line number where a specific word appears with "grep"

Or You can use

   grep -n . file1 |tail -LineNumberToStartWith|grep regEx

This will take care of numbering the lines in the file

   grep -n . file1 

This will print the last-LineNumberToStartWith

   tail -LineNumberToStartWith

And finally it will grep your desired lines(which will include line number as in orignal file)

grep regEX

Pandas/Python: Set value of one column based on value in another column

I suggest doing it in two steps:

# set fixed value to 'c2' where the condition is met
df.loc[df['c1'] == 'Value', 'c2'] = 10

# copy value from 'c3' to 'c2' where the condition is NOT met
df.loc[df['c1'] != 'Value', 'c2'] = df[df['c1'] != 'Value', 'c3']

Android check null or empty string in Android

From @Jon Skeet comment, really the String value is "null". Following code solved it

if (userEmail != null && !userEmail.isEmpty() && !userEmail.equals("null"))