Programs & Examples On #Batch processing

Batch-processing refers to programmatic execution with minimum human interaction.

Batch file. Delete all files and folders in a directory

Use:

  • Create a batch file

  • Copy the below text into the batch file

    set folder="C:\test"
    cd /d %folder%
    for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)
    

It will delete all files and folders.

Run all SQL files in a directory

Use FOR. From the command prompt:

c:\>for %f in (*.sql) do sqlcmd /S <servername> /d <dbname> /E /i "%f"

How to use the start command in a batch file?

I think this other Stack Overflow answer would solve your problem: How do I run a bat file in the background from another bat file?

Basically, you use the /B and /C options:

START /B CMD /C CALL "foo.bat" [args [...]] >NUL 2>&1

Difference between xcopy and robocopy

Its painful to hear people are still suffering at the hands of *{COPY} whatever the version. I am a seasoned batch and Bash script writer and I recommend rsync , you can run this within cygwin (cygwin.org) or you can locate some binaries floating around . and you can redirect output to 2>&1 to some log file like out.log for later analysing. Good luck people its time to love life again . =M. Kaan=

How to close the command line window after running a batch file?

For closing cmd window, especially after ending weblogic or JBOSS app servers console with Ctrl+C, I'm using 'call' command instead of 'start' in my batch files. My startWLS.cmd file then looks like:

call [BEA_HOME]\user_projects\domains\test_domain\startWebLogic.cmd

After Ctrl+C(and 'Y' answer) cmd window is automatically closed.

How do you convert an entire directory with ffmpeg?

for i in *.flac;
  do name=`echo "${i%.*}"`;
  echo $name;
  ffmpeg -i "${i}" -ab 320k -map_metadata 0 -id3v2_version 3 "${name}".mp3;
done

Batch process flac files into mp3 (safe for file names with spaces) using [1] [2]

How do I correctly detect orientation change using Phonegap on iOS?

if (window.matchMedia("(orientation: portrait)").matches) {
   // you're in PORTRAIT mode
}

if (window.matchMedia("(orientation: landscape)").matches) {
  // you're in LANDSCAPE mode
}

jQuery Scroll to Div

You can also use 'name' instead of 'href' for a cleaner url:

    $('a[name^=#]').click(function(){
    var target = $(this).attr('name');
    if (target == '#')
      $('html, body').animate({scrollTop : 0}, 600);
    else
      $('html, body').animate({
        scrollTop: $(target).offset().top - 100
    }, 600);
});

How to make Twitter Bootstrap menu dropdown on hover rather than click

 <ul class="nav navbar-nav">
        <li class="active"><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li class="dropdown">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
          <ul class="dropdown-menu">
            <li><a href="#">Action</a></li>
            <li><a href="#">Another action</a></li>
            <li><a href="#">Something else here</a></li>
            <li class="divider"></li>
            <li><a href="#">Separated link</a></li>
            <li class="divider"></li>
            <li><a href="#">One more separated link</a></li>
          </ul>
        </li>
      </ul>
      <script>
        $('ul.nav li.dropdown').hover(function() {
        $(this).find('.dropdown-menu').stop(true, 
        true).delay(200).fadeIn(500);
        }, function() {
        $(this).find('.dropdown-menu').stop(true, 
        true).delay(200).fadeOut(500);
        });
      </script>

What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

127.0.0.1 is normally the IP address assigned to the "loopback" or local-only interface. This is a "fake" network adapter that can only communicate within the same host. It's often used when you want a network-capable application to only serve clients on the same host. A process that is listening on 127.0.0.1 for connections will only receive local connections on that socket.

"localhost" is normally the hostname for the 127.0.0.1 IP address. It's usually set in /etc/hosts (or the Windows equivalent named "hosts" somewhere under %WINDIR%). You can use it just like any other hostname - try "ping localhost" to see how it resolves to 127.0.0.1.

0.0.0.0 has a couple of different meanings, but in this context, when a server is told to listen on 0.0.0.0 that means "listen on every available network interface". The loopback adapter with IP address 127.0.0.1 from the perspective of the server process looks just like any other network adapter on the machine, so a server told to listen on 0.0.0.0 will accept connections on that interface too.

That hopefully answers the IP side of your question. I'm not familiar with Jekyll or Vagrant, but I'm guessing that your port forwarding 8080 => 4000 is somehow bound to a particular network adapter, so it isn't in the path when you connect locally to 127.0.0.1

ListAGG in SQLSERVER

This might be useful to someone also ..

i.e. For a data analyst and data profiling type of purposes ..(i.e. not grouped by) ..

Prior to the SQL*Server 2017 String_agg function existence ..

(i.e. returns just one row ..)

select distinct
SUBSTRING (
stuff(( select distinct ',' + [FieldB] from tablename order by 1 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') 
,1,0,'' ) 
,2,9999)
from 
    tablename 

e.g. returns comma separated values A,B

Is there any difference between a GUID and a UUID?

Not really. GUID is more Microsoft-centric whereas UUID is used more widely (e.g., as in the urn:uuid: URN scheme, and in CORBA).

How to set min-font-size in CSS

Judging by your above comment, you're OK doing this with jQuery — here goes:

// for every element in the body tag
$("*", "body").each(function() {
  // parse out its computed font size, and see if it is less than 12
  if ( parseInt($(this).css("font-size"), 10) < 12 )
    // if so, then manually give it a CSS property of 12px
    $(this).css("font-size", "12px")
});

A cleaner way to do this might be to have a "min-font" class in your CSS that sets font-size: 12px, and just add the class instead:

$("*", "body").each(function() {
  if ( parseInt($(this).css("font-size"), 10) < 12 )
    $(this).addClass("min-font")
});

How to check whether a pandas DataFrame is empty?

I use the len function. It's much faster than empty. len(df.index) is even faster.

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(10000, 4), columns=list('ABCD'))

def empty(df):
    return df.empty

def lenz(df):
    return len(df) == 0

def lenzi(df):
    return len(df.index) == 0

'''
%timeit empty(df)
%timeit lenz(df)
%timeit lenzi(df)

10000 loops, best of 3: 13.9 µs per loop
100000 loops, best of 3: 2.34 µs per loop
1000000 loops, best of 3: 695 ns per loop

len on index seems to be faster
'''

What is Node.js' Connect, Express and "middleware"?

The accepted answer is really old (and now wrong). Here's the information (with source) based on the current version of Connect (3.0) / Express (4.0).

What Node.js comes with

http / https createServer which simply takes a callback(req,res) e.g.

var server = http.createServer(function (request, response) {

    // respond
    response.write('hello client!');
    response.end();

});

server.listen(3000);

What connect adds

Middleware is basically any software that sits between your application code and some low level API. Connect extends the built-in HTTP server functionality and adds a plugin framework. The plugins act as middleware and hence connect is a middleware framework

The way it does that is pretty simple (and in fact the code is really short!). As soon as you call var connect = require('connect'); var app = connect(); you get a function app that can:

  1. Can handle a request and return a response. This is because you basically get this function
  2. Has a member function .use (source) to manage plugins (that comes from here because of this simple line of code).

Because of 1.) you can do the following :

var app = connect();

// Register with http
http.createServer(app)
    .listen(3000);

Combine with 2.) and you get:

var connect = require('connect');

// Create a connect dispatcher
var app = connect()
      // register a middleware
      .use(function (req, res, next) { next(); });

// Register with http
http.createServer(app)
    .listen(3000);

Connect provides a utility function to register itself with http so that you don't need to make the call to http.createServer(app). Its called listen and the code simply creates a new http server, register's connect as the callback and forwards the arguments to http.listen. From source

app.listen = function(){
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

So, you can do:

var connect = require('connect');

// Create a connect dispatcher and register with http
var app = connect()
          .listen(3000);
console.log('server running on port 3000');

It's still your good old http.createServer with a plugin framework on top.

What ExpressJS adds

ExpressJS and connect are parallel projects. Connect is just a middleware framework, with a nice use function. Express does not depend on Connect (see package.json). However it does the everything that connect does i.e:

  1. Can be registered with createServer like connect since it too is just a function that can take a req/res pair (source).
  2. A use function to register middleware.
  3. A utility listen function to register itself with http

In addition to what connect provides (which express duplicates), it has a bunch of more features. e.g.

  1. Has view engine support.
  2. Has top level verbs (get/post etc.) for its router.
  3. Has application settings support.

The middleware is shared

The use function of ExpressJS and connect is compatible and therefore the middleware is shared. Both are middleware frameworks, express just has more than a simple middleware framework.

Which one should you use?

My opinion: you are informed enough ^based on above^ to make your own choice.

  • Use http.createServer if you are creating something like connect / expressjs from scratch.
  • Use connect if you are authoring middleware, testing protocols etc. since it is a nice abstraction on top of http.createServer
  • Use ExpressJS if you are authoring websites.

Most people should just use ExpressJS.

What's wrong about the accepted answer

These might have been true as some point in time, but wrong now:

that inherits an extended version of http.Server

Wrong. It doesn't extend it and as you have seen ... uses it

Express does to Connect what Connect does to the http module

Express 4.0 doesn't even depend on connect. see the current package.json dependencies section

Volatile Vs Atomic

There are two important concepts in multithreading environment:

  1. atomicity
  2. visibility

The volatile keyword eradicates visibility problems, but it does not deal with atomicity. volatile will prevent the compiler from reordering instructions which involve a write and a subsequent read of a volatile variable; e.g. k++. Here, k++ is not a single machine instruction, but three:

  1. copy the value to a register;
  2. increment the value;
  3. place it back.

So, even if you declare a variable as volatile, this will not make this operation atomic; this means another thread can see a intermediate result which is a stale or unwanted value for the other thread.

On the other hand, AtomicInteger, AtomicReference are based on the Compare and swap instruction. CAS has three operands: a memory location V on which to operate, the expected old value A, and the new value B. CAS atomically updates V to the new value B, but only if the value in V matches the expected old value A; otherwise, it does nothing. In either case, it returns the value currently in V. The compareAndSet() methods of AtomicInteger and AtomicReference take advantage of this functionality, if it is supported by the underlying processor; if it is not, then the JVM implements it via spin lock.

Mock MVC - Add Request Parameter to test

If anyone came to this question looking for ways to add multiple parameters at the same time (my case), you can use .params with a MultivalueMap instead of adding each .param :

LinkedMultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>()
requestParams.add("id", "1");
requestParams.add("name", "john");
requestParams.add("age", "30");

mockMvc.perform(get("my/endpoint").params(requestParams)).andExpect(status().isOk())

What is the "proper" way to cast Hibernate Query.list() to List<Type>?

To answer your question, there is no "proper way" to do that. Now if it's just the warning that bothers you, the best way to avoid its proliferation is to wrap the Query.list() method into a DAO :

public class MyDAO {

    @SuppressWarnings("unchecked")
    public static <T> List<T> list(Query q){
        return q.list();
    }
}

This way you get to use the @SuppressWarnings("unchecked") only once.

Asp.Net MVC with Drop Down List, and SelectListItem Assistance

Step-1: Your Model class

public class RechargeMobileViewModel
    {
        public string CustomerFullName { get; set; }
        public string TelecomSubscriber { get; set; }
        public int TotalAmount { get; set; }
        public string MobileNumber { get; set; }
        public int Month { get; set; }
        public List<SelectListItem> getAllDaysList { get; set; }

        // Define the list which you have to show in Drop down List
        public List<SelectListItem> getAllWeekDaysList()
        {
            List<SelectListItem> myList = new List<SelectListItem>();
            var data = new[]{
                 new SelectListItem{ Value="1",Text="Monday"},
                 new SelectListItem{ Value="2",Text="Tuesday"},
                 new SelectListItem{ Value="3",Text="Wednesday"},
                 new SelectListItem{ Value="4",Text="Thrusday"},
                 new SelectListItem{ Value="5",Text="Friday"},
                 new SelectListItem{ Value="6",Text="Saturday"},
                 new SelectListItem{ Value="7",Text="Sunday"},
             };
            myList = data.ToList();
            return myList;
        }
}

Step-2: Call this method to fill Drop down in your controller Action

namespace MvcVariousApplication.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
              RechargeMobileViewModel objModel = new RechargeMobileViewModel();
                objModel.getAllDaysList = objModel.getAllWeekDaysList();  
                return View(objModel);
            }
    }
    }

Step-3: Fill your Drop-Down List of View as follows

 @model MvcVariousApplication.Models.RechargeMobileViewModel
    @{
        ViewBag.Title = "Contact";
    }
    @Html.LabelFor(model=> model.CustomerFullName)
    @Html.TextBoxFor(model => model.CustomerFullName)

    @Html.LabelFor(model => model.MobileNumber)
    @Html.TextBoxFor(model => model.MobileNumber)

    @Html.LabelFor(model => model.TelecomSubscriber)
    @Html.TextBoxFor(model => model.TelecomSubscriber)

    @Html.LabelFor(model => model.TotalAmount)
    @Html.TextBoxFor(model => model.TotalAmount)

    @Html.LabelFor(model => model.Month)
    @Html.DropDownListFor(model => model.Month, new SelectList(Model.getAllDaysList, "Value", "Text"), "-Select Day-")

How to find all serial devices (ttyS, ttyUSB, ..) on Linux without opening them?

The serial communication manager library has many API and features targeted for the task you want. If the device is a USB-UART its VID/PID can be used. If the device is BT-SPP than platform specific APIs can be used. Take a look at this project for serial port programming: https://github.com/RishiGupta12/serial-communication-manager

ORA-12170: TNS:Connect timeout occurred

I was getting the same error while connecting my "hr" user of ORCLPDB which is a pluggable database.

First, get hostname and port number by typing a command lsnrctl status on windows command prompt. In my case, it was 127.0.0.1 with port number as 1521

Second, enter the below command with your hostname and port number:

sqlplus username/password@HostName:Port Number/PluggableDatabaseName.

For example:

sqlplus hr/[email protected]:1521/ORCLPDB.

Validating IPv4 addresses with regexp

With subnet mask :

