Programs & Examples On #Post processing

How do I use a 32-bit ODBC driver on 64-bit Server 2008 when the installer doesn't create a standard DSN?

It turns out that you can create 32-bit ODBC connections using C:\Windows\SysWOW64\odbcad32.exe. My solution was to create the 32-bit ODBC connection as a System DSN. This still didn't allow me to connect to it since .NET couldn't look it up. After significant and fruitless searching to find how to get the OdbcConnection class to look for the DSN in the right place, I stumbled upon a web site that suggested modifying the registry to solve a different problem.

I ended up creating the ODBC connection directly under HKLM\Software\ODBC. I looked in the SysWOW6432 key to find the parameters that were set up using the 32-bit version of the ODBC administration tool and recreated this in the standard location. I didn't add an entry for the driver, however, as that was not installed by the standard installer for the app either.

After creating the entry (by hand), I fired up my windows service and everything was happy.

Python Pandas: How to read only first n rows of CSV files in?

If you only want to read the first 999,999 (non-header) rows:

read_csv(..., nrows=999999)

If you only want to read rows 1,000,000 ... 1,999,999

read_csv(..., skiprows=1000000, nrows=999999)

nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*

skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file

and for large files, you'll probably also want to use chunksize:

chunksize : int, default None Return TextFileReader object for iteration

pandas.io.parsers.read_csv documentation

How to stop mongo DB in one command

in the terminal window on your mac, press control+c

Padding a table row

give the td padding

GroupBy pandas DataFrame and select most common value

The two top answers here suggest:

df.groupby(cols).agg(lambda x:x.value_counts().index[0])

or, preferably

df.groupby(cols).agg(pd.Series.mode)

However both of these fail in simple edge cases, as demonstrated here:

df = pd.DataFrame({
    'client_id':['A', 'A', 'A', 'A', 'B', 'B', 'B', 'C'],
    'date':['2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01'],
    'location':['NY', 'NY', 'LA', 'LA', 'DC', 'DC', 'LA', np.NaN]
})

The first:

df.groupby(['client_id', 'date']).agg(lambda x:x.value_counts().index[0])

yields IndexError (because of the empty Series returned by group C). The second:

df.groupby(['client_id', 'date']).agg(pd.Series.mode)

returns ValueError: Function does not reduce, since the first group returns a list of two (since there are two modes). (As documented here, if the first group returned a single mode this would work!)

Two possible solutions for this case are:

import scipy
x.groupby(['client_id', 'date']).agg(lambda x: scipy.stats.mode(x)[0])

And the solution given to me by cs95 in the comments here:

def foo(x): 
    m = pd.Series.mode(x); 
    return m.values[0] if not m.empty else np.nan
df.groupby(['client_id', 'date']).agg(foo)

However, all of these are slow and not suited for large datasets. A solution I ended up using which a) can deal with these cases and b) is much, much faster, is a lightly modified version of abw33's answer (which should be higher):

def get_mode_per_column(dataframe, group_cols, col):
    return (dataframe.fillna(-1)  # NaN placeholder to keep group 
            .groupby(group_cols + [col])
            .size()
            .to_frame('count')
            .reset_index()
            .sort_values('count', ascending=False)
            .drop_duplicates(subset=group_cols)
            .drop(columns=['count'])
            .sort_values(group_cols)
            .replace(-1, np.NaN))  # restore NaNs

group_cols = ['client_id', 'date']    
non_grp_cols = list(set(df).difference(group_cols))
output_df = get_mode_per_column(df, group_cols, non_grp_cols[0]).set_index(group_cols)
for col in non_grp_cols[1:]:
    output_df[col] = get_mode_per_column(df, group_cols, col)[col].values

Essentially, the method works on one col at a time and outputs a df, so instead of concat, which is intensive, you treat the first as a df, and then iteratively add the output array (values.flatten()) as a column in the df.

Excel VBA App stops spontaneously with message "Code execution has been halted"

Thanks to everyone for their input. This problem got solved by choosing REPAIR in Control Panel. I guess this explicitly re-registers some of Office's native COM components and does stuff that REINSTALL doesn't. I expect the latter just goes through a checklist and sometimes accepts what's there if it's already installed, maybe. I then had a separate issue with registering my own .NET dll for COM interop on the user's machine (despite this also working on other machines) though I think this was my error rather than Microsoft. Thanks again, I really appreciate it.

How to open a workbook specifying its path

Workbooks.open("E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm")

Or, in a more structured way...

Sub openwb()
    Dim sPath As String, sFile As String
    Dim wb As Workbook

    sPath = "E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\"
    sFile = sPath & "D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm"

    Set wb = Workbooks.Open(sFile)
End Sub

Example of Named Pipes

You can actually write to a named pipe using its name, btw.

Open a command shell as Administrator to get around the default "Access is denied" error:

echo Hello > \\.\pipe\PipeName

Sending "User-agent" using Requests library in Python

The user-agent should be specified as a field in the header.

Here is a list of HTTP header fields, and you'd probably be interested in request-specific fields, which includes User-Agent.

If you're using requests v2.13 and newer

The simplest way to do what you want is to create a dictionary and specify your headers directly, like so:

import requests

url = 'SOME URL'

headers = {
    'User-Agent': 'My User Agent 1.0',
    'From': '[email protected]'  # This is another valid field
}

response = requests.get(url, headers=headers)

If you're using requests v2.12.x and older

Older versions of requests clobbered default headers, so you'd want to do the following to preserve default headers and then add your own to them.

import requests

url = 'SOME URL'

# Get a copy of the default headers that requests would use
headers = requests.utils.default_headers()

# Update the headers with your custom ones
# You don't have to worry about case-sensitivity with
# the dictionary keys, because default_headers uses a custom
# CaseInsensitiveDict implementation within requests' source code.
headers.update(
    {
        'User-Agent': 'My User Agent 1.0',
    }
)

response = requests.get(url, headers=headers)

Firefox and SSL: sec_error_unknown_issuer

If anyone else is experiencing this issue with an Ubuntu LAMP and "COMODO Positive SSL" try to build your own bundle from the certs in the compressed file.

cat AddTrustExternalCARoot.crt COMODORSAAddTrustCA.crt COMODORSADomainValidationSecureServerCA.crt > YOURDOMAIN.ca-bundle

How to set downloading file name in ASP.NET Web API

This should do:

Response.AddHeader("Content-Disposition", "attachment;filename="+ YourFilename)

Python Remove last 3 characters of a string

>>> foo = 'BS1 1AB'
>>> foo.replace(" ", "").rstrip()[:-3].upper()
'BS1'

Creating new table with SELECT INTO in SQL

The syntax for creating a new table is

CREATE TABLE new_table
AS
SELECT *
  FROM old_table

This will create a new table named new_table with whatever columns are in old_table and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.

SELECT INTO is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.

How can strip whitespaces in PHP's variable?

Any possible option is to use custom file wrapper for simulating variables as files. You can achieve it by using this:

1) First of all, register your wrapper (only once in file, use it like session_start()):

stream_wrapper_register('var', VarWrapper);

2) Then define your wrapper class (it is really fast written, not completely correct, but it works):

class VarWrapper {
  protected $pos = 0;
  protected $content;
  public function stream_open($path, $mode, $options, &$opened_path) {
    $varname = substr($path, 6);
    global $$varname;
    $this->content = $$varname;
    return true;
  }
  public function stream_read($count) {
    $s = substr($this->content, $this->pos, $count);
    $this->pos += $count;
    return $s;
  }
  public function stream_stat() {
    $f = fopen(__file__, 'rb');
    $a = fstat($f);
    fclose($f);
    if (isset($a[7])) $a[7] = strlen($this->content);
    return $a;
  }
}

3) Then use any file function with your wrapper on var:// protocol (you can use it for include, require etc. too):

global $__myVar;
$__myVar = 'Enter tags here';
$data = php_strip_whitespace('var://__myVar');

Note: Don't forget to have your variable in global scope (like global $__myVar)

How to get current available GPUs in tensorflow?

There is an undocumented method called device_lib.list_local_devices() that enables you to list the devices available in the local process. (N.B. As an undocumented method, this is subject to backwards incompatible changes.) The function returns a list of DeviceAttributes protocol buffer objects. You can extract a list of string device names for the GPU devices as follows:

from tensorflow.python.client import device_lib

def get_available_gpus():
    local_device_protos = device_lib.list_local_devices()
    return [x.name for x in local_device_protos if x.device_type == 'GPU']

Note that (at least up to TensorFlow 1.4), calling device_lib.list_local_devices() will run some initialization code that, by default, will allocate all of the GPU memory on all of the devices (GitHub issue). To avoid this, first create a session with an explicitly small per_process_gpu_fraction, or allow_growth=True, to prevent all of the memory being allocated. See this question for more details.

How can I remove text within parentheses with a regex?

s/\([^)]*\)//

So in Python, you'd do:

re.sub(r'\([^)]*\)', '', filename)

Convert HTML string to image

Thanks all for your responses. I used HtmlRenderer external dll (library) to achieve the same and found below code for the same.

Here is the code for this

public void ConvertHtmlToImage()
{
   Bitmap m_Bitmap = new Bitmap(400, 600);
   PointF point = new PointF(0, 0);
   SizeF maxSize = new System.Drawing.SizeF(500, 500);
   HtmlRenderer.HtmlRender.Render(Graphics.FromImage(m_Bitmap),
                                           "<html><body><p>This is some html code</p>"
                                           + "<p>This is another html line</p></body>",
                                            point, maxSize);

   m_Bitmap.Save(@"C:\Test.png", ImageFormat.Png);
}

Simplest way to download and unzip files in Node.js cross-platform?

I found success with the following, works with .zip
(Simplified here for posting: no error checking & just unzips all files to current folder)

function DownloadAndUnzip(URL){
    var unzip = require('unzip');
    var http = require('http');
    var request = http.get(URL, function(response) {
        response.pipe(unzip.Extract({path:'./'}))
    });
}

How to get table cells evenly spaced?

Make a surrounding div-tag, and set for it display: grid in its style attribute.

<div style='display: grid; 
            text-align: center;
            background-color: antiquewhite'
>
  <table>
    <tr>
      <th>Month</th>
      <th>Savings</th>
    </tr>
    <tr>
      <td>January</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>February</td>
      <td>$80</td>
    </tr>
  </table>
</div>

The text-align property is set only to show, that the text in the regular table cells are affected by it, even though it is set on the surrounding div. The same with the background-color but it is hard to say which element actually holds the background-color.

What is the default value for enum variable?

You can use this snippet :-D

using System;
using System.Reflection;

public static class EnumUtils
{
    public static T GetDefaultValue<T>()
        where T : struct, Enum
    {
        return (T)GetDefaultValue(typeof(T));
    }

    public static object GetDefaultValue(Type enumType)
    {
        var attribute = enumType.GetCustomAttribute<DefaultValueAttribute>(inherit: false);
        if (attribute != null)
            return attribute.Value;

        var innerType = enumType.GetEnumUnderlyingType();
        var zero = Activator.CreateInstance(innerType);
        if (enumType.IsEnumDefined(zero))
            return zero;

        var values = enumType.GetEnumValues();
        return values.GetValue(0);
    }
}

Example:

using System;

public enum Enum1
{
    Foo,
    Bar,
    Baz,
    Quux
}
public enum Enum2
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 0
}
public enum Enum3
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 4
}
[DefaultValue(Enum4.Bar)]
public enum Enum4
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 4
}

public static class Program 
{
    public static void Main() 
    {
        var defaultValue1 = EnumUtils.GetDefaultValue<Enum1>();
        Console.WriteLine(defaultValue1); // Foo

        var defaultValue2 = EnumUtils.GetDefaultValue<Enum2>();
        Console.WriteLine(defaultValue2); // Quux

        var defaultValue3 = EnumUtils.GetDefaultValue<Enum3>();
        Console.WriteLine(defaultValue3); // Foo

        var defaultValue4 = EnumUtils.GetDefaultValue<Enum4>();
        Console.WriteLine(defaultValue4); // Bar
    }
}

Use ssh from Windows command prompt

Cygwin can give you this functionality.

Python method for reading keypress?

I really did not want to post this as a comment because I would need to comment all answers and the original question.

All of the answers seem to rely on MSVCRT Microsoft Visual C Runtime. If you would like to avoid that dependency :

In case you want cross platform support, using the library here:

https://pypi.org/project/getkey/#files

https://github.com/kcsaff/getkey

Can allow for a more elegant solution.

Code example:

from getkey import getkey, keys
key = getkey()
if key == keys.UP:
  ...  # Handle the UP key
elif key == keys.DOWN:
  ...  # Handle the DOWN key
elif key == 'a':
  ...  # Handle the `a` key
elif key == 'Y':
  ...  # Handle `shift-y`
else:
  # Handle other text characters
  buffer += key
  print(buffer)

What is the cleanest way to ssh and run multiple commands in Bash?

The easiest way to configure your system to use single ssh sessions by default with multiplexing.

This can be done by creating a folder for the sockets:

mkdir ~/.ssh/controlmasters

And then adding the following to your .ssh configuration:

Host *
    ControlMaster auto
    ControlPath ~/.ssh/controlmasters/%r@%h:%p.socket
    ControlMaster auto
    ControlPersist 10m

Now, you do not need to modify any of your code. This allows multiple calls to ssh and scp without creating multiple sessions, which is useful when there needs to be more interaction between your local and remote machines.

Thanks to @terminus's answer, http://www.cyberciti.biz/faq/linux-unix-osx-bsd-ssh-multiplexing-to-speed-up-ssh-connections/ and https://en.wikibooks.org/wiki/OpenSSH/Cookbook/Multiplexing.

Setting the selected attribute on a select list using jQuery

You can use pure DOM. See http://www.w3schools.com/htmldom/prop_select_selectedindex.asp

document.getElementById('dropdown').selectedIndex = 1;

but jQuery can help:

$('#dropdown').selectedIndex = 1;

Server Client send/receive simple text

CLIENT

namespace SocketKlient

{
    class Program

    {
        static Socket Klient;
        static IPEndPoint endPoint;
        static void Main(string[] args)
        {
            Klient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            string command;
            Console.WriteLine("Write IP address");
            command = Console.ReadLine();
            IPAddress Address;
            while(!IPAddress.TryParse(command, out Address)) 
            {
                Console.WriteLine("wrong IP format");
                command = Console.ReadLine();
            }
            Console.WriteLine("Write port");
            command = Console.ReadLine();

            int port;
            while (!int.TryParse(command, out port) && port > 0)
            {
                Console.WriteLine("Wrong port number");
                command = Console.ReadLine();
            }
            endPoint = new IPEndPoint(Address, port); 
            ConnectC(Address, port);
            while(Klient.Connected)
            {
                Console.ReadLine();
                Odesli();
            }
        }

        public static void ConnectC(IPAddress ip, int port)
        {
            IPEndPoint endPoint = new IPEndPoint(ip, port);
            Console.WriteLine("Connecting...");
            try
            {
                Klient.Connect(endPoint);
                Console.WriteLine("Connected!");
            }
            catch
            {
                Console.WriteLine("Connection fail!");
                return; 
            }
            Task t = new Task(WaitForMessages); 
            t.Start(); 
        }

        public static void SendM()
        {
            string message = "Actualy date is " + DateTime.Now; 
            byte[] buffer = Encoding.UTF8.GetBytes(message);
            Console.WriteLine("Sending: " + message);
            Klient.Send(buffer);
        }

        public static void WaitForMessages()
        {
            try
            {
                while (true)
                {
                    byte[] buffer = new byte[64]; 
                    Console.WriteLine("Waiting for answer");
                    Klient.Receive(buffer, 0, buffer.Length, 0); 

                    string message = Encoding.UTF8.GetString(buffer); 
                    Console.WriteLine("Answer: " + message); 
                }
            }
            catch
            {
                Console.WriteLine("Disconnected");
            }
        }
    }
}

Java: convert seconds to minutes, hours and days

Thanks guys for all the help, I really appreciate but I actually did some thinking and start doing some pseudo code and came up with this.

import java.util.Scanner;

public class Project {

public static void main(String[] args) {



//variable declaration  
Scanner scan = new Scanner(System.in);
final int MIN = 60, HRS = 3600, DYS = 84600;
int input, days, seconds, minutes, hours, rDays, rHours;

//input 
System.out.println("Enter amount of seconds!");
input = scan.nextInt();


//calculations
days = input/DYS;
rDays = input%DYS;
hours = rDays/HRS;
rHours = rDays%HRS;
minutes = rHours/MIN;
seconds = rHours%MIN;

//output
if (input >= DYS) {
    System.out.println(input + " seconds equals to " + days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds");
}

else if (input >= HRS && input < DYS) {
    System.out.println(input + " seconds equals to " + hours + " hours " + minutes + " minutes " + seconds + " seconds");
}

else if (input >= MIN && input < HRS) {
    System.out.println(input + " seconds equals to " + minutes + " minutes " + seconds + " seconds");
}

else if (input < MIN) {
    System.out.println(input + " seconds equals to seconds");
}

scan.close();


}   

I know it looks really noobie but keep in mind I'm still new not just Java but programming entirely, and who knew pseudo code was actually really helpful.

Downloading a large file using curl

when curl is used to download a large file then CURLOPT_TIMEOUT is the main option you have to set for.

CURLOPT_RETURNTRANSFER has to be true in case you are getting file like pdf/csv/image etc.

You may find the further detail over here(correct url) Curl Doc

From that page:

curl_setopt($request, CURLOPT_TIMEOUT, 300); //set timeout to 5 mins

curl_setopt($request, CURLOPT_RETURNTRANSFER, true); // true to get the output as string otherwise false

How to set TLS version on apache HttpClient

This is how I got it working on httpClient 4.5 (as per Olive Tree request):

CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
        new AuthScope(AuthScope.ANY_HOST, 443),
        new UsernamePasswordCredentials(this.user, this.password));

SSLContext sslContext = SSLContexts.createDefault();

SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
        new String[]{"TLSv1", "TLSv1.1"},
        null,
        new NoopHostnameVerifier());

