Programs & Examples On #Session state server

Shall we always use [unowned self] inside closure in Swift

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let controller = storyboard.instantiateViewController(withIdentifier: "AnotherViewController")
        self.navigationController?.pushViewController(controller, animated: true)

    }

}



import UIKit
class AnotherViewController: UIViewController {

    var name : String!

    deinit {
        print("Deint AnotherViewController")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        print(CFGetRetainCount(self))

        /*
            When you test please comment out or vice versa

         */

//        // Should not use unowned here. Because unowned is used where not deallocated. or gurranted object alive. If you immediate click back button app will crash here. Though there will no retain cycles
//        clouser(string: "") { [unowned self] (boolValue)  in
//            self.name = "some"
//        }
//


//
//        // There will be a retain cycle. because viewcontroller has a strong refference to this clouser and as well as clouser (self.name) has a strong refferennce to the viewcontroller. Deint AnotherViewController will not print
//        clouser(string: "") { (boolValue)  in
//            self.name = "some"
//        }
//
//


//        // no retain cycle here. because viewcontroller has a strong refference to this clouser. But clouser (self.name) has a weak refferennce to the viewcontroller. Deint AnotherViewController will  print. As we forcefully made viewcontroller weak so its now optional type. migh be nil. and we added a ? (self?)
//
//        clouser(string: "") { [weak self] (boolValue)  in
//            self?.name = "some"
//        }


        // no retain cycle here. because viewcontroller has a strong refference to this clouser. But clouser nos refference to the viewcontroller. Deint AnotherViewController will  print. As we forcefully made viewcontroller weak so its now optional type. migh be nil. and we added a ? (self?)

        clouser(string: "") {  (boolValue)  in
            print("some")
            print(CFGetRetainCount(self))

        }

    }


    func clouser(string: String, completion: @escaping (Bool) -> ()) {
        // some heavy task
        DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
            completion(true)
        }

    }

}

If you do not sure about [unowned self] then use [weak self]

Call one constructor from another

Constructor chaining i.e you can use "Base" for Is a relationship and "This" you can use for same class, when you want call multiple Constructor in single call.

  class BaseClass
{
    public BaseClass():this(10)
    {
    }
    public BaseClass(int val)
    {
    }
}
    class Program
    {
        static void Main(string[] args)
        {
            new BaseClass();
            ReadLine();
        }
    }

How to pass parameters in GET requests with jQuery

The data property allows you to send in a string. On your server side code, accept it as a string argument name "myVar" and then you can parse it out.

$.ajax({
    url: "ajax.aspx",
    data: [myVar = {id: 4, email: 'emailaddress', myArray: [1, 2, 3]}];
    success: function(response) {
    //Do Something
    },
    error: function(xhr) {
    //Do Something to handle error
    }
});

Saving ssh key fails

In Windows I had to create the environment variable HOME pointing to my user profile first (C:\Users\<name>) or whatever directory you prefer.

Then start a new command line window, create a a .ssh directory in your user profile or choosen diretory using mkdir ".ssh" command.

After doing that I was able to use the ssh-keygen without any path problems.

Can I set enum start value in Java?

Java enums are not like C or C++ enums, which are really just labels for integers.

Java enums are implemented more like classes - and they can even have multiple attributes.

public enum Ids {
    OPEN(100), CLOSE(200);

    private final int id;
    Ids(int id) { this.id = id; }
    public int getValue() { return id; }
}

The big difference is that they are type-safe which means you don't have to worry about assigning a COLOR enum to a SIZE variable.

See http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html for more.

Constructor overload in TypeScript

Regarding constructor overloads one good alternative would be to implement the additional overloads as static factory methods. I think its more readable and simple than checking for all possible argument combinations at the constructor. Here is a simple example:

function calculateAge(birthday): number {
  return new Date().getFullYear() - birthday;
}

class Person {
  static fromData(data: PersonData): Person {
    const { first, last, birthday, gender = 'M' } = data;
    return new this(
      `${last}, ${first}`,
      calculateAge(birthday),
      gender,
    );
  }

  constructor(
    public fullName: string,
    public age: number,
    public gender: 'M' | 'F',
  ) {}

  toString(): string {
    return `Hello, my name is ${this.fullName} and I'm a ${this.age}yo ${this.gender}`;
  }
}

interface PersonData {
  first: string;
  last: string;
  birthday: string;
  gender?: 'M' | 'F';
}


const personA = new Person('Doe, John', 31, 'M');
console.log(personA.toString());
const personB = Person.fromData({
  first: 'Jane',
  last: 'Smith',
  birthday: '1986',
  gender: 'F',
});
console.log(personB.toString());

Method overloading in TypeScript isn't for real, let's say, as it would require too much compiler-generated code and the core team try to avoid that at all costs. Currently the main reason for method overloading to be present on the language is to provide a way to write declarations for libraries with magic arguments in their API. Since you'll need to do all the heavy-lifting by yourself to handle different sets of arguments I don't see much advantage in using overloads instead of separated methods.

PHP form - on submit stay on same page

You can use the # action in a form action:

<?php
    if(isset($_POST['SubmitButton'])){ // Check if form was submitted

        $input = $_POST['inputText']; // Get input text
        $message = "Success! You entered: " . $input;
    }
?>

<html>
    <body>
        <form action="#" method="post">
            <?php echo $message; ?>
            <input type="text" name="inputText"/>
            <input type="submit" name="SubmitButton"/>
        </form>
    </body>
</html>

Failed to resolve: com.google.firebase:firebase-core:16.0.1

This is rare, but there is a chance your project's gradle offline mode is enable, disable offline mode with the following steps;

  • In android studio, locate the file tab of the header and click
  • In the drop own menu, select settings
  • In the dialog produced, select "Build, Execution, Deploy" and then select "Gradle"
  • Finally uncheck the "offline work" check box and apply changes

If this doesn't work leave a comment describing your Logcat response and i'll try to help more.

Remove file from SVN repository without deleting local copy

In TortoiseSVN, you can also Shift + right-click to get a menu that includes "Delete (keep local)".

What is the purpose of the "final" keyword in C++11 for functions?

The final keyword allows you to declare a virtual method, override it N times, and then mandate that 'this can no longer be overridden'. It would be useful in restricting use of your derived class, so that you can say "I know my super class lets you override this, but if you want to derive from me, you can't!".

struct Foo
{
   virtual void DoStuff();
}

struct Bar : public Foo
{
   void DoStuff() final;
}

struct Babar : public Bar
{
   void DoStuff(); // error!
}

As other posters pointed out, it cannot be applied to non-virtual functions.

One purpose of the final keyword is to prevent accidental overriding of a method. In my example, DoStuff() may have been a helper function that the derived class simply needs to rename to get correct behavior. Without final, the error would not be discovered until testing.

Git push error: Unable to unlink old (Permission denied)

This is an old question, but this may help Mac users.

If you are copying files from Time Machine manually, instead of restoring them through Time Machine, it'll add ACLs to everything, which can mess up your permissions.

For example, the section in this article that says "How to Fix Mac OS X File Permissions" shows that "everyone" has custom permissions, which messes it all up:

Bad permissions, from http://dreamlight.com/how-to-fix-mac-os-x-file-permissions

You need to remove the ACLs from those directories/files. This Super User answer goes into it, but here's the command:

sudo chmod -RN .

Then you can make sure your directories and files have the proper permissions. I use 750 for directories and 644 for files.

LINQ Orderby Descending Query

You need to choose a Property to sort by and pass it as a lambda expression to OrderByDescending

like:

.OrderByDescending(x => x.Delivery.SubmissionDate);

Really, though the first version of your LINQ statement should work. Is t.Delivery.SubmissionDate actually populated with valid dates?

Is embedding background image data into CSS as Base64 good or bad practice?

This answer is out of date and shouldn't be used.

1) Average latency is much faster on mobile in 2017. https://opensignal.com/reports/2016/02/usa/state-of-the-mobile-network

2) HTTP2 multiplexes https://http2.github.io/faq/#why-is-http2-multiplexed

"Data URIs" should definitely be considered for mobile sites. HTTP access over cellular networks comes with higher latency per request/response. So there are some use cases where jamming your images as data into CSS or HTML templates could be beneficial on mobile web apps. You should measure usage on a case-by-case basis -- I'm not advocating that data URIs should be used everywhere in a mobile web app.

Note that mobile browsers have limitations on total size of files that can be cached. Limits for iOS 3.2 were pretty low (25K per file), but are getting larger (100K) for newer versions of Mobile Safari. So be sure to keep an eye on your total file size when including data URIs.

http://www.yuiblog.com/blog/2010/06/28/mobile-browser-cache-limits/

Use getElementById on HTMLElement instead of HTMLDocument

Sub Scrape()
    Dim Browser As InternetExplorer
    Dim Document As htmlDocument
    Dim Elements As IHTMLElementCollection
    Dim Element As IHTMLElement

    Set Browser = New InternetExplorer
    Browser.Visible = True
    Browser.navigate "http://www.stackoverflow.com"

    Do While Browser.Busy And Not Browser.readyState = READYSTATE_COMPLETE
        DoEvents
    Loop

    Set Document = Browser.Document

    Set Elements = Document.getElementById("hmenus").getElementsByTagName("li")
    For Each Element In Elements
        Debug.Print Element.innerText
        'Questions
        'Tags
        'Users
        'Badges
        'Unanswered
        'Ask Question
    Next Element

    Set Document = Nothing
    Set Browser = Nothing
End Sub

SQL query with avg and group by

As I understand, you want the average value for each id at each pass. The solution is

SELECT id, pass, avg(value) FROM data_r1
GROUP BY id, pass;

How to detect browser using angularjs?

you should use conditional comments

<!--[if IE 9]>
<script type="text/javascript">
    window.isIE9 = true;
</script>
<![endif]-->

You can then check for $window.isIE9 in your controllers.

Why must wait() always be in synchronized block

Thread wait on the monitoring object (object used by synchronization block), There can be n number of monitoring object in whole journey of a single thread. If Thread wait outside the synchronization block then there is no monitoring object and also other thread notify to access for the monitoring object, so how would the thread outside the synchronization block would know that it has been notified. This is also one of the reason that wait(), notify() and notifyAll() are in object class rather than thread class.

Basically the monitoring object is common resource here for all the threads, and monitoring objects can only be available in synchronization block.

