Programs & Examples On #Readerwriterlock

Formatting MM/DD/YYYY dates in textbox in VBA

Just for fun I took Siddharth's suggestion of separate textboxes and did comboboxes. If anybody's interested, add a userform with three comboboxes named cboDay, cboMonth and cboYear and arrange them left to right. Then paste the code below into the UserForm's code module. The required combobox properties are set in UserFormInitialization, so no additional prep should be required.

The tricky part is changing the day when it becomes invalid because of a change in year or month. This code just resets it to 01 when that happens and highlights cboDay.

I haven't coded anything like this in a while. Hopefully it will be of interest to somebody, someday. If not it was fun!

Dim Initializing As Boolean

Private Sub UserForm_Initialize()
Dim i As Long
Dim ctl As MSForms.Control
Dim cbo As MSForms.ComboBox

Initializing = True
With Me
    With .cboMonth
        '        .AddItem "month"
        For i = 1 To 12
            .AddItem Format(i, "00")
        Next i
        .Tag = "DateControl"
    End With
    With .cboDay
        '        .AddItem "day"
        For i = 1 To 31
            .AddItem Format(i, "00")
        Next i
        .Tag = "DateControl"
    End With
    With .cboYear
        '        .AddItem "year"
        For i = Year(Now()) To Year(Now()) + 12
            .AddItem i
        Next i
        .Tag = "DateControl"
    End With
    DoEvents
    For Each ctl In Me.Controls
        If ctl.Tag = "DateControl" Then
            Set cbo = ctl
            With cbo
                .ListIndex = 0
                .MatchRequired = True
                .MatchEntry = fmMatchEntryComplete
                .Style = fmStyleDropDownList
            End With
        End If
    Next ctl
End With
Initializing = False
End Sub

Private Sub cboDay_Change()
If Not Initializing Then
    If Not IsValidDate Then
        ResetMonth
    End If
End If
End Sub

Private Sub cboMonth_Change()
If Not Initializing Then
    ResetDayList
    If Not IsValidDate Then
        ResetMonth
    End If
End If
End Sub

Private Sub cboYear_Change()
If Not Initializing Then
    ResetDayList
    If Not IsValidDate Then
        ResetMonth
    End If
End If
End Sub

Function IsValidDate() As Boolean
With Me
    IsValidDate = IsDate(.cboMonth & "/" & .cboDay & "/" & .cboYear)
End With
End Function
Sub ResetDayList()
Dim i As Long
Dim StartDay As String

With Me.cboDay
    StartDay = .Text
    For i = 31 To 29 Step -1
        On Error Resume Next
        .RemoveItem i - 1
        On Error GoTo 0
    Next i
    For i = 29 To 31
        If IsDate(Me.cboMonth & "/" & i & "/" & Me.cboYear) Then
            .AddItem Format(i, "0")
        End If
    Next i
    On Error Resume Next
    .Text = StartDay
    If Err.Number <> 0 Then
        .SetFocus
        .ListIndex = 0
    End If
End With
End Sub

Sub ResetMonth()
Me.cboDay.ListIndex = 0
End Sub

Delete all data in SQL Server database

SQLMenace's solution worked for me with a slight tweak to how data is deleted - DELETE FROM instead of TRUNCATE.

-- disable referential integrity
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL' 
GO 

EXEC sp_MSForEachTable 'DELETE FROM ?' 
GO 

-- enable referential integrity again 
EXEC sp_MSForEachTable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL' 
GO

how to run a winform from console application?

You can create a winform project in VS2005/ VS2008 and then change its properties to be a command line application. It can then be started from the command line, but will still open a winform.

How do I check out a remote Git branch?

If the branch is on something other than the origin remote I like to do the following:

$ git fetch
$ git checkout -b second/next upstream/next

This will checkout the next branch on the upstream remote in to a local branch called second/next. Which means if you already have a local branch named next it will not conflict.

$ git branch -a
* second/next
  remotes/origin/next
  remotes/upstream/next

How to run Ruby code from terminal?

If Ruby is installed, then

ruby yourfile.rb

where yourfile.rb is the file containing the ruby code.

Or

irb

to start the interactive Ruby environment, where you can type lines of code and see the results immediately.

Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat

I resolved all of my issues by adding this into project.properties

cordova.system.library.7=com.android.support:appcompat-v7:27.1.0

How to handle notification when app in background in Firebase

I feel like all the responses are incomplete but all of them have something that you need to process a notification that have data when your app is in background.

Follow these steps and you will be able to process your notifications when your app is in background.

1.Add an intent-filter like this:

<activity android:name=".MainActivity">
      <intent-filter>
           <action android:name=".MainActivity" />
           <category android:name="android.intent.category.DEFAULT" />
      </intent-filter>
</activity>

to an activity that you want to process the notification data.

  1. Send notifications with the next format:

    { 
     "notification" : {
            "click_action" : ".MainActivity", 
            "body" : "new Symulti update !", 
            "title" : "new Symulti update !", 
            "icon" : "ic_notif_symulti" }, 
     "data": { ... },
     "to" : "c9Vaa3ReGdk:APA91bH-AuXgg3lDN2WMcBrNhJZoFtYF9" }
    

The key here is add

"click_action" : ".MainActivity"

where .MainActivity is the activity with the intent-filter that you added in step 1.

  1. Get "data" info from notification in the onCreate of ".MainActivity":

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //get notification data info
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
           //bundle must contain all info sent in "data" field of the notification
        }
    }
    

And that should be all you need to do. I hope this helps somebody :)

How to use Fiddler to monitor WCF service

So simple, all you need is to change the address in the config client: instead of 'localhost' change to the machine name or IP

"undefined" function declared in another file?

If your source folder is structured /go/src/blog (assuming the name of your source folder is blog).

  1. cd /go/src/blog ... (cd inside the folder that has your package)
  2. go install
  3. blog

That should run all of your files at the same time, instead of you having to list the files manually or "bashing" a method on the command line.

LaTeX: Multiple authors in a two-column article

I put together a little test here:

\documentclass[10pt,twocolumn]{article}

\title{Article Title}
\author{
    First Author\\
    Department\\
    school\\
    email@edu
  \and
    Second Author\\
    Department\\
    school\\
    email@edu
    \and
    Third Author\\
    Department\\
    school\\
    email@edu
    \and
    Fourth Author\\
    Department\\
    school\\
    email@edu
}
\date{\today}

\begin{document}

\maketitle

\begin{abstract}
\ldots
\end{abstract}

\section{Introduction}
\ldots

\end{document}

Things to note, the title, author and date fields are declared before \begin{document}. Also, the multicol package is likely unnecessary in this case since you have declared twocolumn in the document class.

This example puts all four authors on the same line, but if your authors have longer names, departments or emails, this might cause it to flow over onto another line. You might be able to change the font sizes around a little bit to make things fit. This could be done by doing something like {\small First Author}. Here's a more detailed article on \LaTeX font sizes:

https://engineering.purdue.edu/ECN/Support/KB/Docs/LaTeXChangingTheFont

To italicize you can use {\it First Name} or \textit{First Name}.

Be careful though, if the document is meant for publication often times journals or conference proceedings have their own formatting guidelines so font size trickery might not be allowed.

Changing width property of a :before css selector using JQuery

I don't think there's a jQuery-way to directly access the pseudoclass' rules, but you could always append a new style element to the document's head like:

$('head').append('<style>.column:before{width:800px !important;}</style>');

See a live demo here

I also remember having seen a plugin that tackles this issue once but I couldn't find it on first googling unfortunately.

How do I return a string from a regex match in python?

Considering there might be several img tags I would recommend re.findall:

import re

with open("sample.txt", 'r') as f_in, open('writetest.txt', 'w') as f_out:
    for line in f_in:
        for img in re.findall('<img[^>]+>', line):
            print >> f_out, "yo it's a {}".format(img)

How to convert Double to int directly?

double myDb = 12.3;
int myInt = (int) myDb;

Result is: myInt = 12

How to index into a dictionary?

actually I found a novel solution that really helped me out, If you are especially concerned with the index of a certain value in a list or data set, you can just set the value of dictionary to that Index!:

Just watch:

list = ['a', 'b', 'c']
dictionary = {}
counter = 0
for i in list:
   dictionary[i] = counter
   counter += 1

print(dictionary) # dictionary = {'a':0, 'b':1, 'c':2}

Now through the power of hashmaps you can pull the index your entries in constant time (aka a whole lot faster)

apc vs eaccelerator vs xcache

In all tests I have seen, eAccelerator performs faster than any other cache out there and uses less memeory to do so. It comes with a nifty script to view cache utilisation and clear the cache etc. eAccelerator is compatible with xdebug and Zend Optimizer.

APC is being included in PHP because it is being maintained by the PHP developers. It performs very well, but not as good as eAccelerator. And it has compatability issues with Zend Optimizer.

Xcache was made by the developers of lighttpd, benchmarks show it performs similiarly to eAccelerator, and faster than APC.

So which is the best?

APC = Great if you want an easy cache that will always work with PHP, no fuss. eAccelerator = If you have time to maintain it, keep it up todate and understand how it works, it will perform faster. Long term support not as certain as APC because APC is done by the PHP devs.

Update and left outer join statements

If what you need is UPDATE from SELECT statement you can do something like this:

UPDATE suppliers    
SET city = (SELECT customers.city FROM customers

WHERE customers.customer_name = suppliers.supplier_name)

Changing default startup directory for command prompt in Windows 7

regedit worked great. HKEY_CURRENT_USER\SOFTWARE\MICROSOFT\Command Processor, all you have to do is change the AutoRun key value, which is already set to wherever you are currently getting dumped into to a new value in the format of:

cd /d <drive:path>

for c:\, that would be cd /d c:\
for junk, that would be cd d/ c:\junk

its very simple, even a novice thats never used regedit should be able to figure it out. if not, go to the c:\prompt and just type in regedit, then follow the path to the key.

Representing null in JSON

I would use null to show that there is no value for that particular key. For example, use null to represent that "number of devices in your household connects to internet" is unknown.

On the other hand, use {} if that particular key is not applicable. For example, you should not show a count, even if null, to the question "number of cars that has active internet connection" is asked to someone who does not own any cars.

I would avoid defaulting any value unless that default makes sense. While you may decide to use null to represent no value, certainly never use "null" to do so.

Input type DateTime - Value format?

with momentjs i use

moment(value).format("YYYY-MM-DDTHH:mm:ss")

String to decimal conversion: dot separation instead of comma

Instead of replace we can force culture like

var x = decimal.Parse("18,285", new NumberFormatInfo() { NumberDecimalSeparator = "," });

it will give output 18.285

C read file line by line

Here is my several hours... Reading whole file line by line.

char * readline(FILE *fp, char *buffer)
{
    int ch;
    int i = 0;
    size_t buff_len = 0;

    buffer = malloc(buff_len + 1);
    if (!buffer) return NULL;  // Out of memory

    while ((ch = fgetc(fp)) != '\n' && ch != EOF)
    {
        buff_len++;
        void *tmp = realloc(buffer, buff_len + 1);
        if (tmp == NULL)
        {
            free(buffer);
            return NULL; // Out of memory
        }
        buffer = tmp;

        buffer[i] = (char) ch;
        i++;
    }
    buffer[i] = '\0';

    // Detect end
    if (ch == EOF && (i == 0 || ferror(fp)))
    {
        free(buffer);
        return NULL;
    }
    return buffer;
}

void lineByline(FILE * file){
char *s;
while ((s = readline(file, 0)) != NULL)
{
    puts(s);
    free(s);
    printf("\n");
}
}

int main()
{
    char *fileName = "input-1.txt";
    FILE* file = fopen(fileName, "r");
    lineByline(file);
    return 0;
}

Bootstrap modal: close current, open new

You need to add following attribute to the link or button where you want add this functionality:

 data-dismiss="modal" data-toggle="modal" id="forgotPassword" data-target="#ModalForgotPassword"

A detaile blog: http://sforsuresh.in/bootstrap-modal-window-close-current-open-new-modal/

Are there any SHA-256 javascript implementations that are generally considered trustworthy?