CloseableHttpClient httpclient = HttpClients.custom()
        .setDefaultCredentialsProvider(credsProvider)
        .setSSLSocketFactory(sslsf)
        .build();

return httpclient;

How to create <input type=“text”/> dynamically

<button id="add" onclick="add()">Add Element</button>

<div id="hostI"></div>

<template id="templateInput">
    <input type="text">
</template>

<script>
    function add() {

        // Using Template, element is created
        var templateInput = document.querySelector('#templateInput');
        var clone = document.importNode(templateInput.content, true);

        // The Element is added to document
        var hostI = document.querySelector('#hostI');
        hostI.appendChild(clone);
    }

</script>

HTML Templates are now the recommended standards to generate dynamic content.

What is special about /dev/tty?

The 'c' means it's a character device. tty is a special file representing the 'controlling terminal' for the current process.

Character Devices

Unix supports 'device files', which aren't really files at all, but file-like access points to hardware devices. A 'character' device is one which is interfaced byte-by-byte (as opposed to buffered IO).

TTY

/dev/tty is a special file, representing the terminal for the current process. So, when you echo 1 > /dev/tty, your message ('1') will appear on your screen. Likewise, when you cat /dev/tty, your subsequent input gets duplicated (until you press Ctrl-C).

/dev/tty doesn't 'contain' anything as such, but you can read from it and write to it (for what it's worth). I can't think of a good use for it, but there are similar files which are very useful for simple IO operations (e.g. /dev/ttyS0 is normally your serial port)

This quote is from http://tldp.org/HOWTO/Text-Terminal-HOWTO-7.html#ss7.3 :

/dev/tty stands for the controlling terminal (if any) for the current process. To find out which tty's are attached to which processes use the "ps -a" command at the shell prompt (command line). Look at the "tty" column. For the shell process you're in, /dev/tty is the terminal you are now using. Type "tty" at the shell prompt to see what it is (see manual pg. tty(1)). /dev/tty is something like a link to the actually terminal device name with some additional features for C-programmers: see the manual page tty(4).

Here is the man page: http://linux.die.net/man/4/tty

C++ obtaining milliseconds time on Linux -- clock() doesn't seem to work properly

clock() doesn't return milliseconds or seconds on linux. Usually clock() returns microseconds on a linux system. The proper way to interpret the value returned by clock() is to divide it by CLOCKS_PER_SEC to figure out how much time has passed.

How to add days to the current date?

Two or three ways (depends what you want), say we are at Current Date is (in tsql code) -

DECLARE @myCurrentDate datetime = '11Apr2014 10:02:25 AM'

(BTW - did you mean 11April2014 or 04Nov2014 in your original post? hard to tell, as datetime is culture biased. In Israel 11/04/2015 means 11April2014. I know in the USA 11/04/2014 it means 04Nov2014. tommatoes tomatos I guess)

  1. SELECT @myCurrentDate + 360 - by default datetime calculations followed by + (some integer), just add that in days. So you would get 2015-04-06 10:02:25.000 - not exactly what you wanted, but rather just a ball park figure for a close date next year.

  2. SELECT DateADD(DAY, 365, @myCurrentDate) or DateADD(dd, 365, @myCurrentDate) will give you '2015-04-11 10:02:25.000'. These two are syntatic sugar (exacly the same). This is what you wanted, I should think. But it's still wrong, because if the date was a "3 out of 4" year (say DECLARE @myCurrentDate datetime = '11Apr2011 10:02:25 AM') you would get '2012-04-10 10:02:25.000'. because 2012 had 366 days, remember? (29Feb2012 consumes an "extra" day. Almost every fourth year has 29Feb).

  3. So what I think you meant was

    SELECT DateADD(year, 1, @myCurrentDate)
    

    which gives 2015-04-11 10:02:25.000.

  4. or better yet

    SELECT DateADD(year, 1, DateADD(day, DateDiff(day, 0, @myCurrentDate), 0))
    

    which gives you 2015-04-11 00:00:00.000 (because datetime also has time, right?). Subtle, ah?

Display html text in uitextview

For some cases UIWebView is a good solution. Because:

  • it displays tables, images, other files
  • it's fast (comparing with NSAttributedString: NSHTMLTextDocumentType)
  • it's out of the box

Using NSAttributedString can lead to crashes, if html is complex or contains tables (so example)

For loading text to web view you can use the following snippet (just example):

func loadHTMLText(_ text: String?, font: UIFont) {
        let fontSize = font.pointSize * UIScreen.screens[0].scale
        let html = """
        <html><body><span style=\"font-family: \(font.fontName); font-size: \(fontSize)\; color: #112233">\(text ?? "")</span></body></html>
        """
        self.loadHTMLString(html, baseURL: nil)
    }

How do I put an image into my picturebox using ImageLocation?

if you provide a bad path or a broken link, if the compiler cannot find the image, the picture box would display an X icon on its body.

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17),
            Image = Image.FromFile(@"c:\Images\test.jpg"),
            SizeMode = PictureBoxSizeMode.CenterImage
        };
p.Controls.Add(picture);

OR

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17),
            ImageLocation = @"c:\Images\test.jpg",
            SizeMode = PictureBoxSizeMode.CenterImage
        };
p.Controls.Add(picture);

i'm not sure where you put images in your folder structure but you can find the path as bellow

 picture.ImageLocation = Path.Combine(System.Windows.Forms.Application.StartupPath, "Resources\Images\1.jpg");

Error TF30063: You are not authorized to access ... \DefaultCollection

I get this problem when I am forced by our IT security policy to change my password. After a password change, when I connect to TFS using VS2017, I am no longer authorized to access our TFS server and get the TF30063: You are not authorised to access ...:8080/tfs error message.

However, if I connect using VS2013, I can connect to the server without problems and the access denied error with VS2017 goes away.

Generating Fibonacci Sequence

I know this is a bit of an old question, but I realized that many of the answers here are utilizing for loops rather than while loops.

Sometimes, while loops are faster than for loops, so I figured I'd contribute some code that runs the Fibonacci sequence in a while loop as well! Use whatever you find suitable to your needs.

function fib(length) {
  var fibArr = [],
    i = 0,
    j = 1;
  fibArr.push(i);
  fibArr.push(j);
  while (fibArr.length <= length) {
    fibArr.push(fibArr[j] + fibArr[i]);
    j++;
    i++;
  }
  return fibArr;
};
fib(15);

Hide all elements with class using plain Javascript

In the absence of jQuery, I would use something like this:

<script>
    var divsToHide = document.getElementsByClassName("classname"); //divsToHide is an array
    for(var i = 0; i < divsToHide.length; i++){
        divsToHide[i].style.visibility = "hidden"; // or
        divsToHide[i].style.display = "none"; // depending on what you're doing
    }
<script>

This is taken from this SO question: Hide div by class id, however seeing that you're asking for "old-school" JS solution, I believe that getElementsByClassName is only supported by modern browsers

Convert string into Date type on Python

Use datetime.datetime.strptime:

>>> import datetime
>>> date = datetime.datetime.strptime('2012-02-10', '%Y-%m-%d')
>>> date.isoweekday()
5

JavaScript hide/show element

I would like to suggest you the JQuery option.

$("#item").toggle();
$("#item").hide();
$("#item").show();

For example:

$(document).ready(function(){
   $("#item").click(function(event){
     //Your actions here
   });
 });

How to create SPF record for multiple IPs?

Yes the second syntax is fine.

Have you tried using the SPF wizard? https://www.spfwizard.net/

It can quickly generate basic and complex SPF records.

Numpy where function multiple conditions

One interesting thing to point here; the usual way of using OR and AND too will work in this case, but with a small change. Instead of "and" and instead of "or", rather use Ampersand(&) and Pipe Operator(|) and it will work.

When we use 'and':

ar = np.array([3,4,5,14,2,4,3,7])
np.where((ar>3) and (ar<6), 'yo', ar)

Output:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

When we use Ampersand(&):

ar = np.array([3,4,5,14,2,4,3,7])
np.where((ar>3) & (ar<6), 'yo', ar)

Output:
array(['3', 'yo', 'yo', '14', '2', 'yo', '3', '7'], dtype='<U11')

And this is same in the case when we are trying to apply multiple filters in case of pandas Dataframe. Now the reasoning behind this has to do something with Logical Operators and Bitwise Operators and for more understanding about same, I'd suggest to go through this answer or similar Q/A in stackoverflow.

UPDATE

A user asked, why is there a need for giving (ar>3) and (ar<6) inside the parenthesis. Well here's the thing. Before I start talking about what's happening here, one needs to know about Operator precedence in Python.

Similar to what BODMAS is about, python also gives precedence to what should be performed first. Items inside the parenthesis are performed first and then the bitwise operator comes to work. I'll show below what happens in both the cases when you do use and not use "(", ")".

Case1:

np.where( ar>3 & ar<6, 'yo', ar)
np.where( np.array([3,4,5,14,2,4,3,7])>3 & np.array([3,4,5,14,2,4,3,7])<6, 'yo', ar)

Since there are no brackets here, the bitwise operator(&) is getting confused here that what are you even asking it to get logical AND of, because in the operator precedence table if you see, & is given precedence over < or > operators. Here's the table from from lowest precedence to highest precedence.

enter image description here

It's not even performing the < and > operation and being asked to perform a logical AND operation. So that's why it gives that error.

One can check out the following link to learn more about: operator precedence

Now to Case 2:

If you do use the bracket, you clearly see what happens.

np.where( (ar>3) & (ar<6), 'yo', ar)
np.where( (array([False,  True,  True,  True, False,  True, False,  True])) & (array([ True,  True,  True, False,  True,  True,  True, False])), 'yo', ar)

Two arrays of True and False. And you can easily perform logical AND operation on them. Which gives you:

np.where( array([False,  True,  True, False, False,  True, False, False]),  'yo', ar)

And rest you know, np.where, for given cases, wherever True, assigns first value(i.e. here 'yo') and if False, the other(i.e. here, keeping the original).

That's all. I hope I explained the query well.

How to go back to previous page if back button is pressed in WebView?

If using Android 2.2 and above (which is most devices now), the following code will get you what you want.

@Override
public void onBackPressed() {
    if (webView.canGoBack()) {
        webView.goBack();
    } else {
        super.onBackPressed();
    }
}

How to Logout of an Application Where I Used OAuth2 To Login With Google?

If any one want it in Java, Here is my Answer, For this you have to call Another Thread.

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R?

I figured out myself.

cmp calls ComputeBetasAndNuHat which returns a list which has objective as minusloglik

So I can change the function cmp to get this value.

How to test android apps in a real device with Android Studio?

I can run on my device at last, just I enabled the "USB debugging" and "Allow mock location" options from the Debug Menu of my device.

How to run code after some delay in Flutter?

await Future.delayed(Duration(milliseconds: 1000));

SQL Server: Extract Table Meta-Data (description, fields and their data types)

I just finished a .net library with a few useful queries that return strongly typed C# objects for code gen/ t4 templates.

nuget SqlMeta

Project Site

github source

