Programs & Examples On #Focusmanager

Using an integer as a key in an associative array in JavaScript

If the use case is storing data in a collection then ECMAScript 6 provides the Map type.

It's only heavier to initialize.

Here is an example:

const map = new Map();
map.set(1, "One");
map.set(2, "Two");
map.set(3, "Three");

console.log("=== With Map ===");

for (const [key, value] of map) {
    console.log(`${key}: ${value} (${typeof(key)})`);
}

console.log("=== With Object ===");

const fakeMap = {
    1: "One",
    2: "Two",
    3: "Three"
};

for (const key in fakeMap) {
    console.log(`${key}: ${fakeMap[key]} (${typeof(key)})`);
}

Result:

=== With Map ===
1: One (number)
2: Two (number)
3: Three (number)
=== With Object ===
1: One (string)
2: Two (string)
3: Three (string)

How to convert hashmap to JSON object in Java

If you are using net.sf.json.JSONObject then you won't find a JSONObject(map) constructor in it. You have to use the public static JSONObject fromObject( Object object ) method. This method accepts JSON formatted strings, Maps, DynaBeans and JavaBeans.

JSONObject jsonObject = JSONObject.fromObject(myMap);

How should I pass an int into stringWithFormat?

Do this:

label.text = [NSString stringWithFormat:@"%d", count];

"Parse Error : There is a problem parsing the package" while installing Android application

Instead of shooting in the dark, get the reason for this error by installing it via adb:

adb -s emulator-5555 install ~/path-to-your-apk/com.app.apk

Replace emulator-5555 with your device name. You can obtain a list using:

adb devices

Upon failing, it will give a reason. Common reasons and their fixes:

  1. INSTALL_PARSE_FAILED_NO_CERTIFICATES: Reference
  2. INSTALL_FAILED_UPDATE_INCOMPATIBLE: Reference

How to center the elements in ConstraintLayout

you can use layout_constraintCircle for center view inside ConstraintLayout.

<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/mparent"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <ImageButton
            android:id="@+id/btn_settings"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:srcCompat="@drawable/ic_home_black_24dp"
            app:layout_constraintCircle="@id/mparent"
            app:layout_constraintCircleRadius="0dp"
            />
    </android.support.constraint.ConstraintLayout>

with constraintCircle to parent and zero radius you can make your view be center of parent.

Execution failed for task ':app:processDebugResources' even with latest build tools

I changed the target=android-26 to target=android-23

project.properties

this works great for me.

Check if year is leap year in javascript

function leapYear(year)
{
  return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}

How to move the cursor word by word in the OS X Terminal

Switch to iTerm2. It's free and much nicer than plain old terminal. Also it has a lot more options for customization, like keyboard shortcuts.

Also I love that you can use cmd and 1-9 to switch between tabs. Try it and you will never go back to regular terminal :)

How to set up custom keyboard preferences in iterm2

  • Install iTerm2
  • Launch and then go to preference pane.
  • Choose the keyboard profiles tab
  • You will either need to copy the profile to something new and then delete the arrow key shortcuts such as ^+ Right/Left or if you don't care about a backup just delete them from the default profile.
  • Next make sure your modified profile is selected (starred)

Picture 1.png

  • Now choose the keyboard tab (very top row)

iTerm 2

  • Click on the plus button to add a new keyboard shortcut
  • In the first box type CMD+Left arrow
  • In the second box choose "send escape code"
  • In the third box type the letter B

Picture 2.png

  • Repeat with desired key combinations. escape+B moves one word to the left, escape+f moves one word to the right.
  • you may also wish to set up cmd+d to delete the word in front of the cursor with escape+d

I often hit the wrong button (cmd / control / alt) with an arrow key and so i have my arrow key combinations with those buttons all set to jump forward and back words, but please do what fits you best.

getActivity() returns null in Fragment function

I am using OkHttp and I just faced this issue.


For the first part @thucnguyen was on the right track.

This happened when you call getActivity() in another thread that finished after the fragment has been removed. The typical case is calling getActivity() (ex. for a Toast) when an HTTP request finished (in onResponse for example).

Some HTTP calls were being executed even after the activity had been closed (because it can take a while for an HTTP request to be completed). I then, through the HttpCallback tried to update some Fragment fields and got a null exception when trying to getActivity().