Besides the Stanford lib that tylerl mentioned. I found jsrsasign very useful (Github repo here:https://github.com/kjur/jsrsasign). I don't know how exactly trustworthy it is, but i've used its API of SHA256, Base64, RSA, x509 etc. and it works pretty well. In fact, it includes the Stanford lib as well.

If all you want to do is SHA256, jsrsasign might be a overkill. But if you have other needs in the related area, I feel it's a good fit.

How do you get the currently selected <option> in a <select> via JavaScript?

var payeeCountry = document.getElementById( "payeeCountry" );
alert( payeeCountry.options[ yourSelect.selectedIndex ].value );

iOS 7 status bar back to iOS 6 default style in iPhone app?

I found here is the best alternatives and solution for this navigation bar issue in iOS7!!

http://www.appcoda.com/customize-navigation-status-bar-ios-7/

I hope it will clear our all queries and worries.

How to get a variable value if variable name is stored as string?

Modified my search keywords and Got it :).

eval a=\$$a
Thanks for your time.

Difference between _self, _top, and _parent in the anchor tag target attribute

While these answers are good, IMHO I don't think they fully address the question.

The target attribute in an anchor tag tells the browser the target of the destination of the anchor. They were initially created in order to manipulate and direct anchors to the frame system of document. This was well before CSS came to the aid of HTML developers.

While target="_self" is default by browser and the most common target is target="_blank" which opens the anchor in a new window(which has been redirected to tabs by browser settings usually). The "_parent", "_top" and framename tags are left a mystery to those that aren't familiar with the days of iframe site building as the trend.

target="_self" This opens an anchor in the same frame. What is confusing is that because we generally don't write in frames anymore (and the frame and frameset tags are obsolete in HTML5) people assume this a same window function. Instead if this anchor was nested in frames it would open in a sandbox mode of sorts, meaning only in that frame.

target="_parent" Will open the in the next level up of a frame if they were nested to inside one another

target="_top" This breaks outside of all the frames it is nested in and opens the link as top document in the browser window.

target="framename This was originally deprecated but brought back in HTML5. This will target the exact frame in question. While the name was the proper method that method has been replaced with using the id identifying tag.

<!--Example:-->

<html>
<head>
</head>
<body>
<iframe src="url1" name="A"><p> This my first iframe</p></iframe>
<iframe src="url2" name="B"><p> This my second iframe</p></iframe>
<iframe src="url3" name="C"><p> This my third iframe</p></iframe>

<a href="url4" target="B"></a>
</body>
</html>

How to check which locks are held on a table

This is not exactly showing you which rows are locked, but this may helpful to you.

You can check which statements are blocked by running this:

select cmd,* from sys.sysprocesses
where blocked > 0

It will also tell you what each block is waiting on. So you can trace that all the way up to see which statement caused the first block that caused the other blocks.

Edit to add comment from @MikeBlandford:

The blocked column indicates the spid of the blocking process. You can run kill {spid} to fix it.

Check whether an array is empty

function empty() does not work for testing empty arrays! example:

$a=array("","");
if(empty($a)) echo "empty";
else echo "not empty"; //this case is true

a function is necessary:

function is_array_empty($a){
foreach($a as $elm)
if(!empty($elm)) return false;
return true;
}

ok, this is a very old question :) , but i found this thread searching for a solution and i didnt find a good one.

bye (sorry for my english)

Adding images or videos to iPhone Simulator

  1. Ensure the device is running.

  2. Execute the following in terminal:

open ~/Library/Developer/CoreSimulator/Devices/$(xcrun simctl list | grep Booted | grep -Eo '[a-zA-Z0-9]*-[a-zA-Z0-9]*-[a-zA-Z0-9]*-[a-zA-Z0-9]*-[a-zA-Z0-9]*')/data/Media/DCIM

Further regex ref @ https://regex101.com/r/tY951n/3

SQL ORDER BY multiple columns

Yes, the sorting is different.

Items in the ORDER BY list are applied in order.
Later items only order peers left from the preceding step.

Why don't you just try?

Android - How to decode and decompile any APK file?

To decompile APK Use APKTool.
You can learn how APKTool works on http://www.decompileandroid.com/ or by reading the documentation.

SQLite error 'attempt to write a readonly database' during insert?

In summary, I've fixed the problem by putting the database file (* .db) in a subfolder.

  • The subfolder and the database file within it must be a member of the www-data group.
  • In the www-data group, you must have the right to write to the subfolder and the database file.

Apply CSS rules if browser is IE

I prefer using a separate file for ie rules, as described earlier.

<!--[if IE]><link rel="stylesheet" type="text/css" href="ie-style.css"/><![endif]-->

And inside it you can set up rules for different versions of ie using this:

.abc {...} /* ALL MSIE */
*html *.abc {...} /* MSIE 6 */
*:first-child+html .abc {...} /* MSIE 7 */

Implement an input with a mask

Input masks can be implemented using a combination of the keyup event, and the HTMLInputElement value, selectionStart, and selectionEnd properties. Here's a very simple implementation which does some of what you want. It's certainly not perfect, but works well enough to demonstrate the principle:

_x000D_
_x000D_
Array.prototype.forEach.call(document.body.querySelectorAll("*[data-mask]"), applyDataMask);_x000D_
_x000D_
function applyDataMask(field) {_x000D_
    var mask = field.dataset.mask.split('');_x000D_
    _x000D_
    // For now, this just strips everything that's not a number_x000D_
    function stripMask(maskedData) {_x000D_
        function isDigit(char) {_x000D_
            return /\d/.test(char);_x000D_
        }_x000D_
        return maskedData.split('').filter(isDigit);_x000D_
    }_x000D_
    _x000D_
    // Replace `_` characters with characters from `data`_x000D_
    function applyMask(data) {_x000D_
        return mask.map(function(char) {_x000D_
            if (char != '_') return char;_x000D_
            if (data.length == 0) return char;_x000D_
            return data.shift();_x000D_
        }).join('')_x000D_
    }_x000D_
    _x000D_
    function reapplyMask(data) {_x000D_
        return applyMask(stripMask(data));_x000D_
    }_x000D_
    _x000D_
    function changed() {   _x000D_
        var oldStart = field.selectionStart;_x000D_
        var oldEnd = field.selectionEnd;_x000D_
        _x000D_
        field.value = reapplyMask(field.value);_x000D_
        _x000D_
        field.selectionStart = oldStart;_x000D_
        field.selectionEnd = oldEnd;_x000D_
    }_x000D_
    _x000D_
    field.addEventListener('click', changed)_x000D_
    field.addEventListener('keyup', changed)_x000D_
}
_x000D_
ISO Date: <input type="text" value="____-__-__" data-mask="____-__-__"/><br/>_x000D_
Telephone: <input type="text" value="(___) ___-____" data-mask="(___) ___-____"/><br/>
_x000D_
_x000D_
_x000D_

(View in JSFiddle)

There are also a number of libraries out there which perform this function. Some examples include:

Get file content from URL?

1) local simplest methods

<?php
echo readfile("http://example.com/");   //needs "Allow_url_include" enabled
//OR
echo include("http://example.com/");    //needs "Allow_url_include" enabled
//OR
echo file_get_contents("http://example.com/");
//OR
echo stream_get_contents(fopen('http://example.com/', "rb")); //you may use "r" instead of "rb"  //needs "Allow_url_fopen" enabled
?> 

2) Better Way is CURL:

echo get_remote_data('http://example.com'); // GET request 
echo get_remote_data('http://example.com', "var2=something&var3=blabla" ); // POST request

It automatically handles FOLLOWLOCATION problem + Remote urls:
src="./imageblabla.png" turned into:
src="http://example.com/path/imageblabla.png"

Code : https://github.com/tazotodua/useful-php-scripts/blob/master/get-remote-url-content-data.php

super() raises "TypeError: must be type, not classobj" for new-style class

You can also use class TextParser(HTMLParser, object):. This makes TextParser a new-style class, and super() can be used.

Most pythonic way to delete a file which may not exist

if os.path.exists(filename): os.remove(filename)

is a one-liner.

Many of you may disagree - possibly for reasons like considering the proposed use of ternaries "ugly" - but this begs the question of whether we should listen to people used to ugly standards when they call something non-standard "ugly".

How to get random value out of an array?

A simple way to getting Randdom value form Array.

$color_array =["red","green","blue","light_orange"];
$color_array[rand(0,3)

now every time you will get different colors from Array.

How to Consume WCF Service with Android

You will need something more that a http request to interact with a WCF service UNLESS your WCF service has a REST interface. Either look for a SOAP web service API that runs on android or make your service RESTful. You will need .NET 3.5 SP1 to do WCF REST services:

http://msdn.microsoft.com/en-us/netframework/dd547388.aspx

MetadataException when using Entity Framework Entity Connection

There are several possible catches. I think that the most common error is in this part of the connection string:

res://xxx/yyy.csdl|res://xxx/yyy.ssdl|res://xxx/yyy.msl;

This is no magic. Once you understand what is stands for you'll get the connection string right.

First the xxx part. That's nothing else than an assembly name where you defined you EF context clas. Usually it would be something like MyProject.Data. Default value is * which stands for all loaded assemblies. It's always better to specify a particular assembly name.

Now the yyy part. That's a resource name in the xxx assembly. It will usually be something like a relative path to your .edmx file with dots instead of slashes. E.g. Models/Catalog - Models.Catalog The easiest way to get the correct string for your application is to build the xxx assembly. Then open the assembly dll file in a text editor (I prefer the Total Commander's default viewer) and search for ".csdl". Usually there won't be more than 1 occurence of that string.

Your final EF connection string may look like this:

res://MyProject.Data/Models.Catalog.DataContext.csdl|res://MyProject.Data/Models.Catalog.DataContext.ssdl|res://MyProject.Data/Models.Catalog.DataContext.msl;

Generating random, unique values C#

NOTE, I dont recommend this :). Here's a "oneliner" as well:

//This code generates numbers between 1 - 100 and then takes 10 of them.
var result = Enumerable.Range(1,101).OrderBy(g => Guid.NewGuid()).Take(10).ToArray();

Favicon: .ico or .png / correct tags?

For compatibility with all browsers stick with .ico.

.png is getting more and more support though as it is easier to create using multiple programs.

for .ico

<link rel="shortcut icon" href="http://example.com/myicon.ico" />

for .png, you need to specify the type

<link rel="icon" type="image/png" href="http://example.com/image.png" />

Why do people write #!/usr/bin/env python on the first line of a Python script?

This is meant as more of historical information than a "real" answer.

Remember that back in the day you had LOTS of unix like operating systems whose designers all had their own notion of where to put stuff, and sometimes didn't include Python, Perl, Bash, or lots of other GNU/Open Source stuff at all.

This was even true of different Linux distributions. On Linux--pre-FHS[1]-you might have python in /usr/bin/ or /usr/local/bin/. Or it might not have been installed, so you built your own and put it in ~/bin

Solaris was the worst I ever worked on, partially as the transition from Berkeley Unix to System V. You could wind up with stuff in /usr/, /usr/local/, /usr/ucb, /opt/ etc. This could make for some really long paths. I have memories of the stuff from Sunfreeware.com installing each package in it's own directory, but I can't recall if it symlinked the binaries into /usr/bin or not.

Oh, and sometimes /usr/bin was on an NFS server[2].

So the env utility was developed to work around this.

Then you could write #!/bin/env interpreter and as long as the path was proper things had a reasonable chance of running. Of course, reasonable meant (for Python and Perl) that you had also set the appropriate environmental variables. For bash/ksh/zsh it just worked.

This was important because people were passing around shell scripts (like perl and python) and if you'd hard coded /usr/bin/python on your Red Hat Linux workstation it was going to break bad on a SGI...well, no, I think IRIX put python in the right spot. But on a Sparc station it might not run at all.

I miss my sparc station. But not a lot. Ok, now you've got me trolling around on E-Bay. Bastages.

[1] File-system Hierarchy Standard. https://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard

[2] Yes, and sometimes people still do stuff like that. And no, I did not wear either a turnip OR an onion on my belt.

Regular expression: zero or more occurrences of optional character /