^$|([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\
.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\
.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\
.([01]?\\d\\d?|2[0-4]\\d|25[0-5])
((/([01]?\\d\\d?|2[0-4]\\d|25[0-5]))?)$

How can I split a text into sentences?

You could make a new tokenizer for Russian (and some other languages) using this function:

def russianTokenizer(text):
    result = text
    result = result.replace('.', ' . ')
    result = result.replace(' .  .  . ', ' ... ')
    result = result.replace(',', ' , ')
    result = result.replace(':', ' : ')
    result = result.replace(';', ' ; ')
    result = result.replace('!', ' ! ')
    result = result.replace('?', ' ? ')
    result = result.replace('\"', ' \" ')
    result = result.replace('\'', ' \' ')
    result = result.replace('(', ' ( ')
    result = result.replace(')', ' ) ') 
    result = result.replace('  ', ' ')
    result = result.replace('  ', ' ')
    result = result.replace('  ', ' ')
    result = result.replace('  ', ' ')
    result = result.strip()
    result = result.split(' ')
    return result

and then call it in this way:

text = '?? ?????????? ?????, ????????? Google SSL;'
tokens = russianTokenizer(text)

VBA - how to conditionally skip a for loop iteration

Hi I am also facing this issue and I solve this using below example code

For j = 1 To MyTemplte.Sheets.Count

       If MyTemplte.Sheets(j).Visible = 0 Then
           GoTo DoNothing        
       End If 


'process for this for loop
DoNothing:

Next j 

Using app.config in .Net Core

It is possible to use your usual System.Configuration even in .NET Core 2.0 on Linux. Try this test example:

  1. Created a .NET Standard 2.0 Library (say MyLib.dll)
  2. Added the NuGet package System.Configuration.ConfigurationManager v4.4.0. This is needed since this package isn't covered by the meta-package NetStandard.Library v2.0.0 (I hope that changes)
  3. All your C# classes derived from ConfigurationSection or ConfigurationElement go into MyLib.dll. For example MyClass.cs derives from ConfigurationSection and MyAccount.cs derives from ConfigurationElement. Implementation details are out of scope here but Google is your friend.
  4. Create a .NET Core 2.0 app (e.g. a console app, MyApp.dll). .NET Core apps end with .dll rather than .exe in Framework.
  5. Create an app.config in MyApp with your custom configuration sections. This should obviously match your class designs in #3 above. For example:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="myCustomConfig" type="MyNamespace.MyClass, MyLib" />
  </configSections>
  <myCustomConfig>
    <myAccount id="007" />
  </myCustomConfig>
</configuration>

That's it - you'll find that the app.config is parsed properly within MyApp and your existing code within MyLib works just fine. Don't forget to run dotnet restore if you switch platforms from Windows (dev) to Linux (test).

Additional workaround for test projects

If you're finding that your App.config is not working in your test projects, you might need this snippet in your test project's .csproj (e.g. just before the ending </Project>). It basically copies App.config into your output folder as testhost.dll.config so dotnet test picks it up.

  <!-- START: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->
  <Target Name="CopyCustomContent" AfterTargets="AfterBuild">
    <Copy SourceFiles="App.config" DestinationFiles="$(OutDir)\testhost.dll.config" />
  </Target>
  <!-- END: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->

Visual Studio Code open tab in new window

When I want to split the screens I usually do one of the following:

  1. open new window with: Ctrl+Shift+N
    and after that I drag the current file I want to the new window.
  2. on the File explorer - I hit Ctrl+Enter on the file I want - and then this file and the other file open together in the same screen but in split mode, so you can see the two files together. If the screen is wide enough this is not a bad solution at all that you can get used to.

How do I ignore ampersands in a SQL script running from SQL Plus?

You can set the special character, which is looked for upon execution of a script, to another value by means of using the SET DEFINE <1_CHARACTER>

By default, the DEFINE function itself is on, and it is set to &

It can be turned off - as mentioned already - but it can be avoided as well by means of setting it to a different value. Be very aware of what sign you set it to. In the below example, I've chose the # character, but that choice is just an example.

SQL> select '&var_ampersand #var_hash' from dual;
Enter value for var_ampersand: a value

'AVALUE#VAR_HASH'
-----------------
a value #var_hash

SQL> set define #
SQL> r
  1* select '&var_ampersand #var_hash' from dual
Enter value for var_hash: another value

'&VAR_AMPERSANDANOTHERVALUE'
----------------------------
&var_ampersand another value

SQL>

Creating an Array from a Range in VBA

In addition to solutions proposed, and in case you have a 1D range to 1D array, i prefer to process it through a function like below. The reason is simple: If for any reason your range is reduced to 1 element range, as far as i know the command Range().Value will not return a variant array but just a variant and you will not be able to assign a variant variable to a variant array (previously declared).

I had to convert a variable size range to a double array, and when the range was of 1 cell size, i was not able to use a construct like range().value so i proceed with a function like below.

Public Function Rng2Array(inputRange As Range) As Double()

    Dim out() As Double    
    ReDim out(inputRange.Columns.Count - 1)

    Dim cell As Range
    Dim i As Long
    For i = 0 To inputRange.Columns.Count - 1
        out(i) = inputRange(1, i + 1) 'loop over a range "row"
    Next

    Rng2Array = out  
End Function

How to change default language for SQL Server?

If you want to change MSSQL server language, you can use the following QUERY:

EXEC sp_configure 'default language', 'British English';

How to check the multiple permission at single request in Android M?

First initialize permission request code

public  static final int PERMISSIONS_MULTIPLE_REQUEST = 123;

Check android version

 private void checkAndroidVersion() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkPermission();

    } else {
        // write your logic here
    }

}

check multiple permission code

 private void checkPermission() {
    if (ContextCompat.checkSelfPermission(getActivity(),
            Manifest.permission.READ_EXTERNAL_STORAGE) + ContextCompat
            .checkSelfPermission(getActivity(),
                    Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale
                (getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) ||
                ActivityCompat.shouldShowRequestPermissionRationale
                        (getActivity(), Manifest.permission.CAMERA)) {

      Snackbar.make(getActivity().findViewById(android.R.id.content),
                    "Please Grant Permissions to upload profile photo",
                    Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            requestPermissions(
                                    new String[]{Manifest.permission
                                            .READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
                                    PERMISSIONS_MULTIPLE_REQUEST);
                        }
                    }).show();
        } else {
            requestPermissions(
                    new String[]{Manifest.permission
                            .READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
                    PERMISSIONS_MULTIPLE_REQUEST);
        }
    } else {
        // write your logic code if permission already granted
    }
}

call back method after grant permission by user

@Override
public void onRequestPermissionsResult(int requestCode,
                                       @NonNull String[] permissions, @NonNull int[] grantResults) {

    switch (requestCode) {
        case PERMISSIONS_MULTIPLE_REQUEST:
            if (grantResults.length > 0) {
               boolean cameraPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
               boolean readExternalFile = grantResults[0] == PackageManager.PERMISSION_GRANTED;

                if(cameraPermission && readExternalFile)
                {
                    // write your logic here 
                } else {
                    Snackbar.make(getActivity().findViewById(android.R.id.content),
                        "Please Grant Permissions to upload profile photo",
                        Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                requestPermissions(
                                        new String[]{Manifest.permission
                                                .READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
                                        PERMISSIONS_MULTIPLE_REQUEST);
                            }
                        }).show();
                }
           }
           break;
    }
}

Are global variables bad?

The important thing is to remember the overall goal: clarity

The "no global variables" rule is there because most of the time, global variables make the meaning of code less clear.

However, like many rules, people remember the rule, and not what the rule was intended to do.

I've seen programs that seem to double the size of the code by passing an enormous number of parameters around simply to avoid the evil of global variables. In the end, using globals would have made the program clearer to those reading it. By mindlessly adhering to the word of the rule, the original programmer had failed the intent of the rule.

So, yes, globals are often bad. But if you feel that in the end, the intent of the programmer is made clearer by the use of global variables, then go ahead. However, remember the drop in clarity that automatically ensues when you force someone to access a second piece of code (the globals) to understand how the first piece works.

Socket.IO - how do I get a list of connected sockets/clients?

For version 2.3 this works and it will get you the socket too, it seems to me that socketIo is changing too fast and to much with to little readable documentation after using it for a while.

ioSite.of('/').in(roomId).clients((error, clients) => {
    if (error) throw error;
    for (var i=0;i<clients.length;i++) {
        clientId=clients[i];
        console.log(clientId);

        // load the socket of your namespace
        var socket=ioSite.of('/').in(roomId).connected[clientId]
        console.log(socket.constructor.name);
        console.log(socket.id);
    }
});

still this does not feel right, as I have always this feeling with socket Io somehow

Bootstrap: Position of dropdown menu relative to navbar item

Even if it s late i hope i can help someone. if dropdown menu or submenu is on the right side of screen it's open on the left side, if menu or submenu is on the left it's open on the right side.

$(".dropdown-toggle").on("click", function(event){//"show.bs.dropdown"
    var liparent=$(this.parentElement);
    var ulChild=liparent.find('ul');
    var xOffset=liparent.offset().left;
    var alignRight=($(document).width()-xOffset)<xOffset;


    if (liparent.hasClass("dropdown-submenu"))
    {
        ulChild.css("left",alignRight?"-101%":"");
    }
    else
    {                
        ulChild.toggleClass("dropdown-menu-right",alignRight);
    }

});

To detect vertical position you can also add

$( document ).ready(function() {
        var liparent=$(".dropdown");
    var yOffset=liparent.offset().top;
        var toTop=($(document).height()-yOffset)<yOffset;
    liparent.toggleClass("dropup",toTop);
});

https://jsfiddle.net/jd1100/rf9zvdhg/28/

SQL Server 2005 Setting a variable to the result of a select query

What do you mean exactly? Do you want to reuse the result of your query for an other query?

In that case, why don't you combine both queries, by making the second query search inside the results of the first one (SELECT xxx in (SELECT yyy...)

Getting the parameters of a running JVM

On Linux:

java -XX:+PrintFlagsFinal -version | grep -iE 'HeapSize|PermSize|ThreadStackSize'

On Mac OSX:

java -XX:+PrintFlagsFinal -version | grep -iE 'heapsize|permsize|threadstacksize'

On Windows:

C:\>java -XX:+PrintFlagsFinal -version | findstr /i "HeapSize PermSize ThreadStackSize"

Source: https://www.mkyong.com/java/find-out-your-java-heap-memory-size/

How do I convert a byte array to Base64 in Java?

Additionally, for our Android friends (API Level 8):

import android.util.Base64

...

Base64.encodeToString(bytes, Base64.DEFAULT);

What is the difference between a "line feed" and a "carriage return"?

Both of these are primary from the old printing days.

Carriage return is from the days of the teletype printers/old typewriters, where literally the carriage would return to the next line, and push the paper up. This is what we now call \r.

Line feed LF signals the end of the line, it signals that the line has ended - but doesn't move the cursor to the next line. In other words, it doesn't "return" the cursor/printer head to the next line.

For more sundry details, the mighty wikipedia to the rescue.

android: how to use getApplication and getApplicationContext from non activity / service class

The getApplication() method is located in the Activity class, that's why you can't access it from your helper class.

If you really need to access your application context from your helper, you should hold a reference to the activity's context and pass it on invocation to the helper.

What's the best CRLF (carriage return, line feed) handling strategy with Git?

Two alternative strategies to get consistent about line-endings in mixed environments (Microsoft + Linux + Mac):

A. Global per All Repositories Setup

1) Convert all to one format

find . -type f -not -path "./.git/*" -exec dos2unix {} \;
git commit -a -m 'dos2unix conversion'

2) Set core.autocrlf to input on Linux/UNIX or true on MS Windows (repository or global)

git config --global core.autocrlf input

3) [ Optional ] set core.safecrlf to true (to stop) or warn (to sing:) to add extra guard comparing if the reversed newline transformation would result in the same file

git config --global core.safecrlf true


B. Or per Repository Setup

1) Convert all to one format

find . -type f -not -path "./.git/*" -exec dos2unix {} \;
git commit -a -m 'dos2unix conversion'

2) add .gitattributes file to your repository

echo "* text=auto" > .gitattributes
git add .gitattributes
git commit -m 'adding .gitattributes for unified line-ending'

Don't worry about your binary files - Git should be smart enough about them.


More about safecrlf/autocrlf variables

How to check if X server is running?

I wrote xdpyprobe program which is intended for this purpose. Unlike xset, xdpyinfo and other general tools, it does not do any extra actions (just checks X server and exits) and it may not produce any output (if "-q" option is specified).

Return multiple values from a function, sub or type?

you can return 2 or more values to a function in VBA or any other visual basic stuff but you need to use the pointer method called Byref. See my example below. I will make a function to add and subtract 2 values say 5,6

sub Macro1
    ' now you call the function this way
    dim o1 as integer, o2 as integer
    AddSubtract 5, 6, o1, o2
    msgbox o2
    msgbox o1
end sub


function AddSubtract(a as integer, b as integer, ByRef sum as integer, ByRef dif as integer)
    sum = a + b
    dif = b - 1
end function

Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop

Technically slice is the fastest way. However, it is even faster if you add the 0 begin index.

myArray.slice(0);

is faster than

myArray.slice();

http://jsperf.com/cloning-arrays/3

Import CSV to mysql table

Here's how I did it in Python using csv and the MySQL Connector:

import csv
import mysql.connector

credentials = dict(user='...', password='...', database='...', host='...')
connection = mysql.connector.connect(**credentials)
cursor = connection.cursor(prepared=True)
stream = open('filename.csv', 'rb')
csv_file = csv.DictReader(stream, skipinitialspace=True)

query = 'CREATE TABLE t ('
query += ','.join('`{}` VARCHAR(255)'.format(column) for column in csv_file.fieldnames)
query += ')'
cursor.execute(query)
for row in csv_file:
    query = 'INSERT INTO t SET '
    query += ','.join('`{}` = ?'.format(column) for column in row.keys())
    cursor.execute(query, row.values())

stream.close()
cursor.close()
connection.close()

Key points

  • Use prepared statements for the INSERT
  • Open the file.csv in 'rb' binary
  • Some CSV files may need tweaking, such as the skipinitialspace option.
  • If 255 isn't wide enough you'll get errors on INSERT and have to start over.
  • Adjust column types, e.g. ALTER TABLE t MODIFY `Amount` DECIMAL(11,2);
  • Add a primary key, e.g. ALTER TABLE t ADD `id` INT PRIMARY KEY AUTO_INCREMENT;

Difference between DOMContentLoaded and load events

See the difference yourself:

DEMO

From Microsoft IE

