Programs & Examples On #Hard coding

What does "hard coded" mean?

"hard coding" means putting something into your source code. If you are not hard coding, then you do something like prompting the user for the data, or allow the user to put the data on the command line, or something like that.

So, to hard code the location of the file as being on the C: drive, you would just put the pathname of the file all together in your source code.

Here is an example.

int main()
{
    const char *filename = "C:\\myfile.txt";

    printf("Filename is: %s\n", filename);
}

The file name is "hard coded" as: C:\myfile.txt

The reason the backslash is doubled is because backslashes are special in C strings.

How to re import an updated package while in Python Interpreter?

See here for a good explanation of how your dependent modules won't be reloaded and the effects that can have:

http://pyunit.sourceforge.net/notes/reloading.html

The way pyunit solved it was to track dependent modules by overriding __import__ then to delete each of them from sys.modules and re-import. They probably could've just reload'ed them, though.

Using GPU from a docker container?

I would not recommend installing CUDA/cuDNN on the host if you can use docker. Since at least CUDA 8 it has been possible to "stand on the shoulders of giants" and use nvidia/cuda base images maintained by NVIDIA in their Docker Hub repo. Go for the newest and biggest one (with cuDNN if doing deep learning) if unsure which version to choose.

A starter CUDA container:

mkdir ~/cuda11
cd ~/cuda11

echo "FROM nvidia/cuda:11.0-cudnn8-devel-ubuntu18.04" > Dockerfile
echo "CMD [\"/bin/bash\"]" >> Dockerfile

docker build --tag mirekphd/cuda11 .

docker run --rm -it --gpus 1 mirekphd/cuda11 nvidia-smi

Sample output:

(if nvidia-smi is not found in the container, do not try install it there - it was already installed on thehost with NVIDIA GPU driver and should be made available from the host to the container system if docker has access to the GPU(s)):

+-----------------------------------------------------------------------------+
| NVIDIA-SMI 450.57       Driver Version: 450.57       CUDA Version: 11.0     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  GeForce GTX 108...  Off  | 00000000:01:00.0  On |                  N/A |
|  0%   50C    P8    17W / 280W |    409MiB / 11177MiB |      7%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+

Prerequisites

  1. Appropriate NVIDIA driver with the latest CUDA version support to be installed first on the host (download it from NVIDIA Driver Downloads and then mv driver-file.run driver-file.sh && chmod +x driver-file.sh && ./driver-file.sh). These are have been forward-compatible since CUDA 10.1.

  2. GPU access enabled in docker by installing sudo apt get update && sudo apt get install nvidia-container-toolkit (and then restarting docker daemon using sudo systemctl restart docker).

Fastest way to serialize and deserialize .NET objects

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

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

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

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

Modified Code

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Can I convert a C# string value to an escaped string literal

If JSON conventions are enough for the unescaped strings you want to get escaped and you already use Newtonsoft.Jsonin your project (it has a pretty large overhead) you may use this package like the following:

using System;
using Newtonsoft.Json;

public class Program
{
    public static void Main()
    {
    Console.WriteLine(ToLiteral( @"abc\n123") );
    }

    private static string ToLiteral(string input){
        return JsonConvert.DeserializeObject<string>("\"" + input + "\"");
    }
}

WampServer: php-win.exe The program can't start because MSVCR110.dll is missing

As far as I am aware, the MSVCRxxx.dlls are in %SystemRoot%\System32 (usually C:\Windows\System32).

The xxx refers to the version of the MS Visual C Runtime (hence MSVCR...)

However, the complication seems to be that the xxx version is not the same as the two digits of the year "version".

For example, Visual C Runtime 2013 yields MSVCR120.dll and "...Runtime 2012" yields MSVCR110.dll. And then Microsoft packages these as vcredist_x86.exe or vcredist_x64.exe, seemingly irrespective of the xxx version or the Visual Studio version number (2012, 2013 etc) - confused? You have every right to be!

So, firstly, you need to determine whether you need 32 bit, 64 bit or even both (some PHP distributions apparently do need both), then download the relevant vcredist... for the bits AND for the Visual Studio version. As far as I can tell, the only way to tell which vcredist... you have is to start to install it. Recent versions give an intro screen that quotes the Visual Studio version and the xxx version. I have renamed by vcredists to something like vcredist_x64_2012_V11.exe.

[EDIT] Forgot to add earlier that if you are simply looking to "install" the missing DLL (as opposed to resolve some bigger set of issues), then you probably won't do any harm by simply installing the relevant vcredist for your architecture (32 bit, 64 bit) and "missing" version.

How to push object into an array using AngularJS

A couple of answers that should work above but this is how i would write it.

Also, i wouldn't declare controllers inside templates. It's better to declare them on your routes imo.

add-text.tpl.html

<div ng-controller="myController">
    <form ng-submit="addText(myText)">
        <input type="text" placeholder="Let's Go" ng-model="myText">
        <button type="submit">Add</button>
    </form>
    <ul>
        <li ng-repeat="text in arrayText">{{ text }}</li>
    </ul>
</div>

app.js

(function() {

    function myController($scope) {
        $scope.arrayText = ['hello', 'world'];
        $scope.addText = function(myText) {
             $scope.arrayText.push(myText);     
        };
    }

    angular.module('app', [])
        .controller('myController', myController);

})();

Can I hide/show asp:Menu items based on role?

To remove a MenuItem from an ASP.net NavigationMenu by Value:

public static void RemoveMenuItemByValue(MenuItemCollection items, String value)
{
   MenuItem itemToRemove = null;

   //Breadth first, look in the collection
   foreach (MenuItem item in items)
   {
      if (item.Value == value)
      {
          itemToRemove = item;
          break;
      }
   }

   if (itemToRemove != null)
   {
      items.Remove(itemToRemove);
      return;
   }


   //Search children
   foreach (MenuItem item in items)
   {
       RemoveMenuItemByValue(item.ChildItems, value);
   }
}

and helper extension:

public static RemoveMenuItemByValue(this NavigationMenu menu, String value)
{
   RemoveMenuItemByValue(menu.Items, value);
}

and sample usage:

navigationMenu.RemoveMenuItemByValue("UnitTests");

Note: Any code is released into the public domain. No attribution required.

Laravel: Validation unique on update

One simple solution.

In your Model

protected $rules = [
    'email_address' => 'sometimes|required|email|unique:users',
    ..
];

In your Controller, action:update

...
$rules = User::$rules;
$rules['email_address'] = $rules['email_address'] . ',id,' . $id;
$validationCertificate  = Validator::make($input, $rules); 

Count number of times a date occurs and make a graph out of it

The simplest is to do a PivotChart. Select your array of dates (with a header) and create a new Pivot Chart (Insert / PivotChart / Ok) Then on the field list window, drag and drop the date column in the Axis list first and then in the value list first.

Step 1:

Step1

Step 2:

Step2

Can I stretch text using CSS?

The only way I can think of for short texts like "MENU" is to put every single letter in a span and justify them in a container afterwards. Like this:

<div class="menu-burger">
  <span></span>
  <span></span>
  <span></span>
  <div>
    <span>M</span>
    <span>E</span>
    <span>N</span>
    <span>U</span>
  </div>
</div>

And then the CSS:

.menu-burger {
  width: 50px;
  height: 50px;
  padding: 5px;
}

...

.menu-burger > div {
  display: flex;
  justify-content: space-between;
}

How do you use MySQL's source command to import large files in windows

C:\xampp\mysql\bin\mysql -u root -p testdatabase < C:\Users\Juan\Desktop\databasebackup.sql

That worked for me to import 400MB file into my database.

No Activity found to handle Intent : android.intent.action.VIEW

First try this code inside AndroidManifest

  <application>
       
    <uses-library
        android:name="org.apache.http.legacy"
        android:required="false" />
 </application>

If this code works, so fine. But if not. Try this code from which class you want to pass the data or uri.

Intent window = new Intent(getApplicationContext(), Browser.class);
window.putExtra("LINK", "http://www.yourwebsite.com");
startActivity(window);

Error "The input device is not a TTY"

Using docker-compose exec -T fixed the problem for me via Jenkins

docker-compose exec -T containerName php script.php

release Selenium chromedriver.exe from memory

I am using Protractor with directConnect. Disabling the "--no-sandbox" option fixed the issue for me.

// Capabilities to be passed to the webdriver instance.
capabilities: {
  'directConnect': true,
  'browserName': 'chrome',
  chromeOptions: {
      args: [
        //"--headless",
        //"--hide-scrollbars",
        "--disable-software-rasterizer",
        '--disable-dev-shm-usage',
        //"--no-sandbox",
        "incognito",
        "--disable-gpu",
        "--window-size=1920x1080"]
  }
},

mailto link with HTML body

Thunderbird supports html-body: mailto:[email protected]?subject=Me&html-body=<b>ME</b>

git add, commit and push commands in one?

Add in ~/.bash_profile for adding, committing and pushing with one command put:

function g() { git commit -a -m "$*"; git push; }

Usage:

g your commit message
g your commit message 'message'

No quotes are needed although you can't use semicolons or parenthesis in your commit messages (single quotes are allowed). If you want to any of these just simply put double quotes in you message, e.g.:

g "your commit message; (message)"

To create a comment in your message do:

g "your commit message:
> your note"

There's also a function for adding and committing in a similar way:

function c() { git add --all; git commit -m "$*"; }

Works exactly the same way that g function and has the same constraints. Just put c instead. E.g.

c your commit message

You can also add an alias for pushing to the remote:

alias p='git push'

Usage:

p

That amounts into 2 letters, c and p you use while working with your git repository. Or you can use g instead to do it all with only one letter.

Full list of aliases and functions: https://gist.github.com/matt360/0c5765d6f0579a5aa74641bc47ae50ac

How can I detect if this dictionary key exists in C#?

Here is a little something I cooked up today. Seems to work for me. Basically you override the Add method in your base namespace to do a check and then call the base's Add method in order to actually add it. Hope this works for you

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

namespace Main
{
    internal partial class Dictionary<TKey, TValue> : System.Collections.Generic.Dictionary<TKey, TValue>
    {
        internal new virtual void Add(TKey key, TValue value)
        {   
            if (!base.ContainsKey(key))
            {
                base.Add(key, value);
            }
        }
    }

    internal partial class List<T> : System.Collections.Generic.List<T>
    {
        internal new virtual void Add(T item)
        {
            if (!base.Contains(item))
            {
                base.Add(item);
            }
        }
    }

    public class Program
    {
        public static void Main()
        {
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(1,"b");
            dic.Add(1,"a");
            dic.Add(2,"c");
            dic.Add(1, "b");
            dic.Add(1, "a");
            dic.Add(2, "c");

            string val = "";
            dic.TryGetValue(1, out val);

            Console.WriteLine(val);
            Console.WriteLine(dic.Count.ToString());


            List<string> lst = new List<string>();
            lst.Add("b");
            lst.Add("a");
            lst.Add("c");
            lst.Add("b");
            lst.Add("a");
            lst.Add("c");

            Console.WriteLine(lst[2]);
            Console.WriteLine(lst.Count.ToString());
        }
    }
}

Common HTTPclient and proxy

If your software uses a ProxySelector (for example for using a PAC-script instead of a static host/port) and your HTTPComponents is version 4.3 or above then you can use your ProxySelector for your HttpClient like this:

ProxySelector myProxySelector = ...;
HttpClient myHttpClient = HttpClientBuilder.create().setRoutePlanner(new SystemDefaultRoutePlanner(myProxySelector))).build();

And then do your requests as usual:

HttpGet myRequest = new HttpGet("/");
myHttpClient.execute(myRequest);

Core dump file analysis

Steps to debug coredump using GDB:

Some generic help:

gdb start GDB, with no debugging les

gdb program begin debugging program

gdb program core debug coredump core produced by program

gdb --help describe command line options

  1. First of all, find the directory where the corefile is generated.

  2. Then use ls -ltr command in the directory to find the latest generated corefile.

  3. To load the corefile use

    gdb binary path of corefile
    

    This will load the corefile.

  4. Then you can get the information using the bt command.

    For a detailed backtrace use bt full.

  5. To print the variables, use print variable-name or p variable-name

  6. To get any help on GDB, use the help option or use apropos search-topic

  7. Use frame frame-number to go to the desired frame number.

  8. Use up n and down n commands to select frame n frames up and select frame n frames down respectively.

  9. To stop GDB, use quit or q.

Go back button in a page

You can either use:

<button onclick="window.history.back()">Back</button>

or..

<button onclick="window.history.go(-1)">Back</button>

The difference, of course, is back() only goes back 1 page but go() goes back/forward the number of pages you pass as a parameter, relative to your current page.

Windows Task Scheduler doesn't start batch file task

Try the code below:

Batchfile.bat:

cd c:\batchfilepath
net stop "SQL Server Reporting Services (MSSQLSERVER)" 
timeout /t 10
net start "SQL Server Reporting Services (MSSQLSERVER)"

How to set the height and the width of a textfield in Java?

     f.setLayout(null);

add the above lines ( f is a JFrame or a Container where you have added the JTestField )

But try to learn 'LayoutManager' in java ; refer to other answers for the links of the tutorials .Or try This http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

Eclipse error: indirectly referenced from required .class files?

It happens to me sometimes, I always fixed that with "mvn eclipse:clean" command to clean old properties and then run mvn eclipse:eclipse -Dwtpversion=2.0 (for web project of course). There are some old properties saved so eclipse is confused sometimes.

Namenode not getting started

Why do most answers here assume that all data needs to be deleted, reformatted, and then restart Hadoop? How do we know namenode is not progressing, but taking lots of time. It will do this when there is a large amount of data in HDFS. Check progress in logs before assuming anything is hung or stuck.

$ [kadmin@hadoop-node-0 logs]$ tail hadoop-kadmin-namenode-hadoop-node-0.log

...
016-05-13 18:16:44,405 INFO org.apache.hadoop.hdfs.server.namenode.FSEditLogLoader: replaying edit log: 117/141 transactions completed. (83%)
2016-05-13 18:16:56,968 INFO org.apache.hadoop.hdfs.server.namenode.FSEditLogLoader: replaying edit log: 121/141 transactions completed. (86%)
2016-05-13 18:17:06,122 INFO org.apache.hadoop.hdfs.server.namenode.FSEditLogLoader: replaying edit log: 122/141 transactions completed. (87%)
2016-05-13 18:17:38,321 INFO org.apache.hadoop.hdfs.server.namenode.FSEditLogLoader: replaying edit log: 123/141 transactions completed. (87%)
2016-05-13 18:17:56,562 INFO org.apache.hadoop.hdfs.server.namenode.FSEditLogLoader: replaying edit log: 124/141 transactions completed. (88%)
2016-05-13 18:17:57,690 INFO org.apache.hadoop.hdfs.server.namenode.FSEditLogLoader: replaying edit log: 127/141 transactions completed. (90%)

