Programs & Examples On #Msmqintegrationbinding

Node.js setting up environment specific configs to be used with everyauth

This answer is not something new. It's similar to what @andy_t has mentioned. But I use the below pattern for two reasons.

  1. Clean implementation with No external npm dependencies

  2. Merge the default config settings with the environment based settings.

Javascript implementation

const settings = {
    _default: {
       timeout: 100
       baseUrl: "http://some.api/",
    },
    production: {
       baseUrl: "http://some.prod.api/",
    },
}
// If you are not using ECMAScript 2018 Standard
// https://stackoverflow.com/a/171256/1251350
module.exports = { ...settings._default, ...settings[process.env.NODE_ENV] }

I usually use typescript in my node project. Below is my actual implementation copy-pasted.

Typescript implementation

const settings: { default: ISettings, production: any } = {
    _default: {
        timeout: 100,
        baseUrl: "",
    },
    production: {
        baseUrl: "",
    },
}

export interface ISettings {
    baseUrl: string
}

export const config = ({ ...settings._default, ...settings[process.env.NODE_ENV] } as ISettings)

CSS Inset Borders

You may use background-clip: border-box;

Example:

.example {
padding: 2em;
border: 10px solid rgba(51,153,0,0.65);
background-clip: border-box;
background-color: yellow;
}

<div class="example">Example with background-clip: border-box;</div>

Permutations in JavaScript?

The following function permutates an array of any type and calls a specified callback function on each permutation found:

/*
  Permutate the elements in the specified array by swapping them
  in-place and calling the specified callback function on the array
  for each permutation.

  Return the number of permutations.

  If array is undefined, null or empty, return 0.

  NOTE: when permutation succeeds, the array should be in the original state
  on exit!
*/
  function permutate(array, callback) {
    // Do the actual permuation work on array[], starting at index
    function p(array, index, callback) {
      // Swap elements i1 and i2 in array a[]
      function swap(a, i1, i2) {
        var t = a[i1];
        a[i1] = a[i2];
        a[i2] = t;
      }

      if (index == array.length - 1) {
        callback(array);
        return 1;
      } else {
        var count = p(array, index + 1, callback);
        for (var i = index + 1; i < array.length; i++) {
          swap(array, i, index);
          count += p(array, index + 1, callback);
          swap(array, i, index);
        }
        return count;
      }
    }

    if (!array || array.length == 0) {
      return 0;
    }
    return p(array, 0, callback);
  }

If you call it like this:

  // Empty array to hold results
  var result = [];
  // Permutate [1, 2, 3], pushing every permutation onto result[]
  permutate([1, 2, 3], function (a) {
    // Create a copy of a[] and add that to result[]
    result.push(a.slice(0));
  });
  // Show result[]
  document.write(result);

I think it will do exactly what you need - fill an array called result with the permutations of the array [1, 2, 3]. The result is:

[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,2,1],[3,1,2]]

Slightly clearer code on JSFiddle: http://jsfiddle.net/MgmMg/6/

Algorithm/Data Structure Design Interview Questions

I enjoy the classic "what's the difference between a LinkedList and an ArrayList (or between a linked list and an array/vector) and why would you choose one or the other?"

The kind of answer I hope for is one that includes discussion of:

  • insertion performance
  • iteration performance
  • memory allocation/reallocation impact
  • impact of removing elements from the beginning/middle/end
  • how knowing (or not knowing) the maximum size of the list can affect the decision

Handling JSON Post Request in Go

I found the following example from the docs really helpful (source here).

package main

import (
    "encoding/json"
    "fmt"
    "io"
    "log"
    "strings"
)

func main() {
    const jsonStream = `
        {"Name": "Ed", "Text": "Knock knock."}
        {"Name": "Sam", "Text": "Who's there?"}
        {"Name": "Ed", "Text": "Go fmt."}
        {"Name": "Sam", "Text": "Go fmt who?"}
        {"Name": "Ed", "Text": "Go fmt yourself!"}
    `
    type Message struct {
        Name, Text string
    }
    dec := json.NewDecoder(strings.NewReader(jsonStream))
    for {
        var m Message
        if err := dec.Decode(&m); err == io.EOF {
            break
        } else if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%s: %s\n", m.Name, m.Text)
    }
}

The key here being that the OP was looking to decode

type test_struct struct {
    Test string
}

...in which case we would drop the const jsonStream, and replace the Message struct with the test_struct:

func test(rw http.ResponseWriter, req *http.Request) {
    dec := json.NewDecoder(req.Body)
    for {
        var t test_struct
        if err := dec.Decode(&t); err == io.EOF {
            break
        } else if err != nil {
            log.Fatal(err)
        }
        log.Printf("%s\n", t.Test)
    }
}

Update: I would also add that this post provides some great data about responding with JSON as well. The author explains struct tags, which I was not aware of.

Since JSON does not normally look like {"Test": "test", "SomeKey": "SomeVal"}, but rather {"test": "test", "somekey": "some value"}, you can restructure your struct like this:

type test_struct struct {
    Test string `json:"test"`
    SomeKey string `json:"some-key"`
}

...and now your handler will parse JSON using "some-key" as opposed to "SomeKey" (which you will be using internally).

jQuery '.each' and attaching '.click' event

No need to use .each. click already binds to all div occurrences.

$('div').click(function(e) {
    ..    
});

See Demo

Note: use hard binding such as .click to make sure dynamically loaded elements don't get bound.

Connecting PostgreSQL 9.2.1 with Hibernate

This is a hibernate.cfg.xml for posgresql and it will help you with basic hibernate configurations for posgresql.

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.username">postgres</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/hibernatedb</property>



        <property name="connection_pool_size">1</property>

        <property name="hbm2ddl.auto">create</property>

        <property name="show_sql">true</property>



       <mapping class="org.javabrains.sanjaya.dto.UserDetails"/>

    </session-factory>
</hibernate-configuration>

How to execute a query in ms-access in VBA code?

How about something like this...

Dim rs As RecordSet
Set rs = Currentdb.OpenRecordSet("SELECT PictureLocation, ID FROM MyAccessTable;")

Do While Not rs.EOF
   Debug.Print rs("PictureLocation") & " - " & rs("ID")
   rs.MoveNext
Loop

Java JDBC connection status

Your best chance is to just perform a simple query against one table, e.g.:

select 1 from SOME_TABLE;

Oh, I just saw there is a new method available since 1.6:

java.sql.Connection.isValid(int timeoutSeconds):

Returns true if the connection has not been closed and is still valid. The driver shall submit a query on the connection or use some other mechanism that positively verifies the connection is still valid when this method is called. The query submitted by the driver to validate the connection shall be executed in the context of the current transaction.

jQuery if Element has an ID?

You can using the following code:

   if($(".parent a").attr('id')){

      //do something
   }


   $(".parent a").each(function(i,e){
       if($(e).attr('id')){
          //do something and check
          //if you want to break the each
          //return false;
       }
   });

The same question is you can find here: how to check if div has id or not?

How to analyze information from a Java core dump?

IBM provide a number of tools which can be used on the sun jvm as well. Take a look at some of the projects on alphaworks, they provide a heap and thread dump analyzers

Karl

In WPF, what are the differences between the x:Name and Name attributes?

The specified x:Name becomes the name of a field that is created in the underlying code when XAML is processed, and that field holds a reference to the object. In Silverlight, using the managed API, the process of creating this field is performed by the MSBuild target steps, which also are responsible for joining the partial classes for a XAML file and its code-behind. This behavior is not necessarily XAML-language specified; it is the particular implementation that Silverlight applies to use x:Name in its programming and application models.

Read More on MSDN...

SaveFileDialog setting default path and file type?

Environment.GetSystemVariable("%SystemDrive%"); will provide the drive OS installed, and you can set filters to savedialog Obtain file path of C# save dialog box

Javascript to stop HTML5 video playback on modal window close

Try this:

$(document).ready(function(){
    $("#showSimpleModal").click(function() {
        $("div#simpleModal").addClass("show");
        $("#videoContainer")[0].play();
        return false;   
    });

    $("#closeSimple").click(function() {
        $("div#simpleModal").removeClass("show");
        $("#videoContainer")[0].pause();
        return false;                   
    });
});

Check if an object exists

Since filter returns a QuerySet, you can use count to check how many results were returned. This is assuming you don't actually need the results.

num_results = User.objects.filter(email = cleaned_info['username']).count()

After looking at the documentation though, it's better to just call len on your filter if you are planning on using the results later, as you'll only be making one sql query:

A count() call performs a SELECT COUNT(*) behind the scenes, so you should always use count() rather than loading all of the record into Python objects and calling len() on the result (unless you need to load the objects into memory anyway, in which case len() will be faster).

num_results = len(user_object)

How to open Visual Studio Code from the command line on OSX?

If you are using VS Code Insiders:

code-insiders .

If you are using VS Code:

code .

Submit form using <a> tag

Here is how I would do it using vanilla JS

<form id="myform" method="POST" action="xxx">
    <!-- your stuff here -->
    <a href="javascript:void()" onclick="document.getElementById('myform').submit();>Ponies await!</a>
</form>

You can play with the return falses and href="#" vs void and whatever you need to but this method worked for me in Chrome 18, IE 9 and Firefox 14 and the rest depends on your javascript mostly.

Installing Git on Eclipse

I made an installation guide for Egit on Eclipse so I thought I would share it.

  1. INSTALL EGIT plugin in eclispe which is pretty easy. If EGit is missing in your Eclipse installation, you can install it via the Eclipse Update Manager via: Help ? Install new Software. EGit can be installed from the following URL: http://download.eclipse.org/egit/updates Under Eclipse Git Team Provider, tick ONLY "Eclipse EGit" and then download the plugin.

  2. CONNECT TO YOUR LOCAL REPOSITORY. I right clicked on the project, selected "team > share project" and then ticked "use or create repository"

  3. GIT IGNORE. Mark the "bin" folder as "ignored by Git", either by right-clicking on it and selecting Team > Ignore or by creating a .gitignore file. My file was generated for me, I just had to make it visible. Here's how in eclipse: In your package explorer, pull down the menu and select "Filters ...". You can adjust what types of files are shown/hidden there.

  4. IDENTIFY YOURSELF. Click Preferences > Team > Git > Configuration and make sure your name & email are there so we know which user committed/pushed what.

NOW YOU ARE READY TO ADD/COMMIT/PUSH/PULL files with the plugin!

How to sum all the values in a dictionary?

phihag's answer (and similar ones) won't work in python3.

For python 3:

d = {'key1': 1,'key2': 14,'key3': 47}
sum(list(d.values()))

Update! There are complains that it doesn't work! I just attach a screenshot from my terminal. Could be some mismatch in versions etc.

enter image description here

How to specify legend position in matplotlib in graph coordinates

You can change location of legend using loc argument. https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend

import matplotlib.pyplot as plt

plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
           ncol=2, mode="expand", borderaxespad=0.)

plt.subplot(223)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend to the right of this smaller subplot.
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

plt.show()

Get pandas.read_csv to read empty values as empty string instead of nan

I added a ticket to add an option of some sort here:

https://github.com/pydata/pandas/issues/1450

In the meantime, result.fillna('') should do what you want

EDIT: in the development version (to be 0.8.0 final) if you specify an empty list of na_values, empty strings will stay empty strings in the result

Bootstrap 4 Center Vertical and Horizontal Alignment

None has worked for me. But his one did.

Since the Bootstrap 4 .row class is now display:flex you can simply use the new align-self-center flexbox utility on any column to vertically center it:

<div class="row">
   <div class="col-6 align-self-center">
      <div class="card card-block">
      Center
      </div>
   </div>
   <div class="col-6">
      <div class="card card-inverse card-danger">
      Taller
      </div>
   </div>
</div>

I learned about it from https://medium.com/wdstack/bootstrap-4-vertical-center-1211448a2eff

Generate random array of floats between a range

This is the simplest way

np.random.uniform(start,stop,(rows,columns))

Fatal error: Call to undefined function: ldap_connect()

Open the XAMMP php.ini file (the default path is C:\xammp\php\php.ini) and change the code (;extension=ldap) to extension=php_ldap.dll and save. Restart XAMMP and save.

php.ini

; Notes for Windows environments :
;
; - Many DLL files are located in the extensions/ (PHP 4) or ext/ (PHP 5+)
;   extension folders as well as the separate PECL DLL download (PHP 5+).
;   Be sure to appropriately set the extension_dir directive.
;
extension=bz2
extension=curl
extension=fileinfo
extension=gd2
extension=gettext
;extension=gmp
;extension=intl
;extension=imap
;extension=interbase
extension=php_ldap.dll

Make code in LaTeX look *nice*

For simple document, I sometimes use verbatim, but listing is nice for big chunk of code.

How to stop (and restart) the Rails Server?

On OSX, you can take advantage of the UNIX-like command line - here's what I keep handy in my .bashrc to enable me to more easily restart a server that's running in background (-d) mode (note that you have to be in the Rails root directory when running this):

alias restart_rails='kill -9 `cat tmp/pids/server.pid`; rails server -d'

My initial response to the comment by @zane about how the PID file isn't removed was that it might be behavior dependent on the Rails version or OS type. However, it's also possible that the shell runs the second command (rails server -d) sooner than the kill can actually cause the previous running instance to stop.

So alternatively, kill -9 cat tmp/pids/server.pid && rails server -d might be more robust; or you can specifically run the kill, wait for the tmp/pids folder to empty out, then restart your new server.

Completely Remove MySQL Ubuntu 14.04 LTS

remove mysql :

sudo apt -y purge mysql*
sudo apt -y autoremove
sudo rm -rf /etc/mysql
sudo rm -rf /var/lib/mysql*

Restart instance :

sudo shutdown -r now

How to query the permissions on an Oracle directory?

This should give you the roles, users and permissions granted on a directory:

SELECT * 
  FROM all_tab_privs 
 WHERE table_name = 'your_directory';  --> needs to be upper case

And yes, it IS in the all_TAB_privs view ;-) A better name for that view would be something like "ALL_OBJECT_PRIVS", since it also includes PL/SQL objects and their execute permissions as well.

How to get the full URL of a Drupal page?

The following is more Drupal-ish:

url(current_path(), array('absolute' => true)); 

System not declared in scope?

You need to add:

 #include <cstdlib>

in order for the compiler to see the prototype for system().

Generate a random number in the range 1 - 10

(trunc(random() * 10) % 10) + 1

Entity framework self referencing loop detected

I might also look into adding explicit samples for each controller/action, as well covered here:

http://blogs.msdn.com/b/yaohuang1/archive/2012/10/13/asp-net-web-api-help-page-part-2-providing-custom-samples-on-the-help-page.aspx

i.e. config.SetActualResponseType(typeof(SomeType), "Values", "Get");

Filter spark DataFrame on string contains

In pyspark,SparkSql syntax:

where column_n like 'xyz%'

might not work.

Use:

where column_n RLIKE '^xyz' 

This works perfectly fine.

Find substring in the string in TWIG

Just searched for the docs, and found this:

Containment Operator: The in operator performs containment test. It returns true if the left operand is contained in the right:

{# returns true #}

{{ 1 in [1, 2, 3] }}

{{ 'cd' in 'abcde' }}

How do I REALLY reset the Visual Studio window layout?

Have you tried this? In Visual Studio go to Tools > Import and Export Settings > Reset all settings

Be sure you back up your settings before you do this. I made the mistake of trying this to fix an issue and didn't realize it would undo all my appearance settings and toolbars as well. Took a lot of time to get back to the way I like things.

Have a variable in images path in Sass?

We can use relative path instead of absolute path:

$assetPath: '~src/assets/images/';
$logo-img: '#{$assetPath}logo.png';
@mixin logo {
  background-image: url(#{$logo-img});
}

.logo {
    max-width: 65px;
    @include logo;
 }

In javascript, how do you search an array for a substring match

The simplest vanilla javascript code to achieve this is

var windowArray = ["item", "thing", "id-3-text", "class", "3-id-text"];
var textToFind = "id-";

//if you only want to match id- as prefix 
var matches = windowArray.filter(function(windowValue){
  if(windowValue) {
      return (windowValue.substring(0, textToFind.length) === textToFind);
  }
}); //["id-3-text"]

//if you want to match id- string exists at any position
var matches = windowArray.filter(function(windowValue){
  if(windowValue) {
      return windowValue.indexOf(textToFind) >= 0;
  }
}); //["id-3-text", "3-id-text"]

window.open target _self v window.location.href?

As others have said, the second approach is usually preferred.

The two code snippets are not exactly equivalent however: the first one actually sets window.opener to the window object itself, whereas the second will leave it as it is, at least under Firefox.

Converting String array to java.util.List

The Simplest approach:

String[] stringArray = {"Hey", "Hi", "Hello"};

List<String> list = Arrays.asList(stringArray);

How to set the id attribute of a HTML element dynamically with angularjs (1.x)?

A more elegant way I found to achieve this behaviour is simply:

<div id="{{ 'object-' + myScopeObject.index }}"></div>

For my implementation I wanted each input element in a ng-repeat to each have a unique id to associate the label with. So for an array of objects contained inside myScopeObjects one could do this:

<div ng-repeat="object in myScopeObject">
    <input id="{{object.name + 'Checkbox'}}" type="checkbox">
    <label for="{{object.name + 'Checkbox'}}">{{object.name}}</label>
</div>

Being able to generate unique ids on the fly can be pretty useful when dynamically adding content like this.

cordova run with ios error .. Error code 65 for command: xcodebuild with args:

I was getting the same error when I tried to do :

cordova build ios

except mine said ** ARCHIVE FAILED ** rather than ** BUILD FAILED **.

I fixed it by opening the projectName.xcodeproj file in Xcode and then adjusting these 2 settings :

  1. In Targets > General > Signing ensure you have selected a Team

enter image description here

  1. In Targets > Build Settings > (search for "bitcode") set Enable Bitcode to "Yes"

enter image description here

Then I quit out of Xcode and reran cordova build ios and it worked.

Ruby: How to convert a string to boolean

I have a little hack for this one. JSON.parse('false') will return false and JSON.parse('true') will return true. But this doesn't work with JSON.parse(true || false). So, if you use something like JSON.parse(your_value.to_s) it should achieve your goal in a simple but hacky way.

How to find path of active app.config file?

I tried one of the previous answers in a web app (actually an Azure web role running locally) and it didn't quite work. However, this similar approach did work:

var map = new ExeConfigurationFileMap { ExeConfigFilename = "MyComponent.dll.config" };
var path = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None).FilePath;

The config file turned out to be in C:\Program Files\IIS Express\MyComponent.dll.config. Interesting place for it.

How do I debug Windows services in Visual Studio?

Try Visual Studio's very own post-build event command line.

Try to add this in post-build:

@echo off
sc query "ServiceName" > nul
if errorlevel 1060 goto install
goto stop

:delete
echo delete
sc delete "ServiceName" > nul
echo %errorlevel%
goto install

:install
echo install
sc create "ServiceName" displayname= "Service Display Name" binpath= "$(TargetPath)" start= auto > nul
echo %errorlevel%
goto start

:start
echo start
sc start "ServiceName" > nul
echo %errorlevel%
goto end

:stop
echo stop
sc stop "ServiceName" > nul
echo %errorlevel%
goto delete

:end

If the build error with a message like Error 1 The command "@echo off sc query "ServiceName" > nul so on, Ctrl + C then Ctrl + V the error message into Notepad and look at the last sentence of the message.

It could be saying exited with code x. Look for the code in some common error here and see how to resolve it.

1072 -- Marked for deletion ? Close all applications that maybe using the service including services.msc and Windows event log.
1058 -- Can't be started because disabled or has no enabled associated devices ? just delete it.
1060 -- Doesn't exist ? just delete it.
1062 -- Has not been started ? just delete it.
1053 -- Didn't respond to start or control ? see event log (if logged to event log). It may be the service itself throwing an exception.
1056 -- Service is already running ? stop the service, and then delete.

More on error codes here.

And if the build error with message like this,

Error    11    Could not copy "obj\x86\Debug\ServiceName.exe" to "bin\Debug\ServiceName.exe". Exceeded retry count of 10. Failed.    ServiceName
Error    12    Unable to copy file "obj\x86\Debug\ServiceName.exe" to "bin\Debug\ServiceName.exe". The process cannot access the file 'bin\Debug\ServiceName.exe' because it is being used by another process.    ServiceName

open cmd, and then try to kill it first with taskkill /fi "services eq ServiceName" /f

If all is well, F5 should be sufficient to debug it.

Python Math - TypeError: 'NoneType' object is not subscriptable

lista = list.sort(lista)

This should be

lista.sort()

The .sort() method is in-place, and returns None. If you want something not in-place, which returns a value, you could use

sorted_list = sorted(lista)

Aside #1: please don't call your lists list. That clobbers the builtin list type.

Aside #2: I'm not sure what this line is meant to do:

print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")

is it simply

print "value 1a + value 2 = value 3a value 4"

? In other words, I don't know why you're calling str on things which are already str.

Aside #3: sometimes you use print("something") (Python 3 syntax) and sometimes you use print "something" (Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..


The exception TypeError: 'NoneType' object is not subscriptable happens because the value of lista is actually None. You can reproduce TypeError that you get in your code if you try this at the Python command line:

None[0]

The reason that lista gets set to None is because the return value of list.sort() is None... it does not return a sorted copy of the original list. Instead, as the documentation points out, the list gets sorted in-place instead of a copy being made (this is for efficiency reasons).

If you do not want to alter the original version you can use

other_list = sorted(lista)

Rename multiple files in cmd

@echo off
for %%f in (*.txt) do (
    ren "%%~nf%%~xf" "%%~nf 1.1%%~xf"
)

Adding input elements dynamically to form

You could use an onclick event handler in order to get the input value for the text field. Make sure you give the field an unique id attribute so you can refer to it safely through document.getElementById():

If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">. Create new elements by means of document.createElement(), and use appendChild() to append each of them to the container. You might be interested in outputting a meaningful name attribute (e.g. name="member"+i for each of the dynamically generated <input>s if they are to be submitted in a form.

Notice you could also create <br/> elements with document.createElement('br'). If you want to just output some text, you can use document.createTextNode() instead.

Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes() and removeChild() together.

_x000D_
_x000D_
<html>
<head>
    <script type='text/javascript'>
        function addFields(){
            // Number of inputs to create
            var number = document.getElementById("member").value;
            // Container <div> where dynamic content will be placed
            var container = document.getElementById("container");
            // Clear previous contents of the container
            while (container.hasChildNodes()) {
                container.removeChild(container.lastChild);
            }
            for (i=0;i<number;i++){
                // Append a node with a random text
                container.appendChild(document.createTextNode("Member " + (i+1)));
                // Create an <input> element, set its type and name attributes
                var input = document.createElement("input");
                input.type = "text";
                input.name = "member" + i;
                container.appendChild(input);
                // Append a line break 
                container.appendChild(document.createElement("br"));
            }
        }
    </script>
</head>
<body>
    <input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
    <a href="#" id="filldetails" onclick="addFields()">Fill Details</a>
    <div id="container"/>
</body>
</html>
_x000D_
_x000D_
_x000D_

See a working sample in this JSFiddle.

Is right click a Javascript event?

You could use the event window.oncontextmenu, for example:

_x000D_
_x000D_
window.oncontextmenu = function () {_x000D_
  alert('Right Click')_x000D_
}
_x000D_
<h1>Please Right Click here!</h1>
_x000D_
_x000D_
_x000D_

Round integers to the nearest 10

This function will round either be order of magnitude (right to left) or by digits the same way that format treats floating point decimal places (left to right:

def intround(n, p):
    ''' rounds an intger. if "p"<0, p is a exponent of 10; if p>0, left to right digits '''
    if p==0: return n
    if p>0:  
        ln=len(str(n))  
        p=p-ln+1 if n<0 else p-ln
    return (n + 5 * 10**(-p-1)) // 10**-p * 10**-p

>>> tgt=5555555
>>> d=2
>>> print('\t{} rounded to {} places:\n\t{} right to left \n\t{} left to right'.format(
        tgt,d,intround(tgt,-d), intround(tgt,d))) 

Prints

5555555 rounded to 2 places:
5555600 right to left 
5600000 left to right

You can also use Decimal class:

import decimal
import sys

def ri(i, prec=6):
    ic=long if sys.version_info.major<3 else int
    with decimal.localcontext() as lct:
        if prec>0:
            lct.prec=prec
        else:
            lct.prec=len(str(decimal.Decimal(i)))+prec  
        n=ic(decimal.Decimal(i)+decimal.Decimal('0'))
    return n

On Python 3 you can reliably use round with negative places and get a rounded integer:

def intround2(n, p):
    ''' will fail with larger floating point numbers on Py2 and require a cast to an int '''
    if p>0:
        return round(n, p-len(str(n))+1)
    else:
        return round(n, p)    

On Python 2, round will fail to return a proper rounder integer on larger numbers because round always returns a float:

>>> round(2**34, -5)
17179900000.0                     # OK
>>> round(2**64, -5)
1.84467440737096e+19              # wrong 

The other 2 functions work on Python 2 and 3

C# find highest array value and index

If you know max index accessing the max value is immediate. So all you need is max index.

int max=0;

for(int i = 1; i < arr.Length; i++)
    if (arr[i] > arr[max]) max = i;

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

In the web development world, the term "redirect" is the act of sending the client an empty HTTP response with just a Location header containing the new URL to which the client has to send a brand new GET request. So basically:

  • Client sends a HTTP request to some.jsp.
  • Server sends a HTTP response back with Location: other.jsp header
  • Client sends a HTTP request to other.jsp (this get reflected in browser address bar!)
  • Server sends a HTTP response back with content of other.jsp.

You can track it with the web browser's builtin/addon developer toolset. Press F12 in Chrome/IE9/Firebug and check the "Network" section to see it.

Exactly the above is achieved by sendRedirect("other.jsp"). The RequestDispatcher#forward() doesn't send a redirect. Instead, it uses the content of the target page as HTTP response.

  • Client sends a HTTP request to some.jsp.
  • Server sends a HTTP response back with content of other.jsp.

However, as the original HTTP request was to some.jsp, the URL in browser address bar remains unchanged. Also, any request attributes set in the controller behind some.jsp will be available in other.jsp. This does not happen during a redirect because you're basically forcing the client to create a new HTTP request on other.jsp, hereby throwing away the original request on some.jsp including all of its attribtues.


The RequestDispatcher is extremely useful in the MVC paradigm and/or when you want to hide JSP's from direct access. You can put JSP's in the /WEB-INF folder and use a Servlet which controls, preprocesses and postprocesses the requests. The JSPs in the /WEB-INF folder are not directly accessible by URL, but the Servlet can access them using RequestDispatcher#forward().

You can for example have a JSP file in /WEB-INF/login.jsp and a LoginServlet which is mapped on an url-pattern of /login. When you invoke http://example.com/context/login, then the servlet's doGet() will be invoked. You can do any preprocessing stuff in there and finally forward the request like:

request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);

When you submit a form, you normally want to use POST:

<form action="login" method="post">

This way the servlet's doPost() will be invoked and you can do any postprocessing stuff in there (e.g. validation, business logic, login the user, etc).

If there are any errors, then you normally want to forward the request back to the same page and display the errors there next to the input fields and so on. You can use the RequestDispatcher for this.

If a POST is successful, you normally want to redirect the request, so that the request won't be resubmitted when the user refreshes the request (e.g. pressing F5 or navigating back in history).

User user = userDAO.find(username, password);
if (user != null) {
    request.getSession().setAttribute("user", user); // Login user.
    response.sendRedirect("home"); // Redirects to http://example.com/context/home after succesful login.
} else {
    request.setAttribute("error", "Unknown login, please try again."); // Set error.
    request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response); // Forward to same page so that you can display error.
}

A redirect thus instructs the client to fire a new GET request on the given URL. Refreshing the request would then only refresh the redirected request and not the initial request. This will avoid "double submits" and confusion and bad user experiences. This is also called the POST-Redirect-GET pattern.

See also:

Styling an anchor tag to look like a submit button

The best you can get with simple styles would be something like:

.likeabutton {
    text-decoration: none; font: menu;
    display: inline-block; padding: 2px 8px;
    background: ButtonFace; color: ButtonText;
    border-style: solid; border-width: 2px;
    border-color: ButtonHighlight ButtonShadow ButtonShadow ButtonHighlight;
}
.likeabutton:active {
    border-color: ButtonShadow ButtonHighlight ButtonHighlight ButtonShadow;
}

(Possibly with some kind of fix to stop IE6-IE7 treating focused buttons as being ‘active’.)

This won't necessarily look exactly like the buttons on the native desktop, though; indeed, for many desktop themes it won't be possible to reproduce the look of a button in simple CSS.

However, you can ask the browser to use native rendering, which is best of all:

.likeabutton {
    appearance: button;
    -moz-appearance: button;
    -webkit-appearance: button;
    text-decoration: none; font: menu; color: ButtonText;
    display: inline-block; padding: 2px 8px;
}

Unfortunately, as you may have guessed from the browser-specific prefixes, this is a CSS3 feature that isn't suppoorted everywhere yet. In particular IE and Opera will ignore it. But if you include the other styles as backup, the browsers that do support appearance drop that property, preferring the explicit backgrounds and borders!

What you might do is use the appearance styles as above by default, and do JavaScript fixups as necessary, eg.:

<script type="text/javascript">
    var r= document.documentElement;
    if (!('appearance' in r || 'MozAppearance' in r || 'WebkitAppearance' in r)) {
        // add styles for background and border colours
        if (/* IE6 or IE7 */)
            // add mousedown, mouseup handlers to push the button in, if you can be bothered
        else
            // add styles for 'active' button
    }
</script>

Sass Nesting for :hover does not work

For concatenating selectors together when nesting, you need to use the parent selector (&):

.class {
    margin:20px;
    &:hover {
        color:yellow;
    }
}

Initializing a member array in constructor initializer

Workaround:

template<class T, size_t N>
struct simple_array { // like std::array in C++0x
   T arr[N];
};


class C : private simple_array<int, 3> 
{
      static simple_array<int, 3> myarr() {
           simple_array<int, 3> arr = {1,2,3};
           return arr;
      }
public:
      C() : simple_array<int, 3>(myarr()) {}
};

Convert varchar dd/mm/yyyy to dd/mm/yyyy datetime

If you want to return a format mm/dd/yyyy, then use 101 instead of 103: CONVERT(VARCHAR(10), [MyDate], 101)

Class has been compiled by a more recent version of the Java Environment

53 stands for java-9, so it means that whatever class you have has been compiled with javac-9 and you try to run it with jre-8. Either re-compile that class with javac-8 or use the jre-9

Using an HTML button to call a JavaScript function

This looks correct. I guess you defined your function either with a different name or in a context which isn't visible to the button. Please add some code

How do I add space between two variables after a print in Python

Alternatively you can use ljust/rjust to make the formatting nicer.

print "%s%s" % (str(count).rjust(10), conv)

or

print str(count).ljust(10), conv

What exactly is the meaning of an API?

An API is a set of commands, functions, and protocols which programmers can use when building software for a specific OS or any other software. The API allows programmers to use predefined functions to interact with the operating system, instead of writing them from scratch. All computer operating systems, such as Windows, Unix, and the Mac OS and language such as Java provide an application program interface for programmers.

Source

How do I rename a MySQL schema?

If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE

Edit: On the model overview it's under Physical Schemata

Screenshot:

enter image description here

What's the difference between interface and @interface in java?

The interface keyword indicates that you are declaring a traditional interface class in Java.
The @interface keyword is used to declare a new annotation type.

See docs.oracle tutorial on annotations for a description of the syntax.
See the JLS if you really want to get into the details of what @interface means.

Print ArrayList

if you make the @Override public String toString() as comments, you will have the same results as you did. But if you implement your toString() method, it will work.

public class PrintingComplexArrayList {

public static void main(String[] args) {
    List houseAddress = new ArrayList();
    insertAddress(houseAddress);
    printMe1(houseAddress);
    printMe2(houseAddress);
}

private static void insertAddress(List address)
{
    address.add(new Address(1));
    address.add(new Address(2));
    address.add(new Address(3));
    address.add(new Address(4));
}
private static void printMe1(List address)
{
    for (int i=0; i<address.size(); i++)
        System.out.println(address.get(i));
}

private static void printMe2(List address)
{
    System.out.println(address);
}

}

class Address{ private int addr; public Address(int i) { addr = i; }

@Override public String toString()
{
    Integer iAddr = new Integer (addr);
    return iAddr.toString();
}

}

Reading *.wav files in Python

if its just two files and the sample rate is significantly high, you could just interleave them.

from scipy.io import wavfile
rate1,dat1 = wavfile.read(File1)
rate2,dat2 = wavfile.read(File2)

if len(dat2) > len(dat1):#swap shortest
    temp = dat2
    dat2 = dat1
    dat1 = temp

output = dat1
for i in range(len(dat2)/2): output[i*2]=dat2[i*2]

wavfile.write(OUTPUT,rate,dat)

Interface type check with Typescript

export interface ConfSteps {
    group: string;
    key: string;
    steps: string[];
}
private verify(): void {
    const obj = `{
      "group": "group",
      "key": "key",
      "steps": [],
      "stepsPlus": []
    } `;
    if (this.implementsObject<ConfSteps>(obj, ['group', 'key', 'steps'])) {
      console.log(`Implements ConfSteps: ${obj}`);
    }
  }
private objProperties: Array<string> = [];

private implementsObject<T>(obj: any, keys: (keyof T)[]): boolean {
    JSON.parse(JSON.stringify(obj), (key, value) => {
      this.objProperties.push(key);
    });
    for (const key of keys) {
      if (!this.objProperties.includes(key.toString())) {
        return false;
      }
    }
    this.objProperties = null;
    return true;
  }

Set a form's action attribute when submitting?

HTML5's formaction does not work on old IE browsers. An easy fix, based on some of the responses above, is:

<button onclick="this.form.action='/PropertiesList';" 
    Account Details </button>

jQuery .each() index?

$('#list option').each(function(index){
  //do stuff
  console.log(index);
});

logs the index :)

a more detailed example is below.

_x000D_
_x000D_
function run_each() {_x000D_
_x000D_
  var $results = $(".results");_x000D_
_x000D_
  $results.empty();_x000D_
_x000D_
  $results.append("==================== START 1st each ====================");_x000D_
  console.log("==================== START 1st each ====================");_x000D_
_x000D_
  $('#my_select option').each(function(index, value) {_x000D_
    $results.append("<br>");_x000D_
    // log the index_x000D_
    $results.append("index: " + index);_x000D_
    $results.append("<br>");_x000D_
    console.log("index: " + index);_x000D_
    // logs the element_x000D_
    // $results.append(value);  this would actually remove the element_x000D_
    $results.append("<br>");_x000D_
    console.log(value);_x000D_
    // logs element property_x000D_
    $results.append(value.innerHTML);_x000D_
    $results.append("<br>");_x000D_
    console.log(value.innerHTML);_x000D_
    // logs element property_x000D_
    $results.append(this.text);_x000D_
    $results.append("<br>");_x000D_
    console.log(this.text);_x000D_
    // jquery_x000D_
    $results.append($(this).text());_x000D_
    $results.append("<br>");_x000D_
    console.log($(this).text());_x000D_
_x000D_
    // BEGIN just to see what would happen if nesting an .each within an .each_x000D_
    $('p').each(function(index) {_x000D_
      $results.append("==================== nested each");_x000D_
      $results.append("<br>");_x000D_
      $results.append("nested each index: " + index);_x000D_
      $results.append("<br>");_x000D_
      console.log(index);_x000D_
    });_x000D_
    // END just to see what would happen if nesting an .each within an .each_x000D_
_x000D_
  });_x000D_
_x000D_
  $results.append("<br>");_x000D_
  $results.append("==================== START 2nd each ====================");_x000D_
  console.log("");_x000D_
  console.log("==================== START 2nd each ====================");_x000D_
_x000D_
_x000D_
  $('ul li').each(function(index, value) {_x000D_
    $results.append("<br>");_x000D_
    // log the index_x000D_
    $results.append("index: " + index);_x000D_
    $results.append("<br>");_x000D_
    console.log(index);_x000D_
    // logs the element_x000D_
    // $results.append(value); this would actually remove the element_x000D_
    $results.append("<br>");_x000D_
    console.log(value);_x000D_
    // logs element property_x000D_
    $results.append(value.innerHTML);_x000D_
    $results.append("<br>");_x000D_
    console.log(value.innerHTML);_x000D_
    // logs element property_x000D_
    $results.append(this.innerHTML);_x000D_
    $results.append("<br>");_x000D_
    console.log(this.innerHTML);_x000D_
    // jquery_x000D_
    $results.append($(this).text());_x000D_
    $results.append("<br>");_x000D_
    console.log($(this).text());_x000D_
  });_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
$(document).on("click", ".clicker", function() {_x000D_
_x000D_
  run_each();_x000D_
_x000D_
});
_x000D_
.results {_x000D_
  background: #000;_x000D_
  height: 150px;_x000D_
  overflow: auto;_x000D_
  color: lime;_x000D_
  font-family: arial;_x000D_
  padding: 20px;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.one,_x000D_
.two,_x000D_
.three {_x000D_
  width: 33.3%;_x000D_
}_x000D_
_x000D_
.one {_x000D_
  background: yellow;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.two {_x000D_
  background: pink;_x000D_
}_x000D_
_x000D_
.three {_x000D_
  background: darkgray;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
_x000D_
  <div class="one">_x000D_
    <select id="my_select">_x000D_
      <option>apple</option>_x000D_
      <option>orange</option>_x000D_
      <option>pear</option>_x000D_
    </select>_x000D_
  </div>_x000D_
_x000D_
  <div class="two">_x000D_
    <ul id="my_list">_x000D_
      <li>canada</li>_x000D_
      <li>america</li>_x000D_
      <li>france</li>_x000D_
    </ul>_x000D_
  </div>_x000D_
_x000D_
  <div class="three">_x000D_
    <p>do</p>_x000D_
    <p>re</p>_x000D_
    <p>me</p>_x000D_
  </div>_x000D_
_x000D_
</div>_x000D_
_x000D_
<button class="clicker">run_each()</button>_x000D_
_x000D_
_x000D_
<div class="results">_x000D_
_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Should I use Python 32bit or Python 64bit

Machine learning packages like tensorflow 2.x are designed to work only on 64 bit Python as they are memory intensive.

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes)

I had this problem. I searched the internet, took all advices, changes configurations, but the problem is still there. Finally with the help of the server administrator, he found that the problem lies in MySQL database column definition. one of the columns in the a table was assigned to 'Longtext' which leads to allocate 4,294,967,295 bites of memory. It seems working OK if you don't use MySqli prepare statement, but once you use prepare statement, it tries to allocate that amount of memory. I changed the column type to Mediumtext which needs 16,777,215 bites of memory space. The problem is gone. Hope this help.

Set Locale programmatically

For people still looking for this answer, since configuration.locale was deprecated from API 24, you can now use:

configuration.setLocale(locale);

Take in consideration that the minSkdVersion for this method is API 17.

Full example code:

@SuppressWarnings("deprecation")
private void setLocale(Locale locale){
    SharedPrefUtils.saveLocale(locale); // optional - Helper method to save the selected language to SharedPreferences in case you might need to attach to activity context (you will need to code this)
    Resources resources = getResources();
    Configuration configuration = resources.getConfiguration();
    DisplayMetrics displayMetrics = resources.getDisplayMetrics();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
        configuration.setLocale(locale);
    } else{
        configuration.locale=locale;
    }
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N){
        getApplicationContext().createConfigurationContext(configuration);
    } else {
        resources.updateConfiguration(configuration,displayMetrics);
    }
}

Don't forget that, if you change the locale with a running Activity, you will need to restart it for the changes to take effect.

EDIT 11th MAY 2018

As from @CookieMonster's post, you might have problems keeping the locale change in higher API versions. If so, add the following code to your Base Activity so that you update the context locale on every Activity creation:

@Override
protected void attachBaseContext(Context base) {
     super.attachBaseContext(updateBaseContextLocale(base));
}

private Context updateBaseContextLocale(Context context) {
    String language = SharedPrefUtils.getSavedLanguage(); // Helper method to get saved language from SharedPreferences
    Locale locale = new Locale(language);
    Locale.setDefault(locale);

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
        return updateResourcesLocale(context, locale);
    }

    return updateResourcesLocaleLegacy(context, locale);
}

@TargetApi(Build.VERSION_CODES.N_MR1)
private Context updateResourcesLocale(Context context, Locale locale) {
    Configuration configuration = new Configuration(context.getResources().getConfiguration())
    configuration.setLocale(locale);
    return context.createConfigurationContext(configuration);
}

@SuppressWarnings("deprecation")
private Context updateResourcesLocaleLegacy(Context context, Locale locale) {
    Resources resources = context.getResources();
    Configuration configuration = resources.getConfiguration();
    configuration.locale = locale;
    resources.updateConfiguration(configuration, resources.getDisplayMetrics());
    return context;
}

If you use this, don't forget to save the language to SharedPreferences when you set the locale with setLocate(locale)

EDIT 7th APRIL 2020

You might be experiencing issues in Android 6 and 7, and this happens due to an issue in the androidx libraries while handling the night mode. For this you will also need to override applyOverrideConfiguration in your base activity and update the configuration's locale in case a fresh new locale one is created.

Sample code:

@Override
public void applyOverrideConfiguration(Configuration overrideConfiguration) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Build.VERSION.SDK_INT <= Build.VERSION_CODES.N_MR1) {
        // update overrideConfiguration with your locale  
        setLocale(overrideConfiguration) // you will need to implement this
    }
    super.applyOverrideConfiguration(overrideConfiguration);
} 

Why am I not getting a java.util.ConcurrentModificationException in this example?

Change Iterator for each into for loop to solve.

And the Reason is:

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.

--Referred Java Docs.

HTML5 phone number validation with pattern

How about

<input type="text" pattern="[789][0-9]{9}">

TypeError: 'bool' object is not callable

Actually you can fix it with following steps -

  1. Do cls.__dict__
  2. This will give you dictionary format output which will contain {'isFilled':True} or {'isFilled':False} depending upon what you have set.
  3. Delete this entry - del cls.__dict__['isFilled']
  4. You will be able to call the method now.

In this case, we delete the entry which overrides the method as mentioned by BrenBarn.

Returning data from Axios API

axiosTest() is firing asynchronously and not being waited for.

A then() function needs to be hooked up afterwards in order to capture the response variable (axiosTestData).

See Promise for more info.

See Async to level up.

_x000D_
_x000D_
// Dummy Url._x000D_
const url = 'https://jsonplaceholder.typicode.com/posts/1'_x000D_
_x000D_
// Axios Test._x000D_
const axiosTest = axios.get_x000D_
_x000D_
// Axios Test Data._x000D_
axiosTest(url).then(function(axiosTestResult) {_x000D_
  console.log('response.JSON:', {_x000D_
    message: 'Request received',_x000D_
    data: axiosTestResult.data_x000D_
  })_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
_x000D_
_x000D_
_x000D_

Flatten List in LINQ

iList.SelectMany(x => x).ToArray()

A regex for version number parsing

This might work:

^(\*|\d+(\.\d+){0,2}(\.\*)?)$

At the top level, "*" is a special case of a valid version number. Otherwise, it starts with a number. Then there are zero, one, or two ".nn" sequences, followed by an optional ".*". This regex would accept 1.2.3.* which may or may not be permitted in your application.

The code for retrieving the matched sequences, especially the (\.\d+){0,2} part, will depend on your particular regex library.

How do you make a deep copy of an object?

You can make a deep copy with serialization without creating files.

Your object you wish to deep copy will need to implement serializable. If the class isn't final or can't be modified, extend the class and implement serializable.

Convert your class to a stream of bytes:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(object);
oos.flush();
oos.close();
bos.close();
byte[] byteData = bos.toByteArray();

Restore your class from a stream of bytes:

ByteArrayInputStream bais = new ByteArrayInputStream(byteData);
(Object) object = (Object) new ObjectInputStream(bais).readObject();

How to set top position using jquery

And with Prototype:

$('yourDivId').setStyle({top: '100px', left:'80px'});

Java - sending HTTP parameters via POST method easily

Hello pls use this class to improve your post method

public static JSONObject doPostRequest(HashMap<String, String> data, String url) {

    try {
        RequestBody requestBody;
        MultipartBuilder mBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);

        if (data != null) {


            for (String key : data.keySet()) {
                String value = data.get(key);
                Utility.printLog("Key Values", key + "-----------------" + value);

                mBuilder.addFormDataPart(key, value);

            }
        } else {
            mBuilder.addFormDataPart("temp", "temp");
        }
        requestBody = mBuilder.build();


        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        OkHttpClient client = new OkHttpClient();
        Response response = client.newCall(request).execute();
        String responseBody = response.body().string();
        Utility.printLog("URL", url);
        Utility.printLog("Response", responseBody);
        return new JSONObject(responseBody);

    } catch (UnknownHostException | UnsupportedEncodingException e) {

        JSONObject jsonObject=new JSONObject();

        try {
            jsonObject.put("status","false");
            jsonObject.put("message",e.getLocalizedMessage());
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        Log.e(TAG, "Error: " + e.getLocalizedMessage());
    } catch (Exception e) {
        e.printStackTrace();
        JSONObject jsonObject=new JSONObject();

        try {
            jsonObject.put("status","false");
            jsonObject.put("message",e.getLocalizedMessage());
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        Log.e(TAG, "Other Error: " + e.getLocalizedMessage());
    }
    return null;
}

How to differentiate single click event and double click event?

Instead of utilizing more ad-hoc states and setTimeout, turns out there is a native property called detail that you can access from the event object!

element.onclick = event => {
   if (event.detail === 1) {
     // it was a single click
   } else if (event.detail === 2) {
     // it was a double click
   }
};

Modern browsers and even IE-9 supports it :)

Source: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail

Is there a cross-browser onload event when clicking the back button?

jQuery's ready event was created for just this sort of issue. You may want to dig into the implementation to see what is going on under the covers.

SQL conditional SELECT

Sounds like they want the ability to return only allowed fields, which means the number of fields returned also has to be dynamic. This will work with 2 variables. Anything more than that will be getting confusing.

IF (selectField1 = true AND selectField2 = true)
BEGIN
   SELECT Field1, Field2
   FROM Table
END
ELSE IF (selectField1 = true)
BEGIN
   SELECT Field1
   FROM Table
END
ELSE IF (selectField2 = true)
BEGIN
   SELECT Field2
   FROM Table
END

Dynamic SQL will help with multiples. This examples is assuming atleast 1 column is true.

DECLARE @sql varchar(MAX)
SET @sql = 'SELECT '
IF (selectField1 = true)
BEGIN
   SET @sql = @sql + 'Field1, '
END
IF (selectField2 = true)
BEGIN
   SET @sql = @sql + 'Field2, '
END
...
-- DROP ', '
@sql = SUBSTRING(@sql, 1, LEN(@sql)-2)

SET @sql = @sql + ' FROM Table'

EXEC(@sql)

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

function convert(str) {
    var date = new Date(str),
        mnth = ("0" + (date.getMonth()+1)).slice(-2),
        day  = ("0" + date.getDate()).slice(-2);
        hours  = ("0" + date.getHours()).slice(-2);
        minutes = ("0" + date.getMinutes()).slice(-2);
    return [ date.getFullYear(), mnth, day, hours, minutes ].join("-");
}

I used this efficiently in angular because i was losing two hours on updating a $scope.STARTevent, and $scope.ENDevent, IN console.log was fine, however saving to mYsql dropped two hours.

var whatSTART = $scope.STARTevent;
whatSTART = convert(whatever);

THIS WILL ALSO work for END

What does it mean to "program to an interface"?

In Java these concrete classes all implement the CharSequence interface:

CharBuffer, String, StringBuffer, StringBuilder

These concrete classes do not have a common parent class other than Object, so there is nothing that relates them, other than the fact they each have something to do with arrays of characters, representing such, or manipulating such. For instance, the characters of String cannot be changed once a String object is instantiated, whereas the characters of StringBuffer or StringBuilder can be edited.

Yet each one of these classes is capable of suitably implementing the CharSequence interface methods:

char charAt(int index)
int length()
CharSequence subSequence(int start, int end)
String toString()

In some cases, Java class library classes that used to accept String have been revised to now accept the CharSequence interface. So if you have an instance of StringBuilder, instead of extracting a String object (which means instantiating a new object instance), it can instead just pass the StringBuilder itself as it implements the CharSequence interface.

The Appendable interface that some classes implement has much the same kind of benefit for any situation where characters can be appended to an instance of the underlying concrete class object instance. All of these concrete classes implement the Appendable interface:

BufferedWriter, CharArrayWriter, CharBuffer, FileWriter, FilterWriter, LogStream, OutputStreamWriter, PipedWriter, PrintStream, PrintWriter, StringBuffer, StringBuilder, StringWriter, Writer

How can I hash a password in Java?

Among all the standard hash schemes, LDAP ssha is the most secure one to use,

http://www.openldap.org/faq/data/cache/347.html

I would just follow the algorithms specified there and use MessageDigest to do the hash.

You need to store the salt in your database as you suggested.

How to truncate the time on a DateTime object in Python?

6 years later... I found this post and I liked more the numpy aproach:

import numpy as np
dates_array = np.array(['2013-01-01', '2013-01-15', '2013-01-30']).astype('datetime64[ns]')
truncated_dates = dates_array.astype('datetime64[D]')

cheers

Global variables in c#.net

You can create a base class in your application that inherits from System.Web.UI.Page. Let all your pages inherit from the newly created base class. Add a property or a variable to your base class with propected access modifier, so that it will be accessed from all your pages in the application.

Get current URL/URI without some of $_GET variables

I don't know about doing it in Yii, but you could just do this, and it should work anywhere (largely lifted from my answer here):

// Get HTTP/HTTPS (the possible values for this vary from server to server)
$myUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] && !in_array(strtolower($_SERVER['HTTPS']),array('off','no'))) ? 'https' : 'http';
// Get domain portion
$myUrl .= '://'.$_SERVER['HTTP_HOST'];
// Get path to script
$myUrl .= $_SERVER['REQUEST_URI'];
// Add path info, if any
if (!empty($_SERVER['PATH_INFO'])) $myUrl .= $_SERVER['PATH_INFO'];

$get = $_GET; // Create a copy of $_GET
unset($get['lg']); // Unset whatever you don't want
if (count($get)) { // Only add a query string if there's anything left
  $myUrl .= '?'.http_build_query($get);
}

echo $myUrl;

Alternatively, you could pass the result of one of the Yii methods into parse_url(), and manipulate the result to re-build what you want.

How to set a parameter in a HttpServletRequest?

The most upvoted solution generally works but for Spring and/or Spring Boot, the values will not wire to parameters in controller methods annotated with @RequestParam unless you specifically implemented getParameterValues(). I combined the solution(s) here and from this blog:

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class MutableHttpRequest extends HttpServletRequestWrapper {

    private final Map<String, String[]> mutableParams = new HashMap<>();

    public MutableHttpRequest(final HttpServletRequest request) {
        super(request);
    }

    public MutableHttpRequest addParameter(String name, String value) {
        if (value != null)
            mutableParams.put(name, new String[] { value });

        return this;
    }

    @Override
    public String getParameter(final String name) {
        String[] values = getParameterMap().get(name);

        return Arrays.stream(values)
                .findFirst()
                .orElse(super.getParameter(name));
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> allParameters = new HashMap<>();
        allParameters.putAll(super.getParameterMap());
        allParameters.putAll(mutableParams);

        return Collections.unmodifiableMap(allParameters);
    }

    @Override
    public Enumeration<String> getParameterNames() {
        return Collections.enumeration(getParameterMap().keySet());
    }

    @Override
    public String[] getParameterValues(final String name) {
        return getParameterMap().get(name);
    }
}

note that this code is not super-optimized but it works.

Run on server option not appearing in Eclipse

There is only 1 thing that fixed this for me. In the pom.xml, add the tag:

<packaging>war</packaging>

Then after saving that, when you right click on the project you should now see the "Run As... Run on Server" option showing up.

Implement a simple factory pattern with Spring 3 annotations

Following answer of DruidKuma

Litte refactor of his factory with autowired constructor:

@Service
public class MyServiceFactory {

    private static final Map<String, MyService> myServiceCache = new HashMap<>();

    @Autowired
    private MyServiceFactory(List<MyService> services) {
        for(MyService service : services) {
            myServiceCache.put(service.getType(), service);
        }
    }

    public static MyService getService(String type) {
        MyService service = myServiceCache.get(type);
        if(service == null) throw new RuntimeException("Unknown service type: " + type);
        return service;
    }
}

How to change JAVA.HOME for Eclipse/ANT

Go to Environment variable and add

JAVA_HOME=C:\Program Files (x86)\Java\jdk1.6.0_37

till jdk path (exclude bin folder)
now set JAVA_HOME into path as PATH=%JAVA_HOME%\bin;
This will set java path to all the applications which are using java.

For ANT use,

ANT_HOME=C:\Program Files (x86)\apache-ant-1.8.2\bin;

and include ANT_HOME into PATH, so path will look like PATH=%JAVA_HOME%\bin;%ANT_HOME%;

How do I check if an integer is even or odd?

I know this is just syntactic sugar and only applicable in .net but what about extension method...

public static class RudiGroblerExtensions
{
    public static bool IsOdd(this int i)
    {
        return ((i % 2) != 0);
    }
}

Now you can do the following

int i = 5;
if (i.IsOdd())
{
    // Do something...
}

Fade Effect on Link Hover?

You can do this with JQueryUI:

$('a').mouseenter(function(){
  $(this).animate({
    color: '#ff0000'
  }, 1000);
}).mouseout(function(){
  $(this).animate({
    color: '#000000'
  }, 1000);
});

http://jsfiddle.net/dWCbk/

How to limit the number of selected checkboxes?

I did this today, the difference being I wanted to uncheck the oldest checkbox instead of stopping the user from checking a new one:

    let maxCheckedArray = [];
    let assessmentOptions = jQuery('.checkbox-fields').find('input[type="checkbox"]');
    assessmentOptions.on('change', function() {
        let checked = jQuery(this).prop('checked');
        if(checked) {
            maxCheckedArray.push(jQuery(this));
        }
        if(maxCheckedArray.length >= 3) {
            let old_item = maxCheckedArray.shift();
            old_item.prop('checked', false);
        }
    });

TypeError: 'list' object is not callable in python

In the league of stupid Monday morning mistakes, using round brackets instead of square brackets when trying to access an item in the list will also give you the same error message:

l=[1,2,3]

print(l[2])#GOOD
print(l(2))#BAD

TypeError: 'list' object is not callable

Keeping it simple and how to do multiple CTE in a query

You certainly are able to have multiple CTEs in a single query expression. You just need to separate them with a comma. Here is an example. In the example below, there are two CTEs. One is named CategoryAndNumberOfProducts and the second is named ProductsOverTenDollars.

WITH CategoryAndNumberOfProducts (CategoryID, CategoryName, NumberOfProducts) AS
(
   SELECT
      CategoryID,
      CategoryName,
      (SELECT COUNT(1) FROM Products p
       WHERE p.CategoryID = c.CategoryID) as NumberOfProducts
   FROM Categories c
),

ProductsOverTenDollars (ProductID, CategoryID, ProductName, UnitPrice) AS
(
   SELECT
      ProductID,
      CategoryID,
      ProductName,
      UnitPrice
   FROM Products p
   WHERE UnitPrice > 10.0
)

SELECT c.CategoryName, c.NumberOfProducts,
      p.ProductName, p.UnitPrice
FROM ProductsOverTenDollars p
   INNER JOIN CategoryAndNumberOfProducts c ON
      p.CategoryID = c.CategoryID
ORDER BY ProductName

What is VanillaJS?

There's no difference at all, VanillaJS is just a way to refer to native (non-extended and standards-based) JavaScript. Generally speaking it's a term of contrast when using libraries and frameworks like jQuery and React. Website www.vanilla-js.com lays emphasis on it as a joke, by talking 'bout VanillaJS as though it were a fast, lightweight, and cross-platform framework. That muddies the waters! Thus, it can be a little philosophical question: "how many things do I compile to Vanilla JavaScript without being VanillaJS themselves?" So, a mere guideline for that is: if you can write the code and run it in any current web-browser without additional tools or so called compile steps, it might be VanillaJS.

Attempt to write a readonly database - Django w/ SELinux error

This issue is caused by SELinux. After setting file ownership just as you did, I hit this issue. The audit2why(1) tool can be used to diagnose SELinux denials from the log:

(django)[f22-4:www/django/demo] ftweedal% sudo audit2why -a
type=AVC msg=audit(1437490152.208:407): avc:  denied  { write }
      for  pid=20330 comm="httpd" name="db.sqlite3" dev="dm-1" ino=52036
      scontext=system_u:system_r:httpd_t:s0
      tcontext=unconfined_u:object_r:httpd_sys_content_t:s0
      tclass=file permissive=0
    Was caused by:
    The boolean httpd_unified was set incorrectly. 
    Description:
    Allow httpd to unified

    Allow access by executing:
    # setsebool -P httpd_unified 1

Sure enough, running sudo setsebool -P httpd_unified 1 resolved the issue.

Looking into what httpd_unified is for, I came across a fedora-selinux-list post which explains:

This Boolean is off by default, turning it on will allow all httpd executables to have full access to all content labeled with a http file context. Leaving it off makes sure that one httpd service can not interfere with another.

So turning on httpd_unified lets you circumvent the default behaviour that prevents multiple httpd instances on the same server - all running as user apache - messing with each others' stuff.

In my case, I am only running one httpd, so it was fine for me to turn on httpd_unified. If you cannot do this, I suppose some more fine-grained labelling is needed.

How do I get out of 'screen' without typing 'exit'?

Ctrl+a followed by k will "kill" the current screen session.

Can multiple different HTML elements have the same ID if they're different elements?

No.

Element IDs should be unique within the entire document.

(How) can I count the items in an enum?

For C++, there are various type-safe enum techniques available, and some of those (such as the proposed-but-never-submitted Boost.Enum) include support for getting the size of a enum.

The simplest approach, which works in C as well as C++, is to adopt a convention of declaring a ...MAX value for each of your enum types:

enum Folders { FA, FB, FC, Folders_MAX = FC };
ContainerClass *m_containers[Folders_MAX + 1];
....
m_containers[FA] = ...; // etc.

Edit: Regarding { FA, FB, FC, Folders_MAX = FC} versus {FA, FB, FC, Folders_MAX]: I prefer setting the ...MAX value to the last legal value of the enum for a few reasons:

  1. The constant's name is technically more accurate (since Folders_MAX gives the maximum possible enum value).
  2. Personally, I feel like Folders_MAX = FC stands out from other entries out a bit more (making it a bit harder to accidentally add enum values without updating the max value, a problem Martin York referenced).
  3. GCC includes helpful warnings like "enumeration value not included in switch" for code such as the following. Letting Folders_MAX == FC + 1 breaks those warnings, since you end up with a bunch of ...MAX enumeration values that should never be included in switch.
switch (folder) 
{
  case FA: ...;
  case FB: ...;
  // Oops, forgot FC!
}

Want to show/hide div based on dropdown box selection

try this which is working for me in my test demo

<script>
$(document).ready(function(){
$('#dropdown').change(function() 
{ 
//  var selectedValue = parseInt(jQuery(this).val());
var text = $('#dropdown').val();
//alert("text");
    //Depend on Value i.e. 0 or 1 respective function gets called. 
    switch(text){
        case 'Reporting':
          // alert("hello1");
   $("#td1").hide();
            break;
        case 'Buyer':
      //alert("hello");
     $("#td1").show();   
            break;
        //etc... 
        default:
            alert("catch default");
            break;
    }
});
});

</script>

Sort a single String in Java

str.chars().boxed().map(Character::toString).sorted().collect(Collectors.joining())

or

s.chars().mapToObj(Character::toString).sorted().collect(Collectors.joining())

or

Arrays.stream(str.split("")).sorted().collect(Collectors.joining())

Is there a good Valgrind substitute for Windows?

More or less all Profilers include checking for memory leaks and show you the stack when the memory was allocated.

I can recommend Intels Parallel Inspector. Simple to use and no recompilation needed. The trial version runs for 30 days.

GlowCode and AtromatedQA also include such capabilites. They all offer free trials.

Compuware DevPartner (aka BoundsChecker) in Contrast needs a slowed down "instrumentation" recompile and the application also runs slower when checking for errors. And BoundsChecker can not work with 64 Bit evsrions at all. We gave up on that tool.

error: Error parsing XML: not well-formed (invalid token) ...?

It means there is a compilation error in your XML file, something that shouldn't be there: a spelling mistake/a spurious character/an incorrect namespace.

Your issue is you've got a semicolon that shouldn't be there after this line:

  android:text="@string/hello";

How to pass IEnumerable list to controller in MVC including checkbox state?

Use a list instead and replace your foreach loop with a for loop:

@model IList<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()

    @for (var i = 0; i < Model.Count; i++) 
    {
        <tr>
            <td>
                @Html.HiddenFor(x => x[i].IP)           
                @Html.CheckBoxFor(x => x[i].Checked)
            </td>
            <td>
                @Html.DisplayFor(x => x[i].IP)
            </td>
        </tr>
    }
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

Alternatively you could use an editor template:

@model IEnumerable<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()
    @Html.EditorForModel()   
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml which will automatically be rendered for each element of the collection:

@model BlockedIPViewModel
<tr>
    <td>
        @Html.HiddenFor(x => x.IP)
        @Html.CheckBoxFor(x => x.Checked)
    </td>
    <td>
        @Html.DisplayFor(x => x.IP)
    </td>
</tr>

The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article.

Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.

Rename multiple files based on pattern in Unix

I would recommend using my own script, which solves this problem. It also has options to change the encoding of the file names, and to convert combining diacriticals to precomposed characters, a problem I always have when I copy files from my Mac.

#!/usr/bin/perl

# Copyright (c) 2014 André von Kugland

# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

$help_msg =
"rename.pl, a script to rename files in batches, using Perl
           expressions to transform their names.
Usage:
    rename.pl [options] FILE1 [FILE2 ...]