/*

If your delimiters are slash-based, escape it:

\/*

* means "0 or more of the previous repeatable pattern", which can be a single character, a character class or a group.

No notification sound when sending notification from firebase in android

With HTTP v1 API it is different

Documentation

Example:

{
 "message":{
    "topic":"news",
    "notification":{
       "body":"Very good news",
       "title":"Good news"
    },
    "android":{
       "notification":{
          "body":"Very good news",
          "title":"Good news",
          "sound":"default"
       }
    }
  }
}

Cleanest way to reset forms

Doing this with simple HTML and javascript by casting the HTML element so as to avoid typescript errors

<form id="Login">

and in the component.ts file,

clearForm(){
 (<HTMLFormElement>document.getElementById("Login")).reset();
}

the method clearForm() can be called anywhere as need be.

UIScrollView Scrollable Content Size Ambiguity

In my case I received the issue of incorrect content size and content Size Ambiguity in iPad but was working in case of iPhone. I have done the following changes in storyboard to resolve the issue.

  1. Add scrollview in UIView and add constraints leading, top, trailing and bottom to 0,0,0,0.
  2. Set height of scroll view as per the requirements for eg. 100.
  3. Add UIView to scroll view and add constraints leading, top, trailing and bottom to 0,0,0,0 and align centre(X) and center(Y) constraints.
  4. Deselect “Content Layout Guides” in size inspector of scroll view.

Check variable equality against a list of values

Using the answers provided, I ended up with the following:

Object.prototype.in = function() {
    for(var i=0; i<arguments.length; i++)
       if(arguments[i] == this) return true;
    return false;
}

It can be called like:

if(foo.in(1, 3, 12)) {
    // ...
}

Edit: I came across this 'trick' lately which is useful if the values are strings and do not contain special characters. For special characters is becomes ugly due to escaping and is also more error-prone due to that.

/foo|bar|something/.test(str);

To be more precise, this will check the exact string, but then again is more complicated for a simple equality test:

/^(foo|bar|something)$/.test(str);

Recommended way to embed PDF in HTML?

Convert it to PNG via ImageMagick, and display the PNG (quick and dirty).

<?php
  $dir = '/absolute/path/to/my/directory/';
  $name = 'myPDF.pdf';
  exec("/bin/convert $dir$name $dir$name.png");
  print '<img src="$dir$name.png" />';
?>

This is a good option if you need a quick solution, want to avoid cross-browser PDF viewing problems, and if the PDF is only a page or two. Of course, you need ImageMagick installed (which in turn needs Ghostscript) on your webserver, an option that might not be available in shared hosting environments. There is also a PHP plugin (called imagick) that works like this but it has it's own special requirements.

PopupWindow $BadTokenException: Unable to add window -- token null is not valid

Use:

YourActivityName.this

Instead of:

getApplicationContext();

Conveniently map between enum and int / String

Seems the answer(s) to this question are outdated with the release of Java 8.

  1. Don't use ordinal as ordinal is unstable if persisted outside the JVM such as a database.
  2. It is relatively easy to create a static map with the key values.

public enum AccessLevel {
  PRIVATE("private", 0),
  PUBLIC("public", 1),
  DEFAULT("default", 2);

  AccessLevel(final String name, final int value) {
    this.name = name;
    this.value = value;
  }

  private final String name;
  private final int value;

  public String getName() {
    return name;
  }

  public int getValue() {
    return value;
  }

  static final Map<String, AccessLevel> names = Arrays.stream(AccessLevel.values())
      .collect(Collectors.toMap(AccessLevel::getName, Function.identity()));
  static final Map<Integer, AccessLevel> values = Arrays.stream(AccessLevel.values())
      .collect(Collectors.toMap(AccessLevel::getValue, Function.identity()));

  public static AccessLevel fromName(final String name) {
    return names.get(name);
  }

  public static AccessLevel fromValue(final int value) {
    return values.get(value);
  }
}

PHP display current server path

If you call getcwd it should give you the path:

<?php
  echo getcwd();
?>

what does this mean ? image/png;base64?

That is, you are referencing an image, but instead of providing an external url, the png image data is in the url itself, embedded in the style sheet. data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).

How to include files outside of Docker's build context?

I often find myself utilizing the --build-arg option for this purpose. For example after putting the following in the Dockerfile:

ARG SSH_KEY
RUN echo "$SSH_KEY" > /root/.ssh/id_rsa

You can just do:

docker build -t some-app --build-arg SSH_KEY="$(cat ~/file/outside/build/context/id_rsa)" .

But note the following warning from the Docker documentation:

Warning: It is not recommended to use build-time variables for passing secrets like github keys, user credentials etc. Build-time variable values are visible to any user of the image with the docker history command.

Greater than less than, python

Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.

>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False

Edit

Further explanation: How does Python compare string and int?

How to set min-height for bootstrap container

Have you tried height: auto; on your .container div?

Here is a fiddle, if you change img height, container height will adjust to it.

EDIT

So if you "can't" change the inline min-height, you can overwrite the inline style with an !important parameter. It's not the cleanest way, but it solves your problem.

add to your .containerclass this line

min-height:0px !important;

I've updated my fiddle to give you an example.

Error: the entity type requires a primary key

I found a bit different cause of the error. It seems like SQLite wants to use correct primary key class property name. So...

Wrong PK name

public class Client
{
  public int SomeFieldName { get; set; }  // It is the ID
  ...
}

Correct PK name

public class Client
{
  public int Id { get; set; }  // It is the ID
  ...
}

public class Client
{
  public int ClientId { get; set; }  // It is the ID
  ...
}

It still posible to use wrong PK name but we have to use [Key] attribute like

public class Client
{
   [Key]
   public int SomeFieldName { get; set; }  // It is the ID
   ...
}

What is the fastest way to compare two sets in Java?

I think method reference with equals method can be used. We assume that the object type without a shadow of a doubt has its own comparison method. Plain and simple example is here,

Set<String> set = new HashSet<>();
set.addAll(Arrays.asList("leo","bale","hanks"));

Set<String> set2 = new HashSet<>();
set2.addAll(Arrays.asList("hanks","leo","bale"));

Predicate<Set> pred = set::equals;
boolean result = pred.test(set2);
System.out.println(result);   // true

How to configure a HTTP proxy for svn

In TortoiseSVN you can configure the proxy server under Settings=> Network

What is an NP-complete in computer science?

It's a class of problems where we must simulate every possibility to be sure we have the optimal solution.

There are a lot of good heuristics for some NP-Complete problems, but they are only an educated guess at best.

Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass

I also got the same exception:

I tried the following steps:

  1. In Eclipse> Project > Clean. (The Exception remained)

  2. I ran another project(The testng.xml ran successfully)

After running another project, I ran the project in which I was getting the Exception, and fortunately it worked for me, with no errors.

C++ Erase vector element by value rather than by position?

How about std::remove() instead:

#include <algorithm>
...
vec.erase(std::remove(vec.begin(), vec.end(), 8), vec.end());

This combination is also known as the erase-remove idiom.

Export from pandas to_excel without row names (index)?

Example: index = False

import pandas as pd

writer = pd.ExcelWriter("dataframe.xlsx", engine='xlsxwriter')
dataframe.to_excel(writer,sheet_name = dataframe, index=False)
writer.save() 

Reusing output from last command in Bash

The answer is no. Bash doesn't allocate any output to any parameter or any block on its memory. Also, you are only allowed to access Bash by its allowed interface operations. Bash's private data is not accessible unless you hack it.

Angular ng-class if else

Both John Conde's and ryeballar's answers are correct and will work.

If you want to get too geeky:

  • John's has the downside that it has to make two decisions per $digest loop (it has to decide whether to add/remove center and it has to decide whether to add/remove left), when clearly only one is needed.

  • Ryeballar's relies on the ternary operator which is probably going to be removed at some point (because the view should not contain any logic). (We can't be sure it will indeed be removed and it probably won't be any time soon, but if there is a more "safe" solution, why not ?)


So, you can do the following as an alternative:

ng-class="{true:'center',false:'left'}[page.isSelected(1)]"

Android Center text on canvas

I create a method to simplify this:

    public static void drawCenterText(String text, RectF rectF, Canvas canvas, Paint paint) {
    Paint.Align align = paint.getTextAlign();
    float x;
    float y;
    //x
    if (align == Paint.Align.LEFT) {
        x = rectF.centerX() - paint.measureText(text) / 2;
    } else if (align == Paint.Align.CENTER) {
        x = rectF.centerX();
    } else {
        x = rectF.centerX() + paint.measureText(text) / 2;
    }
    //y
    metrics = paint.getFontMetrics();
    float acent = Math.abs(metrics.ascent);
    float descent = Math.abs(metrics.descent);
    y = rectF.centerY() + (acent - descent) / 2f;
    canvas.drawText(text, x, y, paint);

    Log.e("ghui", "top:" + metrics.top + ",ascent:" + metrics.ascent
            + ",dscent:" + metrics.descent + ",leading:" + metrics.leading + ",bottom" + metrics.bottom);
}

rectF is the area you want draw the text,That's it. Details

is there a tool to create SVG paths from an SVG file?

Open the svg using Inkscape.

Inkscape is a svg editor it is a bit like Illustrator but as it is built specifically for svg it handles it way better. It is a free software and it's available @ https://inkscape.org/en/

  • ctrl A (select all)
  • shift ctrl C (=Path/Object to paths)
  • ctrl s (save (choose as plain svg))

done

all rect/circle have been converted to path

How to get name of the computer in VBA?

Dim sHostName As String

' Get Host Name / Get Computer Name

sHostName = Environ$("computername")

check if directory exists and delete in one command unix

Try:

bash -c '[ -d my_mystery_dirname ] && run_this_command'

This will work if you can run bash on the remote machine....

In bash, [ -d something ] checks if there is directory called 'something', returning a success code if it exists and is a directory. Chaining commands with && runs the second command only if the first one succeeded. So [ -d somedir ] && command runs the command only if the directory exists.

Permission denied on CopyFile in VBS

You can do this:

fso.CopyFile "C:\Minecraft\options.txt", "H:\Minecraft\.minecraft\options.txt"

Include the filename in the folder that you copy to.

Build error: You must add a reference to System.Runtime

i added System.Runtime.dll to bin project and it worked :)

Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio

That is just in SDK 23, Httpclient and others are deprecated. You can correct it by changing the target SDK version like below:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "vahid.hoseini.com.testclient"
        minSdkVersion 10
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }

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

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.1.1'
}

Python Linked List

I based this additional function on Nick Stinemates

def add_node_at_end(self, data):
    new_node = Node()
    node = self.curr_node
    while node:
        if node.next == None:
            node.next = new_node
            new_node.next = None
            new_node.data = data
        node = node.next

The method he has adds the new node at the beginning while I have seen a lot of implementations which usually add a new node at the end but whatever, it is fun to do.

"Uncaught Error: [$injector:unpr]" with angular after deployment

Add the $http, $scope services in the controller fucntion, sometimes if they are missing these errors occur.

HTML <select> selected option background-color CSS style

This syntax will work in XHTML and does not work in IE6, but this is a non-javascript way:

option[selected] { background: #f00; }

If you want to do this on-the-fly, then you would have to go with javascript, the way others have suggested....

WHERE IS NULL, IS NOT NULL or NO WHERE clause depending on SQL Server parameter value

This is how it can be done using CASE:

DECLARE @myParam INT;
SET @myParam = 1;

SELECT * 
  FROM MyTable
 WHERE 'T' = CASE @myParam
             WHEN 1 THEN 
                CASE WHEN MyColumn IS NULL THEN 'T' END
             WHEN 2 THEN
                CASE WHEN MyColumn IS NOT NULL THEN 'T' END
             WHEN 3 THEN 'T' END;

mysqli or PDO - what are the pros and cons?

I've started using PDO because the statement support is better, in my opinion. I'm using an ActiveRecord-esque data-access layer, and it's much easier to implement dynamically generated statements. MySQLi's parameter binding must be done in a single function/method call, so if you don't know until runtime how many parameters you'd like to bind, you're forced to use call_user_func_array() (I believe that's the right function name) for selects. And forget about simple dynamic result binding.

Most of all, I like PDO because it's a very reasonable level of abstraction. It's easy to use it in completely abstracted systems where you don't want to write SQL, but it also makes it easy to use a more optimized, pure query type of system, or to mix-and-match the two.

Resize svg when window is resized in d3.js

In force layouts simply setting the 'height' and 'width' attributes will not work to re-center/move the plot into the svg container. However, there's a very simple answer that works for Force Layouts found here. In summary:

Use same (any) eventing you like.

window.on('resize', resize);

Then assuming you have svg & force variables:

var svg = /* D3 Code */;
var force = /* D3 Code */;    

function resize(e){
    // get width/height with container selector (body also works)
    // or use other method of calculating desired values
    var width = $('#myselector').width(); 
    var height = $('#myselector').height(); 

    // set attrs and 'resume' force 
    svg.attr('width', width);
    svg.attr('height', height);
    force.size([width, height]).resume();
}

In this way, you don't re-render the graph entirely, we set the attributes and d3 re-calculates things as necessary. This at least works when you use a point of gravity. I'm not sure if that's a prerequisite for this solution. Can anyone confirm or deny ?

Cheers, g

Clearing Magento Log Data

This script is neat and tidy. Set it up as a cron job and relax:

http://www.crucialwebhost.com/kb/magneto-log-and-cache-maintenance-script/

Objective C - Assign, Copy, Retain

NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"First",@"Second", nil];
NSMutableArray *copiedArray = [array mutableCopy];
NSMutableArray *retainedArray = [array retain];

[retainedArray addObject:@"Retained Third"];
[copiedArray addObject:@"Copied Third"];

NSLog(@"array = %@",array);
NSLog(@"Retained Array = %@",retainedArray);
NSLog(@"Copied Array = %@",copiedArray);

array = (
    First,
    Second,
    "Retained Third"
)
Retained Array = (
    First,
    Second,
    "Retained Third"
)
Copied Array = (
    First,
    Second,
    "Copied Third"
)

Converting a factor to numeric without losing information R (as.numeric() doesn't seem to work)

First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.

For example,

> z <- factor(letters[c(3, 2, 3, 4)])

# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d

# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"

here, z has 4 elements.
The index is 2, 1, 2, 3 in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.

Then, as.numeric converts simply the index part of factor into numeric.
as.character handles the index and levels, and generates character vector expressed by its level.

?as.numeric says that Factors are handled by the default method.

async/await - when to return a Task vs void?

According to Microsoft documentation, should NEVER use async void

Do not do this: The following example uses async void which makes the HTTP request complete when the first await is reached:

  • Which is ALWAYS a bad practice in ASP.NET Core apps.

  • Accesses the HttpResponse after the HTTP request is complete.

  • Crashes the process.

Regular expression to match balanced parentheses

I was also stuck in this situation where nested patterns comes.

Regular Expression is right thing to solve the above problem. Use below pattern

'/(\((?>[^()]+|(?1))*\))/'

In Postgresql, force unique on combination of two columns

Create unique constraint that two numbers together CANNOT together be repeated:

ALTER TABLE someTable
ADD UNIQUE (col1, col2)

How create a new deep copy (clone) of a List<T>?

public static class Cloner
{
    public static T Clone<T>(this T item)
    {
        FieldInfo[] fis = item.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
        object tempMyClass = Activator.CreateInstance(item.GetType());
        foreach (FieldInfo fi in fis)
        {
            if (fi.FieldType.Namespace != item.GetType().Namespace)
                fi.SetValue(tempMyClass, fi.GetValue(item));
            else
            {
                object obj = fi.GetValue(item);
                if (obj != null)
                    fi.SetValue(tempMyClass, obj.Clone());
            }
        }
        return (T)tempMyClass;
    }
}

Typescript: Type 'string | undefined' is not assignable to type 'string'

As of TypeScript 3.7 you can use nullish coalescing operator ??. You can think of this feature as a way to “fall back” to a default value when dealing with null or undefined

let name1:string = person.name ?? '';

The ?? operator can replace uses of || when trying to use a default value and can be used when dealing with booleans, numbers, etc. where || cannot be used.

As of TypeScript 4 you can use ??= assignment operator as a ??= b which is an alternative to a = a ?? b;

One DbContext per web request... why?

I agree with previous opinions. It is good to say, that if you are going to share DbContext in single thread app, you'll need more memory. For example my web application on Azure (one extra small instance) needs another 150 MB of memory and I have about 30 users per hour. Application sharing DBContext in HTTP Request

Here is real example image: application have been deployed in 12PM

What are the differences and similarities between ffmpeg, libav, and avconv?

Confusing messages

These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".

The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.

The real ffmpeg vs the fake one

For a while both Libav and FFmpeg separately developed their own version of ffmpeg.

Libav then renamed their bizarro ffmpeg to avconv to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv instead of their counterfeit version of ffmpeg. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.

This message was removed upstream when the fake "ffmpeg" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.

In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1. Unfortunately the new "deprecated" message has caused additional user confusion.

Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg is back in the repositories again.

libav vs Libav

To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.

How to tell the difference

If you are using avconv then you are using Libav. If you are using ffmpeg you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.

Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg or avconv and viewing the console output.

If you want to use the real ffmpeg

Ubuntu 15.04 "Vivid Vervet" or newer

The real ffmpeg is in the repository, so you can install it with:

apt-get install ffmpeg

For older Ubuntu versions

Your options are:

These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.

Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg from the repository.

Also see

For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.

gdb fails with "Unable to find Mach task port for process-id" error

Here is a really useful guide which solved my problem(OSX 10.13.6).

  1. Open Keychain Access
  2. In the menu, open Keychain Access > Certificate Assistant > Create a certificate
  3. Give it a name (e.g. gdbc)
    • Identity type: Self Signed Root
    • Certificate type: Code Signing
    • Check: let me override defaults
  4. Continue until it prompts you for: "specify a location for..."
  5. Set Keychain location to System
  6. Create a certificate and close assistant.
  7. Find the certificate in System keychains, right click it > get info (or just double click it)
  8. Expand Trust, set Code signing to always trust
  9. Restart taskgated in terminal: killall taskgated
  10. Run codesign -fs gdbc /usr/local/bin/gdb in terminal: this asks for the root password

'do...while' vs. 'while'

The answers so far summarize the general use for do-while. But the OP asked for an example, so here is one: Get user input. But the user's input may be invalid - so you ask for input, validate it, proceed if it's valid, otherwise repeat.

With do-while, you get the input while the input is not valid. With a regular while-loop, you get the input once, but if it's invalid, you get it again and again until it is valid. It's not hard to see that the former is shorter, more elegant, and simpler to maintain if the body of the loop grows more complex.

Is there a no-duplicate List implementation out there?

in add method, why not using HashSet.add() to check duplicates instead of HashSet.consist(). HashSet.add() will return true if no duplicate and false otherwise.

Append column to pandas dataframe

Just as a matter of fact:

data_joined = dat1.join(dat2)
print(data_joined)

How do you detect where two line segments intersect?

Plenty of solutions are available above, but I think below solution is pretty simple and easy to understand.

Two segments Vector AB and Vector CD intersect if and only if

  1. The endpoints a and b are on opposite sides of the segment CD.
  2. The endpoints c and d are on opposite side of the segment AB.

More specifically a and b are on opposite side of segment CD if and only if exactly one of the two triples a,c,d and b,c,d is in counterclockwise order.

Intersect(a, b, c, d)
 if CCW(a, c, d) == CCW(b, c, d)
    return false;
 else if CCW(a, b, c) == CCW(a, b, d)
    return false;
 else
    return true;

Here CCW represent counterclockwise which returns true/false based on the orientation of the points.

Source : http://compgeom.cs.uiuc.edu/~jeffe/teaching/373/notes/x06-sweepline.pdf Page 2

java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

Two possible answers:

1- You did not include spring-beans and spring-context jars in your lib. If you are using maven (which will help a lot) those two lines will be enough

<dependency>
 <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
   <version>3.1.0.RELEASE</version>
</dependency>
<dependency>
 <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
   <version>3.1.0.RELEASE</version>
</dependency>

2- The necessary jars are in your classpath but are not deployed on tomcat.

SQL Server equivalent of MySQL's NOW()?

getdate() 

is the direct equivalent, but you should always use UTC datetimes

getutcdate()

whether your app operates across timezones or not - otherwise you run the risk of screwing up date math at the spring/fall transitions

WPF chart controls

The chart control in the WPF Toolkit has a horrible bug: it never forgets any of the data points. So if you try to implement a floating chart you will get out of memory after round about 3000 DataPoint-objects. This bug has been reported to MS over a year ago but nobody seems to care...

Adding a new value to an existing ENUM Type

I don't know if have other option but we can drop the value using:

select oid from pg_type where typname = 'fase';'
select * from pg_enum where enumtypid = 24773;'
select * from pg_enum where enumtypid = 24773 and enumsortorder = 6;
delete from pg_enum where enumtypid = 24773 and enumsortorder = 6;

Using fonts with Rails asset pipeline

  1. If your Rails version is between > 3.1.0 and < 4, place your fonts in any of the these folders:

    • app/assets/fonts
    • lib/assets/fonts
    • vendor/assets/fonts


    For Rails versions > 4, you must place your fonts in the app/assets/fonts folder.

    Note: To place fonts outside of these designated folders, use the following configuration:

    config.assets.precompile << /\.(?:svg|eot|woff|ttf)\z/

    For Rails versions > 4.2, it is recommended to add this configuration to config/initializers/assets.rb.

    However, you can also add it to either config/application.rb , or to config/production.rb

  2. Declare your font in your CSS file:

    @font-face {
      font-family: 'Icomoon';
      src:url('icomoon.eot');
      src:url('icomoon.eot?#iefix') format('embedded-opentype'),
        url('icomoon.svg#icomoon') format('svg'),
        url('icomoon.woff') format('woff'),
        url('icomoon.ttf') format('truetype');
      font-weight: normal;
      font-style: normal;
    }
    

    Make sure your font is named exactly the same as in the URL portion of the declaration. Capital letters and punctuation marks matter. In this case, the font should have the name icomoon.

  3. If you are using Sass or Less with Rails > 3.1.0 (your CSS file has .scss or .less extension), then change the url(...) in the font declaration to font-url(...).

    Otherwise, your CSS file should have the extension .css.erb, and the font declaration should be url('<%= asset_path(...) %>').

    If you are using Rails > 3.2.1, you can use font_path(...) instead of asset_path(...). This helper does exactly the same thing but it's more clear.

  4. Finally, use your font in your CSS like you declared it in the font-family part. If it was declared capitalized, you can use it like this:

    font-family: 'Icomoon';
    

How do I install cURL on Windows?

Use the following steps to install curl:

  1. Open https://curl.haxx.se/dlwiz?type=bin in a browser.

  2. Select your operating system in the dropdown box: either Windows /Win32 or Win 64. Click Select!

  3. For Win 32, choose whether you will use curl in a Windows Command Prompt (Generic) or in a Cygwin terminal (cygwin). For Win 64, choose whether you will use curl in a Windows Command Prompt (Generic) or MinGW (MinGW64). Click Select!

  4. If required, choose your Windows operating system. Finish.

  5. Click Download for the version which has SSL enabled or disabled

  6. Open the downloaded zip file. Extract the files to an easy-to-find place, such as C:\Program Files.

Testing curl

  1. Open up the Windows Command Prompt terminal. (From the Start menu, click Run, then type cmd.)

  2. Set the path to include the directory where you put curl.exe. For example, if you put it in C:\Program Files\curl, then you would type the following command: set path=%path%;"c:\Program Files\curl"

NOTE: You can also directly copy the curl.exe file any existing path in your path

  1. Type curl. You should see the following message: curl: try 'curl –help' or 'curl –message' for more information This means that curl is installed and the path is correct.

Creating a new user and password with Ansible

I have created an ansible-playbook that allows you to create a linux account that allows password authentication.

See CreateLinuxAccountWithAnsible.

The hashed password is generated using mkpasswd command. I've provided the ways to install mkpasswd on different operating systems.

Here are the steps required to use my script:

  1. Replace <your_user_name> and <your_password> inside run.sh with your desired user name and password.

  2. Change the connection information in inventory so that ansible can connect to the machine to create a user.

  3. Run ./run.sh to execute the script.

Blocking device rotation on mobile web pages

With the new CSS3 features, you could rotate the page the opposite orientation that they rotated. Sorry, no IE7- support. :(.

var rotate = 0 - window.orientation;
setAttribute("transform:rotate("+rotate+"deg);-ms-transform:rotate("+rotate+"deg);-webkit-transform:rotate("+rotate+"deg)", "style");

How can I add a vertical scrollbar to my div automatically?

I got an amazing scroller on my div-popup. To apply, add this style to your div element:

overflow-y: scroll;
height: XXXpx;

The height you specify will be the height of the div and once if you have contents to exceed this height, you have to scroll it.

Thank you.

How to fix Error: this class is not key value coding-compliant for the key tableView.'

Any chance that you changed the name of your table view from "tableView" to "myTableView" at some point?

How can I make an entire HTML form "readonly"?

This is an ideal solution for disabling all inputs, textareas, selects and buttons in a specified element.

For jQuery 1.6 and above:

// To fully disable elements
$('#myForm :input').prop('disabled', true); 

Or

// To make elements readonly
$('#myForm :input').prop('readonly', true); 

jQuery 1.5 and below:

$('#myForm :input').prop('disabled', 'disabled');

And

$('#myForm :input').prop('readonly', 'readonly');

jsPDF multi page PDF with HTML renderer

Below is my code but the problem is that the document doesn't split to display the other part of the document in a new page.

Please improve this code.

<script type='text/javascript'>
$(document).on("click", "#btnExportToPDF", function () {
    var table1 =
    tableToJson($('#table1')[0]),
    cellWidth =42,
    rowCount = 0,
    cellContents,
    leftMargin = 2,
    topMargin = 12,
    topMarginTable =5,
    headerRowHeight = 13,
    rowHeight = 12,
    l = {
        orientation: 'p',
        unit: 'mm',
        format: 'a3',
        compress: true,
        fontSize: 11,
        lineHeight: 1,
        autoSize: false,
        printHeaders: true
    };

    var doc = new jsPDF(l,'pt', 'letter');

    doc.setProperties({
        title: 'Test PDF Document',
        subject: 'This is the subject',
        author: 'author',
        keywords: 'generated, javascript, web 2.0, ajax',
        creator: 'author'
    });
    doc.cellInitialize();

    $.each(table1, function (i, row)
    {
        rowCount++;

        $.each(row, function (j, cellContent) {

            if (rowCount == 1) {
                doc.margins = 1;
                doc.setFont("Times New Roman");
                doc.setFontType("bold");
                doc.setFontSize(11);

                doc.cell(leftMargin, topMargin, cellWidth, headerRowHeight, cellContent, i)
            }
            else if (rowCount == 2) {

                doc.margins = 1;
                doc.setFont("Times ");
                doc.setFontType("normal");
                // or for normal font type use ------ doc.setFontType("normal");

                doc.setFontSize(11);

                doc.cell(leftMargin, topMargin, cellWidth, rowHeight, cellContent, i);
            }
            else {

                doc.margins = 1;
                doc.setFont("Times  ");
                doc.setFontType("normal ");
                doc.setFontSize(11);
                doc.cell(leftMargin, topMargin, cellWidth, rowHeight, cellContent, i);
                // 1st=left margin    2nd parameter=top margin,     3rd=row cell width      4th=Row height
            }
        })
    })
    doc.save('sample Report.pdf');
});

function tableToJson(table) {

    var data = [];

    // first row needs to be headers
    var headers = [];

    for (var i=0; i<table.rows[0].cells.length; i++) {
        headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
    }

    // go through cells
    for (var i=1; i<table.rows.length; i++) {

        var tableRow = table.rows[i];

        var rowData = {};

        for (var j=0; j<tableRow.cells.length; j++) {
            rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
        }

        data.push(rowData);
    }

    return data;
}
</script>

jQuery - Disable Form Fields

$('input, select').attr('disabled', 'disabled');

Error: JavaFX runtime components are missing, and are required to run this application with JDK 11

This worked for me:

File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)

clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.

Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.

then in:

Run >> Edit Configurations

Add this line to VM Options:

--module-path /path/to/JavaFX/lib --add-modules=javafx.controls

(oh and don't forget to set the SDK)

How can I get session id in php and show it?

In the PHP file first you need to register the session

 <? session_start();
     $_SESSION['id'] = $userData['user_id'];?>

And in each page of your php application you can retrive the session id

 <? session_start()
    id =  $_SESSION['id'];
   ?>

Getting an error "fopen': This function or variable may be unsafe." when compling

This is a warning for usual. You can either disable it by

#pragma warning(disable:4996)

or simply use fopen_s like Microsoft has intended.

But be sure to use the pragma before other headers.

How to distinguish mouse "click" and "drag"

You could do this:

_x000D_
_x000D_
var div = document.getElementById("div");
div.addEventListener("mousedown", function() {
  window.addEventListener("mousemove", drag);
  window.addEventListener("mouseup", lift);
  var didDrag = false;
  function drag() {
    //when the person drags their mouse while holding the mouse button down
    didDrag = true;
    div.innerHTML = "drag"
  }
  function lift() {
    //when the person lifts mouse
    if (!didDrag) {
      //if the person didn't drag
      div.innerHTML = "click";
    } else div.innerHTML = "drag";
    //delete event listeners so that it doesn't keep saying drag
    window.removeEventListener("mousemove", drag)
    window.removeEventListener("mouseup", this)
  }
})
_x000D_
body {
  outline: none;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-family: Arial, Helvetica, sans-serif;
  overflow: hidden;
}
#div {
  /* calculating -5px for each side of border in case border-box doesn't work */
  width: calc(100vw - 10px);
  height: calc(100vh - 10px);
  border: 5px solid orange;
  background-color: yellow;
  font-weight: 700;
  display: grid;
  place-items: center;
  user-select: none;
  cursor: pointer;
  padding: 0;
  margin: 0;
}
_x000D_
<html>
  <body>
    <div id="div">Click me or drag me.</div>
  </body>
</html>
_x000D_
_x000D_
_x000D_

What's the difference between ViewData and ViewBag?

Although you might not have a technical advantage to choosing one format over the other, you should be aware of some important differences between the two syntaxes. One obvious difference is that ViewBag works only when the key you’re accessing is a valid C# identifi er. For example, if you place a value in ViewData["Key With Spaces"], you can’t access that value using ViewBag because the code won’t compile. Another key issue to consider is that you cannot pass in dynamic values as parameters to extension methods. The C# compiler must know the real type of every parameter at compile time in order to choose the correct extension method. If any parameter is dynamic, compilation will fail. For example, this code will always fail: @Html.TextBox("name", ViewBag.Name). To work around this, either use ViewData["Name"] or cast the va

Using partial views in ASP.net MVC 4

Change the code where you load the partial view to:

@Html.Partial("_CreateNote", new QuickNotes.Models.Note())

This is because the partial view is expecting a Note but is getting passed the model of the parent view which is the IEnumerable

Unable to install boto3

Don't use sudo in a virtual environment because it ignores the environment's variables and therefore sudo pip refers to your global pip installation.

So with your environment activated, rerun pip install boto3 but without sudo.

How to add an Android Studio project to GitHub

First of all, create a Github account and project in Github. Go to the root folder and follow steps.

The most important thing we forgot here is ignoring the file. Every time we run Gradle or build it creates new files that are changeable from build to build and pc to pc. We do not want all the files from Android Studio to be added to Git. Files like generated code, binary files (executables) should not be added to Git (version control). So please use .gitignore file while uploading projects to Github. It also reduces the size of the project uploaded to the server.

  1. Go to root folder.
  2. git init
  3. Create .gitignore txt file in root folder. Place these content in the file. (this step not required if the file is auto-generated)

    *.iml .gradle /local.properties /.idea/workspace.xml /.idea/libraries .idea .DS_Store /build /captures .externalNativeBuild

  4. git add .
  5. git remote add origin https://github.com/username/project.git
  6. git commit - m "My First Commit"
  7. git push -u origin master

Note : As per suggestion from different developers, they always suggest to use git from the command line. It is up to you.

How to make popup look at the centre of the screen?

If the effect you want is to center in the center of the screen no matter where you've scrolled to, it's even simpler than that:

In your CSS use (for example)

div.centered{
  width: 100px;
  height: 50px;
  position:fixed; 
  top: calc(50% - 25px); // half of width
  left: calc(50% - 50px); // half of height
}

No JS required.

Remove an entire column from a data.frame in R

There are several options for removing one or more columns with dplyr::select() and some helper functions. The helper functions can be useful because some do not require naming all the specific columns to be dropped. Note that to drop columns using select() you need to use a leading - to negate the column names.

Using the dplyr::starwars sample data for some variety in column names:

library(dplyr)

starwars %>% 
  select(-height) %>%                  # a specific column name
  select(-one_of('mass', 'films')) %>% # any columns named in one_of()
  select(-(name:hair_color)) %>%       # the range of columns from 'name' to 'hair_color'
  select(-contains('color')) %>%       # any column name that contains 'color'
  select(-starts_with('bi')) %>%       # any column name that starts with 'bi'
  select(-ends_with('er')) %>%         # any column name that ends with 'er'
  select(-matches('^v.+s$')) %>%       # any column name matching the regex pattern
  select_if(~!is.list(.)) %>%          # not by column name but by data type
  head(2)

# A tibble: 2 x 2
homeworld species
  <chr>     <chr>  
1 Tatooine  Human  
2 Tatooine  Droid 

You can also drop by column number:

starwars %>% 
  select(-2, -(4:10)) # column 2 and columns 4 through 10

How to check if a string array contains one string in JavaScript?

You can use the indexOfmethod and "extend" the Array class with the method contains like this:

Array.prototype.contains = function(element){
    return this.indexOf(element) > -1;
};

with the following results:

["A", "B", "C"].contains("A") equals true

["A", "B", "C"].contains("D") equals false

How to copy a row from one SQL Server table to another

As long as there are no identity columns you can just

INSERT INTO TableNew
SELECT * FROM TableOld
WHERE [Conditions]

Differences between socket.io and websockets

Socket.IO uses WebSocket and when WebSocket is not available uses fallback algo to make real time connections.

CSS background-image - What is the correct usage?

you really don't need quotes if let say use are using the image from your css file it can be

{background-image: url(your image.png/jpg etc);}

Encrypt and Decrypt in Java

Here is a sample I made a couple of months ago The class encrypt and decrypt data

import java.security.*;
import java.security.spec.*;

import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;

public class TestEncryptDecrypt {

private final String ALGO = "DES";
private final String MODE = "ECB";
private final String PADDING = "PKCS5Padding";
private static int mode = 0;

public static void main(String args[]) {
    TestEncryptDecrypt me = new TestEncryptDecrypt();
    if(args.length == 0) mode = 2;
    else mode = Integer.parseInt(args[0]);
    switch (mode) {
    case 0:
        me.encrypt();
        break;
    case 1:
        me.decrypt();
        break;
    default:
        me.encrypt();
        me.decrypt();
    }
}

public void encrypt() {
try {
    System.out.println("Start encryption ...");

    /* Get Input Data */
    String input = getInputData();
    System.out.println("Input data : "+input);

    /* Create Secret Key */
    KeyGenerator keyGen = KeyGenerator.getInstance(ALGO);
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
    keyGen.init(56,random);
      Key sharedKey = keyGen.generateKey();

    /* Create the Cipher and init it with the secret key */
    Cipher c = Cipher.getInstance(ALGO+"/"+MODE+"/"+PADDING);
    //System.out.println("\n" + c.getProvider().getInfo());
    c.init(Cipher.ENCRYPT_MODE,sharedKey);
    byte[] ciphertext = c.doFinal(input.getBytes());
    System.out.println("Input Encrypted : "+new String(ciphertext,"UTF8"));

    /* Save key to a file */
    save(sharedKey.getEncoded(),"shared.key");

    /* Save encrypted data to a file */
    save(ciphertext,"encrypted.txt");
} catch (Exception e) {
    e.printStackTrace();
}   
}

public void decrypt() {
try {
    System.out.println("Start decryption ...");

    /* Get encoded shared key from file*/
    byte[] encoded = load("shared.key");
      SecretKeyFactory kf = SecretKeyFactory.getInstance(ALGO);
    KeySpec ks = new DESKeySpec(encoded);
    SecretKey ky = kf.generateSecret(ks);

    /* Get encoded data */
    byte[] ciphertext = load("encrypted.txt");
    System.out.println("Encoded data = " + new String(ciphertext,"UTF8"));

    /* Create a Cipher object and initialize it with the secret key */
    Cipher c = Cipher.getInstance(ALGO+"/"+MODE+"/"+PADDING);
    c.init(Cipher.DECRYPT_MODE,ky);

    /* Update and decrypt */
    byte[] plainText = c.doFinal(ciphertext);
    System.out.println("Plain Text : "+new String(plainText,"UTF8"));
} catch (Exception e) {
    e.printStackTrace();
}   
}

private String getInputData() {
    String id = "owner.id=...";
    String name = "owner.name=...";
    String contact = "owner.contact=...";
    String tel = "owner.tel=...";
    final String rc = System.getProperty("line.separator");
    StringBuffer buf = new StringBuffer();
    buf.append(id);
    buf.append(rc);
    buf.append(name);
    buf.append(rc);
    buf.append(contact);
    buf.append(rc);
    buf.append(tel);
    return buf.toString();
}


private void save(byte[] buf, String file) throws IOException {
      FileOutputStream fos = new FileOutputStream(file);
      fos.write(buf);
      fos.close();
}

private byte[] load(String file) throws FileNotFoundException, IOException {
    FileInputStream fis = new FileInputStream(file);
    byte[] buf = new byte[fis.available()];
    fis.read(buf);
    fis.close();
    return buf;
}
}

Finding an element in an array in Java

With Java 8, you can do this:

int[] haystack = {1, 2, 3};
int needle = 3;

boolean found = Arrays.stream(haystack).anyMatch(x -> x == needle);

You'd need to do

boolean found = Arrays.stream(haystack).anyMatch(x -> needle.equals(x));

if you're working with objects.

Hot deploy on JBoss - how do I make JBoss "see" the change?

I have had the same problem, but think I've got it under control now.

Are you using eclipse or command line or ??

When I use the command line, I think I did "seam clean" or "seam undeploy" or maybe even "seam restart" followed by "seam explode". I probably tried all of these at one time or another never bothering to look up what each one does.

The idea is to remove the deployed war file from TWO places

1. $JBOSS_HOME/server/default/deploy
2. $PROJECT_HOME/exploded_archives

I'm pretty sure "seam undeploy" removes the 1st and "seam clean" removes the 2nd.

When I use eclipse (I use the free one), I first turn off "Project/Build Automatically" Then when I am ready to deploy I do either Project/Build Project or Project/Build All depending on what I've changed. When I change xhtml, Build Project is sufficient. When I change java source Build All works. It's possible these do the same things and the difference is in my imagination, but some combination of this stuff will work for you.

You have to watch the output though. Occasionally the app does not get cleaned or undeployed. This would result in not seeing your change. Sometimes I shut down the server first and then rebuild/clean/deploy the project.

Hope this helps.

TDR

How to clean up R memory (without the need to restart my PC)?

I came under the same problem with R. I dig a bit and come with a solution, that we need to restart R session to fully clean the memory/RAM. For this, you can use a simple code after removing everything from your workspace. the code is as follows :

rm(list = ls())

.rs.restartR()

How to get $(this) selected option in jQuery?

It's just

$(this).val();

I think jQuery is clever enough to know what you need

Token Authentication vs. Cookies

One of the primary differences is that cookies are subject to Same Origin Policy whereas tokens are not. This creates all kinds of down stream effects.

Since cookies are only sent to and from a particular host that host must bear the burden of authenticating the user and the user must create an account with security data with that host in order to be verifiable.

Tokens on the other hand are issued and are not subject to same origin policy. The issuer can be literally anybody and it is up to the host to decide which issuers to trust. An issuer like Google and Facebook is typically well trusted so a host can shift the burden of authenticating the user (including storing all user security data) to another party and the user can consolidate their personal data under a specific issuer and not have to remember a bunch of different passwords for each host they interact with.

This allows for single sign on scenarios that reduce overall friction in the user experience. In theory the web also becomes more secure as specialised identity providers emerge to provide auth services instead of having every ma and pa website spinning up their own, likely half baked, auth systems. And as these providers emerge the cost of providing secure web resources for even very basic resources trends towards zero.

So in general tokens reduce the friction and costs associated with providing authentication and shifts the burden of the various aspects of a secure web to centralised parties better able to both implement and maintain security systems.

HashSet vs. List performance

Depends on a lot of factors... List implementation, CPU architecture, JVM, loop semantics, complexity of equals method, etc... By the time the list gets big enough to effectively benchmark (1000+ elements), Hash-based binary lookups beat linear searches hands-down, and the difference only scales up from there.

Hope this helps!

How to write a file with C in Linux?

You need to write() the read() data into the new file:

ssize_t nrd;
int fd;
int fd1;

fd = open(aa[1], O_RDONLY);
fd1 = open(aa[2], O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
while (nrd = read(fd,buffer,50)) {
    write(fd1,buffer,nrd);
}

close(fd);
close(fd1);

Update: added the proper opens...

Btw, the O_CREAT can be OR'd (O_CREAT | O_WRONLY). You are actually opening too many file handles. Just do the open once.

Sending E-mail using C#

You could use the System.Net.Mail.MailMessage class of the .NET framework.

You can find the MSDN documentation here.

Here is a simple example (code snippet):

using System.Net;
using System.Net.Mail;
using System.Net.Mime;

...
try
{

   SmtpClient mySmtpClient = new SmtpClient("my.smtp.exampleserver.net");

    // set smtp-client with basicAuthentication
    mySmtpClient.UseDefaultCredentials = false;
   System.Net.NetworkCredential basicAuthenticationInfo = new
      System.Net.NetworkCredential("username", "password");
   mySmtpClient.Credentials = basicAuthenticationInfo;

   // add from,to mailaddresses
   MailAddress from = new MailAddress("[email protected]", "TestFromName");
   MailAddress to = new MailAddress("[email protected]", "TestToName");
   MailMessage myMail = new System.Net.Mail.MailMessage(from, to);

   // add ReplyTo
   MailAddress replyTo = new MailAddress("[email protected]");
   myMail.ReplyToList.Add(replyTo);

   // set subject and encoding
   myMail.Subject = "Test message";
   myMail.SubjectEncoding = System.Text.Encoding.UTF8;

   // set body-message and encoding
   myMail.Body = "<b>Test Mail</b><br>using <b>HTML</b>.";
   myMail.BodyEncoding = System.Text.Encoding.UTF8;
   // text or html
   myMail.IsBodyHtml = true;

   mySmtpClient.Send(myMail);
}

catch (SmtpException ex)
{
  throw new ApplicationException
    ("SmtpException has occured: " + ex.Message);
}
catch (Exception ex)
{
   throw ex;
}

Best way to track onchange as-you-type in input type="text"?

onkeyup happens after you type for example I press t when I lift the finger the action happens but on keydown the action happens before I digit the character t

Hope this is helpful for someone.

So onkeyup is better for when you want to send what you just typed now.

Java 8 LocalDate Jackson format

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime createdDate;

How to convert a String to Bytearray

The best solution I've come up with at on the spot (though most likely crude) would be:

String.prototype.getBytes = function() {
    var bytes = [];
    for (var i = 0; i < this.length; i++) {
        var charCode = this.charCodeAt(i);
        var cLen = Math.ceil(Math.log(charCode)/Math.log(256));
        for (var j = 0; j < cLen; j++) {
            bytes.push((charCode << (j*8)) & 0xFF);
        }
    }
    return bytes;
}

Though I notice this question has been here for over a year.

Python equivalent for HashMap

You need a dict:

my_dict = {'cheese': 'cake'}

Example code (from the docs):

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

You can read more about dictionaries here.

ggplot combining two plots from different data.frames

As Baptiste said, you need to specify the data argument at the geom level. Either

#df1 is the default dataset for all geoms
(plot1 <- ggplot(df1, aes(v, p)) + 
    geom_point() +
    geom_step(data = df2)
)

or

#No default; data explicitly specified for each geom
(plot2 <- ggplot(NULL, aes(v, p)) + 
      geom_point(data = df1) +
      geom_step(data = df2)
)

How to remove undefined and null values from an object using lodash?

I encountered a similar problem with removing undefined from an object (deeply), and found that if you are OK to convert your plain old object and use JSON, a quick and dirty helper function would look like this:

function stripUndefined(obj) {
  return JSON.parse(JSON.stringify(obj));
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description

"...If undefined, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array)."

How to open select file dialog via js?

To expand on the answer from 'levi' and to show how to get the response from the upload so you can process the file upload:

selectFile(event) {
    event.preventDefault();

    file_input = document.createElement('input');
    file_input.addEventListener("change", uploadFile, false);
    file_input.type = 'file';
    file_input.click();
},

uploadFile() {
    let dataArray = new FormData();
    dataArray.append('file', file_input.files[0]);

    // Obviously, you can substitute with JQuery or whatever
    axios.post('/your_super_special_url', dataArray).then(function() {
        //
    });
}

JQuery datepicker not working

Datepicker is not part of jQuery. You have to get jQuery UI to use the datepicker.

What exactly is Spring Framework for?

Old days, Spring was a dependency injection frame work only like (Guice, PicoContainer,...), but nowadays it is a total solution for building your Enterprise Application.

The spring dependency injection, which is, of course, the heart of spring is still there (and you can review other good answers here), but there are more from spring...

Spring now has lots of projects, each with some sub-projects (http://spring.io/projects). When someone speaks about spring, you must find out what spring project he is talking about, is it only spring core, which is known as spring framework, or it is another spring projects.

Some spring projects which is worth too mention are:

If you need some more specify feature for your application, you may find it there too:

  • Spring Batch batch framework designed to enable the development of
    batch application
  • Spring HATEOAS easy creation of REST API based on HATEOAS principal
  • Spring Mobile and Spring Andriod for mobile application development
  • Spring Shell builds a full-featured shell ( aka command line) application
  • Spring Cloud and Spring Cloud Data Flow for cloud applications

There are also some tiny projects there for example spring-social-facebook (http://projects.spring.io/spring-social-facebook/)

You can use spring for web development as it has the Spring MVC module which is part of Spring Framework project. Or you can use spring with another web framework, like struts2.

What is meant by the term "hook" in programming?

In VERY short, you can change the code of an API call such as MessageBox to where it does a different function edited by you (globally will work system wide, locally will work process wide).

jQuery detect if textarea is empty

if (!$("#myTextArea").val()) {
    // textarea is empty
}

You can also use $.trim to make sure the element doesn't contain only white-space:

if (!$.trim($("#myTextArea").val())) {
    // textarea is empty or contains only white-space
}

How to change the background color of Action Bar's Option Menu in Android 4.2?

FAST way!

styles.xml

<style name="popupTheme" parent="Theme.AppCompat.Light">

    <item name="android:background">@color/colorBackground</item>
    <item name="android:textColor">@color/colorItem</item>

</style>

Then add this specific styles to your AppTheme styles

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    ...
    <item name="popupTheme">@style/popupTheme</item>
</style>

DONE!

Can a Byte[] Array be written to a file in C#?

You can use a BinaryWriter object.

protected bool SaveData(string FileName, byte[] Data)
{
    BinaryWriter Writer = null;
    string Name = @"C:\temp\yourfile.name";

    try
    {
        // Create a new stream to write to the file
        Writer = new BinaryWriter(File.OpenWrite(Name));

        // Writer raw data                
        Writer.Write(Data);
        Writer.Flush();
        Writer.Close();
    }
    catch 
    {
        //...
        return false;
    }

    return true;
}

Edit: Oops, forgot the finally part... lets say it is left as an exercise for the reader ;-)

How to install gdb (debugger) in Mac OSX El Capitan?

Just spent a good few days trying to get this to work on High Sierra 10.13.1. The gdb 8.1 version from homebrew would not work no matter what I tried. Ended up installing gdb 8.0.1 via macports and this miraculously worked (after jumping through all of the other necessary hoops related to codesigning etc).

One additional issue is that in Eclipse you will get extraneous single quotes around all of your program arguments which can be worked around by providing the arguments inside .gdbinit instead.

Display all views on oracle database

SELECT * 
FROM DBA_OBJECTS  
WHERE OBJECT_TYPE = 'VIEW'

How to get file name from file path in android

Simple and easy way to get File name

File file = new File("/storage/sdcard0/DCIM/Camera/1414240995236.jpg"); 
String strFileName = file.getName();

After add this code and print strFileName you will get strFileName = 1414240995236.jpg

Run task only if host does not belong to a group

You can set a control variable in vars files located in group_vars/ or directly in hosts file like this:

[vagrant:vars]
test_var=true

[location-1]
192.168.33.10 hostname=apollo

[location-2]
192.168.33.20 hostname=zeus

[vagrant:children]
location-1
location-2

And run tasks like this:

- name: "test"
  command: "echo {{test_var}}"
  when: test_var is defined and test_var

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

jQuery multiple conditions within if statement

i == 'InvKey' && i == 'PostDate' will never be true, since i can never equal two different things at once.

You're probably trying to write

if (i !== 'InvKey' && i !== 'PostDate')) 

How do I create a view controller file after creating a new view controller?

Correct, when you drag a view controller object onto your storyboard in order to create a new scene, it doesn't automatically make the new class for you, too.

Having added a new view controller scene to your storyboard, you then have to:

  1. Create a UIViewController subclass. For example, go to your target's folder in the project navigator panel on the left and then control-click and choose "New File...". Choose a "Cocoa Touch Class":

    Cocoa Touch Class

    And then select a unique name for the new view controller subclass:

    UIViewController subclass

  2. Specify this new subclass as the base class for the scene you just added to the storyboard.

    enter image description here

  3. Now hook up any IBOutlet and IBAction references for this new scene with the new view controller subclass.

How to get value of checked item from CheckedListBox?

Cast it back to its original type, which will be a DataRowView if you're binding a table, and you can then get the Id and Text from the appropriate columns:

foreach(object itemChecked in checkedListBox1.CheckedItems)
{
     DataRowView castedItem = itemChecked as DataRowView;
     string comapnyName = castedItem["CompanyName"];
     int? id = castedItem["ID"];
}

ASP.NET Web API : Correct way to return a 401/unauthorised response

you can use follow code in asp.net core 2.0:

public IActionResult index()
{
     return new ContentResult() { Content = "My error message", StatusCode = (int)HttpStatusCode.Unauthorized };
}

Check if a given key already exists in a dictionary and increment it

You are looking for collections.defaultdict (available for Python 2.5+). This

from collections import defaultdict

my_dict = defaultdict(int)
my_dict[key] += 1

will do what you want.

For regular Python dicts, if there is no value for a given key, you will not get None when accessing the dict -- a KeyError will be raised. So if you want to use a regular dict, instead of your code you would use

if key in my_dict:
    my_dict[key] += 1
else:
    my_dict[key] = 1

How to add lines to end of file on Linux

The easiest way is to redirect the output of the echo by >>:

echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile

How do I get the day month and year from a Windows cmd.exe script?

powershell Set-Date -Da (Get-Date -Y 1980 -Mon 11 -Day 17)

How to Lazy Load div background images

I had to deal with this for my responsive website. I have many different backgrounds for the same elements to deal with different screen widths. My solution is very simple, keep all your images scoped to a css selector, like "zoinked".

The logic:

If user scrolls, then load in styles with background images associated with them. Done!

Here's what I wrote in a library I call "zoinked" I dunno why. It just happened ok?

(function(window, document, undefined) {   var Z = function() {
    this.hasScrolled = false;

    if (window.addEventListener) {
      window.addEventListener("scroll", this, false);
    } else {
      this.load();
    }   };
     Z.prototype.handleEvent = function(e) {
    if ($(window).scrollTop() > 2) {
      this.hasScrolled = true;
      window.removeEventListener("scroll", this);
      this.load();
    }   };
     Z.prototype.load = function() {
    $(document.body).addClass("zoinked");   };
     window.Zoink = Z; 
})(window, document);

For the CSS I'll have all my styles like this:

.zoinked #graphic {background-image: url(large.jpg);}

@media(max-width: 480px) {.zoinked #graphic {background-image: url(small.jpg);}}

My technique with this is to load all the images after the top ones as soon as the user starts to scroll. If you wanted more control you could make the "zoinking" more intelligent.

Play/pause HTML 5 video using JQuery

Found the answer here @ToolmakerSteve, but had to fine tune this way: To pause all

$('video').each(function(index){
    $(this).get(0).pause();
});

or to play all

$('video').each(function(index){
    $(this).get(0).play();
});

How to use template module with different set of variables?

- name: copy vhosts
  template: src=site-vhost.conf dest=/etc/apache2/sites-enabled/{{ item }}.conf
  with_items:
    - somehost.local
    - otherhost.local
  notify: restart apache

IMPORTANT: Note that an item does not have to be just a string, it can be an object with as many properties as you like, so that way you can pass any number of variables.

In the template I have:

<VirtualHost *:80>
    ServerAdmin [email protected]
    ServerName {{ item }}
    DocumentRoot /vagrant/public


    ErrorLog ${APACHE_LOG_DIR}/error-{{ item }}.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

How to make the division of 2 ints produce a float instead of another int?

Try this:

class CalcV 
{
      float v;
      float calcV(int s, int t)
      {
          float value1=s;
          float value2=t;
          v = value1 / value2;
          return v;
      } //end calcV
}

Check if not nil and not empty in Rails shortcut?

You can use .present? which comes included with ActiveSupport.

@city = @user.city.present?
# etc ...

You could even write it like this

def show
  %w(city state bio contact twitter mail).each do |attr|
    instance_variable_set "@#{attr}", @user[attr].present?
  end
end

It's worth noting that if you want to test if something is blank, you can use .blank? (this is the opposite of .present?)

Also, don't use foo == nil. Use foo.nil? instead.

How do I do a case-insensitive string comparison?

How about converting to lowercase first? you can use string.lower().

I lose my data when the container exits

There are really great answers above to the asked question. There might be no need for another answer but still I want to give my personal opinion on the topic in the simplest words possible.

Here are some points about containers & images that will help us for a conclusion:

  • A docker image can be:
    1. created-from-a-given-container
    2. deleted
    3. used-to-create-any-number-of-containers
  • A docker container can be:
    1. created-from-an-image
    2. started
    3. stopped
    4. restarted
    5. deleted
    6. used-to-create-any-number-of-images
  • A docker run command does this:
    1. Downloads an image or uses a cached image
    2. Creates a new container out of it
    3. Starts the container
  • When a Dockerfile is used to create an image:
    1. It is already well known that the image will eventually be used to run a docker container.
    2. After issuing docker build command, docker behind-the-scenes creates a running container with a base-file-system and follows steps inside the Dockerfile to configure that container as per the developers need.
    3. After the container is configured with specs of the Dockerfile, it will be committed as an image.
    4. The image gets ready to rock & roll!

Conclusion:

As we can see, a docker container is independent of a docker image.

A container can be restarted provided the unique ID of that container [use docker ps --all to get the id].

Any operation like making a new directory, creating files, installing tools, etc. can be done inside the container when it is running. Once the container is stopped, it persists all the changes. Container stopping and restarting is like rebooting a computer system.

An already created container is always available for a restart but when we issue docker run command, a new container is created out of an image and hence it is like a new computer system. The changes made inside the old container - as we can understand now - are not available in this new container.

A final note:

I guess it's now obvious why the data seems to be lost yet it is always there.. but in a different [old] container. So, take a good note of the difference in docker start & docker run command & never get confused in them.

How do I use PHP namespaces with autoload?

Your __autoload function will receive the full class-name, including the namespace name.

This means, in your case, the __autoload function will receive 'Person\Barnes\David\Class1', and not only 'Class1'.

So, you have to modify your autoloading code, to deal with that kind of "more-complicated" name ; a solution often used is to organize your files using one level of directory per "level" of namespaces, and, when autoloading, replace '\' in the namespace name by DIRECTORY_SEPARATOR.

height style property doesn't work in div elements

This worked for me:

min-height: 14px;
height: 14px;

Recording video feed from an IP camera over a network

Motion is an alternative to Zoneminder. It has a steeper setup curve as everything is configured via config files.However, the config files are nicely commented and it's easier than it sounds. It's very reliable once running as well.

To add a Foscam camera (mentioned above) use the following syntax to stream the video from the camera.

netcam_url http://<IPADDRESS>/videostream.cgi?user=admin?pwd=

Where the user is admin with a blank password (the default for Foscam cameras).

For really high uptime/reliablity consider using a monitoring tool such as Monit. This works well with Motion.

Can I concatenate multiple MySQL rows into one field?

Alternate syntax to concatenate multiple, individual rows

WARNING: This post will make you hungry.

Given:

I found myself wanting to select multiple, individual rows—instead of a group—and concatenate on a certain field.

Let's say you have a table of product ids and their names and prices:

+------------+--------------------+-------+
| product_id | name               | price |
+------------+--------------------+-------+
|         13 | Double Double      |     5 |
|         14 | Neapolitan Shake   |     2 |
|         15 | Animal Style Fries |     3 |
|         16 | Root Beer          |     2 |
|         17 | Lame T-Shirt       |    15 |
+------------+--------------------+-------+

Then you have some fancy-schmancy ajax that lists these puppies off as checkboxes.

Your hungry-hippo user selects 13, 15, 16. No dessert for her today...

Find:

A way to summarize your user's order in one line, with pure mysql.

Solution:

Use GROUP_CONCAT with the the IN clause:

mysql> SELECT GROUP_CONCAT(name SEPARATOR ' + ') AS order_summary FROM product WHERE product_id IN (13, 15, 16);

Which outputs:

+------------------------------------------------+
| order_summary                                  |
+------------------------------------------------+
| Double Double + Animal Style Fries + Root Beer |
+------------------------------------------------+

Bonus Solution:

If you want the total price too, toss in SUM():

mysql> SELECT GROUP_CONCAT(name SEPARATOR ' + ') AS order_summary, SUM(price) AS total FROM product WHERE product_id IN (13, 15, 16);
+------------------------------------------------+-------+
| order_summary                                  | total |
+------------------------------------------------+-------+
| Double Double + Animal Style Fries + Root Beer |    10 |
+------------------------------------------------+-------+

How can I check the size of a file in a Windows batch script?

I prefer to use a DOS function. Feels cleaner to me.

SET SIZELIMIT=1000
CALL :FileSize %1 FileSize
IF %FileSize% GTR %SIZELIMIT% Echo Large file

GOTO :EOF

:FileSize
SET %~2=%~z1

GOTO :EOF

Uninstall / remove a Homebrew package including all its dependencies

Save the following script as brew-purge

#!/bin/bash
#:Usage: brew purge formula
#: 
#:Removes the package and all dependancies.
#: 
#: 
PKG="$1"
if [ -z "$PKG" ];then
   brew purge --help
   exit 1
fi
brew rm $PKG
[ $? -ne 0 ] && exit 1
while brew rm $(join <(brew leaves) <(brew deps $PKG)) 2>/dev/null
  do :
done
echo Package $PKG and its dependancies have been removed.
exit 0

Now install it with the following command

sudo install brew-purge /usr/local/bin

Now run it

brew purge package

Example using gpg

$ brew purge gpg
Uninstalling /usr/local/Cellar/gnupg/2.2.13... (134 files, 11.0MB)
Uninstalling /usr/local/Cellar/adns/1.5.1... (14 files, 597.5KB)
Uninstalling /usr/local/Cellar/gnutls/3.6.6... (1,200 files, 8.9MB)
Uninstalling /usr/local/Cellar/libgcrypt/1.8.4... (21 files, 2.6MB)
Uninstalling /usr/local/Cellar/libksba/1.3.5... (14 files, 344.2KB)
Uninstalling /usr/local/Cellar/libusb/1.0.22... (29 files, 508KB)
Uninstalling /usr/local/Cellar/npth/1.6... (11 files, 71.7KB)
Uninstalling /usr/local/Cellar/pinentry/1.1.0_1... (12 files, 263.9KB)
Uninstalling /usr/local/Cellar/libassuan/2.5.3... (16 files, 444.2KB)
Uninstalling /usr/local/Cellar/libtasn1/4.13... (59 files, 436KB)
Uninstalling /usr/local/Cellar/libunistring/0.9.10... (54 files, 4.4MB)
Uninstalling /usr/local/Cellar/nettle/3.4.1... (85 files, 2MB)
Uninstalling /usr/local/Cellar/p11-kit/0.23.15... (63 files, 2.9MB)
Uninstalling /usr/local/Cellar/gmp/6.1.2_2... (18 files, 3.1MB)
Uninstalling /usr/local/Cellar/libffi/3.2.1... (16 files, 296.8KB)
Uninstalling /usr/local/Cellar/libgpg-error/1.35... (27 files, 854.8KB)
Package gpg and its dependancies have been removed.
$ 

What does it mean to "call" a function in Python?

To "call" means to make a reference in your code to a function that is written elsewhere. This function "call" can be made to the standard Python library (stuff that comes installed with Python), third-party libraries (stuff other people wrote that you want to use), or your own code (stuff you wrote). For example:

#!/usr/env python

import os

def foo():
    return "hello world"

print os.getlogin()
print foo()

I created a function called "foo" and called it later on with that print statement. I imported the standard "os" Python library then I called the "getlogin" function within that library.

Can I change a column from NOT NULL to NULL without dropping it?

For MYSQL

ALTER TABLE myTable MODIFY myColumn {DataType} NULL

How to Automatically Close Alerts using Twitter Bootstrap

With delay and fade :

setTimeout(function(){
    $(".alert").each(function(index){
        $(this).delay(200*index).fadeTo(1500,0).slideUp(500,function(){
            $(this).remove();
        });
    });
},2000);

Git log to get commits only for a specific branch

You could try something like this:

#!/bin/bash

all_but()
{
    target="$(git rev-parse $1)"
    echo "$target --not"
    git for-each-ref --shell --format="ref=%(refname)" refs/heads | \
    while read entry
    do
        eval "$entry"

        test "$ref" != "$target" && echo "$ref"
    done
}

git log $(all_but $1)

Or, borrowing from the recipe in the Git User's Manual:

#!/bin/bash
git log $1 --not $( git show-ref --heads | cut -d' ' -f2 | grep -v "^$1" )

How do I check if an HTML element is empty using jQuery?

document.getElementById("id").innerHTML == "" || null

or

$("element").html() == "" || null

How to block users from closing a window in Javascript?

Take a look at onBeforeUnload.

It wont force someone to stay but it will prompt them asking them whether they really want to leave, which is probably the best cross browser solution you can manage. (Similar to this site if you attempt to leave mid-answer.)

<script language="JavaScript">
    window.onbeforeunload = confirmExit;
    function confirmExit() {
        return "You have attempted to leave this page. Are you sure?";
    }
</script>

Edit: Most browsers no longer allow a custom message for onbeforeunload.

See this bug report from the 18th of February, 2016.

onbeforeunload dialogs are used for two things on the Modern Web:
1. Preventing users from inadvertently losing data.
2. Scamming users.

In an attempt to restrict their use for the latter while not stopping the former, we are going to not display the string provided by the webpage. Instead, we are going to use a generic string.

Firefox already does this[...]

Properly Handling Errors in VBA (Excel)

This is what I'm teaching my students tomorrow. After years of looking at this stuff... ie all of the documentation above http://www.cpearson.com/excel/errorhandling.htm comes to mind as an excellent one...

I hope this summarizes it for others. There is an Err object and an active (or inactive) ErrorHandler. Both need to be handled and reset for new errors.

Paste this into a workbook and step through it with F8.

Sub ErrorHandlingDemonstration()

    On Error GoTo ErrorHandler

    'this will error
    Debug.Print (1 / 0)

    'this will also error
    dummy = Application.WorksheetFunction.VLookup("not gonna find me", Range("A1:B2"), 2, True)

    'silly error
    Dummy2 = "string" * 50

    Exit Sub

zeroDivisionErrorBlock:
    maybeWe = "did some cleanup on variables that shouldnt have been divided!"
    ' moves the code execution to the line AFTER the one that errored
    Resume Next

vlookupFailedErrorBlock:
    maybeThisTime = "we made sure the value we were looking for was in the range!"
    ' moves the code execution to the line AFTER the one that errored
    Resume Next

catchAllUnhandledErrors:
    MsgBox(thisErrorsDescription)
    Exit Sub

ErrorHandler:
    thisErrorsNumberBeforeReset = Err.Number
    thisErrorsDescription = Err.Description
    'this will reset the error object and error handling
    On Error GoTo 0
    'this will tell vba where to go for new errors, ie the new ErrorHandler that was previous just reset!
    On Error GoTo ErrorHandler

    ' 11 is the err.number for division by 0
    If thisErrorsNumberBeforeReset = 11 Then
        GoTo zeroDivisionErrorBlock
    ' 1004 is the err.number for vlookup failing
    ElseIf thisErrorsNumberBeforeReset = 1004 Then
        GoTo vlookupFailedErrorBlock
    Else
        GoTo catchAllUnhandledErrors
    End If

End Sub

Fastest way to Remove Duplicate Value from a list<> by lambda

There is Distinct() method. it should works.

List<long> longs = new List<long> { 1, 2, 3, 4, 3, 2, 5 };
var distinctList = longs.Distinct().ToList();

Image resizing client-side with JavaScript before upload to the server

Yes, with modern browsers this is totally doable. Even doable to the point of uploading the file specifically as a binary file having done any number of canvas alterations.

http://jsfiddle.net/bo40drmv/

(this answer is a improvement of the accepted answer here)

Keeping in mind to catch process the result submission in the PHP with something akin to:

//File destination
$destination = "/folder/cropped_image.png";
//Get uploaded image file it's temporary name
$image_tmp_name = $_FILES["cropped_image"]["tmp_name"][0];
//Move temporary file to final destination
move_uploaded_file($image_tmp_name, $destination);

If one worries about Vitaly's point, you can try some of the cropping and resizing on the working jfiddle.

How to read a file line-by-line into a list?

with open(filename) as f:
    content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content] 

android : Error converting byte to dex

My project used an external library with heterogeneous Java compatibility versions in my build.gradle files (1.7 and 1.8). I fixed it by using the same version for the lib and for the app project. In my case for both :

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
    }

lodash multi-column sortBy descending

In the documentation of the version 4.11.x, says: ` "This method is like _.sortBy except that it allows specifying the sort orders of the iteratees to sort by. If orders is unspecified, all values are sorted in ascending order. Otherwise, specify an order of "desc" for descending or "asc" for ascending sort order of corresponding values." (source https://lodash.com/docs/4.17.10#orderBy)

let sorted = _.orderBy(this.items, ['fieldFoo', 'fieldBar'], ['asc', 'desc'])

ImportError: No module named matplotlib.pyplot

pip will make your life easy!

Step 1: Install pip - Check if you have pip already simply by writing pip in the python console. If you don't have pip, get a python script called get-pip.py , via here: https://pip.pypa.io/en/latest/installing.html or directly here: https://bootstrap.pypa.io/get-pip.py (You may have to use Save As ..)

Step 2: Take note of where the file got saved and cd the directory from command prompt. Run the get-pip.py script to install pip. You can write in cmd this line within quotes: "python .\get-pip.py"

Step 3: Now in cmd type: pip install matplotlib

And you should be through.

Python & Matplotlib: Make 3D plot interactive in Jupyter Notebook

There is a new library called ipyvolume that may do what you want, the documentation shows live demos. The current version doesn't do meshes and lines, but master from the git repo does (as will version 0.4). (Disclaimer: I'm the author)

Is there an opposite of include? for Ruby Arrays?

Here you go:

unless @players.include?(p.name)
  ...
end

You might have a look at the Ruby Style Guide for more info on similar techniques.

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

NOTE: This answer seems to be specific to: No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android, but it was linked here by:

* https://stackoverflow.com/questions/52193274/no-toolchains-found-in-the-ndk-toolchains-folder-for-abi-with-prefix-mips64el-l

From NDK r19b:

more ~/Android/Sdk/ndk-bundle/CHANGELOG.md
  • This version of the NDK is incompatible with the Android Gradle plugin version 3.0 or older. If you see an error like No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android, update your project file to [use plugin version 3.1 or newer]. You will also need to upgrade to Android Studio 3.1 or newer.

Difference between \n and \r?

To complete,

In a shell (bash) script, you can use \r to send cursor, in front on line and, of course \n to put cursor on a new line.

For example, try :

echo -en "AA--AA" ; echo -en "BB" ; echo -en "\rBB"
  • The first "echo" display AA--AA
  • The second : AA--AABB
  • The last : BB--AABB

But don't forget to use -en as parameters.

Fatal error: Call to undefined function mysql_connect() in C:\Apache\htdocs\test.php on line 2

Uncomment the line extension=php_mysql.dll in your "php.ini" file and restart Apache.

Additionally, "libmysql.dll" file must be available to Apache, i.e., it must be either in available in Windows systems PATH or in Apache working directory.

See more about installing MySQL extension in manual.

P.S. I would advise to consider MySQL extension as deprecated and to use MySQLi or even PDO for working with databases (I prefer PDO).

How can I strip HTML tags from a string in ASP.NET?

Regex.Replace(htmlText, "<.*?>", string.Empty);

How to add an extra column to a NumPy array

I was also interested in this question and compared the speed of

numpy.c_[a, a]
numpy.stack([a, a]).T
numpy.vstack([a, a]).T
numpy.ascontiguousarray(numpy.stack([a, a]).T)               
numpy.ascontiguousarray(numpy.vstack([a, a]).T)
numpy.column_stack([a, a])
numpy.concatenate([a[:,None], a[:,None]], axis=1)
numpy.concatenate([a[None], a[None]], axis=0).T

which all do the same thing for any input vector a. Timings for growing a:

enter image description here

Note that all non-contiguous variants (in particular stack/vstack) are eventually faster than all contiguous variants. column_stack (for its clarity and speed) appears to be a good option if you require contiguity.


Code to reproduce the plot:

import numpy
import perfplot

perfplot.save(
    "out.png",
    setup=lambda n: numpy.random.rand(n),
    kernels=[
        lambda a: numpy.c_[a, a],
        lambda a: numpy.ascontiguousarray(numpy.stack([a, a]).T),
        lambda a: numpy.ascontiguousarray(numpy.vstack([a, a]).T),
        lambda a: numpy.column_stack([a, a]),
        lambda a: numpy.concatenate([a[:, None], a[:, None]], axis=1),
        lambda a: numpy.ascontiguousarray(
            numpy.concatenate([a[None], a[None]], axis=0).T
        ),
        lambda a: numpy.stack([a, a]).T,
        lambda a: numpy.vstack([a, a]).T,
        lambda a: numpy.concatenate([a[None], a[None]], axis=0).T,
    ],
    labels=[
        "c_",
        "ascont(stack)",
        "ascont(vstack)",
        "column_stack",
        "concat",
        "ascont(concat)",
        "stack (non-cont)",
        "vstack (non-cont)",
        "concat (non-cont)",
    ],
    n_range=[2 ** k for k in range(20)],
    xlabel="len(a)",
    logx=True,
    logy=True,
)

How to get previous page url using jquery

    $(document).ready(function() {
               var referrer =  document.referrer;

               if(referrer.equals("Setting.jsp")){                     
                   function goBack() {  
                        window.history.go();                            
                    }
               }  
                   if(referrer.equals("http://localhost:8080/Ads/Terms.jsp")){                     
                        window.history.forward();
                        function noBack() {
                        window.history.forward(); 
                    }
                   }
    }); 

using this you can avoid load previous page load

How to get the mysql table columns data type?

You can use the information_schema columns table:

SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE table_name = 'tbl_name' AND COLUMN_NAME = 'col_name';

how to fire event on file select

This is an older question that needs a newer answer that will address @Christopher Thomas's concern above in the accept answer's comments. If you don't navigate away from the page and then select the file a second time, you need to clear the value when you click or do a touchstart(for mobile). The below will work even when you navigate away from the page and uses jquery:

//the HTML
<input type="file" id="file" name="file" />



//the JavaScript

/*resets the value to address navigating away from the page 
and choosing to upload the same file */ 

$('#file').on('click touchstart' , function(){
    $(this).val('');
});


//Trigger now when you have selected any file 
$("#file").change(function(e) {
    //do whatever you want here
});

What are Bearer Tokens and token_type in OAuth 2?

From RFC 6750, Section 1.2:

Bearer Token

A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

The Bearer Token or Refresh token is created for you by the Authentication server. When a user authenticates your application (client) the authentication server then goes and generates for your a Bearer Token (refresh token) which you can then use to get an access token.

The Bearer Token is normally some kind of cryptic value created by the authentication server, it isn't random it is created based upon the user giving you access and the client your application getting access.

See also: Mozilla MDN Header Information.

Convert java.util.Date to String

Convert a Date to a String using DateFormat#format method:

String pattern = "MM/dd/yyyy HH:mm:ss";

// Create an instance of SimpleDateFormat used for formatting 
// the string representation of date according to the chosen pattern
DateFormat df = new SimpleDateFormat(pattern);

// Get the today date using Calendar object.
Date today = Calendar.getInstance().getTime();        
// Using DateFormat format method we can create a string 
// representation of a date with the defined format.
String todayAsString = df.format(today);

// Print the result!
System.out.println("Today is: " + todayAsString);

From http://www.kodejava.org/examples/86.html

What is the functionality of setSoTimeout and how it works?

The JavaDoc explains it very well:

With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.

SO_TIMEOUT is the timeout that a read() call will block. If the timeout is reached, a java.net.SocketTimeoutException will be thrown. If you want to block forever put this option to zero (the default value), then the read() call will block until at least 1 byte could be read.

How could I use requests in asyncio?

There is a good case of async/await loops and threading in an article by Pimin Konstantin Kefaloukos Easy parallel HTTP requests with Python and asyncio:

To minimize the total completion time, we could increase the size of the thread pool to match the number of requests we have to make. Luckily, this is easy to do as we will see next. The code listing below is an example of how to make twenty asynchronous HTTP requests with a thread pool of twenty worker threads:

# Example 3: asynchronous requests with larger thread pool
import asyncio
import concurrent.futures
import requests

async def main():

    with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:

        loop = asyncio.get_event_loop()
        futures = [
            loop.run_in_executor(
                executor, 
                requests.get, 
                'http://example.org/'
            )
            for i in range(20)
        ]
        for response in await asyncio.gather(*futures):
            pass


loop = asyncio.get_event_loop()
loop.run_until_complete(main())