class A {
   int a = 0;
  //something......
  public void add() {
   synchronization(this) {
      //this is your monitoring object and thread has to wait to gain lock on **this**
       }
  }

SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443

A simple restart fixed it for me. I'm not sure what was the problem since I work with so much software but I have a feeling it was the VPN software or maybe the fact I put my laptop in sleep a lot and some file was corrupted. I really don't know but the restart fixed it.

Convert a file path to Uri in Android

Normal answer for this question if you really want to get something like content//media/external/video/media/18576 (e.g. for your video mp4 absolute path) and not just file///storage/emulated/0/DCIM/Camera/20141219_133139.mp4:

MediaScannerConnection.scanFile(this,
          new String[] { file.getAbsolutePath() }, null,
          new MediaScannerConnection.OnScanCompletedListener() {
      public void onScanCompleted(String path, Uri uri) {
          Log.i("onScanCompleted", uri.getPath());
      }
 });

Accepted answer is wrong (cause it will not return content//media/external/video/media/*)

Uri.fromFile(file).toString() only returns something like file///storage/emulated/0/* which is a simple absolute path of a file on the sdcard but with file// prefix (scheme)

You can also get content uri using MediaStore database of Android

TEST (what returns Uri.fromFile and what returns MediaScannerConnection):

File videoFile = new File("/storage/emulated/0/video.mp4");

Log.i(TAG, Uri.fromFile(videoFile).toString());

MediaScannerConnection.scanFile(this, new String[] { videoFile.getAbsolutePath() }, null,
        (path, uri) -> Log.i(TAG, uri.toString()));

Output:

I/Test: file:///storage/emulated/0/video.mp4

I/Test: content://media/external/video/media/268927

How do I change column default value in PostgreSQL?

'SET' is forgotten

ALTER TABLE ONLY users ALTER COLUMN lang SET DEFAULT 'en_GB';

jQuery using append with effects

Set the appended div to be hidden initially through css visibility:hidden.

Using querySelectorAll to retrieve direct children

I'd have gone with

var myFoo = document.querySelectorAll("#myDiv > .foo");
var myDiv = myFoo.parentNode;

Check if a string within a list contains a specific string with Linq

If yoou use Contains, you could get false positives. Suppose you have a string that contains such text: "My text data Mdd LH" Using Contains method, this method will return true for call. The approach is use equals operator:

bool exists = myStringList.Any(c=>c == "Mdd LH")

composer laravel create project

composer create-project laravel/laravel ProjectName 

Node.js/Express routing with get params

Your route isn't ok, it should be like this (with ':')

app.get('/documents/:format/:type', function (req, res) {
   var format = req.params.format,
       type = req.params.type;
});

Also you cannot interchange parameter order unfortunately. For more information on req.params (and req.query) check out the api reference here.

Check if object is a jQuery object

You can use the instanceof operator:

if (obj instanceof jQuery){
    console.log('object is jQuery');
}

Explanation: the jQuery function (aka $) is implemented as a constructor function. Constructor functions are to be called with the new prefix.

When you call $(foo), internally jQuery translates this to new jQuery(foo)1. JavaScript proceeds to initialize this inside the constructor function to point to a new instance of jQuery, setting it's properties to those found on jQuery.prototype (aka jQuery.fn). Thus, you get a new object where instanceof jQuery is true.


1It's actually new jQuery.prototype.init(foo): the constructor logic has been offloaded to another constructor function called init, but the concept is the same.

How do I turn a python datetime into a string, with readable format date?

very old question, i know. but with the new f-strings (starting from python 3.6) there are fresh options. so here for completeness:

from datetime import datetime

dt = datetime.now()

# str.format
strg = '{:%B %d, %Y}'.format(dt)
print(strg)  # July 22, 2017

# datetime.strftime
strg = dt.strftime('%B %d, %Y')
print(strg)  # July 22, 2017

# f-strings in python >= 3.6
strg = f'{dt:%B %d, %Y}'
print(strg)  # July 22, 2017

strftime() and strptime() Behavior explains what the format specifiers mean.

Fastest way to get the first n elements of a List into an Array

Option 3

Iterators are faster than using the get operation, since the get operation has to start from the beginning if it has to do some traversal. It probably wouldn't make a difference in an ArrayList, but other data structures could see a noticeable speed difference. This is also compatible with things that aren't lists, like sets.

String[] out = new String[n];
Iterator<String> iterator = in.iterator();
for (int i = 0; i < n && iterator.hasNext(); i++)
    out[i] = iterator.next();

How to reset db in Django? I get a command 'reset' not found error

python manage.py flush

deleted old db contents,

Don't forget to create new superuser:

python manage.py createsuperuser

Location of GlassFish Server Logs

Locate the installation path of GlassFish. Then move to domains/domain-dir/logs/ and you'll find there the log files. If you have created the domain with NetBeans, the domain-dir is most probably called domain1.

See this link for the official GlassFish documentation about logging.

What Content-Type value should I send for my XML sitemap?

Other answers here address the general question of what the proper Content-Type for an XML response is, and conclude (as with What's the difference between text/xml vs application/xml for webservice response) that both text/xml and application/xml are permissible. However, none address whether there are any rules specific to sitemaps.

Answer: there aren't. The sitemap spec is https://www.sitemaps.org, and using Google site: searches you can confirm that it does not contain the words or phrases mime, mimetype, content-type, application/xml, or text/xml anywhere. In other words, it is entirely silent on the topic of what Content-Type should be used for serving sitemaps.

In the absence of any commentary in the sitemap spec directly addressing this question, we can safely assume that the same rules apply as when choosing the Content-Type of any other XML document - i.e. that it may be either text/xml or application/xml.

File uploading with Express 4.0: req.files undefined

multer is a middleware which handles “multipart/form-data” and magically & makes the uploaded files and form data available to us in request as request.files and request.body.

installing multer :- npm install multer --save

in .html file:-

<form method="post" enctype="multipart/form-data" action="/upload">
    <input type="hidden" name="msgtype" value="2"/>
    <input type="file" name="avatar" />
    <input type="submit" value="Upload" />
</form>

in .js file:-

var express = require('express');
var multer = require('multer');
var app = express();
var server = require('http').createServer(app);
var port = process.env.PORT || 3000;
var upload = multer({ dest: 'uploads/' });

app.use(function (req, res, next) {
  console.log(req.files); // JSON Object
  next();
});

server.listen(port, function () {
  console.log('Server successfully running at:-', port);
});

app.get('/', function(req, res) {
  res.sendFile(__dirname + '/public/file-upload.html');
})

app.post('/upload', upload.single('avatar'),  function(req, res) {
  console.log(req.files); // JSON Object
});

Hope this helps!

How do you clear the focus in javascript?

Answer: document.activeElement

To do what you want, use document.activeElement.blur()

If you need to support Firefox 2, you can also use this:

function onElementFocused(e)
{
    if (e && e.target)
        document.activeElement = e.target == document ? null : e.target;
} 

if (document.addEventListener) 
    document.addEventListener("focus", onElementFocused, true);

How to insert data to MySQL having auto incremented primary key?

Check out this post

According to it

No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign NULL or 0 to the column to generate sequence numbers.

How to name Dockerfiles

If you want to use the autobuilder at hub.docker.com, it has to be Dockerfile. So there :)

Increase number of axis ticks

Additionally,

ggplot(dat, aes(x,y)) +
geom_point() +
scale_x_continuous(breaks = seq(min(dat$x), max(dat$x), by = 0.05))

Works for binned or discrete scaled x-axis data (I.e., rounding not necessary).

Converting java.util.Properties to HashMap<String,String>

If you know that your Properties object only contains <String, String> entries, you can resort to a raw type:

Properties properties = new Properties();
Map<String, String> map = new HashMap<String, String>((Map) properties);

How to retrieve form values from HTTPPOST, dictionary or?

If you want to get the form data directly from Http request, without any model bindings or FormCollection you can use this:

[HttpPost] 
public ActionResult SubmitAction() {

    // This will return an string array of all keys in the form.
    // NOTE: you specify the keys in form by the name attributes e.g:
    // <input name="this is the key" value="some value" type="test" />
    var keys = Request.Form.AllKeys;

    // This will return the value for the keys.
    var value1 = Request.Form.Get(keys[0]);
    var value2 = Request.Form.Get(keys[1]);
}

What is a Data Transfer Object (DTO)?

Data transfer object (DTO) describes “an object that carries data between processes” (Wikipedia) or an “object that is used to encapsulate data, and send it from one subsystem of an application to another” (Stack Overflow answer).

Insert a line at specific line number with sed or awk

the awk answer

awk -v n=8 -v s="Project_Name=sowstest" 'NR == n {print s} {print}' file > file.new

Where can I set path to make.exe on Windows?

The path is in the registry but usually you edit through this interface:

  1. Go to Control Panel -> System -> System settings -> Environment Variables.
  2. Scroll down in system variables until you find PATH.
  3. Click edit and change accordingly.
  4. BE SURE to include a semicolon at the end of the previous as that is the delimiter, i.e. c:\path;c:\path2
  5. Launch a new console for the settings to take effect.

How to convert list to string

By using ''.join

list1 = ['1', '2', '3']
str1 = ''.join(list1)

Or if the list is of integers, convert the elements before joining them.

list1 = [1, 2, 3]
str1 = ''.join(str(e) for e in list1)

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.

Find and replace with a newline in Visual Studio Code

Also note, after hitting the regex icon, to actually replace \n text with a newline, I had to use \\n as search and \n as replace.

Stop floating divs from wrapping

You want to define min-width on row so when it browser is re-sized it does not go below that and wrap.

How to Call a JS function using OnClick event

Using the onclick attribute or applying a function to your JS onclick properties will erase your onclick initialization in <head>.

What you need to do is add click events on your button. To do that you’ll need the addEventListener or attachEvent (IE) method.

<!DOCTYPE html>
<html>
<head>
    <script>
        function addEvent(obj, event, func) {
            if (obj.addEventListener) {
                obj.addEventListener(event, func, false);
                return true;
            } else if (obj.attachEvent) {
                obj.attachEvent('on' + event, func);
            } else {
                var f = obj['on' + event];
                obj['on' + event] = typeof f === 'function' ? function() {
                    f();
                    func();
                } : func
            }
        }

        function f1()
        {
            alert("f1 called");
            //form validation that recalls the page showing with supplied inputs.    
        }
    </script>
</head>
<body>
    <form name="form1" id="form1" method="post">
        State: <select id="state ID">
        <option></option>
        <option value="ap">ap</option>
        <option value="bp">bp</option>
        </select>
    </form>

    <table><tr><td id="Save" onclick="f1()">click</td></tr></table>

    <script>
        addEvent(document.getElementById('Save'), 'click', function() {
            alert('hello');
        });
    </script>
</body>
</html>

Understanding Apache's access log

I also don't under stand what the "-" means after the 200 140 section of the log

That value corresponds to the referer as described by Joachim. If you see a dash though, that means that there was no referer value to begin with (eg. the user went straight to a specific destination, like if he/she typed a URL in their browser)

Access item in a list of lists

List1 = [[10,-13,17],[3,5,1],[13,11,12]]

num = 50
for i in List1[0]:num -= i
print num

Recursively find all files newer than a given time

This is a bit circuitous because touch doesn't take a raw time_t value, but it should do the job pretty safely in a script. (The -r option to date is present in MacOS X; I've not double-checked GNU.) The 'time' variable could be avoided by writing the command substitution directly in the touch command line.

time=$(date -r 1312603983 '+%Y%m%d%H%M.%S')
marker=/tmp/marker.$$
trap "rm -f $marker; exit 1" 0 1 2 3 13 15
touch -t $time $marker
find . -type f -newer $marker
rm -f $marker
trap 0

How to get a random number between a float range?

Use random.uniform(a, b):

>>> random.uniform(1.5, 1.9)
1.8733202628557872

Plot multiple boxplot in one graph

In base R a formula interface with interactions (:) can be used to achieve this.

df <- read.csv("~/Desktop/TestData.csv")
df <- data.frame(stack(df[,-1]), Label=df$Label) # reshape to long format

boxplot(values ~ Label:ind, data=df, col=c("red", "limegreen"), las=2)

example

How can I multiply all items in a list together with Python?

I would use the numpy.prod to perform the task. See below.

import numpy as np
mylist = [1, 2, 3, 4, 5, 6] 
result = np.prod(np.array(mylist))  

How to center horizontal table-cell

Short snippet for future visitors - how to center horizontal table-cell (+ vertically)

_x000D_
_x000D_
html, body {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.tab {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.cell {_x000D_
  display: table-cell;_x000D_
  vertical-align: middle;_x000D_
  text-align: center; /* the key */_x000D_
  background-color: #EEEEEE;_x000D_
}_x000D_
_x000D_
.content {_x000D_
  display: inline-block; /* important !! */_x000D_
  width: 100px;_x000D_
  background-color: #00FF00;_x000D_
}
_x000D_
<div class="tab">_x000D_
  <div class="cell">_x000D_
    <div class="content" id="a">_x000D_
      <p>Content</p>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

HTML5 Canvas vs. SVG vs. div

To add to this, I've been doing a diagram application, and initially started out with canvas. The diagram consists of many nodes, and they can get quite big. The user can drag elements in the diagram around.

What I found was that on my Mac, for very large images, SVG is superior. I have a MacBook Pro 2013 13" Retina, and it runs the fiddle below quite well. The image is 6000x6000 pixels, and has 1000 objects. A similar construction in canvas was impossible to animate for me when the user was dragging objects around in the diagram.

On modern displays you also have to account for different resolutions, and here SVG gives you all of this for free.

Fiddle: http://jsfiddle.net/knutsi/PUcr8/16/

Fullscreen: http://jsfiddle.net/knutsi/PUcr8/16/embedded/result/

var wiggle_factor = 0.0;
nodes = [];

// create svg:
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute('style', 'border: 1px solid black');
svg.setAttribute('width', '6000');
svg.setAttribute('height', '6000');

svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink",
    "http://www.w3.org/1999/xlink");

document.body.appendChild(svg);


function makeNode(wiggle) {
    var node = document.createElementNS("http://www.w3.org/2000/svg", "g");
    var node_x = (Math.random() * 6000);
    var node_y = (Math.random() * 6000);
    node.setAttribute("transform", "translate(" + node_x + ", " + node_y +")");

    // circle:
    var circ = document.createElementNS("http://www.w3.org/2000/svg", "circle");
    circ.setAttribute( "id","cir")
    circ.setAttribute( "cx", 0 + "px")
    circ.setAttribute( "cy", 0 + "px")
    circ.setAttribute( "r","100px");
    circ.setAttribute('fill', 'red');
    circ.setAttribute('pointer-events', 'inherit')

    // text:
    var text = document.createElementNS("http://www.w3.org/2000/svg", "text");
    text.textContent = "This is a test! ÅÆØ";

    node.appendChild(circ);
    node.appendChild(text);

    node.x = node_x;
    node.y = node_y;

    if(wiggle)
        nodes.push(node)
    return node;
}

// populate with 1000 nodes:
for(var i = 0; i < 1000; i++) {
    var node = makeNode(true);
    svg.appendChild(node);
}

// make one mapped to mouse:
var bnode = makeNode(false);
svg.appendChild(bnode);

document.body.onmousemove=function(event){
    bnode.setAttribute("transform","translate(" +
        (event.clientX + window.pageXOffset) + ", " +
        (event.clientY + window.pageYOffset) +")");
};

setInterval(function() {
    wiggle_factor += 1/60;
    nodes.forEach(function(node) {

        node.setAttribute("transform", "translate(" 
                          + (Math.sin(wiggle_factor) * 200 + node.x) 
                          + ", " 
                          + (Math.sin(wiggle_factor) * 200 + node.y) 
                          + ")");        
    })
},1000/60);

Node.js get file extension

I do think mapping the Content-Type header in the request will also work. This will work even for cases when you upload a file with no extension. (when filename does not have an extension in the request)

Assume you are sending your data using HTTP POST:

POST /upload2 HTTP/1.1
Host: localhost:7098
Connection: keep-alive
Content-Length: 1047799
Accept: */*
Origin: http://localhost:63342
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML,    like Gecko) Chrome/51.0.2704.106 Safari/537.36
Content-Type: multipart/form-data; boundary=----   WebKitFormBoundaryPDULZN8DYK3VppPp
Referer: http://localhost:63342/Admin/index.html? _ijt=3a6a054pasorvrljf8t8ea0j4h
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,az;q=0.6,tr;q=0.4
Request Payload
------WebKitFormBoundaryPDULZN8DYK3VppPp
Content-Disposition: form-data; name="image"; filename="blob"
Content-Type: image/png


------WebKitFormBoundaryPDULZN8DYK3VppPp--

Here name Content-Type header contains the mime type of the data. Mapping this mime type to an extension will get you the file extension :).

Restify BodyParser converts this header in to a property with name type

File {
  domain: 
   Domain {
     domain: null,
     _events: { .... },
     _eventsCount: 1,
     _maxListeners: undefined,
     members: [ ... ] },
  _events: {},
  _eventsCount: 0,
  _maxListeners: undefined,
  size: 1047621,
  path: '/tmp/upload_2a4ac9ef22f7156180d369162ef08cb8',
  name: 'blob',
  **type: 'image/png'**,
  hash: null,
  lastModifiedDate: Wed Jul 20 2016 16:12:21 GMT+0300 (EEST),
  _writeStream: 
  WriteStream {
   ... },
     writable: true,
     domain: 
     Domain {
        ...
     },
      _events: {},
      _eventsCount: 0,
     _maxListeners: undefined,
     path: '/tmp/upload_2a4ac9ef22f7156180d369162ef08cb8',
     fd: null,
     flags: 'w',
     mode: 438,
     start: undefined,
     pos: undefined,
     bytesWritten: 1047621,
     closed: true } 
}

You can use this header and do the extension mapping (substring etc ...) manually, but there are also ready made libraries for this. Below two were the top results when i did a google search

  • mime
  • mime-types

and their usage is simple as well:

 app.post('/upload2', function (req, res) {
  console.log(mime.extension(req.files.image.type));
 }

above snippet will print png to console.

makefile:4: *** missing separator. Stop

This is because tab is replaced by spaces. To disable this feature go to

gedit->edit->preferences->editor

and remove check for

"replace tab with space"

Can you use Microsoft Entity Framework with Oracle?

Oracle have announced a "statement of direction" for ODP.net and the Entity Framework:

In summary, ODP.Net beta around the end of 2010, production sometime in 2011.

Setting Elastic search limit to "unlimited"

use the scan method e.g.

 curl -XGET 'localhost:9200/_search?search_type=scan&scroll=10m&size=50' -d '
 {
    "query" : {
       "match_all" : {}
     }
 }

see here

Effect of NOLOCK hint in SELECT statements

  • The answer is Yes if the query is run multiple times at once, because each transaction won't need to wait for the others to complete. However, If the query is run once on its own then the answer is No.

  • Yes. There's a significant probability that careful use of WITH(NOLOCK) will speed up your database overall. It means that other transactions won't have to wait for this SELECT statement to finish, but on the other hand, other transactions will slow down as they're now sharing their processing time with a new transaction.

Be careful to only use WITH (NOLOCK) in SELECT statements on tables that have a clustered index.

WITH(NOLOCK) is often exploited as a magic way to speed up database read transactions.

The result set can contain rows that have not yet been committed, that are often later rolled back.

If WITH(NOLOCK) is applied to a table that has a non-clustered index then row-indexes can be changed by other transactions as the row data is being streamed into the result-table. This means that the result-set can be missing rows or display the same row multiple times.

READ COMMITTED adds an additional issue where data is corrupted within a single column where multiple users change the same cell simultaneously.

Can you put two conditions in an xslt test attribute?

From XML.com:

Like xsl:if instructions, xsl:when elements can have more elaborate contents between their start- and end-tags—for example, literal result elements, xsl:element elements, or even xsl:if and xsl:choose elements—to add to the result tree. Their test expressions can also use all the tricks and operators that the xsl:if element's test attribute can use, such as and, or, and function calls, to build more complex boolean expressions.

Sort an array in Java

Add the Line before println and your array gets sorted

Arrays.sort( array );

Smart way to truncate long strings

Here's my solution, which has a few improvements over other suggestions:

String.prototype.truncate = function(){
    var re = this.match(/^.{0,25}[\S]*/);
    var l = re[0].length;
    var re = re[0].replace(/\s$/,'');
    if(l < this.length)
        re = re + "&hellip;";
    return re;
}

// "This is a short string".truncate();
"This is a short string"

// "Thisstringismuchlongerthan25characters".truncate();
"Thisstringismuchlongerthan25characters"

// "This string is much longer than 25 characters and has spaces".truncate();
"This string is much longer&hellip;"

It:

  • Truncates on the first space after 25 characters
  • Extends the JavaScript String object, so it can be used on (and chained to) any string.
  • Will trim the string if truncation results in a trailing space;
  • Will add the unicode hellip entity (ellipsis) if the truncated string is longer than 25 characters

How to enable authentication on MongoDB through Docker?

use this images to fix:

With docker-compose.yml

services:
  db:
    image: aashreys/mongo-auth:latest
    environment:
      - AUTH=yes
      - MONGODB_ADMIN_USER=admin
      - MONGODB_ADMIN_PASS=admin123
      - MONGODB_APPLICATION_DATABASE=sample
      - MONGODB_APPLICATION_USER=aashrey
      - MONGODB_APPLICATION_PASS=admin123
    ports:
      - "27017:27017"
     // more configuration

How do you rotate a two dimensional array?

C# code to rotate [n,m] 2D arrays 90 deg right

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MatrixProject
{
    // mattrix class

    class Matrix{
        private int rows;
        private int cols;
        private int[,] matrix;

        public Matrix(int n){
            this.rows = n;
            this.cols = n;
            this.matrix = new int[this.rows,this.cols];

        }

        public Matrix(int n,int m){
            this.rows = n;
            this.cols = m;

            this.matrix = new int[this.rows,this.cols];
        }

        public void Show()
        {
            for (var i = 0; i < this.rows; i++)
            {
                for (var j = 0; j < this.cols; j++) {
                    Console.Write("{0,3}", this.matrix[i, j]);
                }
                Console.WriteLine();
            }                
        }

        public void ReadElements()
        {
           for (var i = 0; i < this.rows; i++)
                for (var j = 0; j < this.cols; j++)
                {
                    Console.Write("element[{0},{1}]=",i,j);
                    this.matrix[i, j] = Convert.ToInt32(Console.ReadLine());
                }            
        }


        // rotate [n,m] 2D array by 90 deg right
        public void Rotate90DegRight()
        {

            // create a mirror of current matrix
            int[,] mirror = this.matrix;

            // create a new matrix
            this.matrix = new int[this.cols, this.rows];

            for (int i = 0; i < this.rows; i++)
            {
                for (int j = 0; j < this.cols; j++)
                {
                    this.matrix[j, this.rows - i - 1] = mirror[i, j];
                }
            }

            // replace cols count with rows count
            int tmp = this.rows;
            this.rows = this.cols;
            this.cols = tmp;           
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Matrix myMatrix = new Matrix(3,4);
            Console.WriteLine("Enter matrix elements:");
            myMatrix.ReadElements();
            Console.WriteLine("Matrix elements are:");
            myMatrix.Show();
            myMatrix.Rotate90DegRight();
            Console.WriteLine("Matrix rotated at 90 deg are:");
            myMatrix.Show();
            Console.ReadLine();
        }
    }
}

Result:

    Enter matrix elements:
    element[0,0]=1
    element[0,1]=2
    element[0,2]=3
    element[0,3]=4
    element[1,0]=5
    element[1,1]=6
    element[1,2]=7
    element[1,3]=8
    element[2,0]=9
    element[2,1]=10
    element[2,2]=11
    element[2,3]=12
    Matrix elements are:
      1  2  3  4
      5  6  7  8
      9 10 11 12
    Matrix rotated at 90 deg are:
      9  5  1
     10  6  2
     11  7  3
     12  8  4

Base 64 encode and decode example code

Above many answers but doesn't work for me some of them no exception handling in correct way. here am adding a perfect solution work amazing for me sure also for you too.

//base64 decode string 
 String s = "ewoic2VydmVyIjoic2cuenhjLmx1IiwKInNuaSI6InRlc3RpbmciLAoidXNlcm5hbWUiOiJ0ZXN0
    ZXIiLAoicGFzc3dvcmQiOiJ0ZXN0ZXIiLAoicG9ydCI6IjQ0MyIKfQ==";
    String val = a(s) ;
     Toast.makeText(this, ""+val, Toast.LENGTH_SHORT).show();
    
       public static String a(String str) {
             try {
                 return new String(Base64.decode(str, 0), "UTF-8");
             } catch (UnsupportedEncodingException | IllegalArgumentException unused) {
                 return "This is not a base64 data";
             }
         }

How to add composite primary key to table

You don't need to create the table first and then add the keys in subsequent steps. You can add both primary key and foreign key while creating the table:

This example assumes the existence of a table (Codes) that we would want to reference with our foreign key.

CREATE TABLE d (
id [numeric](1),
code [varchar](2),
PRIMARY KEY (id, code),
CONSTRAINT fk_d_codes FOREIGN KEY (code) REFERENCES Codes (code)
)

If you don't have a table that we can reference, add one like this so that the example will work:

CREATE TABLE Codes (
    Code [varchar](2) PRIMARY KEY   
    )

NOTE: you must have a table to reference before creating the foreign key.

How to access parent scope from within a custom directive *with own scope* in AngularJS?

If you are using ES6 Classes and ControllerAs syntax, you need to do something slightly different.

See the snippet below and note that vm is the ControllerAs value of the parent Controller as used in the parent HTML

myApp.directive('name', function() {
  return {
    // no scope definition
    link : function(scope, element, attrs, ngModel) {

        scope.vm.func(...)

Excel - Sum column if condition is met by checking other column in same table

This should work, but there is a little trick. After you enter the formula, you need to hold down Ctrl+Shift while you press Enter. When you do, you'll see that the formula bar has curly-braces around your formula. This is called an array formula.

For example, if the Months are in cells A2:A100 and the amounts are in cells B2:B100, your formula would look like {=SUM(If(A2:A100="January",B2:B100))}. You don't actually type the curly-braces though.

You could also do something like =SUM((A2:A100="January")*B2:B100). You'd still need to use the trick to get it to work correctly.

Not able to change TextField Border Color

We have tried custom search box with the pasted snippet. This code will useful for all kind of TextFiled decoration in Flutter. Hope this snippet will helpful for others.

Container(
        margin: EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 10.0),
        child:  new Theme(
          data: new ThemeData(
           hintColor: Colors.white,
            primaryColor: Colors.white,
            primaryColorDark: Colors.white,
          ),
          child:Padding(
          padding: EdgeInsets.all(10.0),
          child: TextField(
            style: TextStyle(color: Colors.white),
            onChanged: (value) {
              filterSearchResults(value);
            },
            controller: editingController,
            decoration: InputDecoration(
                labelText: "Search",
                hintText: "Search",
                prefixIcon: Icon(Icons.search,color: Colors.white,),
                enabled: true,
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: Colors.white),
                    borderRadius: BorderRadius.all(Radius.circular(25.0))),
                border: OutlineInputBorder(
                    borderSide: const BorderSide(color: Colors.white, width: 0.0),
                    borderRadius: BorderRadius.all(Radius.circular(25.0)))),
          ),
        ),
        ),
      ),

Vue.JS: How to call function after page loaded?

Vue watch() life-cycle hook, can be used

html

<div id="demo">{{ fullName }}</div>

js

var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar',
    fullName: 'Foo Bar'
  },
  watch: {
    firstName: function (val) {
      this.fullName = val + ' ' + this.lastName
    },
    lastName: function (val) {
      this.fullName = this.firstName + ' ' + val
    }
  }
})

Add a CSS class to <%= f.submit %>

<%= f.submit 'name of button here', :class => 'submit_class_name_here' %>

This should do. If you're getting an error, chances are that you're not supplying the name.

Alternatively, you can style the button without a class:

form#form_id_here input[type=submit]

Try that, as well.

Change old commit message on Git

Just wanted to provide a different option for this. In my case, I usually work on my individual branches then merge to master, and the individual commits I do to my local are not that important.

Due to a git hook that checks for the appropriate ticket number on Jira but was case sensitive, I was prevented from pushing my code. Also, the commit was done long ago and I didn't want to count how many commits to go back on the rebase.

So what I did was to create a new branch from latest master and squash all commits from problem branch into a single commit on new branch. It was easier for me and I think it's good idea to have it here as future reference.

From latest master:

git checkout -b new-branch

Then

git merge --squash problem-branch
git commit -m "new message" 

Referece: https://github.com/rotati/wiki/wiki/Git:-Combine-all-messy-commits-into-one-commit-before-merging-to-Master-branch

How to save/restore serializable object to/from file?

**1. Convert the json string to base64string and Write or append it to binary file. 2. Read base64string from binary file and deserialize using BsonReader. **

 public static class BinaryJson
{
    public static string SerializeToBase64String(this object obj)
    {
        JsonSerializer jsonSerializer = new JsonSerializer();
        MemoryStream objBsonMemoryStream = new MemoryStream();
        using (BsonWriter bsonWriterObject = new BsonWriter(objBsonMemoryStream))
        {
            jsonSerializer.Serialize(bsonWriterObject, obj);
            return Convert.ToBase64String(objBsonMemoryStream.ToArray());
        }           
        //return Encoding.ASCII.GetString(objBsonMemoryStream.ToArray());
    }
    public static T DeserializeToObject<T>(this string base64String)
    {
        byte[] data = Convert.FromBase64String(base64String);
        MemoryStream ms = new MemoryStream(data);
        using (BsonReader reader = new BsonReader(ms))
        {
            JsonSerializer serializer = new JsonSerializer();
            return serializer.Deserialize<T>(reader);
        }
    }
}

How to overcome "'aclocal-1.15' is missing on your system" warning?

2018, yet another solution ...

https://github.com/apereo/mod_auth_cas/issues/97

in some cases simply running

$ autoreconf -f -i

and nothing else .... solves the problem.

You do that in the directory /pcre2-10.30 .

What a nightmare.

(This usually did not solve the problem in 2017, but now usually does seem to solve the problem - they fixed something. Also, it seems your Dockerfile should now usually start with "FROM ibmcom/swift-ubuntu" ; previously you had to give a certain version/dev-build to make it work.)

Is there a way to include commas in CSV columns without breaking the formatting?

Enclose the field in quotes, e.g.

field1_value,field2_value,"field 3,value",field4, etc...

See wikipedia.

Updated:

To encode a quote, use ", one double quote symbol in a field will be encoded as "", and the whole field will become """". So if you see the following in e.g. Excel:

---------------------------------------
| regular_value |,,,"|  ,"", |"""   |"|
---------------------------------------

the CSV file will contain:

regular_value,",,,""",","""",","""""""",""""

A comma is simply encapsulated using quotes, so , becomes ",".

A comma and quote needs to be encapsulated and quoted, so "," becomes """,""".

How to clear Flutter's Build cache?

Or you can delete the /build folder under your /app-project folder manually if you cannot run flutter command.

How to get current time with jQuery

You may try like this:

new Date($.now());

Also using Javascript you can do like this:

_x000D_
_x000D_
var dt = new Date();_x000D_
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();_x000D_
document.write(time);
_x000D_
_x000D_
_x000D_

Oracle - how to remove white spaces?

This sounds like an output formatting issue? If using SQL Plus, use the COLUMN command like this (assuming you want a maximum display width of 20 chars for each):

column a format a20
column b format a20
select a, b from mytable;

"date(): It is not safe to rely on the system's timezone settings..."

You can set the timezone in your .htaccess file

php_value date.timezone UTC

Android Stop Emulator from Command Line

I use this one-liner, broken into several lines for readability:

adb devices |
 perl -nle 'print $1 if /emulator-(\d+).device$/' |
 xargs -t -l1 -i bash -c "
   ( echo auth $(cat $HOME/.emulator_console_auth_token) ;
     echo kill ;
     yes ) |
   telnet localhost {}"

File path for project files?

I was facing a similar issue, I had a file on my project, and wanted to test a class which had to deal with loading files from the FS and process them some way. What I did was:

  • added the file test.txt to my test project
  • on the solution explorer hit alt-enter (file properties)
  • there I set BuildAction to Content and Copy to Output Directory to Copy if newer, I guess Copy always would have done it as well

then on my tests I just had to Path.Combine(Environment.CurrentDirectory, "test.txt") and that's it. Whenever the project is compiled it will copy the file (and all it's parent path, in case it was in, say, a folder) to the bin\Debug (or whatever configuration you are using) folder.

Hopes this helps someone

Java 8 Stream API to find Unique Object matching a property value

Instead of using a collector try using findFirst or findAny.

Optional<Person> matchingObject = objects.stream().
    filter(p -> p.email().equals("testemail")).
    findFirst();

This returns an Optional since the list might not contain that object.

If you're sure that the list always contains that person you can call:

Person person = matchingObject.get();

Be careful though! get throws NoSuchElementException if no value is present. Therefore it is strongly advised that you first ensure that the value is present (either with isPresent or better, use ifPresent, map, orElse or any of the other alternatives found in the Optional class).

If you're okay with a null reference if there is no such person, then:

Person person = matchingObject.orElse(null);

If possible, I would try to avoid going with the null reference route though. Other alternatives methods in the Optional class (ifPresent, map etc) can solve many use cases. Where I have found myself using orElse(null) is only when I have existing code that was designed to accept null references in some cases.


Optionals have other useful methods as well. Take a look at Optional javadoc.

Endless loop in C/C++

The problem with asking this question is that you'll get so many subjective answers that simply state "I prefer this...". Instead of making such pointless statements, I'll try to answer this question with facts and references, rather than personal opinions.

Through experience, we can probably start by excluding the do-while alternatives (and the goto), as they are not commonly used. I can't recall ever seeing them in live production code, written by professionals.

The while(1), while(true) and for(;;) are the 3 different versions commonly existing in real code. They are of course completely equivalent and results in the same machine code.


for(;;)

  • This is the original, canonical example of an eternal loop. In the ancient C bible The C Programming Language by Kernighan and Ritchie, we can read that:

    K&R 2nd ed 3.5:

    for (;;) {
    ...
    }
    

    is an "infinite" loop, presumably to be broken by other means, such as a break or return. Whether to use while or for is largely a matter of personal preference.

    For a long while (but not forever), this book was regarded as canon and the very definition of the C language. Since K&R decided to show an example of for(;;), this would have been regarded as the most correct form at least up until the C standardization in 1990.

    However, K&R themselves already stated that it was a matter of preference.

    And today, K&R is a very questionable source to use as a canonical C reference. Not only is it outdated several times over (not addressing C99 nor C11), it also preaches programming practices that are often regarded as bad or blatantly dangerous in modern C programming.

    But despite K&R being a questionable source, this historical aspect seems to be the strongest argument in favour of the for(;;).

  • The argument against the for(;;) loop is that it is somewhat obscure and unreadable. To understand what the code does, you must know the following rule from the standard:

    ISO 9899:2011 6.8.5.3:

    for ( clause-1 ; expression-2 ; expression-3 ) statement
    

    /--/

    Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant.

    Based on this text from the standard, I think most will agree that it is not only obscure, it is subtle as well, since the 1st and 3rd part of the for loop are treated differently than the 2nd, when omitted.


while(1)

  • This is supposedly a more readable form than for(;;). However, it relies on another obscure, although well-known rule, namely that C treats all non-zero expressions as boolean logical true. Every C programmer is aware of that, so it is not likely a big issue.

  • There is one big, practical problem with this form, namely that compilers tend to give a warning for it: "condition is always true" or similar. That is a good warning, of a kind which you really don't want to disable, because it is useful for finding various bugs. For example a bug such as while(i = 1), when the programmer intended to write while(i == 1).

    Also, external static code analysers are likely to whine about "condition is always true".


while(true)

  • To make while(1) even more readable, some use while(true) instead. The consensus among programmers seem to be that this is the most readable form.

  • However, this form has the same problem as while(1), as described above: "condition is always true" warnings.

  • When it comes to C, this form has another disadvantage, namely that it uses the macro true from stdbool.h. So in order to make this compile, we need to include a header file, which may or may not be inconvenient. In C++ this isn't an issue, since bool exists as a primitive data type and true is a language keyword.

  • Yet another disadvantage of this form is that it uses the C99 bool type, which is only available on modern compilers and not backwards compatible. Again, this is only an issue in C and not in C++.


So which form to use? Neither seems perfect. It is, as K&R already said back in the dark ages, a matter of personal preference.

Personally, I always use for(;;) just to avoid the compiler/analyser warnings frequently generated by the other forms. But perhaps more importantly because of this:

If even a C beginner knows that for(;;) means an eternal loop, then who are you trying to make the code more readable for?

I guess that's what it all really boils down to. If you find yourself trying to make your source code readable for non-programmers, who don't even know the fundamental parts of the programming language, then you are only wasting time. They should not be reading your code.

And since everyone who should be reading your code already knows what for(;;) means, there is no point in making it further readable - it is already as readable as it gets.

How to subtract X days from a date using Java calendar?

int x = -1;
Calendar cal = ...;
cal.add(Calendar.DATE, x);

See java.util.Calendar#add(int,int)

javac option to compile all java files under a given directory recursively

In the usual case where you want to compile your whole project you can simply supply javac with your main class and let it compile all required dependencies:

javac -sourcepath . path/to/Main.java

Convert String to Float in Swift

to convert string to Float in Xcode 11 as previous methods need modification

func stringToFloat(value : String) -> Float {
    let numberFormatter = NumberFormatter()
    let number = numberFormatter.number(from: value)
    let numberFloatValue = number?.floatValue
    return numberFloatValue!
}

Oracle: how to add minutes to a timestamp?

Based on what you're asking for, you want the HH24:MI format for to_char.

MySQL DROP all tables, ignoring foreign keys

Here is SurlyDre's stored procedure modified so that foreign keys are ignored:

DROP PROCEDURE IF EXISTS `drop_all_tables`;

DELIMITER $$
CREATE PROCEDURE `drop_all_tables`()
BEGIN
    DECLARE _done INT DEFAULT FALSE;
    DECLARE _tableName VARCHAR(255);
    DECLARE _cursor CURSOR FOR
        SELECT table_name 
        FROM information_schema.TABLES
        WHERE table_schema = SCHEMA();
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET _done = TRUE;

    SET FOREIGN_KEY_CHECKS = 0;

    OPEN _cursor;

    REPEAT FETCH _cursor INTO _tableName;

    IF NOT _done THEN
        SET @stmt_sql = CONCAT('DROP TABLE ', _tableName);
        PREPARE stmt1 FROM @stmt_sql;
        EXECUTE stmt1;
        DEALLOCATE PREPARE stmt1;
    END IF;

    UNTIL _done END REPEAT;

    CLOSE _cursor;
    SET FOREIGN_KEY_CHECKS = 1;
END$$

DELIMITER ;

call drop_all_tables(); 

DROP PROCEDURE IF EXISTS `drop_all_tables`;

Printing an int list in a single line python3

If you write

a = [1, 2, 3, 4, 5]
print(*a, sep = ',')

You get this output: 1,2,3,4,5

How do I watch a file for changes?

I'd try something like this.

    try:
            f = open(filePath)
    except IOError:
            print "No such file: %s" % filePath
            raw_input("Press Enter to close window")
    try:
            lines = f.readlines()
            while True:
                    line = f.readline()
                    try:
                            if not line:
                                    time.sleep(1)
                            else:
                                    functionThatAnalisesTheLine(line)
                    except Exception, e:
                            # handle the exception somehow (for example, log the trace) and raise the same exception again
                            raw_input("Press Enter to close window")
                            raise e
    finally:
            f.close()

The loop checks if there is a new line(s) since last time file was read - if there is, it's read and passed to the functionThatAnalisesTheLine function. If not, script waits 1 second and retries the process.

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

This was resolved. It turns out our IT Staff was correct. Both TLS 1.1 and TLS 1.2 were installed on the server. However, the issue was that our sites are running as ASP.NET 4.0 and you have to have ASP.NET 4.5 to run TLS 1.1 or TLS 1.2. So, to resolve the issue, our IT Staff had to re-enable TLS 1.0 to allow a connection with PayTrace.

So in short, the error message, "the client and server cannot communicate, because they do not possess a common algorithm", was caused because there was no SSL Protocol available on the server to communicate with PayTrace's servers.

UPDATE: Please do not enable TLS 1.0 on your servers, this was a temporary fix and is not longer applicable since there are now better work-arounds that ensure strong security practices. Please see accepted answer for a solution. FYI, I'm going to keep this answer on the site as it provides information on what the problem was, please do not down-vote.

cocoapods - 'pod install' takes forever

Try clearing your CocoaPods cache, re-download and re-install all pods as described here

rm -rf "${HOME}/Library/Caches/CocoaPods"

rm -rf "\`pwd\`/Pods/"

pod update

Does C# have a String Tokenizer like Java's?

I think the nearest in the .NET Framework is

string.Split()

Centering a button vertically in table cell, using Twitter Bootstrap

add this to your css

.table-vcenter td {
   vertical-align: middle!important;
}

then add to the class to your table:

        <table class="table table-hover table-striped table-vcenter">

JUnit test for System.out.println()

Full JUnit 5 example to test System.out (replace the when part):

package learning;

import static org.assertj.core.api.BDDAssertions.then;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

class SystemOutLT {

    private PrintStream originalSystemOut;
    private ByteArrayOutputStream systemOutContent;

    @BeforeEach
    void redirectSystemOutStream() {

        originalSystemOut = System.out;

        // given
        systemOutContent = new ByteArrayOutputStream();
        System.setOut(new PrintStream(systemOutContent));
    }

    @AfterEach
    void restoreSystemOutStream() {
        System.setOut(originalSystemOut);
    }

    @Test
    void shouldPrintToSystemOut() {

        // when
        System.out.println("example");

        then(systemOutContent.toString()).containsIgnoringCase("example");
    }
}

Delete file from internal storage

File file = new File(getFilePath(imageUri.getValue())); 
boolean b = file.delete();

is not working in my case.

boolean b = file.delete();                 // returns false
boolean b = file.getAbsolutePath.delete(); // returns false 

always returns false.

The issue has been resolved by using the code below:

ContentResolver contentResolver = getContentResolver();
contentResolver.delete(uriDelete, null, null);

How to place two forms on the same page?

Hope this will help you. Assumed that login form has: username and password inputs.

if(isset($_POST['username']) && trim($_POST['username']) != "" && isset($_POST['password']) && trim($_POST['password']) != ""){
//login
} else {
//register
}

How to destroy JWT Tokens on logout?

The JWT is stored on browser, so remove the token deleting the cookie at client side

If you need also to invalidate the token from server side before its expiration time, for example account deleted/blocked/suspended, password changed, permissions changed, user logged out by admin, take a look at Invalidating JSON Web Tokens for some commons techniques like creating a blacklist or rotating tokens

store and retrieve a class object in shared preference

There is no way to store objects in SharedPreferences, What i did is to create a public class, put all the parameters i need and create setters and getters, i was able to access my objects,

What is the difference between syntax and semantics in programming languages?

He drinks rice (wrong semantic- meaningless, right syntax- grammar)

Hi drink water (right semantic- has meaning, wrong syntax- grammar)

How can I slice an ArrayList out of an ArrayList in Java?

Although this post is very old. In case if somebody is looking for this..

Guava facilitates partitioning the List into sublists of a specified size

List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
    List<List<Integer>> subSets = Lists.partition(intList, 3);

Load and execute external js file in node.js with access to local variables?

If you are planning to load an external javascript file's functions or objects, load on this context using the following code – note the runInThisContext method:

var vm = require("vm");
var fs = require("fs");

var data = fs.readFileSync('./externalfile.js');
const script = new vm.Script(data);
script.runInThisContext();

// here you can use externalfile's functions or objects as if they were instantiated here. They have been added to this context. 

How to use multiprocessing queue in Python?

A multi-producers and multi-consumers example, verified. It should be easy to modify it to cover other cases, single/multi producers, single/multi consumers.

from multiprocessing import Process, JoinableQueue
import time
import os

q = JoinableQueue()

def producer():
    for item in range(30):
        time.sleep(2)
        q.put(item)
    pid = os.getpid()
    print(f'producer {pid} done')


def worker():
    while True:
        item = q.get()
        pid = os.getpid()
        print(f'pid {pid} Working on {item}')
        print(f'pid {pid} Finished {item}')
        q.task_done()

for i in range(5):
    p = Process(target=worker, daemon=True).start()

# send thirty task requests to the worker
producers = []
for i in range(2):
    p = Process(target=producer)
    producers.append(p)
    p.start()

# make sure producers done
for p in producers:
    p.join()

# block until all workers are done
q.join()
print('All work completed')

Explanation:

  1. Two producers and five consumers in this example.
  2. JoinableQueue is used to make sure all elements stored in queue will be processed. 'task_done' is for worker to notify an element is done. 'q.join()' will wait for all elements marked as done.
  3. With #2, there is no need to join wait for every worker.
  4. But it is important to join wait for every producer to store element into queue. Otherwise, program exit immediately.

What does cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);

When the normType is NORM_MINMAX, cv::normalize normalizes _src in such a way that the min value of dst is alpha and max value of dst is beta. cv::normalize does its magic using only scales and shifts (i.e. adding constants and multiplying by constants).

CV_8UC1 says how many channels dst has.

The documentation here is pretty clear: http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#normalize

Simple Deadlock Examples

package test.concurrent;
public class DeadLockTest {
   private static long sleepMillis;
   private final Object lock1 = new Object();
   private final Object lock2 = new Object();

   public static void main(String[] args) {
       sleepMillis = Long.parseLong(args[0]);
       DeadLockTest test = new DeadLockTest();
       test.doTest();
   }

   private void doTest() {
       Thread t1 = new Thread(new Runnable() {
           public void run() {
               lock12();
           }
       });
       Thread t2 = new Thread(new Runnable() {
           public void run() {
               lock21();
           }
       });
       t1.start();
       t2.start();
   }

   private void lock12() {
       synchronized (lock1) {
           sleep();
           synchronized (lock2) {
               sleep();
           }
       }
   }

   private void lock21() {
       synchronized (lock2) {
           sleep();
           synchronized (lock1) {
               sleep();
           }
       }
   }

   private void sleep() {
       try {
           Thread.sleep(sleepMillis);
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
   }
}
To run the deadlock test with sleep time 1 millisecond:
java -cp . test.concurrent.DeadLockTest 1

Laravel 5 How to switch from Production mode

Do not forget to run the command php artisan config:clear after you have made the changes to the .env file. Done this again php artisan env, which will return the correct version.

Adding a column to an existing table in a Rails migration

You also can use special change_table method in the migration for adding new columns:

change_table(:users) do |t|
  t.column :email, :string
end

Add two numbers and display result in textbox with Javascript

<script>
function myFunction() {
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var x = y + z;
document.getElementById("result").innerHTML = x;
}
</script>
<p>
<label>Enter First Number : </label><br>
<input type="number" id="txt1" name="text1"><br/>
<label>Enter Second Number : </label><br>
<input type="number" id="txt2" name="text2">
</p>
<p>
<button onclick="myFunction()">Calculate</button>
</p>
<br/>
<p id="result"></p>

How to force Selenium WebDriver to click on element which is not currently visible?

Or you may use Selenium Action Class to simulate user interaction -- For example

    WebDriver = new FirefoxDriver();

    WebElement menu = driver.findElement(By.xpath("")); // the triger event element

    Actions build = new Actions(driver); // heare you state ActionBuider
    build.moveToElement(menu).build().perform(); // Here you perform hover mouse over the needed elemnt to triger the visibility of the hidden
    WebElement m2m= driver.findElement(By.xpath(""));//the previous non visible element
    m2m.click();

How to write and read java serialized objects into a file

Why not serialize the whole list at once?

FileOutputStream fout = new FileOutputStream("G:\\address.ser");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(MyClassList);

Assuming, of course, that MyClassList is an ArrayList or LinkedList, or another Serializable collection.

In the case of reading it back, in your code you ready only one item, there is no loop to gather all the item written.

Google Maps API v2: How to make markers clickable?

Another Solution : you get the marker by its title

public class MarkerDemoActivity extends android.support.v4.app.FragmentActivity implements OnMarkerClickListener
{
      private Marker myMarker;    

      private void setUpMap()
      {
      .......
      googleMap.setOnMarkerClickListener(this);

      myMarker = googleMap.addMarker(new MarkerOptions()
                  .position(latLng)
                  .title("My Spot")
                  .snippet("This is my spot!")
                  .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
      ......
      }

  @Override
  public boolean onMarkerClick(final Marker marker) 
  {

     String name= marker.getTitle();

      if (name.equalsIgnoreCase("My Spot")) 
      {
          //write your code here
      }
  }
}

How to detect READ_COMMITTED_SNAPSHOT is enabled?

Neither on SQL2005 nor 2012 does DBCC USEROPTIONS show is_read_committed_snapshot_on:

Set Option  Value
textsize    2147483647
language    us_english
dateformat  mdy
datefirst   7
lock_timeout    -1
quoted_identifier   SET
arithabort  SET
ansi_null_dflt_on   SET
ansi_warnings   SET
ansi_padding    SET
ansi_nulls  SET
concat_null_yields_null SET
isolation level read committed

Django - what is the difference between render(), render_to_response() and direct_to_template()?

Render is

def render(request, *args, **kwargs):
    """ Simple wrapper for render_to_response. """
    kwargs['context_instance'] = RequestContext(request)
    return render_to_response(*args, **kwargs)

So there is really no difference between render_to_response except it wraps your context making the template pre-processors work.

Direct to template is a generic view.

There is really no sense in using it here because there is overhead over render_to_response in the form of view function.

Filtering a pyspark dataframe using isin by exclusion

It looks like the ~ gives the functionality that I need, but I am yet to find any appropriate documentation on it.

df.filter(~col('bar').isin(['a','b'])).show()



+---+---+
| id|bar|
+---+---+
|  4|  c|
|  5|  d|
+---+---+

How to create a .gitignore file

You can go to https://www.toptal.com/developers/gitignore

Select the IDE, operating systems or programming language. It will automatically generate for you. enter image description here

Multiple try codes in one block

You could try a for loop


for func,args,kwargs in zip([a,b,c,d], 
                            [args_a,args_b,args_c,args_d],
                            [kw_a,kw_b,kw_c,kw_d]):
    try:
       func(*args, **kwargs)
       break
    except:
       pass

This way you can loop as many functions as you want without making the code look ugly

jQuery check/uncheck radio button onclick

Having tested some of the above solutions which did not work for me 100%, I decided to create my own. It creates new click listeners after a radio button is clicked:

/**
 * Radio select toggler
 * enables radio buttons to be toggled when clicked
 * Created by Michal on 09/05/2016.
 */

var radios = $('input[type=radio]');

/**
 * Adds click listeners to all checkboxes to unselect checkbox if it was checked already
 */
function updateCheckboxes() {
    radios.unbind('click');
    radios.filter(':checked').click(function () {
        $(this).prop('checked', false);
    });
    radios.click(function () {
        updateCheckboxes();
    });
}

updateCheckboxes();

Check div is hidden using jquery

Did you notice your typo, $car2 instead of #car2 ?

Anyway, :hidden seems to be working as expected, try it here.

Error creating bean with name 'entityManagerFactory

Adding dependencies didn't fix the issue at my end.

The issue was happening at my end because of "additional" fields that are part of the "@Entity" class and don't exist in the database.

I removed the additional fields from the @Entity class and it worked.

How to get setuptools and easy_install?

For python3 on Ubuntu

 sudo apt-get install python3-setuptools

How to obtain values of request variables using Python and Flask

You can get posted form data from request.form and query string data from request.args.

myvar =  request.form["myvar"]
myvar = request.args["myvar"]

mysql delete under safe mode

Googling around, the popular answer seems to be "just turn off safe mode":

SET SQL_SAFE_UPDATES = 0;
DELETE FROM instructor WHERE salary BETWEEN 13000 AND 15000;
SET SQL_SAFE_UPDATES = 1;

If I'm honest, I can't say I've ever made a habit of running in safe mode. Still, I'm not entirely comfortable with this answer since it just assumes you should go change your database config every time you run into a problem.

So, your second query is closer to the mark, but hits another problem: MySQL applies a few restrictions to subqueries, and one of them is that you can't modify a table while selecting from it in a subquery.

Quoting from the MySQL manual, Restrictions on Subqueries:

In general, you cannot modify a table and select from the same table in a subquery. For example, this limitation applies to statements of the following forms:

DELETE FROM t WHERE ... (SELECT ... FROM t ...);
UPDATE t ... WHERE col = (SELECT ... FROM t ...);
{INSERT|REPLACE} INTO t (SELECT ... FROM t ...);

Exception: The preceding prohibition does not apply if you are using a subquery for the modified table in the FROM clause. Example:

UPDATE t ... WHERE col = (SELECT * FROM (SELECT ... FROM t...) AS _t ...);

Here the result from the subquery in the FROM clause is stored as a temporary table, so the relevant rows in t have already been selected by the time the update to t takes place.

That last bit is your answer. Select target IDs in a temporary table, then delete by referencing the IDs in that table:

DELETE FROM instructor WHERE id IN (
  SELECT temp.id FROM (
    SELECT id FROM instructor WHERE salary BETWEEN 13000 AND 15000
  ) AS temp
);

SQLFiddle demo.

Iterate over object attributes in python

As mentioned in some of the answers/comments already, Python objects already store a dictionary of their attributes (methods aren't included). This can be accessed as __dict__, but the better way is to use vars (the output is the same, though). Note that modifying this dictionary will modify the attributes on the instance! This can be useful, but also means you should be careful with how you use this dictionary. Here's a quick example:

class A():
    def __init__(self, x=3, y=2, z=5):
        self.x = x
        self._y = y
        self.__z__ = z

    def f(self):
        pass

a = A()
print(vars(a))
# {'x': 3, '_y': 2, '__z__': 5}
# all of the attributes of `a` but no methods!

# note how the dictionary is always up-to-date
a.x = 10
print(vars(a))
# {'x': 10, '_y': 2, '__z__': 5}

# modifying the dictionary modifies the instance attribute
vars(a)["_y"] = 20
print(vars(a))
# {'x': 10, '_y': 20, '__z__': 5}

Using dir(a) is an odd, if not outright bad, approach to this problem. It's good if you really needed to iterate over all attributes and methods of the class (including the special methods like __init__). However, this doesn't seem to be what you want, and even the accepted answer goes about this poorly by applying some brittle filtering to try to remove methods and leave just the attributes; you can see how this would fail for the class A defined above.

(using __dict__ has been done in a couple of answers, but they all define unnecessary methods instead of using it directly. Only a comment suggests to use vars).

How to correctly assign a new string value?

The two structs are different. When you initialize the first struct, about 40 bytes of memory are allocated. When you initialize the second struct, about 10 bytesof memory are allocated. (Actual amount is architecture dependent)

You can use the string literals (string constants) to initalize character arrays. This is why

person p = {"John", "Doe",30};

works in the first example.

You cannot assign (in the conventional sense) a string in C.

The string literals you have ("John") are loaded into memory when your code executes. When you initialize an array with one of these literals, then the string is copied into a new memory location. In your second example, you are merely copying the pointer to (location of) the string literal. Doing something like:

char* string = "Hello";
*string = 'C'

might cause compile or runtime errors (I am not sure.) It is a bad idea because you are modifying the literal string "Hello" which, for example on a microcontroler, could be located in read-only memory.

How can I represent an 'Enum' in Python?

It's funny, I just had a need for this the other day and I couldnt find an implementation worth using... so I wrote my own:

import functools

class EnumValue(object):
    def __init__(self,name,value,type):
        self.__value=value
        self.__name=name
        self.Type=type
    def __str__(self):
        return self.__name
    def __repr__(self):#2.6 only... so change to what ever you need...
        return '{cls}({0!r},{1!r},{2})'.format(self.__name,self.__value,self.Type.__name__,cls=type(self).__name__)

    def __hash__(self):
        return hash(self.__value)
    def __nonzero__(self):
        return bool(self.__value)
    def __cmp__(self,other):
        if isinstance(other,EnumValue):
            return cmp(self.__value,other.__value)
        else:
            return cmp(self.__value,other)#hopefully their the same type... but who cares?
    def __or__(self,other):
        if other is None:
            return self
        elif type(self) is not type(other):
            raise TypeError()
        return EnumValue('{0.Name} | {1.Name}'.format(self,other),self.Value|other.Value,self.Type)
    def __and__(self,other):
        if other is None:
            return self
        elif type(self) is not type(other):
            raise TypeError()
        return EnumValue('{0.Name} & {1.Name}'.format(self,other),self.Value&other.Value,self.Type)
    def __contains__(self,other):
        if self.Value==other.Value:
            return True
        return bool(self&other)
    def __invert__(self):
        enumerables=self.Type.__enumerables__
        return functools.reduce(EnumValue.__or__,(enum for enum in enumerables.itervalues() if enum not in self))

    @property
    def Name(self):
        return self.__name

    @property
    def Value(self):
        return self.__value

class EnumMeta(type):
    @staticmethod
    def __addToReverseLookup(rev,value,newKeys,nextIter,force=True):
        if value in rev:
            forced,items=rev.get(value,(force,()) )
            if forced and force: #value was forced, so just append
                rev[value]=(True,items+newKeys)
            elif not forced:#move it to a new spot
                next=nextIter.next()
                EnumMeta.__addToReverseLookup(rev,next,items,nextIter,False)
                rev[value]=(force,newKeys)
            else: #not forcing this value
                next = nextIter.next()
                EnumMeta.__addToReverseLookup(rev,next,newKeys,nextIter,False)
                rev[value]=(force,newKeys)
        else:#set it and forget it
            rev[value]=(force,newKeys)
        return value

    def __init__(cls,name,bases,atts):
        classVars=vars(cls)
        enums = classVars.get('__enumerables__',None)
        nextIter = getattr(cls,'__nextitr__',itertools.count)()
        reverseLookup={}
        values={}

        if enums is not None:
            #build reverse lookup
            for item in enums:
                if isinstance(item,(tuple,list)):
                    items=list(item)
                    value=items.pop()
                    EnumMeta.__addToReverseLookup(reverseLookup,value,tuple(map(str,items)),nextIter)
                else:
                    value=nextIter.next()
                    value=EnumMeta.__addToReverseLookup(reverseLookup,value,(str(item),),nextIter,False)#add it to the reverse lookup, but don't force it to that value

            #build values and clean up reverse lookup
            for value,fkeys in reverseLookup.iteritems():
                f,keys=fkeys
                for key in keys:
                    enum=EnumValue(key,value,cls)
                    setattr(cls,key,enum)
                    values[key]=enum
                reverseLookup[value]=tuple(val for val in values.itervalues() if val.Value == value)
        setattr(cls,'__reverseLookup__',reverseLookup)
        setattr(cls,'__enumerables__',values)
        setattr(cls,'_Max',max([key for key in reverseLookup] or [0]))
        return super(EnumMeta,cls).__init__(name,bases,atts)

    def __iter__(cls):
        for enum in cls.__enumerables__.itervalues():
            yield enum
    def GetEnumByName(cls,name):
        return cls.__enumerables__.get(name,None)
    def GetEnumByValue(cls,value):
        return cls.__reverseLookup__.get(value,(None,))[0]

class Enum(object):
    __metaclass__=EnumMeta
    __enumerables__=None

class FlagEnum(Enum):
    @staticmethod
    def __nextitr__():
        yield 0
        for val in itertools.count():
            yield 2**val

def enum(name,*args):
    return EnumMeta(name,(Enum,),dict(__enumerables__=args))

Take it or leave it, it did what I needed it to do :)

Use it like:

class Air(FlagEnum):
    __enumerables__=('None','Oxygen','Nitrogen','Hydrogen')

class Mammals(Enum):
    __enumerables__=('Bat','Whale',('Dog','Puppy',1),'Cat')
Bool = enum('Bool','Yes',('No',0))

git revert back to certain commit

http://www.kernel.org/pub/software/scm/git/docs/git-revert.html

using git revert <commit> will create a new commit that reverts the one you dont want to have.

You can specify a list of commits to revert.

An alternative: http://git-scm.com/docs/git-reset

git reset will reset your copy to the commit you want.

How to convert DateTime to/from specific string format (both ways, e.g. given Format is "yyyyMMdd")?

It's the Simple way to convert to format

 DateTime.Now.ToString("yyyyMMdd");

What are the differences between git remote prune, git prune, git fetch --prune, etc

Note that one difference between git remote --prune and git fetch --prune is being fixed, with commit 10a6cc8, by Tom Miller (tmiller) (for git 1.9/2.0, Q1 2014):

When we have a remote-tracking branch named "frotz/nitfol" from a previous fetch, and the upstream now has a branch named "**frotz"**, fetch would fail to remove "frotz/nitfol" with a "git fetch --prune" from the upstream.
git would inform the user to use "git remote prune" to fix the problem.

So: when a upstream repo has a branch ("frotz") with the same name as a branch hierarchy ("frotz/xxx", a possible branch naming convention), git remote --prune was succeeding (in cleaning up the remote tracking branch from your repo), but git fetch --prune was failing.

Not anymore:

Change the way "fetch --prune" works by moving the pruning operation before the fetching operation.
This way, instead of warning the user of a conflict, it automatically fixes it.

Change windows hostname from command line

The previously mentioned wmic command is the way to go, as it is installed by default in recent versions of Windows.

Here is my small improvement to generalize it, by retrieving the current name from the environment:

wmic computersystem where name="%COMPUTERNAME%" 
     call rename name="NEW-NAME"

NOTE: The command must be given in one line, but I've broken it into two to make scrolling unnecessary. As @rbeede mentions you'll have to reboot to complete the update.

MySQL: Selecting multiple fields into multiple variables in a stored procedure

==========Advise==========

@martin clayton Answer is correct, But this is an advise only.

Please avoid the use of ambiguous variable in the stored procedure.

Example :

SELECT Id, dateCreated
INTO id, datecreated
FROM products
WHERE pName = iName

The above example will cause an error (null value error)

Example give below is correct. I hope this make sense.

Example :

SELECT Id, dateCreated
INTO val_id, val_datecreated
FROM products
WHERE pName = iName

You can also make them unambiguous by referencing the table, like:

[ Credit : maganap ]

SELECT p.Id, p.dateCreated INTO id, datecreated FROM products p 
WHERE pName = iName

Database development mistakes made by application developers

15 - Using some crazy construct and application logic instead of a simple COALESCE.

move div with CSS transition

Something like this?

DEMO

And the code I used:

.box{
    position: relative;
    overflow: hidden;
}

.box:hover .hidden{

    left: 0px;
}

.box .hidden {    
    background: yellow;
    height: 300px;    
    position: absolute; 
    top: 0;
    left: -500px;    
    width: 500px;
    opacity: 1;    
    -webkit-transition: all 0.7s ease-out;
       -moz-transition: all 0.7s ease-out;
        -ms-transition: all 0.7s ease-out;
         -o-transition: all 0.7s ease-out;
            transition: all 0.7s ease-out;
}

I may also add that it's possible to move an elment using transform: translate(); , which in this case could work something like this - DEMO nr2

Pause in Python

Try os.system("pause") — I used it and it worked for me.

Make sure to include import os at the top of your script.

How to calculate percentage when old value is ZERO

If you're required to show growth as a percentage it's customary to display [NaN] or something similar in these cases. A growth rate, on the other hand, would be reported in this case as $/month. So in your example for April the growth rate would be calculated as ((20-0)/1.

In any event, determining the correct method for reporting this special case is a user decision. Is it covered in your user requirements?

Android: How to stretch an image to the screen width while maintaining aspect ratio?

I have managed to achieve this using this XML code only. It might be the case that eclipse does not render the height to show it expanding to fit; however, when you actually run this on a device, it properly renders and provides the desired result. (well at least for me)

<FrameLayout
     android:layout_width="match_parent"
     android:layout_height="wrap_content">

     <ImageView
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:adjustViewBounds="true"
          android:scaleType="centerCrop"
          android:src="@drawable/whatever" />
</FrameLayout>

Emulator error: This AVD's configuration is missing a kernel file

I tried what ChrLipp suggested, but that wasn't the problem, as the image was already installed. What I did was run:

android avd

to start the emulator manually. Then I stopped the emulator, and form that point on the

cca emulate android

app started working, without the "missing a kernel file" error.

Get list of certificates from the certificate store in C#

X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

store.Open(OpenFlags.ReadOnly);

foreach (X509Certificate2 certificate in store.Certificates){
    //TODO's
}

Placing/Overlapping(z-index) a view above another view in android

If you are adding the View programmatically, you can use yourLayout.addView(view, 1);

where 1 is the index.

What is a regular expression which will match a valid domain name without a subdomain?

I know that this is a bit of an old post, but all of the regular expressions here are missing one very important component: the support for IDN domain names.

IDN domain names start with xn--. They enable extended UTF-8 characters in domain names. For example, did you know "?.com" is a valid domain name? Yeah, "love heart dot com"! To validate the domain name, you need to let http://xn--c6h.com/ pass the validation.

Note, to use this regex, you will need to convert the domain to lower case, and also use an IDN library to ensure you encode domain names to ACE (also known as "ASCII Compatible Encoding"). One good library is GNU-Libidn.

idn(1) is the command line interface to the internationalized domain name library. The following example converts the host name in UTF-8 into ACE encoding. The resulting URL https://nic.xn--flw351e/ can then be used as ACE-encoded equivalent of https://nic.??/.

  $ idn --quiet -a nic.??
  nic.xn--flw351e

This magic regular expression should cover most domains (although, I am sure there are many valid edge cases that I have missed):

^((?!-))(xn--)?[a-z0-9][a-z0-9-_]{0,61}[a-z0-9]{0,1}\.(xn--)?([a-z0-9\-]{1,61}|[a-z0-9-]{1,30}\.[a-z]{2,})$

When choosing a domain validation regex, you should see if the domain matches the following:

  1. xn--stackoverflow.com
  2. stackoverflow.xn--com
  3. stackoverflow.co.uk

If these three domains do not pass, your regular expression may be not allowing legitimate domains!

Check out The Internationalized Domain Names Support page from Oracle's International Language Environment Guide for more information.

Feel free to try out the regex here: http://www.regexr.com/3abjr

ICANN keeps a list of tlds that have been delegated which can be used to see some examples of IDN domains.


Edit:

 ^(((?!-))(xn--|_{1,1})?[a-z0-9-]{0,61}[a-z0-9]{1,1}\.)*(xn--)?([a-z0-9][a-z0-9\-]{0,60}|[a-z0-9-]{1,30}\.[a-z]{2,})$

This regular expression will stop domains that have '-' at the end of a hostname as being marked as being valid. Additionally, it allows unlimited subdomains.

Basic communication between two fragments

The nicest and recommended way is to use a shared ViewModel.

https://developer.android.com/topic/libraries/architecture/viewmodel#sharing

From Google doc:

public class SharedViewModel extends ViewModel {
private final MutableLiveData<Item> selected = new MutableLiveData<Item>();

public void select(Item item) {
    selected.setValue(item);
}

public LiveData<Item> getSelected() {
    return selected;
}
}


public class MasterFragment extends Fragment {
private SharedViewModel model;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
    itemSelector.setOnClickListener(item -> {
        model.select(item);
    });
}
}


public class DetailFragment extends Fragment {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SharedViewModel model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
    model.getSelected().observe(this, { item ->
       // Update the UI.
    });
}
}

ps: two fragments never communicate directly

Why does 2 mod 4 = 2?

Modulo is the remainder, not division.

2 / 4 = 0R2
2 % 4 = 2

The sign % is often used for the modulo operator, in lieu of the word mod.

For x % 4, you get the following table (for 1-10)

 x x%4
------
 1  1
 2  2
 3  3
 4  0
 5  1
 6  2
 7  3
 8  0
 9  1
10  2

Include CSS and Javascript in my django template

Refer django docs on static files.

In settings.py:

import os
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__).decode('utf-8'))

MEDIA_ROOT = os.path.join(CURRENT_PATH, 'media')

MEDIA_URL = '/media/'

STATIC_ROOT = 'static/'

STATIC_URL = '/static/'

STATICFILES_DIRS = (
                    os.path.join(CURRENT_PATH, 'static'),
)

Then place your js and css files static folder in your project. Not in media folder.

In views.py:

from django.shortcuts import render_to_response, RequestContext

def view_name(request):
    #your stuff goes here
    return render_to_response('template.html', locals(), context_instance = RequestContext(request))

In template.html:

<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/style.css" />
<script type="text/javascript" src="{{ STATIC_URL }}js/jquery-1.8.3.min.js"></script>

In urls.py:

from django.conf import settings
urlpatterns += patterns('',
    url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
)

Project file structure can be found here in imgbin.

The total number of locks exceeds the lock table size

If you have properly structured your tables so that each contains relatively unique values, then the less intensive way to do this would be to do 3 separate insert-into statements, 1 for each table, with the join-filter in place for each insert -

INSERT INTO SkusBought...

SELECT t1.customer, t1.SKU, t1.TypeDesc
FROM transactiondatatransit AS T1
LEFT OUTER JOIN topThreetransit AS T2
ON t1.customer = t2.customernum
WHERE T2.customernum IS NOT NULL

Repeat this for the other two tables - copy/paste is a fine method, simply change the FROM table name. ** IF you are trying to prevent duplicated entries in your SkusBought table you can add the following join code in each section prior to the WHERE clause.

LEFT OUTER JOIN SkusBought AS T3
ON  t1.customer = t3.customer
AND t1.sku = t3.sku

-and then the last line of WHERE clause-

AND t3.customer IS NULL

Your initial code is using a number of sub-queries, and the UNION statement can be expensive as it will first create its own temporary table to populate the data from the three separate sources before inserting into the table you want ALONG with running another sub-query to filter results.

Squaring all elements in a list

def square(a):
    squares = []
    for i in a:
        squares.append(i**2)
    return squares

so how would i do the square of numbers from 1-20 using the above function

Do subclasses inherit private fields?

Private members (state and behavior) are inherited. They (can) affect the behavior and size of the object which is instantiated by the class. Not to mention that they are very well visible to the subclasses via all the encaptulation-breaking mechanisms that are available, or can be assumed by their implementers.

Although inheritance has a "defacto" definition, it definitely has no link to "visibility" aspects, which get assumed by the "no" answers.

So, there is no need to be diplomatic. JLS is just wrong at this point.

Any assumption that they are not "inherited" is unsafe and dangerous.

So among two defacto (partially) conflicting definitions (which I will not repeat), the only one that should be followed is the one that is safer (or safe).

What is the function of FormulaR1C1?

FormulaR1C1 has the same behavior as Formula, only using R1C1 style annotation, instead of A1 annotation. In A1 annotation you would use:

Worksheets("Sheet1").Range("A5").Formula = "=A4+A10"

In R1C1 you would use:

Worksheets("Sheet1").Range("A5").FormulaR1C1 = "=R4C1+R10C1"

It doesn't act upon row 1 column 1, it acts upon the targeted cell or range. Column 1 is the same as column A, so R4C1 is the same as A4, R5C2 is B5, and so forth.

The command does not change names, the targeted cell changes. For your R2C3 (also known as C2) example :

Worksheets("Sheet1").Range("C2").FormulaR1C1 = "=your formula here"

Best way to store a key=>value array in JavaScript?

I know its late but it might be helpful for those that want other ways. Another way array key=>values can be stored is by using an array method called map(); (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) you can use arrow function too

 
    var countries = ['Canada','Us','France','Italy'];  
// Arrow Function
countries.map((value, key) => key+ ' : ' + value );
// Anonomous Function
countries.map(function(value, key){
return key + " : " + value;
});

"The breakpoint will not currently be hit. The source code is different from the original version." What does this mean?

For me; my website was running in an IIS Application under Default Website (http://localhost/myapp/) and the mapping for the IIS application was pointing to a disk path that was different to the source code I was working on.

To resolve; remap your IIS Application to the same path as the source code you are building.

(This can happen if you have multiple versions of the same application running from different locations on your disk)

Replace text in HTML page with jQuery

Check out Padolsey's article on DOM find and replace, as well as the library to implement the described algorithm.

In this sample usage, I replace all text inside a <div id="content"> that looks like a US telephone number with a tel: scheme link:

findAndReplaceDOMText(document.getElementById('content'), {
    find:/\b(\d\d\d-\d\d\d-\d\d\d\d)\b/g,
    replace:function (portion) {
        var a = document.createElement('a');
        a.className = 'telephone';
        a.href = 'tel:' + portion.text.replace(/\D/g, '');
        a.textContent = portion.text;
        return a;
    }
});

powershell mouse move does not prevent idle mode

I've added a notification that you can easily enable / disable just setting its variable to $true or $false. Also the mouse cursor moves 1 px right and then 1 px left so it basically stays in the same place even after several iterations.

# Lines needed for the notification
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
Add-Type -AssemblyName System.Windows.Forms 
$isNotificationOn = $true

$secondsBetweenMouseMoves = 6
$Pos = [System.Windows.Forms.Cursor]::Position
$PosDelta = 1
$logFilename = "previousMouseMoverAction.txt"
$errorLogFilename = "mouseMoverLog.txt"

if (!(Test-Path "$PSScriptRoot\$logFilename")) {
   New-Item -path $PSScriptRoot -name $logFilename -type "file" -value "right"
   Write-Host "Warning: previousMouseMoverAction.txt missing, created a new one."
}

$previousPositionChangeAction = Get-Content -Path $PSScriptRoot\$logFilename

if ($previousPositionChangeAction -eq "left") {
    $PosDelta = 1
    Set-Content -Path $PSScriptRoot\$logFilename -Value 'right'
} else {
    $PosDelta = -1
    Set-Content -Path $PSScriptRoot\$logFilename -Value 'left'
}

for ($i = 0; $i -lt $secondsBetweenMouseMoves; $i++) {
    [System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point((($Pos.X) + $PosDelta) , $Pos.Y)
    if ($isNotificationOn) {
        # Sending a notification to the user
        $global:balloon = New-Object System.Windows.Forms.NotifyIcon
        $path = (Get-Process -id $pid).Path
        $balloon.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon($path) 
        $balloon.BalloonTipIcon = [System.Windows.Forms.ToolTipIcon]::Warning 
        $balloon.BalloonTipText = 'I have just moved your cheese...'
        $balloon.BalloonTipTitle = "Attention, $Env:USERNAME" 
        $balloon.Visible = $true 
        $balloon.ShowBalloonTip(3000)
    }
}

How to display count of notifications in app launcher icon

This is sample and best way for showing badge on notification launcher icon.

Add This Class in your application

public class BadgeUtils {

    public static void setBadge(Context context, int count) {
        setBadgeSamsung(context, count);
        setBadgeSony(context, count);
    }

    public static void clearBadge(Context context) {
        setBadgeSamsung(context, 0);
        clearBadgeSony(context);
    }


    private static void setBadgeSamsung(Context context, int count) {
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null) {
            return;
        }
        Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
        intent.putExtra("badge_count", count);
        intent.putExtra("badge_count_package_name", context.getPackageName());
        intent.putExtra("badge_count_class_name", launcherClassName);
        context.sendBroadcast(intent);
    }

    private static void setBadgeSony(Context context, int count) {
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null) {
            return;
        }

        Intent intent = new Intent();
        intent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", launcherClassName);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", true);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", String.valueOf(count));
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", context.getPackageName());

        context.sendBroadcast(intent);
    }


    private static void clearBadgeSony(Context context) {
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null) {
            return;
        }

        Intent intent = new Intent();
        intent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", launcherClassName);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", false);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", String.valueOf(0));
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", context.getPackageName());

        context.sendBroadcast(intent);
    }

    private static String getLauncherClassName(Context context) {

        PackageManager pm = context.getPackageManager();

        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);

        List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
        for (ResolveInfo resolveInfo : resolveInfos) {
            String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
            if (pkgName.equalsIgnoreCase(context.getPackageName())) {
                String className = resolveInfo.activityInfo.name;
                return className;
            }
        }
        return null;
    }


}

==> MyGcmListenerService.java Use BadgeUtils class when notification comes.

public class MyGcmListenerService extends GcmListenerService { 

    private static final String TAG = "MyGcmListenerService"; 
    @Override
    public void onMessageReceived(String from, Bundle data) {

            String message = data.getString("Msg");
            String Type = data.getString("Type"); 
            Intent intent = new Intent(this, SplashActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                    PendingIntent.FLAG_ONE_SHOT);

            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            NotificationCompat.BigTextStyle bigTextStyle= new NotificationCompat.BigTextStyle();

            bigTextStyle .setBigContentTitle(getString(R.string.app_name))
                    .bigText(message);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(getNotificationIcon())
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText(message)
                    .setStyle(bigTextStyle) 
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);

            int color = getResources().getColor(R.color.appColor);
            notificationBuilder.setColor(color);
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


            int unOpenCount=AppUtill.getPreferenceInt("NOTICOUNT",this);
            unOpenCount=unOpenCount+1;

            AppUtill.savePreferenceLong("NOTICOUNT",unOpenCount,this);  
            notificationManager.notify(unOpenCount /* ID of notification */, notificationBuilder.build()); 

// This is for bladge on home icon          
        BadgeUtils.setBadge(MyGcmListenerService.this,(int)unOpenCount);

    }


    private int getNotificationIcon() {
        boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);
        return useWhiteIcon ? R.drawable.notification_small_icon : R.drawable.icon_launcher;
    }
}

And clear notification from preference and also with badge count

 public class SplashActivity extends AppCompatActivity { 
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_splash);

                    AppUtill.savePreferenceLong("NOTICOUNT",0,this);
                    BadgeUtils.clearBadge(this);
            }
    }
<uses-permission android:name="com.sonyericsson.home.permission.BROADCAST_BADGE" />

Bootstrap 3 Slide in Menu / Navbar on Mobile

This was for my own project and I'm sharing it here too.

DEMO: http://jsbin.com/OjOTIGaP/1/edit

This one had trouble after 3.2, so the one below may work better for you:

https://jsbin.com/seqola/2/edit --- BETTER VERSION, slightly


CSS

/* adjust body when menu is open */
body.slide-active {
    overflow-x: hidden
}
/*first child of #page-content so it doesn't shift around*/
.no-margin-top {
    margin-top: 0px!important
}
/*wrap the entire page content but not nav inside this div if not a fixed top, don't add any top padding */
#page-content {
    position: relative;
    padding-top: 70px;
    left: 0;
}
#page-content.slide-active {
    padding-top: 0
}
/* put toggle bars on the left :: not using button */
#slide-nav .navbar-toggle {
    cursor: pointer;
    position: relative;
    line-height: 0;
    float: left;
    margin: 0;
    width: 30px;
    height: 40px;
    padding: 10px 0 0 0;
    border: 0;
    background: transparent;
}
/* icon bar prettyup - optional */
#slide-nav .navbar-toggle > .icon-bar {
    width: 100%;
    display: block;
    height: 3px;
    margin: 5px 0 0 0;
}
#slide-nav .navbar-toggle.slide-active .icon-bar {
    background: orange
}
.navbar-header {
    position: relative
}
/* un fix the navbar when active so that all the menu items are accessible */
.navbar.navbar-fixed-top.slide-active {
    position: relative
}
/* screw writing importants and shit, just stick it in max width since these classes are not shared between sizes */
@media (max-width:767px) { 
    #slide-nav .container {
        margin: 0;
        padding: 0!important;
    }
    #slide-nav .navbar-header {
        margin: 0 auto;
        padding: 0 15px;
    }
    #slide-nav .navbar.slide-active {
        position: absolute;
        width: 80%;
        top: -1px;
        z-index: 1000;
    }
    #slide-nav #slidemenu {
        background: #f7f7f7;
        left: -100%;
        width: 80%;
        min-width: 0;
        position: absolute;
        padding-left: 0;
        z-index: 2;
        top: -8px;
        margin: 0;
    }
    #slide-nav #slidemenu .navbar-nav {
        min-width: 0;
        width: 100%;
        margin: 0;
    }
    #slide-nav #slidemenu .navbar-nav .dropdown-menu li a {
        min-width: 0;
        width: 80%;
        white-space: normal;
    }
    #slide-nav {
        border-top: 0
    }
    #slide-nav.navbar-inverse #slidemenu {
        background: #333
    }
    /* this is behind the navigation but the navigation is not inside it so that the navigation is accessible and scrolls*/
    #slide-nav #navbar-height-col {
        position: fixed;
        top: 0;
        height: 100%;
        width: 80%;
        left: -80%;
        background: #eee;
    }
    #slide-nav.navbar-inverse #navbar-height-col {
        background: #333;
        z-index: 1;
        border: 0;
    }
    #slide-nav .navbar-form {
        width: 100%;
        margin: 8px 0;
        text-align: center;
        overflow: hidden;
        /*fast clearfixer*/
    }
    #slide-nav .navbar-form .form-control {
        text-align: center
    }
    #slide-nav .navbar-form .btn {
        width: 100%
    }
}
@media (min-width:768px) { 
    #page-content {
        left: 0!important
    }
    .navbar.navbar-fixed-top.slide-active {
        position: fixed
    }
    .navbar-header {
        left: 0!important
    }
}

HTML

 <div class="navbar navbar-inverse navbar-fixed-top" role="navigation" id="slide-nav">
  <div class="container">
   <div class="navbar-header">
    <a class="navbar-toggle"> 
      <span class="sr-only">Toggle navigation</span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
     </a>
    <a class="navbar-brand" href="#">Project name</a>
   </div>
   <div id="slidemenu">
     
          <form class="navbar-form navbar-right" role="form">
            <div class="form-group">
              <input type="search" placeholder="search" class="form-control">
            </div>
            <button type="submit" class="btn btn-primary">Search</button>
          </form>
     
    <ul class="nav navbar-nav">
     <li class="active"><a href="#">Home</a></li>
     <li><a href="#about">About</a></li>
     <li><a href="#contact">Contact</a></li>
     <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
      <ul class="dropdown-menu">
       <li><a href="#">Action</a></li>
       <li><a href="#">Another action</a></li>
       <li><a href="#">Something else here</a></li>
       <li class="divider"></li>
       <li class="dropdown-header">Nav header</li>
       <li><a href="#">Separated link</a></li>
       <li><a href="#">One more separated link</a></li>
       <li><a href="#">Action</a></li>
       <li><a href="#">Another action</a></li>
       <li><a href="#">Something else here</a></li>
       <li class="divider"></li>
       <li class="dropdown-header">Nav header</li>
       <li><a href="#">Separated link</a></li>
       <li><a href="#">One more separated link</a></li>
       <li><a href="#">Action</a></li>
       <li><a href="#">Another action</a></li>
       <li><a href="#">Something else here</a></li>
       <li class="divider"></li>
       <li class="dropdown-header">Nav header</li>
       <li><a href="#">Separated link test long title goes here</a></li>
       <li><a href="#">One more separated link</a></li>
      </ul>
     </li>
    </ul>
          
   </div>
  </div>
 </div>

jQuery

$(document).ready(function () {


    //stick in the fixed 100% height behind the navbar but don't wrap it
    $('#slide-nav.navbar .container').append($('<div id="navbar-height-col"></div>'));

    // Enter your ids or classes
    var toggler = '.navbar-toggle';
    var pagewrapper = '#page-content';
    var navigationwrapper = '.navbar-header';
    var menuwidth = '100%'; // the menu inside the slide menu itself
    var slidewidth = '80%';
    var menuneg = '-100%';
    var slideneg = '-80%';


    $("#slide-nav").on("click", toggler, function (e) {

        var selected = $(this).hasClass('slide-active');

        $('#slidemenu').stop().animate({
            left: selected ? menuneg : '0px'
        });

        $('#navbar-height-col').stop().animate({
            left: selected ? slideneg : '0px'
        });

        $(pagewrapper).stop().animate({
            left: selected ? '0px' : slidewidth
        });

        $(navigationwrapper).stop().animate({
            left: selected ? '0px' : slidewidth
        });


        $(this).toggleClass('slide-active', !selected);
        $('#slidemenu').toggleClass('slide-active');


        $('#page-content, .navbar, body, .navbar-header').toggleClass('slide-active');


    });


    var selected = '#slidemenu, #page-content, body, .navbar, .navbar-header';


    $(window).on("resize", function () {

        if ($(window).width() > 767 && $('.navbar-toggle').is(':hidden')) {
            $(selected).removeClass('slide-active');
        }


    });

});

How do I add 24 hours to a unix timestamp in php?

You could use the DateTime class as well:

$timestamp = mktime(15, 30, 00, 3, 28, 2015);

$d = new DateTime();
$d->setTimestamp($timestamp);

Add a Period of 1 Day:

$d->add(new DateInterval('P1D'));
echo $d->format('c');

See DateInterval for more details.

Print the contents of a DIV

Created something generic to use on any HTML element

HTMLElement.prototype.printMe = printMe;
function printMe(query){             
     var myframe = document.createElement('IFRAME');
     myframe.domain = document.domain;
     myframe.style.position = "absolute";
     myframe.style.top = "-10000px";
     document.body.appendChild(myframe);
     myframe.contentDocument.write(this.innerHTML) ;
     setTimeout(function(){
        myframe.focus();
        myframe.contentWindow.print();
        myframe.parentNode.removeChild(myframe) ;// remove frame
     },3000); // wait for images to load inside iframe
     window.focus();
}
//usage
document.getElementById('xyz').printMe();
document.getElementsByClassName('xyz')[0].printMe();

Hope this helps.

Struct inheritance in C++

Yes, c++ struct is very similar to c++ class, except the fact that everything is publicly inherited, ( single / multilevel / hierarchical inheritance, but not hybrid and multiple inheritance ) here is a code for demonstration

_x000D_
_x000D_
#include<bits/stdc++.h>
using namespace std;

struct parent
{
    int data;
    parent() : data(3){};           // default constructor
    parent(int x) : data(x){};      // parameterized constructor
};
struct child : parent
{
    int a , b;
    child(): a(1) , b(2){};             // default constructor
    child(int x, int y) : a(x) , b(y){};// parameterized constructor
    child(int x, int y,int z)           // parameterized constructor
    {
        a = x;
        b = y;
        data = z;
    }
    child(const child &C)               // copy constructor
    {
        a = C.a;
        b = C.b;
        data = C.data;
    }
};
int main()
{
   child c1 ,
         c2(10 , 20),
         c3(10 , 20, 30),
         c4(c3);

    auto print = [](const child &c) { cout<<c.a<<"\t"<<c.b<<"\t"<<c.data<<endl; };

    print(c1);
    print(c2);
    print(c3);
    print(c4);
}
OUTPUT 
1       2       3
10      20      3
10      20      30
10      20      30
_x000D_
_x000D_
_x000D_

enabling cross-origin resource sharing on IIS7

The 405 response is a "Method not allowed" response. It sounds like your server isn't properly configured to handle CORS preflight requests. You need to do two things:

1) Enable IIS7 to respond to HTTP OPTIONS requests. You are getting the 405 because IIS7 is rejecting the OPTIONS request. I don't know how to do this as I'm not familiar with IIS7, but there are probably others on Stack Overflow who do.

2) Configure your application to respond to CORS preflight requests. You can do this by adding the following two lines underneath the Access-Control-Allow-Origin line in the <customHeaders> section:

<add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />

You may have to add other values to the Access-Control-Allow-Headers section based on what headers your request is asking for. Do you have the sample code for making a request?

You can learn more about CORS and CORS preflight here: http://www.html5rocks.com/en/tutorials/cors/

Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?

[[ has fewer surprises and is generally safer to use. But it is not portable - POSIX doesn't specify what it does and only some shells support it (beside bash, I heard ksh supports it too). For example, you can do

[[ -e $b ]]

to test whether a file exists. But with [, you have to quote $b, because it splits the argument and expands things like "a*" (where [[ takes it literally). That has also to do with how [ can be an external program and receives its argument just normally like every other program (although it can also be a builtin, but then it still has not this special handling).

[[ also has some other nice features, like regular expression matching with =~ along with operators like they are known in C-like languages. Here is a good page about it: What is the difference between test, [ and [[ ? and Bash Tests

Serialize Property as Xml Attribute in Element

Kind of, use the XmlAttribute instead of XmlElement, but it won't look like what you want. It will look like the following:

<SomeModel SomeStringElementName="testData"> 
</SomeModel> 

The only way I can think of to achieve what you want (natively) would be to have properties pointing to objects named SomeStringElementName and SomeInfoElementName where the class contained a single getter named "value". You could take this one step further and use DataContractSerializer so that the wrapper classes can be private. XmlSerializer won't read private properties.

// TODO: make the class generic so that an int or string can be used.
[Serializable]  
public class SerializationClass
{
    public SerializationClass(string value)
    {
        this.Value = value;
    }

    [XmlAttribute("value")]
    public string Value { get; }
}


[Serializable]                     
public class SomeModel                     
{                     
    [XmlIgnore]                     
    public string SomeString { get; set; }                     

    [XmlIgnore]                      
    public int SomeInfo { get; set; }  

    [XmlElement]
    public SerializationClass SomeStringElementName
    {
        get { return new SerializationClass(this.SomeString); }
    }               
}

How to remove stop words using nltk or python

I suppose you have a list of words (word_list) from which you want to remove stopwords. You could do something like this:

filtered_word_list = word_list[:] #make a copy of the word_list
for word in word_list: # iterate over word_list
  if word in stopwords.words('english'): 
    filtered_word_list.remove(word) # remove word from filtered_word_list if it is a stopword

Bootstrap 4 Center Vertical and Horizontal Alignment

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
    <div class="col-12 border border-info">_x000D_
          <div class="d-flex justify-content-center align-items-center" style="height: 100px">_x000D_
              <a href="#" class="btn btn-dark">Transfer</a>_x000D_
              <a href="#" class="btn btn-dark mr-2 ml-2">Replenish</a>_x000D_
              <a href="#" class="btn btn-dark mr-3">Account Details</a>_x000D_
          </div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

Uses of content-disposition in an HTTP response header

For asp.net users, the .NET framework provides a class to create a content disposition header: System.Net.Mime.ContentDisposition

Basic usage:

var cd = new System.Net.Mime.ContentDisposition();
cd.FileName = "myFile.txt";
cd.ModificationDate = DateTime.UtcNow;
cd.Size = 100;
Response.AppendHeader("content-disposition", cd.ToString());

How to add bootstrap in angular 6 project?

npm install --save bootstrap

afterwards, inside angular.json (previously .angular-cli.json) inside the project's root folder, find styles and add the bootstrap css file like this:

for angular 6

"styles": [
          "../node_modules/bootstrap/dist/css/bootstrap.min.css",
          "styles.css"
],

for angular 7

"styles": [
          "node_modules/bootstrap/dist/css/bootstrap.min.css",
          "src/styles.css"
],

Netbeans 8.0.2 The module has not been deployed

UPDATE: this was solved by rebooting but there was another error when running app. This time tomcat woudnt start. To solve this (bugs with latest apache and netbeans versions) follow: Error starting Tomcat from NetBeans - '127.0.0.1*' is not recognized as an internal or external command

What is DOM Event delegation?

The delegation concept

If there are many elements inside one parent, and you want to handle events on them of them - don’t bind handlers to each element. Instead, bind the single handler to their parent, and get the child from event.target. This site provides useful info about how to implement event delegation. http://javascript.info/tutorial/event-delegation

Can you explain the HttpURLConnection connection process?

I went through the exercise to capture low level packet exchange, and found that network connection is only triggered by operations like getInputStream, getOutputStream, getResponseCode, getResponseMessage etc.

Here is the packet exchange captured when I try to write a small program to upload file to Dropbox.

enter image description here

Below is my toy program and annotation

    /* Create a connection LOCAL object,
     * the openConnection() function DOES NOT initiate
     * any packet exchange with the remote server.
     * 
     * The configurations only setup the LOCAL
     * connection object properties.
     */
    HttpURLConnection connection = (HttpURLConnection) dst.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    ...//headers setup
    byte[] testContent = {0x32, 0x32};

    /**
     * This triggers packet exchange with the remote
     * server to create a link. But writing/flushing
     * to a output stream does not send out any data.
     * 
     * Payload are buffered locally.
     */
    try (BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream())) {
        outputStream.write(testContent);
        outputStream.flush();
    }

    /**
     * Trigger payload sending to the server.
     * Client get ALL responses (including response code,
     * message, and content payload) 
     */
    int responseCode = connection.getResponseCode();
    System.out.println(responseCode);

    /* Here no further exchange happens with remote server, since
     * the input stream content has already been buffered
     * in previous step
     */
    try (InputStream is = connection.getInputStream()) {
        Scanner scanner = new Scanner(is);
        StringBuilder stringBuilder = new StringBuilder();
        while (scanner.hasNextLine()) {
        stringBuilder.append(scanner.nextLine()).append(System.lineSeparator());
        }
    }

    /**
     * Trigger the disconnection from the server.
     */
    String responsemsg = connection.getResponseMessage();
    System.out.println(responsemsg);
    connection.disconnect();

AngularJS - Find Element with attribute

Your use-case isn't clear. However, if you are certain that you need this to be based on the DOM, and not model-data, then this is a way for one directive to have a reference to all elements with another directive specified on them.

The way is that the child directive can require the parent directive. The parent directive can expose a method that allows direct directive to register their element with the parent directive. Through this, the parent directive can access the child element(s). So if you have a template like:

<div parent-directive>
  <div child-directive></div>
  <div child-directive></div>
</div>

Then the directives can be coded like:

app.directive('parentDirective', function($window) {
  return {
    controller: function($scope) {
      var registeredElements = [];
      this.registerElement = function(childElement) {
        registeredElements.push(childElement);
      }
    }
  };
});

app.directive('childDirective', function() {
  return {
    require: '^parentDirective',
    template: '<span>Child directive</span>',
    link: function link(scope, iElement, iAttrs, parentController) {
      parentController.registerElement(iElement);
    }
   };
});

You can see this in action at http://plnkr.co/edit/7zUgNp2MV3wMyAUYxlkz?p=preview

Loading local JSON file

function readTextFile(srcfile) {
        try { //this is for IE
            var fso = new ActiveXObject("Scripting.FileSystemObject");;
            if (fso.FileExists(srcfile)) {
                var fileReader = fso.OpenTextFile(srcfile, 1);
                var line = fileReader.ReadLine();
                var jsonOutput = JSON.parse(line); 
            }

        } catch (e) {

        }
}

readTextFile("C:\\Users\\someuser\\json.txt");

What I did was, first of all, from network tab, record the network traffic for the service, and from response body, copy and save the json object in a local file. Then call the function with the local file name, you should be able to see the json object in jsonOutout above.

Round a floating-point number down to the nearest integer?

I used this code where you subtract 0.5 from the number and when you round it, it is the original number rounded down.

round(a-0.5)

Download file using libcurl in C/C++

The example you are using is wrong. See the man page for easy_setopt. In the example write_data uses its own FILE, *outfile, and not the fp that was specified in CURLOPT_WRITEDATA. That's why closing fp causes problems - it's not even opened.

This is more or less what it should look like (no libcurl available here to test)

#include <stdio.h>
#include <curl/curl.h>
/* For older cURL versions you will also need 
#include <curl/types.h>
#include <curl/easy.h>
*/
#include <string>

size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
    size_t written = fwrite(ptr, size, nmemb, stream);
    return written;
}

int main(void) {
    CURL *curl;
    FILE *fp;
    CURLcode res;
    char *url = "http://localhost/aaa.txt";
    char outfilename[FILENAME_MAX] = "C:\\bbb.txt";
    curl = curl_easy_init();
    if (curl) {
        fp = fopen(outfilename,"wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        res = curl_easy_perform(curl);
        /* always cleanup */
        curl_easy_cleanup(curl);
        fclose(fp);
    }
    return 0;
}

Updated: as suggested by @rsethc types.h and easy.h aren't present in current cURL versions anymore.

SOAP client in .NET - references or examples?

I have done quite a bit of what you're talking about, and SOAP interoperability between platforms has one cardinal rule: CONTRACT FIRST. Do not derive your WSDL from code and then try to generate a client on a different platform. Anything more than "Hello World" type functions will very likely fail to generate code, fail to talk at runtime or (my favorite) fail to properly send or receive all of the data without raising an error.

That said, WSDL is complicated, nasty stuff and I avoid writing it from scratch whenever possible. Here are some guidelines for reliable interop of services (using Web References, WCF, Axis2/Java, WS02, Ruby, Python, whatever):

  • Go ahead and do code-first to create your initial WSDL. Then, delete your code and re-generate the server class(es) from the WSDL. Almost every platform has a tool for this. This will show you what odd habits your particular platform has, and you can begin tweaking the WSDL to be simpler and more straightforward. Tweak, re-gen, repeat. You'll learn a lot this way, and it's portable knowledge.
  • Stick to plain old language classes (POCO, POJO, etc.) for complex types. Do NOT use platform-specific constructs like List<> or DataTable. Even PHP associative arrays will appear to work but fail in ways that are difficult to debug across platforms.
  • Stick to basic data types: bool, int, float, string, date(Time), and arrays. Odds are, the more particular you get about a data type, the less agile you'll be to new requirements over time. You do NOT want to change your WSDL if you can avoid it.
  • One exception to the data types above - give yourself a NameValuePair mechanism of some kind. You wouldn't believe how many times a list of these things will save your bacon in terms of flexibility.
  • Set a real namespace for your WSDL. It's not hard, but you might not believe how many web services I've seen in namespace "http://www.tempuri.org". Also, use a URN ("urn:com-myweb-servicename-v1", not a URL-based namespace ("http://servicename.myweb.com/v1". It's not a website, it's an abstract set of characters that defines a logical grouping. I've probably had a dozen people call me for support and say they went to the "website" and it didn't work.

</rant> :)

RESTful Authentication

To be honest with you I've seen great answers here but something that bothers me a bit is when someone will take the whole Stateless concept to a extreme where it becomes dogmatic. It reminds me of those old Smalltalk fans that only wanted to embrace pure OO and if something is not an object, then you're doing it wrong. Give me a break.

The RESTful approach is supposed to make your life easier and reduce the overhead and cost of sessions, try to follow it as it is a wise thing to do, but the minute you follow a discipline (any discipline/guideline) to the extreme where it no longer provides the benefit it was intended for, then you're doing it wrong. Some of the best languages today have both, functional programming and object orientation.

If the easiest way for you to solve your problem is to store the authentication key in a cookie and send it on HTTP header, then do it, just don't abuse it. Remember that sessions are bad when they become heavy and big, if all your session consists of is a short string containing a key, then what's the big deal?

I am open to accept corrections in comments but I just don't see the point (so far) in making our lives miserable to simply avoid keeping a big dictionary of hashes in our server.

Refresh Page C# ASP.NET

Response.Redirect(Request.Url.ToString());

Example of waitpid() in use?

The syntax is

pid_t waitpid(pid_t pid, int *statusPtr, int options);

1.where pid is the process of the child it should wait.

2.statusPtr is a pointer to the location where status information for the terminating process is to be stored.

3.specifies optional actions for the waitpid function. Either of the following option flags may be specified, or they can be combined with a bitwise inclusive OR operator:

WNOHANG WUNTRACED WCONTINUED

If successful, waitpid returns the process ID of the terminated process whose status was reported. If unsuccessful, a -1 is returned.

benifits over wait

1.Waitpid can used when you have more than one child for the process and you want to wait for particular child to get its execution done before parent resumes

2.waitpid supports job control

3.it supports non blocking of the parent process

How to get json key and value in javascript?

You can use the following solution to get a JSON key and value in JavaScript:

var dt = JSON.stringify(data).replace('[', '').replace(']', '');
if (dt) {
  var result = jQuery.parseJSON(dt);
  var val = result.YOUR_OBJECT_NAME;
}

How can I discard remote changes and mark a file as "resolved"?

Make sure of the conflict origin: if it is the result of a git merge, see Brian Campbell's answer.

But if is the result of a git rebase, in order to discard remote (their) changes and use local changes, you would have to do a:

git checkout --theirs -- .

See "Why is the meaning of “ours” and “theirs” reversed"" to see how ours and theirs are swapped during a rebase (because the upstream branch is checked out).

How can I reverse a NSArray in Objective-C?

Or the Scala-way:

-(NSArray *)reverse
{
    if ( self.count < 2 )
        return self;
    else
        return [[self.tail reverse] concat:[NSArray arrayWithObject:self.head]];
}

-(id)head
{
    return self.firstObject;
}

-(NSArray *)tail
{
    if ( self.count > 1 )
        return [self subarrayWithRange:NSMakeRange(1, self.count - 1)];
    else
        return @[];
}

Import Excel to Datagridview

try this following snippet, its working fine.

private void button1_Click(object sender, EventArgs e)
{
     try
     {
             OpenFileDialog openfile1 = new OpenFileDialog();
             if (openfile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
             {
                   this.textBox1.Text = openfile1.FileName;
             }
             {
                   string pathconn = "Provider = Microsoft.jet.OLEDB.4.0; Data source=" + textBox1.Text + ";Extended Properties=\"Excel 8.0;HDR= yes;\";";
                   OleDbConnection conn = new OleDbConnection(pathconn);
                   OleDbDataAdapter MyDataAdapter = new OleDbDataAdapter("Select * from [" + textBox2.Text + "$]", conn);
                   DataTable dt = new DataTable();
                   MyDataAdapter.Fill(dt);
                   dataGridView1.DataSource = dt;
             }
      }
      catch { }
}

How to debug Spring Boot application with Eclipse?

Easier solution:

Instead of typing mvn spring-boot:run, simply type mvnDebug spring-boot:run

You will still need to attach the debugger in Eclipse by making a new Debug Configuration for a "Remote Java Application" on the relevant port.

PHP multidimensional array search by value

Expanding on the function @mayhem created, this example would be more of a "fuzzy" search in case you just want to match part (most) of a search string:

 function searchArrayKeyVal($sKey, $id, $array) {
    foreach ($array as $key => $val) {
        if (strpos(strtolower($val[$sKey]), strtolower(trim($id))) !== false) {
            return $key;
        }
    }
         return false;
 }

For example the value in the array is Welcome to New York! and you wanted the first instance of just "New York!"

MongoDB query multiple collections at once

Here is answer for your question.

db.getCollection('users').aggregate([
    {$match : {admin : 1}},
    {$lookup: {from: "posts",localField: "_id",foreignField: "owner_id",as: "posts"}},
    {$project : {
            posts : { $filter : {input : "$posts"  , as : "post", cond : { $eq : ['$$post.via' , 'facebook'] } } },
            admin : 1

        }}

])

Or either you can go with mongodb group option.

db.getCollection('users').aggregate([
    {$match : {admin : 1}},
    {$lookup: {from: "posts",localField: "_id",foreignField: "owner_id",as: "posts"}},
    {$unwind : "$posts"},
    {$match : {"posts.via":"facebook"}},
    { $group : {
            _id : "$_id",
            posts : {$push : "$posts"}
    }}
])

Should I use int or Int32

There is no difference between int and Int32, but as int is a language keyword many people prefer it stylistically (just as with string vs String).

How do I pipe or redirect the output of curl -v?

This simple example shows how to capture curl output, and use it in a bash script

test.sh

function main
{
  \curl -vs 'http://google.com'  2>&1
  # note: add -o /tmp/ignore.png if you want to ignore binary output, by saving it to a file. 
}

# capture output of curl to a variable
OUT=$(main)

# search output for something using grep.
echo
echo "$OUT" | grep 302 
echo
echo "$OUT" | grep title 

In Postgresql, force unique on combination of two columns

If, like me, you landed here with:

  • a pre-existing table,
  • to which you need to add a new column, and
  • also need to add a new unique constraint on the new column as well as an old one, AND
  • be able to undo it all (i.e. write a down migration)

Here is what worked for me, utilizing one of the above answers and expanding it:

-- up

ALTER TABLE myoldtable ADD COLUMN newcolumn TEXT;
ALTER TABLE myoldtable ADD CONSTRAINT myoldtable_oldcolumn_newcolumn_key UNIQUE (oldcolumn, newcolumn);

---

ALTER TABLE myoldtable DROP CONSTRAINT myoldtable_oldcolumn_newcolumn_key;
ALTER TABLE myoldtable DROP COLUMN newcolumn;

-- down

What is the purpose of backbone.js?

Backbone.js is a JavaScript framework that helps you organize your code. It is literally a backbone upon which you build your application. It doesn't provide widgets (like jQuery UI or Dojo).

It gives you a cool set of base classes that you can extend to create clean JavaScript code that interfaces with RESTful endpoints on your server.

How to change pivot table data source in Excel?

right click on the pivot table in excel choose wizard click 'back' click 'get data...' in the query window File - Table Definition

then you can create a new or choose a different connection

What is the difference between print and puts?

puts adds a new line to the end of each argument if there is not one already.

print does not add a new line.


For example:

puts [[1,2,3], [4,5,nil]] Would return:

1
2
3
4
5

Whereas print [[1,2,3], [4,5,nil]] would return:

[[1,2,3], [4,5,nil]]
Notice how puts does not output the nil value whereas print does.

Is Java RegEx case-insensitive?

You also can lead your initial string, which you are going to check for pattern matching, to lower case. And use in your pattern lower case symbols respectively.

Postgresql - select something where date = "01/01/11"

With PostgreSQL there are a number of date/time functions available, see here.

In your example, you could use:

SELECT * FROM myTable WHERE date_trunc('day', dt) = 'YYYY-MM-DD';

If you are running this query regularly, it is possible to create an index using the date_trunc function as well:

CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt) );

One advantage of this is there is some more flexibility with timezones if required, for example:

CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt at time zone 'Australia/Sydney') );
SELECT * FROM myTable WHERE date_trunc('day', dt at time zone 'Australia/Sydney') = 'YYYY-MM-DD';

How do I insert multiple checkbox values into a table?

I think this should work .. :)

<input type="checkbox" name="Days[]" value="Daily">Daily<br>
<input type="checkbox" name="Days[]" value="Sunday">Sunday<br>

Parsing query strings on Android

For a servlet or a JSP page you can get querystring key/value pairs by using request.getParameter("paramname")

String name = request.getParameter("name");

There are other ways of doing it but that's the way I do it in all the servlets and jsp pages that I create.

How do I make a PHP form that submits to self?

Your submit button doesn't have a name. Add name="submit" to your submit button.

If you view source on the form in the browser, you'll see how it submits to self - the form's action attribute will contain the name of the current script - therefore when the form submits, it submits to itself. Edit for vanity sake!

H.264 file size for 1 hr of HD video

It really depends on many settings, on both the audio and video side of things. If you follow the compression-settings of this video, then it's approximately 3GB per hour. If you have a Mac, I would definitely recommend using 'Compressor' as it is fairly easy to use and works flawless.

As far as storage is concerned, if you're looking at 100hrs / 300GB, I would definitely go with an external hard drive. Video files are so huge, that they (even if they don't totally fill up your hard disk) really do confuse your computer. Make sure to make some time for compressing the whole thing because it takes hours and hours and hours.... for 100 hrs worth of footage, it'll take days.

How to compare strings

You need to use strcmp.

if (strcmp(string,"add") == 0){
    print("success!");
}

Turn off enclosing <p> tags in CKEditor 3.0

Edit the source (or turn off rich text) and replace the p tag with a div. Then style the div any which way you want.

ckEditor won't add any wrapper element on the next submit as you've got the div in there.

(This solved my issue, I'm using Drupal and need small snippets of html which the editor always added the extra, but the rest of the time I want the wrapping p tag).

How do you make a div follow as you scroll?

The post is old but I found a perfect CSS for the purpose and I want to share it.

A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place (like position:fixed).

    div.sticky {
        position: -webkit-sticky; /* Safari */
        position: sticky;
        top: 0;
        background-color: green;
        border: 2px solid #4CAF50;
    }

Source: https://www.w3schools.com/css/css_positioning.asp

Exercises to improve my Java programming skills

I highly recommend reading the book 'Effective Java' from Joshua Bloch.

WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server

I just had the same problem. It turns out that my installation of Windows is using the IPv6 address ::1 instead of 127.0.0.1. To solve this, I opened httpd.conf and changed the following line:

Allow from 127.0.0.1

to:

Allow from 127.0.0.1 ::1

Now I can access the server through localhost. Whatever you do, don't remove the Deny from all from the line above, or anyone on your network can gain access to your web server (unless that's what you want of course).

Variable number of arguments in C++?

It is possible now...using boost any and templates In this case, arguments type can be mixed

#include <boost/any.hpp>
#include <iostream>

#include <vector>
using boost::any_cast;

template <typename T, typename... Types> 
void Alert(T var1,Types... var2) 
{ 

    std::vector<boost::any> a(  {var1,var2...});

    for (int i = 0; i < a.size();i++)
    {

    if (a[i].type() == typeid(int))
    {
        std::cout << "int "  << boost::any_cast<int> (a[i]) << std::endl;
    }
    if (a[i].type() == typeid(double))
    {
        std::cout << "double "  << boost::any_cast<double> (a[i]) << std::endl;
    }
    if (a[i].type() == typeid(const char*))
    {
        std::cout << "char* " << boost::any_cast<const char*> (a[i]) <<std::endl;
    }
    // etc
    }

} 


void main()
{
    Alert("something",0,0,0.3);
}

How to find the Vagrant IP?

Because I haven't seen it here yet... When you vagrant ssh into the box, I realized it actually tells you the ip addresses of the interfaces. You can get it there. For example.

 {~/Documents/jupyterhub-ansible} (features *%)$  vagrant ssh
Welcome to Ubuntu 18.04.2 LTS (GNU/Linux 4.15.0-50-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Wed May 22 12:00:34 UTC 2019

  System load:  0.12              Processes:             101
  Usage of /:   56.5% of 9.63GB   Users logged in:       0
  Memory usage: 19%               IP address for enp0s3: 10.0.2.15
  Swap usage:   0%                IP address for enp0s8: 192.168.33.10


10 packages can be updated.
1 update is a security update.


Last login: Wed May 22 12:00:04 2019 from 192.168.33.1
vagrant@ubuntu-bionic:~$ 

In my vagrant file I assigned the address like this:

config.vm.network "private_network", ip: "192.168.33.10"

and as you can see, IP address for enp0s8: 192.168.33.10