Where options can be:
    -v                      Verbose.
    -vv                     Very verbose.
    --apply                 Really apply modifications.
    -e PERLCODE             Execute PERLCODE. (e.g. 's/a/b/g')
    --from-charset=CS       Source charset. (e.g. \"iso-8859-1\")
    --to-charset=CS         Destination charset. (e.g. \"utf-8\")
    --unicode-normalize=NF  Unicode normalization form. (e.g. \"KD\")
    --basename              Modifies only the last element of the path.
";

use Encode;
use Getopt::Long;
use Unicode::Normalize 'normalize';
use File::Basename;
use I18N::Langinfo qw(langinfo CODESET);

Getopt::Long::Configure ("bundling");

# ----------------------------------------------------------------------------------------------- #
#                                           Our variables.                                        #
# ----------------------------------------------------------------------------------------------- #

my $apply = 0;
my $verbose = 0;
my $help = 0;
my $debug = 0;
my $basename = 0;
my $unicode_normalize = "";
my @scripts;
my $from_charset = "";
my $to_charset = "";
my $codeset = "";

# ----------------------------------------------------------------------------------------------- #
#                                        Get cmdline options.                                     #
# ----------------------------------------------------------------------------------------------- #

$result = GetOptions ("apply" => \$apply,
                      "verbose|v+" => \$verbose,
                      "execute|e=s" => \@scripts,
                      "from-charset=s" => \$from_charset,
                      "to-charset=s" => \$to_charset,
                      "unicode-normalize=s" => \$unicode_normalize,
                      "basename" => \$basename,
                      "help|h|?" => \$help,
                      "debug" => \$debug);

# If not going to apply, then be verbose.
if (!$apply && $verbose == 0) {
  $verbose = 1;
}

if ((($#scripts == -1)
  && (($from_charset eq "") || ($to_charset eq ""))
  && $unicode_normalize eq "")
  || ($#ARGV == -1) || ($help)) {
  print $help_msg;
  exit(0);
}

if (($to_charset ne "" && $from_charset eq "")
  ||($from_charset eq "" && $to_charset ne "")
  ||($to_charset eq "" && $from_charset eq "" && $unicode_normalize ne "")) {
  $codeset = langinfo(CODESET);
  $to_charset = $codeset if $from_charset ne "" && $to_charset eq "";
  $from_charset = $codeset if $from_charset eq "" && $to_charset ne "";
}

# ----------------------------------------------------------------------------------------------- #
#         Composes the filter function using the @scripts array and possibly other options.       #
# ----------------------------------------------------------------------------------------------- #

$f = "sub filterfunc() {\n    my \$s = shift;\n";
$f .= "    my \$d = dirname(\$s);\n    my \$s = basename(\$s);\n" if ($basename != 0);
$f .= "    for (\$s) {\n";
$f .= "        $_;\n" foreach (@scripts);   # Get scripts from '-e' opt. #
# Handle charset translation and normalization.
if (($from_charset ne "") && ($to_charset ne "")) {
  if ($unicode_normalize eq "") {
    $f .= "        \$_ = encode(\"$to_charset\", decode(\"$from_charset\", \$_));\n";
  } else {
    $f .= "        \$_ = encode(\"$to_charset\", normalize(\"$unicode_normalize\", decode(\"$from_charset\", \$_)));\n"
  }
} elsif (($from_charset ne "") || ($to_charset ne "")) {
    die "You can't use `from-charset' nor `to-charset' alone";
} elsif ($unicode_normalize ne "") {
  $f .= "        \$_ = encode(\"$codeset\", normalize(\"$unicode_normalize\", decode(\"$codeset\", \$_)));\n"
}
$f .= "    }\n";
$f .= "    \$s = \$d . '/' . \$s;\n" if ($basename != 0);
$f .= "    return \$s;\n}\n";
print "Generated function:\n\n$f" if ($debug);

# ----------------------------------------------------------------------------------------------- #
#                 Evaluates the filter function body, so to define it in our scope.               #
# ----------------------------------------------------------------------------------------------- #

eval $f;

# ----------------------------------------------------------------------------------------------- #
#                  Main loop, which passes names through filters and renames files.               #
# ----------------------------------------------------------------------------------------------- #

foreach (@ARGV) {
  $old_name = $_;
  $new_name = filterfunc($_);

  if ($old_name ne $new_name) {
    if (!$apply or (rename $old_name, $new_name)) {
      print "`$old_name' => `$new_name'\n" if ($verbose);
    } else {
      print "Cannot rename `$old_name' to `$new_name'.\n";
    }
  } else {
    print "`$old_name' unchanged.\n" if ($verbose > 1);
  }
}

Sort objects in an array alphabetically on one property of the array

objArray.sort( (a, b) => a.id.localeCompare(b.id, 'en', {'sensitivity': 'base'}));

This sorts them alphabetically AND is case insensitive. It's also super clean and easy to read :D

Oracle DB: How can I write query ignoring case?

You can use the upper() function in your query, and to increase performance you can use a function-base index

 CREATE INDEX upper_index_name ON table(upper(name))

Angular 2 - Using 'this' inside setTimeout

You need to use Arrow function ()=> ES6 feature to preserve this context within setTimeout.

// var that = this;                             // no need of this line
this.messageSuccess = true;

setTimeout(()=>{                           //<<<---using ()=> syntax
      this.messageSuccess = false;
 }, 3000);

How can I display a pdf document into a Webview?

You can use the Mozilla pdf.js project. Basically it will show you the PDF. Take a look at their example.

I only use it on the browser (desktop and mobile) and it's working fine.

Where's my JSON data in my incoming Django request?

If you are posting JSON to Django, I think you want request.body (request.raw_post_data on Django < 1.4). This will give you the raw JSON data sent via the post. From there you can process it further.

Here is an example using JavaScript, jQuery, jquery-json and Django.

JavaScript:

var myEvent = {id: calEvent.id, start: calEvent.start, end: calEvent.end,
               allDay: calEvent.allDay };
$.ajax({
    url: '/event/save-json/',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: $.toJSON(myEvent),
    dataType: 'text',
    success: function(result) {
        alert(result.Result);
    }
});

Django:

def save_events_json(request):
    if request.is_ajax():
        if request.method == 'POST':
            print 'Raw Data: "%s"' % request.body   
    return HttpResponse("OK")

Django < 1.4:

  def save_events_json(request):
    if request.is_ajax():
        if request.method == 'POST':
            print 'Raw Data: "%s"' % request.raw_post_data
    return HttpResponse("OK")

Finding height in Binary Search Tree

I guess this question could mean two different things...

  1. Height is the number of nodes in the longest branch:-

    int calcHeight(node* root){ if(root==NULL) return 0; int l=calcHeight(root->left); int r=calcHeight(root->right); if(l>r) return l+1; else return r+1; }

  2. Height is the total number of nodes in the tree itself:

    int calcSize(node* root){ if(root==NULL) return 0; return(calcSize(root->left)+1+calcSize(root->right)); }

Appending a byte[] to the end of another byte[]

You need to declare out as a byte array with a length equal to the lengths of ciphertext and mac added together, and then copy ciphertext over the beginning of out and mac over the end, using arraycopy.

byte[] concatenateByteArrays(byte[] a, byte[] b) {
    byte[] result = new byte[a.length + b.length]; 
    System.arraycopy(a, 0, result, 0, a.length); 
    System.arraycopy(b, 0, result, a.length, b.length); 
    return result;
} 

Get path of executable

If using C++17 one can do the following to get the path to the executable.

#include <filesystem>

std::filesystem::path getExecutablePath()
{
    return std::filesystem::canonical("/proc/self/exe");
}

The above answer has been tested on Debian 10 using G++ 9.3.0

how to delete all commit history in github?

If you are sure you want to remove all commit history, simply delete the .git directory in your project root (note that it's hidden). Then initialize a new repository in the same folder and link it to the GitHub repository:

git init
git remote add origin [email protected]:user/repo

now commit your current version of code

git add *
git commit -am 'message'

and finally force the update to GitHub:

git push -f origin master

However, I suggest backing up the history (the .git folder in the repository) before taking these steps!

How do I write JSON data to a file?

Read and write JSON files with Python 2+3; works with unicode

# -*- coding: utf-8 -*-
import json

# Make it work for Python 2+3 and with Unicode
import io
try:
    to_unicode = unicode
except NameError:
    to_unicode = str

# Define data
data = {'a list': [1, 42, 3.141, 1337, 'help', u'€'],
        'a string': 'bla',
        'another dict': {'foo': 'bar',
                         'key': 'value',
                         'the answer': 42}}

# Write JSON file
with io.open('data.json', 'w', encoding='utf8') as outfile:
    str_ = json.dumps(data,
                      indent=4, sort_keys=True,
                      separators=(',', ': '), ensure_ascii=False)
    outfile.write(to_unicode(str_))

# Read JSON file
with open('data.json') as data_file:
    data_loaded = json.load(data_file)

print(data == data_loaded)

Explanation of the parameters of json.dump:

  • indent: Use 4 spaces to indent each entry, e.g. when a new dict is started (otherwise all will be in one line),
  • sort_keys: sort the keys of dictionaries. This is useful if you want to compare json files with a diff tool / put them under version control.
  • separators: To prevent Python from adding trailing whitespaces

With a package

Have a look at my utility package mpu for a super simple and easy to remember one:

import mpu.io
data = mpu.io.read('example.json')
mpu.io.write('example.json', data)

Created JSON file

{
    "a list":[
        1,
        42,
        3.141,
        1337,
        "help",
        "€"
    ],
    "a string":"bla",
    "another dict":{
        "foo":"bar",
        "key":"value",
        "the answer":42
    }
}

Common file endings

.json

Alternatives

For your application, the following might be important:

  • Support by other programming languages
  • Reading / writing performance
  • Compactness (file size)

See also: Comparison of data serialization formats

In case you are rather looking for a way to make configuration files, you might want to read my short article Configuration files in Python

Excel: the Incredible Shrinking and Expanding Controls

I run across this issue all the time in Excel 2010 (Which always brings me back to this thread) and although I haven't found a fix 100%, I believe I have some information that can help others.

While tediously playing around with the buttons I discovered that DIFFERENT EVENTS for each object were causing different issues. For example,

  • Button A - The size of the button would shrink on the MouseDown event
  • Button B - The text would enlarge on the MouseMove event (But only after the button was clicked. AKA, I click a button, code executes, leave the mouse hovering over the button, and then as soon as I move the mouse the text would enlarge)
  • Text input box A - The text would enlarge on the MouseUp event
  • Text input box B - The text would enlarge on the LostFocus event

The only solution that works for me is to write code to reset the size/text for each object event that was causing the random resizing. Like so ...

Where MaterialNum is the name of the input box, and MouseDown is the event ...

Private Sub MaterialNum_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)

    ' Reset the size, font style, and size
    With Worksheets("QuoteForm").Shapes("MaterialNum")
        .Height = 21
        .Width = 101.25
        .Left = 972.75
        .Top = 87
        With .DrawingObject.Object.Font
            .Name = "Arial"
            .Size = 12
        End With
    End With

End Sub

In addition, I had to change a few options in Format Control (Right click object > Format Control):

  • Size tab: Lock aspect ratio box is checked
  • Properties tab: Print Object box is unchecked

Also, in the Object Properties pane (Right click object > Properties) I set TakeFocusOnClick to false

Yes, this is time consuming and tedious as it has to be done with each object, but it's the only fix that works for me (And it seems to be a quicker fix than waiting for Microsoft to fix this!!!). Hopefully it helps others.

I hope others find this helpful

Execute jQuery function after another function completes

You could also use custom events:

function Typer() {
    // Some stuff

    $(anyDomElement).trigger("myCustomEvent");
}


$(anyDomElement).on("myCustomEvent", function() {
    // Some other stuff
});

in_array() and multidimensional array

I believe you can just use array_key_exists nowadays:

<?php
$a=array("Mac"=>"NT","Irix"=>"Linux");
if (array_key_exists("Mac",$a))
  {
  echo "Key exists!";
  }
else
  {
  echo "Key does not exist!";
  }
?>

Programmatically add custom event in the iPhone Calendar

Working code in Swift-4.2

import UIKit
import EventKit
import EventKitUI

class yourViewController: UIViewController{

    let eventStore = EKEventStore()

    func addEventToCalendar() {

    eventStore.requestAccess( to: EKEntityType.event, completion:{(granted, error) in
        DispatchQueue.main.async {
            if (granted) && (error == nil) {
                let event = EKEvent(eventStore: self.eventStore)
                event.title = self.headerDescription
                event.startDate = self.parse(self.requestDetails.value(forKey: "session_time") as? String ?? "")
                event.endDate = self.parse(self.requestDetails.value(forKey: "session_end_time") as? String ?? "")
                let eventController = EKEventEditViewController()
                eventController.event = event
                eventController.eventStore = self.eventStore
                eventController.editViewDelegate = self
                self.present(eventController, animated: true, completion: nil)

            }
        }


       })
    }

}

Now we will get the event screen and here you can also modify your settings:

enter image description here

Now add delegate method to handle Cancel and add the event button action of event screen:

    extension viewController: EKEventEditViewDelegate {

    func eventEditViewController(_ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction) {
        controller.dismiss(animated: true, completion: nil)

    }
}

Note: Don't forget to add NSCalendarsUsageDescription key into info plist.

Limit length of characters in a regular expression?

(^(\d{2})|^(\d{4})|^(\d{5}))$

This expression takes the number of length 2,4 and 5. Valid Inputs are 12 1234 12345

Find difference between timestamps in seconds in PostgreSQL

SELECT (cast(timestamp_1 as bigint) - cast(timestamp_2 as bigint)) FROM table;

In case if someone is having an issue using extract.

Using PowerShell credentials without being prompted for a password

Here are two ways you could do this, if you are scheduling the reboot.

First you could create a task on one machine using credentials that have rights needed to connect and reboot another machine. This makes the scheduler responsible for securely storing the credentials. The reboot command (I'm a Powershell guy, but this is cleaner.) is:

SHUTDOWN /r /f /m \\ComputerName

The command line to create a scheduled task on the local machine, to remotely reboot another, would be:

SCHTASKS /Create /TN "Reboot Server" /TR "shutdown.exe /r /f /m \\ComputerName" /SC ONCE /ST 00:00 /SD "12/24/2012" /RU "domain\username" /RP "password"

I prefer the second way, where you use your current credentials to create a scheduled task that runs with the system account on a remote machine.

SCHTASKS /Create /TN "Reboot Server" /TR "shutdown.exe /r /f" /SC ONCE /ST 00:00 /SD "12/24/2012" /RU SYSTEM /S ComputerName

This also works through the GUI, just enter SYSTEM as the user name, leaving the password fields blank.

Using '<%# Eval("item") %>'; Handling Null Value and showing 0 against

Try replacing <%# Eval("item") %> with <%# If(Eval("item"), "0 value") %> (or <%# Eval("item") ?? "0 value" %>, when using C#).

Dynamically allocating an array of objects

  1. Use array or common container for objects only if they have default and copy constructors.

  2. Store pointers otherwise (or smart pointers, but may meet some issues in this case).

PS: Always define own default and copy constructors otherwise auto-generated will be used

C# difference between == and Equals()

Just as an addition to the already good answers: This behaviour is NOT limited to Strings or comparing different numbertypes. Even if both elements are of type object of the same underlying type. "==" won't work.

The following screenshot shows the results of comparing two object {int} - values

Example From VS2017

How to break nested loops in JavaScript?

function myFunction(){
  for(var i = 0;i < n;i++){
    for(var m = 0;m < n;m++){
      if(/*break condition*/){
        goto out;
      }
    }
  }
out:
 //your out of the loop;
}

c - warning: implicit declaration of function ‘printf’

the warning or error of kind IMPLICIT DECLARATION is that the compiler is expecting a Function Declaration/Prototype..

It might either be a header file or your own function Declaration..

Convert DataFrame column type from string to datetime, dd/mm/yyyy format

The easiest way is to use to_datetime:

df['col'] = pd.to_datetime(df['col'])

It also offers a dayfirst argument for European times (but beware this isn't strict).

Here it is in action:

In [11]: pd.to_datetime(pd.Series(['05/23/2005']))
Out[11]:
0   2005-05-23 00:00:00
dtype: datetime64[ns]

You can pass a specific format:

In [12]: pd.to_datetime(pd.Series(['05/23/2005']), format="%m/%d/%Y")
Out[12]:
0   2005-05-23
dtype: datetime64[ns]

How to create an empty array in PHP with predefined size?

There is also array_pad. You can use it like this:

$data = array_pad($data,$number_of_items,0);

For initializing with zeros the $number_of_items positions of the array $data.

How to get values of selected items in CheckBoxList with foreach in ASP.NET C#?

string s= string.Empty

for (int i = 0; i < Chkboxlist.Items.Count; i++)

{

    if (Chkboxlist.Items[i].Selected)
    {
        s+= Chkboxlist.Items[i].Value + ";"; 
    }

}

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

How to use GNU Make on Windows?

user1594322 gave a correct answer but when I tried it I ran into admin/permission problems. I was able to copy 'mingw32-make.exe' and paste it, over-ruling/by-passing admin issues and then editing the copy to 'make.exe'. On VirtualBox in a Win7 guest.

Convert blob to base64

There is a pure JavaSript way that is not depended on any stacks:

const blobToBase64 = blob => {
  const reader = new FileReader();
  reader.readAsDataURL(blob);
  return new Promise(resolve => {
    reader.onloadend = () => {
      resolve(reader.result);
    };
  });
};

For using this helper function you should set a callback, example:

blobToBase64(blobData).then(res => {
  // do what you wanna do
  console.log(res); // res is base64 now
});

I write this helper function for my problem on React Native project, I wanted to download an image and then store it as a cached image:

fetch(imageAddressAsStringValue)
  .then(res => res.blob())
  .then(blobToBase64)
  .then(finalResult => { 
    storeOnMyLocalDatabase(finalResult);
  });

VBA - Range.Row.Count

The best solution is to use

Cells(Rows.Count, 1).End(xlUp).Row

since it counts the number of cells until it finds the last one written.

Unlike

Range("A1", sh.Range("A1").End(xlDown)).Rows.Count

what it does is select an "from-to" range and display the row number of the last one busy.
A range implies two minimum values, so ... meanwhile A1 has a value of the range continues to count to the limit (1048576) then it is shown.

Sub test()

Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets(1)
Dim k As Long

    k = Cells(Rows.Count, 1).End(xlUp).Row
    MsgBox k

    k = sh.Range("A1", sh.Range("A1").End(xlDown)).Rows.Count
    MsgBox k

End Sub

enter image description here

android EditText - finished typing event

When the user has finished editing, s/he will press Done or Enter

((EditText)findViewById(R.id.youredittext)).setOnEditorActionListener(
    new EditText.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH ||
                    actionId == EditorInfo.IME_ACTION_DONE ||
                    event != null &&
                    event.getAction() == KeyEvent.ACTION_DOWN &&
                    event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                if (event == null || !event.isShiftPressed()) {
                   // the user is done typing. 

                   return true; // consume.
                }                
            }
            return false; // pass on to other listeners. 
        }
    }
);

How to add number of days in postgresql datetime

This will give you the deadline :

select id,  
       title,
       created_at + interval '1' day * claim_window as deadline
from projects

Alternatively the function make_interval can be used:

select id,  
       title,
       created_at + make_interval(days => claim_window) as deadline
from projects

To get all projects where the deadline is over, use:

select *
from (
  select id, 
         created_at + interval '1' day * claim_window as deadline
  from projects
) t
where localtimestamp at time zone 'UTC' > deadline

How to print jquery object/array

I was having similar problem and

var dataObj = JSON.parse(data);

console.log(dataObj[0].category); //will return Damskie
console.log(dataObj[1].category); //will return Meskie

This solved my problem. Thanks Selvakumar Arumugam

How do I temporarily disable triggers in PostgreSQL?

SET session_replication_role = replica;  

also dosent work for me in Postgres 9.1. i use the two function described by bartolo-otrit with some modification. I modified the first function to make it work for me because the namespace or the schema must be present to identify the table correctly. The new code is :

CREATE OR REPLACE FUNCTION disable_triggers(a boolean, nsp character varying)
  RETURNS void AS
$BODY$
declare 
act character varying;
r record;
begin
    if(a is true) then
        act = 'disable';
    else
        act = 'enable';
    end if;

    for r in select c.relname from pg_namespace n
        join pg_class c on c.relnamespace = n.oid and c.relhastriggers = true
        where n.nspname = nsp
    loop
        execute format('alter table %I.%I %s trigger all', nsp,r.relname, act); 
    end loop;
end;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION disable_triggers(boolean, character varying)
  OWNER TO postgres;

then i simply do a select query for every schema :

SELECT disable_triggers(true,'public');
SELECT disable_triggers(true,'Adempiere');

How to write DataFrame to postgres table?

Starting from pandas 0.14 (released end of May 2014), postgresql is supported. The sql module now uses sqlalchemy to support different database flavors. You can pass a sqlalchemy engine for a postgresql database (see docs). E.g.:

from sqlalchemy import create_engine
engine = create_engine('postgresql://username:password@localhost:5432/mydatabase')
df.to_sql('table_name', engine)

You are correct that in pandas up to version 0.13.1 postgresql was not supported. If you need to use an older version of pandas, here is a patched version of pandas.io.sql: https://gist.github.com/jorisvandenbossche/10841234.
I wrote this a time ago, so cannot fully guarantee that it always works, buth the basis should be there). If you put that file in your working directory and import it, then you should be able to do (where con is a postgresql connection):

import sql  # the patched version (file is named sql.py)
sql.write_frame(df, 'table_name', con, flavor='postgresql')

Enable 'xp_cmdshell' SQL Server

Even if this question has resolved, I want to add my advice about that.... since as developer I ignored.

Is important to know that we're talking about MSSQL xp_cmdshell enabled is critical to security, as indicated in the message warning:

Blockquote SQL Server blocked access to procedure 'sys.xp_cmdshell' of component 'xp_cmdshell' because this component is turned off as part of the security configuration for this server. [...]

Leaving the service enabled is a kind of weakness, that for example in a web-app could reflect and execute commands SQL from an attacker. The popular CWE-89: SQL Injection it could be weakness in the our software, and therefore these type of scenarios could pave the way to possible attacks, such as CAPEC-108: Command Line Execution through SQL Injection

I hope to have done something pleasant, we Developers and Engineer do things with awareness and we will be safer!

How to send a JSON object using html form data

I'm late but I need to say for those who need an object, using only html, there's a way. In some server side frameworks like PHP you can write the follow code:

<form action="myurl" method="POST" name="myForm">
        <p><label for="first_name">First Name:</label>
        <input type="text" name="name[first]" id="fname"></p>

        <p><label for="last_name">Last Name:</label>
        <input type="text" name="name[last]" id="lname"></p>

        <input value="Submit" type="submit">
    </form>

So, we need setup the name of the input as object[property] for got an object. In the above example, we got a data with the follow JSON:

{
"name": {
  "first": "some data",
  "last": "some data"
 }
}

Unable to create/open lock file: /data/mongod.lock errno:13 Permission denied

Do ls -lato know the user and group of /var/log/mongodb. Then do sudo chown -R user:group /data/db Now run sudo service mongodb start. Check the status with sudo service mongodb status

AngularJs: How to set radio button checked based on model

Ended up just using the built-in angular attribute ng-checked="model"

JS map return object

map rockets and add 10 to its launches:

_x000D_
_x000D_
var rockets = [_x000D_
    { country:'Russia', launches:32 },_x000D_
    { country:'US', launches:23 },_x000D_
    { country:'China', launches:16 },_x000D_
    { country:'Europe(ESA)', launches:7 },_x000D_
    { country:'India', launches:4 },_x000D_
    { country:'Japan', launches:3 }_x000D_
];_x000D_
rockets.map((itm) => {_x000D_
    itm.launches += 10_x000D_
    return itm_x000D_
})_x000D_
console.log(rockets)
_x000D_
_x000D_
_x000D_

If you don't want to modify rockets you can do:

var plusTen = []
rockets.forEach((itm) => {
    plusTen.push({'country': itm.country, 'launches': itm.launches + 10})
})

Proper use of errors

Simple solution to emit and show message by Exception.

try {
  throw new TypeError("Error message");
}
catch (e){
  console.log((<Error>e).message);//conversion to Error type
}

Caution

Above is not a solution if we don't know what kind of error can be emitted from the block. In such cases type guards should be used and proper handling for proper error should be done - take a look on @Moriarty answer.

JavaScript - Get Portion of URL Path

If you have an abstract URL string (not from the current window.location), you can use this trick:

let yourUrlString = "http://example.com:3000/pathname/?search=test#hash";

let parser = document.createElement('a');
parser.href = yourUrlString;

parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port;     // => "3000"
parser.pathname; // => "/pathname/"
parser.search;   // => "?search=test"
parser.hash;     // => "#hash"
parser.host;     // => "example.com:3000"

Thanks to jlong

What is the equivalent to getLastInsertId() in Cakephp?

Use this one

function designpage() {
//to create a form Untitled
$this->Form->saveField('name','Untitled Form');
echo $this->Form->id; //here it works

}

Improve subplot size/spacing with many subplots in matplotlib

I found that subplots_adjust(hspace = 0.001) is what ended up working for me. When I use space = None, there is still white space between each plot. Setting it to something very close to zero however seems to force them to line up. What I've uploaded here isn't the most elegant piece of code, but you can see how the hspace works.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tic

fig = plt.figure()

x = np.arange(100)
y = 3.*np.sin(x*2.*np.pi/100.)

for i in range(5):
    temp = 510 + i
    ax = plt.subplot(temp)
    plt.plot(x,y)
    plt.subplots_adjust(hspace = .001)
    temp = tic.MaxNLocator(3)
    ax.yaxis.set_major_locator(temp)
    ax.set_xticklabels(())
    ax.title.set_visible(False)

plt.show()

enter image description here

Background color for Tk in Python

I know this is kinda an old question but:

root["bg"] = "black"

will also do what you want and it involves less typing.

Use component from another module

SOLVED HOW TO USE A COMPONENT DECLARED IN A MODULE IN OTHER MODULE.

Based on Royi Namir explanation (Thank you so much). There is a missing part to reuse a component declared in a Module in any other module while lazy loading is used.

1st: Export the component in the module which contains it:

@NgModule({
  declarations: [TaskCardComponent],
  imports: [MdCardModule],
  exports: [TaskCardComponent] <== this line
})
export class TaskModule{}

2nd: In the module where you want to use TaskCardComponent:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MdCardModule } from '@angular2-material/card';

@NgModule({
  imports: [
   CommonModule,
   MdCardModule
   ],
  providers: [],
  exports:[ MdCardModule ] <== this line
})
export class TaskModule{}

Like this the second module imports the first module which imports and exports the component.

When we import the module in the second module we need to export it again. Now we can use the first component in the second module.

The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported

You will also get this error message when you accidentally forget to define a setter for a property. For example:

public class Building
{
    public string Description { get; }
}

var query = 
    from building in context.Buildings
    select new
    {
        Desc = building.Description
    };
int count = query.ToList();

The call to ToList will give the same error message. This one is a very subtle error and very hard to detect.

Is it better practice to use String.format over string Concatenation in Java?

Here's the same test as above with the modification of calling the toString() method on the StringBuilder. The results below show that the StringBuilder approach is just a bit slower than String concatenation using the + operator.

file: StringTest.java

class StringTest {

  public static void main(String[] args) {

    String formatString = "Hi %s; Hi to you %s";

    long start = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
        String s = String.format(formatString, i, +i * 2);
    }

    long end = System.currentTimeMillis();
    System.out.println("Format = " + ((end - start)) + " millisecond");

    start = System.currentTimeMillis();

    for (int i = 0; i < 1000000; i++) {
        String s = "Hi " + i + "; Hi to you " + i * 2;
    }

    end = System.currentTimeMillis();

    System.out.println("Concatenation = " + ((end - start)) + " millisecond");

    start = System.currentTimeMillis();

    for (int i = 0; i < 1000000; i++) {
        StringBuilder bldString = new StringBuilder("Hi ");
        bldString.append(i).append("Hi to you ").append(i * 2).toString();
    }

    end = System.currentTimeMillis();

    System.out.println("String Builder = " + ((end - start)) + " millisecond");

  }
}

Shell Commands : (compile and run StringTest 5 times)

> javac StringTest.java
> sh -c "for i in \$(seq 1 5); do echo \"Run \${i}\"; java StringTest; done"

Results :

Run 1
Format = 1290 millisecond
Concatenation = 115 millisecond
String Builder = 130 millisecond

Run 2
Format = 1265 millisecond
Concatenation = 114 millisecond
String Builder = 126 millisecond

Run 3
Format = 1303 millisecond
Concatenation = 114 millisecond
String Builder = 127 millisecond

Run 4
Format = 1297 millisecond
Concatenation = 114 millisecond
String Builder = 127 millisecond

Run 5
Format = 1270 millisecond
Concatenation = 114 millisecond
String Builder = 126 millisecond

Forbidden You don't have permission to access /wp-login.php on this server

I had this same problem, and after temporarily deleting all my .htaccess files, then trying to modify them as suggested, and making sure all my files and folder permissions were set to 777, I still couldn't get it to work. I don't know why I couldn't access the file, but I was able to create a new file and access it no problem. So what I did was create a new file in /wp-admin/ called temp.php and pasted all the code from install.php into it. This allowed me to access the file. The only other thing I had to do was edit the code so that the form submitted to temp.php instead of install.php. After that, I could finish the install and everything worked.

<form id="setup" method="post" action="temp.php?step=2">

How can I edit a view using phpMyAdmin 3.2.4?

try running SHOW CREATE VIEW my_view_name in the sql portion of phpmyadmin and you will have a better idea of what is inside the view

How to pass arguments within docker-compose?

This can now be done as of docker-compose v2+ as part of the build object;

docker-compose.yml

version: '2'
services:
    my_image_name:
        build:
            context: . #current dir as build context
            args:
                var1: 1
                var2: c

See the docker compose docs.

In the above example "var1" and "var2" will be sent to the build environment.

Note: any env variables (specified by using the environment block) which have the same name as args variable(s) will override that variable.

How to pass credentials to the Send-MailMessage command for sending emails

in addition to UseSsl, you have to include smtp port 587 to make it work.

Send-MailMessage -SmtpServer smtp.gmail.com -Port 587 -Credential $credential -UseSsl -From '[email protected]' -To '[email protected]' -Subject 'TEST'

How to send a simple string between two programs using pipes?

Here's a sample:

int main()
{
    char buff[1024] = {0};
    FILE* cvt;
    int status;
    /* Launch converter and open a pipe through which the parent will write to it */
    cvt = popen("converter", "w");
    if (!cvt)
    {
        printf("couldn't open a pipe; quitting\n");
        exit(1)
    }
    printf("enter Fahrenheit degrees: " );
    fgets(buff, sizeof (buff), stdin); /*read user's input */
    /* Send expression to converter for evaluation */
    fprintf(cvt, "%s\n", buff);
    fflush(cvt);
    /* Close pipe to converter and wait for it to exit */
    status=pclose(cvt);
    /* Check the exit status of pclose() */
    if (!WIFEXITED(status))
        printf("error on closing the pipe\n");
    return 0;
}

The important steps in this program are:

  1. The popen() call which establishes the association between a child process and a pipe in the parent.
  2. The fprintf() call that uses the pipe as an ordinary file to write to the child process's stdin or read from its stdout.
  3. The pclose() call that closes the pipe and causes the child process to terminate.

How can I cast int to enum?

This is an flags enumeration aware safe convert method:

public static bool TryConvertToEnum<T>(this int instance, out T result)
  where T: Enum
{
  var enumType = typeof (T);
  var success = Enum.IsDefined(enumType, instance);
  if (success)
  {
    result = (T)Enum.ToObject(enumType, instance);
  }
  else
  {
    result = default(T);
  }
  return success;
}

What does void mean in C, C++, and C#?

Basically it means "nothing" or "no type"

There are 3 basic ways that void is used:

  1. Function argument: int myFunc(void) -- the function takes nothing.

  2. Function return value: void myFunc(int) -- the function returns nothing

  3. Generic data pointer: void* data -- 'data' is a pointer to data of unknown type, and cannot be dereferenced

Note: the void in a function argument is optional in C++, so int myFunc() is exactly the same as int myFunc(void), and it is left out completely in C#. It is always required for a return value.

Moving items around in an ArrayList

I came across this old question in my search for an answer, and I thought I would just post the solution I found in case someone else passes by here looking for the same.

For swapping 2 elements, Collections.swap is fine. But if we want to move more elements, there is a better solution that involves a creative use of Collections.sublist and Collections.rotate that I hadn't thought of until I saw it described here:

http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#rotate%28java.util.List,%20int%29

Here's a quote, but go there and read the whole thing for yourself too:

Note that this method can usefully be applied to sublists to move one or more elements within a list while preserving the order of the remaining elements. For example, the following idiom moves the element at index j forward to position k (which must be greater than or equal to j):

Collections.rotate(list.subList(j, k+1), -1);

What is the difference between Cloud Computing and Grid Computing?

Cloud Computing is For Service Oriented where as Grid Computing is for Application Oriented. Grid computing is used to build Virtual supercomputer using a middler ware to achieve a common task that can be shared among several resources. most probably this task will be kind of computing or data storage.

Cloud computing is providing services over the internet through several servers uses Virtualization.In cloud computing either you can provide service in three types Iaas , Paas, Saas . This will give you solution when you don't have any resources for a short time Business service over the Internet.

Namespace not recognized (even though it is there)

Perhaps the project's type table is in an incorrect state. I would try to remove/add the reference and if that didn't work, create another project, import my code, and see if that works.

I ran into this while using VS 2005, one would expect MS to have fixed that particular problem by now though..

show and hide divs based on radio button click

Here you can find exactly what you are looking for.

<div align="center">
  <input type="radio" name="name_radio1" id="id_radio1" value="value_radio1">Radio1
  <input type="radio" name="name_radio1" id="id_radio2" value="value_radio2">Radio2
</div>
 <br />
<div align="center" id="id_data" style="border:5">
  <div>this is div 1</div>
  <div>this is div 2</div>
  <div>this is div 3</div>
  <div>this is div 4</div>
</div>
<script src="jquery.js"></script>
<script>
 $(document).ready(function() {
 // show the table as soon as the DOM is ready
 $("#id_data").show();
 // shows the table on clicking the noted link
  $("#id_radio1").click(function() {
   $("#id_data").show("slow");
  });
 // hides the table on clicking the noted link
   $("#id_radio2").click(function() {
   $("#id_data").hide("fast");
   });
 });

  $(document).ready(function(){} – When document load.
  $("#id_data").show(); – shows div which contain id #id_data.
  $("#id_radio1").click(function() – Checks  radio button is clicked containing id #id_radio1.
  $("#id_data").show("slow"); – shows div containing id #id_data.
  $("#id_data").hide("fast"); -hides div when click on radio button containing id #id_data.

Thats it..

http://patelmilap.wordpress.com/2011/02/04/show-hide-div-on-click-using-jquery/

Multiple INSERT statements vs. single INSERT with multiple VALUES

The issue probably has to do with the time it takes to compile the query.

If you want to speed up the inserts, what you really need to do is wrap them in a transaction:

BEGIN TRAN;
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age) 
   VALUES ('6f3f7257-a3d8-4a78-b2e1-c9b767cfe1c1', 'First 0', 'Last 0', 0);
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age) 
   VALUES ('32023304-2e55-4768-8e52-1ba589b82c8b', 'First 1', 'Last 1', 1);
...
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age) 
   VALUES ('f34d95a7-90b1-4558-be10-6ceacd53e4c4', 'First 999', 'Last 999', 999);