/// <summary>
    ///     Get All Table Names
    /// </summary>
    /// <returns></returns>
    public List<string> GetTableNames()
    {
        var sql = @"SELECT name
                    FROM dbo.sysobjects
                    WHERE xtype = 'U' 
                    AND name <> 'sysdiagrams'
                    order by name asc";

        return databaseWrapper.Call(connection => connection.Query<string>(
            sql: sql))
            .ToList();
    }

    /// <summary>
    ///     Get table info by schema and table or null for all
    /// </summary>
    /// <param name="schema"></param>
    /// <param name="table"></param>
    /// <returns></returns>
    public List<SqlTableInfo> GetTableInfo(string schema = null, string table = null)
    {
        var result = new List<SqlTableInfo>();

        var sql = @"SELECT
                    c.TABLE_CATALOG AS [TableCatalog]
                ,   c.TABLE_SCHEMA AS [Schema]
                ,   c.TABLE_NAME AS [TableName]
                ,   c.COLUMN_NAME AS [ColumnName]
                ,   c.ORDINAL_POSITION AS [OrdinalPosition]
                ,   c.COLUMN_DEFAULT AS [ColumnDefault]
                ,   c.IS_NULLABLE AS [Nullable]
                ,   c.DATA_TYPE AS [DataType]
                ,   c.CHARACTER_MAXIMUM_LENGTH AS [CharacterMaxLength]
                ,   c.CHARACTER_OCTET_LENGTH AS [CharacterOctetLenth]
                ,   c.NUMERIC_PRECISION AS [NumericPrecision]
                ,   c.NUMERIC_PRECISION_RADIX AS [NumericPrecisionRadix]
                ,   c.NUMERIC_SCALE AS [NumericScale]
                ,   c.DATETIME_PRECISION AS [DatTimePrecision]
                ,   c.CHARACTER_SET_CATALOG AS [CharacterSetCatalog]
                ,   c.CHARACTER_SET_SCHEMA AS [CharacterSetSchema]
                ,   c.CHARACTER_SET_NAME AS [CharacterSetName]
                ,   c.COLLATION_CATALOG AS [CollationCatalog]
                ,   c.COLLATION_SCHEMA AS [CollationSchema]
                ,   c.COLLATION_NAME AS [CollationName]
                ,   c.DOMAIN_CATALOG AS [DomainCatalog]
                ,   c.DOMAIN_SCHEMA AS [DomainSchema]
                ,   c.DOMAIN_NAME AS [DomainName]
                ,   IsPrimaryKey = CONVERT(BIT, (SELECT
                            COUNT(*)
                        FROM    INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
                            ,   INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE cu
                        WHERE CONSTRAINT_TYPE = 'PRIMARY KEY'
                        AND tc.CONSTRAINT_NAME = cu.CONSTRAINT_NAME
                        AND tc.TABLE_NAME = c.TABLE_NAME
                        AND cu.TABLE_SCHEMA = c.TABLE_SCHEMA
                        AND cu.COLUMN_NAME = c.COLUMN_NAME)
                    )
                ,   IsIdentity = CONVERT(BIT, (SELECT
                            COUNT(*)
                        FROM sys.objects obj
                        INNER JOIN sys.COLUMNS col
                            ON obj.object_id = col.object_id
                        WHERE obj.type = 'U'
                        AND obj.Name = c.TABLE_NAME
                        AND col.Name = c.COLUMN_NAME
                        AND col.is_identity = 1)
                    )
                FROM INFORMATION_SCHEMA.COLUMNS c
                WHERE (@Schema IS NULL
                        OR c.TABLE_SCHEMA = @Schema)
                    AND (@TableName IS NULL
                        OR c.TABLE_NAME = @TableName)
                    ";

        var columns = databaseWrapper.Call(connection => connection.Query<SqlColumnInfo>(
            sql: sql,
            param: new { Schema = schema, TableName = table },
            commandType: CommandType.Text)
            .ToList());

        var refs = this.GetReferentialConstraints(table: table, schema: schema);

        foreach (var tableName in columns.Select(info => info.TableName).Distinct())
        {
            var tableColumns = columns.Where(info => info.TableName == tableName).ToList();
            var children = refs.Where(c => c.UniqueTableName == tableName).ToList();
            var parents = refs.Where(c => c.TableName == tableName).ToList();
            result.Add(new SqlTableInfo
            {
                TableName = tableName,
                Columns = tableColumns,
                ChildConstraints = children,
                ParentConstraints = parents
            });

        }

        return result;
    }

    public List<SqlReferentialConstraint> GetReferentialConstraints(string table = null, string schema = null)
    {
        //https://technet.microsoft.com/en-us/library/aa175805%28v=sql.80%29.aspx
        //https://technet.microsoft.com/en-us/library/Aa175805.312ron1%28l=en-us,v=sql.80%29.jpg
        //https://msdn.microsoft.com/en-us/library/ms186778.aspx

        var sql = @"
                    SELECT
                        KCU1.CONSTRAINT_NAME AS [ConstraintName]
                    ,   KCU1.TABLE_NAME AS [TableName]
                    ,   KCU1.COLUMN_NAME AS [ColumnName]
                    ,   KCU2.CONSTRAINT_NAME AS [UniqueConstraintName]
                    ,   KCU2.TABLE_NAME AS [UniqueTableName]
                    ,   KCU2.COLUMN_NAME AS [UniqueColumnName]
                    ,   RC.MATCH_OPTION AS [MatchOption]
                    ,   RC.UPDATE_RULE AS [UpdateRule]
                    ,   RC.DELETE_RULE AS [DeleteRule]
                    FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC
                    LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU1 ON KCU1.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG
                        AND KCU1.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA
                        AND KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME
                    LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU2 ON KCU2.CONSTRAINT_CATALOG = RC.UNIQUE_CONSTRAINT_CATALOG
                        AND KCU2.CONSTRAINT_SCHEMA = RC.UNIQUE_CONSTRAINT_SCHEMA
                        AND KCU2.CONSTRAINT_NAME = RC.UNIQUE_CONSTRAINT_NAME
                    WHERE KCU1.ORDINAL_POSITION = KCU2.ORDINAL_POSITION
                            AND (@Table IS NULL
                                OR KCU1.TABLE_NAME = @Table
                                OR KCU2.TABLE_NAME = @Table)
                            AND (@Schema IS NULL
                                OR KCU1.TABLE_SCHEMA = @Schema
                                OR KCU2.TABLE_SCHEMA = @Schema)
                    ";

        return databaseWrapper.Call(connection => connection.Query<SqlReferentialConstraint>(
            sql: sql,
            param: new { Table = table, Schema = schema },
            commandType: CommandType.Text))
            .ToList();
    }

    /// <summary>
    ///     Get Primary Key Column by schema and table name
    /// </summary>
    /// <param name="schema"></param>
    /// <param name="tableName"></param>
    /// <returns></returns>
    public string GetPrimaryKeyColumnName(string schema, string tableName)
    {
        var sql = @"SELECT
                    B.COLUMN_NAME
                FROM    INFORMATION_SCHEMA.TABLE_CONSTRAINTS A
                    ,   INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE B
                WHERE CONSTRAINT_TYPE = 'PRIMARY KEY'
                    AND A.CONSTRAINT_NAME = B.CONSTRAINT_NAME
                    AND A.TABLE_NAME = @TableName
                    AND A.TABLE_SCHEMA = @Schema";

        return databaseWrapper.Call(connection => connection.Query<string>(
            sql: sql,
            param: new { TableName = tableName, Schema = schema },
            commandType: CommandType.Text))
            .SingleOrDefault();
    }

    /// <summary>
    ///     Get Identity Column by table name
    /// </summary>
    /// <param name="tableName"></param>
    /// <returns></returns>
    public string GetIdentityColumnName(string tableName)
    {
        var sql = @"SELECT
                    c.Name
                FROM sys.objects o
                INNER JOIN sys.columns c ON o.object_id = c.object_id
                WHERE o.type = 'U'
                    AND c.is_identity = 1
                    AND o.Name = @TableName";

        return databaseWrapper.Call(connection => connection.Query<string>(
            sql: sql,
            param: new { TableName = tableName },
            commandType: CommandType.Text))
            .SingleOrDefault();
    }

    /// <summary>
    ///     Get All Stored Procedures by schema
    /// </summary>
    /// <param name="schema"></param>
    /// <param name="procName"></param>
    /// <returns></returns>
    public List<SqlStoredProcedureInfo> GetStoredProcedureInfo(string schema = null, string procName = null)
    {
        var result = new List<SqlStoredProcedureInfo>();

        var sql = @"SELECT
                        SPECIFIC_NAME AS [Name]
                    ,   SPECIFIC_SCHEMA AS [Schema]
                    ,   Created AS [Created]
                    ,   LAST_ALTERED AS [LastAltered]
                    FROM INFORMATION_SCHEMA.ROUTINES
                    WHERE ROUTINE_TYPE = 'PROCEDURE'
                        AND (SPECIFIC_SCHEMA = @Schema
                            OR @Schema IS NULL)
                        AND (SPECIFIC_NAME = @ProcName
                            OR @ProcName IS NULL)
                        AND ((SPECIFIC_NAME NOT LIKE 'sp_%'
                                AND SPECIFIC_NAME NOT LIKE 'procUtils_GenerateClass'
                                AND (SPECIFIC_SCHEMA = @Schema
                                    OR @Schema IS NULL))
                            OR SPECIFIC_SCHEMA <> @Schema)";

        var sprocs = databaseWrapper.Call(connection => connection.Query<SqlStoredProcedureInfo>(
            sql: sql,
            param: new { Schema = schema, ProcName = procName },
            commandType: CommandType.Text).ToList());

        foreach (var s in sprocs)
        {
            s.Parameters = GetStoredProcedureInputParameters(sprocName: s.Name, schema: schema);
            s.ResultColumns = GetColumnInfoFromStoredProcResult(storedProcName: s.Name, schema: schema);
            result.Add(s);
        }

        return result;
    }

    /// <summary>
    ///     Get Column info from Stored procedure result set
    /// </summary>
    /// <param name="schema"></param>
    /// <param name="storedProcName"></param>
    /// <returns></returns>
    public List<DataColumn> GetColumnInfoFromStoredProcResult(string schema, string storedProcName)
    {
        //this one actually needs to use the dataset because it has the only accurate information about columns and if they can be null or not.
        var sb = new StringBuilder();
        if (!String.IsNullOrEmpty(schema))
        {
            sb.Append(String.Format("exec [{0}].[{1}] ", schema, storedProcName));
        }
        else
        {
            sb.Append(String.Format("exec [{0}] ", storedProcName));
        }

        var prms = GetStoredProcedureInputParameters(schema, storedProcName);

        var count = 1;
        foreach (var param in prms)
        {
            sb.Append(String.Format("{0}=null", param.Name));
            if (count < prms.Count)
            {
                sb.Append(", ");
            }
            count++;
        }

        var ds = new DataSet();
        using (var sqlConnection = (SqlConnection)databaseWrapper.GetOpenDbConnection())
        {
            using (var sqlAdapter = new SqlDataAdapter(sb.ToString(), sqlConnection))
            {
                if (sqlConnection.State != ConnectionState.Open) sqlConnection.Open();

                sqlAdapter.SelectCommand.ExecuteReader(CommandBehavior.SchemaOnly);

                sqlConnection.Close();

                sqlAdapter.FillSchema(ds, SchemaType.Source, "MyTable");
            }
        }

        var list = new List<DataColumn>();
        if (ds.Tables.Count > 0)
        {
            list = ds.Tables["MyTable"].Columns.Cast<DataColumn>().ToList();
        }

        return list;
    }

    /// <summary>
    ///     Get the input parameters for a stored procedure
    /// </summary>
    /// <param name="schema"></param>
    /// <param name="sprocName"></param>
    /// <returns></returns>
    public List<SqlParameterInfo> GetStoredProcedureInputParameters(string schema = null, string sprocName = null)
    {
        var sql = @"SELECT
                    SCHEMA_NAME(schema_id) AS [Schema]
                ,   P.Name AS Name
                ,   @ProcName AS ProcedureName
                ,   TYPE_NAME(P.user_type_id) AS [ParameterDataType]
                ,   P.max_length AS [MaxLength]
                ,   P.Precision AS [Precision]
                ,   P.Scale AS Scale
                ,   P.has_default_value AS HasDefaultValue
                ,   P.default_value AS DefaultValue
                ,   P.object_id AS ObjectId
                ,   P.parameter_id AS ParameterId
                ,   P.system_type_id AS SystemTypeId
                ,   P.user_type_id AS UserTypeId
                ,   P.is_output AS IsOutput
                ,   P.is_cursor_ref AS IsCursor
                ,   P.is_xml_document AS IsXmlDocument
                ,   P.xml_collection_id AS XmlCollectionId
                ,   P.is_readonly AS IsReadOnly
                FROM sys.objects AS SO
                INNER JOIN sys.parameters AS P ON SO.object_id = P.object_id
                WHERE SO.object_id IN (SELECT
                            object_id
                        FROM sys.objects
                        WHERE type IN ('P', 'FN'))
                    AND (SO.Name = @ProcName
                        OR @ProcName IS NULL)
                    AND (SCHEMA_NAME(schema_id) = @Schema
                        OR @Schema IS NULL)
                ORDER BY P.parameter_id ASC";

        var result = databaseWrapper.Call(connection => connection.Query<SqlParameterInfo>(
            sql: sql,
            param: new { Schema = schema, ProcName = sprocName },
            commandType: CommandType.Text))
            .ToList();

        return result;
    }

Foreign Key Metadata

C#: Printing all properties of an object

Based on the ObjectDumper of the LINQ samples I created a version that dumps each of the properties on its own line.

This Class Sample

namespace MyNamespace
{
    public class User
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Address Address { get; set; }
        public IList<Hobby> Hobbies { get; set; }
    }

    public class Hobby
    {
        public string Name { get; set; }
    }

    public class Address
    {
        public string Street { get; set; }
        public int ZipCode { get; set; }
        public string City { get; set; }    
    }
}

has an output of

{MyNamespace.User}
  FirstName: "Arnold"
  LastName: "Schwarzenegger"
  Address: { }
    {MyNamespace.Address}
      Street: "6834 Hollywood Blvd"
      ZipCode: 90028
      City: "Hollywood"
  Hobbies: ...
    {MyNamespace.Hobby}
      Name: "body building"

Here is the code.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

public class ObjectDumper
{
    private int _level;
    private readonly int _indentSize;
    private readonly StringBuilder _stringBuilder;
    private readonly List<int> _hashListOfFoundElements;

    private ObjectDumper(int indentSize)
    {
        _indentSize = indentSize;
        _stringBuilder = new StringBuilder();
        _hashListOfFoundElements = new List<int>();
    }

    public static string Dump(object element)
    {
        return Dump(element, 2);
    }

    public static string Dump(object element, int indentSize)
    {
        var instance = new ObjectDumper(indentSize);
        return instance.DumpElement(element);
    }

    private string DumpElement(object element)
    {
        if (element == null || element is ValueType || element is string)
        {
            Write(FormatValue(element));
        }
        else
        {
            var objectType = element.GetType();
            if (!typeof(IEnumerable).IsAssignableFrom(objectType))
            {
                Write("{{{0}}}", objectType.FullName);
                _hashListOfFoundElements.Add(element.GetHashCode());
                _level++;
            }

            var enumerableElement = element as IEnumerable;
            if (enumerableElement != null)
            {
                foreach (object item in enumerableElement)
                {
                    if (item is IEnumerable && !(item is string))
                    {
                        _level++;
                        DumpElement(item);
                        _level--;
                    }
                    else
                    {
                        if (!AlreadyTouched(item))
                            DumpElement(item);
                        else
                            Write("{{{0}}} <-- bidirectional reference found", item.GetType().FullName);
                    }
                }
            }
            else
            {
                MemberInfo[] members = element.GetType().GetMembers(BindingFlags.Public | BindingFlags.Instance);
                foreach (var memberInfo in members)
                {
                    var fieldInfo = memberInfo as FieldInfo;
                    var propertyInfo = memberInfo as PropertyInfo;

                    if (fieldInfo == null && propertyInfo == null)
                        continue;

                    var type = fieldInfo != null ? fieldInfo.FieldType : propertyInfo.PropertyType;
                    object value = fieldInfo != null
                                       ? fieldInfo.GetValue(element)
                                       : propertyInfo.GetValue(element, null);

                    if (type.IsValueType || type == typeof(string))
                    {
                        Write("{0}: {1}", memberInfo.Name, FormatValue(value));
                    }
                    else
                    {
                        var isEnumerable = typeof(IEnumerable).IsAssignableFrom(type);
                        Write("{0}: {1}", memberInfo.Name, isEnumerable ? "..." : "{ }");

                        var alreadyTouched = !isEnumerable && AlreadyTouched(value);
                        _level++;
                        if (!alreadyTouched)
                            DumpElement(value);
                        else
                            Write("{{{0}}} <-- bidirectional reference found", value.GetType().FullName);
                        _level--;
                    }
                }
            }

            if (!typeof(IEnumerable).IsAssignableFrom(objectType))
            {
                _level--;
            }
        }

        return _stringBuilder.ToString();
    }

    private bool AlreadyTouched(object value)
    {
        if (value == null)
            return false;

        var hash = value.GetHashCode();
        for (var i = 0; i < _hashListOfFoundElements.Count; i++)
        {
            if (_hashListOfFoundElements[i] == hash)
                return true;
        }
        return false;
    }

    private void Write(string value, params object[] args)
    {
        var space = new string(' ', _level * _indentSize);

        if (args != null)
            value = string.Format(value, args);

        _stringBuilder.AppendLine(space + value);
    }

    private string FormatValue(object o)
    {
        if (o == null)
            return ("null");

        if (o is DateTime)
            return (((DateTime)o).ToShortDateString());

        if (o is string)
            return string.Format("\"{0}\"", o);

        if (o is char && (char)o == '\0') 
            return string.Empty; 

        if (o is ValueType)
            return (o.ToString());

        if (o is IEnumerable)
            return ("...");

        return ("{ }");
    }
}

and you can use it like that:

var dump = ObjectDumper.Dump(user);

Edit

  • Bi - directional references are now stopped. Therefore the HashCode of an object is stored in a list.
  • AlreadyTouched fixed (see comments)
  • FormatValue fixed (see comments)

CSS transition shorthand with multiple properties?

I made it work with this:

.element {
   transition: height 3s ease-out, width 5s ease-in;
}

Convert string to integer type in Go?

Try this

import ("strconv")

value := "123"
number,err := strconv.ParseUint(value, 10, 32)
finalIntNum := int(number) //Convert uint64 To int

ReactNative: how to center text?

used

textalign:center

at the view

Equivalent of String.format in jQuery

None of the answers presented so far has no obvious optimization of using enclosure to initialize once and store regular expressions, for subsequent usages.

// DBJ.ORG string.format function
// usage:   "{0} means 'zero'".format("nula") 
// returns: "nula means 'zero'"
// place holders must be in a range 0-99.
// if no argument given for the placeholder, 
// no replacement will be done, so
// "oops {99}".format("!")
// returns the input
// same placeholders will be all replaced 
// with the same argument :
// "oops {0}{0}".format("!","?")
// returns "oops !!"
//
if ("function" != typeof "".format) 
// add format() if one does not exist already
  String.prototype.format = (function() {
    var rx1 = /\{(\d|\d\d)\}/g, rx2 = /\d+/ ;
    return function() {
        var args = arguments;
        return this.replace(rx1, function($0) {
            var idx = 1 * $0.match(rx2)[0];
            return args[idx] !== undefined ? args[idx] : (args[idx] === "" ? "" : $0);
        });
    }
}());

alert("{0},{0},{{0}}!".format("{X}"));

Also, none of the examples respects format() implementation if one already exists.

problem with <select> and :after with CSS in WebKit

This is a modern solution I cooked up using font-awesome. Vendor extensions have been omitted for brevity.

HTML

<fieldset>
    <label for="color">Select Color</label>
    <div class="select-wrapper">
        <select id="color">
            <option>Red</option>
            <option>Blue</option>
            <option>Yellow</option>
        </select>
        <i class="fa fa-chevron-down"></i>
    </div>
</fieldset>

SCSS

fieldset {
    .select-wrapper {
        position: relative;

        select {
            appearance: none;
            position: relative;
            z-index: 1;
            background: transparent;

            + i {
                position: absolute;
                top: 40%;
                right: 15px;
            }
        }
    }

If your select element has a defined background color, then this won't work as this snippet essentially places the Chevron icon behind the select element (to allow clicking on top of the icon to still initiate the select action).

However, you can style the select-wrapper to the same size as the select element and style its background to achieve the same effect.

Check out my CodePen for a working demo that shows this bit of code on both a dark and light themed select box using a regular label and a "placeholder" label and other cleaned up styles such as borders and widths.

P.S. This is an answer I had posted to another, duplicate question earlier this year.

How to handle invalid SSL certificates with Apache HttpClient?

Another issue you may run into with self signed test certs is this:

java.io.IOException: HTTPS hostname wrong: should be ...

This error occurs when you are trying to access a HTTPS url. You might have already installed the server certificate to your JRE's keystore. But this error means that the name of the server certificate does not match with the actual domain name of the server that is mentioned in the URL. This normally happens when you are using a non CA issued certificate.

This example shows how to write a HttpsURLConnection DefaultHostnameVerifier that ignore the certificates server name:

http://www.java-samples.com/showtutorial.php?tutorialid=211

javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

I was experiencing this error on Android 5.1.1 devices sending network requests using okhttp/4.0.0-RC1. Setting header Content-Length: <sizeof response> on the server side resolved the issue.

Comparing two integer arrays in Java

From what I see you just try to see if they are equal, if this is true, just go with something like this:

boolean areEqual = Arrays.equals(arr1, arr2);

This is the standard way of doing it.

Please note that the arrays must be also sorted to be considered equal, from the JavaDoc:

Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order.

Sorry for missing that.

IndentationError: unindent does not match any outer indentation level

Using Visual studio code

If you are using vs code than, it will convert all mix Indentation to either space or tabs using this simple steps below.

  1. press Ctrl + Shift + p

  2. type indent using spaces

  3. Press Enter

How to ignore SSL certificate errors in Apache HttpClient 4.0

Apache HttpClient 4.5.5

HttpClient httpClient = HttpClients
            .custom()
            .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, TrustAllStrategy.INSTANCE).build())
            .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
            .build();

No deprecated API has been used.

Simple verifiable test case:

package org.apache.http.client.test;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

public class ApacheHttpClientTest {

    private HttpClient httpClient;

    @Before
    public void initClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
        httpClient = HttpClients
                .custom()
                .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, TrustAllStrategy.INSTANCE).build())
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .build();
    }

    @Test
    public void apacheHttpClient455Test() throws IOException {
        executeRequestAndVerifyStatusIsOk("https://expired.badssl.com");
        executeRequestAndVerifyStatusIsOk("https://wrong.host.badssl.com");
        executeRequestAndVerifyStatusIsOk("https://self-signed.badssl.com");
        executeRequestAndVerifyStatusIsOk("https://untrusted-root.badssl.com");
        executeRequestAndVerifyStatusIsOk("https://revoked.badssl.com");
        executeRequestAndVerifyStatusIsOk("https://pinning-test.badssl.com");
        executeRequestAndVerifyStatusIsOk("https://sha1-intermediate.badssl.com");
    }

    private void executeRequestAndVerifyStatusIsOk(String url) throws IOException {
        HttpUriRequest request = new HttpGet(url);

        HttpResponse response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();

        assert statusCode == 200;
    }
}