This was after nearly an hour of waiting on a particular system. It is still progressing each time I look at it. Have patience with Hadoop when bringing up the system and check logs before assuming something is hung or not progressing.

T-SQL substring - separating first and last name

This will take care of names like "Firstname Z. Lastname" and "First Z Last"

SELECT
CASE 
    WHEN CHARINDEX(' ',name) = 0 THEN name
    WHEN CHARINDEX(' ',name) = PATINDEX('% _[., ]%',name) THEN RTRIM(SUBSTRING(name, 1, CHARINDEX(' ',name) + 2)) 
    ELSE SUBSTRING(name,1, CHARINDEX(' ',name))
END [firstname]
,CASE 
    WHEN CHARINDEX(' ',name) = 0 THEN ''
    WHEN CHARINDEX(' ',name) = PATINDEX('% _[., ]%',name) THEN LTRIM(SUBSTRING(name, CHARINDEX(' ',name) + 3,1000)) 
    ELSE SUBSTRING(name,CHARINDEX(' ',name)+1,1000)
END [lastname]
FROM [myTable]

converting list to json format - quick and easy way

I've done something like before using the JavaScript serialization class:

using System.Web.Script.Serialization;

And:

JavaScriptSerializer jss = new JavaScriptSerializer();

string output = jss.Serialize(ListOfMyObject);
Response.Write(output);
Response.Flush();
Response.End();

How to generate unique ID with node.js

nanoid achieves exactly the same thing that you want.

Example usage:

const { nanoid } = require("nanoid")

console.log(nanoid())
//=> "n340M4XJjATNzrEl5Qvsh"

Install Android App Bundle on device

If you want to install apk from your aab to your device for testing purpose then you need to edit the configuration before running it on the connected device.

  1. Go to Edit Configurations
    enter image description here
  2. Select the Deploy dropdown and change it from "Default apk" to "APK from app bundle".enter image description here
  3. Apply the changes and then run it on the device connected. Build time will increase after making this change.

This will install an apk directly on the device connected from the aab.

JSTL if tag for equal strings

I think the other answers miss one important detail regarding the property name to use in the EL expression. The rules for converting from the method names to property names are specified in 'Introspector.decpitalize` which is part of the java bean standard:

This normally means converting the first character from upper case to lower case, but in the (unusual) special case when there is more than one character and both the first and second characters are upper case, we leave it alone.

Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays as "URL".

So in your case the JSTL code should look like the following, note the capital 'P':

<c:if test = "${ansokanInfo.PSystem == 'NAT'}">

Remove a string from the beginning of a string

<?php
$str = 'bla_string_bla_bla_bla';
echo preg_replace('/bla_/', '', $str, 1); 
?>

How to search a Git repository by commit message?

git log --grep="Build 0051"

should do the trick

.gitignore file for java eclipse project

put .gitignore in your main catalog

git status (you will see which files you can commit)
git add -A
git commit -m "message"
git push

How to force deletion of a python object?

Perhaps you are looking for a context manager?

>>> class Foo(object):
...   def __init__(self):
...     self.bar = None
...   def __enter__(self):
...     if self.bar != 'open':
...       print 'opening the bar'
...       self.bar = 'open'
...   def __exit__(self, type_, value, traceback):
...     if self.bar != 'closed':
...       print 'closing the bar', type_, value, traceback
...       self.bar = 'close'
... 
>>> 
>>> with Foo() as f:
...     # oh no something crashes the program
...     sys.exit(0)
... 
opening the bar
closing the bar <type 'exceptions.SystemExit'> 0 <traceback object at 0xb7720cfc>

Pandas split DataFrame by column value

Using groupby you could split into two dataframes like

In [1047]: df1, df2 = [x for _, x in df.groupby(df['Sales'] < 30)]

In [1048]: df1
Out[1048]:
   A  Sales
2  7     30
3  6     40
4  1     50

In [1049]: df2
Out[1049]:
   A  Sales
0  3     10
1  4     20

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

My way is to always Redirect::back() or Redirect::to():

Redirect::back()->with('message', 'error|There was an error...');

Redirect::back()->with('message', 'message|Record updated.');

Redirect::to('/')->with('message', 'success|Record updated.');

I have a helper function to make it work for me, usually this is in a separate service:

function displayAlert()
{
      if (Session::has('message'))
      {
         list($type, $message) = explode('|', Session::get('message'));

         $type = $type == 'error' : 'danger';
         $type = $type == 'message' : 'info';

         return sprintf('<div class="alert alert-%s">%s</div>', $type, message);
      }

      return '';
}

And in my view or layout I just do

{{ displayAlert() }}

PHP/Apache: PHP Fatal error: Call to undefined function mysql_connect()

The Apache module PHP version might for some odd reason not be picking up the php.ini file as the CLI version I'd suggest having a good look at:

  • Any differences in the .ini files that differ between php -i and phpinfo() via a web page*
  • If there are no differences then to look at the permissions of mysql.so and the .ini files but I think that Apache parses these as the root user

To be really clear here, don't go searching for php.ini files on the file system, have a look at what PHP says that it's looking at

How do I count a JavaScript object's attributes?

 var miobj = [
  {"padreid":"0", "sw":"0", "dtip":"UNO", "datos":[]},
  {"padreid":"1", "sw":"0", "dtip":"DOS", "datos":[]}
 ];
 alert(miobj.length) //=== 2

but

 alert(miobj[0].length) //=== undefined

this function is very good

Object.prototype.count = function () {
    var count = 0;
    for(var prop in this) {
        if(this.hasOwnProperty(prop))
            count = count + 1;
    }
    return count;
}

alert(miobj.count()) // === 2
alert(miobj[0].count()) // === 4

The tilde operator in Python

One should note that in the case of array indexing, array[~i] amounts to reversed_array[i]. It can be seen as indexing starting from the end of the array:

[0, 1, 2, 3, 4, 5, 6, 7, 8]
    ^                 ^
    i                ~i

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

Example to get the last input element:

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

installing requests module in python 2.7 windows

There are four options here:

  1. Get virtualenv set up. Each virtual environment you create will automatically have pip.

  2. Get pip set up globally.

  3. Learn how to install Python packages manually—in most cases it's as simple as download, unzip, python setup.py install, but not always.

  4. Use Christoph Gohlke's binary installers.

How to fix a header on scroll

Glorious, Pure-HTML/CSS Solution

In 2019 with CSS3 you can do this without Javascript at all. I frequently make sticky headers like this:

_x000D_
_x000D_
body {_x000D_
  overflow-y: auto;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
header {_x000D_
  position: sticky; /* Allocates space for the element, but moves it with you when you scroll */_x000D_
  top: 0; /* specifies the start position for the sticky behavior - 0 is pretty common */_x000D_
  width: 100%;_x000D_
  padding: 5px 0 5px 15px;_x000D_
  color: white;_x000D_
  background-color: #337AB7;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
div.big {_x000D_
  width: 100%;_x000D_
  min-height: 150vh;_x000D_
  background-color: #1ABB9C;_x000D_
  padding: 10px;_x000D_
}
_x000D_
<body>_x000D_
<header><h1>Testquest</h1></header>_x000D_
<div class="big">Just something big enough to scroll on</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to get the size of a range in Excel

The overall dimensions of a range are in its Width and Height properties.

Dim r As Range
Set r = ActiveSheet.Range("A4:H12")

Debug.Print r.Width
Debug.Print r.Height

Call a React component method from outside

If you are in ES6 just use the "static" keyword on your method from your example would be the following: static alertMessage: function() { ...
},

Hope can help anyone out there :)

How to edit binary file on Unix systems

Bless is a high quality, full featured hex editor.

It is written in mono/Gtk# and its primary platform is GNU/Linux. However it should be able to run without problems on every platform that mono and Gtk# run. Main Features Bless currently provides the following features:

  • Efficient editing of large data files and block devices.
  • Multilevel undo - redo operations.
  • Customizable data views.
  • Fast data rendering on screen.
  • Multiple tabs.
  • Fast find and replace operations.
  • A data conversion table.
  • Advanced copy/paste capabilities.
  • Highlighting of selection pattern matches in the file.
  • Plugin based architecture.
  • Export of data to text and html (others with plugins).
  • Bitwise operations on data.
  • A comprehensive user manual.

copied from http://home.gna.org/bless/

MySQL case sensitive query

Whilst the listed answer is correct, may I suggest that if your column is to hold case sensitive strings you read the documentation and alter your table definition accordingly.

In my case this amounted to defining my column as:

`tag` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT ''

This is in my opinion preferential to adjusting your queries.

Continuous CSS rotation animation on hover, animated back to 0deg on hover out

The solution is to set the default value in your .elem. But this annimation work fine with -moz but not yet implement in -webkit

Look at the fiddle I updated from yours : http://jsfiddle.net/DoubleYo/4Vz63/1648/

It works fine with Firefox but not with Chrome

_x000D_
_x000D_
.elem{_x000D_
    position: absolute;_x000D_
    top: 40px;_x000D_
    left: 40px;_x000D_
    width: 0; _x000D_
    height: 0;_x000D_
    border-style: solid;_x000D_
    border-width: 75px;_x000D_
    border-color: red blue green orange;_x000D_
    transition-property: transform;_x000D_
    transition-duration: 1s;_x000D_
}_x000D_
.elem:hover {_x000D_
    animation-name: rotate; _x000D_
    animation-duration: 2s; _x000D_
    animation-iteration-count: infinite;_x000D_
    animation-timing-function: linear;_x000D_
}_x000D_
_x000D_
@keyframes rotate {_x000D_
    from {transform: rotate(0deg);}_x000D_
    to {transform: rotate(360deg);}_x000D_
}
_x000D_
<div class="elem"></div>
_x000D_
_x000D_
_x000D_

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

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

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

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

How do I remove my IntelliJ license in 2019.3?

in linux/ubuntu you can do, run following commands

cd ~/.config/JetBrains/PyCharm2020.1
rm eval/PyCharm201.evaluation.key
sed -i '/evlsprt/d' options/other.xml
cd ~/.java/.userPrefs/jetbrains
rm -rf pycharm*

Why does CSS not support negative padding?

You asked WHY, not how to cheat it:

Usually because of laziness of programmers of the initial implementation, because they HAVE already put way more effort in other features, delivering more odd side-effects like floats, because they were more requested by designers back then and yet they haven't taken the time to allow this so we can use the FOUR properties to push/pull an element against its neighbors (now we only have four to push, and only 2 to pull).

When html was designed, magazines loved text reflown around images back then, now hated because today we have touch trends, and love squary things with lots of space and nothing to read. That's why they put more pressure on floats than on centering, or they could have designed something like margin-top: fill; or margin: average 0; to simply align the content to the bottom, or distribute its extra space around.

In this case I think it hasn't been implemented because of the same reason that makes CSS to lack of a :parent pseudo-selector: To prevent looping evaluations.

Without being an engineer, I can see that CSS right now is made to paint elements once, remember some properties for future elements to be painted, but NEVER going back to already-painted elements.

That's why (I guess) padding is calculated on the width, because that's the value that was available at the time of starting to paint it.

If you had a negative value for padding, it would affect the outer limits, which has ALREADY been defined when the margin has already been set. I know, nothing has been painted yet, but when you read how the painting process goes, created by geniuses with 90's technology, I feel like I am asking dumb questions and just say "thanks" hehe.

One of the requirements of web pages is that they are quickly available, unlike an app that can take its time and eat the computer resources to get everything correct before displaying it, web pages need to use little resources (so they are fit in every device possible) and be scrolled in a breeze.

If you see applications with complex reflowing and positioning, like InDesign, you can't scroll that fast! It takes a big effort both from processors and graphic card to jump to next pages!

So painting and calculating forward and forgetting about an element once drawn, for now it seems to be a MUST.

How to fix PHP Warning: PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll'?

I have the same issue with windows10, apache 2.2.25, php 5.2 Im trying to add GD to a working PHP.

how I turn around and change between forward and backward slash, plus trailing or not, I get some variant of ;

PHP Warning: PHP Startup: Unable to load dynamic library 'C:/php\php_gd2.dll' - Det g\xe5r inte att hitta den angivna modulen.\r\n in Unknown on line 0

(swedish translated: 'It is not possible to find the module' )

in this perticular case, the php.ini was: extension_dir = "C:/php"

the dll is put in two places C:\php and C:\php\ext

IS it possible that there is and "error" in the error log entry ? I.e. that the .dll IS found (as a file) but not of the right format, or something like that ??

Python: IndexError: list index out of range

I think you mean to put the rolling of the random a,b,c, etc within the loop:

a = None # initialise
while not (a in winning_numbers):
    # keep rolling an a until you get one not in winning_numbers
    a = random.randint(1,30)
    winning_numbers.append(a)

Otherwise, a will be generated just once, and if it is in winning_numbers already, it won't be added. Since the generation of a is outside the while (in your code), if a is already in winning_numbers then too bad, it won't be re-rolled, and you'll have one less winning number.

That could be what causes your error in if guess[i] == winning_numbers[i]. (Your winning_numbers isn't always of length 5).

Retrieving the COM class factory for component failed

This did the trick for me: (solution from the msdn forum)

goto Controlpanel --> Administrative tools-->Component Services -->computers --> myComputer -->DCOM Config --> Microsoft Excel Application.

right click to get properties dialog. Goto Security tab and customize permissions accordingly.

In Launch and Application Permissions, select Customize, Edit. Add the user / group that calls the application.

angular 4: *ngIf with multiple conditions

Besides the redundant ) this expression will always be true because currentStatus will always match one of these two conditions:

currentStatus !== 'open' || currentStatus !== 'reopen'

perhaps you mean one of

!(currentStatus === 'open' || currentStatus === 'reopen')
(currentStatus !== 'open' && currentStatus !== 'reopen')

List of Java processes

try:

ps aux | grep java

and see how you get on

How to parse XML using shellscript?

I am surprised no one has mentioned xmlsh. The mission statement :

A command line shell for XML Based on the philosophy and design of the Unix Shells

xmlsh provides a familiar scripting environment, but specifically tailored for scripting xml processes.

A list of shell like commands are provided here.

I use the xed command a lot which is equivalent to sed for XML, and allows XPath based search and replaces.

How to import load a .sql or .csv file into SQLite?

The sqlite3 .import command won't work for ordinary csv data because it treats any comma as a delimiter even in a quoted string.

This includes trying to re-import a csv file that was created by the shell:

Create table T (F1 integer, F2 varchar);
Insert into T values (1, 'Hey!');
Insert into T values (2, 'Hey, You!');

.mode csv
.output test.csv
select * from T;

Contents of test.csv:
1,Hey!
2,"Hey, You!"

delete from T;

.import test.csv T
Error: test.csv line 2: expected 2 columns of data but found 3

It seems we must transform the csv into a list of Insert statements, or perhaps a different delimiter will work.

Over at SuperUser I saw a suggestion to use LogParser to deal with csv files, I'm going to look into that.

How to find column names for all tables in all databases in SQL Server

Some minor improvements

->previous answers weren't showing all results

->possible to filter on column name by setting the column name variable

DECLARE @columnname nvarchar(150)
SET @columnname=''

DECLARE @SQL varchar(max)
SET @SQL=''
SELECT @SQL=@SQL+'UNION
select 
'''+d.name+'.''+sh.name+''.''+o.name COLLATE SQL_Latin1_General_CP1_CI_AS as name,c.name COLLATE SQL_Latin1_General_CP1_CI_AS as columnname,c.column_id
from '+d.name+'.sys.columns            c
    inner join '+d.name+'.sys.objects  o on c.object_id=o.object_id
    INNER JOIN '+d.name+'.sys.schemas  sh on o.schema_id=sh.schema_id
    where c.name like ''%'+@columnname+'%'' and sh.name<>''sys'' 
'
FROM sys.databases d
SELECT @SQL=RIGHT(@SQL,LEN(@SQL)-5)+'order by 1,3'
--print @SQL
EXEC (@SQL)

UNIX nonblocking I/O: O_NONBLOCK vs. FIONBIO

Prior to standardization there was ioctl(...FIONBIO...) and fcntl(...O_NDELAY...), but these behaved inconsistently between systems, and even within the same system. For example, it was common for FIONBIO to work on sockets and O_NDELAY to work on ttys, with a lot of inconsistency for things like pipes, fifos, and devices. And if you didn't know what kind of file descriptor you had, you'd have to set both to be sure. But in addition, a non-blocking read with no data available was also indicated inconsistently; depending on the OS and the type of file descriptor the read may return 0, or -1 with errno EAGAIN, or -1 with errno EWOULDBLOCK. Even today, setting FIONBIO or O_NDELAY on Solaris causes a read with no data to return 0 on a tty or pipe, or -1 with errno EAGAIN on a socket. However 0 is ambiguous since it is also returned for EOF.

POSIX addressed this with the introduction of O_NONBLOCK, which has standardized behavior across different systems and file descriptor types. Because existing systems usually want to avoid any changes to behavior which might break backward compatibility, POSIX defined a new flag rather than mandating specific behavior for one of the others. Some systems like Linux treat all 3 the same, and also define EAGAIN and EWOULDBLOCK to the same value, but systems wishing to maintain some other legacy behavior for backward compatibility can do so when the older mechanisms are used.

New programs should use fcntl(...O_NONBLOCK...), as standardized by POSIX.

How do you pass view parameters when navigating from an action in JSF2?

You can do it using Primefaces like this :

<p:button 
      outcome="/page2.xhtml?faces-redirect=true&amp;id=#{myBean.id}">
</p:button>

What's the best way to use R scripts on the command line (terminal)?

Content of script.r:

#!/usr/bin/env Rscript

args = commandArgs(trailingOnly = TRUE)
message(sprintf("Hello %s", args[1L]))

The first line is the shebang line. It’s best practice to use /usr/bin/env Rscript instead of hard-coding the path to your R installation. Otherwise you risk your script breaking on other computers.

Next, make it executable (on the command line):

chmod +x script.r

Invocation from command line:

./script.r world
# Hello world

No operator matches the given name and argument type(s). You might need to add explicit type casts. -- Netbeans, Postgresql 8.4 and Glassfish

I had this issue, and solved. This was due to the WHERE clause contains String value instead of integer value.

Online Internet Explorer Simulators

Use wine - it has IE6 with Gecko support built into it. More information here.

Built in Python hash() function

Most answers suggest this is because of different platforms, but there is more to it. From the documentation of object.__hash__(self):

By default, the __hash__() values of str, bytes and datetime objects are “salted” with an unpredictable random value. Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python.

This is intended to provide protection against a denial-of-service caused by carefully-chosen inputs that exploit the worst case performance of a dict insertion, O(n²) complexity. See http://www.ocert.org/advisories/ocert-2011-003.html for details.

Changing hash values affects the iteration order of dicts, sets and other mappings. Python has never made guarantees about this ordering (and it typically varies between 32-bit and 64-bit builds).

Even running on the same machine will yield varying results across invocations:

$ python -c "print(hash('http://stackoverflow.com'))"
-3455286212422042986
$ python -c "print(hash('http://stackoverflow.com'))"
-6940441840934557333

While:

$ python -c "print(hash((1,2,3)))"
2528502973977326415
$ python -c "print(hash((1,2,3)))"
2528502973977326415

See also the environment variable PYTHONHASHSEED:

If this variable is not set or set to random, a random value is used to seed the hashes of str, bytes and datetime objects.

If PYTHONHASHSEED is set to an integer value, it is used as a fixed seed for generating the hash() of the types covered by the hash randomization.

Its purpose is to allow repeatable hashing, such as for selftests for the interpreter itself, or to allow a cluster of python processes to share hash values.

The integer must be a decimal number in the range [0, 4294967295]. Specifying the value 0 will disable hash randomization.

For example:

$ export PYTHONHASHSEED=0                            
$ python -c "print(hash('http://stackoverflow.com'))"
-5843046192888932305
$ python -c "print(hash('http://stackoverflow.com'))"
-5843046192888932305

How do I find which rpm package supplies a file I'm looking for?

You can do this alike here but with your package. In my case, it was lsb_release

Run: yum whatprovides lsb_release

Response:

redhat-lsb-core-4.1-24.el7.i686 : LSB Core module support
Repo        : rhel-7-server-rpms
Matched from:
Filename    : /usr/bin/lsb_release

redhat-lsb-core-4.1-24.el7.x86_64 : LSB Core module support
Repo        : rhel-7-server-rpms
Matched from:
Filename    : /usr/bin/lsb_release

redhat-lsb-core-4.1-27.el7.i686 : LSB Core module support
Repo        : rhel-7-server-rpms
Matched from:
Filename    : /usr/bin/lsb_release

redhat-lsb-core-4.1-27.el7.x86_64 : LSB Core module support
Repo        : rhel-7-server-rpms
Matched from:
Filename    : /usr/bin/lsb_release`

Run to install: yum install redhat-lsb-core

The package name SHOULD be without number and system type so yum packager can choose what is best for him.

Update cordova plugins in one command

I got tired of manually checking for plugin updates so created a tool to do it for me: https://github.com/dpa99c/cordova-check-plugins

Install it globally:

$ npm install -g cordova-check-plugins

Then run from the root of your Cordova project. You can optionally update outdated plugins interactively or automatically, e.g.

$ cordova-check-plugins --update=auto

CLI screenshot

how to run mysql in ubuntu through terminal

You seem to just have begun using mysql.

Simple answer: for now use

mysql -u root -p password

Password is usually root by default. You may use other usernames if you have created other user using create user in mysql. For details use "help, help manage accounts, help create users" etc. If you dont want your password to be shown in open just press return key after "-p" and you will be prompted for password next. Hope this resolves the issue.

What is the maximum possible length of a query string?

Different web stacks do support different lengths of http-requests. I know from experience that the early stacks of Safari only supported 4000 characters and thus had difficulty handling ASP.net pages because of the USER-STATE. This is even for POST, so you would have to check the browser and see what the stack limit is. I think that you may reach a limit even on newer browsers. I cannot remember but one of them (IE6, I think) had a limit of 16-bit limit, 32,768 or something.

Clone an image in cv2 python

Using python 3 and opencv-python version 4.4.0, the following code should work:

img_src = cv2.imread('image.png')
img_clone = img_src.copy()

failed to lazily initialize a collection of role

It's possible that you're not fetching the Joined Set. Be sure to include the set in your HQL:

public List<Node> getAll() {
    Session session = sessionFactory.getCurrentSession();
    Query query = session.createQuery("FROM Node as n LEFT JOIN FETCH n.nodeValues LEFT JOIN FETCH n.nodeStats");
    return  query.list();
}

Where your class has 2 sets like:

public class Node implements Serializable {

@OneToMany(fetch=FetchType.LAZY)
private Set<NodeValue> nodeValues;

@OneToMany(fetch=FetchType.LAZY)
private Set<NodeStat> nodeStats;

}

Using port number in Windows host file

Fiddler2 -> Rules -> Custom Rules

then find function OnBeforeRequest on put in the next script at the end:

if (oSession.HostnameIs("mysite.com")){
    oSession.host="localhost:39901";
}

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

In addition to the other answers so far, here is unobvious example where static_cast is not sufficient so that reinterpret_cast is needed. Suppose there is a function which in an output parameter returns pointers to objects of different classes (which do not share a common base class). A real example of such function is CoCreateInstance() (see the last parameter, which is in fact void**). Suppose you request particular class of object from this function, so you know in advance the type for the pointer (which you often do for COM objects). In this case you cannot cast pointer to your pointer into void** with static_cast: you need reinterpret_cast<void**>(&yourPointer).

In code:

#include <windows.h>
#include <netfw.h>
.....
INetFwPolicy2* pNetFwPolicy2 = nullptr;
HRESULT hr = CoCreateInstance(__uuidof(NetFwPolicy2), nullptr,
    CLSCTX_INPROC_SERVER, __uuidof(INetFwPolicy2),
    //static_cast<void**>(&pNetFwPolicy2) would give a compile error
    reinterpret_cast<void**>(&pNetFwPolicy2) );

However, static_cast works for simple pointers (not pointers to pointers), so the above code can be rewritten to avoid reinterpret_cast (at a price of an extra variable) in the following way:

#include <windows.h>
#include <netfw.h>
.....
INetFwPolicy2* pNetFwPolicy2 = nullptr;
void* tmp = nullptr;
HRESULT hr = CoCreateInstance(__uuidof(NetFwPolicy2), nullptr,
    CLSCTX_INPROC_SERVER, __uuidof(INetFwPolicy2),
    &tmp );
pNetFwPolicy2 = static_cast<INetFwPolicy2*>(tmp);

Getting Class type from String

You can get the Class reference of any class during run time through the Java Reflection Concept.

Check the Below Code. Explanation is given below

Here is one example that uses returned Class to create an instance of AClass:

package com.xyzws;
class AClass {
    public AClass() {
        System.out.println("AClass's Constructor"); 
    }  
    static {   
        System.out.println("static block in AClass");  
    }
}
public class Program {   
    public static void main(String[] args) {
        try {       
            System.out.println("The first time calls forName:");   
            Class c = Class.forName("com.xyzws.AClass");      
            AClass a = (AClass)c.newInstance();    
            System.out.println("The second time calls forName:");  
            Class c1 = Class.forName("com.xyzws.AClass"); 
        } catch (ClassNotFoundException e) { 
            // ...
        } catch (InstantiationException e) {  
            // ...
        } catch (IllegalAccessException e) { 
            // ...
        }     
    }
}

The printed output is

    The first time calls forName:
    static block in AClass
    AClass's Constructor
    The second time calls forName:

The class has already been loaded so there is no second "static block in AClass"

The Explanation is below

Class.ForName is called to get a Class Object

By Using the Class Object we are creating the new instance of the Class.

Any doubts about this let me know

Type of expression is ambiguous without more context Swift

The compiler can't figure out what type to make the Dictionary, because it's not homogenous. You have values of different types. The only way to get around this is to make it a [String: Any], which will make everything clunky as all hell.

return [
    "title": title,
    "is_draft": isDraft,
    "difficulty": difficulty,
    "duration": duration,
    "cost": cost,
    "user_id": userId,
    "description": description,
    "to_sell": toSell,
    "images": [imageParameters, imageToDeleteParameters].flatMap { $0 }
] as [String: Any]

This is a job for a struct. It'll vastly simplify working with this data structure.

How to prevent 'query timeout expired'? (SQLNCLI11 error '80040e31')

Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.

I had a opened record set of the post that was created by:

Set RecSet = Conn.Execute()

This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...

RecSet.Close
Set RecSet = Nothing

...everything worked just fine.

So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.

Regular Expressions: Is there an AND operator?

You need to use lookahead as some of the other responders have said, but the lookahead has to account for other characters between its target word and the current match position. For example:

(?=.*word1)(?=.*word2)(?=.*word3)

The .* in the first lookahead lets it match however many characters it needs to before it gets to "word1". Then the match position is reset and the second lookahead seeks out "word2". Reset again, and the final part matches "word3"; since it's the last word you're checking for, it isn't necessary that it be in a lookahead, but it doesn't hurt.

In order to match a whole paragraph, you need to anchor the regex at both ends and add a final .* to consume the remaining characters. Using Perl-style notation, that would be:

/^(?=.*word1)(?=.*word2)(?=.*word3).*$/m

The 'm' modifier is for multline mode; it lets the ^ and $ match at paragraph boundaries ("line boundaries" in regex-speak). It's essential in this case that you not use the 's' modifier, which lets the dot metacharacter match newlines as well as all other characters.

Finally, you want to make sure you're matching whole words and not just fragments of longer words, so you need to add word boundaries:

/^(?=.*\bword1\b)(?=.*\bword2\b)(?=.*\bword3\b).*$/m

How to fix div on scroll

I made a mix of the answers here, took the code of @Julian and ideas from the others, seems clearer to me, this is what's left:

fiddle http://jsfiddle.net/wq2Ej/

jquery

//store the element
var $cache = $('.my-sticky-element');

//store the initial position of the element
var vTop = $cache.offset().top - parseFloat($cache.css('marginTop').replace(/auto/, 0));
  $(window).scroll(function (event) {
    // what the y position of the scroll is
    var y = $(this).scrollTop();

    // whether that's below the form
    if (y >= vTop) {
      // if so, ad the fixed class
      $cache.addClass('stuck');
    } else {
      // otherwise remove it
      $cache.removeClass('stuck');
    }
  });

css:

.my-sticky-element.stuck {
    position:fixed;
    top:0;
    box-shadow:0 2px 4px rgba(0, 0, 0, .3);
}

Why can't I display a pound (£) symbol in HTML?

1st: the pound symbol is a "special" char in utf8 encoding (try saving £$ in a iso-8859-1 (or iso-8859-15) file and you will get ä when encoding using header)

2nd: change your encoding to utf8 form the file. there are plenty of methods to do it. notepad and notepad++ are great sugestions.

3rd: use ob_start(); (in php) BEFORE YOU MAKE ANY OUTPUT if you are getting weird encoding errors, like missing the encoding sometimes. and YES, this solves it! this kind of errors occurs when a page is encoded in windows-1252(ANSI),ASCII,iso-8859-1(5) and then you have all the others in utf8. this is a terrible error and can cause weird things like session_start(); not working.

4th: other php solutions:

utf8_encode('£');
htmlentities('£');
echo '&amp;pound;';

5th: javascript solutions:

document.getElementById('id_goes_here').innerText.replace('£','&amp;pound;');
document.getElementById('id_goes_here').innerText.replace('£',"\u00A3");
$(this).html().replace('£','&amp;pound;'); //jquery
$(this).html().replace('£',"\u00A3"); //jquery
String.fromCharCode('163');

you MUST send £, so it will repair the broken encoded code point. please, avoid these solutions! use php! these solutions only show how to 'fix' the error, and the last one only to create the well-encoded char.

Deleting specific rows from DataTable

the easy way use this in button :

 var table = $('#example1').DataTable();
 table.row($(`#yesmediasec-${id}`).closest('tr')).remove( ).draw();

example1 = id table . yesmediasec = id of the button in the row

use it and every thing will be ok

How do I convert a Python 3 byte-string variable into a regular string?

You had it nearly right in the last line. You want

str(bytes_string, 'utf-8')

because the type of bytes_string is bytes, the same as the type of b'abc'.

How to JOIN three tables in Codeigniter

Try as follows:

public function funcname($id)
{
    $this->db->select('*');
    $this->db->from('Album a'); 
    $this->db->join('Category b', 'b.cat_id=a.cat_id', 'left');
    $this->db->join('Soundtrack c', 'c.album_id=a.album_id', 'left');
    $this->db->where('c.album_id',$id);
    $this->db->order_by('c.track_title','asc');         
    $query = $this->db->get(); 
    return $query->result_array();
}

If no result found CI returns false otherwise true

Why do we assign a parent reference to the child object in Java?

Let's say you'd like to have an array of instances of Parent class, and a set of child classes Child1, Child2, Child3 extending Parent. There're situations when you're only interested with the parent class implementation, which is more general, and do not care about more specific stuff introduced by child classes.

Error: "setFile(null,false) call failed" when using log4j

i just add write permission to "logs" folder and it works for me

add write permission

How to insert Records in Database using C# language?

You should form the command with the contents of the textboxes:

sql = "insert into Main (Firt Name, Last Name) values(" + textbox2.Text + "," + textbox3.Text+ ")";

This, of course, provided that you manage to open the connection correctly.

It would be helpful to know what's happening with your current code. If you are getting some error displayed in that message box, it would be great to know what it's saying.

You should also validate the inputs before actually running the command (i.e. make sure they don't contain malicious code...).

Minimum Hardware requirements for Android development

Hey, I have used the same software on an AMD 3Ghz chip, dual core. had 2gbs of ram at the time, and i noticed the emulator ran at an alright speed, but took a ridiculous amount of time to load. I have not done enough development on Android to tell you if this is a common, or even still existing problem, but it is certainly something I remember from my experience.

Subtract 1 day with PHP

How to add 1 year to a date and then subtract 1 day from it in asp.net c#

Convert.ToDateTime(txtDate.Value.Trim()).AddYears(1).AddDays(-1);

How to get row count using ResultSet in Java?

your sql Statement creating code may be like

statement = connection.createStatement();

To solve "com.microsoft.sqlserver.jdbc.SQLServerException: The requested operation is not supported on forward only result sets" exception change above code with

statement = connection.createStatement(
    ResultSet.TYPE_SCROLL_INSENSITIVE, 
    ResultSet.CONCUR_READ_ONLY);

After above change you can use

int size = 0;
try {
    resultSet.last();
    size = resultSet.getRow();
    resultSet.beforeFirst();
}
catch(Exception ex) {
    return 0;
}
return size;

to get row count

Check if an array contains any element of another array in JavaScript

vanilla js

/**
 * @description determine if an array contains one or more items from another array.
 * @param {array} haystack the array to search.
 * @param {array} arr the array providing items to check for in the haystack.
 * @return {boolean} true|false if haystack contains at least one item from arr.
 */
var findOne = function (haystack, arr) {
    return arr.some(function (v) {
        return haystack.indexOf(v) >= 0;
    });
};

As noted by @loganfsmyth you can shorten it in ES2016 to

/**
 * @description determine if an array contains one or more items from another array.
 * @param {array} haystack the array to search.
 * @param {array} arr the array providing items to check for in the haystack.
 * @return {boolean} true|false if haystack contains at least one item from arr.
 */
var findOne = (haystack, arr) => {
    return arr.some(v => haystack.includes(v));
};

or simply as arr.some(v => haystack.includes(v));

How do I get bootstrap-datepicker to work with Bootstrap 3?

I also use Stefan Petre’s http://www.eyecon.ro/bootstrap-datepicker and it does not work with Bootstrap 3 without modification. Note that http://eternicode.github.io/bootstrap-datepicker/ is a fork of Stefan Petre's code.

You have to change your markup (the sample markup will not work) to use the new CSS and form grid layout in Bootstrap 3. Also, you have to modify some CSS and JavaScript in the actual bootstrap-datepicker implementation.

Here is my solution:

<div class="form-group row">
  <div class="col-xs-8">
    <label class="control-label">My Label</label>
    <div class="input-group date" id="dp3" data-date="12-02-2012" data-date-format="mm-dd-yyyy">
      <input class="form-control" type="text" readonly="" value="12-02-2012">
      <span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
    </div>
  </div>
</div>

CSS changes in datepicker.css on lines 176-177:

.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {

Javascript change in datepicker-bootstrap.js on line 34:

this.component = this.element.is('.date') ? this.element.find('.input-group-addon') : false;

UPDATE

Using the newer code from http://eternicode.github.io/bootstrap-datepicker/ the changes are as follows:

CSS changes in datepicker.css on lines 446-447:

.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {

Javascript change in datepicker-bootstrap.js on line 46:

 this.component = this.element.is('.date') ? this.element.find('.input-group-addon, .btn') : false;

Finally, the JavaScript to enable the datepicker (with some options):

 $(".input-group.date").datepicker({ autoclose: true, todayHighlight: true });

Tested with Bootstrap 3.0 and JQuery 1.9.1. Note that this fork is better to use than the other as it is more feature rich, has localization support and auto-positions the datepicker based on the control position and window size, avoiding the picker going off the screen which was a problem with the older version.

What is the default Jenkins password?

When you install jenkins on your local machine, the default username is admin and password it gets automatically filled.

Could not create the Java virtual machine

Make sure the physical available memory is more then VM defined min/max memory.

How do I remove carriage returns with Ruby?

If you are using Rails, there is a squish method

"\tgoodbye\r\n".squish => "goodbye"

"\tgood \t\r\nbye\r\n".squish => "good bye"

Setting DIV width and height in JavaScript

These are several ways to apply style to an element. Try any one of the examples below:

1. document.getElementById('div_register').className = 'wide';
  /* CSS */ .wide{width:500px;}
2. document.getElementById('div_register').setAttribute('class','wide');
3. document.getElementById('div_register').style.width = '500px';

Reading e-mails from Outlook with Python through MAPI

I had the same issue. Combining various approaches from the internet (and above) come up with the following approach (checkEmails.py)

class CheckMailer:

        def __init__(self, filename="LOG1.txt", mailbox="Mailbox - Another User Mailbox", folderindex=3):
            self.f = FileWriter(filename)
            self.outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI").Folders(mailbox)
            self.inbox = self.outlook.Folders(folderindex)


        def check(self):                
        #===============================================================================
        # for i in xrange(1,100):                           #Uncomment this section if index 3 does not work for you
        #     try:
        #         self.inbox = self.outlook.Folders(i)     # "6" refers to the index of inbox for Default User Mailbox
        #         print "%i %s" % (i,self.inbox)            # "3" refers to the index of inbox for Another user's mailbox
        #     except:
        #         print "%i does not work"%i
        #===============================================================================

                self.f.pl(time.strftime("%H:%M:%S"))
                tot = 0                
                messages = self.inbox.Items
                message = messages.GetFirst()
                while message:
                    self.f.pl (message.Subject)
                    message = messages.GetNext()
                    tot += 1
                self.f.pl("Total Messages found: %i" % tot)
                self.f.pl("-" * 80)
                self.f.flush()

if __name__ == "__main__":
    mail = CheckMailer()
    for i in xrange(320):  # this is 10.6 hours approximately
            mail.check()
            time.sleep(120.00)

For concistency I include also the code for the FileWriter class (found in FileWrapper.py). I needed this because trying to pipe UTF8 to a file in windows did not work.

class FileWriter(object):
    '''
    convenient file wrapper for writing to files
    '''


    def __init__(self, filename):
        '''
        Constructor
        '''
        self.file = open(filename, "w")

    def pl(self, a_string):
        str_uni = a_string.encode('utf-8')
        self.file.write(str_uni)
        self.file.write("\n")

    def flush(self):
        self.file.flush()

Delete rows from multiple tables using a single query (SQL Express 2005) with a WHERE condition

CREATE PROCEDURE sp_deleteUserDetails
    @Email varchar(255)
AS
    declare @tempRegId as int
    Delete UserRegistration where Email=@Email  
    set @tempRegId = (select Id from UserRegistration where Email = @Email)
    Delete UserProfile where RegID=@tempRegId

RETURN 0

How to unpack pkl file?

In case you want to work with the original MNIST files, here is how you can deserialize them.

If you haven't downloaded the files yet, do that first by running the following in the terminal:

wget http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz
wget http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz
wget http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz
wget http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz

Then save the following as deserialize.py and run it.

import numpy as np
import gzip

IMG_DIM = 28

def decode_image_file(fname):
    result = []
    n_bytes_per_img = IMG_DIM*IMG_DIM

    with gzip.open(fname, 'rb') as f:
        bytes_ = f.read()
        data = bytes_[16:]

        if len(data) % n_bytes_per_img != 0:
            raise Exception('Something wrong with the file')

        result = np.frombuffer(data, dtype=np.uint8).reshape(
            len(bytes_)//n_bytes_per_img, n_bytes_per_img)

    return result

def decode_label_file(fname):
    result = []

    with gzip.open(fname, 'rb') as f:
        bytes_ = f.read()
        data = bytes_[8:]

        result = np.frombuffer(data, dtype=np.uint8)

    return result

train_images = decode_image_file('train-images-idx3-ubyte.gz')
train_labels = decode_label_file('train-labels-idx1-ubyte.gz')

test_images = decode_image_file('t10k-images-idx3-ubyte.gz')
test_labels = decode_label_file('t10k-labels-idx1-ubyte.gz')

The script doesn't normalize the pixel values like in the pickled file. To do that, all you have to do is

train_images = train_images/255
test_images = test_images/255

How can I show dots ("...") in a span with hidden overflow?

If you are using text-overflow:ellipsis, the browser will show the contents whatever possible within that container. But if you want to specifiy the number of letters before the dots or strip some contents and add dots, you can use the below function.

function add3Dots(string, limit)
{
  var dots = "...";
  if(string.length > limit)
  {
    // you can also use substr instead of substring
    string = string.substring(0,limit) + dots;
  }
 
    return string;
}

call like

add3Dots("Hello World",9);

outputs

Hello Wor...

See it in action here

_x000D_
_x000D_
function add3Dots(string, limit)
{
  var dots = "...";
  if(string.length > limit)
  {
    // you can also use substr instead of substring
    string = string.substring(0,limit) + dots;
  }

    return string;
}



console.log(add3Dots("Hello, how are you doing today?", 10));
_x000D_
_x000D_
_x000D_

Error in file(file, "rt") : cannot open the connection

I had a same issue .I removed the extension from the file name.Example my file name was saved as xyz. csv. i saved it as xyz.

Get a filtered list of files in a directory

Keep it simple:

import os
relevant_path = "[path to folder]"
included_extensions = ['jpg','jpeg', 'bmp', 'png', 'gif']
file_names = [fn for fn in os.listdir(relevant_path)
              if any(fn.endswith(ext) for ext in included_extensions)]

I prefer this form of list comprehensions because it reads well in English.

I read the fourth line as: For each fn in os.listdir for my path, give me only the ones that match any one of my included extensions.

It may be hard for novice python programmers to really get used to using list comprehensions for filtering, and it can have some memory overhead for very large data sets, but for listing a directory and other simple string filtering tasks, list comprehensions lead to more clean documentable code.

The only thing about this design is that it doesn't protect you against making the mistake of passing a string instead of a list. For example if you accidentally convert a string to a list and end up checking against all the characters of a string, you could end up getting a slew of false positives.

But it's better to have a problem that's easy to fix than a solution that's hard to understand.

Is there a link to the "latest" jQuery library on Google APIs?

jQuery also doesn't allow you to call their latest file over SSL, a consideration if you want to use jQuery in a shopping cart etc.

e.g.

<script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script>

will give you a security error.

Google's API will let you call over SSL:

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
  google.load("jquery", "1.7");
</script>

How to include PHP files that require an absolute path?

@Flubba, does this allow me to have folders inside my include directory? flat include directories give me nightmares. as the whole objects directory should be in the inc directory.

Oh yes, absolutely. So for example, we use a single layer of subfolders, generally:

require_once('library/string.class.php')

You need to be careful with relying on the include path too much in really high traffic sites, because php has to hunt through the current directory and then all the directories on the include path in order to see if your file is there and this can slow things up if you're getting hammered.

So for example if you're doing MVC, you'd put the path to your application directoy in the include path and then specify refer to things in the form

'model/user.class'
'controllers/front.php'

or whatever.

But generally speaking, it just lets you work with really short paths in your PHP that will work from anywhere and it's a lot easier to read than all that realpath document root malarkey.

The benefit of those script-based alternatives others have suggested is they work anywhere, even on shared boxes; setting the include path requires a little more thought and effort but as I mentioned lets you start using __autoload which just the coolest.

How to change facet labels?

Have you tried changing the specific levels of your Hospital vector?

levels(survey$hospital)[levels(survey$hospital) == "Hospital #1"] <- "Hosp 1"
levels(survey$hospital)[levels(survey$hospital) == "Hospital #2"] <- "Hosp 2"
levels(survey$hospital)[levels(survey$hospital) == "Hospital #3"] <- "Hosp 3"

Two div blocks on same line

Use a table inside a div.

<div>
   <table style='margin-left: auto; margin-right: auto'>
        <tr>
           <td>
              <div>Your content </div>
           </td>
           <td>
              <div>Your content </div>
           </td>
        </tr>
   </table>
</div>

Set content of HTML <span> with Javascript

With modern browsers, you can set the textContent property, see Node.textContent:

var span = document.getElementById("myspan");
span.textContent = "some text";

R dates "origin" must be supplied

So generally this has been solved, but you might get this error message because the date you use is not in the correct format.

I know this is an old post, but whenever I run this I get NA all the way down my date column. My dates are in this format 20150521 – NealC Jun 5 '15 at 16:06

If you have dates of this format just check the format of your dates with:

str(sides$date)

If the format is not a character, then convert it:

as.character(sides$date)

For as.Date, you won't need an origin any longer, because this is supplied for numeric values only. Thus you can use (assuming you have the format of NealC):

as.Date(as.character(sides$date),format="%Y%m%d")

I hope this might help some of you.

"No resource identifier found for attribute 'showAsAction' in package 'android'"

remove android:showAsAction="never" from res/menu folder from every xml file.

Add a CSS border on hover without moving the element

Add a border to the regular item, the same color as the background, so that it cannot be seen. That way the item has a border: 1px whether it is being hovered or not.

The Network Adapter could not establish the connection when connecting with Oracle DB

When a client connects to an Oracle server, it first connnects to the Oracle listener service. It often redirects the client to another port. So the client has to open another connection on a different port, which is blocked by the firewall.

So you might in fact have encountered a firewall problem due to Oracle port redirection. It should be possible to diagnose it with a network monitor on the client machine or with the firewall management software on the firewall.

Count multiple columns with group by in one query

You didn't say which database server you are using, but if temp tables are available they may be the best approach.

// table is a temp table
select ... into #table ....
SELECT COUNT(column1),column1 FROM #table GROUP BY column1  
SELECT COUNT(column2),column2 FROM #table GROUP BY column2  
SELECT COUNT(column3),column3 FROM #table GROUP BY column3  
// drop may not be required
drop table #table

Parameter in like clause JPQL

Just leave out the ''

LIKE %:code%

JQuery datepicker language

Here is example how you can do localization by yourself.

_x000D_
_x000D_
jQuery(function($) {_x000D_
  $('input.datetimepicker').datepicker({_x000D_
    duration: '',_x000D_
    changeMonth: false,_x000D_
    changeYear: false,_x000D_
    yearRange: '2010:2020',_x000D_
    showTime: false,_x000D_
    time24h: true_x000D_
  });_x000D_
_x000D_
  $.datepicker.regional['cs'] = {_x000D_
    closeText: 'Zavrít',_x000D_
    prevText: '&#x3c;Dríve',_x000D_
    nextText: 'Pozdeji&#x3e;',_x000D_
    currentText: 'Nyní',_x000D_
    monthNames: ['leden', 'únor', 'brezen', 'duben', 'kveten', 'cerven', 'cervenec', 'srpen',_x000D_
      'zárí', 'ríjen', 'listopad', 'prosinec'_x000D_
    ],_x000D_
    monthNamesShort: ['led', 'úno', 'bre', 'dub', 'kve', 'cer', 'cvc', 'srp', 'zár', 'ríj', 'lis', 'pro'],_x000D_
    dayNames: ['nedele', 'pondelí', 'úterý', 'streda', 'ctvrtek', 'pátek', 'sobota'],_x000D_
    dayNamesShort: ['ne', 'po', 'út', 'st', 'ct', 'pá', 'so'],_x000D_
    dayNamesMin: ['ne', 'po', 'út', 'st', 'ct', 'pá', 'so'],_x000D_
    weekHeader: 'Týd',_x000D_
    dateFormat: 'dd/mm/yy',_x000D_
    firstDay: 1,_x000D_
    isRTL: false,_x000D_
    showMonthAfterYear: false,_x000D_
    yearSuffix: ''_x000D_
  };_x000D_
_x000D_
  $.datepicker.setDefaults($.datepicker.regional['cs']);_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
  <link data-require="jqueryui@*" data-semver="1.10.0" rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.0/css/smoothness/jquery-ui-1.10.0.custom.min.css" />_x000D_
  <script data-require="jqueryui@*" data-semver="1.10.0" src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.0/jquery-ui.js"></script>_x000D_
  <script src="datepicker-cs.js"></script>_x000D_
  <script type="text/javascript">_x000D_
    $(document).ready(function() {_x000D_
      console.log("test");_x000D_
      $("#test").datepicker({_x000D_
        dateFormat: "dd.m.yy",_x000D_
        minDate: 0,_x000D_
        showOtherMonths: true,_x000D_
        firstDay: 1_x000D_
      });_x000D_
    });_x000D_
  </script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <h1>Here is your datepicker</h1>_x000D_
  <input id="test" type="text" />_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Creating a JavaScript cookie on a domain and reading it across sub domains

You want:

document.cookie = cookieName +"=" + cookieValue + ";domain=.example.com;path=/;expires=" + myDate;

As per the RFC 2109, to have a cookie available to all subdomains, you must put a . in front of your domain.

Setting the path=/ will have the cookie be available within the entire specified domain(aka .example.com).

Bootstrap 3, 4 and 5 .container-fluid with grid adding unwanted padding

So here is the brief summary for Bootstrap 4:

<div class="container-fluid px-0">
  <div class="row no-gutters">
    <div class="col-12">          //any cols you need
        ...
    </div>
  </div>
</div>

It works for me.

How to access my localhost from another PC in LAN?

after your pc connects to other pc use these 4 step:
4 steps:
1- Edit this file: httpd.conf
for that click on wamp server and select Apache and select httpd.conf
2- Find this text: Deny from all
in the below tag:

  <Directory "c:/wamp/www"><!-- maybe other url-->

    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   AllowOverride FileInfo AuthConfig Limit
    #
    AllowOverride All

    #
    # Controls who can get stuff from this server.
    #
#    Require all granted
#   onlineoffline tag - don't remove
     Order Deny,Allow
    Deny from all
     Allow from 127.0.0.1
     Allow from ::1
     Allow from localhost
</Directory>

3- Change to: Deny from none
like this:

<Directory "c:/wamp/www">

    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   AllowOverride FileInfo AuthConfig Limit
    #
    AllowOverride All

    #
    # Controls who can get stuff from this server.
    #
#    Require all granted
#   onlineoffline tag - don't remove
     Order Deny,Allow
    Deny from none
     Allow from 127.0.0.1
     Allow from ::1
     Allow from localhost

4- Restart Apache
Don't forget restart Apache or all servises!!!

How to determine if .NET Core is installed

It doesn't need a installation process.

I have pinned "VSCore" on my taskbar (win10), so open it, and open a task manager choose "Visual Studio Core" process expand left arrow and over any of them child process right button over it and click in "Open File Location" menu.

If you don't remember where is installed search "Code.exe" file in all your hard drives.

Aborting a shell script if any command returns a non-zero value

I am just throwing in another one for reference since there was an additional question to Mark Edgars input and here is an additional example and touches on the topic overall:

[[ `cmd` ]] && echo success_else_silence

Which is the same as cmd || exit errcode as someone showed.

For example, I want to make sure a partition is unmounted if mounted:

[[ `mount | grep /dev/sda1` ]] && umount /dev/sda1

How do I find the mime-type of a file with php?

i got very good results using a user function from http://php.net/manual/de/function.mime-content-type.php @''john dot howard at prismmg dot com 26-Oct-2009 03:43''

function get_mime_type($filename, $mimePath = '../etc') { ...

which doesnt use finfo, exec or deprecated function

works well also with remote ressources!

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

In the simplest terms, git pull does a git fetch followed by a git merge.

You can do a git fetch at any time to update your remote-tracking branches under refs/remotes/<remote>/.

This operation never changes any of your own local branches under refs/heads, and is safe to do without changing your working copy. I have even heard of people running git fetch periodically in a cron job in the background (although I wouldn't recommend doing this).

A git pull is what you would do to bring a local branch up-to-date with its remote version, while also updating your other remote-tracking branches.

From the Git documentation for git pull:

In its default mode, git pull is shorthand for git fetch followed by git merge FETCH_HEAD.

How to start IIS Express Manually

There is not a program but you can make a batch file and run a command like that :

powershell "start-process 'C:\Program Files (x86)\IIS Express\iisexpress.exe' -workingdirectory 'C:\Program Files (x86)\IIS Express\' -windowstyle Hidden"

Store a cmdlet's result value in a variable in Powershell

Use the -ExpandProperty flag of Select-Object

$var=Get-WSManInstance -enumerate wmicimv2/win32_process | select -expand Priority

Update to answer the other question:

Note that you can as well just access the property:

$var=(Get-WSManInstance -enumerate wmicimv2/win32_process).Priority

So to get multiple of these into variables:

$var=Get-WSManInstance -enumerate wmicimv2/win32_process
   $prio = $var.Priority
   $pid = $var.ProcessID

PKIX path building failed in Java application

I ran into similar issues whose cause and solution turned out both to be rather simple:

Main Cause: Did not import the proper cert using keytool

NOTE: Only import root CA (or your own self-signed) certificates

NOTE: don't import an intermediate, non certificate chain root cert

Solution Example for imap.gmail.com

  1. Determine the root CA cert:

    openssl s_client -showcerts -connect imap.gmail.com:993
    

    in this case we find the root CA is Equifax Secure Certificate Authority

  2. Download root CA cert.
  3. Verify downloaded cert has proper SHA-1 and/or MD5 fingerprints by comparing with info found here
  4. Import cert for javax.net.ssl.trustStore:

    keytool -import -alias gmail_imap -file Equifax_Secure_Certificate_Authority.pem
    
  5. Run your java code

How to forward declare a template class in namespace std?

there is a limited alternative you can use

header:

class std_int_vector;

class A{
    std_int_vector* vector;
public:
    A();
    virtual ~A();
};

cpp:

#include "header.h"
#include <vector>
class std_int_vector: public std::vectror<int> {}

A::A() : vector(new std_int_vector()) {}
[...]

not tested in real programs, so expect it to be non-perfect.

docker error - 'name is already in use by container'

Here what i did, it works fine.

step 1:(it lists docker container with its name)

docker ps -a

step 2:

docker rm name_of_the_docker_container

Error: fix the version conflict (google-services plugin)

Please change your project-level build.gradle file in which you have to change your dependencies class path of google-services or build.gradle path.

buildscript {

    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.2'
        classpath 'com.google.gms:google-services:4.0.1'
    }
}

How do I force Robocopy to overwrite files?

From the documentation:

/is Includes the same files. /it Includes "tweaked" files.

"Same files" means files that are identical (name, size, times, attributes). "Tweaked files" means files that have the same name, size, and times, but different attributes.

robocopy src dst sample.txt /is      # copy if attributes are equal
robocopy src dst sample.txt /it      # copy if attributes differ
robocopy src dst sample.txt /is /it  # copy irrespective of attributes

This answer on Super User has a good explanation of what kind of files the selection parameters match.

With that said, I could reproduce the behavior you describe, but from my understanding of the documentation and the output robocopy generated in my tests I would consider this a bug.

PS C:\temp> New-Item src -Type Directory >$null
PS C:\temp> New-Item dst -Type Directory >$null
PS C:\temp> New-Item src\sample.txt -Type File -Value "test001" >$null
PS C:\temp> New-Item dst\sample.txt -Type File -Value "test002" >$null
PS C:\temp> Set-ItemProperty src\sample.txt -Name LastWriteTime -Value "2016/1/1 15:00:00"
PS C:\temp> Set-ItemProperty dst\sample.txt -Name LastWriteTime -Value "2016/1/1 15:00:00"
PS C:\temp> robocopy src dst sample.txt /is /it /copyall /mir
...
  Options : /S /E /COPYALL /PURGE /MIR /IS /IT /R:1000000 /W:30

------------------------------------------------------------------------------

                           1    C:\temp\src\
            Modified                   7        sample.txt

------------------------------------------------------------------------------

               Total    Copied   Skipped  Mismatch    FAILED    Extras
    Dirs :         1         0         0         0         0         0
   Files :         1         1         0         0         0         0
   Bytes :         7         7         0         0         0         0
...
PS C:\temp> robocopy src dst sample.txt /is /it /copyall /mir
...
  Options : /S /E /COPYALL /PURGE /MIR /IS /IT /R:1000000 /W:30

------------------------------------------------------------------------------

                           1    C:\temp\src\
            Same                       7        sample.txt

------------------------------------------------------------------------------

               Total    Copied   Skipped  Mismatch    FAILED    Extras
    Dirs :         1         0         0         0         0         0
   Files :         1         1         0         0         0         0
   Bytes :         7         7         0         0         0         0
...
PS C:\temp> Get-Content .\src\sample.txt
test001
PS C:\temp> Get-Content .\dst\sample.txt
test002

The file is listed as copied, and since it becomes a same file after the first robocopy run at least the times are synced. However, even though seven bytes have been copied according to the output no data was actually written to the destination file in both cases despite the data flag being set (via /copyall). The behavior also doesn't change if the data flag is set explicitly (/copy:d).

I had to modify the last write time to get robocopy to actually synchronize the data.

PS C:\temp> Set-ItemProperty src\sample.txt -Name LastWriteTime -Value (Get-Date)
PS C:\temp> robocopy src dst sample.txt /is /it /copyall /mir
...
  Options : /S /E /COPYALL /PURGE /MIR /IS /IT /R:1000000 /W:30

------------------------------------------------------------------------------

                           1    C:\temp\src\
100%        Newer                      7        sample.txt

------------------------------------------------------------------------------

               Total    Copied   Skipped  Mismatch    FAILED    Extras
    Dirs :         1         0         0         0         0         0
   Files :         1         1         0         0         0         0
   Bytes :         7         7         0         0         0         0
...
PS C:\temp> Get-Content .\dst\sample.txt
test001

An admittedly ugly workaround would be to change the last write time of same/tweaked files to force robocopy to copy the data:

& robocopy src dst /is /it /l /ndl /njh /njs /ns /nc |
  Where-Object { $_.Trim() } |
  ForEach-Object {
    $f = Get-Item $_
    $f.LastWriteTime = $f.LastWriteTime.AddSeconds(1)
  }
& robocopy src dst /copyall /mir

Switching to xcopy is probably your best option:

& xcopy src dst /k/r/e/i/s/c/h/f/o/x/y

SQL: How to to SUM two values from different tables

you can also try this in sql-server !!

select a.city,a.total + b.total as mytotal from [dbo].[cash] a join [dbo].[cheque] b on a.city=b.city 

demo

or try using sum,union

select sum(total)  as mytotal,city
from
(
    select * from cash union
    select * from cheque
) as vij
group by city 

How to uninstall Apache with command line

I've had this sort of problem.....

The solve: cmd / powershell run as ADMINISTRATOR! I always forget.

Notice: In powershell, you need to put .\ for example:

.\httpd -k shutdown .\httpd -k stop .\httpd -k uninstall

Result: Removing the apache2.4 service The Apache2.4 service has been removed successfully.

How do I abort/cancel TPL Tasks?

Task are being executed on the ThreadPool (at least, if you are using the default factory), so aborting the thread cannot affect the tasks. For aborting tasks, see Task Cancellation on msdn.

Button background as transparent

use #0000 (only four zeros otherwise it will be considered as black) this is the color code for transparent. You can use it directly but I recommend you to define a color in color.xml so you can enjoy re-usefullness of the code.

No value accessor for form control

For UnitTest angular 2 with angular material you have to add MatSelectModule module in imports section.

import { MatSelectModule } from '@angular/material';

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ CreateUserComponent ],
      imports : [ReactiveFormsModule,        
        MatSelectModule,
        MatAutocompleteModule,......

      ],
      providers: [.........]
    })
    .compileComponents();
  }));

Unsupported Media Type in postman

You need to set the content-type in postman as JSON (application/json).

Go to the body inside your POST request, there you will find the raw option.

Right next to it, there will be a drop down, select JSON (application.json).

Understanding the set() function

As an unordered collection type, set([8, 1, 6]) is equivalent to set([1, 6, 8]).

While it might be nicer to display the set contents in sorted order, that would make the repr() call more expensive.

Internally, the set type is implemented using a hash table: a hash function is used to separate items into a number of buckets to reduce the number of equality operations needed to check if an item is part of the set.

To produce the repr() output it just outputs the items from each bucket in turn, which is unlikely to be the sorted order.

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

All the three syntax work very well.

Another way is to first write

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

and then passing it to os.chdir(path)

In CSS what is the difference between "." and "#" when declaring a set of styles?

It is also worth noting that in the cascade, an id (#) selector is more specific than a b (.) selector. Therefore, rules in the id statement will override rules in the class statement.

For example, if both of the following statements:

.headline {
  color:red;
  font-size: 3em;
}

#specials {
  color:blue;
  font-style: italic;
}

are applied to the same HTML element:

<h1 id="specials" class="headline">Today's Specials</h1>

the color:blue rule would override the color:red rule.

CSS Transition doesn't work with top, bottom, left, right

Something that is not relevant for the OP, but maybe for someone else in the future:

For pixels (px), if the value is "0", the unit can be omitted: right: 0 and right: 0px both work.

However I noticed that in Firefox and Chrome this is not the case for the seconds unit (s). While transition: right 1s ease 0s works, transition: right 1s ease 0 (missing unit s for last value transition-delay) does not (it does work in Edge however).

In the following example, you'll see that right works for both 0px and 0, but transition only works for 0s and it doesn't work with 0.

_x000D_
_x000D_
#box {_x000D_
    border: 1px solid black;_x000D_
    height: 240px;_x000D_
    width: 260px;_x000D_
    margin: 50px;_x000D_
    position: relative;_x000D_
}_x000D_
.jump {_x000D_
    position: absolute;_x000D_
    width: 200px;_x000D_
    height: 50px;_x000D_
    color: white;_x000D_
    padding: 5px;_x000D_
}_x000D_
#jump1 {_x000D_
    background-color: maroon;_x000D_
    top: 0px;_x000D_
    right: 0px;_x000D_
    transition: right 1s ease 0s;_x000D_
}_x000D_
#jump2 {_x000D_
    background-color: green;_x000D_
    top: 60px;_x000D_
    right: 0;_x000D_
    transition: right 1s ease 0s;_x000D_
}_x000D_
#jump3 {_x000D_
    background-color: blue;_x000D_
    top: 120px;_x000D_
    right: 0px;_x000D_
    transition: right 1s ease 0;_x000D_
}_x000D_
#jump4 {_x000D_
    background-color: gray;_x000D_
    top: 180px;_x000D_
    right: 0;_x000D_
    transition: right 1s ease 0;_x000D_
}_x000D_
#box:hover .jump {_x000D_
    right: 50px;_x000D_
}
_x000D_
<div id="box">_x000D_
  <div class="jump" id="jump1">right: 0px<br>transition: right 1s ease 0s</div>_x000D_
  <div class="jump" id="jump2">right: 0<br>transition: right 1s ease 0s</div>_x000D_
  <div class="jump" id="jump3">right: 0px<br>transition: right 1s ease 0</div>_x000D_
  <div class="jump" id="jump4">right: 0<br>transition: right 1s ease 0</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Java ResultSet how to check if there are any results

Why not use rs.getRow()?

int getRow()
           throws SQLException
Retrieves the current row number. The first row is number 1, the second number 2, and so on.
Note:Support for the getRow method is optional for ResultSets with a result set type of TYPE_FORWARD_ONLY

Returns:
the current row number; 0 if there is no current row
Throws:
SQLException - if a database access error occurs or this method is called on a closed result set
SQLFeatureNotSupportedException - if the JDBC driver does not support this method
Since:
1.2

For me check "if (rs.getRow() != 0)" seems to work just fine.

How do I set environment variables from Java?

This is the Kotlin evil version of the @pushy's evil answer =)

@Suppress("UNCHECKED_CAST")
@Throws(Exception::class)
fun setEnv(newenv: Map<String, String>) {
    try {
        val processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment")
        val theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment")
        theEnvironmentField.isAccessible = true
        val env = theEnvironmentField.get(null) as MutableMap<String, String>
        env.putAll(newenv)
        val theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment")
        theCaseInsensitiveEnvironmentField.isAccessible = true
        val cienv = theCaseInsensitiveEnvironmentField.get(null) as MutableMap<String, String>
        cienv.putAll(newenv)
    } catch (e: NoSuchFieldException) {
        val classes = Collections::class.java.getDeclaredClasses()
        val env = System.getenv()
        for (cl in classes) {
            if ("java.util.Collections\$UnmodifiableMap" == cl.getName()) {
                val field = cl.getDeclaredField("m")
                field.setAccessible(true)
                val obj = field.get(env)
                val map = obj as MutableMap<String, String>
                map.clear()
                map.putAll(newenv)
            }
        }
    }

It is working in macOS Mojave at least.

Installing tkinter on ubuntu 14.04

First, make sure you have Tkinter module installed.

sudo apt-get install python-tk

In python 2 the package name is Tkinter not tkinter.

from Tkinter import *

ref: http://www.techinfected.net/2015/09/how-to-install-and-use-tkinter-in-ubuntu-debian-linux-mint.html

iOS - UIImageView - how to handle UIImage image orientation

I converted the code from @Nicolas Miari answer to Swift 3 in case anybody needs it

func fixOrientation() -> UIImage
{

    if self.imageOrientation == UIImageOrientation.up {
        return self
    }

    var transform = CGAffineTransform.identity

    switch self.imageOrientation {
    case .down, .downMirrored:
        transform = transform.translatedBy(x: self.size.width, y: self.size.height)
        transform = transform.rotated(by: CGFloat(M_PI));

    case .left, .leftMirrored:
        transform = transform.translatedBy(x: self.size.width, y: 0);
        transform = transform.rotated(by: CGFloat(M_PI_2));

    case .right, .rightMirrored:
        transform = transform.translatedBy(x: 0, y: self.size.height);
        transform = transform.rotated(by: CGFloat(-M_PI_2));

    case .up, .upMirrored:
        break
    }


    switch self.imageOrientation {

    case .upMirrored, .downMirrored:
        transform = transform.translatedBy(x: self.size.width, y: 0)
        transform = transform.scaledBy(x: -1, y: 1)

    case .leftMirrored, .rightMirrored:
        transform = transform.translatedBy(x: self.size.height, y: 0)
        transform = transform.scaledBy(x: -1, y: 1);

    default:
        break;
    }

    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    let ctx = CGContext(
        data: nil,
        width: Int(self.size.width),
        height: Int(self.size.height),
        bitsPerComponent: self.cgImage!.bitsPerComponent,
        bytesPerRow: 0,
        space: self.cgImage!.colorSpace!,
        bitmapInfo: UInt32(self.cgImage!.bitmapInfo.rawValue)
    )



    ctx!.concatenate(transform);

    switch self.imageOrientation {

    case .left, .leftMirrored, .right, .rightMirrored:
        // Grr...
        ctx?.draw(self.cgImage!, in: CGRect(x:0 ,y: 0 ,width: self.size.height ,height:self.size.width))

    default:
        ctx?.draw(self.cgImage!, in: CGRect(x:0 ,y: 0 ,width: self.size.width ,height:self.size.height))
        break;
    }

    // And now we just create a new UIImage from the drawing context
    let cgimg = ctx!.makeImage()

    let img = UIImage(cgImage: cgimg!)

    return img;

}

How to export table data in MySql Workbench to csv?

MySQL Workbench 6.3.6

Export the SELECT result

  • After you run a SELECT: Query > Export Results...

    Query Export Results

Export table data

  • In the Navigator, right click on the table > Table Data Export Wizard

    Table Data Export

  • All columns and rows are included by default, so click on Next.

  • Select File Path, type, Field Separator (by default it is ;, not ,!!!) and click on Next.

    CSV

  • Click Next > Next > Finish and the file is created in the specified location

Exception in thread "main" java.util.NoSuchElementException

simply don't close in

remove in.close() from your code.

What is the difference between decodeURIComponent and decodeURI?

To explain the difference between these two let me explain the difference between encodeURI and encodeURIComponent.

The main difference is that:

  • The encodeURI function is intended for use on the full URI.
  • The encodeURIComponent function is intended to be used on .. well .. URI components that is any part that lies between separators (; / ? : @ & = + $ , #).

So, in encodeURIComponent these separators are encoded also because they are regarded as text and not special characters.

Now back to the difference between the decode functions, each function decodes strings generated by its corresponding encode counterpart taking care of the semantics of the special characters and their handling.

How to bundle vendor scripts separately and require them as needed with Webpack?

in my webpack.config.js (Version 1,2,3) file, I have

function isExternal(module) {
  var context = module.context;

  if (typeof context !== 'string') {
    return false;
  }

  return context.indexOf('node_modules') !== -1;
}

in my plugins array

plugins: [
  new CommonsChunkPlugin({
    name: 'vendors',
    minChunks: function(module) {
      return isExternal(module);
    }
  }),
  // Other plugins
]

Now I have a file that only adds 3rd party libs to one file as required.

If you want get more granular where you separate your vendors and entry point files:

plugins: [
  new CommonsChunkPlugin({
    name: 'common',
    minChunks: function(module, count) {
      return !isExternal(module) && count >= 2; // adjustable
    }
  }),
  new CommonsChunkPlugin({
    name: 'vendors',
    chunks: ['common'],
    // or if you have an key value object for your entries
    // chunks: Object.keys(entry).concat('common')
    minChunks: function(module) {
      return isExternal(module);
    }
  })
]

Note that the order of the plugins matters a lot.

Also, this is going to change in version 4. When that's official, I update this answer.

Update: indexOf search change for windows users

Centering floating divs within another div

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

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

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

How to detect a mobile device with JavaScript?

Since it's now 2015, if you stumbled across this question then you should probably be using window.matchMedia (and, if it's still 2015, polyfilling for older browsers):

if (matchMedia('handheld').matches) {
    //...
} else {
    //...
}

How do you implement a re-try-catch?

Below snippet execute some code snippet. If you got any error while executing the code snippet, sleep for M milliseconds and retry. Reference link.

public void retryAndExecuteErrorProneCode(int noOfTimesToRetry, CodeSnippet codeSnippet, int sleepTimeInMillis)
  throws InterruptedException {

 int currentExecutionCount = 0;
 boolean codeExecuted = false;

 while (currentExecutionCount < noOfTimesToRetry) {
  try {
   codeSnippet.errorProneCode();
   System.out.println("Code executed successfully!!!!");
   codeExecuted = true;
   break;
  } catch (Exception e) {
   // Retry after 100 milliseconds
   TimeUnit.MILLISECONDS.sleep(sleepTimeInMillis);
   System.out.println(e.getMessage());
  } finally {
   currentExecutionCount++;
  }
 }

 if (!codeExecuted)
  throw new RuntimeException("Can't execute the code within given retries : " + noOfTimesToRetry);
}

Expansion of variables inside single quotes in a command in Bash

Below is what worked for me -

QUOTE="'"
hive -e "alter table TBL_NAME set location $QUOTE$TBL_HDFS_DIR_PATH$QUOTE"

Setting dynamic scope variables in AngularJs - scope.<some_string>

The solution I have found is to use $parse.

"Converts Angular expression into a function."

If anyone has a better one please add a new answer to the question!

Here is the example:

var the_string = 'life.meaning';

// Get the model
var model = $parse(the_string);

// Assigns a value to it
model.assign($scope, 42);

// Apply it to the scope
// $scope.$apply(); <- According to comments, this is no longer needed

console.log($scope.life.meaning);  // logs 42

Which Python memory profiler is recommended?

Try also the pytracemalloc project which provides the memory usage per Python line number.

EDIT (2014/04): It now has a Qt GUI to analyze snapshots.

Get full path without filename from path that includes filename

Use GetParent() as shown, works nicely. Add error checking as you need.

var fn = openFileDialogSapTable.FileName;
var currentPath = Path.GetFullPath( fn );
currentPath = Directory.GetParent(currentPath).FullName;

Android: Clear Activity Stack

For Xamarin Developers, you can use:

intent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);

Getting URL hash location, and using it in jQuery

I would suggest better cek first if the current page has a hash. Otherwise it will be undefined.

$(window).on('load', function(){        
    if( location.hash && location.hash.length ) {
       var hash = decodeURIComponent(location.hash.substr(1));
       $('ul'+hash+':first').show();;
    }       
});

PHP Fatal error when trying to access phpmyadmin mb_detect_encoding

I had the same trouble, this is what worked for me.

You can click at the wampserver icon, then at the PHP error log. Check if it says this: Unable to load dynamic library 'c:/wamp/bin/php/php5.5.12/ext/php_ldap.dll'

If yes, then you can reload your version of PHP, by clicking at the wampserver icon, then PHP, then version, and then you click at your version. Wait for everything to be online again, then try to access phpmyadmin.

Cordova app not displaying correctly on iPhone X (Simulator)

If you install newer versions of ionic globally you can run ionic cordova resources and it will generate all of the splashscreen images for you along with the correct sizes.

Append a Lists Contents to another List C#

GlobalStrings.AddRange(localStrings);

Note: You cannot declare the list object using the interface (IList).
Documentation: List<T>.AddRange(IEnumerable<T>).

How to make 'submit' button disabled?

Form validation is very much straight forward in Angular 2

Here is an example,

<form (ngSubmit)="onSubmit()" #myForm="ngForm">

 <div class="form-group">
  <label for="firstname">First Name</label>
  <input type="text" class="form-control" id="firstname" 
   required [(ngModel)]="firstname" name="firstname">
 </div>

 <div class="form-group">
  <label for="middlename">Middle Name</label>
  <input type="text"  class="form-control" id="middlename" 
   [(ngModel)]="middlename" name="middlename">
 </div>

 <div class="form-group">
  <label for="lastname">Last Name</label>
  <input type="text"  class="form-control" id="lastname" 
   required minlength = '2' maxlength="6" [(ngModel)] = "lastname" name="lastname">
 </div>

 <div class="form-group">
  <label for="mobnumber">Mob Number</label>
  <input type="text"  class="form-control" id="mobnumber"  
   minlength = '2' maxlength="10" pattern="^[0-9()\-+\s]+$" 
   [(ngModel)] = "mobnumber" name="mobnumber">
 </div>

 <button type="submit" [disabled]="!myForm.form.valid">Submit</button>

</form>

Check this plunker for demo

More info

Access all Environment properties as a Map or Properties object

You need something like this, maybe it can be improved. This is a first attempt:

...
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.AbstractEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
...

@Configuration
...
@org.springframework.context.annotation.PropertySource("classpath:/config/default.properties")
...
public class GeneralApplicationConfiguration implements WebApplicationInitializer 
{
    @Autowired
    Environment env;

    public void someMethod() {
        ...
        Map<String, Object> map = new HashMap();
        for(Iterator it = ((AbstractEnvironment) env).getPropertySources().iterator(); it.hasNext(); ) {
            PropertySource propertySource = (PropertySource) it.next();
            if (propertySource instanceof MapPropertySource) {
                map.putAll(((MapPropertySource) propertySource).getSource());
            }
        }
        ...
    }
...

Basically, everything from the Environment that's a MapPropertySource (and there are quite a lot of implementations) can be accessed as a Map of properties.

Use multiple css stylesheets in the same html page

You never refer to a specific style sheet. All CSS rules in a document are internally fused into one.

In the case of rules in both style sheets that apply to the same element with the same specificity, the style sheet embedded later will override the earlier one.

You can use an element inspector like Firebug to see which rules apply, and which ones are overridden by others.

sql server convert date to string MM/DD/YYYY

That task should be done by the next layer up in your software stack. SQL is a data repository, not a presentation system

You can do it with

CONVERT(VARCHAR(10), fmdate(), 101)

But you shouldn't

Any way to return PHP `json_encode` with encode UTF-8 and not Unicode?

just use this,

utf8_encode($string);

you've to replace your $arr with $string.

I think it will work...try this.

How do I calculate r-squared using Python and Numpy?

Here's a very simple python function to compute R^2 from the actual and predicted values assuming y and y_hat are pandas series:

def r_squared(y, y_hat):
    y_bar = y.mean()
    ss_tot = ((y-y_bar)**2).sum()
    ss_res = ((y-y_hat)**2).sum()
    return 1 - (ss_res/ss_tot)

Get custom product attributes in Woocommerce

Although @airdrumz solutions works, you will get lots of errors about you doing it wrong by accessing ID directly, this is not good for future compatibility.

But it lead me to inspect the object and create this OOP approach:

function myplug_get_prod_attrs() {
    // Enqueue scripts happens very early, global $product has not been created yet, neither has the post/loop
    global $product;
    $wc_attr_objs = $product->get_attributes();
    $prod_attrs = [];
    foreach ($wc_attr_objs as $wc_attr => $wc_term_objs) {
        $prod_attrs[$wc_attr] = [];
        $wc_terms = $wc_term_objs->get_terms();
        foreach ($wc_terms as $wc_term) {
            array_push($prod_attrs[$wc_attr], $wc_term->slug);
        }
    }
    return $prod_attrs;
}

Bonus, if you are performing the above early before the global $product item is created (e.g. during enqueue scripts), you can make it yourself with:

    $product = wc_get_product(get_queried_object_id());

How do I set up Visual Studio Code to compile C++ code?

There is a much easier way to compile and run C++ code, no configuration needed:

  1. Install the Code Runner Extension
  2. Open your C++ code file in Text Editor, then use shortcut Ctrl+Alt+N, or press F1 and then select/type Run Code, or right click the Text Editor and then click Run Code in context menu, the code will be compiled and run, and the output will be shown in the Output Window.

Moreover you could update the config in settings.json using different C++ compilers as you want, the default config for C++ is as below:

"code-runner.executorMap": {
    "cpp": "g++ $fullFileName && ./a.out"
}

What can cause a “Resource temporarily unavailable” on sock send() command

Let'e me give an example:

  1. client connect to server, and send 1MB data to server every 1 second.

  2. server side accept a connection, and then sleep 20 second, without recv msg from client.So the tcp send buffer in the client side will be full.

Code in client side:

#include <arpa/inet.h>
#include <sys/socket.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#define exit_if(r, ...)                                                                          \
    if (r) {                                                                                     \
        printf(__VA_ARGS__);                                                                     \
        printf("%s:%d error no: %d error msg %s\n", __FILE__, __LINE__, errno, strerror(errno)); \
        exit(1);                                                                                 \
    }

void setNonBlock(int fd) {
    int flags = fcntl(fd, F_GETFL, 0);
    exit_if(flags < 0, "fcntl failed");
    int r = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
    exit_if(r < 0, "fcntl failed");
}

void test_full_sock_buf_1(){
    short port = 8000;
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof addr);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = INADDR_ANY;


    int fd = socket(AF_INET, SOCK_STREAM, 0);
    exit_if(fd<0, "create socket error");

    int ret = connect(fd, (struct sockaddr *) &addr, sizeof(struct sockaddr));
    exit_if(ret<0, "connect to server error");
    setNonBlock(fd);

    printf("connect to server success");

    const int LEN = 1024 * 1000;
    char msg[LEN];  // 1MB data
    memset(msg, 'a', LEN);

    for (int i = 0; i < 1000; ++i) {
        int len = send(fd, msg, LEN, 0);
        printf("send: %d, erron: %d, %s \n", len, errno, strerror(errno));
        sleep(1);
    }

}

int main(){
    test_full_sock_buf_1();

    return 0;
}

Code in server side:

    #include <arpa/inet.h>
    #include <sys/socket.h>
    #include <stdio.h>
    #include <errno.h>
    #include <fcntl.h>
    #include <stdlib.h>
    #include <string.h>
    #define exit_if(r, ...)                                                                          \
        if (r) {                                                                                     \
            printf(__VA_ARGS__);                                                                     \
            printf("%s:%d error no: %d error msg %s\n", __FILE__, __LINE__, errno, strerror(errno)); \
            exit(1);                                                                                 \
        }
void test_full_sock_buf_1(){

    int listenfd = socket(AF_INET, SOCK_STREAM, 0);
    exit_if(listenfd<0, "create socket error");

    short port = 8000;
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof addr);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = INADDR_ANY;

    int r = ::bind(listenfd, (struct sockaddr *) &addr, sizeof(struct sockaddr));
    exit_if(r<0, "bind socket error");

    r = listen(listenfd, 100);
    exit_if(r<0, "listen socket error");

    struct sockaddr_in raddr;
    socklen_t rsz = sizeof(raddr);
    int cfd = accept(listenfd, (struct sockaddr *) &raddr, &rsz);
    exit_if(cfd<0, "accept socket error");

    sockaddr_in peer;
    socklen_t alen = sizeof(peer);
    getpeername(cfd, (sockaddr *) &peer, &alen);

    printf("accept a connection from %s:%d\n", inet_ntoa(peer.sin_addr), ntohs(peer.sin_port));

    printf("but now I will sleep 15 second, then exit");
    sleep(15);
}

Start server side, then start client side.

server side may output:

accept a connection from 127.0.0.1:35764
but now I will sleep 15 second, then exit
Process finished with exit code 0

enter image description here

client side may output:

connect to server successsend: 1024000, erron: 0, Success 
send: 1024000, erron: 0, Success 
send: 1024000, erron: 0, Success 
send: 552190, erron: 0, Success 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 104, Connection reset by peer 
send: -1, erron: 32, Broken pipe 
send: -1, erron: 32, Broken pipe 
send: -1, erron: 32, Broken pipe 
send: -1, erron: 32, Broken pipe 
send: -1, erron: 32, Broken pipe 

enter image description here

You can see, as the server side doesn't recv the data from client, so when the client side tcp buffer get full, but you still send data, so you may get Resource temporarily unavailable error.

What properties can I use with event.target?

If you were to inspect the event.target with firebug or chrome's developer tools you would see for a span element (e.g. the following properties) it will have whatever properties any element has. It depends what the target element is:

event.target: HTMLSpanElement

attributes: NamedNodeMap
baseURI: "file:///C:/Test.html"
childElementCount: 0
childNodes: NodeList[1]
children: HTMLCollection[0]
classList: DOMTokenList
className: ""
clientHeight: 36
clientLeft: 1
clientTop: 1
clientWidth: 1443
contentEditable: "inherit"
dataset: DOMStringMap
dir: ""
draggable: false
firstChild: Text
firstElementChild: null
hidden: false
id: ""
innerHTML: "click"
innerText: "click"
isContentEditable: false
lang: ""
lastChild: Text
lastElementChild: null
localName: "span"
namespaceURI: "http://www.w3.org/1999/xhtml"
nextElementSibling: null
nextSibling: null
nodeName: "SPAN"
nodeType: 1
nodeValue: null
offsetHeight: 38
offsetLeft: 26
offsetParent: HTMLBodyElement
offsetTop: 62
offsetWidth: 1445
onabort: null
onbeforecopy: null
onbeforecut: null
onbeforepaste: null
onblur: null
onchange: null
onclick: null
oncontextmenu: null
oncopy: null
oncut: null
ondblclick: null
ondrag: null
ondragend: null
ondragenter: null
ondragleave: null
ondragover: null
ondragstart: null
ondrop: null
onerror: null
onfocus: null
oninput: null
oninvalid: null
onkeydown: null
onkeypress: null
onkeyup: null
onload: null
onmousedown: null
onmousemove: null
onmouseout: null
onmouseover: null
onmouseup: null
onmousewheel: null
onpaste: null
onreset: null
onscroll: null
onsearch: null
onselect: null
onselectstart: null
onsubmit: null
onwebkitfullscreenchange: null
outerHTML: "<span>click</span>"
outerText: "click"
ownerDocument: HTMLDocument
parentElement: HTMLElement
parentNode: HTMLElement
prefix: null
previousElementSibling: null
previousSibling: null
scrollHeight: 36
scrollLeft: 0
scrollTop: 0
scrollWidth: 1443
spellcheck: true
style: CSSStyleDeclaration
tabIndex: -1
tagName: "SPAN"
textContent: "click"
title: ""
webkitdropzone: ""
__proto__: HTMLSpanElement

The application may be doing too much work on its main thread

Optimize your images ... Dont use images larger than 100KB ... Image loading takes too much CPU and cause your app hangs .

Slide up/down effect with ng-show and ng-animate

This class-based javascript animation works in AngularJS 1.2 (and 1.4 tested)

Edit: I ended up abandoning this code and went a completely different direction. I like my other answer much better. This answer will give you some problems in certain situations.

myApp.animation('.ng-show-toggle-slidedown', function(){
  return {
    beforeAddClass : function(element, className, done){
        if (className == 'ng-hide'){
            $(element).slideUp({duration: 400}, done);
        } else {done();}
    },
    beforeRemoveClass :  function(element, className, done){
        if (className == 'ng-hide'){
            $(element).css({display:'none'});
            $(element).slideDown({duration: 400}, done);
        } else {done();}
    }
}

});

Simply add the .ng-hide-toggle-slidedown class to the container element, and the jQuery slide down behavior will be implemented based on the ng-hide class.

You must include the $(element).css({display:'none'}) line in the beforeRemoveClass method because jQuery will not execute a slideDown unless the element is in a state of display: none prior to starting the jQuery animation. AngularJS uses the CSS

.ng-hide:not(.ng-hide-animate) {
    display: none !important;
}

to hide the element. jQuery is not aware of this state, and jQuery will need the display:none prior to the first slide down animation.

The AngularJS animation will add the .ng-hide-animate and .ng-animate classes while the animation is occuring.

Load local HTML file in a C# WebBrowser

Update on @ghostJago answer above

for me it worked as the following lines in VS2017

string curDir = Directory.GetCurrentDirectory();
this.webBrowser1.Navigate(new Uri(String.Format("file:///{0}/my_html.html", curDir)));

Build an iOS app without owning a mac?

You can use Phonegap (Cordova) to develop iOS Apps without a Mac, but yout would still need a Mac to submit your application to the App Store. We developed a cloud application which also can publish your app without a Mac https://www.wenz.io/ApplicationLoader. Currently we are in beta and you can use the service for free.

Best regards, Steffen Wenz

(I'm the creator of the site)

How to access parameters in a RESTful POST method

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

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

Then your @POST method would look like the following:

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

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

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

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

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


HTML <FORM>

The parameters would be annotated using @FormParam:

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

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

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

param1=hello&param2=world

The content is URL encoded in this case.

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

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

HTTP Headers

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

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

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

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

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


HTTP Query Parameters

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

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

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

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

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


HTTP Path Parameters

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

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

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

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

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


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

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

How to get row index number in R?

Perhaps this complementary example of "match" would be helpful.

Having two datasets:

first_dataset <- data.frame(name = c("John", "Luke", "Simon", "Gregory", "Mary"),
                            role = c("Audit", "HR", "Accountant", "Mechanic", "Engineer"))

second_dataset <- data.frame(name = c("Mary", "Gregory", "Luke", "Simon"))

If the name column contains only unique across collection values (across whole collection) then you can access row in other dataset by value of index returned by match

name_mapping <- match(second_dataset$name, first_dataset$name)

match returns proper row indexes of names in first_dataset from given names from second: 5 4 2 1 example here - accesing roles from first dataset by row index (by given name value)

for(i in 1:length(name_mapping)) {
    role <- as.character(first_dataset$role[name_mapping[i]])   
    second_dataset$role[i] = role
}

===

second dataset with new column:
     name       role
1    Mary   Engineer
2 Gregory   Mechanic
3    Luke Supervisor
4   Simon Accountant

How to preventDefault on anchor tags?

The easiest solution I have found is this one :

<a href="#" ng-click="do(); $event.preventDefault()">Click</a>

How to make a gui in python

While some suggestions have included tkinter and wxPython, the other part of the answer to your question is that you will also need to package it using something like py2app, pyinstaller, or py2exe (depending on the operating system). You mentioned the other machines do not have python, so this would be required in order to distribute the entire python environment with your app.

Also have a look at PySide or PyQt. They have a ton of tutorials everywhere and heavy documentation from Qt.

what is an illegal reflective access

There is an Oracle article I found regarding Java 9 module system

By default, a type in a module is not accessible to other modules unless it’s a public type and you export its package. You expose only the packages you want to expose. With Java 9, this also applies to reflection.

As pointed out in https://stackoverflow.com/a/50251958/134894, the differences between the AccessibleObject#setAccessible for JDK8 and JDK9 are instructive. Specifically, JDK9 added

This method may be used by a caller in class C to enable access to a member of declaring class D if any of the following hold:

  • C and D are in the same module.
  • The member is public and D is public in a package that the module containing D exports to at least the module containing C.
  • The member is protected static, D is public in a package that the module containing D exports to at least the module containing C, and C is a subclass of D.
  • D is in a package that the module containing D opens to at least the module containing C. All packages in unnamed and open modules are open to all modules and so this method always succeeds when D is in an unnamed or open module.

which highlights the significance of modules and their exports (in Java 9)

Check if an object belongs to a class in Java

Use the instanceof operator:

if(a instanceof MyClass)
{
    //do something
}

Getting vertical gridlines to appear in line plot in matplotlib

plt.gca().xaxis.grid(True) proved to be the solution for me

UITableView - change section header color

iOS 8+

func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        tableView.tableHeaderView?.backgroundColor = UIColor.blue()
}

In Java, remove empty elements from a list of Strings

Its a very late answer, but you can also use the Collections.singleton:

List<String> list = new ArrayList<String>(Arrays.asList("", "Hi", null, "How"));
list.removeAll(Collections.singleton(null));
list.removeAll(Collections.singleton(""));

Stop an input field in a form from being submitted

I just wanted to add an additional option: In your input add the form tag and specify the name of a form that doesn't exist on your page:

<input form="fakeForm" type="text" readonly value="random value" />

Android 'Unable to add window -- token null is not for an application' exception

I tried with this in the context field:

this.getActivity().getParent()

and it works fine for me. This was from a class which extends from "Fragment":

public class filtro extends Fragment{...

Append key/value pair to hash with << in Ruby

No, I don't think you can append key/value pairs. The only thing closest that I am aware of is using the store method:

h = {}
h.store("key", "value")

How to generate auto increment field in select query

DECLARE @id INT 
SET @id = 0 
UPDATE cartemp
SET @id = CarmasterID = @id + 1 
GO

How to define constants in ReactJS

You don't need to use anything but plain React and ES6 to achieve what you want. As per Jim's answer, just define the constant in the right place. I like the idea of keeping the constant local to the component if not needed externally. The below is an example of possible usage.

import React from "react";

const sizeToLetterMap = {
  small_square: 's',
  large_square: 'q',
  thumbnail: 't',
  small_240: 'm',
  small_320: 'n',
  medium_640: 'z',
  medium_800: 'c',
  large_1024: 'b',
  large_1600: 'h',
  large_2048: 'k',
  original: 'o'
};

class PhotoComponent extends React.Component {
  constructor(args) {
    super(args);
  }

  photoUrl(image, size_text) {
    return (<span>
      Image: {image}, Size Letter: {sizeToLetterMap[size_text]}
    </span>);
  }

  render() {
    return (
      <div className="photo-wrapper">
        The url is: {this.photoUrl(this.props.image, this.props.size_text)}
      </div>
    )
  }
}

export default PhotoComponent;

// Call this with <PhotoComponent image="abc.png" size_text="thumbnail" />
// Of course the component must first be imported where used, example:
// import PhotoComponent from "./photo_component.jsx";

Dynamically adding elements to ArrayList in Groovy

What you actually created with:

MyType[] list = []

Was fixed size array (not list) with size of 0. You can create fixed size array of size for example 4 with:

MyType[] array = new MyType[4]

But there's no add method of course.

If you create list with def it's something like creating this instance with Object (You can read more about def here). And [] creates empty ArrayList in this case.

So using def list = [] you can then append new items with add() method of ArrayList

list.add(new MyType())

Or more groovy way with overloaded left shift operator:

list << new MyType() 

SQL/mysql - Select distinct/UNIQUE but return all columns?

select min(table.id), table.column1
from table 
group by table.column1

How to load specific image from assets with Swift

Since swift 3.0 there is more convenient way: #imageLiterals here is text example. And below animated example from here:

enter image description here

Rails: FATAL - Peer authentication failed for user (PG::Error)

I also faced this same issue while working in my development environment, the problem was that I left host: localhost commented out in the config/database.yml file.

So my application could not connect to the PostgreSQL database, simply uncommenting it solved the issue.

development:
  <<: *default
  database: database_name

  username: database_username 

  password: database_password

  host: localhost

That's all.

I hope this helps

Updating GUI (WPF) using a different thread

You may use a delegate to solve this issue. Here is an example that is showing how to update a textBox using diffrent thread

public delegate void UpdateTextCallback(string message);

private void TestThread()
{
    for (int i = 0; i <= 1000000000; i++)
    {
        Thread.Sleep(1000);                
        richTextBox1.Dispatcher.Invoke(
            new UpdateTextCallback(this.UpdateText),
            new object[] { i.ToString() }
        );
    }
}
private void UpdateText(string message)
{
    richTextBox1.AppendText(message + "\n");
}

private void button1_Click(object sender, RoutedEventArgs e)
{
   Thread test = new Thread(new ThreadStart(TestThread));
   test.Start();
}

TestThread method is used by thread named test to update textBox

Ping all addresses in network, windows

I know this is a late response, but a neat way of doing this is to ping the broadcast address which populates your local arp cache.

This can then be shown by running arp -a which will list all the addresses in you local arp table.

ping 192.168.1.255
arp -a

Hopefully this is a nice neat option that people can use.

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 to preview a part of a large pandas DataFrame, in iPython notebook?

df.head(5) # will print out the first 5 rows
df.tail(5) # will print out the 5 last rows

How do I pick randomly from an array?

class String

  def black
    return "\e[30m#{self}\e[0m"
  end

  def red
    return "\e[31m#{self}\e[0m"
  end

  def light_green
    return "\e[32m#{self}\e[0m"
  end

  def purple
    return "\e[35m#{self}\e[0m"
  end

  def blue_dark
    return "\e[34m#{self}\e[0m"
  end

  def blue_light
    return "\e[36m#{self}\e[0m"
  end

  def white
    return "\e[37m#{self}\e[0m"
  end


  def randColor
    array_color = [
      "\e[30m#{self}\e[0m",
      "\e[31m#{self}\e[0m",
      "\e[32m#{self}\e[0m",
      "\e[35m#{self}\e[0m",
      "\e[34m#{self}\e[0m",
      "\e[36m#{self}\e[0m",
      "\e[37m#{self}\e[0m" ]

      return array_color[rand(0..array_color.size)]
  end


end
puts "black".black
puts "red".red
puts "light_green".light_green
puts "purple".purple
puts "dark blue".blue_dark
puts "light blue".blue_light
puts "white".white
puts "random color".randColor

Android ImageView's onClickListener does not work

Check if other view has the property match_parent or fill_parent ,those properties may cover your ImageView which has shown in your RelativeLayout.By the way,the accepted answer does not work in my case.

Oracle JDBC ojdbc6 Jar as a Maven Dependency

After executing

mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.3 -Dpackaging=jar -Dfile=ojdbc6.jar -DgeneratePom=true

check your .m2 repository folder (/com/oracle/ojdbc6/11.2.0.3) to see if ojdbc6.jar exists. If not check your maven repository settings under $M2_HOME/conf/settings.xml

Android: Storing username and password?

You should use the Android AccountManager. It's purpose-built for this scenario. It's a little bit cumbersome but one of the things it does is invalidate the local credentials if the SIM card changes, so if somebody swipes your phone and throws a new SIM in it, your credentials won't be compromised.

This also gives the user a quick and easy way to access (and potentially delete) the stored credentials for any account they have on the device, all from one place.

SampleSyncAdapter (like @Miguel mentioned) is an example that makes use of stored account credentials.

jQuery javascript regex Replace <br> with \n

Not really anything to do with jQuery, but if you want to trim a pattern from a string, then use a regular expression:

<textarea id="ta0"></textarea>
<button onclick="
  var ta = document.getElementById('ta0');
  var text = 'some<br>text<br />to<br/>replace';
  var re = /<br *\/?>/gi;
  ta.value = text.replace(re, '\n');
">Add stuff to text area</button>

Java stack overflow error - how to increase the stack size in Eclipse?

Open the Run Configuration for your application (Run/Run Configurations..., then look for the applications entry in 'Java application').

The arguments tab has a text box Vm arguments, enter -Xss1m (or a bigger parameter for the maximum stack size). The default value is 512 kByte (SUN JDK 1.5 - don't know if it varies between vendors and versions).

Android Get Current timestamp?

Solution in Kotlin:

val nowInEpoch = Instant.now().epochSecond

Make sure your minimum SDK version is 26.

iterating quickly through list of tuples

The question is dead but still knowing one more way doesn't hurt:

my_list = [ (old1, new1), (old2, new2), (old3, new3), ... (oldN, newN)]

for first,*args in my_list:
    if first == Value:
        PAIR_FOUND = True
        MATCHING_VALUE = args
        break

How to get the path of a running JAR file?

To obtain the File for a given Class, there are two steps:

  1. Convert the Class to a URL
  2. Convert the URL to a File

It is important to understand both steps, and not conflate them.

Once you have the File, you can call getParentFile to get the containing folder, if that is what you need.

Step 1: Class to URL

As discussed in other answers, there are two major ways to find a URL relevant to a Class.

  1. URL url = Bar.class.getProtectionDomain().getCodeSource().getLocation();

  2. URL url = Bar.class.getResource(Bar.class.getSimpleName() + ".class");

Both have pros and cons.

The getProtectionDomain approach yields the base location of the class (e.g., the containing JAR file). However, it is possible that the Java runtime's security policy will throw SecurityException when calling getProtectionDomain(), so if your application needs to run in a variety of environments, it is best to test in all of them.

The getResource approach yields the full URL resource path of the class, from which you will need to perform additional string manipulation. It may be a file: path, but it could also be jar:file: or even something nastier like bundleresource://346.fwk2106232034:4/foo/Bar.class when executing within an OSGi framework. Conversely, the getProtectionDomain approach correctly yields a file: URL even from within OSGi.

Note that both getResource("") and getResource(".") failed in my tests, when the class resided within a JAR file; both invocations returned null. So I recommend the #2 invocation shown above instead, as it seems safer.

Step 2: URL to File

Either way, once you have a URL, the next step is convert to a File. This is its own challenge; see Kohsuke Kawaguchi's blog post about it for full details, but in short, you can use new File(url.toURI()) as long as the URL is completely well-formed.

Lastly, I would highly discourage using URLDecoder. Some characters of the URL, : and / in particular, are not valid URL-encoded characters. From the URLDecoder Javadoc:

It is assumed that all characters in the encoded string are one of the following: "a" through "z", "A" through "Z", "0" through "9", and "-", "_", ".", and "*". The character "%" is allowed but is interpreted as the start of a special escaped sequence.

...

There are two possible ways in which this decoder could deal with illegal strings. It could either leave illegal characters alone or it could throw an IllegalArgumentException. Which approach the decoder takes is left to the implementation.

In practice, URLDecoder generally does not throw IllegalArgumentException as threatened above. And if your file path has spaces encoded as %20, this approach may appear to work. However, if your file path has other non-alphameric characters such as + you will have problems with URLDecoder mangling your file path.

Working code

To achieve these steps, you might have methods like the following:

/**
 * Gets the base location of the given class.
 * <p>
 * If the class is directly on the file system (e.g.,
 * "/path/to/my/package/MyClass.class") then it will return the base directory
 * (e.g., "file:/path/to").
 * </p>
 * <p>
 * If the class is within a JAR file (e.g.,
 * "/path/to/my-jar.jar!/my/package/MyClass.class") then it will return the
 * path to the JAR (e.g., "file:/path/to/my-jar.jar").
 * </p>
 *
 * @param c The class whose location is desired.
 * @see FileUtils#urlToFile(URL) to convert the result to a {@link File}.
 */
public static URL getLocation(final Class<?> c) {
    if (c == null) return null; // could not load the class

    // try the easy way first
    try {
        final URL codeSourceLocation =
            c.getProtectionDomain().getCodeSource().getLocation();
        if (codeSourceLocation != null) return codeSourceLocation;
    }
    catch (final SecurityException e) {
        // NB: Cannot access protection domain.
    }
    catch (final NullPointerException e) {
        // NB: Protection domain or code source is null.
    }

    // NB: The easy way failed, so we try the hard way. We ask for the class
    // itself as a resource, then strip the class's path from the URL string,
    // leaving the base path.

    // get the class's raw resource path
    final URL classResource = c.getResource(c.getSimpleName() + ".class");
    if (classResource == null) return null; // cannot find class resource

    final String url = classResource.toString();
    final String suffix = c.getCanonicalName().replace('.', '/') + ".class";
    if (!url.endsWith(suffix)) return null; // weird URL

    // strip the class's path from the URL string
    final String base = url.substring(0, url.length() - suffix.length());

    String path = base;

    // remove the "jar:" prefix and "!/" suffix, if present
    if (path.startsWith("jar:")) path = path.substring(4, path.length() - 2);

    try {
        return new URL(path);
    }
    catch (final MalformedURLException e) {
        e.printStackTrace();
        return null;
    }
} 

/**
 * Converts the given {@link URL} to its corresponding {@link File}.
 * <p>
 * This method is similar to calling {@code new File(url.toURI())} except that
 * it also handles "jar:file:" URLs, returning the path to the JAR file.
 * </p>
 * 
 * @param url The URL to convert.
 * @return A file path suitable for use with e.g. {@link FileInputStream}
 * @throws IllegalArgumentException if the URL does not correspond to a file.
 */
public static File urlToFile(final URL url) {
    return url == null ? null : urlToFile(url.toString());
}

/**
 * Converts the given URL string to its corresponding {@link File}.
 * 
 * @param url The URL to convert.
 * @return A file path suitable for use with e.g. {@link FileInputStream}
 * @throws IllegalArgumentException if the URL does not correspond to a file.
 */
public static File urlToFile(final String url) {
    String path = url;
    if (path.startsWith("jar:")) {
        // remove "jar:" prefix and "!/" suffix
        final int index = path.indexOf("!/");
        path = path.substring(4, index);
    }
    try {
        if (PlatformUtils.isWindows() && path.matches("file:[A-Za-z]:.*")) {
            path = "file:/" + path.substring(5);
        }
        return new File(new URL(path).toURI());
    }
    catch (final MalformedURLException e) {
        // NB: URL is not completely well-formed.
    }
    catch (final URISyntaxException e) {
        // NB: URL is not completely well-formed.
    }
    if (path.startsWith("file:")) {
        // pass through the URL as-is, minus "file:" prefix
        path = path.substring(5);
        return new File(path);
    }
    throw new IllegalArgumentException("Invalid URL: " + url);
}

You can find these methods in the SciJava Common library: