Programs & Examples On #Delayedvariableexpansion

How to get time difference in minutes in PHP

$date1=date_create("2020-03-15");
$date2=date_create("2020-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");

For detailed format specifiers, visit the link.

How to Copy Contents of One Canvas to Another Canvas Locally

@robert-hurst has a cleaner approach.

However, this solution may also be used, in places when you actually want to have a copy of Data Url after copying. For example, when you are building a website that uses lots of image/canvas operations.

    // select canvas elements
    var sourceCanvas = document.getElementById("some-unique-id");
    var destCanvas = document.getElementsByClassName("some-class-selector")[0];

    //copy canvas by DataUrl
    var sourceImageData = sourceCanvas.toDataURL("image/png");
    var destCanvasContext = destCanvas.getContext('2d');

    var destinationImage = new Image;
    destinationImage.onload = function(){
      destCanvasContext.drawImage(destinationImage,0,0);
    };
    destinationImage.src = sourceImageData;

What is the difference between signed and unsigned variables?

This may not be the exact definition but I'll give you an example: If you were to create a random number taking it from the system time, here using the unsigned variable is beneficial as there is large scope for random numbers as signed numbers give both positive and negative numbers. As the system time can't be negative we use unsigned variable(Only positive numbers) and we have more wide range of random numbers.

Using Google Text-To-Speech in Javascript

Run this code it will take input as audio(microphone) and convert into the text than audio play.

<!doctype HTML>
<head>
<title>MY Echo</title>
<script src="http://code.responsivevoice.org/responsivevoice.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.1/css/font-awesome.min.css" />
<style type="text/css">
    body {
        font-family: verdana;
    }

    #result {
        height: 100px;
        border: 1px solid #ccc;
        padding: 10px;
        box-shadow: 0 0 10px 0 #bbb;
        margin-bottom: 30px;
        font-size: 14px;
        line-height: 25px;
    }

    button {
        font-size: 20px;
        position: relative;
        left: 50%;
    }
</style>

Speech to text converter in JS var r = document.getElementById('result');

    function startConverting() {
        if ('webkitSpeechRecognition' in window) {
            var speechRecognizer = new webkitSpeechRecognition();
            speechRecognizer.continuous = true;
            speechRecognizer.interimResults = true;
            speechRecognizer.lang = 'en-IN';
            speechRecognizer.start();
            var finalTranscripts = '';
            speechRecognizer.onresult = function(event) {
                var interimTranscripts = '';
                for (var i = event.resultIndex; i < event.results.length; i++) {
                    var transcript = event.results[i][0].transcript;
                    transcript.replace("\n", "<br>");
                    if (event.results[i].isFinal) {
                        finalTranscripts += transcript;
                        var speechresult = finalTranscripts;
                        console.log(speechresult);
                        if (speechresult) {
                            responsiveVoice.speak(speechresult, "UK English Female", {
                                pitch: 1
                            }, {
                                rate: 1
                            });
                        }
                    } else {
                        interimTranscripts += transcript;
                    }
                }
                r.innerHTML = finalTranscripts + '<span style="color:#999">' + interimTranscripts + '</span>';
            };
            speechRecognizer.onerror = function(event) {};
        } else {
            r.innerHTML = 'Your browser is not supported. If google chrome, please upgrade!';
        }
    }
</script>
</body>

</html>

Zoom to fit: PDF Embedded in HTML

Use iframe tag do display pdf file with zoom fit

<iframe src="filename.pdf" width="" height="" border="0"></iframe>

Insert line break inside placeholder attribute of a textarea?

Based on a combination of three different tricks I saw this seems to work in all browsers I've tested it in.

HTML:

<textarea placeholder="Line One&#10;Line Two&#10;&#10;Line Four"></textarea>

JS At bottom of HTML file:

<script>
    
    var textAreas = document.getElementsByTagName('textarea');

    Array.prototype.forEach.call(textAreas, function(elem) {
        elem.placeholder = elem.placeholder.replace(/\u000A/g, 
        '                                                     \
                                                              \
                                                              \
        \n\u2063');
    });

</script>

Note, the extra spaces will cause a clean wrap around but there has to be enough spaces that it will fill the width of the textarea, I placed enough that it's sufficient for my projects but you could be robust and generate them by observing the textarea.width and calculating the proper cardinality.

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) on dispatch_semaphore_dispose

I had a different issue that brought me to this question, which will probably be more common than the overrelease issue in the accepted answer.

Root cause was our completion block being called twice due to bad if/else fallthrough in the network handler, leading to two calls of dispatch_group_leave for every one call to dispatch_group_enter.

Completion block called multiple times:

dispatch_group_enter(group);
[self badMethodThatCallsMULTIPLECompletions:^(NSString *completion) {

    // this block is called multiple times
    // one `enter` but multiple `leave`

    dispatch_group_leave(group);
}];

Debug via the dispatch_group's count

Upon the EXC_BAD_INSTRUCTION, you should still have access to your dispatch_group in the debugger. DispatchGroup: check how many "entered"

Print out the dispatch_group and you'll see:

<OS_dispatch_group: group[0x60800008bf40] = { xrefcnt = 0x2, refcnt = 0x1, port = 0x0, count = -1, waiters = 0 }>

When you see count = -1 it indicates that you've over-left the dispatch_group. Be sure to dispatch_enter and dispatch_leave the group in matched pairs.

Reloading the page gives wrong GET request with AngularJS HTML5 mode

IIS URL Rewrite Rule to prevent 404 error after page refresh in html5mode

For angular running under IIS on Windows

<rewrite>
  <rules>
    <rule name="AngularJS" stopProcessing="true">
      <match url=".*" />
      <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
      </conditions>
      <action type="Rewrite" url="/" />
    </rule>
  </rules>
</rewrite>

NodeJS / ExpressJS Routes to prevent 404 error after page refresh in html5mode

For angular running under Node/Express

var express = require('express');
var path = require('path');
var router = express.Router();

// serve angular front end files from root path
router.use('/', express.static('app', { redirect: false }));

// rewrite virtual urls to angular app to enable refreshing of internal pages
router.get('*', function (req, res, next) {
    res.sendFile(path.resolve('app/index.html'));
});

module.exports = router;

More info at: AngularJS - Enable HTML5 Mode Page Refresh Without 404 Errors in NodeJS and IIS

Eclipse Optimize Imports to Include Static Imports

Not exactly what I wanted, but I found a workaround. In Eclipse 3.4 (Ganymede), go to

Window->Preferences->Java->Editor->Content Assist

and check the checkbox for Use static imports (only 1.5 or higher).

This will not bring in the import on an Optimize Imports, but if you do a Quick Fix (CTRL + 1) on the line it will give you the option to add the static import which is good enough.

"Debug only" code that should run only when "turned on"

If you want to know whether if debugging, everywhere in program. Use this.

Declare global variable.

bool isDebug=false;

Create function for checking debug mode

[ConditionalAttribute("DEBUG")]
    public static void isDebugging()
    {
        isDebug = true;
    }

In the initialize method call the function

isDebugging();

Now in the entire program. You can check for debugging and do the operations. Hope this Helps!

Android: How to handle right to left swipe gestures

Expanding on Mirek's answer, for the case when you want to use the swipe gestures inside a scroll view. By default the touch listener for the scroll view get disabled and therefore scroll action does not happen. In order to fix this you need to override the dispatchTouchEvent method of the Activity and return the inherited version of this method after you're done with your own listener.

In order to do a few modifications to Mirek's code: I add a getter for the gestureDetector in the OnSwipeTouchListener.

public GestureDetector getGestureDetector(){
    return  gestureDetector;
}

Declare the OnSwipeTouchListener inside the Activity as a class-wide field.

OnSwipeTouchListener onSwipeTouchListener;

Modify the usage code accordingly:

onSwipeTouchListener = new OnSwipeTouchListener(MyActivity.this) {
    public void onSwipeTop() {
        Toast.makeText(MyActivity.this, "top", Toast.LENGTH_SHORT).show();
    }
    public void onSwipeRight() {
        Toast.makeText(MyActivity.this, "right", Toast.LENGTH_SHORT).show();
    }
    public void onSwipeLeft() {
        Toast.makeText(MyActivity.this, "left", Toast.LENGTH_SHORT).show();
    }
    public void onSwipeBottom() {
        Toast.makeText(MyActivity.this, "bottom", Toast.LENGTH_SHORT).show();
    }
});

imageView.setOnTouchListener(onSwipeTouchListener);

And override the dispatchTouchEvent method inside Activity:

@Override
    public boolean dispatchTouchEvent(MotionEvent ev){
        swipeListener.getGestureDetector().onTouchEvent(ev); 
            return super.dispatchTouchEvent(ev);   
    }

Now both scroll and swipe actions should work.

MYSQL query between two timestamps

Try this its worked for me

SELECT * from bookedroom
    WHERE UNIX_TIMESTAMP('2020-8-07 5:31')
        between UNIX_TIMESTAMP('2020-8-07 5:30') and
        UNIX_TIMESTAMP('2020-8-09 5:30')

Graph visualization library in JavaScript

Disclaimer: I'm a developer of Cytoscape.js

Cytoscape.js is a HTML5 graph visualisation library. The API is sophisticated and follows jQuery conventions, including

  • selectors for querying and filtering (cy.elements("node[weight >= 50].someClass") does much as you would expect),
  • chaining (e.g. cy.nodes().unselect().trigger("mycustomevent")),
  • jQuery-like functions for binding to events,
  • elements as collections (like jQuery has collections of HTMLDomElements),
  • extensibility (can add custom layouts, UI, core & collection functions, and so on),
  • and more.

If you're thinking about building a serious webapp with graphs, you should at least consider Cytoscape.js. It's free and open-source:

http://js.cytoscape.org

How can I display the current branch and folder path in terminal?

Keep it fast, keep it simple

put this in your ~/.bashrc file.

git_stuff() {
  git_branch=$(git branch --show-current 2> /dev/null)
  if [[ $git_branch == "" ]];then
    echo -e ""
  elif [[ $git_branch == *"Nocommit"* ]];then
    echo -e "No commits"
  else
    echo -e "$git_branch"
  fi
}
prompt() {
  PS1="\e[2m$(date +%H:%M:%S.%3N) \e[4m$(git_stuff)\033[0m\n\w$ "
}
PROMPT_COMMAND=prompt

Then source ~/.bashrc

enter image description here

Is there a macro to conditionally copy rows to another worksheet?

The way I would do this manually is:

  • Use Data - AutoFilter
  • Apply a custom filter based on a date range
  • Copy the filtered data to the relevant month sheet
  • Repeat for every month

Listed below is code to do this process via VBA.

It has the advantage of handling monthly sections of data rather than individual rows. Which can result in quicker processing for larger sets of data.

    Sub SeperateData()

    Dim vMonthText As Variant
    Dim ExcelLastCell As Range
    Dim intMonth As Integer

   vMonthText = Array("January", "February", "March", "April", "May", _
 "June", "July", "August", "September", "October", "November", "December")

        ThisWorkbook.Worksheets("Sharepoint").Select
        Range("A1").Select

    RowCount = ThisWorkbook.Worksheets("Sharepoint").UsedRange.Rows.Count
'Forces excel to determine the last cell, Usually only done on save
    Set ExcelLastCell = ThisWorkbook.Worksheets("Sharepoint"). _
     Cells.SpecialCells(xlLastCell)
'Determines the last cell with data in it


        Selection.EntireColumn.Insert
        Range("A1").FormulaR1C1 = "Month No."
        Range("A2").FormulaR1C1 = "=MONTH(RC[1])"
        Range("A2").Select
        Selection.Copy
        Range("A3:A" & ExcelLastCell.Row).Select
        ActiveSheet.Paste
        Application.CutCopyMode = False
        Calculate
    'Insert a helper column to determine the month number for the date

        For intMonth = 1 To 12
            Range("A1").CurrentRegion.Select
            Selection.AutoFilter Field:=1, Criteria1:="" & intMonth
            Selection.Copy
            ThisWorkbook.Worksheets("" & vMonthText(intMonth - 1)).Select
            Range("A1").Select
            ActiveSheet.Paste
            Columns("A:A").Delete Shift:=xlToLeft
            Cells.Select
            Cells.EntireColumn.AutoFit
            Range("A1").Select
            ThisWorkbook.Worksheets("Sharepoint").Select
            Range("A1").Select
            Application.CutCopyMode = False
        Next intMonth
    'Filter the data to a particular month
    'Convert the month number to text
    'Copy the filtered data to the month sheet
    'Delete the helper column
    'Repeat for each month

        Selection.AutoFilter
        Columns("A:A").Delete Shift:=xlToLeft
 'Get rid of the auto-filter and delete the helper column

    End Sub

How to draw a circle with text in the middle?

I think you want to write text in an oval or circle? why not this one?

_x000D_
_x000D_
<span style="border-radius:50%; border:solid black 1px;padding:5px">Hello</span>
_x000D_
_x000D_
_x000D_

How to check the differences between local and github before the pull

git pull is really equivalent to running git fetch and then git merge. The git fetch updates your so-called "remote-tracking branches" - typically these are ones that look like origin/master, github/experiment, etc. that you see with git branch -r. These are like a cache of the state of branches in the remote repository that are updated when you do git fetch (or a successful git push).

So, suppose you've got a remote called origin that refers to your GitHub repository, you would do:

git fetch origin

... and then do:

git diff master origin/master

... in order to see the difference between your master, and the one on GitHub. If you're happy with those differences, you can merge them in with git merge origin/master, assuming master is your current branch.

Personally, I think that doing git fetch and git merge separately is generally a good idea.

Find the day of a week

Use the lubridate package and function wday:

library(lubridate)
df$date <- as.Date(df$date)
wday(df$date, label=TRUE)
[1] Wed   Wed   Thurs
Levels: Sun < Mon < Tues < Wed < Thurs < Fri < Sat

How can I round down a number in Javascript?

Rounding a number towards 0 can be done by subtracting its signed fractional part number % 1:

rounded = number - number % 1;

Like Math.floor (rounds towards -Infinity) this method is perfectly accurate.

There are differences in the handling of -0, +Infinity and -Infinity though:

Math.floor(-0) => -0
-0 - -0 % 1    => +0

Math.floor(Infinity)    => Infinity
Infinity - Infinity % 1 => NaN

Math.floor(-Infinity)     => -Infinity
-Infinity - -Infinity % 1 => NaN

Closing JFrame with button click

You can use super.dispose() method which is more similar to close operation.

What is a "callable"?

__call__ makes any object be callable as a function.

This example will output 8:

class Adder(object):
  def __init__(self, val):
    self.val = val

  def __call__(self, val):
    return self.val + val

func = Adder(5)
print func(3)

'True' and 'False' in Python

While the other posters addressed why is True does what it does, I wanted to respond to this part of your post:

I thought Python treats anything with value as True. Why is this happening?

Coming from Java, I got tripped up by this, too. Python does not treat anything with a value as True. Witness:

if 0:
    print("Won't get here")

This will print nothing because 0 is treated as False. In fact, zero of any numeric type evaluates to False. They also made decimal work the way you'd expect:

from decimal import *
from fractions import *

if 0 or 0.0 or 0j or Decimal(0) or Fraction(0, 1):
    print("Won't get here")

Here are the other value which evaluate to False:

if None or False or '' or () or [] or {} or set() or range(0):
    print("Won't get here")

Sources:

  1. Python Truth Value Testing is Awesome
  2. Truth Value Testing (in Built-in Types)

What is a reasonable length limit on person "Name" fields?

depending on who is going to be using your database, for example African names will do with varchar(20) for last name and first name separated. however it is different from nation to nation but for the sake saving your database resources and memory, separate last name and first name fields and use varchar(30) think that will work.

C#: Looping through lines of multiline string

I suggest using a combination of StringReader and my LineReader class, which is part of MiscUtil but also available in this StackOverflow answer - you can easily copy just that class into your own utility project. You'd use it like this:

string text = @"First line
second line
third line";

foreach (string line in new LineReader(() => new StringReader(text)))
{
    Console.WriteLine(line);
}

Looping over all the lines in a body of string data (whether that's a file or whatever) is so common that it shouldn't require the calling code to be testing for null etc :) Having said that, if you do want to do a manual loop, this is the form that I typically prefer over Fredrik's:

using (StringReader reader = new StringReader(input))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        // Do something with the line
    }
}

This way you only have to test for nullity once, and you don't have to think about a do/while loop either (which for some reason always takes me more effort to read than a straight while loop).

Bootstrap4 adding scrollbar to div

Yes, It is possible, Just add a class like anyclass and give some CSS style. Live

.anyClass {
  height:150px;
  overflow-y: scroll;
}

_x000D_
_x000D_
.anyClass {_x000D_
  height:150px;_x000D_
  overflow-y: scroll;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class=" col-md-2">_x000D_
  <ul class="nav nav-pills nav-stacked anyClass">_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link active" href="#">Active</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li><li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li><li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li><li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li><li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link disabled" href="#">Disabled</a>_x000D_
    </li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to fix syntax error, unexpected T_IF error in php?

add semi-colon the line before:

$total_pages = ceil($total_result / $per_page);

Simple way to get element by id within a div tag?

A simple way to do what OP desires in core JS.

document.getElementById(parent.id).children[child.id];

How to create hyperlink to call phone number on mobile devices?

Dashes (-) have no significance other than making the number more readable, so you might as well include them.

Since we never know where our website visitors are coming from, we need to make phone numbers callable from anywhere in the world. For this reason the + sign is always necessary. The + sign is automatically converted by your mobile carrier to your international dialing prefix, also known as "exit code". This code varies by region, country, and sometimes a single country can use multiple codes, depending on the carrier. Fortunately, when it is a local call, dialing it with the international format will still work.

Using your example number, when calling from China, people would need to dial:

00-1-555-555-1212

And from Russia, they would dial

810-1-555-555-1212

The + sign solves this issue by allowing you to omit the international dialing prefix.

After the international dialing prefix comes the country code(pdf), followed by the geographic code (area code), finally the local phone number.

Therefore either of the last two of your examples would work, but my recommendation is to use this format for readability:

<a href="tel:+1-555-555-1212">+1-555-555-1212</a>

Note: For numbers that contain a trunk prefix different from the country code (e.g. if you write it locally with brackets around a 0), you need to omit it because the number must be in international format.

How to make Java Set?

Like this:

import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

Or adding from an Array/ or multiple literals; wrap to a list, first.

Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals

To get the intersection:

// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);

Hope this answer helps. Vote for it!

CSS content generation before or after 'input' elements

This is not due to input tags not having any content per-se, but that their content is outside the scope of CSS.

input elements are a special type called replaced elements, these do not support :pseudo selectors like :before and :after.

In CSS, a replaced element is an element whose representation is outside the scope of CSS. These are kind of external objects whose representation is independent of the CSS. Typical replaced elements are <img>, <object>, <video> or form elements like <textarea> and <input>. Some elements, like <audio> or <canvas> are replaced elements only in specific cases. Objects inserted using the CSS content properties are anonymous replaced elements.

Note that this is even referred to in the spec:

This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML).

And more explicitly:

Replaced elements do not have ::before and ::after pseudo-elements

Whitespaces in java

boolean containsWhitespace = false;
for (int i = 0; i < text.length() && !containsWhitespace; i++) {
    if (Character.isWhitespace(text.charAt(i)) {
        containsWhitespace = true;
    }
}
return containsWhitespace;

or, using Guava,

boolean containsWhitespace = CharMatcher.WHITESPACE.matchesAnyOf(text);

Verify if file exists or not in C#

Simple answer is that you can't - you won't be able to check a for a file on their machine from an ASP website, as to do so would be a dangerous risk for them.

You have to give them a file upload control - and there's not much you can do with that control. For security reasons javascript can't really touch it.

<asp:FileUpload ID="FileUpload1" runat="server" />

They then pick a file to upload, and you have to deal with any empty file that they might send up server side.

java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver

For someone looking to solve same by using maven. Add below dependency in POM:

<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <version>7.0.0.jre8</version>
</dependency>

And use below code for connection:

String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=master;user=sa;password=your_password";

try {
    System.out.print("Connecting to SQL Server ... ");
    try (Connection connection = DriverManager.getConnection(connectionUrl))        {
        System.out.println("Done.");
    }
} catch (Exception e) {
    System.out.println();
    e.printStackTrace();
}

Look for this link for other CRUD type of queries.

R: Print list to a text file

Format won't be completely the same, but it does write the data to a text file, and R will be able to reread it using dget when you want to retrieve it again as a list.

dput(mylist, "mylist.txt")

Automatically start a Windows Service on install

How about following commands?

net start "<service name>"
net stop "<service name>"

Extract substring using regexp in plain bash

Quick 'n dirty, regex-free, low-robustness chop-chop technique

string="US/Central - 10:26 PM (CST)"
etime="${string% [AP]M*}"
etime="${etime#* - }"

scrollTop animation without jquery

HTML:

<button onclick="scrollToTop(1000);"></button>

1# JavaScript (linear):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const totalScrollDistance = document.scrollingElement.scrollTop;
    let scrollY = totalScrollDistance, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollY will be -Infinity
            scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
            if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = scrollY;
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}

2# JavaScript (ease in and out):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const cosParameter = document.scrollingElement.scrollTop / 2;
    let scrollCount = 0, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollCount will be Infinity
            scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
            if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}
/* 
  Explanation:
  - pi is the length/end point of the cosinus intervall (see below)
  - newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
    (for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
  - newTimestamp - oldTimestamp equals the delta time

    a * cos (bx + c) + d                        | c translates along the x axis = 0
  = a * cos (bx) + d                            | d translates along the y axis = 1 -> only positive y values
  = a * cos (bx) + 1                            | a stretches along the y axis = cosParameter = window.scrollY / 2
  = cosParameter + cosParameter * (cos bx)  | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
  = cosParameter + cosParameter * (cos scrollCount * x)
*/

Note:

  • Duration in milliseconds (1000ms = 1s)
  • Second script uses the cos function. Example curve:

enter image description here

3# Simple scrolling library on Github

Is the Scala 2.8 collections library a case of "the longest suicide note in history"?

Is this going to put people off coming to Scala?

I don't think it is the main factor that will affect how popular Scala will become, because Scala has a lot of power and its syntax is not as foreign to a Java/C++/PHP programmer as Haskell, OCaml, SML, Lisps, etc..

But I do think Scala's popularity will plateau at less than where Java is today, because I also think the next mainstream language must be much simplified, and the only way I see to get there is pure immutability, i.e. declarative like HTML, but Turing complete. However, I am biased because I am developing such a language, but I only did so after ruling out over a several month study that Scala could not suffice for what I needed.

Is this going to give Scala a bad name in the commercial world as an academic plaything that only dedicated PhD students can understand? Are CTOs and heads of software going to get scared off?

I don't think Scala's reputation will suffer from the Haskell complex. But I think that some will put off learning it, because for most programmers, I don't yet see a use case that forces them to use Scala, and they will procrastinate learning about it. Perhaps the highly-scalable server side is the most compelling use case.

And, for the mainstream market, first learning Scala is not a "breath of fresh air", where one is writing programs immediately, such as first using HTML or Python. Scala tends to grow on you, after one learns all the details that one stumbles on from the start. However, maybe if I had read Programming in Scala from the start, my experience and opinion of the learning curve would have been different.

Was the library re-design a sensible idea?

Definitely.

If you're using Scala commercially, are you worried about this? Are you planning to adopt 2.8 immediately or wait to see what happens?

I am using Scala as the initial platform of my new language. I probably wouldn't be building code on Scala's collection library if I was using Scala commercially otherwise. I would create my own category theory based library, since the one time I looked, I found Scalaz's type signatures even more verbose and unwieldy than Scala's collection library. Part of that problem perhaps is Scala's way of implementing type classes, and that is a minor reason I am creating my own language.


I decided to write this answer, because I wanted to force myself to research and compare Scala's collection class design to the one I am doing for my language. Might as well share my thought process.

The 2.8 Scala collections use of a builder abstraction is a sound design principle. I want to explore two design tradeoffs below.

  1. WRITE-ONLY CODE: After writing this section, I read Carl Smotricz's comment which agrees with what I expect to be the tradeoff. James Strachan and davetron5000's comments concur that the meaning of That (it is not even That[B]) and the mechanism of the implicit is not easy to grasp intuitively. See my use of monoid in issue #2 below, which I think is much more explicit. Derek Mahar's comment is about writing Scala, but what about reading the Scala of others that is not "in the common cases".

    One criticism I have read about Scala, is that it is easier to write it, than read the code that others have written. And I find this to be occasionally true for various reasons (e.g. many ways to write a function, automatic closures, Unit for DSLs, etc), but I am undecided if this is major factor. Here the use of implicit function parameters has pluses and minuses. On the plus side, it reduces verbosity and automates selection of the builder object. In Odersky's example the conversion from a BitSet, i.e. Set[Int], to a Set[String] is implicit. The unfamiliar reader of the code might not readily know what the type of collection is, unless they can reason well about the all the potential invisible implicit builder candidates which might exist in the current package scope. Of course, the experienced programmer and the writer of the code will know that BitSet is limited to Int, thus a map to String has to convert to a different collection type. But which collection type? It isn't specified explicitly.

  2. AD-HOC COLLECTION DESIGN: After writing this section, I read Tony Morris's comment and realized I am making nearly the same point. Perhaps my more verbose exposition will make the point more clear.

    In "Fighting Bit Rot with Types" Odersky & Moors, two use cases are presented. They are the restriction of BitSet to Int elements, and Map to pair tuple elements, and are provided as the reason that the general element mapping function, A => B, must be able to build alternative destination collection types. However, afaik this is flawed from a category theory perspective. To be consistent in category theory and thus avoid corner cases, these collection types are functors, in which each morphism, A => B, must map between objects in the same functor category, List[A] => List[B], BitSet[A] => BitSet[B]. For example, an Option is a functor that can be viewed as a collection of sets of one Some( object ) and the None. There is no general map from Option's None, or List's Nil, to other functors which don't have an "empty" state.

    There is a tradeoff design choice made here. In the design for collections library of my new language, I chose to make everything a functor, which means if I implement a BitSet, it needs to support all element types, by using a non-bit field internal representation when presented with a non-integer type parameter, and that functionality is already in the Set which it inherits from in Scala. And Map in my design needs to map only its values, and it can provide a separate non-functor method for mapping its (key,value) pair tuples. One advantage is that each functor is then usually also an applicative and perhaps a monad too. Thus all functions between element types, e.g. A => B => C => D => ..., are automatically lifted to the functions between lifted applicative types, e.g. List[A] => List[B] => List[C] => List[D] => .... For mapping from a functor to another collection class, I offer a map overload which takes a monoid, e.g. Nil, None, 0, "", Array(), etc.. So the builder abstraction function is the append method of a monoid and is supplied explicitly as a necessary input parameter, thus with no invisible implicit conversions. (Tangent: this input parameter also enables appending to non-empty monoids, which Scala's map design can't do.) Such conversions are a map and a fold in the same iteration pass. Also I provide a traversable, in the category sense, "Applicative programming with effects" McBride & Patterson, which also enables map + fold in a single iteration pass from any traversable to any applicative, where most every collection class is both. Also the state monad is an applicative and thus is a fully generalized builder abstraction from any traversable.

    So afaics the Scala collections is "ad-hoc" in the sense that it is not grounded in category theory, and category theory is the essense of higher-level denotational semantics. Although Scala's implicit builders are at first appearance "more generalized" than a functor model + monoid builder + traversable -> applicative, they are afaik not proven to be consistent with any category, and thus we don't know what rules they follow in the most general sense and what the corner cases will be given they may not obey any category model. It is simply not true that adding more variables makes something more general, and this was one of huge benefits of category theory is it provides rules by which to maintain generality while lifting to higher-level semantics. A collection is a category.

    I read somewhere, I think it was Odersky, as another justification for the library design, is that programming in a pure functional style has the cost of limited recursion and speed where tail recursion isn't used. I haven't found it difficult to employ tail recursion in every case that I have encountered so far.


Additionally I am carrying in my mind an incomplete idea that some of Scala's tradeoffs are due to trying to be both an mutable and immutable language, unlike for example Haskell or the language I am developing. This concurs with Tony Morris's comment about for comprehensions. In my language, there are no loops and no mutable constructs. My language will sit on top of Scala (for now) and owes much to it, and this wouldn't be possible if Scala didn't have the general type system and mutability. That might not be true though, because I think Odersky & Moors ("Fighting Bit Rot with Types") are incorrect to state that Scala is the only OOP language with higher-kinds, because I verified (myself and via Bob Harper) that Standard ML has them. Also appears SML's type system may be equivalently flexible (since 1980s), which may not be readily appreciated because the syntax is not so much similar to Java (and C++/PHP) as Scala. In any case, this isn't a criticism of Scala, but rather an attempt to present an incomplete analysis of tradeoffs, which is I hope germane to the question. Scala and SML don't suffer from Haskell's inability to do diamond multiple inheritance, which is critical and I understand is why so many functions in the Haskell Prelude are repeated for different types.

Mongoose: Get full list of users

There was the very easy way to list your data :

server.get('/userlist' , function (req , res) {
 User.find({}).then(function (users) {
 res.send(users);
 });
});

"FATAL: Module not found error" using modprobe

The reason is that modprobe looks into /lib/modules/$(uname -r) for the modules and therefore won't work with local file path. That's one of differences between modprobe and insmod.

How to place div in top right hand corner of page

You can use css float

<div style='float: left;'><a href="login.php">Log in</a></div>

<div style='float: right;'><a href="home.php">Back to Home</a></div>

Have a look at this CSS Positioning

how to do "press enter to exit" in batch

My guess is that rake is a batch program. When you invoke it without call, then control doesn't return to your build.bat. Try:

@echo off
cls
CALL rake
pause

Calculating time difference between 2 dates in minutes

ROUND(time_to_sec((TIMEDIFF(NOW(), "2015-06-10 20:15:00"))) / 60);

Phone validation regex

Adding to @Joe Johnston's answer, this will also accept:

+16444444444,,241119933

(Required for Apple's special character support for dial-ins - https://support.apple.com/kb/PH18551?locale=en_US)

\(?\+[0-9]{1,3}\)? ?-?[0-9]{1,3} ?-?[0-9]{3,5} ?-?[0-9]{4}( ?-?[0-9]{3})? ?([\w\,\@\^]{1,10}\s?\d{1,10})?

Note: Accepts upto 10 digits for extension code

base_url() function not working in codeigniter

In order to use base_url(), you must first have the URL Helper loaded. This can be done either in application/config/autoload.php (on or around line 67):

$autoload['helper'] = array('url');

Or, manually:

$this->load->helper('url');

Once it's loaded, be sure to keep in mind that base_url() doesn't implicitly print or echo out anything, rather it returns the value to be printed:

echo base_url();

Remember also that the value returned is the site's base url as provided in the config file. CodeIgniter will accomodate an empty value in the config file as well:

If this (base_url) is not set then CodeIgniter will guess the protocol, domain and path to your installation.

application/config/config.php, line 13

Setting public class variables

Add getter and setter method to your class.

public function setValue($new_value)
{
    $this->testvar = $new_value;
}

public function getValue()
{
    return $this->testvar;        
}

How to make Toolbar transparent?

Just add android:background="@android:color/transparent" like below in your appbar layout

<android.support.design.widget.AppBarLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:background="@android:color/transparent">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>`

Multiple inputs with same name through POST in php

It can be:

echo "Welcome".$_POST['firstname'].$_POST['lastname'];

How to extract extension from filename string in Javascript?

I would recommend using lastIndexOf() as opposed to indexOf()

var myString = "this.is.my.file.txt"
alert(myString.substring(myString.lastIndexOf(".")+1))

Export HTML page to PDF on user click using JavaScript

This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.

change it to:

$(function () {

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#cmd').click(function () {
        var doc = new jsPDF();
        doc.fromHTML(
            $('#target').html(), 15, 15, 
            { 'width': 170, 'elementHandlers': specialElementHandlers }, 
            function(){ doc.save('sample-file.pdf'); }
        );

    });  
});

and it will work.

What is /dev/null 2>&1?

Let me explain a bit by bit.

0,1,2

0: standard input
1: standard output
2: standard error

>>

>> in command >> /dev/null 2>&1 appends the command output to /dev/null.

command >> /dev/null 2>&1

  1. After command:
command
=> 1 output on the terminal screen
=> 2 output on the terminal screen
  1. After redirect:
command >> /dev/null
=> 1 output to /dev/null
=> 2 output on the terminal screen
  1. After /dev/null 2>&1
command >> /dev/null 2>&1
=> 1 output to /dev/null
=> 2 output is redirected to 1 which is now to /dev/null

How to add elements to a list in R (loop)

You should not add to your list using c inside the loop, because that can result in very very slow code. Basically when you do c(l, new_element), the whole contents of the list are copied. Instead of that, you need to access the elements of the list by index. If you know how long your list is going to be, it's best to initialise it to this size using l <- vector("list", N). If you don't you can initialise it to have length equal to some large number (e.g if you have an upper bound on the number of iterations) and then just pick the non-NULL elements after the loop has finished. Anyway, the basic point is that you should have an index to keep track of the list element and add using that eg

i <- 1
while(...) {
    l[[i]] <- new_element
    i <- i + 1
}

For more info have a look at Patrick Burns' The R Inferno (Chapter 2).

Equivalent of String.format in jQuery

Expanding on adamJLev's great answer above, here is the TypeScript version:

// Extending String prototype
interface String {
    format(...params: any[]): string;
}

// Variable number of params, mimicking C# params keyword
// params type is set to any so consumer can pass number
// or string, might be a better way to constraint types to
// string and number only using generic?
String.prototype.format = function (...params: any[]) {
    var s = this,
        i = params.length;

    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), params[i]);
    }

    return s;
};

Oracle find a constraint

maybe this can help..

SELECT constraint_name, constraint_type, column_name
from user_constraints natural join user_cons_columns
where table_name = "my_table_name";

How can I get all element values from Request.Form without specifying exactly which one with .GetValues("ElementIdName")

Request.Form is a NameValueCollection. In NameValueCollection you can find the GetAllValues() method.

By the way the LINQ method also works.

How to iterate std::set?

You must dereference the iterator in order to retrieve the member of your set.

std::set<unsigned long>::iterator it;
for (it = SERVER_IPS.begin(); it != SERVER_IPS.end(); ++it) {
    u_long f = *it; // Note the "*" here
}

If you have C++11 features, you can use a range-based for loop:

for(auto f : SERVER_IPS) {
  // use f here
}    

How can I put CSS and HTML code in the same file?

Or also you can do something like this.

<div style="background=#aeaeae; float: right">

</div>

We can add any CSS inside the style attribute of HTML tags.

Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'"

I too had to face the same problem. This worked for me. Right click and run as admin than run usual command to install. But first run update command to update the pip

python -m pip install --upgrade pip

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

you may need to try

pip install --upgrade setuptools

you may also need to install Visual Studio 2015, and remember to choose to install Visual C++ 14.0 https://visualstudio.microsoft.com/visual-cpp-build-tools/

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

I had the same problem but it had nothing to do with annotations. The problem happened while indexing beans in my container (Jboss EAP 6.3). One of my beans could not be indexed because it used Java 8 features an I got this sneaky little warning while deploying:

WARN [org.jboss.as.server.deployment] ... Could not index class ... java.lang.IllegalStateException: Unknown tag! pos=20 poolCount = 133

Then at the injection point I got the error:

Unsatisfied dependencies for type ... with qualifiers @Default

The solution is to update the Java annotations index. download new version of jandex (jandex-1.2.3.Final or newer) then put it into

JBOSS_HOME\modules\system\layers\base\org\jboss\jandex\main and then update reference to the new file in module.xml

NOTE: EAP 6.4.x already have this fixed

HTML select drop-down with an input field

You can use input text with "list" attribute, which refers to the datalist of values.

_x000D_
_x000D_
<input type="text" name="city" list="cityname">_x000D_
    <datalist id="cityname">_x000D_
      <option value="Boston">_x000D_
      <option value="Cambridge">_x000D_
    </datalist>
_x000D_
_x000D_
_x000D_

This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist

creating json object with variables

var formValues = {
    firstName: $('#firstName').val(),
    lastName: $('#lastName').val(),
    phone: $('#phoneNumber').val(),
    address: $('#address').val()
};

Note this will contain the values of the elements at the point in time the object literal was interpreted, not when the properties of the object are accessed. You'd need to write a getter for that.

Spring: @Component versus @Bean

  • @component and its specializations(@Controller, @service, @repository) allow for auto-detection using classpath scanning. If we see component class like @Controller, @service, @repository will be scan automatically by the spring framework using the component scan.
  • @Bean on the other hand can only be used to explicitly declare a single bean in a configuration class.
  • @Bean used to explicitly declare a single bean, rather than letting spring do it automatically. Its make septate declaration of bean from the class definition.
  • In short @Controller, @service, @repository are for auto-detection and @Bean to create seprate bean from class
    - @Controller
    public class LoginController 
    { --code-- }

    - @Configuration
    public class AppConfig {
    @Bean
    public SessionFactory sessionFactory() 
    {--code-- }

Transform DateTime into simple Date in Ruby on Rails

Try converting the entry to a string first. As long as the database column type is a date it will be formated as a date.

self.date || self.exif_date_time_original.to_s

c# regex matches example

    public void match2()
    {
        string input = "%download%#893434";
        Regex word = new Regex(@"\d+");
        Match m = word.Match(input);
        Console.WriteLine(m.Value);
    }

HTML - Change\Update page contents without refreshing\reloading the page

jQuery will do the job. You can use either jQuery.ajax function, which is general one for performing ajax calls, or its wrappers: jQuery.get, jQuery.post for getting/posting data. Its very easy to use, for example, check out this tutorial, which shows how to use jQuery with PHP.

What are the best practices for using a GUID as a primary key, specifically regarding performance?

I am currently developing an web application with EF Core and here is the pattern I use:

All my classes (tables) have an int PK and FK. I then have an additional column of type Guid (generated by the C# constructor) with a non clustered index on it.

All the joins of tables within EF are managed through the int keys while all the access from outside (controllers) are done with the Guids.

This solution allows to not show the int keys on URLs but keep the model tidy and fast.

Can you require two form fields to match with HTML5?

JavaScript will be required, but the amount of code can be kept to a minimum by using an intermediary <output> element and an oninput form handler to perform the comparison (patterns and validation could augment this solution, but aren't shown here for sake of simplicity):

<form oninput="result.value=!!p2.value&&(p1.value==p2.value)?'Match!':'Nope!'">
  <input type="password" name="p1" value="" required />
  <input type="password" name="p2" value="" required />
  <output name="result"></output>
</form>

invalid_grant trying to get oAuth token from google

if you are using scribe library, just set up the offline mode, like bonkydog suggested here is the code:

OAuthService service = new ServiceBuilder().provider(Google2Api.class).apiKey(clientId).apiSecret(apiSecret)
                .callback(callbackUrl).scope(SCOPE).offline(true)
                .build();

https://github.com/codolutions/scribe-java/

Get the correct week number of a given date

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

What I ended up with is the following extension method:

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

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

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

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

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

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

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

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

Remove large .pack file created by git

this is more of a handy solution than a coding one. zip the file. Open the zip in file view format (different from unzipping). Delete the .pack file. Unzip and replace the folder. Works like a charm!

Starting of Tomcat failed from Netbeans

This affects:

  • All versions of Tomcat starting from 8.5.3 onwards.
  • All versions of Netbeans up to 8.1 (It is fixed in Netbeans 8.2).

This is because Netbeans does not 'see' that tomcat is started, although it started just fine.

I have filed Bug #262749 with NetBeans.

Workaround

In the server.xml file, in the Connector element for HTTP/1.1, add the following attribute: server="Apache-Coyote/1.1".

Example:

<Connector
  connectionTimeout="20000"
  port="8080"
  protocol="HTTP/1.1"
  redirectPort="8443"
  server="Apache-Coyote/1.1"
/>

Cause

The reason for that is that prior to 8.5.3, the default was to set the server header as Apache-Coyote/1.1, while since 8.5.3 this default has now been changed to blank. Apparently Netbeans checks on this header.

Maybe in the future we can expect a fix in netbeans addressing this issue.

I was able to trace it back to a change in documentation.

Tomcat 8.5:

"Overrides the Server header for the http response. If set, the value for this attribute overrides any Server header set by a web application. If not set, any value specified by the application is used. If the application does not specify a value then no Server header is set."

Tomcat 8.0:

"Overrides the Server header for the http response. If set, the value for this attribute overrides the Tomcat default and any Server header set by a web application. If not set, any value specified by the application is used. If the application does not specify a value then Apache-Coyote/1.1 is used. Unless you are paranoid, you won't need this feature."

That explains the need for explicitly adding the server attribute since version 8.5.3.

Solutions for INSERT OR UPDATE on SQL Server

Although its pretty late to comment on this I want to add a more complete example using MERGE.

Such Insert+Update statements are usually called "Upsert" statements and can be implemented using MERGE in SQL Server.

A very good example is given here: http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx

The above explains locking and concurrency scenarios as well.

I will be quoting the same for reference:

ALTER PROCEDURE dbo.Merge_Foo2
      @ID int
AS

SET NOCOUNT, XACT_ABORT ON;

MERGE dbo.Foo2 WITH (HOLDLOCK) AS f
USING (SELECT @ID AS ID) AS new_foo
      ON f.ID = new_foo.ID
WHEN MATCHED THEN
    UPDATE
            SET f.UpdateSpid = @@SPID,
            UpdateTime = SYSDATETIME()
WHEN NOT MATCHED THEN
    INSERT
      (
            ID,
            InsertSpid,
            InsertTime
      )
    VALUES
      (
            new_foo.ID,
            @@SPID,
            SYSDATETIME()
      );

RETURN @@ERROR;

How to convert a string to number in TypeScript?

As shown by other answers here, there are multiple ways to do the conversion:

Number('123');
+'123';
parseInt('123');
parseFloat('123.45')

I'd like to mention one more thing on parseInt though.

When using parseInt, it makes sense to always pass the radix parameter. For decimal conversion, that is 10. This is the default value for the parameter, which is why it can be omitted. For binary, it's a 2 and 16 for hexadecimal. Actually, any radix between and including 2 and 36 works.

parseInt('123')         // 123 (don't do this)
parseInt('123', 10)     // 123 (much better)

parseInt('1101', 2)     // 13
parseInt('0xfae3', 16)  // 64227

In some JS implementations, parseInt parses leading zeros as octal:

Although discouraged by ECMAScript 3 and forbidden by ECMAScript 5, many implementations interpret a numeric string beginning with a leading 0 as octal. The following may have an octal result, or it may have a decimal result. Always specify a radix to avoid this unreliable behavior.

— MDN

The fact that code gets clearer is a nice side effect of specifying the radix parameter.

Since parseFloat only parses numeric expressions in radix 10, there's no need for a radix parameter here.

More on this:

How to get hostname from IP (Linux)?

In order to use nslookup, host or gethostbyname() then the target's name will need to be registered with DNS or statically defined in the hosts file on the machine running your program. Yes, you could connect to the target with SSH or some other application and query it directly, but for a generic solution you'll need some sort of DNS entry for it.

Bootstrap how to get text to vertical align in a div container

Could you not have simply added:

align-items:center;

to a new class in your row div. Essentially:

<div class="row align_center">

.align_center { align-items:center; }

What is the quickest way to HTTP GET in Python?

Python 3:

import urllib.request
contents = urllib.request.urlopen("http://example.com/foo/bar").read()

Python 2:

import urllib2
contents = urllib2.urlopen("http://example.com/foo/bar").read()

Documentation for urllib.request and read.

How to correctly implement custom iterators and const_iterators?

I don't know if Boost has anything that would help.

My preferred pattern is simple: take a template argument which is equal to value_type, either const qualified or not. If necessary, also a node type. Then, well, everything kind of falls into place.

Just remember to parameterize (template-ize) everything that needs to be, including the copy constructor and operator==. For the most part, the semantics of const will create correct behavior.

template< class ValueType, class NodeType >
struct my_iterator
 : std::iterator< std::bidirectional_iterator_tag, T > {
    ValueType &operator*() { return cur->payload; }

    template< class VT2, class NT2 >
    friend bool operator==
        ( my_iterator const &lhs, my_iterator< VT2, NT2 > const &rhs );

    // etc.

private:
    NodeType *cur;

    friend class my_container;
    my_iterator( NodeType * ); // private constructor for begin, end
};

typedef my_iterator< T, my_node< T > > iterator;
typedef my_iterator< T const, my_node< T > const > const_iterator;

R memory management / cannot allocate vector of size n Mb

The simplest way to sidestep this limitation is to switch to 64 bit R.

How to right-align and justify-align in Markdown?

In a generic Markdown document, use:

<style>body {text-align: right}</style>

or

<style>body {text-align: justify}</style>

Does not seem to work with Jupyter though.

Add 10 seconds to a Date

Try this

a = new Date();
a.setSeconds(a.getSeconds() + 10);

PowerShell: Store Entire Text File Contents in Variable

One more approach to reading a file that I happen to like is referred to variously as variable notation or variable syntax and involves simply enclosing a filespec within curly braces preceded by a dollar sign, to wit:

$content = ${C:file.txt}

This notation may be used as either an L-value or an R-value; thus, you could just as easily write to a file with something like this:

 ${D:\path\to\file.txt} = $content

Another handy use is that you can modify a file in place without a temporary file and without sub-expressions, for example:

${C:file.txt} = ${C:file.txt} | select -skip 1

I became fascinated by this notation initially because it was very difficult to find out anything about it! Even the PowerShell 2.0 specification mentions it only once showing just one line using it--but with no explanation or details of use at all. I have subsequently found this blog entry on PowerShell variables that gives some good insights.

One final note on using this: you must use a drive designation, i.e. ${drive:filespec} as I have done in all the examples above. Without the drive (e.g. ${file.txt}) it does not work. No restrictions on the filespec on that drive: it may be absolute or relative.

Video streaming over websockets using JavaScript

To answer the question:

What is the fastest way to stream live video using JavaScript? Is WebSockets over TCP a fast enough protocol to stream a video of, say, 30fps?

Yes, Websocket can be used to transmit over 30 fps and even 60 fps.

The main issue with Websocket is that it is low-level and you have to deal with may other issues than just transmitting video chunks. All in all it's a great transport for video and also audio.

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

Perhaps slightly more long winded than you want, but i've used more code than maybe nescessary in order for it to be more readable.

That said, it comes out with the same result as you are getting - what is it you want/expect it to come out with?

//Today is whenever I want it to be.
$today = mktime(0,0,0,3,31,2011);

$hour   = date("H",$today);
$minute = date("i",$today);
$second = date("s",$today);
$month  = date("m",$today);
$day    = date("d",$today);
$year   = date("Y",$today);

echo "Today: ".date('Y-m-d', $today)."<br/>";
echo "Recalulated: ".date("Y-m-d",mktime($hour,$minute,$second,$month-1,$day,$year));

If you just want the month and year, then just set the day to be '01' rather than taking 'todays' day:

 $day = 1;

That should give you what you need. You can just set the hour, minute and second to zero as well as you aren't interested in using those.

 date("Y-m",mktime(0,0,0,$month-1,1,$year);

Cuts it down quite a bit ;-)

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); }
    }               
}

Usage of @see in JavaDoc?

The @see tag is a bit different than the @link tag,
limited in some ways and more flexible in others:

different JavaDoc link types Different JavaDoc link types

  1. Displays the member name for better learning, and is refactorable; the name will update when renaming by refactor
  2. Refactorable and customizable; your text is displayed instead of the member name
  3. Displays name, refactorable
  4. Refactorable, customizable
  5. A rather mediocre combination that is:
  • Refactorable, customizable, and stays in the See Also section
  • Displays nicely in the Eclipse hover
  • Displays the link tag and its formatting when generated
  • When using multiple @see items, commas in the description make the output confusing
  1. Completely illegal; causes unexpected content and illegal character errors in the generator

See the results below:

JavaDoc generation results with different link types JavaDoc generation results with different link types

Best regards.

Select all child elements recursively in CSS

The rule is as following :

A B 

B as a descendant of A

A > B 

B as a child of A

So

div.dropdown *

and not

div.dropdown > *

How to debug apk signed for release?

I tried with the following and it's worked:

release {
            debuggable true
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

git checkout master error: the following untracked working tree files would be overwritten by checkout

With Git 2.23 (August 2019), that would be, using git switch -f:

git switch -f master

That avoids the confusion with git checkout (which deals with files or branches).

And that will proceeds, even if the index or the working tree differs from HEAD.
Both the index and working tree are restored to match the switching target.
If --recurse-submodules is specified, submodule content is also restored to match the switching target.
This is used to throw away local changes.

Alternative to header("Content-type: text/xml");

Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.

Take this

<?php
require("database.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','&lt;',$htmlStr);
$xmlStr=str_replace('>','&gt;',$xmlStr);
$xmlStr=str_replace('"','&quot;',$xmlStr);
$xmlStr=str_replace("'",'&#39;',$xmlStr);
$xmlStr=str_replace("&",'&amp;',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
  die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
  // ADD TO XML DOCUMENT NODE
  echo '<marker ';
  echo 'name="' . parseToXML($row['name']) . '" ';
  echo 'address="' . parseToXML($row['address']) . '" ';
  echo 'lat="' . $row['lat'] . '" ';
  echo 'lng="' . $row['lng'] . '" ';
  echo 'type="' . $row['type'] . '" ';
  echo '/>';
}
// End XML file
echo '</markers>';
?>

and place it in phpsqlajax_genxml.php so your javascript can download the XML file. You are trying to do too many things in the same file.

Spark specify multiple column conditions for dataframe join

Scala:

Leaddetails.join(
    Utm_Master, 
    Leaddetails("LeadSource") <=> Utm_Master("LeadSource")
        && Leaddetails("Utm_Source") <=> Utm_Master("Utm_Source")
        && Leaddetails("Utm_Medium") <=> Utm_Master("Utm_Medium")
        && Leaddetails("Utm_Campaign") <=> Utm_Master("Utm_Campaign"),
    "left"
)

To make it case insensitive,

import org.apache.spark.sql.functions.{lower, upper}

then just use lower(value) in the condition of the join method.

Eg: dataFrame.filter(lower(dataFrame.col("vendor")).equalTo("fortinet"))

How do I add a ToolTip to a control?

I did it this way: Just add the event to any control, set the control's tag, and add a conditional to handle the tooltip for the appropriate control/tag.

private void Info_MouseHover(object sender, EventArgs e)
{
    Control senderObject = sender as Control;
    string hoveredControl = senderObject.Tag.ToString();

    // only instantiate a tooltip if the control's tag contains data
    if (hoveredControl != "")
    {
        ToolTip info = new ToolTip
        {
            AutomaticDelay = 500
        };

        string tooltipMessage = string.Empty;

        // add all conditionals here to modify message based on the tag 
        // of the hovered control
        if (hoveredControl == "save button")
        {
            tooltipMessage = "This button will save stuff.";
        }

        info.SetToolTip(senderObject, tooltipMessage);
    }
}

How to install SignTool.exe for Windows 10

Location:

C:\Program Files (x86)\Windows Kits\10\App Certification Kit\signtool.exe

Download File Using Javascript/jQuery

I don't know if the question is just too old, but setting window.location to a download url will work, as long as the download mime type is correct (for example a zip archive).

var download = function(downloadURL) {

   location = downloadURL;

});

download('http://example.com/archive.zip'); //correct usage
download('http://example.com/page.html'); //DON'T

Is there a limit on number of tcp/ip connections between machines on linux?

When looking for the max performance you run into a lot of issue and potential bottlenecks. Running a simple hello world test is not necessarily going to find them all.

Possible limitations include:

  • Kernel socket limitations: look in /proc/sys/net for lots of kernel tuning..
  • process limits: check out ulimit as others have stated here
  • as your application grows in complexity, it may not have enough CPU power to keep up with the number of connections coming in. Use top to see if your CPU is maxed
  • number of threads? I'm not experienced with threading, but this may come into play in conjunction with the previous items.

Get all unique values in a JavaScript array (remove duplicates)

Found this sweet snippet from a post by Changhui Xu for those looking to get unique objects. I haven't measured its performance against the other alternatives though.

_x000D_
_x000D_
const array = [{_x000D_
    name: 'Joe',_x000D_
    age: 17_x000D_
  },_x000D_
  {_x000D_
    name: 'Bob',_x000D_
    age: 17_x000D_
  },_x000D_
  {_x000D_
    name: 'Tom',_x000D_
    age: 25_x000D_
  },_x000D_
  {_x000D_
    name: 'John',_x000D_
    age: 22_x000D_
  },_x000D_
  {_x000D_
    name: 'Jane',_x000D_
    age: 20_x000D_
  },_x000D_
];_x000D_
_x000D_
const distinctAges = [...new Set(array.map(a => a.age))];_x000D_
_x000D_
console.log(distinctAges)
_x000D_
_x000D_
_x000D_

Convenient way to parse incoming multipart/form-data parameters in a Servlet

Not always there's a servlet before of an upload (I could use a filter for example). Or could be that the same controller ( again a filter or also a servelt ) can serve many actions, so I think that rely on that servlet configuration to use the getPart method (only for Servlet API >= 3.0), I don't know, I don't like.

In general, I prefer independent solutions, able to live alone, and in this case http://commons.apache.org/proper/commons-fileupload/ is one of that.

List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
    for (FileItem item : multiparts) {
        if (!item.isFormField()) {
            //your operations on file
        } else {
            String name = item.getFieldName();
            String value = item.getString();
            //you operations on paramters
        }
}

Sonar properties files

You have to specify the projectBaseDir if the module name doesn't match you module directory.

Since both your module are located in ".", you can simply add the following to your sonar-project properties:

module1.sonar.projectBaseDir=.
module2.sonar.projectBaseDir=.

Sonar will handle your modules as components of the project:

Result of Sonar analysis

EDIT

If both of your modules are located in the same source directory, define the same source folder for both and exclude the unwanted packages with sonar.exclusions:

module1.sonar.sources=src/main/java
module1.sonar.exclusions=app2code/**/*

module2.sonar.sources=src/main/java
module2.sonar.exclusions=app1code/**/*

More details about file exclusion

Create <div> and append <div> dynamically

var iDiv = document.createElement('div'),
    jDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';
jDiv.className = 'block-2';
iDiv.appendChild(jDiv);
document.getElementsByTagName('body')[0].appendChild(iDiv);

Close Form Button Event

If am not wrong

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
   //You may decide to prompt to user
   //else just kill
   Process.GetCurrentProcess().Kill();
} 

`require': no such file to load -- mkmf (LoadError)

You can use RVM(Ruby version manager) which helps in managing all versions of ruby on your machine , which is very helpful for you development (when migrating to unstable release to stable release )

or for Linux (ubuntu) go for sudo apt-get install ruby1.8-dev

then sudo gem install rails to verify it do rails -v it will show version on rails

after that you can install bundles (required gems for development)

How to erase the file contents of text file in Python?

You have to overwrite the file. In C++:

#include <fstream>

std::ofstream("test.txt", std::ios::out).close();

pros and cons between os.path.exists vs os.path.isdir

os.path.isdir() checks if the path exists and is a directory and returns TRUE for the case.

Similarly, os.path.isfile() checks if the path exists and is a file and returns TRUE for the case.

And, os.path.exists() checks if the path exists and doesn’t care if the path points to a file or a directory and returns TRUE in either of the cases.

How do I convert special UTF-8 chars to their iso-8859-1 equivalent using javascript?

The problem is that once the page is served up, the content is going to be in the encoding described in the content-type meta tag. The content in "wrong" encoding is already garbled.

You're best to do this on the server before serving up the page. Or as I have been know to say: UTF-8 end-to-end or die.

Is if(document.getElementById('something')!=null) identical to if(document.getElementById('something'))?

jquery will provide you with this and more ...

if($("#something").val()){ //do stuff}

It took me a couple of days to pick it up, but it provides you with you with so much more functionality. An example below.

jQuery(document).ready(function() {
    /* finds closest element with class divright/left and 
    makes all checkboxs inside that div class the same as selectAll...
    */
        $("#selectAll").click(function() {
        $(this).closest('.divright').find(':checkbox').attr('checked', this.checked);
    });
});

Turning off eslint rule for a specific file

To disable a specific rule for the file:

/* eslint-disable no-use-before-define */

Note there is a bug in eslint where single line comment will not work -

// eslint-disable max-classes-per-file
// This fails!

Check this post

JQuery .hasClass for multiple values in an if statement

You could use is() instead of hasClass():

if ($('html').is('.m320, .m768')) { ... }

Remove all special characters from a string in R?

Convert the Special characters to apostrophe,

Data  <- gsub("[^0-9A-Za-z///' ]","'" , Data ,ignore.case = TRUE)

Below code it to remove extra ''' apostrophe

Data <- gsub("''","" , Data ,ignore.case = TRUE)

Use gsub(..) function for replacing the special character with apostrophe

How to configure encoding in Maven?

OK, I have found the problem.

I use some reporting plugins. In the documentation of the failsafe-maven-plugin I found, that the <encoding> configuration - of course - uses ${project.reporting.outputEncoding} by default.

So I added the property as a child element of the project element and everything is fine now:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>

See also http://maven.apache.org/general.html#encoding-warning

what's data-reactid attribute in html?

Custom Data attribute in HTML5

Would like to quote Ian's comment in my answer:

It's just an attribute (a valid one) on the element that you can use to store data/info about it.

This code then retrieves it later in the event handler, and uses it to find the target output element. It effectively stores the class of the div where its text should be outputted.

reactid is just a suffix, you can have any name here eg: data-Ayman.

If you want to find the difference check the fiddles in this SO answer and comment.

Why does multiplication repeats the number several times?

I think you're confused about types here. You'll only get that result if you're multiplying a string. Start the interpreter and try this:

>>> print "1" * 9
111111111
>>> print 1 * 9
9
>>> print int("1") * 9
9

So make sure the first operand is an integer (and not a string), and it will work.

Redirect to Action in another controller

Use this:

return RedirectToAction("LogIn", "Account", new { area = "" });

This will redirect to the LogIn action in the Account controller in the "global" area.

It's using this RedirectToAction overload:

protected internal RedirectToRouteResult RedirectToAction(
    string actionName,
    string controllerName,
    Object routeValues
)

MSDN

How do I clear the previous text field value after submitting the form with out refreshing the entire page?

I believe it's better to use

$('#form-id').find('input').val('');

instead of

$('#form-id').children('input').val('');

incase you have checkboxes in your form use this to rest it:

$('#form-id').find('input:checkbox').removeAttr('checked');

Hive cast string to date dd-MM-yyyy

AFAIK you must reformat your String in ISO format to be able to cast it as a Date:

cast(concat(substr(STR_DMY,7,4), '-',
            substr(STR_DMY,1,2), '-',
            substr(STR_DMY,4,2)
           )
     as date
     ) as DT

To display a Date as a String with specific format, then it's the other way around, unless you have Hive 1.2+ and can use date_format()

=> did you check the documentation by the way?

How to quickly clear a JavaScript Object?

ES5

ES5 solution can be:

// for enumerable and non-enumerable properties
Object.getOwnPropertyNames(obj).forEach(function (prop) {
  delete obj[prop];
});

ES6

And ES6 solution can be:

// for enumerable and non-enumerable properties
for (const prop of Object.getOwnPropertyNames(obj)) {
  delete obj[prop];
}

Performance

Regardless of the specs, the quickest solutions will generally be:

// for enumerable and non-enumerable of an object with proto chain
var props = Object.getOwnPropertyNames(obj);
for (var i = 0; i < props.length; i++) {
  delete obj[props[i]];
}

// for enumerable properties of shallow/plain object
for (var key in obj) {
  // this check can be safely omitted in modern JS engines
  // if (obj.hasOwnProperty(key))
    delete obj[key];
}

The reason why for..in should be performed only on shallow or plain object is that it traverses the properties that are prototypically inherited, not just own properties that can be deleted. In case it isn't known for sure that an object is plain and properties are enumerable, for with Object.getOwnPropertyNames is a better choice.

Android difference between Two Dates

You can calculate the difference in time in miliseconds using this method and get the outputs in seconds, minutes, hours, days, months and years.

You can download class from here: DateTimeDifference GitHub Link

  • Simple to use
long currentTime = System.currentTimeMillis();
long previousTime = (System.currentTimeMillis() - 864000000); //10 days ago

Log.d("DateTime: ", "Difference With Second: " + AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.SECOND));
Log.d("DateTime: ", "Difference With Minute: " + AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.MINUTE));
  • You can compare the example below
if(AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.MINUTE) > 100){
    Log.d("DateTime: ", "There are more than 100 minutes difference between two dates.");
}else{
    Log.d("DateTime: ", "There are no more than 100 minutes difference between two dates.");
}

jQuery - simple input validation - "empty" and "not empty"

Actually there is a simpler way to do this, just:

if ($("#input").is(':empty')) {
console.log('empty');
} else {
console.log('not empty');
}

src: https://www.geeksforgeeks.org/how-to-check-an-html-element-is-empty-using-jquery/

Downloading a Google font and setting up an offline site that uses it

Just go to Google Fonts - http://www.google.com/fonts/ , add the font you like to your collection, and press the download button. And then just use the @fontface to connect this font to your web page. Btw, if you open the link you are using, you'll see an example of using @fontface

http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600,300

For an example

@font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: 300;
  src: local('Open Sans Light'), local('OpenSans-Light'), url(http://themes.googleusercontent.com/static/fonts/opensans/v6/DXI1ORHCpsQm3Vp6mXoaTaRDOzjiPcYnFooOUGCOsRk.woff) format('woff');
}

Just change the url address to the local link on the font file, you've downloaded.

You can do it even easier.

Just download the file, you've linked:

http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600,300

Name it opensans.css or so.

Then just change the links in url() to your path to font files.

And then replace your example string with:

<link href='opensans.css' rel='stylesheet' type='text/css'>

Click in OK button inside an Alert (Selenium IDE)

1| Print Alert popup text and close -I

Alert alert = driver.switchTo().alert();
System.out.println(closeAlertAndGetItsText());

2| Print Alert popup text and close -II

Alert alert = driver.switchTo().alert();
System.out.println(alert.getText()); //Print Alert popup
alert.accept(); //Close Alert popup

3| Assert Alert popup text and close

Alert alert = driver.switchTo().alert();
assertEquals("Expected Value", closeAlertAndGetItsText());

editing PATH variable on mac

use

~/.bash_profile

or

~/.MacOSX/environment.plist

(see Runtime Configuration Guidelines)

How to checkout in Git by date?

Going further with the rev-list option, if you want to find the most recent merge commit from your master branch into your production branch (as a purely hypothetical example):

git checkout `git rev-list -n 1 --merges --first-parent --before="2012-01-01" production`

I needed to find the code that was on the production servers as of a given date. This found it for me.

In C can a long printf statement be broken up into multiple lines?

Just some other formatting options:

printf("name: %s\targs: %s\tvalue %d\tarraysize %d\n", 
        a,        b,        c,        d);

printf("name: %s\targs: %s\tvalue %d\tarraysize %d\n", 
              a,        b,        c,            d);

printf("name: %s\t"      "args: %s\t"      "value %d\t"      "arraysize %d\n", 
        very_long_name_a, very_long_name_b, very_long_name_c, very_long_name_d);

You can add variations on the theme. The idea is that the printf() conversion speficiers and the respective variables are all lined up "nicely" (for some values of "nicely").

Pip install Matplotlib error with virtualenv

None of the above answers worked for me in Mint, so I did:

sudo apt-get install build-essential g++

Laravel: How do I parse this json data in view blade?

It's pretty easy. First of all send to the view decoded variable (see Laravel Views):

view('your-view')->with('leads', json_decode($leads, true));

Then just use common blade constructions (see Laravel Templating):

@foreach($leads['member'] as $member)
    Member ID: {{ $member['id'] }}
    Firstname: {{ $member['firstName'] }}
    Lastname: {{ $member['lastName'] }}
    Phone: {{ $member['phoneNumber'] }}

    Owner ID: {{ $member['owner']['id'] }}
    Firstname: {{ $member['owner']['firstName'] }} 
    Lastname: {{ $member['owner']['lastName'] }}
@endforeach

How to check model string property for null in a razor view

Try this first, you may be passing a Null Model:

@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
    <label for="Image">Change picture</label>
}
else
{ 
    <label for="Image">Add picture</label>
}

Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.

<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>

What is declarative programming?

Declarative programming is "the act of programming in languages that conform to the mental model of the developer rather than the operational model of the machine".

The difference between declarative and imperative programming is well illustrated by the problem of parsing structured data.

An imperative program would use mutually recursive functions to consume input and generate data. A declarative program would express a grammar that defines the structure of the data so that it can then be parsed.

The difference between these two approaches is that the declarative program creates a new language that is more closely mapped to the mental model of the problem than is its host language.

LINQ-to-SQL vs stored procedures?

LINQ definitely has its place in application-specific databases and in small businesses.

But in a large enterprise, where central databases serve as a hub of common data for many applications, we need abstraction. We need to centrally manage security and show access histories. We need to be able to do impact analysis: if I make a small change to the data model to serve a new business need, what queries need to be changed and what applications need to be re-tested? Views and Stored Procedures give me that. If LINQ can do all that, and make our programmers more productive, I'll welcome it -- does anyone have experience using it in this kind of environment?

Spring Boot application.properties value not populating

The user "geoand" is right in pointing out the reasons here and giving a solution. But a better approach is to encapsulate your configuration into a separate class, say SystemContiguration java class and then inject this class into what ever services you want to use those fields.

Your current way(@grahamrb) of reading config values directly into services is error prone and would cause refactoring headaches if config setting name is changed.

In Java, what purpose do the keywords `final`, `finally` and `finalize` fulfil?

The final keyword is used to declare constants.

final int FILE_TYPE = 3;

The finally keyword is used in a try catch statement to specify a block of code to execute regardless of thrown exceptions.

try
{
  //stuff
}
catch(Exception e)
{
  //do stuff
}
finally
{
  //this is always run
}

And finally (haha), finalize im not entirely sure is a keyword, but there is a finalize() function in the Object class.

HTML.ActionLink method

Html.ActionLink(article.Title, "Login/" + article.ArticleID, 'Item") 

How do I assert equality on two classes without an equals method?

I generally implement this usecase using org.apache.commons.lang3.builder.EqualsBuilder

Assert.assertTrue(EqualsBuilder.reflectionEquals(expected,actual));

JavaScript replace \n with <br />

Handles either type of line break

str.replace(new RegExp('\r?\n','g'), '<br />');

Why does Java have transient fields?

transient is used to indicate that a class field doesn't need to be serialized. Probably the best example is a Thread field. There's usually no reason to serialize a Thread, as its state is very 'flow specific'.

Jackson overcoming underscores in favor of camel-case

If its a spring boot application, In application.properties file, just use

spring.jackson.property-naming-strategy=SNAKE_CASE

Or Annotate the model class with this annotation.

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)

MySQL string replace

In addition to gmaggio's answer if you need to dynamically REPLACE and UPDATE according to another column you can do for example:

UPDATE your_table t1
INNER JOIN other_table t2
ON t1.field_id = t2.field_id
SET t1.your_field = IF(LOCATE('articles/updates/', t1.your_field) > 0, 
REPLACE(t1.your_field, 'articles/updates/', t2.new_folder), t1.your_field) 
WHERE...

In my example the string articles/news/ is stored in other_table t2 and there is no need to use LIKE in the WHERE clause.

How to encode a URL in Swift

Just completing Desmond Hume's answer to extend the String class for a RFC 3986 unreserved characters valid encoding function (needed if you are encoding query FORM parameters):

Swift 3

extension String {

    var RFC3986UnreservedEncoded:String {
        let unreservedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
        let unreservedCharsSet: CharacterSet = CharacterSet(charactersIn: unreservedChars)
        let encodedString: String = self.addingPercentEncoding(withAllowedCharacters: unreservedCharsSet)!
        return encodedString
    }
}

C++ STL Vectors: Get iterator from index?

Try this:

vector<Type>::iterator nth = v.begin() + index;

Lollipop : draw behind statusBar with its color set to transparent

There is good library StatusBarUtil from @laobie that help to easily draw image in the StatusBar.

Just add in your build.gradle:

compile 'com.jaeger.statusbarutil:library:1.4.0'

Then in the Activity set

StatusBarUtil.setTranslucentForImageView(Activity activity, int statusBarAlpha, View viewNeedOffset)

In the layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:orientation="vertical">

    <ImageView
        android:layout_alignParentTop="true"
        android:layout_width="match_parent"
        android:adjustViewBounds="true"
        android:layout_height="wrap_content"
        android:src="@drawable/toolbar_bg"/>

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/view_need_offset"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@android:color/transparent"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

        <!-- Your layout code -->
    </android.support.design.widget.CoordinatorLayout>
</RelativeLayout>

For more info download demo or clone from github page and play with all feature.

Note: Support KitKat and above.

Hope that helps somebody else!

HTML iframe - disable scroll

This works for me:

<style>
*{overflow:hidden!important;}
html{overflow:scroll!important;}
</style>

Note: if you need scrollbar in any other element, also add css {overflow:scroll!important;} to that element

Bootstrap Element 100% Width

QUICK ANSWER

  1. Use multiple NOT NESTED .containers
  2. Wrap those .containers you want to have a full-width background in a div
  3. Add a CSS background to the wrapping div

Fiddles: Simple: https://jsfiddle.net/vLhc35k4/ , Container borders: https://jsfiddle.net/vLhc35k4/1/
HTML:

<div class="container">
  <h2>Section 1</h2>
</div>
<div class="specialBackground">
  <div class="container">
    <h2>Section 2</h2>
  </div>
</div>

CSS: .specialBackground{ background-color: gold; /*replace with own background settings*/ }

FURTHER INFO

DON'T USE NESTED CONTAINERS

Many people will (wrongly) suggest, that you should use nested containers.
Well, you should NOT.
They are not ment to be nested. (See to "Containers" section in the docs)

HOW IT WORKS

div is a block element, which by default spans to the full width of a document body - there is the full-width feature. It also has a height of it's content (if you don't specify otherwise).

The bootstrap containers are not required to be direct children of a body, they are just containers with some padding and possibly some screen-width-variable fixed widths.

If a basic grid .container has some fixed width it is also auto-centered horizontally.
So there is no difference whether you put it as a:

  1. Direct child of a body
  2. Direct child of a basic div that is a direct child of a body.

By "basic" div I mean div that does not have a CSS altering his border, padding, dimensions, position or content size. Really just a HTML element with display: block; CSS and possibly background.
But of course setting vertical-like CSS (height, padding-top, ...) should not break the bootstrap grid :-)

Bootstrap itself is using the same approach

...All over it's own website and in it's "JUMBOTRON" example:
http://getbootstrap.com/examples/jumbotron/

How many threads can a Java VM support?

After playing around with Charlie's DieLikeACode class, it looks like the Java thread stack size is a huge part of how many threads you can create.

-Xss set java thread stack size

For example

java -Xss100k DieLikeADog

But, Java has the Executor interface. I would use that, you will be able to submit thousands of Runnable tasks, and have the Executor process those tasks with a fixed number of threads.

Minimum and maximum date

As you can see, 01/01/1970 returns 0, which means it is the lowest possible date.

new Date('1970-01-01Z00:00:00:000') //returns Thu Jan 01 1970 01:00:00 GMT+0100 (Central European Standard Time)
new Date('1970-01-01Z00:00:00:000').getTime() //returns 0
new Date('1970-01-01Z00:00:00:001').getTime() //returns 1

How do I solve the INSTALL_FAILED_DEXOPT error?

I needed to disable Instant Run to fix the issue. To disable Instant Run on OS X, go to Android Studio > Preferences > Build, Execution, Deployment > Instant Run then remove the tick from Enable Instant Run to hot swap code/resource changes on deploy (default enabled).

Errno 13 Permission denied Python

If you have this problem in Windows 10, and you know you have premisions on folder (You could write before but it just started to print exception PermissionError recently).. You will need to install Windows updates... I hope someone will help this info.

How can I access getSupportFragmentManager() in a fragment?

All you need to do is using

getFragmentManager()

method on your fragment. It will give you the support fragment manager, when you used it while adding this fragment.

Fragment Documentation

[Vue warn]: Cannot find element

I get the same error. the solution is to put your script code before the end of body, not in the head section.

Alternate table with new not null Column in existing table in SQL

There are two ways to add the NOT NULL Columns to the table :

  1. ALTER the table by adding the column with NULL constraint. Fill the column with some data. Ex: column can be updated with ''

  2. ALTER the table by adding the column with NOT NULL constraint by giving DEFAULT values. ALTER table TableName ADD NewColumn DataType NOT NULL DEFAULT ''

Getting user input

In python 3.x, use input() instead of raw_input()

Notepad++ Multi editing

Notepad++ also handles multiple cursors now.

Go into Settings => Preferences => Editing and check "Enable" in "Multi editing settings" Then, just use Ctrl+click to use multiple cursors.

Feature demo on official website here : https://npp-user-manual.org/docs/editing/

Copying text to the clipboard using Java

I found a better way of doing it so you can get a input from a txtbox or have something be generated in that text box and be able to click a button to do it.!

import java.awt.datatransfer.*;
import java.awt.Toolkit;

private void /* Action performed when the copy to clipboard button is clicked */ {
    String ctc = txtCommand.getText().toString();
    StringSelection stringSelection = new StringSelection(ctc);
    Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
    clpbrd.setContents(stringSelection, null);
}

// txtCommand is the variable of a text box

How to enumerate a range of numbers starting at 1

>>> list(enumerate(range(1999, 2005)))[1:]
[(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)]

How to move all HTML element children to another parent using JavaScript?

Here's a simple function:

function setParent(el, newParent)
{
    newParent.appendChild(el);
}

el's childNodes are the elements to be moved, newParent is the element el will be moved to, so you would execute the function like:

var l = document.getElementById('old-parent').childNodes.length;
var a = document.getElementById('old-parent');
var b = document.getElementById('new-parent');
for (var i = l; i >= 0; i--)
{
    setParent(a.childNodes[0], b);
}

Here is the Demo

How do I add to the Windows PATH variable using setx? Having weird problems

setx path "%PATH%; C:\Program Files (x86)\Microsoft Office\root\Office16" /m

This should do the appending to the System Environment Variable Path without any extras added, and keeping the original intact without any loss of data. I have used this command to correct the issue that McAfee's Web Control does to Microsoft's Outlook desktop client.

The quotations are used in the path value because command line sees spaces as a delimiter, and will attempt to execute next value in the command line. The quotations override this behavior and handles everything inside the quotations as a string.

Logging framework incompatibility

Just to help those in a similar situation to myself...

This can be caused when a dependent library has accidentally bundled an old version of slf4j. In my case, it was tika-0.8. See https://issues.apache.org/jira/browse/TIKA-556

The workaround is exclude the component and then manually depends on the correct, or patched version.

EG.

<dependency>
    <groupId>org.apache.tika</groupId>
    <artifactId>tika-parsers</artifactId>
    <version>0.8</version>
    <exclusions>
        <exclusion>
            <!-- NOTE: Version 4.2 has bundled slf4j -->
            <groupId>edu.ucar</groupId>
            <artifactId>netcdf</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <!-- Patched version 4.2-min does not bundle slf4j -->
    <groupId>edu.ucar</groupId>
    <artifactId>netcdf</artifactId>
    <version>4.2-min</version>
</dependency>

Declare a variable in DB2 SQL

I'm coming from a SQL Server background also and spent the past 2 weeks figuring out how to run scripts like this in IBM Data Studio. Hope it helps.

CREATE VARIABLE v_lookupid INTEGER DEFAULT (4815162342); --where 4815162342 is your variable data 
  SELECT * FROM DB1.PERSON WHERE PERSON_ID = v_lookupid;
  SELECT * FROM DB1.PERSON_DATA WHERE PERSON_ID = v_lookupid;
  SELECT * FROM DB1.PERSON_HIST WHERE PERSON_ID = v_lookupid;
DROP VARIABLE v_lookupid; 

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

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

NVL2( field_to_check, value_if_NOT_null, value_if_null )

Usage: ORACLE/PLSQL: NVL2 FUNCTION

List of tables, db schema, dump etc using the Python sqlite3 API

Some might find my function useful if you just want to print out all of the tables and columns in your db.

In the loop, I query each TABLE with LIMIT 0 so it just returns the header info without all the data. You make an empty df out of it, and use the iterable df.columns to print each column name out.

conn = sqlite3.connect('example.db')
c = conn.cursor()

def table_info(c, conn):
    '''
    prints out all of the columns of every table in db
    c : cursor object
    conn : database connection object
    '''
    tables = c.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall()
    for table_name in tables:
        table_name = table_name[0] # tables is a list of single item tuples
        table = pd.read_sql_query("SELECT * from {} LIMIT 0".format(table_name), conn)
        print(table_name)
        for col in table.columns:
            print('\t-' + col)
        print()

table_info(c, conn)
Results will be:

table1
    -column1
    -column2

table2
    -column1
    -column2
    -column3 

etc.

Simple way to convert datarow array to datatable

.Net 3.5+ added DataTableExtensions, use DataTableExtensions.CopyToDataTable Method

For datarow array just use .CopyToDataTable() and it will return datatable.

For single datarow use

new DataRow[] { myDataRow }.CopyToDataTable()

Task vs Thread differences

The Thread class is used for creating and manipulating a thread in Windows.

A Task represents some asynchronous operation and is part of the Task Parallel Library, a set of APIs for running tasks asynchronously and in parallel.

In the days of old (i.e. before TPL) it used to be that using the Thread class was one of the standard ways to run code in the background or in parallel (a better alternative was often to use a ThreadPool), however this was cumbersome and had several disadvantages, not least of which was the performance overhead of creating a whole new thread to perform a task in the background.

Nowadays using tasks and the TPL is a far better solution 90% of the time as it provides abstractions which allows far more efficient use of system resources. I imagine there are a few scenarios where you want explicit control over the thread on which you are running your code, however generally speaking if you want to run something asynchronously your first port of call should be the TPL.

What is a regular expression for a MAC Address?

The standard (IEEE 802) format for printing MAC-48 addresses in human-friendly form is six groups of two hexadecimal digits, separated by hyphens - or colons :.

So:

^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$

Perfect 100% width of parent container for a Bootstrap input?

Just add box-sizing:

input[type="text"] {
    box-sizing: border-box;
}

Check if $_POST exists

  • In that case using method isset is not appropriate.

According to PHP documentation: http://php.net/manual/en/function.array-key-exists.php
(see Example #2 array_key_exists() vs isset())
The method array_key_exists is intended for checking key presence in array.

So code in the question could be changed as follow:

function fromPerson() {
   if (array_key_exists('fromPerson', $_POST) == FALSE) {
        return '';
   } else {
        return '+from%3A'.$_POST['fromPerson'];
   };
}

$newString = fromPerson();


  • Checking presence of array $_POST is not necessary because it is PHP environment global variable since version 4.1.0 (nowadays we does not meet older versions of PHP).

What's the best way to trim std::string?

Use the following code to right trim (trailing) spaces and tab characters from std::strings (ideone):

// trim trailing spaces
size_t endpos = str.find_last_not_of(" \t");
size_t startpos = str.find_first_not_of(" \t");
if( std::string::npos != endpos )
{
    str = str.substr( 0, endpos+1 );
    str = str.substr( startpos );
}
else {
    str.erase(std::remove(std::begin(str), std::end(str), ' '), std::end(str));
}

And just to balance things out, I'll include the left trim code too (ideone):

// trim leading spaces
size_t startpos = str.find_first_not_of(" \t");
if( string::npos != startpos )
{
    str = str.substr( startpos );
}

In Python, how to check if a string only contains certain characters?

EDIT: Changed the regular expression to exclude A-Z

Regular expression solution is the fastest pure python solution so far

reg=re.compile('^[a-z0-9\.]+$')
>>>reg.match('jsdlfjdsf12324..3432jsdflsdf')
True
>>> timeit.Timer("reg.match('jsdlfjdsf12324..3432jsdflsdf')", "import re; reg=re.compile('^[a-z0-9\.]+$')").timeit()
0.70509696006774902

Compared to other solutions:

>>> timeit.Timer("set('jsdlfjdsf12324..3432jsdflsdf') <= allowed", "import string; allowed = set(string.ascii_lowercase + string.digits + '.')").timeit()
3.2119350433349609
>>> timeit.Timer("all(c in allowed for c in 'jsdlfjdsf12324..3432jsdflsdf')", "import string; allowed = set(string.ascii_lowercase + string.digits + '.')").timeit()
6.7066690921783447

If you want to allow empty strings then change it to:

reg=re.compile('^[a-z0-9\.]*$')
>>>reg.match('')
False

Under request I'm going to return the other part of the answer. But please note that the following accept A-Z range.

You can use isalnum

test_str.replace('.', '').isalnum()

>>> 'test123.3'.replace('.', '').isalnum()
True
>>> 'test123-3'.replace('.', '').isalnum()
False

EDIT Using isalnum is much more efficient than the set solution

>>> timeit.Timer("'jsdlfjdsf12324..3432jsdflsdf'.replace('.', '').isalnum()").timeit()
0.63245487213134766

EDIT2 John gave an example where the above doesn't work. I changed the solution to overcome this special case by using encode

test_str.replace('.', '').encode('ascii', 'replace').isalnum()

And it is still almost 3 times faster than the set solution

timeit.Timer("u'ABC\u0131\u0661'.encode('ascii', 'replace').replace('.','').isalnum()", "import string; allowed = set(string.ascii_lowercase + string.digits + '.')").timeit()
1.5719811916351318

In my opinion using regular expressions is the best to solve this problem

How do I parse a YAML file in Ruby?

I had the same problem but also wanted to get the content of the file (after the YAML front-matter).

This is the best solution I have found:

if (md = contents.match(/^(?<metadata>---\s*\n.*?\n?)^(---\s*$\n?)/m))
  self.contents = md.post_match
  self.metadata = YAML.load(md[:metadata])
end

Source and discussion: https://practicingruby.com/articles/tricks-for-working-with-text-and-files

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

In brief

This kind of a setup is simple and elegant :

env.json

{
  "development": {
      "facebook_app_id": "facebook_dummy_dev_app_id",
      "facebook_app_secret": "facebook_dummy_dev_app_secret",
  }, 
  "production": {
      "facebook_app_id": "facebook_dummy_prod_app_id",
      "facebook_app_secret": "facebook_dummy_prod_app_secret",
  }
}

common.js

var env = require('env.json');

exports.config = function() {
  var node_env = process.env.NODE_ENV || 'development';
  return env[node_env];
};

app.js

var common = require('./routes/common')
var config = common.config();

var facebook_app_id = config.facebook_app_id;
// do something with facebook_app_id

To run in production mode : $ NODE_ENV=production node app.js


In detail

This solution is from : http://himanshu.gilani.info/blog/2012/09/26/bootstraping-a-node-dot-js-app-for-dev-slash-prod-environment/, check it out for more detail.

GCC: array type has incomplete element type

The compiler needs to know the size of the second dimension in your two dimensional array. For example:

void print_graph(g_node graph_node[], double weight[][5], int nodes);

Correct way to pass multiple values for same parameter name in GET request

I would suggest looking at how browsers handle forms by default. For example take a look at the form element <select multiple> and how it handles multiple values from this example at w3schools.

<form action="/action_page.php">
<select name="cars" multiple>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>
<input type="submit">
</form>

For PHP use:

<select name="cars[]" multiple>

Live example from above at w3schools.com

From above if you click "saab, opel" and click submit, it will generate a result of cars=saab&cars=opel. Then depending on the back-end server, the parameter cars should come across as an array that you can further process.

Hope this helps anyone looking for a more 'standard' way of handling this issue.

Convert HTML Character Back to Text Using Java Standard Library

You can use the class org.apache.commons.lang.StringEscapeUtils:

String s = StringEscapeUtils.unescapeHtml("Happy &amp; Sad")

It is working.

How to convert a const char * to std::string

There is a constructor accepting two pointer parameters, so the code is simply

 std::string cppstr(cstr, cstr + min(max_length, strlen(cstr)));

this is also going to be as efficient as std::string cppstr(cstr) if the length is smaller than max_length.

Color picker utility (color pipette) in Ubuntu

I recommend GPick:

sudo apt-get install gpick

Applications -> Graphics -> GPick

It has many more features than gcolor2 but is still extremely simple to use: click on one of the hex swatches, move your mouse around the screen over the colours you want to pick, then press the Space bar to add to your swatch list.

If that doesn't work, another way is to click-and-drag from the centre of the hexagon and release your mouse over the pixel that you want to sample. Then immediately hit Space to copy that color into the next swatch in rotation.

It also has a traditional colour picker (like gcolor2) in the bottom right-hand corner of the window to allow you to pick individual colours with magnification.

Gather multiple sets of columns

It's not at all related to "tidyr" and "dplyr", but here's another option to consider: merged.stack from my "splitstackshape" package, V1.4.0 and above.

library(splitstackshape)
merged.stack(df, id.vars = c("id", "time"), 
             var.stubs = c("Q3.2.", "Q3.3."),
             sep = "var.stubs")
#     id       time .time_1       Q3.2.       Q3.3.
#  1:  1 2009-01-01      1. -0.62645381  1.35867955
#  2:  1 2009-01-01      2.  1.51178117 -0.16452360
#  3:  1 2009-01-01      3.  0.91897737  0.39810588
#  4:  2 2009-01-02      1.  0.18364332 -0.10278773
#  5:  2 2009-01-02      2.  0.38984324 -0.25336168
#  6:  2 2009-01-02      3.  0.78213630 -0.61202639
#  7:  3 2009-01-03      1. -0.83562861  0.38767161
# <<:::SNIP:::>>
# 24:  8 2009-01-08      3. -1.47075238 -1.04413463
# 25:  9 2009-01-09      1.  0.57578135  1.10002537
# 26:  9 2009-01-09      2.  0.82122120 -0.11234621
# 27:  9 2009-01-09      3. -0.47815006  0.56971963
# 28: 10 2009-01-10      1. -0.30538839  0.76317575
# 29: 10 2009-01-10      2.  0.59390132  0.88110773
# 30: 10 2009-01-10      3.  0.41794156 -0.13505460
#     id       time .time_1       Q3.2.       Q3.3.

Parse JSON in TSQL

I do also have a huge masochistic streak as that I've written yet another JSON parser. This one uses a procedural approach. It uses a similat SQL hierarchy list table to store the parsed data. Also in the package are:

  • Reverse process: from hierarchy to JSON
  • Querying functions: to fetch particular values from a JSON object

Please feel free to use and have fun with it

http://www.codeproject.com/Articles/1000953/JSON-for-Sql-Server-Part

Is there a way to get a textarea to stretch to fit its content without using PHP or JavaScript?

Here is a function that works with jQuery (for height only, not width):

function setHeight(jq_in){
    jq_in.each(function(index, elem){
        // This line will work with pure Javascript (taken from NicB's answer):
        elem.style.height = elem.scrollHeight+'px'; 
    });
}
setHeight($('<put selector here>'));

Note: The op asked for a solution that does not use Javascript, however this should be helpful to many people who come across this question.

Map.Entry: How to use it?

Note that you can also create your own structures using a Map.Entry as the main type, using its basic implementation AbstractMap.SimpleEntry. For instance, if you wanted to have an ordered list of entries, you could write:

List<Map.Entry<String, Integer>> entries = new ArrayList<>();
entries.add(new AbstractMap.SimpleEntry<String, Integer>(myStringValue, myIntValue));

And so on. From there, you have a list of tuples. Very useful when you want ordered tuples and a basic Map is a no-go.

Creating a directory in /sdcard fails

File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
        + "/FoderName");
if (!f.exists()) {
    f.mkdirs();
}

Struct Constructor in C++?

In C++ the only difference between a class and a struct is that members and base classes are private by default in classes, whereas they are public by default in structs.

So structs can have constructors, and the syntax is the same as for classes.

jQuery .find() on data from .ajax() call is returning "[object Object]" instead of div

I just spent 3 hours to solve a similar problem. This is what worked for me.

The element that I was attempting to retrieve from my $.get response was a first child element of the body tag. For some reason when I wrapped a div around this element, it became retrievable through $(response).find('#nameofelement').

No idea why but yeah, retrievable element cannot be first child of body... that might be helpful to someone :)

Unable to add window -- token null is not valid; is your activity running?

This error happens when you are trying to show popUpWindow too early ,to fix it, give Id to main layout as main_layout and use below code

Java:

 findViewById(R.id.main_layout).post(new Runnable() {
   public void run() {
       popupWindow.showAtLocation(findViewById(R.id.main_layout), Gravity.CENTER, 0, 0);
   }
});

Kotlin:

 main_layout.post {
      popupWindow?.showAtLocation(main_layout, Gravity.CENTER, 0, 0)
    }

Credit to @kordzik

How to refresh activity after changing language (Locale) inside application

If I imagined that you set android:configChanges in manifest.xml and create several directory for several language such as: values-fr OR values-nl, I could suggest this code(In Activity class):

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button btn = (Button) findViewById(R.id.btn);
    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // change language by onclick a button
             Configuration newConfig = new Configuration();
             newConfig.locale = Locale.FRENCH;
             onConfigurationChanged(newConfig);
        }
    });
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics());
    setContentView(R.layout.main);
    setTitle(R.string.app_name);

    // Checks the active language
    if (newConfig.locale == Locale.ENGLISH) {
        Toast.makeText(this, "English", Toast.LENGTH_SHORT).show();
    } else if (newConfig.locale == Locale.FRENCH){
        Toast.makeText(this, "French", Toast.LENGTH_SHORT).show();
    }
}

I tested this code, It is correct.

How do I get an object's unqualified (short) class name?

Quoting php.net:

On Windows, both slash (/) and backslash () are used as directory separator character. In other environments, it is the forward slash (/).

Based on this info and expanding from arzzzen answer this should work on both Windows and Nix* systems:

<?php

if (basename(str_replace('\\', '/', get_class($object))) == 'Name') {
    // ... do this ...
}

Note: I did a benchmark of ReflectionClass against basename+str_replace+get_class and using reflection is roughly 20% faster than using the basename approach, but YMMV.

How can I check if a Perl module is installed on my system from the command line?

You can check for a module's installation path by:

perldoc -l XML::Simple

The problem with your one-liner is that, it is not recursively traversing directories/sub-directories. Hence, you get only pragmatic module names as output.

How to view method information in Android Studio?

I'm using Visual Studio too much and I want to see params when I click on Ctrl+Space that's why I'm using Visual Studio keys. To change keymap to VS keymap: enter image description here enter image description here

.NET - How do I retrieve specific items out of a Dataset?

The DataSet object has a Tables array. If you know the table you want, it will have a Row array, each object of which has an ItemArray array. In your case the code would most likely be

int var1 = int.Parse(ds.Tables[0].Rows[0].ItemArray[4].ToString());

and so forth. This would give you the 4th item in the first row. You can also use Columns instead of ItemArray and specify the column name as a string instead of remembering it's index. That approach can be easier to keep up with if the table structure changes. So that would be

int var1 = int.Parse(ds.Tables[0].Rows[0]["MyColumnName"].ToString());

CSS selectors ul li a {...} vs ul > li > a {...}

1) for example HTML code:

<ul>
    <li>
        <a href="#">firstlink</a>
        <span><a href="#">second link&lt;/a>
    </li>
</ul>

and css rules:

1) ul li a {color:red;} 
2) ul > li > a {color:blue;}

">" - symbol mean that that will be searching only child selector (parentTag > childTag)

so first css rule will apply to all links (first and second) and second rule will apply anly to first link

2) As for efficiency - I think second will be more fast - as in case with JavaScript selectors. This rule read from right to left, this mean that when rule will parse by browser, it get all links on page: - in first case it will find all parent elements for each link on page and filter all links where exist parent tags "ul" and "li" - in second case it will check only parent node of link if it is "li" tag then -> check if parent tag of "li" is "ul"

some thing like this. Hope I describe all properly for you

Git push won't do anything (everything up-to-date)

I tried many methods including defined here. What I got is,

  • Make sure the name of repository is valid. The best way is to copy the link from repository site and paste in git bash.

  • Make sure you have commited the selected files.

    git commit -m "Your commit here"
    
  • If both steps don't work, try

    git push -u -f origin master

Find the version of an installed npm package

npm list --depth 0 is the command which shows all libraries with version but you can use npm-check

npm-check is a good library to manage all those things regarding the version system event it will show libraries versions, new version update, and unused version and many more.

to install it just run

npm install -g npm-check

and simply run

npm-check

check the screenshot it is showing everything about the package version, new version update, and unused version.

enter image description here

It works globally too. give it a try. Hope this help someone.

Proper way to return JSON using node or Express

If you are trying to send a json file you can use streams

var usersFilePath = path.join(__dirname, 'users.min.json');

apiRouter.get('/users', function(req, res){
    var readable = fs.createReadStream(usersFilePath);
    readable.pipe(res);
});

Parsing CSV files in C#, with header

This solution is using the official Microsoft.VisualBasic assembly to parse CSV.

Advantages:

  • delimiter escaping
  • ignores Header
  • trim spaces
  • ignore comments

Code:

    using Microsoft.VisualBasic.FileIO;

    public static List<List<string>> ParseCSV (string csv)
    {
        List<List<string>> result = new List<List<string>>();


        // To use the TextFieldParser a reference to the Microsoft.VisualBasic assembly has to be added to the project. 
        using (TextFieldParser parser = new TextFieldParser(new StringReader(csv))) 
        {
            parser.CommentTokens = new string[] { "#" };
            parser.SetDelimiters(new string[] { ";" });
            parser.HasFieldsEnclosedInQuotes = true;

            // Skip over header line.
            //parser.ReadLine();

            while (!parser.EndOfData)
            {
                var values = new List<string>();

                var readFields = parser.ReadFields();
                if (readFields != null)
                    values.AddRange(readFields);
                result.Add(values);
            }
        }

        return result;
    }

How to create a 100% screen width div inside a container in bootstrap?

2019's answer as this is still actively seen today

You should likely change the .container to .container-fluid, which will cause your container to stretch the entire screen. This will allow any div's inside of it to naturally stretch as wide as they need.

original hack from 2015 that still works in some situations

You should pull that div outside of the container. You're asking a div to stretch wider than its parent, which is generally not recommended practice.

If you cannot pull it out of the div for some reason, you should change the position style with this css:

.full-width-div {
    position: absolute;
    width: 100%;
    left: 0;
}

Instead of absolute, you could also use fixed, but then it will not move as you scroll.

What are the best PHP input sanitizing functions?

My 5 cents.

Nobody here understands the way mysql_real_escape_string works. This function do not filter or "sanitize" anything.
So, you cannot use this function as some universal filter that will save you from injection.
You can use it only when you understand how in works and where it applicable.

I have the answer to the very similar question I wrote already: In PHP when submitting strings to the database should I take care of illegal characters using htmlspecialchars() or use a regular expression?
Please click for the full explanation for the database side safety.

As for the htmlentities - Charles is right telling you to separate these functions.
Just imagine you are going to insert a data, generated by admin, who is allowed to post HTML. your function will spoil it.

Though I'd advise against htmlentities. This function become obsoleted long time ago. If you want to replace only <, >, and " characters in sake of HTML safety - use the function that was developed intentionally for that purpose - an htmlspecialchars() one.

Insert some string into given string at given index in Python

line='Name Age Group Class Profession'
arr = line.split()
for i in range(3):
    arr.insert(2, arr[2])
print(' '.join(arr))

Angular 2 two way binding using ngModel is not working

Angular has released its final version on 15th of September. Unlike Angular 1 you can use ngModel directive in Angular 2 for two way data binding, but you need write it in a bit different way like [(ngModel)] (Banana in a box syntax). Almost all angular2 core directives doesn't support kebab-case now instead you should use camelCase.

Now ngModel directive belongs to FormsModule, that's why you should import the FormsModule from @angular/forms module inside imports metadata option of AppModule(NgModule). Thereafter you can use ngModel directive inside on your page.

app/app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<h1>My First Angular 2 App</h1>
    <input type="text" [(ngModel)]="myModel"/>
    {{myModel}}
  `
})
export class AppComponent { 
  myModel: any;
}

app/app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent }   from './app.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule ], //< added FormsModule here
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})

export class AppModule { }

app/main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';

const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);

Demo Plunkr

Number to String in a formula field

i wrote a simple function for this:

Function (stringVar param)
(
    Local stringVar oneChar := '0';
    Local numberVar strLen := Length(param);
    Local numberVar index := strLen;

    oneChar = param[strLen];

    while index > 0 and oneChar = '0' do
    (
        oneChar := param[index];
        index := index - 1;
    );

    Left(param , index + 1);
)

If Else in LINQ

I assume from db that this is LINQ-to-SQL / Entity Framework / similar (not LINQ-to-Objects);

Generally, you do better with the conditional syntax ( a ? b : c) - however, I don't know if it will work with your different queries like that (after all, how would your write the TSQL?).

For a trivial example of the type of thing you can do:

select new {p.PriceID, Type = p.Price > 0 ? "debit" : "credit" };

You can do much richer things, but I really doubt you can pick the table in the conditional. You're welcome to try, of course...

Remove grid, background color, and top and right borders from ggplot2

The above options do not work for maps created with sf and geom_sf(). Hence, I want to add the relevant ndiscr parameter here. This will create a nice clean map showing only the features.

library(sf)
library(ggplot2)

ggplot() + 
  geom_sf(data = some_shp) + 
  theme_minimal() +                     # white background
  theme(axis.text = element_blank(),    # remove geographic coordinates
        axis.ticks = element_blank()) + # remove ticks
  coord_sf(ndiscr = 0)                  # remove grid in the background

How to select a dropdown value in Selenium WebDriver using Java

You can use following methods to handle drop down in selenium.

  1. driver.selectByVisibleText("Text");
  2. driver.selectByIndex(1);
  3. driver.selectByValue("prog");

For more details you can refer http://www.codealumni.com/handle-drop-selenium-webdriver/ this post.

It will definately help you a lot in resolving your queries.

Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot

None of the above worked for me. I SOLVED my problem by saving my source data (save as) Excel file as a single xls Worksheet Excel 5.0/95 and imported without column headings. Also, I created the table in advance and mapped manually instead of letting SQL create the table.