Bootstrap: Use .pull-right without having to hardcode a negative margin-top

Keep the h2 at the top, then pull-left on the p and pull-right on the login-box

<div class='container'>
  <div class='hero-unit'>

    <h2>Welcome</h2>

    <div class="pull-left">
      <p>Please log in</p>
    </div>

    <div id='login-box' class='pull-right control-group'>
        <div class='clearfix'>
            <input type='text' placeholder='Username' />
        </div>
        <div class='clearfix'>
            <input type='password' placeholder='Password' />
        </div>
        <button type='button' class='btn btn-primary'>Log in</button>
    </div>

    <div class="clearfix"></div>

  </div>
</div>

the default vertical-align on floated boxes is baseline, so the "Please log in" exactly lines up with the "Username" (check by changing the pull-right to pull-left).

What is Parse/parsing?

Parsing can be considered as a synonym of "Breaking down into small pieces" and then analysing what is there or using it in a modified way. In Java, Strings are parsed into Decimal, Octal, Binary, Hexadecimal, etc. It is done if your application is taking input from the user in the form of string but somewhere in your application you want to use that input in the form of an integer or of double type. It is not same as type casting. For type casting the types used should be compatible in order to caste but nothing such in parsing.

Replace last occurrence of character in string

_x000D_
_x000D_
    // Define variables_x000D_
    let haystack = 'I do not want to replace this, but this'_x000D_
    let needle = 'this'_x000D_
    let replacement = 'hey it works :)'_x000D_
    _x000D_
    // Reverse it_x000D_
    haystack = Array.from(haystack).reverse().join('')_x000D_
    needle = Array.from(needle).reverse().join('')_x000D_
    replacement = Array.from(replacement).reverse().join('')_x000D_
    _x000D_
    // Make the replacement_x000D_
    haystack = haystack.replace(needle, replacement)_x000D_
    _x000D_
    // Reverse it back_x000D_
    let results = Array.from(haystack).reverse().join('')_x000D_
    console.log(results)_x000D_
    // 'I do not want to replace this, but hey it works :)'
_x000D_
_x000D_
_x000D_

How to convert from Hex to ASCII in JavaScript?

I found a useful function present in web3 library.

var hexString = "0x1231ac"
string strValue = web3.toAscii(hexString)

Multiple files upload in Codeigniter

_x000D_
_x000D_
<?php

if(isset($_FILES[$input_name]) && is_array($_FILES[$input_name]['name'])){
            $image_path = array();          
            $count = count($_FILES[$input_name]['name']);   
            for($key =0; $key <$count; $key++){     
                $_FILES['file']['name']     = $_FILES[$input_name]['name'][$key]; 
                $_FILES['file']['type']     = $_FILES[$input_name]['type'][$key]; 
                $_FILES['file']['tmp_name'] = $_FILES[$input_name]['tmp_name'][$key]; 
                $_FILES['file']['error']     = $_FILES[$input_name]['error'][$key]; 
                $_FILES['file']['size']     = $_FILES[$input_name]['size'][$key]; 
                    
                $config['file_name'] = $_FILES[$input_name]['name'][$key];                      
                $this->upload->initialize($config); 
                
                if($this->upload->do_upload('file')) {
                    $data = $this->upload->data();
                    $image_path[$key] = $path ."$data[file_name]";                  
                }else{
                    $error =  $this->upload->display_errors();
                $this->session->set_flashdata('msg_error',"image upload! ".$error);
                }   
            }
            return json_encode($image_path);
        }
    
    
   ?>
_x000D_
_x000D_
_x000D_

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

Since you claim to be used to JavaScript:

The Python in operator is similar to the JavaScript in operator.

Here's some JavaScript:

var d = {1: 2, 3: 4};
if (1 in d) {
    alert('true!');
}

And the equivalent Python:

d = {1: 2, 3: 4}
if 1 in d:
    print('true!')

With objects/dicts, they're nearly identical, both checking whether 1 is a key of the object/dict. The big difference, of course, is that JavaScript is sloppily-typed, so '1' in d would be just as true.

With arrays/lists, they're very different. A JS array is an object, and its indexes are the keys, so 1 in [3, 4, 5] will be true. A Python list is completely different from a dict, and its in operator checks the values, not the indexes, which tends to be more useful. And Python extends this behavior to all iterables.

With strings, they're even more different. A JS string isn't an object, so you will get a TypeError. But a Python str or unicode will check whether the other operand is a substring. (This means 1 in '123' is illegal, because 1 can't be a substring of anything, but '1' in '123' is true.)

With objects as objects, in JS there is of course no distinction, but in Python, objects are instances of classes, not dicts. So, in JS, 1 in d will be true for an object if it has a member or method named '1', but in Python, it's up to your class what it means—Python will call d.__contains__(1), then, if that fails, it tries to use your object as an utterable (by calling its __iter__, and, if that fails, by trying to index it with integers starting from 0).

Also, note that JS's in, because it's actually checking for object membership, does the usual JS method-resolution-order search, while Python's in, because it's checking for keys of a dict, members of a sequence, etc., does no such thing. So, technically, it's probably a bit closer to the hasOwnProperty method than the in operator.

Leverage browser caching, how on apache or .htaccess?

First we need to check if we have enabled mod_headers.c and mod_expires.c.

sudo apache2 -l

If we don't have it, we need to enable them

sudo a2enmod headers

Then we need to restart apache

sudo apache2 restart

At last, add the rules on .htaccess (seen on other answers), for example

ExpiresActive On
ExpiresByType image/gif A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType image/jpg A2592000
ExpiresByType image/png A2592000
ExpiresByType image/x-icon A2592000
ExpiresByType text/css A86400
ExpiresByType text/javascript A86400
ExpiresByType application/x-shockwave-flash A2592000
#
<FilesMatch "\.(gif|jpe?g|png|ico|css|js|swf)$">
Header set Cache-Control "public"
</FilesMatch>

Global Events in Angular

This is my version:

export interface IEventListenr extends OnDestroy{
    ngOnDestroy(): void
}

@Injectable()
export class EventManagerService {


    private listeners = {};
    private subject = new EventEmitter();
    private eventObserver = this.subject.asObservable();


    constructor() {

        this.eventObserver.subscribe(({name,args})=>{



             if(this.listeners[name])
             {
                 for(let listener of this.listeners[name])
                 {
                     listener.callback(args);
                 }
             }
        })

    }

    public registerEvent(eventName:string,eventListener:IEventListenr,callback:any)
    {

        if(!this.listeners[eventName])
             this.listeners[eventName] = [];

         let eventExist = false;
         for(let listener of this.listeners[eventName])
         {

             if(listener.eventListener.constructor.name==eventListener.constructor.name)
             {
                 eventExist = true;
                 break;
             }
         }

        if(!eventExist)
        {
             this.listeners[eventName].push({eventListener,callback});
        }
    }

    public unregisterEvent(eventName:string,eventListener:IEventListenr)
    {

        if(this.listeners[eventName])
        {
            for(let i = 0; i<this.listeners[eventName].length;i++)
            {

                if(this.listeners[eventName][i].eventListener.constructor.name==eventListener.constructor.name)
                {
                    this.listeners[eventName].splice(i, 1);
                    break;
                }
            }
        }


    }


    emit(name:string,...args:any[])
    {
        this.subject.next({name,args});
    }
}

use:

export class <YOURCOMPONENT> implements IEventListener{

  constructor(private eventManager: EventManagerService) {


    this.eventManager.registerEvent('EVENT_NAME',this,(args:any)=>{
       ....
    })


  }

  ngOnDestroy(): void {
    this.eventManager.unregisterEvent('closeModal',this)
  }

}

emit:

 this.eventManager.emit("EVENT_NAME");

How to export all data from table to an insertable sql format?

I have not seen any option in Microsoft SQL Server Management Studio 2012 to-date that will do that.

I am sure you can write something in T-SQL given the time.

Check out TOAD from QUEST - now owned by DELL.

http://www.toadworld.com/products/toad-for-oracle/f/10/t/9778.aspx

Select your rows.
Rt -click -> Export Dataset.
Choose Insert Statement format
Be sure to check “selected rows only”

Nice thing about toad, it works with both SQL server and Oracle. If you have to work with both, it is a good investment.

How to repeat a string a variable number of times in C++?

You should write your own stream manipulator

cout << multi(5) << "whatever" << "lolcat";

Notepad++ change text color?

A little late reply, but what I found in Notepad++ v7.8.6 is, on RMB (Right Mouse Button), on selection text, it gives an option called "Style token" where it shows "Using 1st/2nd/3rd/4th/5th style" to highlight the selected text in different pre-defined colors

What's the difference between implementation and compile in Gradle?

Since version 5.6.3 Gradle documentation provides simple rules of thumb to identify whether an old compile dependency (or a new one) should be replaced with an implementation or an api dependency:

  • Prefer the implementation configuration over api when possible

This keeps the dependencies off of the consumer’s compilation classpath. In addition, the consumers will immediately fail to compile if any implementation types accidentally leak into the public API.

So when should you use the api configuration? An API dependency is one that contains at least one type that is exposed in the library binary interface, often referred to as its ABI (Application Binary Interface). This includes, but is not limited to:

  • types used in super classes or interfaces
  • types used in public method parameters, including generic parameter types (where public is something that is visible to compilers. I.e. , public, protected and package private members in the Java world)
  • types used in public fields
  • public annotation types

By contrast, any type that is used in the following list is irrelevant to the ABI, and therefore should be declared as an implementation dependency:

  • types exclusively used in method bodies
  • types exclusively used in private members
  • types exclusively found in internal classes (future versions of Gradle will let you declare which packages belong to the public API)

How can I turn a List of Lists into a List in Java 8?

The flatMap method on Stream can certainly flatten those lists for you, but it must create Stream objects for element, then a Stream for the result.

You don't need all those Stream objects. Here is the simple, concise code to perform the task.

// listOfLists is a List<List<Object>>.
List<Object> result = new ArrayList<>();
listOfLists.forEach(result::addAll);

Because a List is Iterable, this code calls the forEach method (Java 8 feature), which is inherited from Iterable.

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. Actions are performed in the order of iteration, if that order is specified.

And a List's Iterator returns items in sequential order.

For the Consumer, this code passes in a method reference (Java 8 feature) to the pre-Java 8 method List.addAll to add the inner list elements sequentially.

Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator (optional operation).

Concatenate two JSON objects

The actual way is using JS Object.assign.

Object.assign(target, ...sources)

MDN Link

There is another object spread operator which is proposed for ES7 and can be used with Babel plugins.

 Obj = {...sourceObj1, ...sourceObj2}

android get all contacts

Cursor contacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
String aNameFromContacts[] = new String[contacts.getCount()];  
String aNumberFromContacts[] = new String[contacts.getCount()];  
int i = 0;

int nameFieldColumnIndex = contacts.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int numberFieldColumnIndex = contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

while(contacts.moveToNext()) {

    String contactName = contacts.getString(nameFieldColumnIndex);
    aNameFromContacts[i] =    contactName ; 

    String number = contacts.getString(numberFieldColumnIndex);
    aNumberFromContacts[i] =    number ;
i++;
}

contacts.close();

The result will be aNameFromContacts array full of contacts. Also ensure that you have added

<uses-permission android:name="android.permission.READ_CONTACTS" />

in main.xml

c++ array assignment of multiple values

You have to replace the values one by one such as in a for-loop or copying another array over another such as using memcpy(..) or std::copy

e.g.

for (int i = 0; i < arrayLength; i++) {
    array[i] = newValue[i];
}

Take care to ensure proper bounds-checking and any other checking that needs to occur to prevent an out of bounds problem.

How to rename a table column in Oracle 10g

suppose supply_master is a table, and

SQL>desc supply_master;


SQL>Name
 SUPPLIER_NO    
 SUPPLIER_NAME
 ADDRESS1       
 ADDRESS2       
 CITY           
 STATE          
 PINCODE  


SQL>alter table Supply_master rename column ADDRESS1 TO ADDR;
Table altered



SQL> desc Supply_master;
 Name                   
 -----------------------
 SUPPLIER_NO            
 SUPPLIER_NAME          
 ADDR   ///////////this has been renamed........//////////////                
 ADDRESS2               
 CITY                   
 STATE                  
 PINCODE                  

How to SSH into Docker?

These files will successfully open sshd and run service so you can ssh in locally. (you are using cyberduck aren't you?)

Dockerfile

FROM swiftdocker/swift
MAINTAINER Nobody

RUN apt-get update && apt-get -y install openssh-server supervisor
RUN mkdir /var/run/sshd
RUN echo 'root:password' | chpasswd
RUN sed -i 's/PermitRootLogin without-password/PermitRootLogin yes/' /etc/ssh/sshd_config

# SSH login fix. Otherwise user is kicked off after login
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd

ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile

COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf

EXPOSE 22
CMD ["/usr/bin/supervisord"]

supervisord.conf

[supervisord]
nodaemon=true

[program:sshd]
command=/usr/sbin/sshd -D

to build / run start daemon / jump into shell.

docker build -t swift3-ssh .  
docker run -p 2222:22 -i -t swift3-ssh
docker ps # find container id
docker exec -i -t <containerid> /bin/bash

enter image description here

SQL Order By Count

SELECT group, COUNT(*) FROM table GROUP BY group ORDER BY group

or to order by the count

SELECT group, COUNT(*) AS count FROM table GROUP BY group ORDER BY count DESC

How can I create directory tree in C++/Linux?

With C++17 or later, there's the standard header <filesystem> with function std::filesystem::create_directories which should be used in modern C++ programs. The C++ standard functions do not have the POSIX-specific explicit permissions (mode) argument, though.

However, here's a C function that can be compiled with C++ compilers.

/*
@(#)File:           mkpath.c
@(#)Purpose:        Create all directories in path
@(#)Author:         J Leffler
@(#)Copyright:      (C) JLSS 1990-2020
@(#)Derivation:     mkpath.c 1.16 2020/06/19 15:08:10
*/

/*TABSTOP=4*/

#include "posixver.h"
#include "mkpath.h"
#include "emalloc.h"

#include <errno.h>
#include <string.h>
/* "sysstat.h" == <sys/stat.h> with fixup for (old) Windows - inc mode_t */
#include "sysstat.h"

typedef struct stat Stat;

static int do_mkdir(const char *path, mode_t mode)
{
    Stat            st;
    int             status = 0;

    if (stat(path, &st) != 0)
    {
        /* Directory does not exist. EEXIST for race condition */
        if (mkdir(path, mode) != 0 && errno != EEXIST)
            status = -1;
    }
    else if (!S_ISDIR(st.st_mode))
    {
        errno = ENOTDIR;
        status = -1;
    }

    return(status);
}

/**
** mkpath - ensure all directories in path exist
** Algorithm takes the pessimistic view and works top-down to ensure
** each directory in path exists, rather than optimistically creating
** the last element and working backwards.
*/
int mkpath(const char *path, mode_t mode)
{
    char           *pp;
    char           *sp;
    int             status;
    char           *copypath = STRDUP(path);

    status = 0;
    pp = copypath;
    while (status == 0 && (sp = strchr(pp, '/')) != 0)
    {
        if (sp != pp)
        {
            /* Neither root nor double slash in path */
            *sp = '\0';
            status = do_mkdir(copypath, mode);
            *sp = '/';
        }
        pp = sp + 1;
    }
    if (status == 0)
        status = do_mkdir(path, mode);
    FREE(copypath);
    return (status);
}

#ifdef TEST

#include <stdio.h>
#include <unistd.h>

/*
** Stress test with parallel running of mkpath() function.
** Before the EEXIST test, code would fail.
** With the EEXIST test, code does not fail.
**
** Test shell script
** PREFIX=mkpath.$$
** NAME=./$PREFIX/sa/32/ad/13/23/13/12/13/sd/ds/ww/qq/ss/dd/zz/xx/dd/rr/ff/ff/ss/ss/ss/ss/ss/ss/ss/ss
** : ${MKPATH:=mkpath}
** ./$MKPATH $NAME &
** [...repeat a dozen times or so...]
** ./$MKPATH $NAME &
** wait
** rm -fr ./$PREFIX/
*/

int main(int argc, char **argv)
{
    int             i;

    for (i = 1; i < argc; i++)
    {
        for (int j = 0; j < 20; j++)
        {
            if (fork() == 0)
            {
                int rc = mkpath(argv[i], 0777);
                if (rc != 0)
                    fprintf(stderr, "%d: failed to create (%d: %s): %s\n",
                            (int)getpid(), errno, strerror(errno), argv[i]);
                exit(rc == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
            }
        }
        int status;
        int fail = 0;
        while (wait(&status) != -1)
        {
            if (WEXITSTATUS(status) != 0)
                fail = 1;
        }
        if (fail == 0)
            printf("created: %s\n", argv[i]);
    }
    return(0);
}

#endif /* TEST */

The macros STRDUP() and FREE() are error-checking versions of strdup() and free(), declared in emalloc.h (and implemented in emalloc.c and estrdup.c). The "sysstat.h" header deals with broken versions of <sys/stat.h> and can be replaced by <sys/stat.h> on modern Unix systems (but there were many issues back in 1990). And "mkpath.h" declares mkpath().

The change between v1.12 (original version of the answer) and v1.13 (amended version of the answer) was the test for EEXIST in do_mkdir(). This was pointed out as necessary by Switch — thank you, Switch. The test code has been upgraded and reproduced the problem on a MacBook Pro (2.3GHz Intel Core i7, running Mac OS X 10.7.4), and suggests that the problem is fixed in the revision (but testing can only show the presence of bugs, never their absence). The code shown is now v1.16; there have been cosmetic or administrative changes made since v1.13 (such as use mkpath.h instead of jlss.h and include <unistd.h> unconditionally in the test code only). It's reasonable to argue that "sysstat.h" should be replaced by <sys/stat.h> unless you have an unusually recalcitrant system.

(You are hereby given permission to use this code for any purpose with attribution.)

This code is available in my SOQ (Stack Overflow Questions) repository on GitHub as files mkpath.c and mkpath.h (etc.) in the src/so-0067-5039 sub-directory.

Good Free Alternative To MS Access

I'd the same problem of you. I had a MS access application but I wanted to go to a web application accessible to everybody and without paying money to MS. So I decided to use MySql and Wavemaker (open source) to get the scope..I'm very happy of this decision. and that's the result http://www.mara-database.org/

Force an Android activity to always use landscape mode

The following is the code which I used to display all activity in landscape mode:

<activity android:screenOrientation="landscape"
          android:configChanges="orientation|keyboardHidden"
          android:name="abcActivty"/>

Is there a shortcut to make a block comment in Xcode?

There is now an Xcode plugin that allows this: CComment.

The easiest way to install this is to use the amazing Alcatraz plugin manager for Xcode.

EDIT Apple has sadly (and wrongly, IMHO) retired the old plugin model with Xcode 8. The new plugin system is quite limited, but should allow development of a plugin like this again. For anyone interested in doing this, watch WWDC 2016 session 414. Also, please file radars for API for plugins you'd like to write or see.

How to use order by with union all in sql?

Select 'Shambhu' as ShambhuNewsFeed,Note as [News Fedd],NotificationId
from Notification with(nolock) where DesignationId=@Designation 
Union All 
Select 'Shambhu' as ShambhuNewsFeed,Note as [Notification],NotificationId
from Notification with(nolock) 
where DesignationId=@Designation 
order by NotificationId desc

Xcode is not currently available from the Software Update server

Had the same issue and was getting the same error. When i ran xcode-select -p, it gave output as /Library/Developer/CommandLineTools. So that means xcode was already installed in my system. Then i ran steps as given on this answer. After which any command which required xcode ran successfully.

Get individual query parameters from Uri

You could reference System.Web in your console application and then look for the Utility functions that split the URL parameters.

Delete all the records

For one table

truncate table [table name]

For all tables

EXEC sp_MSforeachtable @command1="truncate table ?"

Android RelativeLayout programmatically Set "centerInParent"

Completely untested, but this should work:

View positiveButton = findViewById(R.id.positiveButton);
RelativeLayout.LayoutParams layoutParams = 
    (RelativeLayout.LayoutParams)positiveButton.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
positiveButton.setLayoutParams(layoutParams);

add android:configChanges="orientation|screenSize" inside your activity in your manifest

In laymans terms, what does 'static' mean in Java?

In addition to what @inkedmn has pointed out, a static member is at the class level. Therefore, the said member is loaded into memory by the JVM once for that class (when the class is loaded). That is, there aren't n instances of a static member loaded for n instances of the class to which it belongs.

How an 'if (A && B)' statement is evaluated?

Yes, it is called Short-circuit Evaluation.

If the validity of the boolean statement can be assured after part of the statement, the rest is not evaluated.

This is very important when some of the statements have side-effects.

How to justify a single flexbox item (override justify-content)

AFAIK there is no property for that in the specs, but here is a trick I’ve been using: set the container element ( the one with display:flex ) to justify-content:space-around Then add an extra element between the first and second item and set it to flex-grow:10 (or some other value that works with your setup)

Edit: if the items are tightly aligned it's a good idea to add flex-shrink: 10; to the extra element as well, so the layout will be properly responsive on smaller devices.

Are there benefits of passing by pointer over passing by reference in C++?

Passing by pointer

  • Caller has to take the address -> not transparent
  • A 0 value can be provided to mean nothing. This can be used to provide optional arguments.

Pass by reference

  • Caller just passes the object -> transparent. Has to be used for operator overloading, since overloading for pointer types is not possible (pointers are builtin types). So you can't do string s = &str1 + &str2; using pointers.
  • No 0 values possible -> Called function doesn't have to check for them
  • Reference to const also accepts temporaries: void f(const T& t); ... f(T(a, b, c));, pointers cannot be used like that since you cannot take the address of a temporary.
  • Last but not least, references are easier to use -> less chance for bugs.

How to implement swipe gestures for mobile devices?

NOTE: Greatly inspired by EscapeNetscape's answer, I've made an edit of his script using modern javascript in a comment. I made an answer of this due to user interest and a massive 4h jsfiddle.net downtime. I chose not to edit the original answer since it would change everything...


Here is a detectSwipe function, working pretty well (used on one of my websites). I'd suggest you read it before you use it. Feel free to review it/edit the answer.

_x000D_
_x000D_
// usage example_x000D_
detectSwipe('swipeme', (el, dir) => alert(`you swiped on element with id ${el.id} to ${dir} direction`))_x000D_
_x000D_
// source code_x000D_
_x000D_
// Tune deltaMin according to your needs. Near 0 it will almost_x000D_
// always trigger, with a big value it can never trigger._x000D_
function detectSwipe(id, func, deltaMin = 90) {_x000D_
  const swipe_det = {_x000D_
    sX: 0,_x000D_
    sY: 0,_x000D_
    eX: 0,_x000D_
    eY: 0_x000D_
  }_x000D_
  // Directions enumeration_x000D_
  const directions = Object.freeze({_x000D_
    UP: 'up',_x000D_
    DOWN: 'down',_x000D_
    RIGHT: 'right',_x000D_
    LEFT: 'left'_x000D_
  })_x000D_
  let direction = null_x000D_
  const el = document.getElementById(id)_x000D_
  el.addEventListener('touchstart', function(e) {_x000D_
    const t = e.touches[0]_x000D_
    swipe_det.sX = t.screenX_x000D_
    swipe_det.sY = t.screenY_x000D_
  }, false)_x000D_
  el.addEventListener('touchmove', function(e) {_x000D_
    // Prevent default will stop user from scrolling, use with care_x000D_
    // e.preventDefault();_x000D_
    const t = e.touches[0]_x000D_
    swipe_det.eX = t.screenX_x000D_
    swipe_det.eY = t.screenY_x000D_
  }, false)_x000D_
  el.addEventListener('touchend', function(e) {_x000D_
    const deltaX = swipe_det.eX - swipe_det.sX_x000D_
    const deltaY = swipe_det.eY - swipe_det.sY_x000D_
    // Min swipe distance, you could use absolute value rather_x000D_
    // than square. It just felt better for personnal use_x000D_
    if (deltaX ** 2 + deltaY ** 2 < deltaMin ** 2) return_x000D_
    // horizontal_x000D_
    if (deltaY === 0 || Math.abs(deltaX / deltaY) > 1)_x000D_
      direction = deltaX > 0 ? directions.RIGHT : directions.LEFT_x000D_
    else // vertical_x000D_
      direction = deltaY > 0 ? directions.UP : directions.DOWN_x000D_
_x000D_
    if (direction && typeof func === 'function') func(el, direction)_x000D_
_x000D_
    direction = null_x000D_
  }, false)_x000D_
}
_x000D_
#swipeme {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  background-color: orange;_x000D_
  color: black;_x000D_
  text-align: center;_x000D_
  padding-top: 20%;_x000D_
  padding-bottom: 20%;_x000D_
}
_x000D_
<div id='swipeme'>_x000D_
  swipe me_x000D_
</div>
_x000D_
_x000D_
_x000D_

Disable Proximity Sensor during call

I found my solution here. Basically use an app called Proximity Screen Off Lite and set it as below:

  1. Screen On/Off Modes Check "Cover and hold to turn on Screen" Timeout: 1 second Check "Disable Accidentla Lock" Timeout: 4 seconds

  2. All settings Check "Disable in Lanscape" Check "Lock phone on screen ON"

  3. [Advanced] Configure Sensore Select sensor: Proximity sensor Value when sensor covered: 0 Value when sensor un-covered: 1

ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

On CentOS Linux, Python3.6, I edited this file (make a backup copy first)

/usr/lib/python3.6/site-packages/certifi/cacert.pem

to the end of the file, I added my public certificate from my .pem file. you should be able to obtain the .pem file from your ssl certificate provider.

How to detect my browser version and operating system using JavaScript?

For Firefox, Chrome, Opera, Internet Explorer and Safari

var ua="Mozilla/1.22 (compatible; MSIE 10.0; Windows 3.1)";
//ua = navigator.userAgent;
var b;
var browser;
if(ua.indexOf("Opera")!=-1) {

    b=browser="Opera";
}
if(ua.indexOf("Firefox")!=-1 && ua.indexOf("Opera")==-1) {
    b=browser="Firefox";
    // Opera may also contains Firefox
}
if(ua.indexOf("Chrome")!=-1) {
    b=browser="Chrome";
}
if(ua.indexOf("Safari")!=-1 && ua.indexOf("Chrome")==-1) {
    b=browser="Safari";
    // Chrome always contains Safari
}

if(ua.indexOf("MSIE")!=-1 && (ua.indexOf("Opera")==-1 && ua.indexOf("Trident")==-1)) {
    b="MSIE";
    browser="Internet Explorer";
    //user agent with MSIE and Opera or MSIE and Trident may exist.
}

if(ua.indexOf("Trident")!=-1) {
    b="Trident";
    browser="Internet Explorer";
}

// now for version


var version=ua.match(b+"[ /]+[0-9]+(.[0-9]+)*")[0];

console.log("broswer",browser);
console.log("version",version);

Check if object is a jQuery object

However, There is one more way to check the object in jQuery.

jQuery.type(a); //this returns type of variable.

I have made example to understand things, jsfiddle link

Deleting all files from a folder using PHP?

foreach (new DirectoryIterator('/path/to/directory') as $fileInfo) {
    if(!$fileInfo->isDot()) {
        unlink($fileInfo->getPathname());
    }
}

How do I make a placeholder for a 'select' box?

See this answer :

<select>
        <option style="display: none;" value="" selected>SelectType</option>
        <option value="1">Type 1</option>
        <option value="2">Type 2</option>
        <option value="3">Type 3</option>
        <option value="4">Type 4</option>
</select>

Spring Data JPA findOne() change to Optional how to use this?

The method has been renamed to findById(…) returning an Optional so that you have to handle absence yourself:

Optional<Foo> result = repository.findById(…);

result.ifPresent(it -> …); // do something with the value if present
result.map(it -> …); // map the value if present
Foo foo = result.orElse(null); // if you want to continue just like before

If else on WHERE clause

try this ,hope it helps

select user_display_image as user_image,
user_display_name as user_name,
invitee_phone,
(
 CASE 
    WHEN invitee_status=1 THEN "attending" 
    WHEN invitee_status=2 THEN "unsure" 
    WHEN invitee_status=3 THEN "declined" 
    WHEN invitee_status=0 THEN "notreviwed" END
) AS  invitee_status
 FROM your_tbl

Adding Python Path on Windows 7

You can set the path from the current cmd window using the PATH = command. That will only add it for the current cmd instance. if you want to add it permanently, you should add it to system variables. (Computer > Advanced System Settings > Environment Variables)

You would goto your cmd instance, and put in PATH=C:/Python27/;%PATH%.

ERROR : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

I got a similar error, which was resolved by installing the corresponding MySQL drivers from:

http://www.connectionstrings.com/mysql-connector-odbc-5-2/info-and-download/

and by performing the following steps:

  1. Go to IIS and Application Pools in the left menu.
  2. Select relevant application pool which is assigned to the project.
  3. Click the Set Application Pool Defaults.
  4. In General Tab, set the Enable 32 Bit Application entry to "True".

Reference:

http://www.codeproject.com/Tips/305249/ERROR-IM-Microsoft-ODBC-Driver-Manager-Data-sou

Get JSON object from URL

You need to read about json_decode function http://php.net/manual/en/function.json-decode.php

Here you go

$json = '{"expires_in":5180976,"access_token":"AQXzQgKTpTSjs-qiBh30aMgm3_Kb53oIf-VA733BpAogVE5jpz3jujU65WJ1XXSvVm1xr2LslGLLCWTNV5Kd_8J1YUx26axkt1E-vsOdvUAgMFH1VJwtclAXdaxRxk5UtmCWeISB6rx6NtvDt7yohnaarpBJjHWMsWYtpNn6nD87n0syud0"}';
//OR $json = file_get_contents('http://someurl.dev/...');

$obj = json_decode($json);
var_dump($obj-> access_token);

//OR 

$arr = json_decode($json, true);
var_dump($arr['access_token']);

Where is the user's Subversion config file stored on the major operating systems?

~/.subversion/config or /etc/subversion/config

for Mac/Linux

and

%appdata%\subversion\config

for Windows

SQL Query to find missing rows between two related tables

SELECT A.ABC_ID, A.VAL FROM A WHERE NOT EXISTS 
   (SELECT * FROM B WHERE B.ABC_ID = A.ABC_ID AND B.VAL = A.VAL)

or

SELECT A.ABC_ID, A.VAL FROM A WHERE VAL NOT IN 
    (SELECT VAL FROM B WHERE B.ABC_ID = A.ABC_ID)

or

SELECT A.ABC_ID, A.VAL LEFT OUTER JOIN B 
    ON A.ABC_ID = B.ABC_ID AND A.VAL = B.VAL FROM A WHERE B.VAL IS NULL

Please note that these queries do not require that ABC_ID be in table B at all. I think that does what you want.

jQuery get the id/value of <li> element after click function

If You Have Multiple li elements inside an li element then this will definitely help you, and i have checked it and it works....

<script>
$("li").on('click', function() {
          alert(this.id);
          return false;
      });
</script>

What's the right way to decode a string that has special HTML entities in it?

This is my favourite way of decoding HTML characters. The advantage of using this code is that tags are also preserved.

function decodeHtml(html) {
    var txt = document.createElement("textarea");
    txt.innerHTML = html;
    return txt.value;
}

Example: http://jsfiddle.net/k65s3/

Input:

Entity:&nbsp;Bad attempt at XSS:<script>alert('new\nline?')</script><br>

Output:

Entity: Bad attempt at XSS:<script>alert('new\nline?')</script><br>

What does "Content-type: application/json; charset=utf-8" really mean?

Note that IETF RFC4627 has been superseded by IETF RFC7158. In section [8.1] it retracts the text cited by @Drew earlier by saying:

Implementations MUST NOT add a byte order mark to the beginning of a JSON text.

Refresh Part of Page (div)

Let's assume that you have 2 divs inside of your html file.

<div id="div1">some text</div>
<div id="div2">some other text</div>

The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.

You can, however, communicate between the server (the back-end) and the client.

What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.

Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.

setInterval(function()
{
    alert("hi");
}, 30000);

You could also do it like this:

setTimeout(foo, 30000);

Whereea foo is a function.

Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.

A classic AJAX looks like this:

var fetch = true;
var url = 'someurl.java';
$.ajax(
{
    // Post the variable fetch to url.
    type : 'post',
    url : url,
    dataType : 'json', // expected returned data format.
    data : 
    {
        'fetch' : fetch // You might want to indicate what you're requesting.
    },
    success : function(data)
    {
        // This happens AFTER the backend has returned an JSON array (or other object type)
        var res1, res2;

        for(var i = 0; i < data.length; i++)
        {
            // Parse through the JSON array which was returned.
            // A proper error handling should be added here (check if
            // everything went successful or not)

            res1 = data[i].res1;
            res2 = data[i].res2;

            // Do something with the returned data
            $('#div1').html(res1);
        }
    },
    complete : function(data)
    {
        // do something, not critical.
    }
});

Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.

I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.

how to view the contents of a .pem certificate

An alternative to using keytool, you can use the command

openssl x509 -in certificate.pem -text

This should work for any x509 .pem file provided you have openssl installed.

Selenium C# WebDriver: Wait until element is present

WebDriverWait won't take effect.

var driver = new FirefoxDriver(
    new FirefoxOptions().PageLoadStrategy = PageLoadStrategy.Eager
);
driver.Navigate().GoToUrl("xxx");
new WebDriverWait(driver, TimeSpan.FromSeconds(60))
    .Until(d => d.FindElement(By.Id("xxx"))); // A tag that close to the end

This would immediately throw an exception once the page was "interactive". I don't know why, but the timeout acts as if it does not exist.

Perhaps SeleniumExtras.WaitHelpers works, but I didn't try. It's official, but it was split out into another NuGet package. You can refer to C# Selenium 'ExpectedConditions is obsolete'.

I use FindElements and check Count == 0. If true, use await Task.Delay. It's really not quite efficient.

How to send emails from my Android application?

I've been using this since long time ago and it seems good, no non-email apps showing up. Just another way to send a send email intent:

Intent intent = new Intent(Intent.ACTION_SENDTO); // it's not ACTION_SEND
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject of email");
intent.putExtra(Intent.EXTRA_TEXT, "Body of email");
intent.setData(Uri.parse("mailto:[email protected]")); // or just "mailto:" for blank
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // this will make such that when user returns to your app, your app is displayed, instead of the email app.
startActivity(intent);

What range of values can integer types store in C++

The size of the numerical types is not defined in the C++ standard, although the minimum sizes are. The way to tell what size they are on your platform is to use numeric limits

For example, the maximum value for a int can be found by:

std::numeric_limits<int>::max();

Computers don't work in base 10, which means that the maximum value will be in the form of 2n-1 because of how the numbers of represent in memory. Take for example eight bits (1 byte)

  0100 1000

The right most bit (number) when set to 1 represents 20, the next bit 21, then 22 and so on until we get to the left most bit which if the number is unsigned represents 27.

So the number represents 26 + 23 = 64 + 8 = 72, because the 4th bit from the right and the 7th bit right the left are set.

If we set all values to 1:

11111111

The number is now (assuming unsigned)
128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255 = 28 - 1
And as we can see, that is the largest possible value that can be represented with 8 bits.

On my machine and int and a long are the same, each able to hold between -231 to 231 - 1. In my experience the most common size on modern 32 bit desktop machine.

How to correctly catch change/focusOut event on text input in React.js?

Its late, yet it's worth your time nothing that, there are some differences in browser level implementation of focusin and focusout events and react synthetic onFocus and onBlur. focusin and focusout actually bubble, while onFocus and onBlur dont. So there is no exact same implementation for focusin and focusout as of now for react. Anyway most cases will be covered in onFocus and onBlur.

How to use paginator from material angular?

I'm struggling with the same here. But I can show you what I've got doing some research. Basically, you first start adding the page @Output event in the foo.template.ts:

 <md-paginator #paginator
                [length]="length"
                [pageIndex]="pageIndex"
                [pageSize]="pageSize"
                [pageSizeOptions]="[5, 10, 25, 100]"
                (page)="pageEvent = getServerData($event)"
                >
 </md-paginator>

And later, you have to add the pageEvent attribute in the foo.component.ts class and the others to handle paginator requirements:

pageEvent: PageEvent;
datasource: null;
pageIndex:number;
pageSize:number;
length:number;

And add the method that will fetch the server data:

ngOnInit() {
   getServerData(null) ...
}

public getServerData(event?:PageEvent){
  this.fooService.getdata(event).subscribe(
    response =>{
      if(response.error) {
        // handle error
      } else {
        this.datasource = response.data;
        this.pageIndex = response.pageIndex;
        this.pageSize = response.pageSize;
        this.length = response.length;
      }
    },
    error =>{
      // handle error
    }
  );
  return event;
}

So, basically every time you click the paginator, you'll activate getServerData(..) method that will call foo.service.ts getting all data required. In this case, you do not need to handle nextPage and nextXXX events because it will be automatically calculated upon view rendering.

Hope this can help you. Let me know if you had success. =]

Selecting data from two different servers in SQL Server

As @Super9 told about OPENDATASOURCE using SQL Server Authentication with data provider SQLOLEDB . I am just posting here a code snippet for one table is in the current sever database where the code is running and another in other server '192.166.41.123'

SELECT top 2 * from dbo.tblHamdoonSoft  tbl1 inner JOIN  
OpenDataSource('SQLOLEDB','Data Source=192.166.41.123;User ID=sa;Password=hamdoonsoft')
.[TestDatabase].[dbo].[tblHamdoonSoft1] tbl2 on tbl1.id = tbl2.id

Angular.js: How does $eval work and why is it different from vanilla eval?

$eval and $parse don't evaluate JavaScript; they evaluate AngularJS expressions. The linked documentation explains the differences between expressions and JavaScript.

Q: What exactly is $eval doing? Why does it need its own mini parsing language?

From the docs:

Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. Expressions are processed by $parse service.

It's a JavaScript-like mini-language that limits what you can run (e.g. no control flow statements, excepting the ternary operator) as well as adds some AngularJS goodness (e.g. filters).

Q: Why isn't plain old javascript "eval" being used?

Because it's not actually evaluating JavaScript. As the docs say:

If ... you do want to run arbitrary JavaScript code, you should make it a controller method and call the method. If you want to eval() an angular expression from JavaScript, use the $eval() method.

The docs linked to above have a lot more information.

Extract MSI from EXE

I'm guessing this question was mainly about InstallShield given the tags, but in case anyone comes here with the same problem for WiX-based packages (and possibly others), just call the installer with /extract, like so:

C:\> installer.exe /extract

That'll place the MSI in the folder alongside the installer.

Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

Using ios_base::sync_with_stdio(false); is sufficient to decouple the C and C++ streams. You can find a discussion of this in Standard C++ IOStreams and Locales, by Langer and Kreft. They note that how this works is implementation-defined.

The cin.tie(NULL) call seems to be requesting a decoupling between the activities on cin and cout. I can't explain why using this with the other optimization should cause a crash. As noted, the link you supplied is bad, so no speculation here.

Android Completely transparent Status Bar?

add these lines into your Activity before the setContentView()

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    Window w = getWindow();
    w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}

add these 2 lines into your AppTheme

<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>

and last thing your minSdkVersion must b 19

minSdkVersion 19

'Access-Control-Allow-Origin' issue when API call made from React (Isomorphic app)

Because the server don't have CORS header, so you are not allowed to get the response.

This is header from API that I captured from Chrome brower:

Age:28
Cache-Control:max-age=3600, public
Connection:keep-alive
Date:Fri, 06 Jan 2017 02:05:33 GMT
ETag:"18303ae5d3714f8f1fbcb2c8e6499190"
Server:Cowboy
Status:200 OK
Via:1.1 vegur, 1.1 e01a35c1b8f382e5c0a399f1741255fd.cloudfront.net (CloudFront)
X-Amz-Cf-Id:GH6w6y_P5ht7AqAD3SnlK39EJ0PpnignqSI3o5Fsbi9PKHEFNMA0yw==
X-Cache:Hit from cloudfront
X-Content-Type-Options:nosniff
X-Frame-Options:SAMEORIGIN
X-Request-Id:b971e55f-b43d-43ce-8d4f-aa9d39830629
X-Runtime:0.014042
X-Ua-Compatible:chrome=1
X-Xss-Protection:1; mode=block

No CORS header in response headers.

How to create a new column in a select query

It depends what you wanted to do with that column e.g. here's an example of appending a new column to a recordset which can be updated on the client side:

Sub MSDataShape_AddNewCol()

  Dim rs As ADODB.Recordset
  Set rs = CreateObject("ADODB.Recordset")
  With rs
    .ActiveConnection = _
    "Provider=MSDataShape;" & _
    "Data Provider=Microsoft.Jet.OLEDB.4.0;" & _
    "Data Source=C:\Tempo\New_Jet_DB.mdb"
    .Source = _
    "SHAPE {" & _
    " SELECT ExistingField" & _
    " FROM ExistingTable" & _
    " ORDER BY ExistingField" & _
    "} APPEND NEW adNumeric(5, 4) AS NewField"

    .LockType = adLockBatchOptimistic

    .Open

    Dim i As Long
    For i = 0 To .RecordCount - 1
      .Fields("NewField").Value = Round(.Fields("ExistingField").Value, 4)
      .MoveNext
    Next

    rs.Save "C:\rs.xml", adPersistXML

  End With
End Sub

PHP date time greater than today

You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015 > 01/02/2016 because 09 > 01. You need to either put your date in a comparable string format or compare DateTime objects which are comparable.

<?php
 $date_now = date("Y-m-d"); // this format is string comparable