COMMIT TRAN;

From C#, you might also consider using a table valued parameter. Issuing multiple commands in a single batch, by separating them with semicolons, is another approach that will also help.

How to mock static methods in c# using MOQ framework?

Moq (and other DynamicProxy-based mocking frameworks) are unable to mock anything that is not a virtual or abstract method.

Sealed/static classes/methods can only be faked with Profiler API based tools, like Typemock (commercial) or Microsoft Moles (free, known as Fakes in Visual Studio 2012 Ultimate /2013 /2015).

Alternatively, you could refactor your design to abstract calls to static methods, and provide this abstraction to your class via dependency injection. Then you'd not only have a better design, it will be testable with free tools, like Moq.

A common pattern to allow testability can be applied without using any tools altogether. Consider the following method:

public class MyClass
{
    public string[] GetMyData(string fileName)
    {
        string[] data = FileUtil.ReadDataFromFile(fileName);
        return data;
    }
}

Instead of trying to mock FileUtil.ReadDataFromFile, you could wrap it in a protected virtual method, like this:

public class MyClass
{
    public string[] GetMyData(string fileName)
    {
        string[] data = GetDataFromFile(fileName);
        return data;
    }

    protected virtual string[] GetDataFromFile(string fileName)
    {
        return FileUtil.ReadDataFromFile(fileName);
    }
}

Then, in your unit test, derive from MyClass and call it TestableMyClass. Then you can override the GetDataFromFile method to return your own test data.

Hope that helps.

How to call function that takes an argument in a Django template?

You cannot call a function that requires arguments in a template. Write a template tag or filter instead.

How do I get the value of a textbox using jQuery?

Noticed your comment about using it for email validation and needing a plugin, the validation plugin may help you, its located at http://bassistance.de/jquery-plugins/jquery-plugin-validation/, it comes with a e-mail rule as well.

Get the correct week number of a given date

Since there doesn't seem to be a .Net-culture that yields the correct ISO-8601 week number, I'd rather bypass the built-in week determination altogether, and do the calculation manually, instead of attempting to correct a partially correct result.

What I ended up with is the following extension method:

/// <summary>
/// Converts a date to a week number.
/// ISO 8601 week 1 is the week that contains the first Thursday that year.
/// </summary>
public static int ToIso8601Weeknumber(this DateTime date)
{
    var thursday = date.AddDays(3 - date.DayOfWeek.DayOffset());
    return (thursday.DayOfYear - 1) / 7 + 1;
}