The DOMContentLoaded event fires when parsing of the current page is complete; the load event fires when all files have finished loading from all resources, including ads and images. DOMContentLoaded is a great event to use to hookup UI functionality to complex web pages.

From Mozilla Developer Network

The DOMContentLoaded event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading (the load event can be used to detect a fully-loaded page).

Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (23.1.0) and test app (23.0.1) differ

I was getting this error

Error:Execution failed for task ':app:preDebugAndroidTestBuild'. Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ. See https://d.android.com/r/tools/test-apk-dependency-conflicts.html for details.

I was having following dependencies in my build.gradle file under Gradle Scripts

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:support-v4:26.1.0'
implementation 'com.android.support:support-vector-drawable:26.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

So, I resolved it by commenting the following dependencies

testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

So my dependencies look like this

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:support-v4:26.1.0'
implementation 'com.android.support:support-vector-drawable:26.1.0'
//testImplementation 'junit:junit:4.12'
//androidTestImplementation 'com.android.support.test:runner:1.0.2'
//androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

Hope it helps!

Query to get the names of all tables in SQL Server 2008 Database

In a single database - yes:

USE your_database
SELECT name FROM sys.tables

Getting all tables across all databases - only with a hack.... see this SO question for several approaches how to do that: How do I list all tables in all databases in SQL Server in a single result set?

What is the difference between prefix and postfix operators?

The postfix increment ++ does not increase the value of its operand until after it has been evaluated. The value of i++ is i.

The prefix decrement increases the value of its operand before it has been evaluated. The value of --i is i - 1.

Prefix increment/decrement change the value before the expression is evaluated. Postfix increment/decrement change the value after.

So, in your case, fun(10) returns 10, and printing --i prints i - 1, which is 9.

Where can I download JSTL jar

If youre using Maven, here's something for your pom.xml file

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

What is the best way to conditionally apply a class?

I am new to Angular but have found this to solve my issue:

<i class="icon-download" ng-click="showDetails = ! showDetails" ng-class="{'icon-upload': showDetails}"></i>

This will conditionally apply a class based on a var. It starts off with a icon-download as a default, the using ng-class, I check the status of showDetails if true/false and apply class icon-upload. Its working great.

Hope it helps.

pypi UserWarning: Unknown distribution option: 'install_requires'

In conclusion:

distutils doesn't support install_requires or entry_points, setuptools does.

change from distutils.core import setup in setup.py to from setuptools import setup or refactor your setup.py to use only distutils features.

I came here because I hadn't realized entry_points was only a setuptools feature.

If you are here wanting to convert setuptools to distutils like me:

  1. remove install_requires from setup.py and just use requirements.txt with pip
  2. change entry_points to scripts (doc) and refactor any modules relying on entry_points to be full scripts with shebangs and an entry point.

Get the time difference between two datetimes

When you call diff, moment.js calculates the difference in milliseconds. If the milliseconds is passed to duration, it is used to calculate duration which is correct. However. when you pass the same milliseconds to the moment(), it calculates the date that is milliseconds from(after) epoch/unix time that is January 1, 1970 (midnight UTC/GMT). That is why you get 1969 as the year together with wrong hour.

duration.get("hours") +":"+ duration.get("minutes") +":"+ duration.get("seconds")

So, I think this is how you should do it since moment.js does not offer format function for duration. Or you can write a simple wrapper to make it easier/prettier.

How to divide two columns?

Presumably, those columns are integer columns - which will be the reason as the result of the calculation will be of the same type.

e.g. if you do this:

SELECT 1 / 2

you will get 0, which is obviously not the real answer. So, convert the values to e.g. decimal and do the calculation based on that datatype instead.

e.g.

SELECT CAST(1 AS DECIMAL) / 2

gives 0.500000

Fail to create Android virtual Device, "No system image installed for this Target"

In order to create an Android Wear emulator you need to follow the instructions below:

  1. If your version of Android SDK Tools is lower than 22.6, you must update

  2. Under Android 4.4.2, select Android Wear ARM EABI v7a System Image and install it.

  3. Under Extras, ensure that you have the latest version of the Android Support Library. If an update is available, select Android Support Library. If you're using Android Studio, also select Android Support Repository.

Below is the snapshot of what it should look like:

Screenshot1

Then you must check the following in order to create a Wearable AVD:

  1. For the Device, select Android Wear Square or Android Wear Round.

  2. For the Target, select Android 4.4.2 - API Level 19 (or higher, otherwise corresponding system image will not show up.).

  3. For the CPU/ABI, select Android Wear ARM (armeabi-v7a).

  4. For the Skin, select AndroidWearSquare or AndroidWearRound.

  5. Leave all other options set to their defaults and click OK.

Screenshot2

Then you are good to go. For more information you can always refer to the developer site.

Vue js error: Component template should contain exactly one root element

if, for any reasons, you don't want to add a wrapper (in my first case it was for <tr/> components), you can use a functionnal component.

Instead of having a single components/MyCompo.vue you will have few files in a components/MyCompo folder :

  • components/MyCompo/index.js
  • components/MyCompo/File.vue
  • components/MyCompo/Avatar.vue

With this structure, the way you call your component won't change.

components/MyCompo/index.js file content :

import File from './File';
import Avatar from './Avatar';   

const commonSort=(a,b)=>b-a;

export default {
  functional: true,
  name: 'MyCompo',
  props: [ 'someProp', 'plopProp' ],
  render(createElement, context) {
    return [
        createElement( File, { props: Object.assign({light: true, sort: commonSort},context.props) } ),
        createElement( Avatar, { props: Object.assign({light: false, sort: commonSort},context.props) } )
    ]; 
  }
};

And if you have some function or data used in both templates, passed them as properties and that's it !

I let you imagine building list of components and so much features with this pattern.

How to Cast Objects in PHP

You may think about factories

class XyFactory {
    public function createXyObject ($other) {
        $new = new XyObject($other->someValue);
        // Do other things, that let $new look like $other (except the used class)
        return $new;
    }
}

Otherwise user250120s solution is the only one, which comes close to class casting.

C Program to find day of week given date

This one works: I took January 2006 as a reference. (It is a Sunday)

int isLeapYear(int year) {

     if(((year%4==0)&&(year%100!=0))||((year%400==0))) 
        return 1;
     else 
        return 0;

 }

int isDateValid(int dd,int mm,int yyyy) {

    int isValid=-1; 
    if(mm<0||mm>12) {
        isValid=-1;
    }
    else {

    if((mm==1)||(mm==3)||(mm==5)||(mm==7)||(mm==8)||(mm==10)||(mm==12)) {
           if((dd>0)&&(dd<=31))
             isValid=1;
    }  else if((mm==4)||(mm==6)||(mm==9)||(mm==11)) {
         if((dd>0)&&(dd<=30))
             isValid=1;
    }  else {
             if(isLeapYear(yyyy)){
                 if((dd>0)&&dd<30)
                     isValid=1;
             } else {
                   if((dd>0)&&dd<29)
                     isValid=1;
             }
        }  



    }
               return isValid;



 }


int calculateDayOfWeek(int dd,int mm,int yyyy)  {

                if(isDateValid(dd,mm,yyyy)==-1) {
                    return -1;
                }

                 int days=0;
                  int i; 

                   for(i=yyyy-1;i>=2006;i--) {
                         days+=(365+isLeapYear(i));

                     }
                     printf("days after years is %d\n",days);

                   for(i=mm-1;i>0;i--) {

                       if((i==1)||(i==3)||(i==5)||(i==7)||(i==8)||(i==10)) {

                           days+=31;
                       }
                       else if((i==4)||(i==6)||(i==9)||(i==11)) {
                           days+=30;
                       } else {

                           days+= (28+isLeapYear(i));

                       }


                   }
                       printf("days after months is %d\n",days);

                   days+=dd;

                   printf("days after days is %d\n",days);

                   return ((days-1)%7);                


              }

Oracle - how to remove white spaces?

Run below query replacing TABLE_NAME & COLUMN_NAME with your actual table & column names:

UPDATE TABLE_NAME SET COLUMN_NAME=TRIM(' ' from COLUMN_NAME);

What is the difference between a static method and a non-static method?

Simply put, from the point of view of the user, a static method either uses no variables at all or all of the variables it uses are local to the method or they are static fields. Defining a method as static gives a slight performance benefit.

How do you force a CIFS connection to unmount

Try umount -f /mnt/share. Works OK with NFS, never tried with cifs.

Also, take a look at autofs, it will mount the share only when accessed, and will unmount it afterworlds.

There is a good tutorial at www.howtoforge.net

Log to the base 2 in python

>>> def log2( x ):
...     return math.log( x ) / math.log( 2 )
... 
>>> log2( 2 )
1.0
>>> log2( 4 )
2.0
>>> log2( 8 )
3.0
>>> log2( 2.4 )
1.2630344058337937
>>> 

Function pointer as a member of a C struct

The pointer str is never allocated. It should be malloc'd before use.

How to specify "does not contain" in dplyr filter

Note that %in% returns a logical vector of TRUE and FALSE. To negate it, you can use ! in front of the logical statement:

SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean, 
 !where_case_travelled_1 %in% 
   c('Outside Canada','Outside province/territory of residence but within Canada'))

Regarding your original approach with -c(...), - is a unary operator that "performs arithmetic on numeric or complex vectors (or objects which can be coerced to them)" (from help("-")). Since you are dealing with a character vector that cannot be coerced to numeric or complex, you cannot use -.

How do I load an url in iframe with Jquery

Just in case anyone still stumbles upon this old question:

The code was theoretically almost correct in a sense, the problem was the use of $('this') instead of $(this), therefore telling jQuery to look for a tag.

$(document).ready(function(){
  $("#frame").click(function () { 
    $(this).load("http://www.google.com/");
  });
});

The script itself woudln't work as it is right now though because the load() function itself is an AJAX function, and google does not seem to specifically allow the use of loading this page with AJAX, but this method should be easy to use in order to load pages from your own domain by using relative paths.

Using multiple arguments for string formatting in Python (e.g., '%s ... %s')

You must just put the values into parentheses:

'%s in %s' % (unicode(self.author),  unicode(self.publication))

Here, for the first %s the unicode(self.author) will be placed. And for the second %s, the unicode(self.publication) will be used.

Note: You should favor string formatting over the % Notation. More info here

How to run an .ipynb Jupyter Notebook from terminal?

In your Terminal run ipython:

ipython

then locate your script and put there:

%run your_script.ipynb

Specifying trust store information in spring boot application.properties

Here my extended version of Oleksandr Shpota's answer, including the imports. The package org.apache.http.* can be found in org.apache.httpcomponents:httpclient. I've commented the changes:

import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Value("${http.client.ssl.key-store}")
private Resource keyStore;

@Value("${http.client.ssl.trust-store}")
private Resource trustStore;

// I use the same pw for both keystores:
@Value("${http.client.ssl.trust-store-password}")
private String keyStorePassword;

// wasn't able to provide this as a @Bean...:
private RestTemplate getRestTemplate() {
  try {
    SSLContext sslContext = SSLContexts.custom()
        // keystore wasn't within the question's scope, yet it might be handy:
        .loadKeyMaterial(
            keyStore.getFile(),
            keyStorePassword.toCharArray(),
            keyStorePassword.toCharArray())
        .loadTrustMaterial(
            trustStore.getURL(),
            keyStorePassword.toCharArray(),
            // use this for self-signed certificates only:
            new TrustSelfSignedStrategy())
        .build();

    HttpClient httpClient = HttpClients.custom()
        // use NoopHostnameVerifier with caution, see https://stackoverflow.com/a/22901289/3890673
        .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()))
        .build();

    return new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
  } catch (IOException | GeneralSecurityException e) {
    throw new RuntimeException(e);
  }
}

Plot smooth line with PyPlot

For this example spline works well, but if the function is not smooth inherently and you want to have smoothed version you can also try:

from scipy.ndimage.filters import gaussian_filter1d

ysmoothed = gaussian_filter1d(y, sigma=2)
plt.plot(x, ysmoothed)
plt.show()

if you increase sigma you can get a more smoothed function.

Proceed with caution with this one. It modifies the original values and may not be what you want.

View HTTP headers in Google Chrome?

My favorite way in Chrome is clicking on a bookmarklet:

javascript:(function(){function read(url){var r=new XMLHttpRequest();r.open('HEAD',url,false);r.send(null);return r.getAllResponseHeaders();}alert(read(window.location))})();

Put this code in your developer console pad.

Source: http://www.danielmiessler.com/blog/a-bookmarklet-that-displays-http-headers

How to convert a Kotlin source file to a Java source file

As @Vadzim said, in IntelliJ or Android Studio, you just have to do the following to get java code from kotlin:

  1. Menu > Tools > Kotlin > Show Kotlin Bytecode
  2. Click on the Decompile button
  3. Copy the java code

Update:

With a recent version (1.2+) of the Kotlin plugin you also can directly do Menu > Tools > Kotlin -> Decompile Kotlin to Java.

How to securely save username/password (local)?

DPAPI is just for this purpose. Use DPAPI to encrypt the password the first time the user enters is, store it in a secure location (User's registry, User's application data directory, are some choices). Whenever the app is launched, check the location to see if your key exists, if it does use DPAPI to decrypt it and allow access, otherwise deny it.

Connecting to remote URL which requires authentication using Java

i did that this way you need to do this just copy paste it be happy

    HttpURLConnection urlConnection;
    String url;
 //   String data = json;
    String result = null;
    try {
        String username ="[email protected]";
        String password = "12345678";

        String auth =new String(username + ":" + password);
        byte[] data1 = auth.getBytes(UTF_8);
        String base64 = Base64.encodeToString(data1, Base64.NO_WRAP);
        //Connect
        urlConnection = (HttpURLConnection) ((new URL(urlBasePath).openConnection()));
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestProperty("Authorization", "Basic "+base64);
        urlConnection.setRequestProperty("Accept", "application/json");
        urlConnection.setRequestMethod("POST");
        urlConnection.setConnectTimeout(10000);
        urlConnection.connect();
        JSONObject obj = new JSONObject();

        obj.put("MobileNumber", "+97333746934");
        obj.put("EmailAddress", "[email protected]");
        obj.put("FirstName", "Danish");
        obj.put("LastName", "Hussain");
        obj.put("Country", "BH");
        obj.put("Language", "EN");
        String data = obj.toString();
        //Write
        OutputStream outputStream = urlConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        writer.write(data);
        writer.close();
        outputStream.close();
        int responseCode=urlConnection.getResponseCode();
        if (responseCode == HttpsURLConnection.HTTP_OK) {
            //Read
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));

        String line = null;
        StringBuilder sb = new StringBuilder();

        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }

        bufferedReader.close();
        result = sb.toString();

        }else {
        //    return new String("false : "+responseCode);
        new String("false : "+responseCode);
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

List of encodings that Node.js supports

If the above solution does not work for you it is may be possible to obtain the same result with the following pure nodejs code. The above did not work for me and resulted in a compilation exception when running 'npm install iconv' on OSX:

npm install iconv

npm WARN package.json [email protected] No README.md file found!
npm http GET https://registry.npmjs.org/iconv
npm http 200 https://registry.npmjs.org/iconv
npm http GET https://registry.npmjs.org/iconv/-/iconv-2.0.4.tgz
npm http 200 https://registry.npmjs.org/iconv/-/iconv-2.0.4.tgz

> [email protected] install /Users/markboyd/git/portal/app/node_modules/iconv
> node-gyp rebuild

gyp http GET http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz
gyp http 200 http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz
xcode-select: Error: No Xcode is selected. Use xcode-select -switch <path-to-xcode>, or see the xcode-select manpage (man xcode-select) for further information.

fs.readFileSync() returns a Buffer if no encoding is specified. And Buffer has a toString() method that will convert to UTF8 if no encoding is specified giving you the file's contents. See the nodejs documentation. This worked for me.

convert htaccess to nginx

Online tools to translate Apache .htaccess to Nginx rewrite tools include:

Note that these tools will convert to equivalent rewrite expressions using if statements, but they should be converted to try_files. See:

Pivoting rows into columns dynamically in Oracle

First of all, dynamically pivot using pivot xml again needs to be parsed. We have another way of doing this by storing the column names in a variable and passing them in the dynamic sql as below.

Consider we have a table like below.

enter image description here

If we need to show the values in the column YR as column names and the values in those columns from QTY, then we can use the below code.

declare
  sqlqry clob;
  cols clob;
begin
  select listagg('''' || YR || ''' as "' || YR || '"', ',') within group (order by YR)
  into   cols
  from   (select distinct YR from EMPLOYEE);


  sqlqry :=
  '      
  select * from
  (
      select *
      from EMPLOYEE
  )
  pivot
  (
    MIN(QTY) for YR in (' || cols  || ')
  )';

  execute immediate sqlqry;
end;
/

RESULT

enter image description here

'JSON' is undefined error in JavaScript in Internet Explorer

I had this error 2 times. Each time it was solved by changing the ajax type. Either GET to POST or POST to GET.

$.ajax({
        type:'GET', // or 'POST'
        url: "file.cfm?action=get_table&varb=" + varb
    });

canvas.toDataURL() SecurityError

Just use the crossOrigin attribute and pass 'anonymous' as the second parameter

var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;

Java 8 Streams FlatMap method example

A very simple example: Split a list of full names to get a list of names, regardless of first or last

 List<String> fullNames = Arrays.asList("Barry Allen", "Bruce Wayne", "Clark Kent");

 fullNames.stream()
            .flatMap(fullName -> Pattern.compile(" ").splitAsStream(fullName))
            .forEach(System.out::println);

This prints out:

Barry
Allen
Bruce
Wayne
Clark
Kent

What algorithms compute directions from point A to point B on a map?

Graph algorithms like Dijkstra's algorithm will not work because the graph is enormous.

This argument doesn't necessarily hold because Dijkstra will not usually look at the complete graph but rather just a very small subset (the better interconnected the graph, the smaller this subset).

Dijkstra may actually perform rather well for well-behaved graphs. On the other hand, with careful parametrization A* will always perform just as good, or better. Have you already tried how it would perform on your data?

That said, I'd also be very interested to hear about other peoples' experiences. Of course, prominent examples like Google Map's search are particularly interesting. I could imagine something like a directed nearest neighbour heuristic.

How to recognize vehicle license / number plate (ANPR) from an image?

There is a new, open source library on GitHub that does ANPR for US and European plates. It looks pretty accurate and it should do exactly what you need (recognize the plate regions). Here is the GitHub project: https://github.com/openalpr/openalpr

Tools to selectively Copy HTML+CSS+JS From A Specific Element of DOM

There is a firefox plugin that saves the whole page's HTML, CSS, etc.. but I have not seen one that does a partial save.

I remember IE 5.5 had what you were looking for though ;)

Setting DEBUG = False causes 500 Error

I encountered the same issue just recently in Django 2.0. I was able to figure out the problem by setting DEBUG_PROPAGATE_EXCEPTIONS = True. See here: https://docs.djangoproject.com/en/2.0/ref/settings/#debug-propagate-exceptions

In my case, the error was ValueError: Missing staticfiles manifest entry for 'admin/css/base.css'. I fixed that by locally running python manage.py collectstatic.

How to ensure that there is a delay before a service is started in systemd?

You can run the sleep command before your ExecStart with ExecStartPre :

[Service]
ExecStartPre=/bin/sleep 30

Expand Python Search Path to Other Source

You should also read about python packages here: http://docs.python.org/tutorial/modules.html.

From your example, I would guess that you really have a package at ~/codez/project. The file __init__.py in a python directory maps a directory into a namespace. If your subdirectories all have an __init__.py file, then you only need to add the base directory to your PYTHONPATH. For example:

PYTHONPATH=$PYTHONPATH:$HOME/adaifotis/project

In addition to testing your PYTHONPATH environment variable, as David explains, you can test it in python like this:

$ python
>>> import project                      # should work if PYTHONPATH set
>>> import sys
>>> for line in sys.path: print line    # print current python path

...

Determine number of pages in a PDF file

I have good success using CeTe Dynamic PDF products. They're not free, but are well documented. They did the job for me.

http://www.dynamicpdf.com/

Create a circular button in BS3

To add a rounded border in any button the best way is to add the border-radius property. I belive this class is better because you can add-it at any button size. If you set the height and widht you will need to create a "rouding" class to each button size.

_x000D_
_x000D_
.btn-circle {_x000D_
  border-radius: 50%;_x000D_
}
_x000D_
<button class='btn-circle'>Click Me!</button>_x000D_
<button class='btn-circle'>?</button>
_x000D_
_x000D_
_x000D_

iPad Web App: Detect Virtual Keyboard Using JavaScript in Safari?

maybe a slightly better solution is to bind (with jQuery in my case) the "blur" event on the various input fields.

This because when the keyboard disappear all form fields are blurred. So for my situation this snipped solved the problem.

$('input, textarea').bind('blur', function(e) {

       // Keyboard disappeared
       window.scrollTo(0, 1);

});

hope it helps. Michele

Convert list of ints to one number?

I found this thread while trying to convert a list to the real value of the underlying int in terms of a C-style pointer, but none of the other answers appear to work for this case. I think the following solution works as intended and could be useful to others even though it doesn't necessarily answer the original question.

def listToInt(x, reverseBytes=False):
  if reverseBytes:
    x = x[::-1]
  return reduce(lambda x,y: x*256+y, x)

listToInt([1, 249]) == 505

listToInt([249, 1], True) == 505

The primary value of this is to emulate the behavior of casting a byte array to another data type, e.g. uint16, which Python can't seem to do natively, on either a big or little endian system.

Generate an integer sequence in MySQL

The following will return 1..10000 and is not so slow

SELECT @row := @row + 1 AS row FROM 
(select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t,
(select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t2, 
(select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t3, 
(select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t4, 
(SELECT @row:=0) numbers;

Bootstrap 4 File Input

In case you want to use it globally on all custom inputs use following jQuery code:

$(document).ready(function () {
    $('.custom-file-input').on('change', function (e) {
         e.target.nextElementSibling.innerHTML = e.target.files[0].name;
    });
});

Displaying a vector of strings in C++

You ask two questions; your title says "Displaying a vector of strings", but you're not actually doing that, you actually build a single string composed of all the strings and output that.

Your question body asks "Why doesn't this work".

It doesn't work because your for loop is constrained by "userString.size()" which is 0, and you test your loop variable for being "userString.size() - 1". The condition of a for() loop is tested before permitting execution of the first iteration.

int n = 1;
for (int i = 1; i < n; ++i) {
    std::cout << i << endl;
}

will print exactly nothing.

So your loop executes exactly no iterations, leaving userString and sentence empty.

Lastly, your code has absolutely zero reason to use a vector. The fact that you used "decltype(userString.size())" instead of "size_t" or "auto", while claiming to be a rookie, suggests you're either reading a book from back to front or you are setting yourself up to fail a class.

So to answer your question at the end of your post: It doesn't work because you didn't step through it with a debugger and inspect the values as it went. While I say it tongue-in-cheek, I'm going to leave it out there.

What is the Oracle equivalent of SQL Server's IsNull() function?

Also use NVL2 as below if you want to return other value from the field_to_check:

NVL2( field_to_check, value_if_NOT_null, value_if_null )

Usage: ORACLE/PLSQL: NVL2 FUNCTION

How to detect if a stored procedure already exists

IF OBJECT_ID('SPNAME') IS NULL
     -- Does Not Exists
ELSE
     -- Exists

URL Encode a string in jQuery for an AJAX request

try this one

var query = "{% url accounts.views.instasearch  %}?q=" + $('#tags').val().replace(/ /g, '+');

How to split a comma-separated string?

In Kotlin,

val stringArray = commasString.replace(", ", ",").split(",")

where stringArray is List<String> and commasString is String with commas and spaces

JavaScript - get the first day of the week from current date

I'm using this

function get_next_week_start() {
   var now = new Date();
   var next_week_start = new Date(now.getFullYear(), now.getMonth(), now.getDate()+(8 - now.getDay()));
   return next_week_start;
}

how to iterate through dictionary in a dictionary in django template?

Lets say your data is -

data = {'a': [ [1, 2] ], 'b': [ [3, 4] ],'c':[ [5,6]] }

You can use the data.items() method to get the dictionary elements. Note, in django templates we do NOT put (). Also some users mentioned values[0] does not work, if that is the case then try values.items.

<table>
    <tr>
        <td>a</td>
        <td>b</td>
        <td>c</td>
    </tr>

    {% for key, values in data.items %}
    <tr>
        <td>{{key}}</td>
        {% for v in values[0] %}
        <td>{{v}}</td>
        {% endfor %}
    </tr>
    {% endfor %}
</table>

Am pretty sure you can extend this logic to your specific dict.


To iterate over dict keys in a sorted order - First we sort in python then iterate & render in django template.

return render_to_response('some_page.html', {'data': sorted(data.items())})

In template file:

{% for key, value in data %}
    <tr>
        <td> Key: {{ key }} </td> 
        <td> Value: {{ value }} </td>
    </tr>
{% endfor %}

C non-blocking keyboard input

The curses library can be used for this purpose. Of course, select() and signal handlers can be used too to a certain extent.

Problems after upgrading to Xcode 10: Build input file cannot be found

For Swift files or files that belong to the project such as:

Build input file cannot be found: PATH/TO/FILE/FILE.swift

This issue can happen when files or folders have been removed or moved in the project.

To fix it:

  1. Go in the project-navigator, select your project

  2. Select Build Phasestab

  3. In Compile Sources section, check for the file(s) that Xcode is complaining of

  4. Notice that the file(s) have the wrong path, and delete them by clicking on the minus icon

  5. Re-add the file(s) by clicking the plus icon and search in the project.

  6. Product > Clean Build Folder

  7. Build

You generally find these missing files in the Recovered References folder of Xcode in the project tree (look for the search bar at the bottom-left of Xcode and search for your complaining file):

Deleting them from this folder can also solve the error.

ALTER TABLE add constraint

alter table User 
    add constraint userProperties
    foreign key (properties)
    references Properties(ID)

android.view.InflateException: Binary XML file: Error inflating class fragment

In my case .

The layout i was trying to inflate had

<include 
 layout  = "...."
/>

tag, removing it fixed it.

I was trying to inflate a previous layout designed for a Actvity into the view-pager adapter.

Javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: Failure in SSL library, usually a protocol error

Previously, I've also solved this problem with custom SSLFactory implementation, but according to OkHttp docs the solution is much easier.

My final solution with needed TLS ciphers for 4.2+ devices looks like this:

public UsersApi provideUsersApi() {

    private ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS)
        .supportsTlsExtensions(true)
        .tlsVersions(TlsVersion.TLS_1_2, TlsVersion.TLS_1_1, TlsVersion.TLS_1_0)
        .cipherSuites(
                CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
                CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
                CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
                CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
                CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
                CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
                CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
                CipherSuite.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
                CipherSuite.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
                CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
                CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
                CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA)
        .build();

    OkHttpClient client = new OkHttpClient.Builder()
            .connectionSpecs(Collections.singletonList(spec))
            .build();

    return new Retrofit.Builder()
            .baseUrl(USERS_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build()
            .create(UsersApi.class);
}

Note that set of supported protocols depends on configured on your server.

R for loop skip to next iteration ifelse

for(n in 1:5) {
  if(n==3) next # skip 3rd iteration and go to next iteration
  cat(n)
}

@AspectJ pointcut for all methods of a class with specific annotation

The simplest way seems to be :

@Around("execution(@MyHandling * com.exemple.YourService.*(..))")
public Object aroundServiceMethodAdvice(final ProceedingJoinPoint pjp)
   throws Throwable {
   // perform actions before

   return pjp.proceed();

   // perform actions after
}

It will intercept execution of all methods specifically annotated with '@MyHandling' in 'YourService' class. To intercept all methods without exception, just put the annotation directly on the class.

No matter of the private / public scope here, but keep in mind that spring-aop cannot use aspect for method calls in same instance (typically private ones), because it doesn't use the proxy class in this case.

We use @Around advice here, but it's basically the same syntax with @Before, @After or any advice.

By the way, @MyHandling annotation must be configured like this :

@Retention(RetentionPolicy.RUNTIME)
@Target( { ElementType.METHOD, ElementType.TYPE })
public @interface MyHandling {

}

How to select all the columns of a table except one column?

You can use this approach to get the data from all the columns except one:-

  1. Insert all the data into a temporary table
  2. Then drop the column which you dont want from the temporary table
  3. Fetch the data from the temporary table(This will not contain the data of the removed column)
  4. Drop the temporary table

Something like this:

SELECT * INTO #TemporaryTable FROM YourTableName

ALTER TABLE #TemporaryTable DROP COLUMN Columnwhichyouwanttoremove

SELECT * FROM #TemporaryTable 

DROP TABLE #TemporaryTable 

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

I would like to add an example of prototypical inheritance with javascript to @Scott Driscoll answer. We'll be using classical inheritance pattern with Object.create() which is a part of EcmaScript 5 specification.

First we create "Parent" object function

function Parent(){

}

Then add a prototype to "Parent" object function

 Parent.prototype = {
 primitive : 1,
 object : {
    one : 1
   }
}

Create "Child" object function

function Child(){

}

Assign child prototype (Make child prototype inherit from parent prototype)

Child.prototype = Object.create(Parent.prototype);

Assign proper "Child" prototype constructor

Child.prototype.constructor = Child;

Add method "changeProps" to a child prototype, which will rewrite "primitive" property value in Child object and change "object.one" value both in Child and Parent objects

Child.prototype.changeProps = function(){
    this.primitive = 2;
    this.object.one = 2;
};

Initiate Parent (dad) and Child (son) objects.

var dad = new Parent();
var son = new Child();

Call Child (son) changeProps method

son.changeProps();

Check the results.

Parent primitive property did not change

console.log(dad.primitive); /* 1 */

Child primitive property changed (rewritten)

console.log(son.primitive); /* 2 */

Parent and Child object.one properties changed

console.log(dad.object.one); /* 2 */
console.log(son.object.one); /* 2 */

Working example here http://jsbin.com/xexurukiso/1/edit/

More info on Object.create here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/create

Restart pods when configmap updates in Kubernetes?

Signalling a pod on config map update is a feature in the works (https://github.com/kubernetes/kubernetes/issues/22368).

You can always write a custom pid1 that notices the confimap has changed and restarts your app.

You can also eg: mount the same config map in 2 containers, expose a http health check in the second container that fails if the hash of config map contents changes, and shove that as the liveness probe of the first container (because containers in a pod share the same network namespace). The kubelet will restart your first container for you when the probe fails.

Of course if you don't care about which nodes the pods are on, you can simply delete them and the replication controller will "restart" them for you.

Find first element by predicate

However this seems inefficient to me, as the filter will scan the whole list

No it won't - it will "break" as soon as the first element satisfying the predicate is found. You can read more about laziness in the stream package javadoc, in particular (emphasis mine):

Many stream operations, such as filtering, mapping, or duplicate removal, can be implemented lazily, exposing opportunities for optimization. For example, "find the first String with three consecutive vowels" need not examine all the input strings. Stream operations are divided into intermediate (Stream-producing) operations and terminal (value- or side-effect-producing) operations. Intermediate operations are always lazy.

Is mongodb running?

Probably because I didn't shut down my dev server properly or a similar reason. To fix it, remove the lock and start the server with: sudo rm /var/lib/mongodb/mongod.lock ; sudo start mongodb

Can someone explain __all__ in Python?

I'm just adding this to be precise:

All other answers refer to modules. The original question explicitely mentioned __all__ in __init__.py files, so this is about python packages.

Generally, __all__ only comes into play when the from xxx import * variant of the import statement is used. This applies to packages as well as to modules.

The behaviour for modules is explained in the other answers. The exact behaviour for packages is described here in detail.

In short, __all__ on package level does approximately the same thing as for modules, except it deals with modules within the package (in contrast to specifying names within the module). So __all__ specifies all modules that shall be loaded and imported into the current namespace when us use from package import *.

The big difference is, that when you omit the declaration of __all__ in a package's __init__.py, the statement from package import * will not import anything at all (with exceptions explained in the documentation, see link above).

On the other hand, if you omit __all__ in a module, the "starred import" will import all names (not starting with an underscore) defined in the module.

What is the purpose of a self executing function in javascript?

Simplistic. So very normal looking, its almost comforting:

var userName = "Sean";

console.log(name());

function name() {
  return userName;
}

However, what if I include a really handy javascript library to my page that translates advanced characters into their base level representations?

Wait... what?

I mean, if someone types in a character with some kind of accent on it, but I only want 'English' characters A-Z in my program? Well... the Spanish 'ñ' and French 'é' characters can be translated into base characters of 'n' and 'e'.

So someone nice person has written a comprehensive character converter out there that I can include in my site... I include it.

One problem: it has a function in it called 'name' same as my function.

This is what's called collision. We've got two functions declared in the same scope with the same name. We want to avoid this.

So we need to scope our code somehow.

The only way to scope code in javascript is to wrap it in a function:

function main() {
  // We are now in our own sound-proofed room and the 
  // character-converter libarary's name() function can exist at the 
  // same time as ours. 

  var userName = "Sean";

  console.log(name());

  function name() {
    return userName;
  }
}

That might solve our problem. Everything is now enclosed and can only be accessed from within our opening and closing braces.

We have a function in a function... which is weird to look at, but totally legal.

Only one problem. Our code doesn't work. Our userName variable is never echoed into the console!

We can solve this issue by adding a call to our function after our existing code block...

function main() {
  // We are now in our own sound-proofed room and the 
  // character-converter libarary's name() function can exist at the 
  // same time as ours. 

  var userName = "Sean";

  console.log(name());

  function name() {
    return userName;
  }
}

main();

Or before!

main();

function main() {
  // We are now in our own sound-proofed room and the 
  // character-converter libarary's name() function can exist at the 
  // same time as ours. 

  var userName = "Sean";

  console.log(name());

  function name() {
    return userName;
  }
}

A secondary concern: What are the chances that the name 'main' hasn't been used yet? ...so very, very slim.

We need MORE scoping. And some way to automatically execute our main() function.

Now we come to auto-execution functions (or self-executing, self-running, whatever).

((){})();

The syntax is awkward as sin. However, it works.

When you wrap a function definition in parentheses, and include a parameter list (another set or parentheses!) it acts as a function call.

So lets look at our code again, with some self-executing syntax:

(function main() {
  var userName = "Sean";

    console.log(name());

    function name() {
      return userName;
    }
  }
)();

So, in most tutorials you read, you will now be bombard with the term 'anonymous self-executing' or something similar.

After many years of professional development, I strongly urge you to name every function you write for debugging purposes.

When something goes wrong (and it will), you will be checking the backtrace in your browser. It is always easier to narrow your code issues when the entries in the stack trace have names!

Hugely long-winded and I hope it helps!

How do I delete from multiple tables using INNER JOIN in SQL server

$sql="DELETE FROM basic_tbl,education_tbl, personal_tbl ,address_tbl,department_tbl USING basic_tbl,education_tbl, personal_tbl ,address_tbl,department_tbl WHERE b_id=e_id=p_id=a_id=d_id='".$id."' "; $rs=mysqli_query($con,$sql);

How to Merge Two Eloquent Collections?

Creating a new base collection for each eloquent collection the merge works for me.

$foo = collect(Foo::all());
$bar = collect(Bar::all());
$merged = $foo->merge($bar);

In this case don't have conflits by its primary keys.

Convert Time DataType into AM PM Format:

In SQL 2012 you can use the Format() function.

https://technet.microsoft.com/en-us/library/hh213505%28v=sql.110%29.aspx

Skip casting if the column type is (datetime).

Example:

SELECT FORMAT(StartTime,'hh:mm tt') AS StartTime
FROM TableA

Call a "local" function within module.exports from another function in module.exports?

Starting with Node.js version 13 you can take advantage of ES6 Modules.

export function foo() {
    return 'foo';
}

export function bar() {
    return foo();
}

Following the Class approach:

class MyClass {

    foo() {
        return 'foo';
    }

    bar() {
        return this.foo();
    }
}

module.exports = new MyClass();

This will instantiate the class only once, due to Node's module caching:
https://nodejs.org/api/modules.html#modules_caching

How can a query multiply 2 cell for each row MySQL?

I'm assuming this should work. This will actually put it in the column in your database

UPDATE yourTable yt SET yt.Total = (yt.Pieces * yt.Price)

If you want to retrieve the 2 values from the database and put your multiplication in the third column of the result only, then

SELECT yt.Pieces, yt.Price, (yt.Pieces * yt.Price) as 'Total' FROM yourTable yt

will be your friend

How do I view the Explain Plan in Oracle Sql developer?

Explain only shows how the optimizer thinks the query will execute.

To show the real plan, you will need to run the sql once. Then use the same session run the following:

@yoursql 
select * from table(dbms_xplan.display_cursor()) 

This way can show the real plan used during execution. There are several other ways in showing plan using dbms_xplan. You can Google with term "dbms_xplan".

How to display a date as iso 8601 format with PHP

Here is the good function for pre PHP 5: I added GMT difference at the end, it's not hardcoded.

function iso8601($time=false) {
    if ($time === false) $time = time();
    $date = date('Y-m-d\TH:i:sO', $time);
    return (substr($date, 0, strlen($date)-2).':'.substr($date, -2));
}

Is there a constraint that restricts my generic method to numeric types?

I created a little library functionality to solve these problems:

Instead of:

public T DifficultCalculation<T>(T a, T b)
{
    T result = a * b + a; // <== WILL NOT COMPILE!
    return result;
}
Console.WriteLine(DifficultCalculation(2, 3)); // Should result in 8.

You could write:

public T DifficultCalculation<T>(Number<T> a, Number<T> b)
{
    Number<T> result = a * b + a;
    return (T)result;
}
Console.WriteLine(DifficultCalculation(2, 3)); // Results in 8.

You can find the source code here: https://codereview.stackexchange.com/questions/26022/improvement-requested-for-generic-calculator-and-generic-number

Flask Value error view function did not return a response

You are not returning a response object from your view my_form_post. The function ends with implicit return None, which Flask does not like.

Make the function my_form_post return an explicit response, for example

return 'OK'

at the end of the function.

How do you change the launcher logo of an app in Android Studio?

In the manifest file, under the tag, there will be a similar line:

android:icon="drawable_resource_path"

Place the launcher icon you want in drawable folder and write its resource path.

Styling text input caret

'Caret' is the word you are looking for. I do believe though, that it is part of the browsers design, and not within the grasp of css.

However, here is an interesting write up on simulating a caret change using Javascript and CSS http://www.dynamicdrive.com/forums/showthread.php?t=17450 It seems a bit hacky to me, but probably the only way to accomplish the task. The main point of the article is:

We will have a plain textarea somewhere in the screen out of the view of the viewer and when the user clicks on our "fake terminal" we will focus into the textarea and when the user starts typing we will simply append the data typed into the textarea to our "terminal" and that's that.

HERE is a demo in action


2018 update

There is a new css property caret-color which applies to the caret of an input or contenteditable area. The support is growing but not 100%, and this only affects color, not width or other types of appearance.

_x000D_
_x000D_
input{_x000D_
  caret-color: rgb(0, 200, 0);_x000D_
}
_x000D_
<input type="text"/>
_x000D_
_x000D_
_x000D_

Counting repeated characters in a string in Python

I can count the number of days I know Python on my two hands so forgive me if I answer something silly :)

Instead of using a dict, I thought why not use a list? I'm not sure how lists and dictionaries are implemented in Python so this would have to be measured to know what's faster.

If this was C++ I would just use a normal c-array/vector for constant time access (that would definitely be faster) but I don't know what the corresponding datatype is in Python (if there's one...):

count = [0 for i in range(26)]

for c in ''.join(s.lower().split()): # get rid of whitespaces and capital letters
    count[ord(c) - 97] += 1          # ord('a') == 97

It's also possible to make the list's size ord('z') and then get rid of the 97 subtraction everywhere, but if you optimize, why not all the way :)

EDIT: A commenter suggested that the join/split is not worth the possible gain of using a list, so I thought why not get rid of it:

count = [0 for i in range(26)]

for c in s:
    if c.isalpha(): count[ord(c.lower()) - 97] += 1

Using headers with the Python requests library's get method

According to the API, the headers can all be passed in using requests.get:

import requests
r=requests.get("http://www.example.com/", headers={"content-type":"text"})

Extract substring using regexp in plain bash

If your string is

foo="US/Central - 10:26 PM (CST)"

then

echo "${foo}" | cut -d ' ' -f3

will do the job.

How to prevent form resubmission when page is refreshed (F5 / CTRL+R)

  1. Use header and redirect the page.

    header("Location:your_page.php"); You can redirect to same page or different page.

  2. Unset $_POST after inserting it to Database.

    unset($_POST);

Get UTC time in seconds

One might consider adding this line to ~/.bash_profile (or similar) in order to can quickly get the current UTC both as current time and as seconds since the epoch.

alias utc='date -u && date -u +%s'

JavaScript: Global variables after Ajax requests

The reason your code fails is because post() will start an asynchronous request to the server. What that means for you is that post() returns immediately, not after the request completes, like you are expecting.

What you need, then, is for the request to be synchronous and block the current thread until the request completes. Thus,

var it_works = false;

$.ajax({
  url: 'some_file.php',
  async: false,  # makes request synchronous
  success: function() {
    it_works = true;
  }
});

alert(it_works);

Is it possible to focus on a <div> using JavaScript focus() function?

_x000D_
_x000D_
document.getElementById('test').onclick = function () {_x000D_
    document.getElementById('scripted').focus();_x000D_
};
_x000D_
div:focus {_x000D_
    background-color: Aqua;_x000D_
}
_x000D_
<div>Element X (not focusable)</div>_x000D_
<div tabindex="0">Element Y (user or script focusable)</div>_x000D_
<div tabindex="-1" id="scripted">Element Z (script-only focusable)</div>_x000D_
<div id="test">Set Focus To Element Z</div>
_x000D_
_x000D_
_x000D_

There was no endpoint listening at (url) that could accept the message

go to webconfig page of your site, look for the tag endpoint, and check the port in the address attribute, maybe there was a change in the port number

LINQ .Any VS .Exists - What's the difference?

See documentation

List.Exists (Object method - MSDN)

Determines whether the List(T) contains elements that match the conditions defined by the specified predicate.

This exists since .NET 2.0, so before LINQ. Meant to be used with the Predicate delegate, but lambda expressions are backward compatible. Also, just List has this (not even IList)

IEnumerable.Any (Extension method - MSDN)

Determines whether any element of a sequence satisfies a condition.

This is new in .NET 3.5 and uses Func(TSource, bool) as argument, so this was intended to be used with lambda expressions and LINQ.

In behaviour, these are identical.

How to highlight text using javascript

Here's my regexp pure JavaScript solution:

function highlight(text) {
    document.body.innerHTML = document.body.innerHTML.replace(
        new RegExp(text + '(?!([^<]+)?<)', 'gi'),
        '<b style="background-color:#ff0;font-size:100%">$&</b>'
    );
}

How to programmatically tell if a Bluetooth device is connected?

BluetoothAdapter.getDefaultAdapter().isEnabled -> returns true when bluetooth is open

val audioManager = this.getSystemService(Context.AUDIO_SERVICE) as AudioManager

audioManager.isBluetoothScoOn -> returns true when device connected

java: How can I do dynamic casting of a variable from one type to another?

Don't do this. Just have a properly parameterized constructor instead. The set and types of the connection parameters are fixed anyway, so there is no point in doing this all dynamically.

Download and open PDF file using Ajax

_x000D_
_x000D_
var xhr;_x000D_
var beforeSend = function(){_x000D_
    $('#pleasewaitDL').modal('show');_x000D_
}_x000D_
$(function () {_x000D_
    $('#print_brochure_link').click(function(){_x000D_
        beforeSend();_x000D_
        xhr = new XMLHttpRequest();_x000D_
        xhr.open("GET",$('#preparedPrintModalForm').attr('action'), true); _x000D_
        xhr.responseType = "blob";_x000D_
        xhr.onload = function (e) {_x000D_
            if (this.status === 200) {_x000D_
                var file = window.URL.createObjectURL(this.response);_x000D_
                var a = document.createElement("a");_x000D_
                a.href = file;_x000D_
                a.download = this.response.name || "Property Brochure";_x000D_
                console.log(file);_x000D_
                document.body.appendChild(a);_x000D_
                a.click();_x000D_
                _x000D_
                window.onfocus = function () {                     _x000D_
                  document.body.removeChild(a)_x000D_
                }_x000D_
                $('#pleasewaitDL').modal('hide');_x000D_
            };_x000D_
        };_x000D_
        xhr.send($('#preparedPrintModalForm').serialize());_x000D_
    });_x000D_
    $('#pleasewaitDLCancel').click(function() {_x000D_
        xhr.abort();_x000D_
    });_x000D_
});
_x000D_
_x000D_
_x000D_

Use of Custom Data Types in VBA

Sure you can:

Option Explicit

'***** User defined type
Public Type MyType
     MyInt As Integer
     MyString As String
     MyDoubleArr(2) As Double
End Type

'***** Testing MyType as single variable
Public Sub MyFirstSub()
    Dim MyVar As MyType

    MyVar.MyInt = 2
    MyVar.MyString = "cool"
    MyVar.MyDoubleArr(0) = 1
    MyVar.MyDoubleArr(1) = 2
    MyVar.MyDoubleArr(2) = 3

    Debug.Print "MyVar: " & MyVar.MyInt & " " & MyVar.MyString & " " & MyVar.MyDoubleArr(0) & " " & MyVar.MyDoubleArr(1) & " " & MyVar.MyDoubleArr(2)
End Sub

'***** Testing MyType as an array
Public Sub MySecondSub()
    Dim MyArr(2) As MyType
    Dim i As Integer

    MyArr(0).MyInt = 31
    MyArr(0).MyString = "VBA"
    MyArr(0).MyDoubleArr(0) = 1
    MyArr(0).MyDoubleArr(1) = 2
    MyArr(0).MyDoubleArr(2) = 3
    MyArr(1).MyInt = 32
    MyArr(1).MyString = "is"
    MyArr(1).MyDoubleArr(0) = 11
    MyArr(1).MyDoubleArr(1) = 22
    MyArr(1).MyDoubleArr(2) = 33
    MyArr(2).MyInt = 33
    MyArr(2).MyString = "cool"
    MyArr(2).MyDoubleArr(0) = 111
    MyArr(2).MyDoubleArr(1) = 222
    MyArr(2).MyDoubleArr(2) = 333

    For i = LBound(MyArr) To UBound(MyArr)
        Debug.Print "MyArr: " & MyArr(i).MyString & " " & MyArr(i).MyInt & " " & MyArr(i).MyDoubleArr(0) & " " & MyArr(i).MyDoubleArr(1) & " " & MyArr(i).MyDoubleArr(2)
    Next
End Sub

Re-render React component when prop changes

componentWillReceiveProps(nextProps) { // your code here}

I think that is the event you need. componentWillReceiveProps triggers whenever your component receive something through props. From there you can have your checking then do whatever you want to do.

How do I detect whether a Python variable is a function?

callable(x) will return true if the object passed can be called in Python, but the function does not exist in Python 3.0, and properly speaking will not distinguish between:

class A(object):
    def __call__(self):
        return 'Foo'

def B():
    return 'Bar'

a = A()
b = B

print type(a), callable(a)
print type(b), callable(b)

You'll get <class 'A'> True and <type function> True as output.

isinstance works perfectly well to determine if something is a function (try isinstance(b, types.FunctionType)); if you're really interested in knowing if something can be called, you can either use hasattr(b, '__call__') or just try it.

test_as_func = True
try:
    b()
except TypeError:
    test_as_func = False
except:
    pass

This, of course, won't tell you whether it's callable but throws a TypeError when it executes, or isn't callable in the first place. That may not matter to you.

How to find files modified in last x minutes (find -mmin does not work as expected)

I am working through the same need and I believe your timeframe is incorrect.

Try these:

  • 15min change: find . -mtime -.01
  • 1hr change: find . -mtime -.04
  • 12 hr change: find . -mtime -.5

You should be using 24 hours as your base. The number after -mtime should be relative to 24 hours. Thus -.5 is the equivalent of 12 hours, because 12 hours is half of 24 hours.

How to determine CPU and memory consumption from inside a process?

For Linux You can also use /proc/self/statm to get a single line of numbers containing key process memory information which is a faster thing to process than going through a long list of reported information as you get from proc/self/status

See http://man7.org/linux/man-pages/man5/proc.5.html

   /proc/[pid]/statm
          Provides information about memory usage, measured in pages.
          The columns are:

              size       (1) total program size
                         (same as VmSize in /proc/[pid]/status)
              resident   (2) resident set size
                         (same as VmRSS in /proc/[pid]/status)
              shared     (3) number of resident shared pages (i.e., backed by a file)
                         (same as RssFile+RssShmem in /proc/[pid]/status)
              text       (4) text (code)
              lib        (5) library (unused since Linux 2.6; always 0)
              data       (6) data + stack
              dt         (7) dirty pages (unused since Linux 2.6; always 0)

Is it possible to set the equivalent of a src attribute of an img tag in CSS?

You can convert it with JS:

$('.image-class').each(function(){
    var processing = $(this).attr('src');
    $(this).parent().css({'background-image':'url('+processing+')'});
    $(this).hide();
});

How to find specific lines in a table using Selenium?

(.//*[table-locator])[n]

where n represents the specific line.

Apply function to each column in a data frame observing each columns existing data type

df <- head(mtcars)
df$string <- c("a","b", "c", "d","e", "f"); df

my.min <- unlist(lapply(df, min))
my.max <- unlist(lapply(df, max))

find -exec with multiple commands

I don't know if you can do this with find, but an alternate solution would be to create a shell script and to run this with find.

lastline.sh:

echo $(tail -1 $1),$1

Make the script executable

chmod +x lastline.sh

Use find:

find . -name "*.txt" -exec ./lastline.sh {} \;

jquery: $(window).scrollTop() but no $(window).scrollBottom()

try:

 $(window).scrollTop( $('body').height() );

Listing only directories using ls in Bash?

I partially solved it with:

cd "/path/to/pricipal/folder"

for i in $(ls -d .*/); do sudo ln -s "$PWD"/${i%%/} /home/inukaze/${i%%/}; done

 

    ln: «/home/inukaze/./.»: can't overwrite a directory
    ln: «/home/inukaze/../..»: can't overwrite a directory
    ln: accesing to «/home/inukaze/.config»: too much symbolics links levels
    ln: accesing to «/home/inukaze/.disruptive»: too much symbolics links levels
    ln: accesing to «/home/inukaze/innovations»: too much symbolics links levels
    ln: accesing to «/home/inukaze/sarl»: too much symbolics links levels
    ln: accesing to «/home/inukaze/.e_old»: too much symbolics links levels
    ln: accesing to «/home/inukaze/.gnome2_private»: too much symbolics links levels
    ln: accesing to «/home/inukaze/.gvfs»: too much symbolics links levels
    ln: accesing to «/home/inukaze/.kde»: too much symbolics links levels
    ln: accesing to «/home/inukaze/.local»: too much symbolics links levels
    ln: accesing to «/home/inukaze/.xVideoServiceThief»: too much symbolics links levels

Well, this reduce to me, the major part :)

Why does Git treat this text file as a binary file?

Git will even determine that it is binary if you have one super-long line in your text file. I broke up a long String, turning it into several source code lines, and suddenly the file went from being 'binary' to a text file that I could see (in SmartGit).

So don't keep typing too far to the right without hitting 'Enter' in your editor - otherwise later on Git will think you have created a binary file.

How to debug PDO database queries?

Here is a function I made to return a SQL query with "resolved" parameters.

function paramToString($query, $parameters) {
    if(!empty($parameters)) {
        foreach($parameters as $key => $value) {
            preg_match('/(\?(?!=))/i', $query, $match, PREG_OFFSET_CAPTURE);
            $query = substr_replace($query, $value, $match[0][1], 1);
        }
    }
    return $query;
    $query = "SELECT email FROM table WHERE id = ? AND username = ?";
    $values = [1, 'Super'];

    echo paramToString($query, $values);

Assuming you execute like this

$values = array(1, 'SomeUsername');
$smth->execute($values);

This function DOES NOT add quotes to queries but does the job for me.

Wrapping a react-router Link in an html button

For anyone looking for a solution using React 16.8+ (hooks) and React Router 5:

You can change the route using a button with the following code:

<button onClick={() => props.history.push("path")}>

React Router provides some props to your components, including the push() function on history which works pretty much like the < Link to='path' > element.

You don't need to wrap your components with the Higher Order Component "withRouter" to get access to those props.

How do I multiply each element in a list by a number?

I found it interesting to use list comprehension or map with just one object name x. Note that whenever x is reassigned, its id(x) changes, i.e. points to a different object.

x = [1, 2, 3]
id(x)
2707834975552
x = [1.5 * x for x in x]
id(x)
2707834976576
x
[1.5, 3.0, 4.5]
list(map(lambda x : 2 * x / 3, x))
[1.0, 2.0, 3.0]
id(x) # not reassigned
2707834976576
x = list(map(lambda x : 2 * x / 3, x))
x
[1.0, 2.0, 3.0]
id(x)
2707834980928

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use

Save code below as command.sql

USE restaurant
TRUNCATE `orders`;
TRUNCATE `order_items`;

Then run

mysql -u root <comands.sql> output.tab

Add a Progress Bar in WebView

in oncreate method where you have set your Webview.

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);

this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.web_view);

web_view = (WebView) findViewById(R.id.web_view);
pd = new ProgressDialog(SiteOpenInWebView.this);
    pd.setMessage("Please wait Loading...");
    pd.show();
    web_view.setWebViewClient(new MyWebViewClient());
    web_view.loadUrl("ur site name");
 }

WebViewClient

private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    view.loadUrl(url);

    if (!pd.isShowing()) {
        pd.show();
    }

    return true;
}

@Override
public void onPageFinished(WebView view, String url) {
    System.out.println("on finish");
    if (pd.isShowing()) {
        pd.dismiss();
    }

  }
}

Generate Row Serial Numbers in SQL Query

Sometime we might don't want to apply ordering on our result set to add serial number. But if we are going to use ROW_NUMBER() then we have to have a ORDER BY clause. So, for that we can simply apply a tricks to avoid any ordering on the result set.

SELECT ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS ItemNo, ItemName FROM ItemMastetr

For that we don't need to apply order by on our result set. We'll just add ItemNo on our given result set.

Generating combinations in c++

A simple way using std::next_permutation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
            }
        }
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;
}

or a slight variation that outputs the results in an easier to follow order:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
   int n, r;
   std::cin >> n;
   std::cin >> r;

   std::vector<bool> v(n);
   std::fill(v.begin(), v.begin() + r, true);

   do {
       for (int i = 0; i < n; ++i) {
           if (v[i]) {
               std::cout << (i + 1) << " ";
           }
       }
       std::cout << "\n";
   } while (std::prev_permutation(v.begin(), v.end()));
   return 0;
}

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v.


You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
{
    typedef vector<int> combination_t;

    // initialize status
   combinations(int N, int R) :
       completed(N < 1 || R > N),
       generated(0),
       N(N), R(R)
   {
       for (int c = 1; c <= R; ++c)
           curr.push_back(c);
   }

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

   // get current and compute next combination
   combination_t next()
   {
       combination_t ret = curr;

       // find what to increment
       completed = true;
       for (int i = R - 1; i >= 0; --i)
           if (curr[i] < N - R + i + 1)
           {
               int j = curr[i] + 1;
               while (i <= R-1)
                   curr[i++] = j++;
               completed = false;
               ++generated;
               break;
           }

       return ret;
   }

private:

   int N, R;
   combination_t curr;
};

int main(int argc, char **argv)
{
    int N = argc >= 2 ? atoi(argv[1]) : 5;
    int R = argc >= 3 ? atoi(argv[2]) : 2;
    combinations cs(N, R);
    while (!cs.completed)
    {
        combinations::combination_t c = cs.next();
        copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
        cout << endl;
    }
    return cs.generated;
}

test output:

1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,

How to position a CSS triangle using ::after?

Add a class:

.com_box:after {
     content: '';
    position: absolute;
    left: 18px;
    top: 50px;
    width: 0;
    height: 0;
    border-left: 20px solid transparent;
    border-right: 20px solid transparent;
    border-top: 20px solid #000;
    clear: both;

}

Updated your jsfiddle: http://jsfiddle.net/wrm4y8k6/8/

Undo a git stash

git stash list to list your stashed changes.

git stash show to see what n is in the below commands.

git stash apply to apply the most recent stash.

git stash apply stash@{n} to apply an older stash.

https://git-scm.com/book/en/v2/Git-Tools-Stashing-and-Cleaning

Can I assume (bool)true == (int)1 for any C++ compiler?

According to the standard, you should be safe with that assumption. The C++ bool type has two values - true and false with corresponding values 1 and 0.

The thing to watch about for is mixing bool expressions and variables with BOOL expression and variables. The latter is defined as FALSE = 0 and TRUE != FALSE, which quite often in practice means that any value different from 0 is considered TRUE.

A lot of modern compilers will actually issue a warning for any code that implicitly tries to cast from BOOL to bool if the BOOL value is different than 0 or 1.

Using margin:auto to vertically-align a div

Update Aug 2020

Although the below is still worth reading for the useful info, we have had Flexbox for some time now, so just use that, as per this answer.


You can't use:

vertical-align:middle because it's not applicable to block-level elements

margin-top:auto and margin-bottom:auto because their used values would compute as zero

margin-top:-50% because percentage-based margin values are calculated relative to the width of containing block

In fact, the nature of document flow and element height calculation algorithms make it impossible to use margins for centering an element vertically inside its parent. Whenever a vertical margin's value is changed, it will trigger a parent element height re-calculation (re-flow), which would in turn trigger a re-center of the original element... making it an infinite loop.

You can use:

A few workarounds like this which work for your scenario; the three elements have to be nested like so:

_x000D_
_x000D_
.container {
    display: table;
    height: 100%;
    position: absolute;
    overflow: hidden;
    width: 100%;
}
.helper {
    #position: absolute;
    #top: 50%;
    display: table-cell;
    vertical-align: middle;
}
.content {
    #position: relative;
    #top: -50%;
    margin: 0 auto;
    width: 200px;
    border: 1px solid orange;
}
_x000D_
<div class="container">
    <div class="helper">
        <div class="content">
            <p>stuff</p>
        </div>
    </div>
</div
_x000D_
_x000D_
_x000D_

JSFiddle works fine according to Browsershot.

How to detect iPhone 5 (widescreen devices)?

I've taken the liberty to put the macro by Macmade into a C function, and name it properly because it detects widescreen availability and NOT necessarily the iPhone 5.

The macro also doesn't detect running on an iPhone 5 in case where the project doesn't include the [email protected]. Without the new Default image, the iPhone 5 will report a regular 480x320 screen size (in points). So the check isn't just for widescreen availability but for widescreen mode being enabled as well.

BOOL isWidescreenEnabled()
{
    return (BOOL)(fabs((double)[UIScreen mainScreen].bounds.size.height - 
                                               (double)568) < DBL_EPSILON);
}

How do I call a specific Java method on a click/submit event of a specific button in JSP?

<form method="post" action="servletName">   
     <input type="submit" id="btn1" name="btn1"/>
     <input type="submit" id="btn2" name="btn2"/>
</form>  

on pressing it request will go to servlet on the servlet page check which button is pressed and then accordingly call the needed method as objectName.method

How to pause for specific amount of time? (Excel/VBA)

Add this to your module

Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Or, for 64-bit systems use:

Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)

Call it in your macro like so:

Sub Macro1()
'
' Macro1 Macro
'
Do
    Calculate
    Sleep (1000) ' delay 1 second

Loop
End Sub

Fastest way to copy a file in Node.js

Mike's solution, but with promises:

const FileSystem = require('fs');

exports.copyFile = function copyFile(source, target) {
    return new Promise((resolve,reject) => {
        const rd = FileSystem.createReadStream(source);
        rd.on('error', err => reject(err));
        const wr = FileSystem.createWriteStream(target);
        wr.on('error', err => reject(err));
        wr.on('close', () => resolve());
        rd.pipe(wr);
    });
};

How to output MySQL query results in CSV format?

This saved me a couple of times. Fast and it works!

--batch Print results using tab as the column separator, with each row on a new line.

--raw disables character escaping (\n, \t, \0, and \)

Example:

mysql -udemo_user -p -h127.0.0.1 --port=3306 \
   --default-character-set=utf8mb4 --database=demo_database \
   --batch --raw < /tmp/demo_sql_query.sql > /tmp/demo_csv_export.tsv

For completeness you could convert to csv (but be careful because tabs could be inside field values - e.g. text fields)

tr '\t' ',' < file.tsv > file.csv

How to perform runtime type checking in Dart?

The instanceof-operator is called is in Dart. The spec isn't exactly friendly to a casual reader, so the best description right now seems to be http://www.dartlang.org/articles/optional-types/.

Here's an example:

class Foo { }

main() {
  var foo = new Foo();
  if (foo is Foo) {
    print("it's a foo!");
  }
}

How to send a compressed archive that contains executables so that Google's attachment filter won't reject it

Try this:

tar -czf my.tar.gz dir/

But are you sure you are not compressing some .exe file or something? Maybe the problem is not with te compression, but with the files you are compressing?

Split string into individual words Java

Yet another method, using StringTokenizer :

String s = "I want to walk my dog";
StringTokenizer tokenizer = new StringTokenizer(s);

while(tokenizer.hasMoreTokens()) {
    System.out.println(tokenizer.nextToken());
}

MongoDB vs. Cassandra

I saw a presentation on mongodb yesterday. I can definitely say that setup was "simple", as simple as unpacking it and firing it up. Done.

I believe that both mongodb and cassandra will run on virtually any regular linux hardware so you should not find to much barrier in that area.

I think in this case, at the end of the day, it will come down to which do you personally feel more comfortable with and which has a toolset that you prefer. As far as the presentation on mongodb, the presenter indicated that the toolset for mongodb was pretty light and that there werent many (they said any really) tools similar to whats available for MySQL. This was of course their experience so YMMV. One thing that I did like about mongodb was that there seemed to be lots of language support for it (Python, and .NET being the two that I primarily use).

The list of sites using mongodb is pretty impressive, and I know that twitter just switched to using cassandra.

C++11 rvalues and move semantics confusion (return statement)

Not an answer per se, but a guideline. Most of the time there is not much sense in declaring local T&& variable (as you did with std::vector<int>&& rval_ref). You will still have to std::move() them to use in foo(T&&) type methods. There is also the problem that was already mentioned that when you try to return such rval_ref from function you will get the standard reference-to-destroyed-temporary-fiasco.

Most of the time I would go with following pattern:

// Declarations
A a(B&&, C&&);
B b();
C c();

auto ret = a(b(), c());

You don't hold any refs to returned temporary objects, thus you avoid (inexperienced) programmer's error who wish to use a moved object.

auto bRet = b();
auto cRet = c();
auto aRet = a(std::move(b), std::move(c));

// Either these just fail (assert/exception), or you won't get 
// your expected results due to their clean state.
bRet.foo();
cRet.bar();

Obviously there are (although rather rare) cases where a function truly returns a T&& which is a reference to a non-temporary object that you can move into your object.

Regarding RVO: these mechanisms generally work and compiler can nicely avoid copying, but in cases where the return path is not obvious (exceptions, if conditionals determining the named object you will return, and probably couple others) rrefs are your saviors (even if potentially more expensive).

Docker official registry (Docker Hub) URL

For those trying to create a Google Cloud instance using the "Deploy a container image to this VM instance." option then the correct url format would be

docker.io/<dockerimagename>:version

The suggestion above of registry.hub.docker.com/library/<dockerimagename> did not work for me.

I finally found the solution here (in my case, i was trying to run docker.io/tensorflow/serving:latest)

Verify ImageMagick installation

In Bash you can check if Imagick is an installed module:

$ php -m | grep imagick

If the response is blank it is not installed.

Why Maven uses JDK 1.6 but my java -version is 1.7

You can also explicitly tell maven which java version to compile for. You can try adding the maven-compiler-plugin to your pom.

<project>
  [...]
  <build>
    [...]
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
    [...]
  </build>
  [...]
</project>

If you imported a maven project into an IDE, then there is probably a maven setting in your IDE for default compiler that your maven runner is using.

How to check if android checkbox is checked within its onClick method (declared in XML)?

<CheckBox
      android:id="@+id/checkBox1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Fees Paid Rs100:"
      android:textColor="#276ca4"
      android:checked="false"
      android:onClick="checkbox_clicked" />

Main Activity from here

   public class RegistA extends Activity {
CheckBox fee_checkbox;
 @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_regist);
 fee_checkbox = (CheckBox)findViewById(R.id.checkBox1);// Fee Payment Check box
}

checkbox clicked

     public void checkbox_clicked(View v)
     {

         if(fee_checkbox.isChecked())
         {
            // true,do the task 

         }
         else
         {

         }

     }

SQL Server: Is it possible to insert into two tables at the same time?

Before being able to do a multitable insert in Oracle, you could use a trick involving an insert into a view that had an INSTEAD OF trigger defined on it to perform the inserts. Can this be done in SQL Server?

Iterate through 2 dimensional array

Consider it as an array of arrays and this will work for sure.

int mat[][] = { {10, 20, 30, 40, 50, 60, 70, 80, 90},
                {15, 25, 35, 45},
                {27, 29, 37, 48},
                {32, 33, 39, 50, 51, 89},
              };


    for(int i=0; i<mat.length; i++) {
        for(int j=0; j<mat[i].length; j++) {
            System.out.println("Values at arr["+i+"]["+j+"] is "+mat[i][j]);
        }
    }

Attach parameter to button.addTarget action in Swift

If you have a loop of buttons like me you can try something like this