http.newCall(request).enqueue(new Callback(...
  onResponse(Call call, Response response) {
    ...
    getActivity().runOnUiThread(...) // <-- getActivity() was null when it had been destroyed already

IMO the solution is to prevent callbacks to occur when the fragment is no longer alive anymore (and that's not just with Okhttp).

The fix: Prevention.

If you have a look at the fragment lifecycle (more info here), you'll notice that there's onAttach(Context context) and onDetach() methods. These get called after the Fragment belongs to an activity and just before stop being so respectively.

That means that we can prevent that callback to happen by controlling it in the onDetach method.

@Override
public void onAttach(Context context) {
    super.onAttach(context);

    // Initialize HTTP we're going to use later.
    http = new OkHttpClient.Builder().build();
}

@Override
public void onDetach() {
    super.onDetach();

    // We don't want to receive any more information about the current HTTP calls after this point.
    // With Okhttp we can simply cancel the on-going ones (credits to https://github.com/square/okhttp/issues/2205#issuecomment-169363942).
    for (Call call : http.dispatcher().queuedCalls()) {
        call.cancel();
    }
    for (Call call : http.dispatcher().runningCalls()) {
        call.cancel();
    }
}

What's the difference between unit tests and integration tests?

A unit test is a test written by the programmer to verify that a relatively small piece of code is doing what it is intended to do. They are narrow in scope, they should be easy to write and execute, and their effectiveness depends on what the programmer considers to be useful. The tests are intended for the use of the programmer, they are not directly useful to anybody else, though, if they do their job, testers and users downstream should benefit from seeing fewer bugs.

Part of being a unit test is the implication that things outside the code under test are mocked or stubbed out. Unit tests shouldn't have dependencies on outside systems. They test internal consistency as opposed to proving that they play nicely with some outside system.

An integration test is done to demonstrate that different pieces of the system work together. Integration tests can cover whole applications, and they require much more effort to put together. They usually require resources like database instances and hardware to be allocated for them. The integration tests do a more convincing job of demonstrating the system works (especially to non-programmers) than a set of unit tests can, at least to the extent the integration test environment resembles production.

Actually "integration test" gets used for a wide variety of things, from full-on system tests against an environment made to resemble production to any test that uses a resource (like a database or queue) that isn't mocked out. At the lower end of the spectrum an integration test could be a junit test where a repository is exercised against an in-memory database, toward the upper end it could be a system test verifying applications can exchange messages.

How to get MD5 sum of a string using python?

Use hashlib.md5 in Python 3.

import hashlib

source = '000005fab4534d05api_key9a0554259914a86fb9e7eb014e4e5d52permswrite'.encode()
md5 = hashlib.md5(source).hexdigest() # returns a str
print(md5) # a02506b31c1cd46c2e0b6380fb94eb3d

If you need byte type output, use digest() instead of hexdigest().

Error: " 'dict' object has no attribute 'iteritems' "

As you are in python3 , use dict.items() instead of dict.iteritems()

iteritems() was removed in python3, so you can't use this method anymore.

Take a look at Python 3.0 Wiki Built-in Changes section, where it is stated:

Removed dict.iteritems(), dict.iterkeys(), and dict.itervalues().

Instead: use dict.items(), dict.keys(), and dict.values() respectively.

Differences between socket.io and websockets

https://socket.io/docs/#What-Socket-IO-is-not (with my emphasis)

What Socket.IO is not

Socket.IO is NOT a WebSocket implementation. Although Socket.IO indeed uses WebSocket as a transport when possible, it adds some metadata to each packet: the packet type, the namespace and the packet id when a message acknowledgement is needed. That is why a WebSocket client will not be able to successfully connect to a Socket.IO server, and a Socket.IO client will not be able to connect to a WebSocket server either. Please see the protocol specification here.

// WARNING: the client will NOT be able to connect!
const client = io('ws://echo.websocket.org');

How to change text and background color?

Colors are bit-encoded. If You want to change the Text color in C++ language There are many ways. In the console, you can change the properties of output.click this icon of the console and go to properties and change color.

The second way is calling the system colors.

#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
    //Changing Font Colors of the System

    system("Color 7C");
    cout << "\t\t\t ****CEB Electricity Bill Calculator****\t\t\t " << endl;
    cout << "\t\t\t  ***                MENU           ***\t\t\t  " <<endl;

    return 0;

}

Spark read file from S3 using sc.textFile ("s3n://...)

This is a sample spark code which can read the files present on s3

val hadoopConf = sparkContext.hadoopConfiguration
hadoopConf.set("fs.s3.impl", "org.apache.hadoop.fs.s3native.NativeS3FileSystem")
hadoopConf.set("fs.s3.awsAccessKeyId", s3Key)
hadoopConf.set("fs.s3.awsSecretAccessKey", s3Secret)
var jobInput = sparkContext.textFile("s3://" + s3_location)

Try-catch block in Jenkins pipeline script

Look up the AbortException class for Jenkins. You should be able to use the methods to get back simple messages or stack traces. In a simple case, when making a call in a script block (as others have indicated), you can call getMessage() to get the string to echo to the user. Example:

script {
        try {
            sh "sudo docker rmi frontend-test"
        } catch (err) {
            echo err.getMessage()
            echo "Error detected, but we will continue."
        }
        ...continue with other code...
}

Using StringWriter for XML Serialization

public static T DeserializeFromXml<T>(string xml)
{
    T result;
    XmlSerializerFactory serializerFactory = new XmlSerializerFactory();
    XmlSerializer serializer =serializerFactory.CreateSerializer(typeof(T));

    using (StringReader sr3 = new StringReader(xml))
    {
        XmlReaderSettings settings = new XmlReaderSettings()
        {
            CheckCharacters = false // default value is true;
        };

        using (XmlReader xr3 = XmlTextReader.Create(sr3, settings))
        {
            result = (T)serializer.Deserialize(xr3);
        }
    }

    return result;
}

.net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible

The package is not fully compatible with dotnetcore 2.0 for now.

eg, for 'Microsoft.AspNet.WebApi.Client' it maybe supported in version (5.2.4). See Consume new Microsoft.AspNet.WebApi.Client.5.2.4 package for details.

You could try the standard Client package as Federico mentioned.

If that still not work, then as a workaround you can only create a Console App (.Net Framework) instead of the .net core 2.0 console app.

Reference this thread: Microsoft.AspNet.WebApi.Client supported in .NET Core or not?

pandas DataFrame: replace nan values with average of columns

Directly use df.fillna(df.mean()) to fill all the null value with mean

If you want to fill null value with mean of that column then you can use this

suppose x=df['Item_Weight'] here Item_Weight is column name

here we are assigning (fill null values of x with mean of x into x)

df['Item_Weight'] = df['Item_Weight'].fillna((df['Item_Weight'].mean()))

If you want to fill null value with some string then use

here Outlet_size is column name

df.Outlet_Size = df.Outlet_Size.fillna('Missing')

How do I find which process is leaking memory?

In addition to top, you can use System Monitor (System - Administration - System Monitor, then select Processes tab). Select View - All Processes, go to Edit - Preferences and enable Virtual Memory column. Sort either by this column, or by Memory column

How to determine the current iPhone/device model?

All the answers are great. After getting some bits I have created THIS GIST

It contains DeviceModel which is part and of the 'Core' (No UIKit dependency) Module. It can even be used as a model.

It can be used from another 'Core' module component like that:

struct DeviceHelper {
    static var specificModelType: DeviceModel {
        var systemInfo = utsname()
            uname(&systemInfo)
            let modelCode = withUnsafePointer(to: &systemInfo.machine) {
                $0.withMemoryRebound(to: CChar.self, capacity: 1) {
                    ptr in String.init(validatingUTF8: ptr)
                }
            }

        let modelType = DeviceModel(modelCode: modelCode ?? "")
        if modelType == .simulator {
            return .simulator
            // UP TO YOU
//            if let simModelCode = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] {
//                return DeviceModel(modelCode: simModelCode)
//            }
        } else {
            return modelType
        }
}

Or from a 'UI' Module component like that:

extension UIDevice {
    static var specificModelType: DeviceModel {
        DeviceHelper.specificModelType
    }
}

COPY with docker but with exclusion

FOR A ONE LINER SOLUTION, type the following in Command prompt or Terminal at project root.

echo node_modules > .dockerignore

This creates the extension-less . prefixed file without any issue. Replace node_modules with the folder you want to exclude.

Formatting floats in a numpy array

In order to make numpy display float arrays in an arbitrary format, you can define a custom function that takes a float value as its input and returns a formatted string:

In [1]: float_formatter = "{:.2f}".format

The f here means fixed-point format (not 'scientific'), and the .2 means two decimal places (you can read more about string formatting here).

Let's test it out with a float value:

In [2]: float_formatter(1.234567E3)
Out[2]: '1234.57'

To make numpy print all float arrays this way, you can pass the formatter= argument to np.set_printoptions:

In [3]: np.set_printoptions(formatter={'float_kind':float_formatter})

Now numpy will print all float arrays this way:

In [4]: np.random.randn(5) * 10
Out[4]: array([5.25, 3.91, 0.04, -1.53, 6.68]

Note that this only affects numpy arrays, not scalars:

In [5]: np.pi
Out[5]: 3.141592653589793

It also won't affect non-floats, complex floats etc - you will need to define separate formatters for other scalar types.

You should also be aware that this only affects how numpy displays float values - the actual values that will be used in computations will retain their original precision.

For example:

In [6]: a = np.array([1E-9])

In [7]: a
Out[7]: array([0.00])

In [8]: a == 0
Out[8]: array([False], dtype=bool)

numpy prints a as if it were equal to 0, but it is not - it still equals 1E-9.

If you actually want to round the values in your array in a way that affects how they will be used in calculations, you should use np.round, as others have already pointed out.

Force IE9 to emulate IE8. Possible?

The 1st element as in no hard returns. A hard return I guess = an empty node/element in the DOM which becomes the 1st element disabling the doc compatability meta tag.

How to convert numbers between hexadecimal and decimal

To convert from decimal to hex do...

string hexValue = decValue.ToString("X");

To convert from hex to decimal do either...

int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);

or

int decValue = Convert.ToInt32(hexValue, 16);

Creating a new directory in C

You can use mkdir:

$ man 2 mkdir

#include <sys/stat.h>
#include <sys/types.h>

int result = mkdir("/home/me/test.txt", 0777);

Android Error Building Signed APK: keystore.jks not found for signing config 'externalOverride'

I found the solution. I misplaced the path to the keystore.jks file. Searched for the file on my computer used that path and everything worked great.

How to replace a substring of a string

You need to create the variable to assign the new value to, like this:

String str = string.replaceAll("abcd","dddd");

How do you kill all current connections to a SQL Server 2005 database?

Take offline takes a while and sometimes I experience some problems with that..

Most solid way in my opinion:

Detach Right click DB -> Tasks -> Detach... check "Drop Connections" Ok

Reattach Right click Databases -> Attach.. Add... -> select your database, and change the Attach As column to your desired database name. Ok

Creating a list of pairs in java

just fixing some small mistakes in Mark Elliot's code:

public class Pair<L,R> {
    private L l;
    private R r;
    public Pair(L l, R r){
        this.l = l;
        this.r = r;
    }
    public L getL(){ return l; }
    public R getR(){ return r; }
    public void setL(L l){ this.l = l; }
    public void setR(R r){ this.r = r; }
}

Apply pandas function to column to create multiple new columns?

Just use result_type="expand"

df = pd.DataFrame(np.random.randint(0,10,(10,2)), columns=["random", "a"])
df[["sq_a","cube_a"]] = df.apply(lambda x: [x.a**2, x.a**3], axis=1, result_type="expand")

How to remove outliers from a dataset

Nobody has posted the simplest answer:

x[!x %in% boxplot.stats(x)$out]

Also see this: http://www.r-statistics.com/2011/01/how-to-label-all-the-outliers-in-a-boxplot/

d3.select("#element") not working when code above the html element

just add your <script src="./custom.js"></script> before </bod> tag. that is supply time to d3.select(#chart) detect your #chart element in html body

Resolving LNK4098: defaultlib 'MSVCRT' conflicts with

I get this every time I want to create an application in VC++.

Right-click the project, select Properties then under 'Configuration properties | C/C++ | Code Generation', select "Multi-threaded Debug (/MTd)" for Debug configuration.

Note that this does not change the setting for your Release configuration - you'll need to go to the same location and select "Multi-threaded (/MT)" for Release.

Must declare the scalar variable

Just FYI, I know this is an old post, but depending on the database COLLATION settings you can get this error on a statement like this,

SET @sql = @Sql + ' WHERE RowNum BETWEEN @RowFrom AND @RowTo;';

if for example you typo the S in the

SET @sql = @***S***ql 

sorry to spin off the answers already posted here, but this is an actual instance of the error reported.

Note also that the error will not display the capital S in the message, I am not sure why, but I think it is because the

Set @sql =

is on the left of the equal sign.

Boolean vs tinyint(1) for boolean values in MySQL

While it's true that bool and tinyint(1) are functionally identical, bool should be the preferred option because it carries the semantic meaning of what you're trying to do. Also, many ORMs will convert bool into your programing language's native boolean type.

ORACLE and TRIGGERS (inserted, updated, deleted)

Separate it into 2 triggers. One for the deletion and one for the insertion\ update.

How to set Angular 4 background image?

This works for me:

put this in your markup:

<div class="panel panel-default" [ngStyle]="{'background-image': getUrl()}">

then in component:

getUrl()
{
  return "url('http://estringsoftware.com/wp-content/uploads/2017/07/estring-header-lowsat.jpg')";
}

How to compare 2 files fast using .NET?

My answer is a derivative of @lars but fixes the bug in the call to Stream.Read. I also add some fast path checking that other answers had, and input validation. In short, this should be the answer:

using System;
using System.IO;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            var fi1 = new FileInfo(args[0]);
            var fi2 = new FileInfo(args[1]);
            Console.WriteLine(FilesContentsAreEqual(fi1, fi2));
        }

        public static bool FilesContentsAreEqual(FileInfo fileInfo1, FileInfo fileInfo2)
        {
            if (fileInfo1 == null)
            {
                throw new ArgumentNullException(nameof(fileInfo1));
            }

            if (fileInfo2 == null)
            {
                throw new ArgumentNullException(nameof(fileInfo2));
            }

            if (string.Equals(fileInfo1.FullName, fileInfo2.FullName, StringComparison.OrdinalIgnoreCase))
            {
                return true;
            }

            if (fileInfo1.Length != fileInfo2.Length)
            {
                return false;
            }
            else
            {
                using (var file1 = fileInfo1.OpenRead())
                {
                    using (var file2 = fileInfo2.OpenRead())
                    {
                        return StreamsContentsAreEqual(file1, file2);
                    }
                }
            }
        }

        private static int ReadFullBuffer(Stream stream, byte[] buffer)
        {
            int bytesRead = 0;
            while (bytesRead < buffer.Length)
            {
                int read = stream.Read(buffer, bytesRead, buffer.Length - bytesRead);
                if (read == 0)
                {
                    // Reached end of stream.
                    return bytesRead;
                }

                bytesRead += read;
            }

            return bytesRead;
        }

        private static bool StreamsContentsAreEqual(Stream stream1, Stream stream2)
        {
            const int bufferSize = 1024 * sizeof(Int64);
            var buffer1 = new byte[bufferSize];
            var buffer2 = new byte[bufferSize];

            while (true)
            {
                int count1 = ReadFullBuffer(stream1, buffer1);
                int count2 = ReadFullBuffer(stream2, buffer2);

                if (count1 != count2)
                {
                    return false;
                }

                if (count1 == 0)
                {
                    return true;
                }

                int iterations = (int)Math.Ceiling((double)count1 / sizeof(Int64));
                for (int i = 0; i < iterations; i++)
                {
                    if (BitConverter.ToInt64(buffer1, i * sizeof(Int64)) != BitConverter.ToInt64(buffer2, i * sizeof(Int64)))
                    {
                        return false;
                    }
                }
            }
        }
    }
}

Or if you want to be super-awesome, you can use the async variant:

using System;
using System.IO;
using System.Threading.Tasks;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            var fi1 = new FileInfo(args[0]);
            var fi2 = new FileInfo(args[1]);
            Console.WriteLine(FilesContentsAreEqualAsync(fi1, fi2).GetAwaiter().GetResult());
        }

        public static async Task<bool> FilesContentsAreEqualAsync(FileInfo fileInfo1, FileInfo fileInfo2)
        {
            if (fileInfo1 == null)
            {
                throw new ArgumentNullException(nameof(fileInfo1));
            }

            if (fileInfo2 == null)
            {
                throw new ArgumentNullException(nameof(fileInfo2));
            }

            if (string.Equals(fileInfo1.FullName, fileInfo2.FullName, StringComparison.OrdinalIgnoreCase))
            {
                return true;
            }

            if (fileInfo1.Length != fileInfo2.Length)
            {
                return false;
            }
            else
            {
                using (var file1 = fileInfo1.OpenRead())
                {
                    using (var file2 = fileInfo2.OpenRead())
                    {
                        return await StreamsContentsAreEqualAsync(file1, file2).ConfigureAwait(false);
                    }
                }
            }
        }

        private static async Task<int> ReadFullBufferAsync(Stream stream, byte[] buffer)
        {
            int bytesRead = 0;
            while (bytesRead < buffer.Length)
            {
                int read = await stream.ReadAsync(buffer, bytesRead, buffer.Length - bytesRead).ConfigureAwait(false);
                if (read == 0)
                {
                    // Reached end of stream.
                    return bytesRead;
                }

                bytesRead += read;
            }

            return bytesRead;
        }

        private static async Task<bool> StreamsContentsAreEqualAsync(Stream stream1, Stream stream2)
        {
            const int bufferSize = 1024 * sizeof(Int64);
            var buffer1 = new byte[bufferSize];
            var buffer2 = new byte[bufferSize];

            while (true)
            {
                int count1 = await ReadFullBufferAsync(stream1, buffer1).ConfigureAwait(false);
                int count2 = await ReadFullBufferAsync(stream2, buffer2).ConfigureAwait(false);

                if (count1 != count2)
                {
                    return false;
                }

                if (count1 == 0)
                {
                    return true;
                }

                int iterations = (int)Math.Ceiling((double)count1 / sizeof(Int64));
                for (int i = 0; i < iterations; i++)
                {
                    if (BitConverter.ToInt64(buffer1, i * sizeof(Int64)) != BitConverter.ToInt64(buffer2, i * sizeof(Int64)))
                    {
                        return false;
                    }
                }
            }
        }
    }
}

How can I completely uninstall nodejs, npm and node in Ubuntu

sudo apt-get remove nodejs
sudo apt-get remove npm

Then go to /etc/apt/sources.list.d and remove any node list if you have. Then do a

sudo apt-get update

Check for any .npm or .node folder in your home folder and delete those.

If you type

which node

you can see the location of the node. Try which nodejs and which npm too.

I would recommend installing node using Node Version Manager(NVM). That saved a lot of headache for me. You can install nodejs and npm without sudo using nvm.

Picasso v/s Imageloader v/s Fresco vs Glide

Mind you that this is a highly opinion based question, so I stopped making fjords and made a quick table

enter image description here

Now library comparison is hard because on many parameters, all the four pretty much do the same thing, except possibly for Fresco because there is a whole bunch of new memory level optimizations in it.So let me know if certain parameters you'd like to see a comparison for based on my experience.

Having used Fresco the least, the answer might evolve as I continue to use and understand it for current exploits. The used personally is having used the library atleast once in a completed app.

*Note - Fresco now supports GIF as well as WebP animations

Deserialize JSON string to c# object

Same problem happened to me. So if the service returns the response as a JSON string you have to deserialize the string first, then you will be able to deserialize the object type from it properly:

string json= string.Empty;
using (var streamReader = new StreamReader(response.GetResponseStream(), true))
        {
            json= new JavaScriptSerializer().Deserialize<string>(streamReader.ReadToEnd());

        }
//To deserialize to your object type...
MyType myType;
using (var memoryStream = new MemoryStream())
         {
            byte[] jsonBytes = Encoding.UTF8.GetBytes(@json);
            memoryStream.Write(jsonBytes, 0, jsonBytes.Length);
            memoryStream.Seek(0, SeekOrigin.Begin);
            using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(memoryStream, Encoding.UTF8,          XmlDictionaryReaderQuotas.Max, null))
            {
                var serializer = new DataContractJsonSerializer(typeof(MyType));
                myType = (MyType)serializer.ReadObject(jsonReader);

            }
        }

4 Sure it will work.... ;)

How to remove error about glyphicons-halflings-regular.woff2 not found

For me, the problem was twofold: First, the version of IIS I was dealing with didn't know about the .woff2 MIME type, only about .woff. I fixed that using IIS Manager at the server level, not at the web app level, so the setting wouldn't get overridden with each new app deployment. (Under IIS Manager, I went to MIME types, and added the missing .woff2, then updated .woff.)

Second, and more importantly, I was bundling bootstrap.css along with some other files as "~/bundles/css/site". Meanwhile, my font files were in "~/fonts". bootstrap.css looks for the glyphicon fonts in "../fonts", which translated to "~/bundles/fonts" -- wrong path.

In other words, my bundle path was one directory too deep. I renamed it to "~/bundles/siteCss", and updated all the references to it that I found in my project. Now bootstrap looked in "~/fonts" for the glyphicon files, which worked. Problem solved.

Before I fixed the second problem above, none of the glyphicon font files were loading. The symptom was that all instances of glyphicon glyphs in the project just showed an empty box. However, this symptom only occurred in the deployed versions of the web app, not on my dev machine. I'm still not sure why that was the case.

Function vs. Stored Procedure in SQL Server

To decide on when to use what the following points might help-

  1. Stored procedures can't return a table variable where as function can do that.

  2. You can use stored procedures to alter the server environment parameters where as using functions you can't.

cheers

How to pass command line arguments to a shell alias?

Here's a simple example function using python. You can stick in ~/.bashrc
You gotta have a space after the first left curly bracket
The python command needs to be in double quotes to get the variable substitution
Don't forget that semicolon at the end

function count(){ python -c "for num in xrange($1):print num";}

$ count 6
0
1
2
3
4
5
$

Find and replace entire mysql database

This isn't possible - you need to carry out an UPDATE for each table individually.

WARNING: DUBIOUS, BUT IT'LL WORK (PROBABLY) SOLUTION FOLLOWS