if ($date_now > '2016-01-02') {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Or

<?php
 $date_now = new DateTime();
 $date2    = new DateTime("01/02/2016");

if ($date_now > $date2) {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Playing a MP3 file in a WinForm application

You can use the mciSendString API to play an MP3 or a WAV file:

[DllImport("winmm.dll")]
public static extern uint mciSendString( 
    string lpstrCommand,
    StringBuilder lpstrReturnString,
    int uReturnLength,
    IntPtr hWndCallback
);

mciSendString(@"close temp_alias", null, 0, IntPtr.Zero);
mciSendString(@"open ""music.mp3"" alias temp_alias", null, 0, IntPtr.Zero);
mciSendString("play temp_alias repeat", null, 0, IntPtr.Zero);

String contains another two strings

That is because the if statements returns false since d doesn't contain b + a i.e "someonedamage"

How to use split?

Look in JavaScript split() Method

Usage:

"something -- something_else".split(" -- ") 

How to use Boost in Visual Studio 2010

In addition, there is something I find very useful. Use environment variables for your boost paths. (How to set environment variables in windows, link at bottom for 7,8,10) The BOOST_ROOT variable seems to be common place anymore and is set to the root path where you unzip boost.

Then in Properties, c++, general, Additional Include Directories use $(BOOST_ROOT). Then if/when you move to a newer version of the boost library you can update your environment variable to point to this newer version. As more of your projects, use boost you will not have to update the 'Additional Include Directories' for all of them.

You may also create a BOOST_LIB variable and point it to where the libs are staged. So likewise for the Linker->Additional Library Directories, you won't have to update projects. I have some old stuff built with vs10 and new stuff with vs14 so built both flavors of the boost lib to the same folder. So if I move a project from vs10 to vs14 I don't have to change the boost paths.

NOTE: If you change an environment variable it will not suddenly work in an open VS project. VS loads variables on startup. So you will have to close VS and reopen it.

How to download Javadoc to read offline?

F.ex. http://docs.oracle.com/javase/7/docs/ has a link to download "JDK 7 Documentation" in the sidebar under "Downloads". I'd expect the same for other versions.

How to get previous month and year relative to today, using strtotime and date?

strtotime have second timestamp parameter that make the first parameter relative to second parameter. So you can do this:

date('Y-m', strtotime('-1 month', time()))

How to uncheck a radio button?

function setRadio(obj) 
{
    if($("input[name='r_"+obj.value+"']").val() == 0 ){
      obj.checked = true
     $("input[name='r_"+obj.value+"']").val(1);
    }else{
      obj.checked = false;
      $("input[name='r_"+obj.value+"']").val(0);
    }

}

<input type="radio" id="planoT" name="planoT[{ID_PLANO}]" value="{ID_PLANO}" onclick="setRadio(this)" > <input type="hidden" id="r_{ID_PLANO}" name="r_{ID_PLANO}" value="0" >

:D

Check if checkbox is checked with jQuery

IDs must be unique in your document, meaning that you shouldn't do this:

<input type="checkbox" name="chk[]" id="chk[]" value="Apples" />
<input type="checkbox" name="chk[]" id="chk[]" value="Bananas" />

Instead, drop the ID, and then select them by name, or by a containing element:

<fieldset id="checkArray">
    <input type="checkbox" name="chk[]" value="Apples" />

    <input type="checkbox" name="chk[]" value="Bananas" />
</fieldset>

And now the jQuery:

var atLeastOneIsChecked = $('#checkArray:checkbox:checked').length > 0;
//there should be no space between identifier and selector

// or, without the container:

var atLeastOneIsChecked = $('input[name="chk[]"]:checked').length > 0;

How to extract this specific substring in SQL Server?

An alternative to the answer provided by @Marc

SELECT SUBSTRING(LEFT(YOUR_FIELD, CHARINDEX('[', YOUR_FIELD) - 1), CHARINDEX(';', YOUR_FIELD) + 1, 100)
FROM YOUR_TABLE
WHERE CHARINDEX('[', YOUR_FIELD) > 0 AND
    CHARINDEX(';', YOUR_FIELD) > 0;

This makes sure the delimiters exist, and solves an issue with the currently accepted answer where doing the LEFT last is working with the position of the last delimiter in the original string, rather than the revised substring.

How to get first record in each group using Linq

var result = input.GroupBy(x=>x.F1,(key,g)=>g.OrderBy(e=>e.F2).First());

ps command doesn't work in docker container

Firstly, run the command below:

apt-get update && apt-get install procps

and then run:

ps -ef

Disable arrow key scrolling in users browser

Summary

Simply prevent the default browser action:

window.addEventListener("keydown", function(e) {
    // space and arrow keys
    if([32, 37, 38, 39, 40].indexOf(e.code) > -1) {
        e.preventDefault();
    }
}, false);

If you need to support Internet Explorer or other older browsers, use e.keyCode instead of e.code, but keep in mind that keyCode is deprecated.

Original answer

I used the following function in my own game:

var keys = {};
window.addEventListener("keydown",
    function(e){
        keys[e.code] = true;
        switch(e.code){
            case 37: case 39: case 38:  case 40: // Arrow keys
            case 32: e.preventDefault(); break; // Space
            default: break; // do not block other keys
        }
    },
false);
window.addEventListener('keyup',
    function(e){
        keys[e.code] = false;
    },
false);

The magic happens in e.preventDefault();. This will block the default action of the event, in this case moving the viewpoint of the browser.

If you don't need the current button states you can simply drop keys and just discard the default action on the arrow keys:

var arrow_keys_handler = function(e) {
    switch(e.code){
        case 37: case 39: case 38:  case 40: // Arrow keys
        case 32: e.preventDefault(); break; // Space
        default: break; // do not block other keys
    }
};
window.addEventListener("keydown", arrow_keys_handler, false);

Note that this approach also enables you to remove the event handler later if you need to re-enable arrow key scrolling:

window.removeEventListener("keydown", arrow_keys_handler, false);

References

Remove whitespaces inside a string in javascript

For space-character removal use

"hello world".replace(/\s/g, "");

for all white space use the suggestion by Rocket in the comments below!

ASP.NET MVC get textbox input value

you can do it so simple:

First: For Example in Models you have User.cs with this implementation

public class User
 {
   public string username { get; set; }
   public string age { get; set; }
 } 

We are passing the empty model to user – This model would be filled with user’s data when he submits the form like this

public ActionResult Add()
{
  var model = new User();
  return View(model);
}

When you return the View by empty User as model, it maps with the structure of the form that you implemented. We have this on HTML side:

@model MyApp.Models.Student
@using (Html.BeginForm()) 
 {
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Student</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.username, htmlAttributes: new { 
                           @class = "control-label col-md-2" })
            <div class="col-md-10">
                 @Html.EditorFor(model => model.username, new { 
                                 htmlAttributes = new { @class = "form-
                                 control" } })
                 @Html.ValidationMessageFor(model => model.userame, "", 
                                            new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.age, htmlAttributes: new { @class 
                           = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.age, new { htmlAttributes = 
                                new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.age, "", new { 
                                           @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" 
                 />
            </div>
        </div>
   </div>
}

So on button submit you will use it like this

[HttpPost]
public ActionResult Add(User user)
 {
   // now user.username has the value that user entered on form
 }

How to Delete a topic in apache kafka

Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable to true) on all brokers first.

Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable is by default true.

Follow this step by step process for manual deletion of topics

  1. Stop Kafka server
  2. Delete the topic directory, on each broker (as defined in the logs.dirs and log.dir properties) with rm -rf command
  3. Connect to Zookeeper instance: zookeeper-shell.sh host:port
  4. From within the Zookeeper instance:
    1. List the topics using: ls /brokers/topics
    2. Remove the topic folder from ZooKeeper using: rmr /brokers/topics/yourtopic
    3. Exit the Zookeeper instance (Ctrl+C)
  5. Restart Kafka server
  6. Confirm if it was deleted or not by using this command kafka-topics.sh --list --zookeeper host:port

iOS detect if user is on an iPad

You can also use this

#define IPAD UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad
...
if (IPAD) {
   // iPad
} else {
   // iPhone / iPod Touch
}

Using Linq select list inside list

After my previous answer disaster, I'm going to try something else.

List<Model> usrList  = 
(list.Where(n => n.application == "applicationame").ToList());
usrList.ForEach(n => n.users.RemoveAll(n => n.surname != "surname"));

How to check if a string is null in python

Try this:

if cookie and not cookie.isspace():
    # the string is non-empty
else:
    # the string is empty

The above takes in consideration the cases where the string is None or a sequence of white spaces.

Convert date from 'Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)' to 'YYYY-MM-DD' in javascript

 function convertDatePickerTimeToMySQLTime(str) {
        var month, day, year, hours, minutes, seconds;
        var date = new Date(str),
            month = ("0" + (date.getMonth() + 1)).slice(-2),
            day = ("0" + date.getDate()).slice(-2);
        hours = ("0" + date.getHours()).slice(-2);
        minutes = ("0" + date.getMinutes()).slice(-2);
        seconds = ("0" + date.getSeconds()).slice(-2);

        var mySQLDate = [date.getFullYear(), month, day].join("-");
        var mySQLTime = [hours, minutes, seconds].join(":");
        return [mySQLDate, mySQLTime].join(" ");
    }

How to convert object to Dictionary<TKey, TValue> in C#?

You can create a generic extension method and then use it on the object like:

public static class Extensions
{
    public static KeyValuePair<TKey, TValue> ToKeyValuePair<TKey, TValue>(this Object obj)
    {
        // if obj is null throws exception
        Contract.Requires(obj != null);

        // gets the type of the obj parameter
        var type = obj.GetType();
        // checks if obj is of type KeyValuePair
        if (type.IsGenericType && type == typeof(KeyValuePair<TKey, TValue>))
        {

            return new KeyValuePair<TKey, TValue>(
                                                    (TKey)type.GetProperty("Key").GetValue(obj, null), 
                                                    (TValue)type.GetProperty("Value").GetValue(obj, null)
                                                 );

        }
        // if obj type does not match KeyValuePair throw exception
        throw new ArgumentException($"obj argument must be of type KeyValuePair<{typeof(TKey).FullName},{typeof(TValue).FullName}>");   
 }

and usage would be like:

KeyValuePair<string,long> kvp = obj.ToKeyValuePair<string,long>();

How to validate numeric values which may contain dots or commas?

\d means a digit in most languages. You can also use [0-9] in all languages. For the "period or comma" use [\.,]. Depending on your language you may need more backslashes based on how you quote the expression. Ultimately, the regular expression engine needs to see a single backslash.

* means "zero-or-more", so \d* and [0-9]* mean "zero or more numbers". ? means "zero-or-one". Neither of those qualifiers means exactly one. Most languages also let you use {m,n} to mean "between m and n" (ie: {1,2} means "between 1 and 2")

Since the dot or comma and additional numbers are optional, you can put them in a group and use the ? quantifier to mean "zero-or-one" of that group.

Putting that all together you can use:

\d{1,2}([\.,][\d{1,2}])?

Meaning, one or two digits \d{1,2}, followed by zero-or-one of a group (...)? consisting of a dot or comma followed by one or two digits [\.,]\d{1,2}

How to Define Callbacks in Android?

Example to implement callback method using interface.

Define the interface, NewInterface.java.

package javaapplication1;

public interface NewInterface {
    void callback();
}

Create a new class, NewClass.java. It will call the callback method in main class.

package javaapplication1;

public class NewClass {

    private NewInterface mainClass;

    public NewClass(NewInterface mClass){
        mainClass = mClass;
    }

    public void calledFromMain(){
        //Do somthing...

        //call back main
        mainClass.callback();
    }
}

The main class, JavaApplication1.java, to implement the interface NewInterface - callback() method. It will create and call NewClass object. Then, the NewClass object will callback it's callback() method in turn.

package javaapplication1;
public class JavaApplication1 implements NewInterface{

    NewClass newClass;

    public static void main(String[] args) {

        System.out.println("test...");

        JavaApplication1 myApplication = new JavaApplication1();
        myApplication.doSomething();

    }

    private void doSomething(){
        newClass = new NewClass(this);
        newClass.calledFromMain();
    }

    @Override
    public void callback() {
        System.out.println("callback");
    }

}

Could not open a connection to your authentication agent

I just got this working. Open your ~/.ssh/config file.

Append the following-

Host github.com
 IdentityFile ~/.ssh/github_rsa

The page that gave me the hint Set up SSH for Git said that the single space indentation is important... though I had a configuration in here from Heroku that did not have that space and works properly.

lodash: mapping array to object

It can also solve without using any lodash function like this:

let paramsVal = [
    { name: 'foo', input: 'bar' },
    { name: 'baz', input: 'zle' }
];
let output = {};

paramsVal.forEach(({name, input})=>{
  output[name] = input;
})


console.log(output);

enter image description here

document.getElementById().value and document.getElementById().checked not working for IE

Jin Yong - IE has an issue with polluting the global scope with object references to any DOM elements with a "name" or "id" attribute set on the "initial" page load.

Thus you may have issues due to your variable name.

Try this and see if it works.

var someOtherName="abc";
//  ^^^^^^^^^^^^^
document.getElementById('msg').value = someOtherName;
document.getElementById('sp_100').checked = true;

There is a chance (in your original code) that IE attempts to set the value of the input to a reference to that actual element (ignores the error) but leaves you with no new value.

Keep in mind that in IE6/IE7 case doesn't matter for naming objects. IE believes that "foo" "Foo" and "FOO" are all the same object.

How to hide elements without having them take space on the page?

The answer to this question is saying to use display:none and display:block, but this does not help for someone who is trying to use css transitions to show and hide content using the visibility property.

This also drove me crazy, because using display kills any css transitions.

One solution is to add this to the class that's using visibility:

overflow:hidden

For this to work is does depend on the layout, but it should keep the empty content within the div it resides in.

How to do a batch insert in MySQL

Most of the time, you are not working in a MySQL client and you should batch inserts together using the appropriate API.

E.g. in JDBC:

connection con.setAutoCommit(false); 
PreparedStatement prepStmt = con.prepareStatement("UPDATE DEPT SET MGRNO=? WHERE DEPTNO=?");
prepStmt.setString(1,mgrnum1);                 
prepStmt.setString(2,deptnum1);
prepStmt.addBatch();

prepStmt.setString(1,mgrnum2);                        
prepStmt.setString(2,deptnum2);
prepStmt.addBatch();

int [] numUpdates=prepStmt.executeBatch();

http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/ad/tjvbtupd.htm

Mobile Safari: Javascript focus() method on inputfield only works with click?

Please try using on-tap instead of ng-click event. I had this issue. I resolved it by making my clear-search-box button inside search form label and replaced ng-click of clear-button by on-tap. It works fine now.

Replace characters from a column of a data frame R

You can use the stringr library:

library('stringr')

a <- runif(10)
b <- letters[1:10]
c <- c(rep('A-B', 4), rep('A_B', 6))
data <- data.frame(a, b, c)

data

#             a b   c
# 1  0.19426707 a A-B
# 2  0.12902673 b A-B
# 3  0.78324955 c A-B
# 4  0.06469028 d A-B
# 5  0.34752264 e A_C
# 6  0.55313288 f A_C
# 7  0.31264280 g A_C
# 8  0.33759921 h A_C
# 9  0.72322599 i A_C
# 10 0.25223075 j A_C

data$c <- str_replace_all(data$c, '_', '-')

data

#             a b   c
# 1  0.19426707 a A-B
# 2  0.12902673 b A-B
# 3  0.78324955 c A-B
# 4  0.06469028 d A-B
# 5  0.34752264 e A-C
# 6  0.55313288 f A-C
# 7  0.31264280 g A-C
# 8  0.33759921 h A-C
# 9  0.72322599 i A-C
# 10 0.25223075 j A-C

Note that this does change factored variables into character.

Creating executable files in Linux

It's really not that big of a deal. You could just make a script with the single command:

chmod a+x *.pl

And run the script after creating a perl file. Alternatively, you could open a file with a command like this:

touch filename.pl && chmod a+x filename.pl && vi filename.pl # choose your favorite editor

How to concatenate multiple lines of output to one line?

In bash echo without quotes remove carriage returns, tabs and multiple spaces

echo $(cat file)

What is ViewModel in MVC?

ViewModel is workaround that patches the conceptual clumsiness of the MVC framework. It represents the 4th layer in the 3-layer Model-View-Controller architecture. when Model (domain model) is not appropriate, too big (bigger than 2-3 fields) for the View, we create smaller ViewModel to pass it to the View.

How does the compilation/linking process work?

The skinny is that a CPU loads data from memory addresses, stores data to memory addresses, and execute instructions sequentially out of memory addresses, with some conditional jumps in the sequence of instructions processed. Each of these three categories of instructions involves computing an address to a memory cell to be used in the machine instruction. Because machine instructions are of a variable length depending on the particular instruction involved, and because we string a variable length of them together as we build our machine code, there is a two step process involved in calculating and building any addresses.

First we laying out the allocation of memory as best we can before we can know what exactly goes in each cell. We figure out the bytes, or words, or whatever that form the instructions and literals and any data. We just start allocating memory and building the values that will create the program as we go, and note down anyplace we need to go back and fix an address. In that place we put a dummy to just pad the location so we can continue to calculate memory size. For example our first machine code might take one cell. The next machine code might take 3 cells, involving one machine code cell and two address cells. Now our address pointer is 4. We know what goes in the machine cell, which is the op code, but we have to wait to calculate what goes in the address cells till we know where that data will be located, i.e. what will be the machine address of that data.

If there were just one source file a compiler could theoretically produce fully executable machine code without a linker. In a two pass process it could calculate all of the actual addresses to all of the data cells referenced by any machine load or store instructions. And it could calculate all of the absolute addresses referenced by any absolute jump instructions. This is how simpler compilers, like the one in Forth work, with no linker.

A linker is something that allows blocks of code to be compiled separately. This can speed up the overall process of building code, and allows some flexibility with how the blocks are later used, in other words they can be relocated in memory, for example adding 1000 to every address to scoot the block up by 1000 address cells.

So what the compiler outputs is rough machine code that is not yet fully built, but is laid out so we know the size of everything, in other words so we can start to calculate where all of the absolute addresses will be located. the compiler also outputs a list of symbols which are name/address pairs. The symbols relate a memory offset in the machine code in the module with a name. The offset being the absolute distance to the memory location of the symbol in the module.

That's where we get to the linker. The linker first slaps all of these blocks of machine code together end to end and notes down where each one starts. Then it calculates the addresses to be fixed by adding together the relative offset within a module and the absolute position of the module in the bigger layout.

Obviously I've oversimplified this so you can try to grasp it, and I have deliberately not used the jargon of object files, symbol tables, etc. which to me is part of the confusion.

Cannot GET / Nodejs Error

Have you checked your folder structure? It seems to me like Express can't find your root directory, which should be a a folder named "site" right under your default directory. Here is how it should look like, according to the tutorial:

node_modules/
  .bin/
  express/
  mongoose/
  path/
site/
  css/
  img/
  js/
  index.html
package.json

For example on my machine, I started getting the same error as you when I renamed my "site" folder as something else. So I would suggest you check that you have the index.html page inside a "site" folder that sits on the same path as your server.js file.

Hope that helps!

Public class is inaccessible due to its protection level

Also if you want to do something like ClassB.Run("thing");, make sure the Method Run(); is static or you could call it like this: thing.Run("thing");.

MySQL vs MongoDB 1000 reads

Honestly even if MongoDB is slower, MongoDB definitely makes me and you code faster.... no need to worry about silly table columns, row or entity migrations...

With MongoDB, you just instantiate a class and save!

How can I get the timezone name in JavaScript?

Most upvoted answer is probably the best way to get the timezone, however, Intl.DateTimeFormat().resolvedOptions().timeZone returns IANA timezone name by definition, which is in English.

If you want the timezone's name in current user's language, you can parse it from Date's string representation like so:

_x000D_
_x000D_
function getTimezoneName() {_x000D_
  const today = new Date();_x000D_
  const short = today.toLocaleDateString(undefined);_x000D_
  const full = today.toLocaleDateString(undefined, { timeZoneName: 'long' });_x000D_
_x000D_
  // Trying to remove date from the string in a locale-agnostic way_x000D_
  const shortIndex = full.indexOf(short);_x000D_
  if (shortIndex >= 0) {_x000D_
    const trimmed = full.substring(0, shortIndex) + full.substring(shortIndex + short.length);_x000D_
    _x000D_
    // by this time `trimmed` should be the timezone's name with some punctuation -_x000D_
    // trim it from both sides_x000D_
    return trimmed.replace(/^[\s,.\-:;]+|[\s,.\-:;]+$/g, '');_x000D_
_x000D_
  } else {_x000D_
    // in some magic case when short representation of date is not present in the long one, just return the long one as a fallback, since it should contain the timezone's name_x000D_
    return full;_x000D_
  }_x000D_
}_x000D_
_x000D_
console.log(getTimezoneName());
_x000D_
_x000D_
_x000D_

Tested in Chrome and Firefox.

Ofcourse, this will not work as intended in some of the environments. For example, node.js returns a GMT offset (e.g. GMT+07:00) instead of a name. But I think it's still readable as a fallback.

P.S. Won't work in IE11, just as the Intl... solution.

SVG fill color transparency / alpha?

As a not yet fully standardized solution (though in alignment with the color syntax in CSS3) you can use e.g fill="rgba(124,240,10,0.5)". Works fine in Firefox, Opera, Chrome.

Here's an example.

Getting a random value from a JavaScript array

If you want to write it on one line, like Pascual's solution, another solution would be to write it using ES6's find function (based on the fact, that the probability of randomly selecting one out of n items is 1/n):

_x000D_
_x000D_
var item = ['A', 'B', 'C', 'D'].find((_, i, ar) => Math.random() < 1 / (ar.length - i));_x000D_
console.log(item);
_x000D_
_x000D_
_x000D_

Use that approach for testing purposes and if there is a good reason to not save the array in a seperate variable only. Otherwise the other answers (floor(random()*length and using a seperate function) are your way to go.

@Directive vs @Component in Angular

If you refer the official angular docs

https://angular.io/guide/attribute-directives

There are three kinds of directives in Angular:

  1. Components—directives with a template.
  2. Structural directives—change the DOM layout by adding and removing DOM elements. e.g *ngIf
  3. Attribute directives—change the appearance or behavior of an element, component, or another directive. e.g [ngClass].

As the Application grows we find difficulty in maintaining all these codes. For reusability purpose, we separate our logic in smart components and dumb components and we use directives (structural or attribute) to make changes in the DOM.

How to make System.out.println() shorter

Some interesting alternatives:

OPTION 1

PrintStream p = System.out;
p.println("hello");

OPTION 2

PrintWriter p = new PrintWriter(System.out, true);
p.println("Hello");

Downloading and unzipping a .zip file without writing to disk

Use the zipfile module. To extract a file from a URL, you'll need to wrap the result of a urlopen call in a BytesIO object. This is because the result of a web request returned by urlopen doesn't support seeking:

from urllib.request import urlopen

from io import BytesIO
from zipfile import ZipFile

zip_url = 'http://example.com/my_file.zip'

with urlopen(zip_url) as f:
    with BytesIO(f.read()) as b, ZipFile(b) as myzipfile:
        foofile = myzipfile.open('foo.txt')
        print(foofile.read())

If you already have the file downloaded locally, you don't need BytesIO, just open it in binary mode and pass to ZipFile directly:

from zipfile import ZipFile

zip_filename = 'my_file.zip'

with open(zip_filename, 'rb') as f:
    with ZipFile(f) as myzipfile:
        foofile = myzipfile.open('foo.txt')
        print(foofile.read().decode('utf-8'))

Again, note that you have to open the file in binary ('rb') mode, not as text or you'll get a zipfile.BadZipFile: File is not a zip file error.

It's good practice to use all these things as context managers with the with statement, so that they'll be closed properly.

Configuring Hibernate logging using Log4j XML config file?

The answers were useful. After the change, I got duplicate logging of SQL statements, one in the log4j log file and one on the standard console. I changed the persistence.xml file to say show_sql to false to get rid of logging from the standard console. Keeping format_sql true also affects the log4j log file, so I kept that true.

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
        version="2.0">
    <persistence-unit name="myUnit" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:file:d:\temp\database\cap1000;shutdown=true"></property>
            <property name="dialect" value="org.hibernate.dialect.HSQLDialect"/>
            <property name="hibernate.show_sql" value="false"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hibernate.connection.username" value="sa"/>
            <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
        </properties>
    </persistence-unit>
</persistence>

Conditional step/stage in Jenkins pipeline

Doing the same in declarative pipeline syntax, below are few examples:

stage('master-branch-stuff') {
    when {
        branch 'master'
    }
    steps {
        echo 'run this stage - ony if the branch = master branch'
    }
}

stage('feature-branch-stuff') {
    when {
        branch 'feature/*'
    }
    steps {
        echo 'run this stage - only if the branch name started with feature/'
    }
}

stage('expression-branch') {
    when {
        expression {
            return env.BRANCH_NAME != 'master';
        }
    }
    steps {
        echo 'run this stage - when branch is not equal to master'
    }
}

stage('env-specific-stuff') {
    when { 
        environment name: 'NAME', value: 'this' 
    }
    steps {
        echo 'run this stage - only if the env name and value matches'
    }
}

More effective ways coming up - https://issues.jenkins-ci.org/browse/JENKINS-41187
Also look at - https://jenkins.io/doc/book/pipeline/syntax/#when


The directive beforeAgent true can be set to avoid spinning up an agent to run the conditional, if the conditional doesn't require git state to decide whether to run:

when { beforeAgent true; expression { return isStageConfigured(config) } }

Release post and docs


UPDATE
New WHEN Clause
REF: https://jenkins.io/blog/2018/04/09/whats-in-declarative

equals - Compares two values - strings, variables, numbers, booleans - and returns true if they’re equal. I’m honestly not sure how we missed adding this earlier! You can do "not equals" comparisons using the not { equals ... } combination too.

changeRequest - In its simplest form, this will return true if this Pipeline is building a change request, such as a GitHub pull request. You can also do more detailed checks against the change request, allowing you to ask "is this a change request against the master branch?" and much more.

buildingTag - A simple condition that just checks if the Pipeline is running against a tag in SCM, rather than a branch or a specific commit reference.

tag - A more detailed equivalent of buildingTag, allowing you to check against the tag name itself.

JavaScript dictionary with names

An easier, native and more efficient way of emulating a dict in JavaScript than a hash table:

It also exploits that JavaScript is weakly typed. Rather type inference.

Here's how (an excerpt from Google Chrome's console):

var myDict = {};

myDict.one = 1;
1

myDict.two = 2;
2

if (myDict.hasOwnProperty('three'))
{
  console.log(myDict.two);
}
else
{
  console.log('Key does not exist!');
}
Key does not exist! VM361:8

if (myDict.hasOwnProperty('two'))
{
  console.log(myDict.two);
}
else
{
  console.log('Key does not exist!');
}
2 VM362:4

Object.keys(myDict);
["one", "two"]

delete(myDict.two);
true

myDict.hasOwnProperty('two');
false

myDict.two
undefined

myDict.one
1

href="tel:" and mobile numbers

It's the same. Your international format is already correct, and is recommended for use in all cases, where possible.

Using Image control in WPF to display System.Drawing.Bitmap

According to http://khason.net/blog/how-to-use-systemdrawingbitmap-hbitmap-in-wpf/

   [DllImport("gdi32")]
   static extern int DeleteObject(IntPtr o);

   public static BitmapSource loadBitmap(System.Drawing.Bitmap source)
   {
       IntPtr ip = source.GetHbitmap();
       BitmapSource bs = null;
       try
       {
           bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip, 
              IntPtr.Zero, Int32Rect.Empty, 
              System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
       }
       finally
       {
           DeleteObject(ip);
       }

       return bs;
   }

It gets System.Drawing.Bitmap (from WindowsBased) and converts it into BitmapSource, which can be actually used as image source for your Image control in WPF.

image1.Source = YourUtilClass.loadBitmap(SomeBitmap);

How can I delete an item from an array in VB.NET?

That depends on what you mean by delete. An array has a fixed size, so deleting doesn't really make sense.

If you want to remove element i, one option would be to move all elements j > i one position to the left (a[j - 1] = a[j] for all j, or using Array.Copy) and then resize the array using ReDim Preserve.

So, unless you are forced to use an array by some external constraint, consider using a data structure more suitable for adding and removing items. List<T>, for example, also uses an array internally but takes care of all the resizing issues itself: For removing items, it uses the algorithm mentioned above (without the ReDim), which is why List<T>.RemoveAt is an O(n) operation.

There's a whole lot of different collection classes in the System.Collections.Generic namespace, optimized for different use cases. If removing items frequently is a requirement, there are lots of better options than an array (or even List<T>).

How to serialize an object to XML without getting xmlns="..."?

I Suggest this helper class:

public static class Xml
{
    #region Fields

    private static readonly XmlWriterSettings WriterSettings = new XmlWriterSettings {OmitXmlDeclaration = true, Indent = true};
    private static readonly XmlSerializerNamespaces Namespaces = new XmlSerializerNamespaces(new[] {new XmlQualifiedName("", "")});

    #endregion

    #region Methods

    public static string Serialize(object obj)
    {
        if (obj == null)
        {
            return null;
        }

        return DoSerialize(obj);
    }

    private static string DoSerialize(object obj)
    {
        using (var ms = new MemoryStream())
        using (var writer = XmlWriter.Create(ms, WriterSettings))
        {
            var serializer = new XmlSerializer(obj.GetType());
            serializer.Serialize(writer, obj, Namespaces);
            return Encoding.UTF8.GetString(ms.ToArray());
        }
    }

    public static T Deserialize<T>(string data)
        where T : class
    {
        if (string.IsNullOrEmpty(data))
        {
            return null;
        }

        return DoDeserialize<T>(data);
    }

    private static T DoDeserialize<T>(string data) where T : class
    {
        using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(data)))
        {
            var serializer = new XmlSerializer(typeof (T));
            return (T) serializer.Deserialize(ms);
        }
    }

    #endregion
}

:)

Why should C++ programmers minimize use of 'new'?

One more point to all the above correct answers, it depends on what sort of programming you are doing. Kernel developing in Windows for example -> The stack is severely limited and you might not be able to take page faults like in user mode.

In such environments, new, or C-like API calls are prefered and even required.

Of course, this is merely an exception to the rule.

Using Python, find anagrams for a list of words

I'm using a dictionary to store each character of string one by one. Then iterate through second string and find the character in the dictionary, if it's present decrease the count of the corresponding key from dictionary.

class Anagram:

    dict = {}

    def __init__(self):
        Anagram.dict = {}

    def is_anagram(self,s1, s2):
        print '***** starting *****'

        print '***** convert input strings to lowercase'
        s1 = s1.lower()
        s2 = s2.lower()

        for i in s1:
           if i not in Anagram.dict:
              Anagram.dict[i] = 1
           else:
              Anagram.dict[i] += 1

        print Anagram.dict

        for i in s2:
           if i not in Anagram.dict:
              return false
           else:
              Anagram.dict[i] -= 1

        print Anagram.dict

       for i in Anagram.dict.keys():
          if Anagram.dict.get(i) == 0:
              del Anagram.dict[i]

       if len(Anagram.dict) == 0:
         print Anagram.dict
         return True
       else:
         return False

Android-Studio upgraded from 0.1.9 to 0.2.0 causing gradle build errors now

if you get this error

Gradle: 
FAILURE: Could not determine which tasks to execute.
* What went wrong:
Task 'assemble' not found in root project 'MyProject'.
* Try:
Run gradle tasks to get a list of available tasks.

You need to edit your Projects .iml file. not the one under src. the one that is like myappProject.iml' delete the whole component name = facetmanager

<module external.system.id="GRADLE" type="JAVA_MODULE" version="4">
<component name="FacetManager">
...remove this element and everything inside such as <facet> elements...
</component>
<component name="NewModuleRootManager" inherit-compiler-output="true">
...keep this part...
</component

How to hide a div element depending on Model value? MVC

The below code should apply different CSS classes based on your Model's CanEdit Property value .

<div class="@(Model.CanEdit?"visible-item":"hidden-item")">Some links</div>

But if it is something important like Edit/Delete links, you shouldn't be simply hiding,because people can update the css class/HTML markup in their browser and get access to your important link. Instead you should be simply not Rendering the important stuff to the browser.

@if(Model.CanEdit)
{
  <div>Edit/Delete link goes here</div>
}

MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050

You can use the following query to create a table to a particular database in MySql.

create database if not exists `test`;

USE `test`;

SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;

/*Table structure for table `test` */

CREATE TABLE IF NOT EXISTS `tblsample` (

  `id` int(11) NOT NULL auto_increment,   
  `recid` int(11) NOT NULL default '0',       
  `cvfilename` varchar(250)  NOT NULL default '',     
  `cvpagenumber`  int(11) NULL,     
  `cilineno` int(11)  NULL,    
  `batchname`  varchar(100) NOT NULL default '',
  `type` varchar(20) NOT NULL default '',    
  `data` varchar(100) NOT NULL default '',
   PRIMARY KEY  (`id`)

);

Pagination using MySQL LIMIT, OFFSET

If you want to keep it simple go ahead and try this out.

$page_number = mysqli_escape_string($con, $_GET['page']);
$count_per_page = 20;
$next_offset = $page_number * $count_per_page;
$cat =mysqli_query($con, "SELECT * FROM categories LIMIT $count_per_page OFFSET $next_offset");
while ($row = mysqli_fetch_array($cat))
        $count = $row[0];

The rest is up to you. If you have result comming from two tables i suggest you try a different approach.

How do I split a string so I can access item x?

If your database has compatibility level of 130 or higher then you can use the STRING_SPLIT function along with OFFSET FETCH clauses to get the specific item by index.

To get the item at index N (zero based), you can use the following code

SELECT value
FROM STRING_SPLIT('Hello John Smith',' ')
ORDER BY (SELECT NULL)
OFFSET N ROWS
FETCH NEXT 1 ROWS ONLY

To check the compatibility level of your database, execute this code:

SELECT compatibility_level  
FROM sys.databases WHERE name = 'YourDBName';

PHP prepend leading zero before single digit number, on-the-fly

You can use str_pad for adding 0's

str_pad($month, 2, '0', STR_PAD_LEFT); 

string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )

How to change the CHARACTER SET (and COLLATION) throughout a database?

change database collation:

ALTER DATABASE <database_name> CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;

change table collation:

ALTER TABLE <table_name> CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;

change column collation:

ALTER TABLE <table_name> MODIFY <column_name> VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;

What do the parts of utf8mb4_0900_ai_ci mean?

3 bytes -- utf8
4 bytes -- utf8mb4 (new)
v4.0 --   _unicode_
v5.20 --  _unicode_520_
v9.0 --   _0900_ (new)
_bin      -- just compare the bits; don't consider case folding, accents, etc
_ci       -- explicitly case insensitive (A=a) and implicitly accent insensitive (a=á)
_ai_ci    -- explicitly case insensitive and accent insensitive
_as (etc) -- accent-sensitive (etc)
_bin         -- simple, fast
_general_ci  -- fails to compare multiple letters; eg ss=ß, somewhat fast
...          -- slower
_0900_       -- (8.0) much faster because of a rewrite

More info:

Default passwords of Oracle 11g?

Login into the machine as oracle login user id( where oracle is installed)..

  1. Add ORACLE_HOME = <Oracle installation Directory> in Environment variable

  2. Open a command prompt

  3. Change the directory to %ORACLE_HOME%\bin

  4. type the command sqlplus /nolog

  5. SQL> connect /as sysdba

  6. SQL> alter user SYS identified by "newpassword";

One more check, while oracle installation and database confiuration assistant setup, if you configure any database then you might have given password and checked the same password for all other accounts.. If so, then you try with the password which you have given in your database configuration assistant setup.

Hope this will work for you..

How to get number of entries in a Lua table?

I stumbled upon this thread and want to post another option. I'm using Luad generated from a block controller, but it essentially works by checking values in the table, then incrementing which value is being checked by 1. Eventually, the table will run out, and the value at that index will be Nil.

So subtract 1 from the index that returned a nil, and that's the size of the table.

I have a global Variable for TableSize that is set to the result of this count.

function Check_Table_Size()
  local Count = 1
  local CurrentVal = (CueNames[tonumber(Count)])
  local repeating = true
  print(Count)
  while repeating == true do
    if CurrentVal ~= nil then
      Count = Count + 1
      CurrentVal = CueNames[tonumber(Count)]
     else
      repeating = false
      TableSize = Count - 1
    end
  end
  print(TableSize)
end

Can I change the checkbox size using CSS?

The problem is Firefox doesn't listen to width and height. Disable that and your good to go.

_x000D_
_x000D_
input[type=checkbox] {_x000D_
    width: 25px;_x000D_
    height: 25px;_x000D_
    -moz-appearance: none;_x000D_
}
_x000D_
<label><input type="checkbox"> Test</label>
_x000D_
_x000D_
_x000D_

How to save final model using keras?

you can save the model in json and weights in a hdf5 file format.

# keras library import  for Saving and loading model and weights

from keras.models import model_from_json
from keras.models import load_model

# serialize model to JSON
#  the keras model which is trained is defined as 'model' in this example
model_json = model.to_json()


with open("model_num.json", "w") as json_file:
    json_file.write(model_json)

# serialize weights to HDF5
model.save_weights("model_num.h5")

files "model_num.h5" and "model_num.json" are created which contain our model and weights

To use the same trained model for further testing you can simply load the hdf5 file and use it for the prediction of different data. here's how to load the model from saved files.

# load json and create model
json_file = open('model_num.json', 'r')

loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)

# load weights into new model
loaded_model.load_weights("model_num.h5")
print("Loaded model from disk")

loaded_model.save('model_num.hdf5')
loaded_model=load_model('model_num.hdf5')

To predict for different data you can use this

loaded_model.predict_classes("your_test_data here")

Current date without time

String test = DateTime.Now.ToShortDateString();

How can I convert a std::string to int?

What about Boost.Lexical_cast?

Here is their example:

The following example treats command line arguments as a sequence of numeric data:

int main(int argc, char * argv[])
{
    using boost::lexical_cast;
    using boost::bad_lexical_cast;

    std::vector<short> args;

    while(*++argv)
    {
        try
        {
            args.push_back(lexical_cast<short>(*argv));
        }
        catch(bad_lexical_cast &)
        {
            args.push_back(0);
        }
    }
    ...
}

Replace one character with another in Bash

Try this

 echo "hello world" | sed 's/ /./g' 

mysql extract year from date format

try this code:

SELECT YEAR( str_to_date( subdateshow, '%m/%d/%Y' ) ) AS Mydate

How to toggle a boolean?

Let's see this in action:

_x000D_
_x000D_
var b = true;_x000D_
_x000D_
console.log(b); // true_x000D_
_x000D_
b = !b;_x000D_
console.log(b); // false_x000D_
_x000D_
b = !b;_x000D_
console.log(b); // true
_x000D_
_x000D_
_x000D_

Anyways, there is no shorter way than what you currently have.

What is the '.well' equivalent class in Bootstrap 4

Card seems to be "discarded" LOL, I found the "well" not working with bootstrap 4.3.1 and jQuery v3.4.1, just working fine with bootstrap 4.3.1 and jQuery v3.3.1. Hope it helps.

For each row in an R dataframe

Well, since you asked for R equivalent to other languages, I tried to do this. Seems to work though I haven't really looked at which technique is more efficient in R.

> myDf <- head(iris)
> myDf
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa
> nRowsDf <- nrow(myDf)
> for(i in 1:nRowsDf){
+ print(myDf[i,4])
+ }
[1] 0.2
[1] 0.2
[1] 0.2
[1] 0.2
[1] 0.2
[1] 0.4

For the categorical columns though, it would fetch you a Data Frame which you could typecast using as.character() if needed.

How can I pass data from Flask to JavaScript in a template?

Using a data attribute on an HTML element avoids having to use inline scripting, which in turn means you can use stricter CSP rules for increased security.

Specify a data attribute like so:

<div id="mydiv" data-geocode='{{ geocode|tojson }}'>...</div>

Then access it in a static JavaScript file like so:

// Raw JavaScript
var geocode = JSON.parse(document.getElementById("mydiv").dataset.geocode);

// jQuery
var geocode = JSON.parse($("#mydiv").data("geocode"));

How to check for Is not Null And Is not Empty string in SQL server?

You can use either one of these to check null, whitespace and empty strings.

WHERE COLUMN <> '' 

WHERE LEN(COLUMN) > 0

WHERE NULLIF(LTRIM(RTRIM(COLUMN)), '') IS NOT NULL

How to use group by with union in t-sql

You need to alias the subquery. Thus, your statement should be:

Select Z.id
From    (
        Select id, time
        From dbo.tablea
        Union All
        Select id, time
        From dbo.tableb
        ) As Z
Group By Z.id

Git push: "fatal 'origin' does not appear to be a git repository - fatal Could not read from remote repository."

First, check that your origin is set by running

git remote -v

This should show you all of the push / fetch remotes for the project.

If this returns with no output, skip to last code block.

Verify remote name / address

If this returns showing that you have remotes set, check that the name of the remote matches the remote you are using in your commands.

$git remote -v
myOrigin ssh://[email protected]:1234/myRepo.git (fetch)
myOrigin ssh://[email protected]:1234/myRepo.git (push)

# this will fail because `origin` is not set
$git push origin master

# you need to use
$git push myOrigin master

If you want to rename the remote or change the remote's URL, you'll want to first remove the old remote, and then add the correct one.

Remove the old remote

$git remote remove myOrigin

Add missing remote

You can then add in the proper remote using

$git remote add origin ssh://[email protected]:1234/myRepo.git

# this will now work as expected
$git push origin master

Save the console.log in Chrome to a file

On Linux (at least) you can set CHROME_LOG_FILE in the environment to have chrome write a log of the Console activity to the named file each time it runs. The log is overwritten every time chrome starts. This way, if you have an automated session that runs chrome, you don't have a to change the way chrome is started, and the log is there after the session ends.

export CHROME_LOG_FILE=chrome.log

How to insert new cell into UITableView in Swift

Here is your code for add data into both tableView:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var table1Text: UITextField!
    @IBOutlet weak var table2Text: UITextField!
    @IBOutlet weak var table1: UITableView!
    @IBOutlet weak var table2: UITableView!

    var table1Data = ["a"]
    var table2Data = ["1"]

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func addData(sender: AnyObject) {

        //add your data into tables array from textField
        table1Data.append(table1Text.text)
        table2Data.append(table2Text.text)

        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            //reload your tableView
            self.table1.reloadData()
            self.table2.reloadData()
        })


        table1Text.resignFirstResponder()
        table2Text.resignFirstResponder()
    }

    //delegate methods
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == table1 {
            return table1Data.count
        }else if tableView == table2 {
            return table2Data.count
        }
        return Int()
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        if tableView == table1 {
            let cell = table1.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell

            let row = indexPath.row
            cell.textLabel?.text = table1Data[row]

            return cell
        }else if tableView == table2 {

            let cell = table2.dequeueReusableCellWithIdentifier("Cell1", forIndexPath: indexPath) as! UITableViewCell

            let row = indexPath.row
            cell.textLabel?.text = table2Data[row]

            return cell
        }

        return UITableViewCell()
    }
}

And your result will be:

enter image description here

How do I retrieve query parameters in Spring Boot?

To accept both @PathVariable and @RequestParam in the same /user endpoint:

@GetMapping(path = {"/user", "/user/{data}"})
public void user(@PathVariable(required=false,name="data") String data,
                 @RequestParam(required=false) Map<String,String> qparams) {
    qparams.forEach((a,b) -> {
        System.out.println(String.format("%s -> %s",a,b));
    }
  
    if (data != null) {
        System.out.println(data);
    }
}

Testing with curl:

  • curl 'http://localhost:8080/user/books'
  • curl 'http://localhost:8080/user?book=ofdreams&name=nietzsche'

jQuery AJAX form data serialize using PHP

Try this

 $(document).ready(function(){
    var form=$("#myForm");
    $("#smt").click(function(){
    $.ajax({
            type:"POST",
            url:form.attr("action"),
            data:$("#myForm input").serialize(),//only input
            success: function(response){
                console.log(response);  
            }
        });
    });
    });

Most efficient way to check if a file is empty in Java on Windows

I think the best way is to use file.length == 0.

It is sometimes possible that the first line is empty.