var buttonTags:[Int:String]? // can be [Int:Any]
let myArray = [0:"a",1:"b"]
for (index,value) in myArray {

     let button = // Create a button

     buttonTags?[index] = myArray[index]
     button.tag = index
     button.addTarget(self, action: #selector(buttonAction(_:)), for: .touchDown)

}
@objc func buttonAction(_ sender:UIButton) {

    let myString = buttonTags[sender.tag]

}

Android Stop Emulator from Command Line

The other answer didn't work for me (on Windows 7). But this worked:

telnet localhost 5554
kill

jQuery: go to URL with target="_blank"

Use,

var url = $(this).attr('href');
window.open(url, '_blank');

Update:the href is better off being retrieved with prop since it will return the full url and it's slightly faster.

var url = $(this).prop('href');

What is the difference between 'java', 'javaw', and 'javaws'?

See Java tools documentation for:

  1. The java tool launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class's main method.
  2. The javaw command is identical to java, except that with javaw there is no associated console window. Use javaw when you don't want a command prompt window to appear.

The javaws command launches Java Web Start, which is the reference implementation of the Java Network Launching Protocol (JNLP). Java Web Start launches Java applications/applets hosted on a network.

If a JNLP file is specified, javaws will launch the Java application/applet specified in the JNLP file.

The javaws launcher has a set of options that are supported in the current release. However, the options may be removed in a future release.

See also JDK 9 Release Notes Deprecated APIs, Features, and Options:

Java Deployment Technologies are deprecated and will be removed in a future release
Java Applet and WebStart functionality, including the Applet API, the Java plug-in, the Java Applet Viewer, JNLP and Java Web Start, including the javaws tool, are all deprecated in JDK 9 and will be removed in a future release.

How to display a pdf in a modal window?

You can have a look at this library: https://github.com/mozilla/pdf.js it renders PDF document in a Web/HTML page

Also you can use Flash to embed the document into any HTML page like that:

<object data="your_file.pdf#view=Fit" type="application/pdf" width="100%" height="850">
    <p>
        It appears your Web browser is not configured to display PDF files. No worries, just <a href="your_file.pdf">click here to download the PDF file.</a>
    </p>
</object>

How to enable CORS on Firefox?

Do nothing to the browser. CORS is supported by default on all modern browsers (and since Firefox 3.5).

The server being accessed by JavaScript has to give the site hosting the HTML document in which the JS is running permission via CORS HTTP response headers.


security.fileuri.strict_origin_policy is used to give JS in local HTML documents access to your entire hard disk. Don't set it to false as it makes you vulnerable to attacks from downloaded HTML documents (including email attachments).

Difference between Select Unique and Select Distinct

Only In Oracle =>

SELECT DISTINCT and SELECT UNIQUE behave the same way. While DISTINCT is ANSI SQL standard, UNIQUE is an Oracle specific statement.

In other databases (like sql-server in your case) =>

SELECT UNIQUE is invalid syntax. UNIQUE is keyword for adding unique constraint on the column.

SELECT DISTINCT

How do I select the "last child" with a specific class name in CSS?

You can't target the last instance of the class name in your list without JS.

However, you may not be entirely out-of-css-luck, depending on what you are wanting to achieve. For example, by using the next sibling selector, I have added a visual divider after the last of your .list elements here: http://jsbin.com/vejixisudo/edit?html,css,output

SQL 'LIKE' query using '%' where the search criteria contains '%'

Escape the percent sign \% to make it part of your comparison value.

How to set minDate to current date in jQuery UI Datepicker?

Set minDate to current date in jQuery Datepicker :

$("input.DateFrom").datepicker({
    minDate: new Date()
});

Linux / Bash, using ps -o to get process by specific name?

ps -fC PROCESSNAME

ps and grep is a dangerous combination -- grep tries to match everything on each line (thus the all too common: grep -v grep hack). ps -C doesn't use grep, it uses the process table for an exact match. Thus, you'll get an accurate list with: ps -fC sh rather finding every process with sh somewhere on the line.

Postgres user does not exist?

I get exactly the same errors as kryshah with su - postgres and sudo -u postgres psql. DanielM's answer gives also errors.

Outputs when wrong settings

Answer however from przbabu's comment.

masi$ psql
psql: FATAL:  database "masi" does not exist
masi$ psql -U postgres
psql: FATAL:  role "postgres" does not exist
masi$ psql postgres
psql (9.4.1)
Type "help" for help.

I think the some part of this problem may be in owner settings in OSX

masi$ ls -al /Users/
total 0
drwxr-xr-x   7 root      admin  238 Jul  3 09:50 .
drwxr-xr-x  37 root      wheel 1326 Jul  2 19:02 ..
-rw-r--r--   1 root      wheel    0 Sep 10  2014 .localized
drwxrwxrwt   7 root      wheel  238 Apr  9 19:49 Shared
drwxr-xr-x   2 root      admin   68 Jul  3 09:50 postgres
drwxr-xr-x+ 71 masi      staff 2414 Jul  3 09:50 masi

but doing sudo chown -R postgres:staff /Users/postgres gives chown: invalid user: ‘postgres:staff’.

In short, this is not the solution the problem. Use the tools provided by the postgres installation to create a user and database.

To get right settings and outputs

There are specific commands after postgres installation to add a new user to the database system. After initdb, run the following as described here

createuser --pwprompt postgres
createdb -Opostgres -Eutf8 masi_development
psql -U postgres -W masi_development

To avoid the password request all the time, you have three choices as described here.

Moment Js UTC to Local Time

I've written this Codesandbox for a roundtrip from UTC to local time and from local time to UTC. You can change the timezone and the format. Enjoy!

Full Example on Codesandbox (DEMO):

https://codesandbox.io/s/momentjs-utc-to-local-roundtrip-foj57?file=/src/App.js

Reporting (free || open source) Alternatives to Crystal Reports in Winforms

If you are using Sql Server (any edition, even express) then you can install Sql Server Reporting Services. This allows the creation of reports through a visual studio plugin, or through a browser control and can export the reports in a variety of formats, including PDF. You can view the reports through the winforms report viewer control which is included, or take advantage of all of the built in generated web content.

The learning curve is not very steep at all if you are used to using datasets in Visual Studio.

Cast from VARCHAR to INT - MySQL

As described in Cast Functions and Operators:

The type for the result can be one of the following values:

  • BINARY[(N)]
  • CHAR[(N)]
  • DATE
  • DATETIME
  • DECIMAL[(M[,D])]
  • SIGNED [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]

Therefore, you should use:

SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT

Print JSON parsed object?

to Print JSON parsed object just type

console.log( JSON.stringify(data, null, " ") );

and you will get output very clear

Convert Object to JSON string

Also useful is Object.toSource() for debugging purposes, where you want to show the object and its properties for debugging purposes. This is a generic Javascript (not jQuery) function, however it only works in "modern" browsers.

How to hash a password

@csharptest.net's and Christian Gollhardt's answers are great, thank you very much. But after running this code on production with millions of record, I discovered there is a memory leak. RNGCryptoServiceProvider and Rfc2898DeriveBytes classes are derived from IDisposable but we don't dispose of them. I will write my solution as an answer if someone needs with disposed version.

public static class SecurePasswordHasher
{
    /// <summary>
    /// Size of salt.
    /// </summary>
    private const int SaltSize = 16;

    /// <summary>
    /// Size of hash.
    /// </summary>
    private const int HashSize = 20;

    /// <summary>
    /// Creates a hash from a password.
    /// </summary>
    /// <param name="password">The password.</param>
    /// <param name="iterations">Number of iterations.</param>
    /// <returns>The hash.</returns>
    public static string Hash(string password, int iterations)
    {
        // Create salt
        using (var rng = new RNGCryptoServiceProvider())
        {
            byte[] salt;
            rng.GetBytes(salt = new byte[SaltSize]);
            using (var pbkdf2 = new Rfc2898DeriveBytes(password, salt, iterations))
            {
                var hash = pbkdf2.GetBytes(HashSize);
                // Combine salt and hash
                var hashBytes = new byte[SaltSize + HashSize];
                Array.Copy(salt, 0, hashBytes, 0, SaltSize);
                Array.Copy(hash, 0, hashBytes, SaltSize, HashSize);
                // Convert to base64
                var base64Hash = Convert.ToBase64String(hashBytes);

                // Format hash with extra information
                return $"$HASH|V1${iterations}${base64Hash}";
            }
        }

    }

    /// <summary>
    /// Creates a hash from a password with 10000 iterations
    /// </summary>
    /// <param name="password">The password.</param>
    /// <returns>The hash.</returns>
    public static string Hash(string password)
    {
        return Hash(password, 10000);
    }

    /// <summary>
    /// Checks if hash is supported.
    /// </summary>
    /// <param name="hashString">The hash.</param>
    /// <returns>Is supported?</returns>
    public static bool IsHashSupported(string hashString)
    {
        return hashString.Contains("HASH|V1$");
    }

    /// <summary>
    /// Verifies a password against a hash.
    /// </summary>
    /// <param name="password">The password.</param>
    /// <param name="hashedPassword">The hash.</param>
    /// <returns>Could be verified?</returns>
    public static bool Verify(string password, string hashedPassword)
    {
        // Check hash
        if (!IsHashSupported(hashedPassword))
        {
            throw new NotSupportedException("The hashtype is not supported");
        }

        // Extract iteration and Base64 string
        var splittedHashString = hashedPassword.Replace("$HASH|V1$", "").Split('$');
        var iterations = int.Parse(splittedHashString[0]);
        var base64Hash = splittedHashString[1];

        // Get hash bytes
        var hashBytes = Convert.FromBase64String(base64Hash);

        // Get salt
        var salt = new byte[SaltSize];
        Array.Copy(hashBytes, 0, salt, 0, SaltSize);

        // Create hash with given salt
        using (var pbkdf2 = new Rfc2898DeriveBytes(password, salt, iterations))
        {
            byte[] hash = pbkdf2.GetBytes(HashSize);

            // Get result
            for (var i = 0; i < HashSize; i++)
            {
                if (hashBytes[i + SaltSize] != hash[i])
                {
                    return false;
                }
            }

            return true;
        }

    }
}

Usage:

// Hash
var hash = SecurePasswordHasher.Hash("mypassword");

// Verify
var result = SecurePasswordHasher.Verify("mypassword", hash);

conversion from infix to prefix

I saw this method on youtube hence posting here.

given infix expression : (a–b)/c*(d + e – f / g)

reverse it :

)g/f-e+d(*c/)b-a(

read characters from left to right.
maintain one stack for operators

 1. if character is operand add operand to the output
 2. else if character is operator or )
   2.1 while operator on top of the stack has lower or **equal** precedence than this character pop
   2.2 add the popped character to the output.
   push the character on stack

 3. else if character is parenthesis ( 
    3.1 [ same as 2 till you encounter ) . pop ) as well
 4. // no element left to read
   4.1 pop operators from stack till it is not empty
   4.2 add them to the output. 

reverse the output and print.

credits : youtube

set gvim font in .vimrc file

I use the following (Uses Consolas size 11 on Windows, Menlo Regular size 14 on Mac OS X and Inconsolata size 12 everywhere else):

if has("gui_running")
  if has("gui_gtk2")
    set guifont=Inconsolata\ 12
  elseif has("gui_macvim")
    set guifont=Menlo\ Regular:h14
  elseif has("gui_win32")
    set guifont=Consolas:h11:cANSI
  endif
endif

Edit: And while you're at it, you could take a look at Coding Horror's Programming Fonts blog post.

Edit²: Added MacVim.

Scheduling recurring task in Android

I have created on time task in which the task which user wants to repeat, add in the Custom TimeTask run() method. it is successfully reoccurring.

 import java.text.SimpleDateFormat;
 import java.util.Calendar;
 import java.util.Timer;
 import java.util.TimerTask;

 import android.os.Bundle;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.Button;
 import android.widget.CheckBox;
 import android.widget.TextView;
 import android.app.Activity;
 import android.content.Intent;

 public class MainActivity extends Activity {

     CheckBox optSingleShot;
     Button btnStart, btnCancel;
     TextView textCounter;

     Timer timer;
     MyTimerTask myTimerTask;

     int tobeShown = 0  ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    optSingleShot = (CheckBox)findViewById(R.id.singleshot);
    btnStart = (Button)findViewById(R.id.start);
    btnCancel = (Button)findViewById(R.id.cancel);
    textCounter = (TextView)findViewById(R.id.counter);
    tobeShown = 1;

    if(timer != null){
        timer.cancel();
    }

    //re-schedule timer here
    //otherwise, IllegalStateException of
    //"TimerTask is scheduled already" 
    //will be thrown
    timer = new Timer();
    myTimerTask = new MyTimerTask();

    if(optSingleShot.isChecked()){
        //singleshot delay 1000 ms
        timer.schedule(myTimerTask, 1000);
    }else{
        //delay 1000ms, repeat in 5000ms
        timer.schedule(myTimerTask, 1000, 1000);
    }

    btnStart.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View arg0) {


            Intent i = new Intent(MainActivity.this, ActivityB.class);
            startActivity(i);

            /*if(timer != null){
                timer.cancel();
            }

            //re-schedule timer here
            //otherwise, IllegalStateException of
            //"TimerTask is scheduled already" 
            //will be thrown
            timer = new Timer();
            myTimerTask = new MyTimerTask();

            if(optSingleShot.isChecked()){
                //singleshot delay 1000 ms
                timer.schedule(myTimerTask, 1000);
            }else{
                //delay 1000ms, repeat in 5000ms
                timer.schedule(myTimerTask, 1000, 1000);
            }*/
        }});

    btnCancel.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {
            if (timer!=null){
                timer.cancel();
                timer = null;
            }
        }
    });

}

@Override
protected void onResume() {
    super.onResume();

    if(timer != null){
        timer.cancel();
    }

    //re-schedule timer here
    //otherwise, IllegalStateException of
    //"TimerTask is scheduled already" 
    //will be thrown
    timer = new Timer();
    myTimerTask = new MyTimerTask();

    if(optSingleShot.isChecked()){
        //singleshot delay 1000 ms
        timer.schedule(myTimerTask, 1000);
    }else{
        //delay 1000ms, repeat in 5000ms
        timer.schedule(myTimerTask, 1000, 1000);
    }
}


@Override
protected void onPause() {
    super.onPause();

    if (timer!=null){
        timer.cancel();
        timer = null;
    }

}

@Override
protected void onStop() {
    super.onStop();

    if (timer!=null){
        timer.cancel();
        timer = null;
    }

}

class MyTimerTask extends TimerTask {

    @Override
    public void run() {

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat simpleDateFormat = 
                new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
        final String strDate = simpleDateFormat.format(calendar.getTime());

        runOnUiThread(new Runnable(){

            @Override
            public void run() {
                textCounter.setText(strDate);
            }});
    }
}

}

How do I find out which keystore was used to sign an app?

First, unzip the APK and extract the file /META-INF/ANDROID_.RSA (this file may also be CERT.RSA, but there should only be one .RSA file).

Then issue this command:

keytool -printcert -file ANDROID_.RSA

You will get certificate fingerprints like this:

     MD5:  B3:4F:BE:07:AA:78:24:DC:CA:92:36:FF:AE:8C:17:DB
     SHA1: 16:59:E7:E3:0C:AA:7A:0D:F2:0D:05:20:12:A8:85:0B:32:C5:4F:68
     Signature algorithm name: SHA1withRSA

Then use the keytool again to print out all the aliases of your signing keystore:

keytool -list -keystore my-signing-key.keystore

You will get a list of aliases and their certificate fingerprint:

android_key, Jan 23, 2010, PrivateKeyEntry,
Certificate fingerprint (MD5): B3:4F:BE:07:AA:78:24:DC:CA:92:36:FF:AE:8C:17:DB

Voila! we can now determined the apk has been signed with this keystore, and with the alias 'android_key'.

Keytool is part of Java, so make sure your PATH has Java installation dir in it.

Count items in a folder with PowerShell

You should use Measure-Object to count things. In this case it would look like:

Write-Host ( Get-ChildItem c:\MyFolder | Measure-Object ).Count;

or if that's too long

Write-Host ( dir c:\MyFolder | mo).Count;

and in PowerShell 4.0 use the measure alias instead of mo

Write-Host (dir c:\MyFolder | measure).Count;

How to get city name from latitude and longitude coordinates in Google Maps?

 private class MatchingNearByLocationTask extends
        AsyncTask<Void, Void, Void> 
 {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog

        progressDialog = new ProgressDialog(mContext);
        progressDialog.setMessage("Loading...");
        progressDialog.setCancelable(true);
        progressDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {

        jsonStr = getLocationInfo(Latitude, Longitude).toString();
        if (jsonStr != null) {
            Log.i("location--??", jsonStr);

            JSONObject jsonObj;
            try {
                jsonObj = new JSONObject(jsonStr);

                String Status = jsonObj.getString("status");
                if (Status.equalsIgnoreCase("OK")) {
                    JSONArray Results = jsonObj.getJSONArray("results");
                    JSONObject zero = Results.getJSONObject(0);
                    JSONArray address_components = zero
                            .getJSONArray("address_components");

                    for (int i = 0; i < address_components.length(); i++) {
                        JSONObject zero2 = address_components
                                .getJSONObject(i);
                        String long_name = zero2.getString("long_name");
                        JSONArray mtypes = zero2.getJSONArray("types");
                        String Type = mtypes.getString(0);
                        if (Type.equalsIgnoreCase("administrative_area_level_2")) {
                            // Address2 = Address2 + long_name + ", ";
                            String City = long_name;
                            Log.d(" CityName --->", City + "");
                        }
                    }
                }

            }

            catch (JSONException e) {

                e.printStackTrace();
            }

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

    }

    @Override
    protected void onCancelled() {

        super.onCancelled();
        progressDialog.dismiss();

    }

}




private JSONObject getLocationInfo(double lat, double lng) {

    HttpGet httpGet = new HttpGet(
            "http://maps.googleapis.com/maps/api/geocode/json?latlng="
                    + lat + "," + lng + "&sensor=false");
    HttpClient client = new DefaultHttpClient();
    HttpResponse response;
    StringBuilder stringBuilder = new StringBuilder();

    try {
        response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) {
            stringBuilder.append((char) b);
        }
    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }

    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject = new JSONObject(stringBuilder.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return jsonObject;
}

The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel

If you are using a Route::group, with a vendor plugin like LaravelLocalization (from MCAMARA), you need to put POST routes outside of this group. I've experienced problems with POST routes using this plugin and I did solved right now by putting these routes outside Route::group..

How to select the first element in the dropdown using jquery?

    var arr_select_val=[];

    $("select").each(function() { 
        var name=this.name;
            arr_select_val[name]=$('select option:first-child').val();
    });


// Process the array object
     $('.orders_status_summary_div').print(arr_select_val);

Reading images in python

Easy way

from IPython.display import Image

Image(filename ="Covid.jpg" size )

How to read a string one letter at a time in python

Create a lookup table first:

morse = [None] * (ord('z') - ord('a') + 1)
for line in moreCodeFile:
    morse[ord(line[0].lower()) - ord('a')] = line[2:]

Then convert using the table:

for ch in userInput:
    print morse[ord(ch.lower()) - ord('a')]

Print array to a file

just use file_put_contents('file',$myarray); file_put_contents() works with arrays too.