Alternatively, you could dump the database via mysqldump and simply perform the search/replace on the resultant SQL file. (I'd recommend offlining anything that might touch the database whilst this is in progress, as well as using the --add-drop-table and --extended-insert flags.) However, you'd need to be sure that the search/replace text wasn't going to alter anything other than the data itself (i.e.: that the text you were going to swap out might not occur as a part of SQL syntax) and I'd really try doing the re-insert on an empty test database first.)

"Post Image data using POSTMAN"

That's not how you send file on postman. What you did is sending a string which is the path of your image, nothing more.

What you should do is;

  1. After setting request method to POST, click to the 'body' tab.
  2. Select form-data. At first line, you'll see text boxes named key and value. Write 'image' to the key. You'll see value type which is set to 'text' as default. Make it File and upload your file.
  3. Then select 'raw' and paste your json file. Also just next to the binary choice, You'll see 'Text' is clicked. Make it JSON.

form-data section

raw section

You're ready to go.

In your Django view,

from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser
from rest_framework.decorators import parser_classes

@parser_classes((MultiPartParser, ))
class UploadFileAndJson(APIView):

    def post(self, request, format=None):
        thumbnail = request.FILES["file"]
        info = json.loads(request.data['info'])
        ...
        return HttpResponse()

Text file with 0D 0D 0A line breaks

The CRCRLF is known as result of a Windows XP notepad word wrap bug.

For future reference, here's an extract of relevance from the linked blog:

When you press the Enter key on Windows computers, two characters are actually stored: a carriage return (CR) and a line feed (LF). The operating system always interprets the character sequence CR LF the same way as the Enter key: it moves to the next line. However when there are extra CR or LF characters on their own, this can sometimes cause problems.

There is a bug in the Windows XP version of Notepad that can cause extra CR characters to be stored in the display window. The bug happens in the following situation:

If you have the word wrap option turned on and the display window contains long lines that wrap around, then saving the file causes Notepad to insert the characters CR CR LF at each wrap point in the display window, but not in the saved file.

The CR CR LF characters can cause oddities if you copy and paste them into other programs. They also prevent Notepad from properly re-wrapping the lines if you resize the Notepad window.

You can remove the CR CR LF characters by turning off the word wrap feature, then turning it back on if desired. However, the cursor is repositioned at the beginning of the display window when you do this.

"NOT IN" clause in LINQ to Entities

Try:

from p in db.Products
where !theBadCategories.Contains(p.Category)
select p;

What's the SQL query you want to translate into a Linq query?

List to array conversion to use ravel() function

if variable b has a list then you can simply do the below:

create a new variable "a" as: a=[] then assign the list to "a" as: a=b

now "a" has all the components of list "b" in array.

so you have successfully converted list to array.

How to set initial size of std::vector?

std::vector<CustomClass *> whatever(20000);

or:

std::vector<CustomClass *> whatever;
whatever.reserve(20000);

The former sets the actual size of the array -- i.e., makes it a vector of 20000 pointers. The latter leaves the vector empty, but reserves space for 20000 pointers, so you can insert (up to) that many without it having to reallocate.

At least in my experience, it's fairly unusual for either of these to make a huge difference in performance--but either can affect correctness under some circumstances. In particular, as long as no reallocation takes place, iterators into the vector are guaranteed to remain valid, and once you've set the size/reserved space, you're guaranteed there won't be any reallocations as long as you don't increase the size beyond that.

'tuple' object does not support item assignment

Tuples, in python can't have their values changed. If you'd like to change the contained values though I suggest using a list:

[1,2,3] not (1,2,3)

Append values to query string

Note you can add the Microsoft.AspNetCore.WebUtilities nuget package from Microsoft and then use this to append values to query string:

QueryHelpers.AddQueryString(longurl, "action", "login1")
QueryHelpers.AddQueryString(longurl, new Dictionary<string, string> { { "action", "login1" }, { "attempts", "11" } });

How to create a label inside an <input> element?

If you're using HTML5, you can use the placeholder attribute.

<input type="text" name="user" placeholder="Username">

popup form using html/javascript/css

Here is a resource you can edit and use Download Source Code or see live demo here http://purpledesign.in/blog/pop-out-a-form-using-jquery-and-javascript/

Add a Button or link to your page like this

<p><a href="#inline">click to open</a></p>

“#inline” here should be the “id” of the that will contain the form.

<div id="inline">
 <h2>Send us a Message</h2>
 <form id="contact" name="contact" action="#" method="post">
 <label for="email">Your E-mail</label>
 <input type="email" id="email" name="email" class="txt">
 <br>
 <label for="msg">Enter a Message</label>
 <textarea id="msg" name="msg" class="txtarea"></textarea>
<button id="send">Send E-mail</button>
 </form>
</div>

Include these script to listen of the event of click. If you have an action defined in your form you can use “preventDefault()” method

<script type="text/javascript">
 $(document).ready(function() {
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
var emailval = $("#email").val();
var msgval = $("#msg").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
 $("#email").removeClass("error");
 }

 if(msglen < 4) {
 $("#msg").addClass("error");
 }
 else if(msglen >= 4){
 $("#msg").removeClass("error");
 }

 if(mailvalid == true && msglen >= 4) {
 // if both validate we attempt to send the e-mail
 // first we hide the submit btn so the user doesnt click twice
 $("#send").replaceWith("<em>sending...</em>");
 //This will post it to the php page
 $.ajax({
 type: 'POST',
 url: 'sendmessage.php',
 data: $("#contact").serialize(),
 success: function(data) {
 if(data == "true") {
 $("#contact").fadeOut("fast", function(){
//Display a message on successful posting for 1 sec
 $(this).before("<p><strong>Success! Your feedback has been sent, thanks :)</strong></p>");
 setTimeout("$.fancybox.close()", 1000);
 });
 }
 }
 });
 }
 });
 });
</script>

You can add anything you want to do in your PHP file.

Deserialize JSON to ArrayList<POJO> using Jackson

You can deserialize directly to a list by using the TypeReference wrapper. An example method:

public static <T> T fromJSON(final TypeReference<T> type,
      final String jsonPacket) {
   T data = null;

   try {
      data = new ObjectMapper().readValue(jsonPacket, type);
   } catch (Exception e) {
      // Handle the problem
   }
   return data;
}

And is used thus:

final String json = "";
Set<POJO> properties = fromJSON(new TypeReference<Set<POJO>>() {}, json);

TypeReference Javadoc

PHP array: count or sizeof?

sizeof() is just an alias of count() as mentioned here

http://php.net/manual/en/function.sizeof.php

copy-item With Alternate Credentials

I would try to map a drive to the remote system (using 'net use' or WshNetwork.MapNetworkDrive, both methods support credentials) and then use copy-item.

Horizontal swipe slider with jQuery and touch devices support?

Have a look at jQuery scroll view (demo here). Here is the git hub repository for that experimental project. Look at their html to see what files need to be included and what attributes to add to the elements you want to be scrollable.

I have used this to be able to scroll div elements horizontally on touch devices.

Facebook login "given URL not allowed by application configuration"

I kept getting this error, when using wildcard subdomains with my app. I had the site url set to: http://myapp.com and app domain also to http://myapp.com, and also the same value for the Valid OAuth redirect URIs in the advanced tab of the settings app. I tried different combinations but only setting the http://subdomain.myapp.com as the redirect value worked, of course only for that subdomain.

The solution was to empty the redirect fields, leave it blank, that worked! ;)

Get the POST request body from HttpServletRequest

If all you want is the POST request body, you could use a method like this:

static String extractPostRequestBody(HttpServletRequest request) throws IOException {
    if ("POST".equalsIgnoreCase(request.getMethod())) {
        Scanner s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }
    return "";
}

Credit to: https://stackoverflow.com/a/5445161/1389219

Given URL is not allowed by the Application configuration

For me it was the "Single Sign On" (can be seen at the bottome of the screenshot in phwd's answer) setting that was turned off.

Group by with union mysql select query

This may be what your after:

SELECT Count(Owner_ID), Name
FROM (
    SELECT M.Owner_ID, O.Name, T.Type
    FROM Transport As T, Owner As O, Motorbike As M
    WHERE T.Type = 'Motorbike'
    AND O.Owner_ID = M.Owner_ID
    AND T.Type_ID = M.Motorbike_ID

    UNION ALL

    SELECT C.Owner_ID, O.Name, T.Type
    FROM Transport As T, Owner As O, Car As C
    WHERE T.Type = 'Car'
    AND O.Owner_ID = C.Owner_ID
    AND T.Type_ID = C.Car_ID
)
GROUP BY Owner_ID

How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption

This message can also occur when you specify the incorrect decryption password (yeah, lame, but not quite obvious to realize this from the error message, huh?).

I was using the command line to decrypt the recent DataBase backup for my auxiliary tool and suddenly faced this issue.

Finally, after 10 mins of grief and plus reading through this question/answers I have remembered that the password is different and everything worked just fine with the correct password.

Char array declaration and initialization in C

That's because your first code snippet is not performing initialization, but assignment:

char myarray[4] = "abc";  // Initialization.

myarray = "abc";          // Assignment.

And arrays are not directly assignable in C.

The name myarray actually resolves to the address of its first element (&myarray[0]), which is not an lvalue, and as such cannot be the target of an assignment.

Usage of unicode() and encode() functions in Python

str is text representation in bytes, unicode is text representation in characters.

You decode text from bytes to unicode and encode a unicode into bytes with some encoding.

That is:

>>> 'abc'.decode('utf-8')  # str to unicode
u'abc'
>>> u'abc'.encode('utf-8') # unicode to str
'abc'

UPD Sep 2020: The answer was written when Python 2 was mostly used. In Python 3, str was renamed to bytes, and unicode was renamed to str.

>>> b'abc'.decode('utf-8') # bytes to str
'abc'
>>> 'abc'.encode('utf-8'). # str to bytes
b'abc'

Practical uses for AtomicInteger

The primary use of AtomicInteger is when you are in a multithreaded context and you need to perform thread safe operations on an integer without using synchronized. The assignation and retrieval on the primitive type int are already atomic but AtomicInteger comes with many operations which are not atomic on int.

The simplest are the getAndXXX or xXXAndGet. For instance getAndIncrement() is an atomic equivalent to i++ which is not atomic because it is actually a short cut for three operations: retrieval, addition and assignation. compareAndSet is very useful to implements semaphores, locks, latches, etc.

Using the AtomicInteger is faster and more readable than performing the same using synchronization.

A simple test:

public synchronized int incrementNotAtomic() {
    return notAtomic++;
}

public void performTestNotAtomic() {
    final long start = System.currentTimeMillis();
    for (int i = 0 ; i < NUM ; i++) {
        incrementNotAtomic();
    }
    System.out.println("Not atomic: "+(System.currentTimeMillis() - start));
}

public void performTestAtomic() {
    final long start = System.currentTimeMillis();
    for (int i = 0 ; i < NUM ; i++) {
        atomic.getAndIncrement();
    }
    System.out.println("Atomic: "+(System.currentTimeMillis() - start));
}

On my PC with Java 1.6 the atomic test runs in 3 seconds while the synchronized one runs in about 5.5 seconds. The problem here is that the operation to synchronize (notAtomic++) is really short. So the cost of the synchronization is really important compared to the operation.

Beside atomicity AtomicInteger can be use as a mutable version of Integer for instance in Maps as values.

Difference between a View's Padding and Margin

Sometimes you can achieve the same result by playing only with padding OR margin. Example :

Say View X contains view Y (aka : View Y is inside View X).

-View Y with Margin=30 OR View X with Padding=30 will achieve the same result: View Y will have an offset of 30.

How do I install opencv using pip?

You can install opencv in a simple way $ pip install opencv-python If u are having errors, you can do this $ pip install opencv-python-headless

Python Set Comprehension

You can get clean and clear solutions by building the appropriate predicates as helper functions. In other words, use the Python set-builder notation the same way you would write the answer with regular mathematics set-notation.

The whole idea behind set comprehensions is to let us write and reason in code the same way we do mathematics by hand.

With an appropriate predicate in hand, problem 1 simplifies to:

 low_primes = {x for x in range(1, 100) if is_prime(x)}

And problem 2 simplifies to:

 low_prime_pairs = {(x, x+2) for x in range(1,100,2) if is_prime(x) and is_prime(x+2)}

Note how this code is a direct translation of the problem specification, "A Prime Pair is a pair of consecutive odd numbers that are both prime."

P.S. I'm trying to give you the correct problem solving technique without actually giving away the answer to the homework problem.

How to comment lines in rails html.erb files?

Note that if you want to comment out a single line of printing erb you should do like this

<%#= ["Buck", "Papandreou"].join(" you ") %>

How to send email from MySQL 5.1

I agree with Jim Blizard. The database is not the part of your technology stack that should send emails. For example, what if you send an email but then roll back the change that triggered that email? You can't take the email back.

It's better to send the email in your application code layer, after your app has confirmed that the SQL change was made successfully and committed.

Python: Split a list into sub-lists based on index ranges

If you already know the indices:

list1 = ['x','y','z','a','b','c','d','e','f','g']
indices = [(0, 4), (5, 9)]
print [list1[s:e+1] for s,e in indices]

Note that we're adding +1 to the end to make the range inclusive...

How do I "shake" an Android device within the Android emulator to bring up the dev menu to debug my React Native app

As while developing react native apps, we play with the terminal so much

so I added a script in the scripts in the package.json file

"menu": "adb shell input keyevent 82"

and I hit $ yarn menu

for the menu to appear on the emulator it will forward the keycode 82 to the emulator via ADB not the optimal way but I like it and felt to share it.

enter image description here

Which one is the best PDF-API for PHP?

From the mpdf site: "mPDF is a PHP class which generates PDF files from UTF-8 encoded HTML. It is based on FPDF and HTML2FPDF, with a number of enhancements."

mpdf is superior to FPDF for language handling and UTF-8 support. For CJK support it not only supports font embedding, but font subsetting (so your CJK PDFs are not oversized). TCPDF and FPDF have nothing on the UTF-8 and Font support of mpdf. It even comes with some open source fonts as of version 5.0.

How to get all of the IDs with jQuery?

My suggestion?

var arr = $.map($("#mydiv [id]"), function(n, i) {
  return n.id;
});

you could also do this as:

var arr = $.map($("#mydiv span"), function(n, i) {

or

var arr = $.map($("#mydiv span[id]"), function(n, i) {

or even just:

var arr = $("#mydiv [id]").map(function() {
  return this.id;
});

Lots of ways basically.

SSIS expression: convert date to string

For SSIS you could go with:

RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" +  (DT_STR, 4, 1252) DATEPART("yy" , GETDATE())

Expression builder screen:

Expression builder screen

Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window

For those of you who are popping up a new window to print from, and then automatically closing it after the user clicks "Print" or "Cancel" on the Chrome print preview, I used the following (thanks to the help from PaulVB's answer):

if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
    var showPopup = false;
    window.onbeforeunload = function () {
        if (showPopup) {
            return 'You must use the Cancel button to close the Print Preview window.\n';
        } else {
            showPopup = true;
        }
    }
    window.print();
    window.close();
} else {
    window.print();
    window.close();
}

I am debating if it would be a good idea to also filter by the version of Chrome...

clear cache of browser by command line

Here is how to clear all trash & caches (without other private data in browsers) by a command line. This is a command line batch script that takes care of all trash (as of April 2014):

erase "%TEMP%\*.*" /f /s /q
for /D %%i in ("%TEMP%\*") do RD /S /Q "%%i"

erase "%TMP%\*.*" /f /s /q
for /D %%i in ("%TMP%\*") do RD /S /Q "%%i"

erase "%ALLUSERSPROFILE%\TEMP\*.*" /f /s /q
for /D %%i in ("%ALLUSERSPROFILE%\TEMP\*") do RD /S /Q "%%i"

erase "%SystemRoot%\TEMP\*.*" /f /s /q
for /D %%i in ("%SystemRoot%\TEMP\*") do RD /S /Q "%%i"


@rem Clear IE cache -  (Deletes Temporary Internet Files Only)
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
erase "%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*") do RD /S /Q "%%i"

@rem Clear Google Chrome cache
erase "%LOCALAPPDATA%\Google\Chrome\User Data\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Google\Chrome\User Data\*") do RD /S /Q "%%i"


@rem Clear Firefox cache
erase "%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*") do RD /S /Q "%%i"

pause

I am pretty sure it will run for some time when you first run it :) Enjoy!

Change DataGrid cell colour based on values

Based on the answer by 'Cassio Borghi'. With this method, there is no need to change the XAML at all.

        DataGridTextColumn colNameStatus2 = new DataGridTextColumn();
        colNameStatus2.Header = "Status";
        colNameStatus2.MinWidth = 100;
        colNameStatus2.Binding = new Binding("Status");
        grdComputer_Servives.Columns.Add(colNameStatus2);

        Style style = new Style(typeof(TextBlock));
        Trigger running = new Trigger() { Property = TextBlock.TextProperty, Value = "Running" };
        Trigger stopped = new Trigger() { Property = TextBlock.TextProperty, Value = "Stopped" };

        stopped.Setters.Add(new Setter() { Property = TextBlock.BackgroundProperty, Value = Brushes.Blue });
        running.Setters.Add(new Setter() { Property = TextBlock.BackgroundProperty, Value = Brushes.Green });

        style.Triggers.Add(running);
        style.Triggers.Add(stopped);

        colNameStatus2.ElementStyle = style;

        foreach (var Service in computerResult)
        {
            var RowName = Service;  
            grdComputer_Servives.Items.Add(RowName);
        }

Get first element in PHP stdObject

Update PHP 7.4

Curly brace access syntax is deprecated since PHP 7.4

Update 2019

Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.

Simply iterate its using {}

Example:

$videos{0}->id

This way your object is not destroyed and you can easily iterate through object.

For PHP 5.6 and below use this

$videos{0}['id']

Both array() and the stdClass objects can be accessed using the current() key() next() prev() reset() end() functions.

So, if your object looks like

object(stdClass)#19 (3) {
  [0]=>
  object(stdClass)#20 (22) {
    ["id"]=>
    string(1) "123"
  etc...

Then you can just do;

$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object

If you need the key for some reason, you can do;

reset($obj); //Ensure that we're at the first element
$key = key($obj);

Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4


2022 Update:
After PHP 7.4, using current(), end(), etc functions on objects is deprecated.

In newer versions of PHP, use the ArrayIterator class:

$objIterator = new ArrayIterator($obj);

$id = $objIterator->current()->id; // Gets the 'id' attr of the first entry in the object

$key = $objIterator->key(); // and gets the key

Print PHP Call Stack

To log the trace

$e = new Exception;
error_log(var_export($e->getTraceAsString(), true));

Thanks @Tobiasz

How to create Android Facebook Key Hash?

Since API 26, you can generate your HASH KEYS using the following code in KOTLIN without any need of Facebook SDK.

fun generateSSHKey(context: Context){
    try {
        val info = context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_SIGNATURES)
        for (signature in info.signatures) {
            val md = MessageDigest.getInstance("SHA")
            md.update(signature.toByteArray())
            val hashKey = String(Base64.getEncoder().encode(md.digest()))
            Log.i("AppLog", "key:$hashKey=")
        }
    } catch (e: Exception) {
        Log.e("AppLog", "error:", e)
    }

}

enter image description here

How to create Java gradle project

I could handle it using a groovy method in build.gradle to create all source folders for java, resources and test. Then I set it to run before gradle eclipse task.

eclipseClasspath.doFirst {
    initSourceFolders()
}

def initSourceFolders() {
    sourceSets*.java.srcDirs*.each { it.mkdirs() }
    sourceSets*.resources.srcDirs*.each { it.mkdirs() }
}

Now we can setup a new gradle Java EE project to eclipse with only one command. I put this example at GitHub

Html: Difference between cell spacing and cell padding

This is the simple answer I can give.

enter image description here

Microsoft Advertising SDK doesn't deliverer ads

I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.

Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled

Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is

  1. Remove the XAML for the ad
  2. Remove the xmlns declaration (usually at the top of the page, but sometimes will be declared in the ad itself)
  3. Remove the bad DLL (the one ending in .SDK )
  4. Do a Clean and then Build (clean out anything remaining from the DLL)
  5. Add the xmlns reference (actual reference is below)
  6. Add the ad to the page (example below)

Here is the xmlns reference:

xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI" 

Then the ad itself:

<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480"                    AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/> 

Iterate through DataSet

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (object item in row.ItemArray)
        {
            // read item
        }
    }
}

Or, if you need the column info:

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn column in table.Columns)
        {
            object item = row[column];
            // read column and item
        }
    }
}

How to install wget in macOS?

You need to do

./configure --with-ssl=openssl --with-libssl-prefix=/usr/local/ssl

Instead of this

./configure --with-ssl=openssl

Is it possible to import a whole directory in sass using @import?

It might be an old question, but still relevant in 2020, so I might post some update. Since Octobers'19 update we generally should use @use instead of @import, but that's only a remark. Solution to this question is use index files to simplify including whole folders. Example below.

// foundation/_code.scss
code {
  padding: .25em;
  line-height: 0;
}

// foundation/_lists.scss
ul, ol {
  text-align: left;

  & & {
    padding: {
      bottom: 0;
      left: 0;
    }
  }
}

// foundation/_index.scss
@use 'code';
@use 'lists';

// style.scss
@use 'foundation';

https://sass-lang.com/documentation/at-rules/use#index-files

How do I hide a menu item in the actionbar?

The best way to hide all items in a menu with just one command is to use "group" on your menu xml. Just add all menu items that will be in your overflow menu inside the same group.

In this example we have two menu items that will always show (regular item and search) and three overflow items:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/someItemNotToHide1"
        android:title="ITEM"
        app:showAsAction="always" />

    <item
        android:id="@+id/someItemNotToHide2"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="collapseActionView|ifRoom"
        app:actionViewClass="android.support.v7.widget.SearchView"
        android:title="Search"/>

    <group android:id="@+id/overFlowItemsToHide">
    <item android:id="@+id/someID" 
    android:orderInCategory="1" app:showAsAction="never" />
    <item android:id="@+id/someID2" 
    android:orderInCategory="1" app:showAsAction="never" />
    <item android:id="@+id/someID3" 
    android:orderInCategory="1" app:showAsAction="never" />
    </group>
</menu>

Then, on your activity (preferable at onCreateOptionsMenu), use command setGroupVisible to set all menu items visibility to false or true.

public boolean onCreateOptionsMenu(Menu menu) {
   menu.setGroupVisible(R.id.overFlowItems, false); // Or true to be visible
}

If you want to use this command anywhere else on your activity, be sure to save menu class to local, and always check if menu is null, because you can execute before createOptionsMenu:

Menu menu;

public boolean onCreateOptionsMenu(Menu menu) {
       this.menu = menu;

}

public void hideMenus() {
       if (menu != null) menu.setGroupVisible(R.id.overFlowItems, false); // Or true to be visible       
}

Proper way to initialize a C# dictionary with values?

Object initializers were introduced in C# 3.0, check which framework version you are targeting.

Overview of C# 3.0

How to get the last day of the month?

Considering there are unequal number of days in different months, here is the standard solution that works for every month.

import datetime
ref_date = datetime.today() # or what ever specified date

end_date_of_month = datetime.strptime(datetime.strftime(ref_date + relativedelta(months=1), '%Y-%m-01'),'%Y-%m-%d') + relativedelta(days=-1)

In the above code we are just adding a month to our selected date and then navigating to the first day of that month and then subtracting a day from that date.

jQuery ajax request with json response, how to?

Firstly, it will help if you set the headers of your PHP to serve JSON:

header('Content-type: application/json');

Secondly, it will help to adjust your ajax call:

$.ajax({
    url: "main.php",
    type: "POST",
    dataType: "json",
    data: {"action": "loadall", "id": id},
    success: function(data){
        console.log(data);
    },
    error: function(error){
         console.log("Error:");
         console.log(error);
    }
});

If successful, the response you receieve should be picked up as true JSON and an object should be logged to console.

NOTE: If you want to pick up pure html, you might want to consider using another method to JSON, but I personally recommend using JSON and rendering it into html using templates (such as Handlebars js).

String comparison technique used by Python

Python and just about every other computer language use the same principles as (I hope) you would use when finding a word in a printed dictionary:

(1) Depending on the human language involved, you have a notion of character ordering: 'a' < 'b' < 'c' etc

(2) First character has more weight than second character: 'az' < 'za' (whether the language is written left-to-right or right-to-left or boustrophedon is quite irrelevant)

(3) If you run out of characters to test, the shorter string is less than the longer string: 'foo' < 'food'

Typically, in a computer language the "notion of character ordering" is rather primitive: each character has a human-language-independent number ord(character) and characters are compared and sorted using that number. Often that ordering is not appropriate to the human language of the user, and then you need to get into "collating", a fun topic.

How to get EditText value and display it on screen through TextView?

I'm just beginner to help you for getting edittext value to textview. Try out this code -

EditText edit = (EditText)findViewById(R.id.editext1);
TextView tview = (TextView)findViewById(R.id.textview1);
String result = edit.getText().toString();
tview.setText(result);

This will get the text which is in EditText Hope this helps you.

Can I limit the length of an array in JavaScript?

var  arrLength = arr.length;
if(arrLength > maxNumber){
    arr.splice( 0, arrLength - maxNumber);
}

This soultion works better in an dynamic environment like p5js. I put this inside the draw call and it clamps the length of the array dynamically.

The problem with:

arr.slice(0,5)

...is that it only takes a fixed number of items off the array per draw frame, which won't be able to keep the array size constant if your user can add multiple items.

The problem with:

if (arr.length > 4) arr.length = 4;

...is that it takes items off the end of the array, so which won't cycle through the array if you are also adding to the end with push().

Objective-C declared @property attributes (nonatomic, copy, strong, weak)

Nonatomic

Nonatomic will not generate threadsafe routines thru @synthesize accessors. atomic will generate threadsafe accessors so atomic variables are threadsafe (can be accessed from multiple threads without botching of data)

Copy

copy is required when the object is mutable. Use this if you need the value of the object as it is at this moment, and you don't want that value to reflect any changes made by other owners of the object. You will need to release the object when you are finished with it because you are retaining the copy.

Assign

Assign is somewhat the opposite to copy. When calling the getter of an assign property, it returns a reference to the actual data. Typically you use this attribute when you have a property of primitive type (float, int, BOOL...)

Retain

retain is required when the attribute is a pointer to a reference counted object that was allocated on the heap. Allocation should look something like:

NSObject* obj = [[NSObject alloc] init]; // ref counted var

The setter generated by @synthesize will add a reference count to the object when it is copied so the underlying object is not autodestroyed if the original copy goes out of scope.

You will need to release the object when you are finished with it. @propertys using retain will increase the reference count and occupy memory in the autorelease pool.

Strong

strong is a replacement for the retain attribute, as part of Objective-C Automated Reference Counting (ARC). In non-ARC code it's just a synonym for retain.

This is a good website to learn about strong and weak for iOS 5. http://www.raywenderlich.com/5677/beginning-arc-in-ios-5-part-1

Weak

weak is similar to strong except that it won't increase the reference count by 1. It does not become an owner of that object but just holds a reference to it. If the object's reference count drops to 0, even though you may still be pointing to it here, it will be deallocated from memory.

The above link contain both Good information regarding Weak and Strong.

How can I edit javascript in my browser like I can use Firebug to edit CSS/HTML?

I'd like to get back to Fiddler. After having played with that for a while, it is clearly the best way to edit any web requests on-the-fly. Being JavaScript, POST, GET, HTML, XML whatever and anything. It's free, but a little tricky to implement. Here's my HOW-TO:

To use Fiddler to manipulate JavaScript (on-the-fly) with Firefox, do the following:

1) Download and install Fiddler

2) Download and install the Fiddler extension: "3 Syntax-Highlighting add-ons"

3) Restart Firefox and enable the "FiddlerHook" extension

4) Open Firefox and enable the FiddlerHook toolbar button: View > Toolbars > Customize...

5) Click the Fiddler tool button and wait for fiddler to start.

6) Point your browser to Fiddler's test URLs:

Echo Service:  http://127.0.0.1:8888/
DNS Lookup:    http://www.localhost.fiddler:8888/

7) Add Fiddler Rules in order to intercept and edit JavaScript before reaching the browser/server. In Fiddler click: Rules > Customize Rules.... [CTRL-R] This will start the ScriptEditor.

8) Edit and Add the following rules:


a) To pause JavaScript to allow editing, add under the function "OnBeforeResponse":

if (oSession.oResponse.headers.ExistsAndContains("Content-Type", "javascript")){
  oSession["x-breakresponse"]="reason is JScript"; 
}

b) To pause HTTP POSTs to allow editing when using the POST verb, edit "OnBeforeRequest":

if (oSession.HTTPMethodIs("POST")){
  oSession["x-breakrequest"]="breaking for POST";
}

c) To pause a request for an XML file to allow editing, edit "OnBeforeRequest":

if (oSession.url.toLowerCase().indexOf(".xml")>-1){
  oSession["x-breakrequest"]="reason_XML"; 
}

[9] TODO: Edit the above CustomRules.js to allow for disabling (a-c).

10) The browser loading will now stop on every JavaScript found and display a red pause mark for every script. In order to continue loading the page you need to click the green "Run to Completion" button for every script. (Which is why we'd like to implement [9].)

Use Font Awesome icon as CSS content

Here's my webpack 4 + font awesome 5 solution:

webpack plugin:

new CopyWebpackPlugin([
    { from: 'node_modules/font-awesome/fonts', to: 'font-awesome' }
  ]),

global css style:

@font-face {
    font-family: 'FontAwesome';
    src: url('/font-awesome/fontawesome-webfont.eot');
    src: url('/font-awesome/fontawesome-webfont.eot?#iefix') format('embedded-opentype'),
    url('/font-awesome/fontawesome-webfont.woff2') format('woff2'),
    url('/font-awesome/fontawesome-webfont.woff') format('woff'),
    url('/font-awesome/fontawesome-webfont.ttf') format('truetype'),
    url('/font-awesome/fontawesome-webfont.svgfontawesomeregular') format('svg');
    font-weight: normal;
    font-style: normal;
}

i {
    font-family: "FontAwesome";
}

MINGW64 "make build" error: "bash: make: command not found"

Try using cmake itself. In the build directory, run:

cmake --build .

set the iframe height automatically

Try this coding

<div>
    <iframe id='iframe2' src="Mypage.aspx" frameborder="0" style="overflow: hidden; height: 100%;
        width: 100%; position: absolute;"></iframe>
</div>

How do I compare two Integers?

Use the equals method. Why are you so worried that it's expensive?

DataGridView - how to set column width?

Regarding your final bullet

make width fit the text

You can experiment with the .AutoSizeMode of your DataGridViewColumn, setting it to one of these values:

None
AllCells
AllCellsExceptHeader
DisplayedCells
DisplayedCellsExceptHeader
ColumnHeader
Fill

More info on the MSDN page

Redirect in Spring MVC

Try this, it should work if you have configured your view resolver properly

 return "redirect:/index.html";

java Arrays.sort 2d array

Simplified Java 8

IntelliJ suggests to simplify the top answer to the:

Arrays.sort(queries, Comparator.comparingDouble(a -> a[0]));

Setting Action Bar title and subtitle

supportActionBar?.title = "Hola tio"
supportActionBar?.subtitle = "Vamos colega!"

Countdown timer using Moment js

Here's my timer for 5 minutes:

var start = moment("5:00", "m:ss");
var seconds = start.minutes() * 60;
this.interval = setInterval(() => {
    this.timerDisplay = start.subtract(1, "second").format("m:ss");
    seconds--;
    if (seconds === 0) clearInterval(this.interval);
}, 1000);

Doctrine query builder using inner join with conditions

You can explicitly have a join like this:

$qb->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId');

But you need to use the namespace of the class Join from doctrine:

use Doctrine\ORM\Query\Expr\Join;

Or if you prefere like that:

$qb->innerJoin('c.phones', 'p', Doctrine\ORM\Query\Expr\Join::ON, 'c.id = p.customerId');

Otherwise, Join class won't be detected and your script will crash...

Here the constructor of the innerJoin method:

public function innerJoin($join, $alias, $conditionType = null, $condition = null);

You can find other possibilities (not just join "ON", but also "WITH", etc...) here: http://docs.doctrine-project.org/en/2.0.x/reference/query-builder.html#the-expr-class

EDIT

Think it should be:

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId')
    ->where('c.username = :username')
    ->andWhere('p.phone = :phone');

    $qb->setParameters(array(
        'username' => $username,
        'phone' => $phone->getPhone(),
    ));

Otherwise I think you are performing a mix of ON and WITH, perhaps the problem.

Don't change link color when a link is clicked

you are looking for this:

a:visited{
  color:blue;
}

Links have several states you can alter... the way I remember them is LVHFA (Lord Vader's Handle Formerly Anakin)

Each letter stands for a pseudo class: (Link,Visited,Hover,Focus,Active)

a:link{
  color:blue;
}
a:visited{
  color:purple;
}
a:hover{
  color:orange;
}
a:focus{
  color:green;
}
a:active{
  color:red;
}

If you want the links to always be blue, just change all of them to blue. I would note though on a usability level, it would be nice if the mouse click caused the color to change a little bit (even if just a lighter/darker blue) to help indicate that the link was actually clicked (this is especially important in a touchscreen interface where you're not always sure the click was actually registered)

If you have different types of links that you want to all have the same color when clicked, add a class to the links.

a.foo, a.foo:link, a.foo:visited, a.foo:hover, a.foo:focus, a.foo:active{
  color:green;
}
a.bar, a.bar:link, a.bar:visited, a.bar:hover, a.bar:focus, a.bar:active{
  color:orange;
}

It should be noted that not all browsers respect each of these options ;-)

Error:java: javacTask: source release 8 requires target release 1.8

I fixed it just by changing target compile version to 1.8. Its in:

File >> Settings >> Build, Execution, Deployment >> Compiler >> Java Compiler

How to show grep result with complete path or file name

For me

grep -b "searchsomething" *.log

worked as I wanted

How to get element by innerText

I think you'll need to be a bit more specific for us to help you.

  1. How are you finding this? Javascript? PHP? Perl?
  2. Can you apply an ID attribute to the tag?

If the text is unique (or really, if it's not, but you'd have to run through an array) you could run a regular expression to find it. Using PHP's preg_match() would work for that.

If you're using Javascript and can insert an ID attribute, then you can use getElementById('id'). You can then access the returned element's attributes through the DOM: https://developer.mozilla.org/en/DOM/element.1.

How to convert QString to std::string?

An alternative to the proposed:

QString qs;
std::string current_locale_text = qs.toLocal8Bit().constData();

could be:

QString qs;
std::string current_locale_text = qPrintable(qs);

See qPrintable documentation, a macro delivering a const char * from QtGlobal.

Passing headers with axios POST request

Interceptors

I had the same issue and the reason was that I hadn't returned the response in the interceptor. Javascript thought, rightfully so, that I wanted to return undefined for the promise:

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

VIM Disable Automatic Newline At End Of File

I found this vimscript plugin is helpful for this situation.

Plugin 'vim-scripts/PreserveNoEOL'

Or read more at github

How do I make an http request using cookies on Android?

It turns out that Google Android ships with Apache HttpClient 4.0, and I was able to figure out how to do it using the "Form based logon" example in the HttpClient docs:

https://github.com/apache/httpcomponents-client/blob/master/httpclient5/src/test/java/org/apache/hc/client5/http/examples/ClientFormLogin.java


import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

/**
 * A example that demonstrates how HttpClient APIs can be used to perform
 * form-based logon.
 */
public class ClientFormLogin {

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

        DefaultHttpClient httpclient = new DefaultHttpClient();

        HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt");

        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println("Login form get: " + response.getStatusLine());
        if (entity != null) {
            entity.consumeContent();
        }
        System.out.println("Initial set of cookies:");
        List<Cookie> cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("- " + cookies.get(i).toString());
            }
        }

        HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" +
                "org=self_registered_users&" +
                "goto=/portal/dt&" +
                "gotoOnFail=/portal/dt?error=true");

        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("IDToken1", "username"));
        nvps.add(new BasicNameValuePair("IDToken2", "password"));

        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        response = httpclient.execute(httpost);
        entity = response.getEntity();

        System.out.println("Login form get: " + response.getStatusLine());
        if (entity != null) {
            entity.consumeContent();
        }

        System.out.println("Post logon cookies:");
        cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("- " + cookies.get(i).toString());
            }
        }

        // When HttpClient instance is no longer needed, 
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();        
    }
}

Meaning of "[: too many arguments" error from if [] (square brackets)

I have had same problem with my scripts. But when I did some modifications it worked for me. I did like this :-

export k=$(date "+%k");
if [ $k -ge 16 ] 
    then exit 0; 
else 
    echo "good job for nothing"; 
fi;

that way I resolved my problem. Hope that will help for you too.

error: use of deleted function

I encountered this error when inheriting from an abstract class and not implementing all of the pure virtual methods in my subclass.

What is a NullPointerException, and how do I fix it?

In Java all the variables you declare are actually "references" to the objects (or primitives) and not the objects themselves.

When you attempt to execute one object method, the reference asks the living object to execute that method. But if the reference is referencing NULL (nothing, zero, void, nada) then there is no way the method gets executed. Then the runtime let you know this by throwing a NullPointerException.

Your reference is "pointing" to null, thus "Null -> Pointer".

The object lives in the VM memory space and the only way to access it is using this references. Take this example:

public class Some {
    private int id;
    public int getId(){
        return this.id;
    }
    public setId( int newId ) {
        this.id = newId;
    }
}

And on another place in your code:

Some reference = new Some();    // Point to a new object of type Some()
Some otherReference = null;     // Initiallly this points to NULL

reference.setId( 1 );           // Execute setId method, now private var id is 1

System.out.println( reference.getId() ); // Prints 1 to the console

otherReference = reference      // Now they both point to the only object.

reference = null;               // "reference" now point to null.

// But "otherReference" still point to the "real" object so this print 1 too...
System.out.println( otherReference.getId() );

// Guess what will happen
System.out.println( reference.getId() ); // :S Throws NullPointerException because "reference" is pointing to NULL remember...

This an important thing to know - when there are no more references to an object (in the example above when reference and otherReference both point to null) then the object is "unreachable". There is no way we can work with it, so this object is ready to be garbage collected, and at some point, the VM will free the memory used by this object and will allocate another.

How do I add a custom script to my package.json file that runs a javascript file?

Steps are below:

  1. In package.json add:

    "bin":{
        "script1": "bin/script1.js" 
    }
    
  2. Create a bin folder in the project directory and add file runScript1.js with the code:

    #! /usr/bin/env node
    var shell = require("shelljs");
    shell.exec("node step1script.js");
    
  3. Run npm install shelljs in terminal

  4. Run npm link in terminal

  5. From terminal you can now run script1 which will run node script1.js

Reference: http://blog.npmjs.org/post/118810260230/building-a-simple-command-line-tool-with-npm

String method cannot be found in a main class method

It seem like your Resort method doesn't declare a compareTo method. This method typically belongs to the Comparable interface. Make sure your class implements it.

Additionally, the compareTo method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String argument, but rather a Resort.

Alternatively, you can compare the names of the resorts. For example

if (resortList[mid].getResortName().compareTo(resortName)>0)  

Can I stretch text using CSS?

I'll answer for horizontal stretching of text, since the vertical is the easy part - just use "transform: scaleY()"

_x000D_
_x000D_
.stretched-text {
  letter-spacing: 2px;
  display: inline-block;
  font-size: 32px;
  transform: scaleY(0.5);
  transform-origin: 0 0;
  margin-bottom: -50%;
}
span {
  font-size: 16px;
  vertical-align: top;
}
_x000D_
<span class="stretched-text">this is some stretched text</span>
<span>and this is some random<br />triple line <br />not stretched text</span>
_x000D_
_x000D_
_x000D_

letter-spacing just adds space between letters, stretches nothing, but it's kinda relative

inline-block because inline elements are too restrictive and the code below wouldn't work otherwise

Now the combination that makes the difference

font-size to get to the size we want - that way the text will really be of the length it's supposed to be and the text before and after it will appear next to it (scaleX is just for show, the browser still sees the element at its original size when positioning other elements).

scaleY to reduce the height of the text, so that it's the same as the text beside it.

transform-origin to make the text scale from the top of the line.

margin-bottom set to a negative value, so that the next line will not be far below - preferably percentage, so that we won't change the line-height property. vertical-align set to top, to prevent the text before or after from floating to other heights (since the stretched text has a real size of 32px)

-- The simple span element has a font-size, only as a reference.

The question asked for a way to prevent the boldness of the text caused by the stretch and I still haven't given one, BUT the font-weight property has more values than just normal and bold.

I know, you just can't see that, but if you search for the appropriate fonts, you can use the more values.

Loop through an array php

foreach($array as $item=>$values){
     echo $values->filepath;
    }

NSDate get year/month/day

As of iOS 8.0 (and OS X 10) you can use the component method to simplify getting a single date component like so:

int year = [[NSCalendar currentCalendar] component:NSCalendarUnitYear fromDate:[NSDate date]];

Should make things simpler and hopefully this is implemented efficiently.

How to select first and last TD in a row?

You can use the following snippet:

  tr td:first-child {text-decoration: underline;}
  tr td:last-child {color: red;}

Using the following pseudo classes:

:first-child means "select this element if it is the first child of its parent".

:last-child means "select this element if it is the last child of its parent".

Only element nodes (HTML tags) are affected, these pseudo-classes ignore text nodes.

Serializing list to JSON

You can use pure Python to do it:

import json
list = [1, 2, (3, 4)] # Note that the 3rd element is a tuple (3, 4)
json.dumps(list) # '[1, 2, [3, 4]]'

How to change indentation mode in Atom?

Adding @Manbroski answer here that worked for me:

try Ctrl-Shift-P Editor: Toggle Soft Tabs

how to sort order of LEFT JOIN in SQL query?

Several other answer give the solution using MAX. In some scenarios using an agregate function is either not possilbe, or not performant.

The alternative that I use a lot is to use a correlated sub-query in the join...

SELECT
   `userName`,
   `carPrice`
FROM `users`
LEFT JOIN `cars`
ON cars.id = (
  SELECT id FROM `cars` WHERE BelongsToUser = users.id ORDER BY carPrice DESC LIMIT 1
)
WHERE `id`='4'

iOS 7: UITableView shows under status bar

For anyone interested in replicating this, simply follow these steps:

  1. Create a new iOS project
  2. Open the main storyboard and delete the default/initial UIViewController
  3. Drag out a new UITableViewController from the Object Library
  4. Set it as the initial view controller
  5. Feed the table some test data

If you follow the above steps, when you run the app, you will see that nothing, including tweaking Xcode's checkboxes to "Extend Edges Under {Top, Bottom, Opaque} Bars" works to stop the first row from appearing under the status bar, nor can you address this programmatically.

E.g. In the above scenario, the following will have no effect:

// These do not work
self.edgesForExtendedLayout=UIRectEdgeNone;
self.extendedLayoutIncludesOpaqueBars=NO;
self.automaticallyAdjustsScrollViewInsets=NO;

This issue can be very frustrating, and I believe it is a bug on Apple's end, especially because it shows up in their own pre-wired UITableViewController from the object library.

I disagree with everyone who is trying to solve this by using any form of "Magic Numbers" e.g. "use a delta of 20px". This kind of tightly coupled programming is definitely not what Apple wants us to do here.

I have discovered two solutions to this problem:

  • Preserving the UITableViewController's scene:
    If you would like to keep the UITableViewController in the storyboard, without manually placing it into another view, you can embed the UITableViewController in a UINavigationController (Editor > Embed In > Navigation Controller) and uncheck "Shows Navigation Bar" in the inspector. This solves the issue with no extra tweaking needed, and it also preserves your UITableViewController's scene in the storyboard.

  • Using AutoLayout and embedding the UITableView into another view (I believe this is how Apple wants us to do this):
    Create an empty UIViewController and drag your UITableView in it. Then, Ctrl-drag from your UITableView towards the status bar. As the mouse gets to the bottom of the status bar, you will see an Autolayout bubble that says "Top Layout Guide". Release the mouse and choose "Vertical Spacing". That will tell the layout system to place it right below the status bar.

I have tested both ways on an empty application and they both work. You may need to do some extra tweaking to make them work for your project.

How to change the scrollbar color using css

You can use the following attributes for webkit, which reach into the shadow DOM:

::-webkit-scrollbar              { /* 1 */ }
::-webkit-scrollbar-button       { /* 2 */ }
::-webkit-scrollbar-track        { /* 3 */ }
::-webkit-scrollbar-track-piece  { /* 4 */ }
::-webkit-scrollbar-thumb        { /* 5 */ }
::-webkit-scrollbar-corner       { /* 6 */ }
::-webkit-resizer                { /* 7 */ }

Here's a working fiddle with a red scrollbar, based on code from this page explaining the issues.

http://jsfiddle.net/hmartiro/Xck2A/1/

Using this and your solution, you can handle all browsers except Firefox, which at this point I think still requires a javascript solution.

Understanding the basics of Git and GitHub

  1. What is the difference between Git and GitHub?

    Git is a version control system; think of it as a series of snapshots (commits) of your code. You see a path of these snapshots, in which order they where created. You can make branches to experiment and come back to snapshots you took.

    GitHub, is a web-page on which you can publish your Git repositories and collaborate with other people.

  2. Is Git saving every repository locally (in the user's machine) and in GitHub?

    No, it's only local. You can decide to push (publish) some branches on GitHub.

  3. Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?

    Yes, Git runs local if you don't use GitHub. An alternative to using GitHub could be running Git on files hosted on Dropbox, but GitHub is a more streamlined service as it was made especially for Git.

  4. How does Git compare to a backup system such as Time Machine?

    It's a different thing, Git lets you track changes and your development process. If you use Git with GitHub, it becomes effectively a backup. However usually you would not push all the time to GitHub, at which point you do not have a full backup if things go wrong. I use git in a folder that is synchronized with Dropbox.

  5. Is this a manual process, in other words if you don't commit you won't have a new version of the changes made?

    Yes, committing and pushing are both manual.

  6. If are not collaborating and you are already using a backup system why would you use Git?

    • If you encounter an error between commits you can use the command git diff to see the differences between the current code and the last working commit, helping you to locate your error.

    • You can also just go back to the last working commit.

    • If you want to try a change, but are not sure that it will work. You create a branch to test you code change. If it works fine, you merge it to the main branch. If it does not you just throw the branch away and go back to the main branch.

    • You did some debugging. Before you commit you always look at the changes from the last commit. You see your debug print statement that you forgot to delete.

Make sure you check gitimmersion.com.

Passing data between view controllers

Passing data back from ViewController 2 (destination) to viewController 1 (source) is the more interesting thing. Assuming you use storyBoard, these are all the ways I found out:

  • Delegate
  • Notification
  • User defaults
  • Singleton

Those were discussed here already.

I found there are more ways:

Using Block callbacks:

Use it in the prepareForSegue method in the VC1

NextViewController *destinationVC = (NextViewController *) segue.destinationViewController;
[destinationVC setDidFinishUsingBlockCallback:^(NextViewController *destinationVC)
{
    self.blockLabel.text = destination.blockTextField.text;
}];

Using storyboards Unwind (Exit)

Implement a method with a UIStoryboardSegue argument in VC 1,like this one:

-(IBAction)UnWindDone:(UIStoryboardSegue *)segue { }

In the storyBoard, hook the "return" button to the green Exit button (Unwind) of the vc. Now you have a segue that "goes back" so you can use the destinationViewController property in the prepareForSegue of VC2 and change any property of VC1 before it goes back.

  • Another option of using storyboards Undwind (Exit) - you can use the method you wrote in VC1

     -(IBAction)UnWindDone:(UIStoryboardSegue *)segue {
         NextViewController *nextViewController = segue.sourceViewController;
         self.unwindLabel.text = nextViewController.unwindPropertyPass;
     }
    

And in the prepareForSegue of VC1 you can change any property you want to share.

In both unwind options, you can set the tag property of the button and check it in the prepareForSegue.

Getting the parent div of element

The property pDoc.parentElement or pDoc.parentNode will get you the parent element.

Apache gives me 403 Access Forbidden when DocumentRoot points to two different drives

Somewhere, you need to tell Apache that people are allowed to see contents of this directory.

<Directory "F:/bar/public">
    Order Allow,Deny
    Allow from All
    # Any other directory-specific stuff
</Directory>

More info

Getting list of parameter names inside python function

locals() returns a dictionary with local names:

def func(a,b,c):
    print(locals().keys())

prints the list of parameters. If you use other local variables those will be included in this list. But you could make a copy at the beginning of your function.

index.php not loading by default

Same issue for me. My solution was that mod_dir was not enabled and apache2 was not issuing an error when reading the directive in my VirtualHost file:

DirectoryIndex index.html

Using the commands:

sudo a2enmod dir
sudo sudo service apache2 restart

Fixed the issue.

How to make div occupy remaining height?

With CSS tables, you could wrap a div around the two you have there and use this css/html structure:

<style type="text/css">
.container { display:table; width:100%; height:100%;  }
#div1 { display:table-row; height:50px; background-color:red; }
#div2 { display:table-row; background-color:blue; }
</style>

<div class="container">
    <div id="div1"></div>
    <div id="div2"></div>
</div>

Depends on what browsers support these display types, however. I don't think IE8 and below do. EDIT: Scratch that-- IE8 does support CSS tables.

Shortcut for creating single item list in C#

Use an extension method with method chaining.

public static List<T> WithItems(this List<T> list, params T[] items)
{
    list.AddRange(items);
    return list;
}

This would let you do this:

List<string> strings = new List<string>().WithItems("Yes");

or

List<string> strings = new List<string>().WithItems("Yes", "No", "Maybe So");

Update

You can now use list initializers:

var strings = new List<string> { "This", "That", "The Other" };

See http://msdn.microsoft.com/en-us/library/bb384062(v=vs.90).aspx

What are the Differences Between "php artisan dump-autoload" and "composer dump-autoload"?

Laravel's Autoload is a bit different:

1) It will in fact use Composer for some stuff

2) It will call Composer with the optimize flag

3) It will 'recompile' loads of files creating the huge bootstrap/compiled.php

4) And also will find all of your Workbench packages and composer dump-autoload them, one by one.

How do HashTables deal with collisions?

I've heard in my degree classes that a HashTable will place a new entry into the 'next available' bucket if the new Key entry collides with another.

This is actually not true, at least for the Oracle JDK (it is an implementation detail that could vary between different implementations of the API). Instead, each bucket contains a linked list of entries prior to Java 8, and a balanced tree in Java 8 or above.

then how would the HashTable still return the correct Value if this collision occurs when calling for one back with the collision key?

It uses the equals() to find the actually matching entry.

If I implement my own hashing function and use it as part of a look-up table (i.e. a HashMap or Dictionary), what strategies exist for dealing with collisions?

There are various collision handling strategies with different advantages and disadvantages. Wikipedia's entry on hash tables gives a good overview.

Using Html.ActionLink to call action on different controller

With that parameters you're triggering the wrong overloaded function/method.

What worked for me:

<%= Html.ActionLink("Details", "Details", "Product", new { id=item.ID }, null) %>

It fires HtmlHelper.ActionLink(string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes)

I'm using MVC 4.

Cheerio!

What is the regex pattern for datetime (2008-09-01 12:35:45 )?

$date = "2014-04-01 12:00:00";

preg_match('/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/',$date, $matches);

print_r($matches);

$matches will be:

Array ( 
   [0] => 2014-04-01 12:00:00 
   [1] => 2014 
   [2] => 04 
   [3] => 01 
   [4] => 12 
   [5] => 00 
   [6] => 00
)

An easy way to break up a datetime formated string.

ArrayAdapter in android to create simple listview

public ArrayAdapter (Context context, int resource, int textViewResourceId, T[] objects)

I am also new to Android , so i might be wrong. But as per my understanding while using this for listview creation 2nd argument is the layout of list items. A layout consists of many views (image view,text view etc). With 3rd argument you are specifying in which view or textview you want the text to be displayed.

How does one convert a HashMap to a List in Java?

If you only want it to iterate over your HashMap, no need for a list:

HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
for (String s : map.values()) {
    System.out.println(s);
}

Of course, if you want to modify your map structurally (i.e. more than only changing the value for an existing key) while iterating, then you better use the "copy to ArrayList" method, since otherwise you'll get a ConcurrentModificationException. Or export as an array:

HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
for (String s : map.values().toArray(new String[]{})) {
    System.out.println(s);
}

'Framework not found' in Xcode

1:- Delete the framework from the Xcode project. Quit the Xcode.

2:- Open your project in XCode and go to file under Menu and select Add files to "YourProjectName".

enter image description here

3:- Select "YourFramwork.framework" in the directory where you keep it.

4:- Click on the Copy items if needed checkbox.

5:- Click Add.

enter image description here

Make sure that you have the framework added in both Embedded Binaries and Linked Frameworks and Libraries under Target settings - General. As shown in the following images:-

enter image description here

enter image description here

Summarizing count and conditional aggregate functions on the same factor

Assuming that your original dataset is similar to the one you created (i.e. with NA as character. You could specify na.strings while reading the data using read.table. But, I guess NAs would be detected automatically.

The price column is factor which needs to be converted to numeric class. When you use as.numeric, all the non-numeric elements (i.e. "NA", FALSE) gets coerced to NA) with a warning.

library(dplyr)
df %>%
     mutate(price=as.numeric(as.character(price))) %>%  
     group_by(company, year, product) %>%
     summarise(total.count=n(), 
               count=sum(is.na(price)), 
               avg.price=mean(price,na.rm=TRUE),
               max.price=max(price, na.rm=TRUE))

data

I am using the same dataset (except the ... row) that was showed.

df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
 year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
 "Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
 "7.12", "12.99", "10.99", "NA",FALSE)))

Excel VBA: Copying multiple sheets into new workbook

This worked for me (I added an "if sheet visible" because in my case I wanted to skip hidden sheets)

   Sub Create_new_file()

Application.DisplayAlerts = False

Dim wb As Workbook
Dim wbNew As Workbook
Dim sh As Worksheet
Dim shNew As Worksheet
Dim pname, parea As String


Set wb = ThisWorkbook
Workbooks.Add
Set wbNew = ActiveWorkbook

For Each sh In wb.Worksheets

    pname = sh.Name


    If sh.Visible = True Then

    sh.Copy After:=wbNew.Sheets(Sheets.Count)

    wbNew.Sheets(Sheets.Count).Cells.ClearContents
    wbNew.Sheets(Sheets.Count).Cells.ClearFormats
    wb.Sheets(sh.Name).Activate
    Range(sh.PageSetup.PrintArea).Select
    Selection.Copy

    wbNew.Sheets(pname).Activate
    Range("A1").Select

    With Selection

        .PasteSpecial (xlValues)
        .PasteSpecial (xlFormats)
        .PasteSpecial (xlPasteColumnWidths)

    End With

    ActiveSheet.Name = pname

    End If


Next

wbNew.Sheets("Hoja1").Delete

Application.DisplayAlerts = True

End Sub

How do I align spans or divs horizontally?

My answer:

<style>
 #whatever div {
  display: inline;
  margin: 0 1em 0 1em;
  width: 30%;
}
</style>

<div id="whatever">
 <div>content</div>
 <div>content</div>
 <div>content</div>
</div>

Why?

Technically, a Span is an inline element, however it can have width, you just need to set their display property to block first. However, in this context, a div is probably more appropriate, as I'm guessing you want to fill these divs with content.

One thing you definitely don't want to do is have clear:both set on the divs. Setting it like that will mean that the browser will not allow any elements to sit on the same line as them. The result, your elements will stack up.

Note, the use of display:inline. This deals with the ie6 margin-doubling bug. You could tackle this in other ways if necessary, for example conditional stylesheets.

I've added a wrapper (#whatever) as I'm guessing these won't be the only elements on page, so you'll almost certainly need to segregate them from the other page elements.

Anyway, I hope that's helpful.

How do I count unique values inside a list

For ndarray there is a numpy method called unique:

np.unique(array_name)

Examples:

>>> np.unique([1, 1, 2, 2, 3, 3])
array([1, 2, 3])
>>> a = np.array([[1, 1], [2, 3]])
>>> np.unique(a)
array([1, 2, 3])

For a Series there is a function call value_counts():

Series_name.value_counts()

pull access denied repository does not exist or may require docker login

The message usually comes when you put the wrong image name. Please check your image if it exists on the Docker repository with the correct tag. It helped me.

docker run -d -p 80:80 --name ngnix ngnix:latest
Unable to find image 'ngnix:latest' locally
docker: Error response from daemon: pull access denied for ngnix, repository does not exist or may require 'docker login': denied: requested access to the resource is denied.
See 'docker run --help'.
$ docker run -d -p 80:80 --name nginx nginx:latest
Unable to find image 'nginx:latest' locally
latest: Pulling from library/nginx

Remove an item from a dictionary when its key is unknown

There is nothing wrong with deleting items from the dictionary while iterating, as you've proposed. Be careful about multiple threads using the same dictionary at the same time, which may result in a KeyError or other problems.

Of course, see the docs at http://docs.python.org/library/stdtypes.html#typesmapping

Resize background image in div using css

i would recommend using this:

  background-repeat:no-repeat;
  background-image: url(your file location here);
  background-size:cover;(will only work with css3)

hope it helps :D

And if this doesnt support your needs just say it: i can make a jquery for multibrowser support.

How can I show/hide a specific alert with twitter bootstrap?

You need to use an id selector:

 //show
 $('#passwordsNoMatchRegister').show();
 //hide
 $('#passwordsNoMatchRegister').hide();

# is an id selector and passwordsNoMatchRegister is the id of the div.

How to change the JDK for a Jenkins job?

Here is my experience with Jenkins version 1.636: as long as I have only one "Install automatically" JDK configured in Jenkins JDK section, I don't see "JDK" dropdown in Job=>Configure section, but as soon as I added second JDK in Jenkins config, JDK dropdown appeared in Job=>Configure section with 3 options [(System), JDK1, JDK2]

How to convert TimeStamp to Date in Java?

try to use this java code :

Timestamp stamp = new Timestamp(System.currentTimeMillis());
Date date = new Date(stamp.getTime());
DateFormat f = new SimpleDateFormat("yyyy-MM-dd");
DateFormat f1 = new SimpleDateFormat("yyyy/MM/dd");
String d = f.format(date);
String d1 = f1.format(date);
System.out.println(d);
System.out.println(d1);

Android EditText Max Length

EditText editText= ....;
InputFilter[] fa= new InputFilter[1];
fa[0] = new InputFilter.LengthFilter(8);
editText.setFilters(fa);

How to import a module given the full path?

Adding this to the list of answers as I couldn't find anything that worked. This will allow imports of compiled (pyd) python modules in 3.4:

import sys
import importlib.machinery

def load_module(name, filename):
    # If the Loader finds the module name in this list it will use
    # module_name.__file__ instead so we need to delete it here
    if name in sys.modules:
        del sys.modules[name]
    loader = importlib.machinery.ExtensionFileLoader(name, filename)
    module = loader.load_module()
    locals()[name] = module
    globals()[name] = module

load_module('something', r'C:\Path\To\something.pyd')
something.do_something()

How to SELECT a dropdown list item by value programmatically

Please try below:

myDropDown.SelectedIndex = 
myDropDown.Items.IndexOf(myDropDown.Items.FindByValue("myValue"))

Gradle version 2.2 is required. Current version is 2.10

Just Change in build.gradle file

 classpath 'com.android.tools.build:gradle:1.3.0'

To

 classpath 'com.android.tools.build:gradle:2.0.0'
  1. Now GoTo -> menu choose File -> Invalidate Caches/Restart...

  2. Choose first option: Invalidate and Restart

    Android Studio would restart.

    After this, it should work normally.

File.separator vs FileSystem.getSeparator() vs System.getProperty("file.separator")?

System.getProperties() can be overridden by calls to System.setProperty(String key, String value) or with command line parameters -Dfile.separator=/

File.separator gets the separator for the default filesystem.

FileSystems.getDefault() gets you the default filesystem.

FileSystem.getSeparator() gets you the separator character for the filesystem. Note that as an instance method you can use this to pass different filesystems to your code other than the default, in cases where you need your code to operate on multiple filesystems in the one JVM.

Connect to SQL Server Database from PowerShell

I did remove integrated security ... my goal is to log onto a sql server using a connection string WITH active directory username / password. When I do that it always fails. Does not matter the format ... sam company\user ... upn [email protected] ... basic username.

Radio Buttons ng-checked with ng-model

I think you should only use ng-model and should work well for you, here is the link to the official documentation of angular https://docs.angularjs.org/api/ng/input/input%5Bradio%5D

The code from the example should not be difficult to adapt to your specific situation:

<script>
   function Ctrl($scope) {
      $scope.color = 'blue';
      $scope.specialValue = {
         "id": "12345",
         "value": "green"
      };
   }
</script>
<form name="myForm" ng-controller="Ctrl">
   <input type="radio" ng-model="color" value="red">  Red <br/>
   <input type="radio" ng-model="color" ng-value="specialValue"> Green <br/>
   <input type="radio" ng-model="color" value="blue"> Blue <br/>
   <tt>color = {{color | json}}</tt><br/>
</form>

How do I convert a Swift Array to a String?

In Swift 2.2 you may have to cast your array to NSArray to use componentsJoinedByString(",")

let stringWithCommas = (yourArray as NSArray).componentsJoinedByString(",")

Can I have H2 autocreate a schema in an in-memory database?

Yes, H2 supports executing SQL statements when connecting. You could run a script, or just a statement or two:

String url = "jdbc:h2:mem:test;" + 
             "INIT=CREATE SCHEMA IF NOT EXISTS TEST"
String url = "jdbc:h2:mem:test;" + 
             "INIT=CREATE SCHEMA IF NOT EXISTS TEST\\;" + 
                  "SET SCHEMA TEST";
String url = "jdbc:h2:mem;" + 
             "INIT=RUNSCRIPT FROM '~/create.sql'\\;" + 
                  "RUNSCRIPT FROM '~/populate.sql'";

Please note the double backslash (\\) is only required within Java. The backslash(es) before ; within the INIT is required.

How do I add python3 kernel to jupyter (IPython)

Make sure you have ipykernel installed and use ipython kernel install to drop the kernelspec in the right location for python2. Then ipython3 kernel install for Python3. Now you should be able to chose between the 2 kernels regardless of whether you use jupyter notebook, ipython notebook or ipython3 notebook (the later two are deprecated).

Note that if you want to install for a specific Python executable you can use the following trick:

path/to/python -m ipykernel install <options>

This works when using environments (venv,conda,...) and the <options> let you name your kernel (see --help). So you can do

conda create -n py36-test python=3.6
source activate py36-test
python -m ipykernel install --name py36-test
source deactivate

And now you get a kernel named py36-test in your dropdown menus, along the other ones.

See Using both Python 2.x and Python 3.x in IPython Notebook which has more recent information.

Python function to convert seconds into minutes, hours, and days

This will convert n seconds into d days, h hours, m minutes, and s seconds.

from datetime import datetime, timedelta

def GetTime():
    sec = timedelta(seconds=int(input('Enter the number of seconds: ')))
    d = datetime(1,1,1) + sec

    print("DAYS:HOURS:MIN:SEC")
    print("%d:%d:%d:%d" % (d.day-1, d.hour, d.minute, d.second))

How to initialize const member variable in a class?

If you don't want to make the const data member in class static, You can initialize the const data member using the constructor of the class. For example:

class Example{
      const int x;
    public:
      Example(int n);
};

Example::Example(int n):x(n){
}

if there are multiple const data members in class you can use the following syntax to initialize the members:

Example::Example(int n, int z):x(n),someOtherConstVariable(z){}

Excel - extracting data based on another list

I couldn't get the first method to work, and I know this is an old topic, but this is what I ended up doing for a solution:

=IF(ISNA(MATCH(A1,B:B,0)),"Not Matched", A1)

Basically, MATCH A1 to Column B exactly (the 0 stands for match exactly to a value in Column B). ISNA tests for #N/A response which match will return if the no match is found. Finally, if ISNA is true, write "Not Matched" to the selected cell, otherwise write the contents of the matched cell.

Converting string to byte array in C#

var result = System.Text.Encoding.Unicode.GetBytes(text);

MSOnline can't be imported on PowerShell (Connect-MsolService error)

I'm using a newer version of the SPO Management Shell. For me to get the error to go away, I changed my Import-Module statement to use:

Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking;

I also use the newer command:

Connect-SPOService

UIButton: how to center an image and a text using imageEdgeInsets and titleEdgeInsets?

Updated for Xcode 11+

The insets described in my original answer have been moved to the size inspector in more recent versions of Xcode. I am not 100% clear on when the switch happened but readers should review the size inspector if the inset information is not found in the attributes inspector. Below is a sample of the new inset screen (located at the top of size attributes inspector as of 11.5).

insets_moved_to_size_inspector

Original Answer

Nothing wrong with the other answers, however I just wanted to note that the same behavior can be accomplished visually within Xcode using zero lines of code. This solution is useful if you do not need a calculated value or are building with a storyboard/xib (otherwise other solutions apply).

Note - I do understand that the OP's question is one requiring code. I am just providing this answer for completeness and as a logical alternative for those using storyboards/xibs.

To modify spacing on image, title, and content views of a button using edge insets you can select the button/control and open the attributes inspector. Scroll down towards the middle of the inspector and find the section for Edge insets.

edge-insets

One can also access and modify the specific edge insets for the title, image or content view .

menu-options

Sorting an array of objects by property values

For a normal array of elements values only:

function sortArrayOfElements(arrayToSort) {
    function compareElements(a, b) {
        if (a < b)
            return -1;
        if (a > b)
            return 1;
        return 0;
    }

    return arrayToSort.sort(compareElements);
}

e.g. 1:
var array1 = [1,2,545,676,64,2,24]
output : [1, 2, 2, 24, 64, 545, 676]

var array2 = ["v","a",545,676,64,2,"24"]
output: ["a", "v", 2, "24", 64, 545, 676]

For an array of objects:

function sortArrayOfObjects(arrayToSort, key) {
    function compareObjects(a, b) {
        if (a[key] < b[key])
            return -1;
        if (a[key] > b[key])
            return 1;
        return 0;
    }

    return arrayToSort.sort(compareObjects);
}

e.g. 1: var array1= [{"name": "User4", "value": 4},{"name": "User3", "value": 3},{"name": "User2", "value": 2}]