/// <summary>
/// Converts a week number to a date.
/// Note: Week 1 of a year may start in the previous year.
/// ISO 8601 week 1 is the week that contains the first Thursday that year, so
/// if December 28 is a Monday, December 31 is a Thursday,
/// and week 1 starts January 4.
/// If December 28 is a later day in the week, week 1 starts earlier.
/// If December 28 is a Sunday, it is in the same week as Thursday January 1.
/// </summary>
public static DateTime FromIso8601Weeknumber(int weekNumber, int? year = null, DayOfWeek day = DayOfWeek.Monday)
{
    var dec28 = new DateTime((year ?? DateTime.Today.Year) - 1, 12, 28);
    var monday = dec28.AddDays(7 * weekNumber - dec28.DayOfWeek.DayOffset());
    return monday.AddDays(day.DayOffset());
}

/// <summary>
/// Iso8601 weeks start on Monday. This returns 0 for Monday.
/// </summary>
private static int DayOffset(this DayOfWeek weekDay)
{
    return ((int)weekDay + 6) % 7;
}

First of all, ((int)date.DayOfWeek + 6) % 7) determines the weekday number, 0=monday, 6=sunday.

date.AddDays(-((int)date.DayOfWeek + 6) % 7) determines the date of the monday preceiding the requested week number.

Three days later is the target thursday, which determines what year the week is in.

If you divide the (zero based) day-number within the year by seven (round down), you get the (zero based) week number in the year.

In c#, integer calculation results are round down implicitly.

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

push_back vs emplace_back

emplace_back shouldn't take an argument of type vector::value_type, but instead variadic arguments that are forwarded to the constructor of the appended item.

template <class... Args> void emplace_back(Args&&... args); 

It is possible to pass a value_type which will be forwarded to the copy constructor.

Because it forwards the arguments, this means that if you don't have rvalue, this still means that the container will store a "copied" copy, not a moved copy.

 std::vector<std::string> vec;
 vec.emplace_back(std::string("Hello")); // moves
 std::string s;
 vec.emplace_back(s); //copies

But the above should be identical to what push_back does. It is probably rather meant for use cases like:

 std::vector<std::pair<std::string, std::string> > vec;
 vec.emplace_back(std::string("Hello"), std::string("world")); 
 // should end up invoking this constructor:
 //template<class U, class V> pair(U&& x, V&& y);
 //without making any copies of the strings

How to copy files between two nodes using ansible

If you need to sync files between two remote nodes via ansible you can use this:

- name: synchronize between nodes
  environment:
    RSYNC_PASSWORD: "{{ input_user_password_if_needed }}"
  synchronize:
    src: rsync://user@remote_server:/module/
    dest: /destination/directory/
    // if needed
    rsync_opts:
       - "--include=what_needed"
       - "--exclude=**/**"
    mode: pull
    delegate_to: "{{ inventory_hostname }}"

when on remote_server you need to startup rsync with daemon mode. Simple example:

pid file = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock
log file = /var/log/rsync.log
port = port

[module]
path = /path/to/needed/directory/
uid = nobody
gid = nobody
read only = yes
list = yes
auth users = user
secrets file = /path/to/secret/file

How to print multiple variable lines in Java

You can do it with 1 printf:

System.out.printf("First Name: %s\nLast Name: %s",firstname, lastname);

How to add a tooltip to an svg graphic?

Can you use simply the SVG <title> element and the default browser rendering it conveys? (Note: this is not the same as the title attribute you can use on div/img/spans in html, it needs to be a child element named title)

_x000D_
_x000D_
rect {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  fill: #69c;_x000D_
  stroke: #069;_x000D_
  stroke-width: 5px;_x000D_
  opacity: 0.5_x000D_
}
_x000D_
<p>Mouseover the rect to see the tooltip on supporting browsers.</p>_x000D_
_x000D_
<svg xmlns="http://www.w3.org/2000/svg">_x000D_
  <rect>_x000D_
    <title>Hello, World!</title>_x000D_
  </rect>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

Alternatively, if you really want to show HTML in your SVG, you can embed HTML directly:

_x000D_
_x000D_
rect {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  fill: #69c;_x000D_
  stroke: #069;_x000D_
  stroke-width: 5px;_x000D_
  opacity: 0.5_x000D_
}_x000D_
_x000D_
foreignObject {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
svg div {_x000D_
  text-align: center;_x000D_
  line-height: 150px;_x000D_
}
_x000D_
<svg xmlns="http://www.w3.org/2000/svg">_x000D_
  <rect/>_x000D_
  <foreignObject>_x000D_
    <body xmlns="http://www.w3.org/1999/xhtml">_x000D_
      <div>_x000D_
        Hello, <b>World</b>!_x000D_
      </div>_x000D_
    </body>      _x000D_
  </foreignObject>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

…but then you'd need JS to turn the display on and off. As shown above, one way to make the label appear at the right spot is to wrap the rect and HTML in the same <g> that positions them both together.

To use JS to find where an SVG element is on screen, you can use getBoundingClientRect(), e.g. http://phrogz.net/svg/html_location_in_svg_in_html.xhtml

Allow all remote connections, MySQL

mysql> CREATE USER 'monty'@'192.168.%.%' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'192.168.%.%'

Rails: Why "sudo" command is not recognized?

sudo is a command for Linux so it cant be used in windows so you will get that error

How to recursively delete an entire directory with PowerShell 2.0?

To delete the complete contents including the folder structure use

get-childitem $dest -recurse | foreach ($_) {remove-item $_.fullname -recurse}

The -recurse added to remove-item ensures interactive prompts are disabled.

How to increase image size of pandas.DataFrame.plot in jupyter notebook?

Try figsize param in df.plot(figsize=(width,height)):

df = pd.DataFrame({"a":[1,2],"b":[1,2]})
df.plot(figsize=(3,3));

enter image description here

df = pd.DataFrame({"a":[1,2],"b":[1,2]})
df.plot(figsize=(5,3));

enter image description here

The size in figsize=(5,3) is given in inches per (width, height)

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.html

Python: how to print range a-z?

import string
print list(string.ascii_lowercase)
# ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

How can I display a messagebox in ASP.NET?

Try This Code:Successfully

Written on click Button.

ScriptManager.RegisterStartupScript(this, GetType(),"alertMessage", "alert('Record Inserted Successfully');", true);

jQuery - Getting the text value of a table cell in the same row as a clicked element

Nick has the right answer, but I wanted to add you could also get the cell data without needing the class name

var Something = $(this).closest('tr').find('td:eq(1)').text();

:eq(#) has a zero based index (link).

Reason for Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

Suppose I have the following table T:

a   b
--------
1   abc
1   def
1   ghi
2   jkl
2   mno
2   pqr

And I do the following query:

SELECT a, b
FROM T
GROUP BY a

The output should have two rows, one row where a=1 and a second row where a=2.

But what should the value of b show on each of these two rows? There are three possibilities in each case, and nothing in the query makes it clear which value to choose for b in each group. It's ambiguous.

This demonstrates the single-value rule, which prohibits the undefined results you get when you run a GROUP BY query, and you include any columns in the select-list that are neither part of the grouping criteria, nor appear in aggregate functions (SUM, MIN, MAX, etc.).

Fixing it might look like this:

SELECT a, MAX(b) AS x
FROM T
GROUP BY a

Now it's clear that you want the following result:

a   x
--------
1   ghi
2   pqr

What's the difference between "Write-Host", "Write-Output", or "[console]::WriteLine"?

Regarding [Console]::WriteLine() - you should use it if you are going to use pipelines in CMD (not in powershell). Say you want your ps1 to stream a lot of data to stdout, and some other utility to consume/transform it. If you use Write-Host in the script it will be much slower.

Delete statement in SQL is very slow

I read this article it was really helpful for troubleshooting any kind of inconveniences

https://support.microsoft.com/en-us/kb/224453

this is a case of waitresource KEY: 16:72057595075231744 (ab74b4daaf17)

-- First SQL Provider to find the SPID (Session ID)

-- Second Identify problem, check Status, Open_tran, Lastwaittype, waittype, and waittime
-- iMPORTANT Waitresource select * from sys.sysprocesses where spid = 57

select * from sys.databases where database_id=16

-- with Waitresource check this to obtain object id 
select * from sys.partitions where hobt_id=72057595075231744

select * from sys.objects where object_id=2105058535

Laravel is there a way to add values to a request array

you can use laravel helper and request() magic method ...

request()->request->add(['variable1'=>'value1','variable2'=>'value2']);

How to dynamically create CSS class in JavaScript and apply?

There is a light jQuery plugin which allows to generate CSS declarations: jQuery-injectCSS

In fact, it uses JSS (CSS described by JSON), but it's quite easy to handle in order to generate dynamic css stylesheets.

$.injectCSS({
    "#test": {
        height: 123
    }
});

Rails params explained?

On the Rails side, params is a method that returns an ActionController::Parameters object. See https://stackoverflow.com/a/44070358/5462485

How to decode Unicode escape sequences like "\u00ed" to proper UTF-8 encoded characters?

This is a sledgehammer approach to replacing raw UNICODE with HTML. I haven't seen any other place to put this solution, but I assume others have had this problem.

Apply this str_replace function to the RAW JSON, before doing anything else.

function unicode2html($str){
    $i=65535;
    while($i>0){
        $hex=dechex($i);
        $str=str_replace("\u$hex","&#$i;",$str);
        $i--;
     }
     return $str;
}

This won't take as long as you think, and this will replace ANY unicode with HTML.

Of course this can be reduced if you know the unicode types that are being returned in the JSON.

For example my code was getting lots of arrows and dingbat unicode. These are between 8448 an 11263. So my production code looks like:

$i=11263;
while($i>08448){
    ...etc...

You can look up the blocks of Unicode by type here: http://unicode-table.com/en/ If you know you're translating Arabic or Telegu or whatever, you can just replace those codes, not all 65,000.

You could apply this same sledgehammer to simple encoding:

 $str=str_replace("\u$hex",chr($i),$str);

How to reduce the image file size using PIL

See the thumbnail function of PIL's Image Module. You can use it to save smaller versions of files as various filetypes and if you're wanting to preserve as much quality as you can, consider using the ANTIALIAS filter when you do.

Other than that, I'm not sure if there's a way to specify a maximum desired size. You could, of course, write a function that might try saving multiple versions of the file at varying qualities until a certain size is met, discarding the rest and giving you the image you wanted.

Git branching: master vs. origin/master vs. remotes/origin/master

Take a clone of a remote repository and run git branch -a (to show all the branches git knows about). It will probably look something like this:

* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/master

Here, master is a branch in the local repository. remotes/origin/master is a branch named master on the remote named origin. You can refer to this as either origin/master, as in:

git diff origin/master..master

You can also refer to it as remotes/origin/master:

git diff remotes/origin/master..master

These are just two different ways of referring to the same thing (incidentally, both of these commands mean "show me the changes between the remote master branch and my master branch).

remotes/origin/HEAD is the default branch for the remote named origin. This lets you simply say origin instead of origin/master.

How I can delete in VIM all text from current line to end of file?

dG will delete from the current line to the end of file

dCtrl+End will delete from the cursor to the end of the file

But if this file is as large as you say, you may be better off reading the first few lines with head rather than editing and saving the file.

head hugefile > firstlines

(If you are on Windows you can use the Win32 port of head)

How can I get my Android device country code without using GPS?

The checked answer has deprecated code. You need to implement this:

String locale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    locale = context.getResources().getConfiguration().getLocales().get(0).getCountry();
} else {
    locale = context.getResources().getConfiguration().locale.getCountry();
}

what is the use of fflush(stdin) in c programming

it clears stdin buffer before reading. From the man page:

For output streams, fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underlying write function. For input streams, fflush() discards any buffered data that has been fetched from the underlying file, but has not been consumed by the application.

Note: This is Linux-specific, using fflush() on input streams is undefined by the standard, however, most implementations behave the same as in Linux.

How to .gitignore all files/folder in a folder, but not the folder itself?

You can't commit empty folders in git. If you want it to show up, you need to put something in it, even just an empty file.

For example, add an empty file called .gitkeep to the folder you want to keep, then in your .gitignore file write:

# exclude everything
somefolder/*

# exception to the rule
!somefolder/.gitkeep 

Commit your .gitignore and .gitkeep files and this should resolve your issue.

How to fit a smooth curve to my data in R?

LOESS is a very good approach, as Dirk said.

Another option is using Bezier splines, which may in some cases work better than LOESS if you don't have many data points.

Here you'll find an example: http://rosettacode.org/wiki/Cubic_bezier_curves#R

# x, y: the x and y coordinates of the hull points
# n: the number of points in the curve.
bezierCurve <- function(x, y, n=10)
    {
    outx <- NULL
    outy <- NULL

    i <- 1
    for (t in seq(0, 1, length.out=n))
        {
        b <- bez(x, y, t)
        outx[i] <- b$x
        outy[i] <- b$y

        i <- i+1
        }

    return (list(x=outx, y=outy))
    }

bez <- function(x, y, t)
    {
    outx <- 0
    outy <- 0
    n <- length(x)-1
    for (i in 0:n)
        {
        outx <- outx + choose(n, i)*((1-t)^(n-i))*t^i*x[i+1]
        outy <- outy + choose(n, i)*((1-t)^(n-i))*t^i*y[i+1]
        }

    return (list(x=outx, y=outy))
    }

# Example usage
x <- c(4,6,4,5,6,7)
y <- 1:6
plot(x, y, "o", pch=20)
points(bezierCurve(x,y,20), type="l", col="red")

Swift - Integer conversion to Hours/Minutes/Seconds

I have built a mashup of existing answers to simplify everything and reduce the amount of code needed for Swift 3.

func hmsFrom(seconds: Int, completion: @escaping (_ hours: Int, _ minutes: Int, _ seconds: Int)->()) {

        completion(seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)

}

func getStringFrom(seconds: Int) -> String {

    return seconds < 10 ? "0\(seconds)" : "\(seconds)"
}

Usage:

var seconds: Int = 100

hmsFrom(seconds: seconds) { hours, minutes, seconds in

    let hours = getStringFrom(seconds: hours)
    let minutes = getStringFrom(seconds: minutes)
    let seconds = getStringFrom(seconds: seconds)

    print("\(hours):\(minutes):\(seconds)")                
}

Prints:

00:01:40

bootstrap 4 file input doesn't show the file name

If you want you can use the recommended Bootstrap plugin to dynamize your custom file input: https://www.npmjs.com/package/bs-custom-file-input

This plugin can be use with or without jQuery and works with React an Angular