output : [{"name": "User2", "value": 2},{"name": "User3", "value": 3},{"name": "User4", "value": 4}]

MySQL said: Documentation #1045 - Access denied for user 'root'@'localhost' (using password: NO)

Here's the solution to getting the 1045 Access denied for user 'root'@'localhost' (using password: NO) in phpMyAdmin.

First here's what happens:

The problem occurs when you change over from using phpMyAdmin with no password and mysql with no root password. You change root in mysql to having a root password. You dutifully change phpMyAdmin's config.ini.php file's $cfg['Servers'][$i]['password']='' line to include your password and restart everything you can find, but phpMyAdmin still can't get through.

The reason is that your browser still contains cookies for phpMyAdmin and those cookies reflect not needing a password to access mysql.

The solution:

Clear out the cookies relating to phpMyAdmin. Its browser specific, but in my Firefox, its under Tools > Page Info > Cookies.

You might need to relog in with phpMyAdmin or use the signon.php script (under /examples in my WAMP install).

Firebase FCM force onTokenRefresh() to be called

Guys it has very simple solution

https://developers.google.com/instance-id/guides/android-implementation#generate_a_token

Note: If your app used tokens that were deleted by deleteInstanceID, your app will need to generate replacement tokens.

In stead of deleting instance Id, delete only token:

String authorizedEntity = PROJECT_ID;
String scope = "GCM";
InstanceID.getInstance(context).deleteToken(authorizedEntity,scope);

$http get parameters does not work

From $http.get docs, the second parameter is a configuration object:

get(url, [config]);

Shortcut method to perform GET request.

You may change your code to:

$http.get('accept.php', {
    params: {
        source: link, 
        category_id: category
    }
});

Or:

$http({
    url: 'accept.php', 
    method: 'GET',
    params: { 
        source: link, 
        category_id: category
    }
});

As a side note, since Angular 1.6: .success should not be used anymore, use .then instead:

$http.get('/url', config).then(successCallback, errorCallback);

Run script with rc.local: script works, but not at boot

On some linux's (Centos & RH, e.g.), /etc/rc.local is initially just a symbolic link to /etc/rc.d/rc.local. On those systems, if the symbolic link is broken, and /etc/rc.local is a separate file, then changes to /etc/rc.local won't get seen at bootup -- the boot process will run the version in /etc/rc.d. (They'll work if one runs /etc/rc.local manually, but won't be run at bootup.)

Sounds like on dimadima's system, they are separate files, but /etc/rc.d/rc.local calls /etc/rc.local

The symbolic link from /etc/rc.local to the 'real' one in /etc/rc.d can get lost if one moves rc.local to a backup directory and copies it back or creates it from scratch, not realizing the original one in /etc was just a symbolic link.

How do I jump to a closing bracket in Visual Studio Code?

Mac Cmd+Shift+\

  • Mac with french keyboard : Ctrl+Cmd+Option+Shift+L

Windows Ctrl+Shift+\

  • Windows with spanish keyboard Ctrl+Shift+|

  • Windows with german keyboard Ctrl+Shift+^


Alternatively, you can do:

Ctrl+Shift+p

And select

Preferences: Open Keyboard Shortcuts

There you will be able to see all the shortcuts, and create your own.

ALTER TABLE on dependent column

you can drop the Constraint which is restricting you. If the column has access to other table. suppose a view is accessing the column which you are altering then it wont let you alter the column unless you drop the view. and after making changes you can recreate the view.

enter image description here

New to unit testing, how to write great tests?

Unit testing is about the output you get from a function/method/application. It does not matter at all how the result is produced, it just matters that it is correct. Therefore, your approach of counting calls to inner methods and such is wrong. What I tend to do is sit down and write what a method should return given certain input values or a certain environment, then write a test which compares the actual value returned with what I came up with.

SQL Server - stop or break execution of a SQL script

I would not use RAISERROR- SQL has IF statements that can be used for this purpose. Do your validation and lookups and set local variables, then use the value of the variables in IF statements to make the inserts conditional.

You wouldn't need to check a variable result of every validation test. You could usually do this with only one flag variable to confirm all conditions passed:

declare @valid bit

set @valid = 1

if -- Condition(s)
begin
  print 'Condition(s) failed.'
  set @valid = 0
end

-- Additional validation with similar structure

-- Final check that validation passed
if @valid = 1
begin
  print 'Validation succeeded.'

  -- Do work
end

Even if your validation is more complex, you should only need a few flag variables to include in your final check(s).

Use getElementById on HTMLElement instead of HTMLDocument

I would use XMLHTTP request to retrieve page content as much faster. Then it is easy enough to use querySelectorAll to apply a CSS class selector to grab by class name. Then you access the child elements by tag name and index.

Option Explicit
Public Sub GetInfo()
    Dim sResponse As String, html As HTMLDocument, elements As Object, i As Long

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "https://www.hsbc.com/about-hsbc/leadership", False
        .setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
        .send
        sResponse = StrConv(.responseBody, vbUnicode)
    End With
    Set html = New HTMLDocument
    With html
        .body.innerHTML = sResponse
        Set elements = .querySelectorAll(".profile-col1")
        For i = 0 To elements.Length - 1
            Debug.Print String(20, Chr$(61))
            Debug.Print elements.item(i).getElementsByTagName("a")(0).innerText
            Debug.Print elements.item(i).getElementsByTagName("p")(0).innerText
            Debug.Print elements.item(i).getElementsByTagName("p")(1).innerText
        Next
    End With
End Sub

References:

VBE > Tools > References > Microsoft HTML Object Library

NLS_NUMERIC_CHARACTERS setting for decimal

You can see your current session settings by querying nls_session_parameters:

select value
from nls_session_parameters
where parameter = 'NLS_NUMERIC_CHARACTERS';

VALUE                                  
----------------------------------------
.,                                       

That may differ from the database defaults, which you can see in nls_database_parameters.

In this session your query errors:

select to_number('100,12') from dual;

Error report -
SQL Error: ORA-01722: invalid number
01722. 00000 -  "invalid number"

I could alter my session, either directly with alter session or by ensuring my client is configured in a way that leads to the setting the string needs (it may be inherited from a operating system or Java locale, for example):

alter session set NLS_NUMERIC_CHARACTERS = ',.';
select to_number('100,12') from dual;

TO_NUMBER('100,12')
-------------------
             100,12 

In SQL Developer you can set your preferred value in Tool->Preferences->Database->NLS.

But I can also override that session setting as part of the query, with the optional third nlsparam parameter to to_number(); though that makes the optional second fmt parameter necessary as well, so you'd need to be able pick a suitable format:

alter session set NLS_NUMERIC_CHARACTERS = '.,';
select to_number('100,12', '99999D99', 'NLS_NUMERIC_CHARACTERS='',.''')
from dual;

TO_NUMBER('100,12','99999D99','NLS_NUMERIC_CHARACTERS='',.''')
--------------------------------------------------------------
                                                        100.12 

By default the result is still displayed with my session settings, so the decimal separator is still a period.

HTML5 live streaming

It is not possible to use the RTMP protocol in HTML 5, because the RTMP protocol is only used between the server and the flash player. So you can use the other streaming protocols for viewing the streaming videos in HTML 5.

wget/curl large file from google drive

Here's a quick way to do this.

Make sure the link is shared, and it will look something like this:

https://drive.google.com/open?id=FILEID&authuser=0

Then, copy that FILEID and use it like this

wget --no-check-certificate 'https://docs.google.com/uc?export=download&id=FILEID' -O FILENAME

How to get the last char of a string in PHP?

I can't leave comments, but in regard to FastTrack's answer, also remember that the line ending may be only single character. I would suggest

substr(trim($string), -1)

EDIT: My code below was edited by someone, making it not do what I indicated. I have restored my original code and changed the wording to make it more clear.

trim (or rtrim) will remove all whitespace, so if you do need to check for a space, tab, or other whitespace, manually replace the various line endings first:

$order = array("\r\n", "\n", "\r");
$string = str_replace($order, '', $string);
$lastchar = substr($string, -1);

How to load/edit/run/save text files (.py) into an IPython notebook cell?

I have not found a satisfying answer for this question, i.e how to load edit, run and save. Overwriting either using %%writefile or %save -f doesn't work well if you want to show incremental changes in git. It would look like you delete all the lines in filename.py and add all new lines, even though you just edit 1 line.

How to get the selected value from drop down list in jsp?

use jquery

$("#item").change(function({
    var x=$(this).val();
});

Your value will be in x variable, use this variable value in your jsp, like this {x} this statement will give the value

How do you attach and detach from Docker's process?

If you only need the docker process to go in the background you can use

Ctrl + Z

Be aware that it is not a real detach and it comes with a performance penalty. (You can return it to foreground with the bg command).

Another option is to just close your terminal, if you don't need it any longer.

ValueError: unsupported pickle protocol: 3, python2 pickle can not load the file dumped by python 3 pickle?

You should write the pickled data with a lower protocol number in Python 3. Python 3 introduced a new protocol with the number 3 (and uses it as default), so switch back to a value of 2 which can be read by Python 2.

Check the protocolparameter in pickle.dump. Your resulting code will look like this.

pickle.dump(your_object, your_file, protocol=2)

There is no protocolparameter in pickle.load because pickle can determine the protocol from the file.

Python: Checking if a 'Dictionary' is empty doesn't seem to work

Here are three ways you can check if dict is empty. I prefer using the first way only though. The other two ways are way too wordy.

test_dict = {}

if not test_dict:
    print "Dict is Empty"


if not bool(test_dict):
    print "Dict is Empty"


if len(test_dict) == 0:
    print "Dict is Empty"

How do I create a datetime in Python from milliseconds?

Converting millis to datetime (UTC):

import datetime
time_in_millis = 1596542285000
dt = datetime.datetime.fromtimestamp(time_in_millis / 1000.0, tz=datetime.timezone.utc)

Converting datetime to string following the RFC3339 standard (used by Open API specification):

from rfc3339 import rfc3339
converted_to_str = rfc3339(dt, utc=True, use_system_timezone=False)
# 2020-08-04T11:58:05Z

How to find the number of days between two dates

DATEDIFF(d, 'Start Date', 'End Date')

do it

Generate random password string with requirements in javascript

Any password generated with Math.random() is EXTREMELY BAD.

This function uses the system time as a seed for the random number generator. Anyone who knows the time the password was generated can easily brute-force the password.

In almost all cases, this data is easily available - just take the registration_time column in a hacked database, and test out all the values generated by the Math.random() algorithm using the times from 15 to 0 minutes before.

A password generated with Math.random() is completely worthless because the time the password was first used is enough for cracking it.

How to sort an array in Bash

I am not convinced that you'll need an external sorting program in Bash.

Here is my implementation for the simple bubble-sort algorithm.

function bubble_sort()
{   #
    # Sorts all positional arguments and echoes them back.
    #
    # Bubble sorting lets the heaviest (longest) element sink to the bottom.
    #
    local array=($@) max=$(($# - 1))
    while ((max > 0))
    do
        local i=0
        while ((i < max))
        do
            if [ ${array[$i]} \> ${array[$((i + 1))]} ]
            then
                local t=${array[$i]}
                array[$i]=${array[$((i + 1))]}
                array[$((i + 1))]=$t
            fi
            ((i += 1))
        done
        ((max -= 1))
    done
    echo ${array[@]}
}

array=(a c b f 3 5)
echo " input: ${array[@]}"
echo "output: $(bubble_sort ${array[@]})"

This shall print:

 input: a c b f 3 5
output: 3 5 a b c f

Spring MVC - Why not able to use @RequestBody and @RequestParam together

The @RequestBody javadoc states

Annotation indicating a method parameter should be bound to the body of the web request.

It uses registered instances of HttpMessageConverter to deserialize the request body into an object of the annotated parameter type.

And the @RequestParam javadoc states

Annotation which indicates that a method parameter should be bound to a web request parameter.

  1. Spring binds the body of the request to the parameter annotated with @RequestBody.

  2. Spring binds request parameters from the request body (url-encoded parameters) to your method parameter. Spring will use the name of the parameter, ie. name, to map the parameter.

  3. Parameters are resolved in order. The @RequestBody is processed first. Spring will consume all the HttpServletRequest InputStream. When it then tries to resolve the @RequestParam, which is by default required, there is no request parameter in the query string or what remains of the request body, ie. nothing. So it fails with 400 because the request can't be correctly handled by the handler method.

  4. The handler for @RequestParam acts first, reading what it can of the HttpServletRequest InputStream to map the request parameter, ie. the whole query string/url-encoded parameters. It does so and gets the value abc mapped to the parameter name. When the handler for @RequestBody runs, there's nothing left in the request body, so the argument used is the empty string.

  5. The handler for @RequestBody reads the body and binds it to the parameter. The handler for @RequestParam can then get the request parameter from the URL query string.

  6. The handler for @RequestParam reads from both the body and the URL query String. It would usually put them in a Map, but since the parameter is of type String, Spring will serialize the Map as comma separated values. The handler for @RequestBody then, again, has nothing left to read from the body.

Check if cookie exists else set cookie to Expire in 10 days

You need to read and write document.cookie

if (document.cookie.indexOf("visited=") >= 0) {
  // They've been here before.
  alert("hello again");
}
else {
  // set a new cookie
  expiry = new Date();
  expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes

  // Date()'s toGMTSting() method will format the date correctly for a cookie
  document.cookie = "visited=yes; expires=" + expiry.toGMTString();
  alert("this is your first time");
}