How to copy text to the client's clipboard using jQuery?
Copying to the clipboard is a tricky task to do in Javascript in terms of browser compatibility. The best way to do it is using a small flash. It will work on every browser. You can check it in this article.
Here's how to do it for Internet Explorer:
function copy (str)
{
//for IE ONLY!
window.clipboardData.setData('Text',str);
}
Copying a rsa public key to clipboard
Your command is right, but the error shows that you didn't create your ssh key yet. To generate new ssh key enter the following command into the terminal.
ssh-keygen
After entering the command then you will be asked to enter file name and passphrase. Normally you don't need to change this. Just press enter. Then your key will be generated in ~/.ssh
directory. After this, you can copy your key by the following command.
pbcopy < ~/.ssh/id_rsa.pub
or
cat .ssh/id_rsa.pub | pbcopy
You can find more about this here ssh.
How to copy to clipboard using Access/VBA?
User Leigh Webber on the social.msdn.microsoft.com site posted VBA code implementing an easy-to-use clipboard interface that uses the Windows API:
http://social.msdn.microsoft.com/Forums/en/worddev/thread/ee9e0d28-0f1e-467f-8d1d-1a86b2db2878
You can get Leigh Webber's source code here
If this link doesn't go through, search for "A clipboard object for VBA" in the Office Dev Center > Microsoft Office for Developers Forums > Word for Developers section.
I created the two classes, ran his test cases, and it worked perfectly inside Outlook 2007 SP3 32-bit VBA under Windows 7 64-bit. It will most likely work for Access.
Tip: To rename classes, select the class in the VBA 'Project' window, then click 'View' on the menu bar and click 'Properties Window' (or just hit F4).
With his classes, this is what it takes to copy to/from the clipboard:
Dim myClipboard As New vbaClipboard ' Create clipboard
' Copy text to clipboard as ClipboardFormat TEXT (CF_TEXT)
myClipboard.SetClipboardText "Text to put in clipboard", "CF_TEXT"
' Retrieve clipboard text in CF_TEXT format (CF_TEXT = 1)
mytxt = myClipboard.GetClipboardText(1)
He also provides other functions for manipulating the clipboard.
It also overcomes 32KB MSForms_DataObject.SetText limitation - the main reason why SetText often fails. However, bear in mind that, unfortunatelly, I haven't found a reference on Microsoft recognizing this limitation.
-Jim
JavaScript get clipboard data on paste event (Cross browser)
Solution #1 (Plain Text only and requires Firefox 22+)
Works for IE6+, FF 22+, Chrome, Safari, Edge
(Only tested in IE9+, but should work for lower versions)
If you need support for pasting HTML or Firefox <= 22, see Solution #2.
HTML
<div id='editableDiv' contenteditable='true'>Paste</div>
JavaScript
function handlePaste (e) {
var clipboardData, pastedData;
// Stop data actually being pasted into div
e.stopPropagation();
e.preventDefault();
// Get pasted data via clipboard API
clipboardData = e.clipboardData || window.clipboardData;
pastedData = clipboardData.getData('Text');
// Do whatever with pasteddata
alert(pastedData);
}
document.getElementById('editableDiv').addEventListener('paste', handlePaste);
JSFiddle: https://jsfiddle.net/swL8ftLs/12/
Note that this solution uses the parameter 'Text' for the getData
function, which is non-standard. However, it works in all browsers at the time of writing.
Solution #2 (HTML and works for Firefox <= 22)
Tested in IE6+, FF 3.5+, Chrome, Safari, Edge
HTML
<div id='div' contenteditable='true'>Paste</div>
JavaScript
var editableDiv = document.getElementById('editableDiv');
function handlepaste (e) {
var types, pastedData, savedContent;
// Browsers that support the 'text/html' type in the Clipboard API (Chrome, Firefox 22+)
if (e && e.clipboardData && e.clipboardData.types && e.clipboardData.getData) {
// Check for 'text/html' in types list. See abligh's answer below for deatils on
// why the DOMStringList bit is needed. We cannot fall back to 'text/plain' as
// Safari/Edge don't advertise HTML data even if it is available
types = e.clipboardData.types;
if (((types instanceof DOMStringList) && types.contains("text/html")) || (types.indexOf && types.indexOf('text/html') !== -1)) {
// Extract data and pass it to callback
pastedData = e.clipboardData.getData('text/html');
processPaste(editableDiv, pastedData);
// Stop the data from actually being pasted
e.stopPropagation();
e.preventDefault();
return false;
}
}
// Everything else: Move existing element contents to a DocumentFragment for safekeeping
savedContent = document.createDocumentFragment();
while(editableDiv.childNodes.length > 0) {
savedContent.appendChild(editableDiv.childNodes[0]);
}
// Then wait for browser to paste content into it and cleanup
waitForPastedData(editableDiv, savedContent);
return true;
}
function waitForPastedData (elem, savedContent) {
// If data has been processes by browser, process it
if (elem.childNodes && elem.childNodes.length > 0) {
// Retrieve pasted content via innerHTML
// (Alternatively loop through elem.childNodes or elem.getElementsByTagName here)
var pastedData = elem.innerHTML;
// Restore saved content
elem.innerHTML = "";
elem.appendChild(savedContent);
// Call callback
processPaste(elem, pastedData);
}
// Else wait 20ms and try again
else {
setTimeout(function () {
waitForPastedData(elem, savedContent)
}, 20);
}
}
function processPaste (elem, pastedData) {
// Do whatever with gathered data;
alert(pastedData);
elem.focus();
}
// Modern browsers. Note: 3rd argument is required for Firefox <= 6
if (editableDiv.addEventListener) {
editableDiv.addEventListener('paste', handlepaste, false);
}
// IE <= 8
else {
editableDiv.attachEvent('onpaste', handlepaste);
}
JSFiddle: https://jsfiddle.net/nicoburns/wrqmuabo/23/
Explanation
The onpaste
event of the div
has the handlePaste
function attached to it and passed a single argument: the event
object for the paste event. Of particular interest to us is the clipboardData
property of this event which enables clipboard access in non-ie browsers. In IE the equivalent is window.clipboardData
, although this has a slightly different API.
See resources section below.
The handlepaste
function:
This function has two branches.
The first checks for the existence of event.clipboardData
and checks whether it's types
property contains 'text/html' (types
may be either a DOMStringList
which is checked using the contains
method, or a string which is checked using the indexOf
method). If all of these conditions are fulfilled, then we proceed as in solution #1, except with 'text/html' instead of 'text/plain'. This currently works in Chrome and Firefox 22+.
If this method is not supported (all other browsers), then we
- Save the element's contents to a
DocumentFragment
- Empty the element
- Call the
waitForPastedData
function
The waitforpastedata
function:
This function first polls for the pasted data (once per 20ms), which is necessary because it doesn't appear straight away. When the data has appeared it:
- Saves the innerHTML of the editable div (which is now the pasted data) to a variable
- Restores the content saved in the DocumentFragment
- Calls the 'processPaste' function with the retrieved data
The processpaste
function:
Does arbitrary things with the pasted data. In this case we just alert the data, you can do whatever you like. You will probably want to run the pasted data through some kind of data sanitising process.
Saving and restoring the cursor position
In a real sitution you would probably want to save the selection before, and restore it afterwards (Set cursor position on contentEditable <div>). You could then insert the pasted data at the position the cursor was in when the user initiated the paste action.
Resources:
Thanks to Tim Down to suggesting the use of a DocumentFragment, and abligh for catching an error in Firefox due to the use of DOMStringList instead of a string for clipboardData.types
Pipe to/from the clipboard in Bash script
Although >1 year later, I share a slightly different solution. Hope this is useful for somebody.
Yesterday I found myself with the question: "How to share the clipboard between different user sessions?". When switching between sessions with ctrlaltF7 - ctrlaltF8, in fact, you can't paste what you copied.
I came up with the following quick & dirty solution, based on a named pipe. It is surely quite bare and raw, but I found it functional:
user1@host:~$ mkfifo /tmp/sharedClip
then in the sending terminal
user1@host:~$ cat > /tmp/sharedClip
last, in the receiving terminal:
user2@host:~$ cat /tmp/sharedClip
Now, you type or paste anything in the first terminal, and (after hitting return), it will appear immediately in the receiving terminal, from where you can Copy/Paste again anywhere you like.
Of course this doesn't just strictly take the content from user1's clipboard to make it available in user2's clipboard, but rather it requires an additional pair of Paste & Copy clicks.
Leave out quotes when copying from cell
"If you want to Select multiple Cells and Copy their values to the Clipboard without all those annoying quotes" (without the bugs in Peter Smallwood's multi-Cells solution) "the following code may be useful." This is an enhancement of the code given above from Peter Smallwood (which "is an enhancement of the code given above from user3616725"). This fixes the following bugs in Peter Smallwood's solution:
- Avoids "Variable not defined" Compiler Error (for "CR" - "clibboardFieldDelimiter " here)
- Convert an Empty Cell to an empty String vs. "0".
- Append Tab (ASCII 9) vs. CR (ASCII 13) after each Cell.
- Append a CR (ASCII 13) + LF (ASCII 10) (vs. CR (ASCII 13)) after each Row.
NOTE: You still won't be able to copy characters embedded within a Cell that would cause an exit of the target field you're Pasting that Cell into (i.e. Tab or CR when Pasting into the Edit Table Window of Access or SSMS).
Option Explicit
Sub CopyCellsWithoutAddingQuotes()
' -- Attach Microsoft Forms 2.0 Library: tools\references\Browse\FM20.DLL
' -- NOTE: You may have to temporarily insert a UserForm into your VBAProject for it to show up.
' -- Then set a Keyboard Shortcut to the "CopyCellsWithoutAddingQuotes" Macro (i.e. Crtl+E)
Dim clibboardFieldDelimiter As String
Dim clibboardLineDelimiter As String
Dim row As Range
Dim cell As Range
Dim cellValueText As String
Dim clipboardText As String
Dim isFirstRow As Boolean
Dim isFirstCellOfRow As Boolean
Dim dataObj As New dataObject
clibboardFieldDelimiter = Chr(9)
clibboardLineDelimiter = Chr(13) + Chr(10)
isFirstRow = True
isFirstCellOfRow = True
For Each row In Selection.Rows
If Not isFirstRow Then
clipboardText = clipboardText + clibboardLineDelimiter
End If
For Each cell In row.Cells
If IsEmpty(cell.Value) Then
cellValueText = ""
ElseIf IsNumeric(cell.Value) Then
cellValueText = LTrim(Str(cell.Value))
Else
cellValueText = cell.Value
End If ' -- Else Non-empty Non-numeric
If isFirstCellOfRow Then
clipboardText = clipboardText + cellValueText
isFirstCellOfRow = False
Else ' -- Not (isFirstCellOfRow)
clipboardText = clipboardText + clibboardFieldDelimiter + cellValueText
End If ' -- Else Not (isFirstCellOfRow)
Next cell
isFirstRow = False
isFirstCellOfRow = True
Next row
clipboardText = clipboardText + clibboardLineDelimiter
dataObj.SetText (clipboardText)
dataObj.PutInClipboard
End Sub
How to fix broken paste clipboard in VNC on Windows
I use Remote login with vnc-ltsp-config with GNOME Desktop Environment on CentOS 5.9. From experimenting today, I managed to get cut and paste working for the session and the login prompt (because I'm lazy and would rather copy and paste difficult passwords).
I created a file vncconfig.desktop in the /etc/xdg/autostart directory which enabled cut and paste during the session after login. The vncconfig process is run as the logged in user.
[Desktop Entry]
Name=No name
Encoding=UTF-8
Version=1.0
Exec=vncconfig -nowin
X-GNOME-Autostart-enabled=true
Added vncconfig -nowin & to the bottom of the file /etc/gdm/Init/Desktop which enabled cut and paste in the session during login but terminates after login. The vncconfig process is run as root.
Adding vncconfig -nowin & to the bottom of the file /etc/gdm/PostLogin/Desktop also enabled cut and paste during the session after login. The vncconfig process is run as root however.
Excel VBA code to copy a specific string to clipboard
If the url is in a cell in your workbook, you can simply copy the value from that cell:
Private Sub CommandButton1_Click()
Sheets("Sheet1").Range("A1").Copy
End Sub
(Add a button by using the developer tab. Customize the ribbon if it isn't visible.)
If the url isn't in the workbook, you can use the Windows API. The code that follows can be found here: http://support.microsoft.com/kb/210216
After you've added the API calls below, change the code behind the button to copy to the clipboard:
Private Sub CommandButton1_Click()
ClipBoard_SetData ("http:\\stackoverflow.com")
End Sub
Add a new module to your workbook and paste in the following code:
Option Explicit
Declare Function GlobalUnlock Lib "kernel32" (ByVal hMem As Long) _
As Long
Declare Function GlobalLock Lib "kernel32" (ByVal hMem As Long) _
As Long
Declare Function GlobalAlloc Lib "kernel32" (ByVal wFlags As Long, _
ByVal dwBytes As Long) As Long
Declare Function CloseClipboard Lib "User32" () As Long
Declare Function OpenClipboard Lib "User32" (ByVal hwnd As Long) _
As Long
Declare Function EmptyClipboard Lib "User32" () As Long
Declare Function lstrcpy Lib "kernel32" (ByVal lpString1 As Any, _
ByVal lpString2 As Any) As Long
Declare Function SetClipboardData Lib "User32" (ByVal wFormat _
As Long, ByVal hMem As Long) As Long
Public Const GHND = &H42
Public Const CF_TEXT = 1
Public Const MAXSIZE = 4096
Function ClipBoard_SetData(MyString As String)
Dim hGlobalMemory As Long, lpGlobalMemory As Long
Dim hClipMemory As Long, X As Long
' Allocate moveable global memory.
'-------------------------------------------
hGlobalMemory = GlobalAlloc(GHND, Len(MyString) + 1)
' Lock the block to get a far pointer
' to this memory.
lpGlobalMemory = GlobalLock(hGlobalMemory)
' Copy the string to this global memory.
lpGlobalMemory = lstrcpy(lpGlobalMemory, MyString)
' Unlock the memory.
If GlobalUnlock(hGlobalMemory) <> 0 Then
MsgBox "Could not unlock memory location. Copy aborted."
GoTo OutOfHere2
End If
' Open the Clipboard to copy data to.
If OpenClipboard(0&) = 0 Then
MsgBox "Could not open the Clipboard. Copy aborted."
Exit Function
End If
' Clear the Clipboard.
X = EmptyClipboard()
' Copy the data to the Clipboard.
hClipMemory = SetClipboardData(CF_TEXT, hGlobalMemory)
OutOfHere2:
If CloseClipboard() = 0 Then
MsgBox "Could not close Clipboard."
End If
End Function
How to copy a selection to the OS X clipboard
Use Homebrew's vim: brew install vim
Mac (as of 10.10.3 Yosemite) comes pre-installed with a system vim that does not have the clipboard
flag enabled.
You can either compile vim for yourself and enable that flag, or simply use Homebrew's vim which is setup properly.
To see this for yourself, check out the stock system vim with /usr/bin/vim --version
You'll see something like:
$ /usr/bin/vim --version
VIM - Vi IMproved 7.3 (2010 Aug 15, compiled Nov 5 2014 21:00:28)
Compiled by [email protected]
Normal version without GUI. Features included (+) or not (-):
... -clientserver -clipboard +cmdline_compl ...
Note the -clipboard
With homebrew's vim you instead get
$ /usr/local/bin/vim --version
VIM - Vi IMproved 7.4 (2013 Aug 10, compiled May 10 2015 14:04:42)
MacOS X (unix) version
Included patches: 1-712
Compiled by Homebrew
Huge version without GUI. Features included (+) or not (-):
... +clipboard ...
Note the +clipboard
How to copy data to clipboard in C#
My Experience with this issue using WPF C# coping to clipboard and System.Threading.ThreadStateException
is here with my code that worked correctly with all browsers:
Thread thread = new Thread(() => Clipboard.SetText("String to be copied to clipboard"));
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start();
thread.Join();
credits to this post here
But this works only on localhost, so don't try this on a server, as it's not going to work.
On server-side, I did it by using zeroclipboard
. The only way, after a lot of research.
In reactJS, how to copy text to clipboard?
Your code should work perfectly, I use it the same way. Only make sure that if the click event is triggered from within a pop up screen like a bootstrap modal or something, the created element has to be within that modal otherwise it won't copy. You could always give the id of an element within that modal (as a second parameter) and retrieve it with getElementById, then append the newly created element to that one instead of the document. Something like this:
copyToClipboard = (text, elementId) => {
const textField = document.createElement('textarea');
textField.innerText = text;
const parentElement = document.getElementById(elementId);
parentElement.appendChild(textField);
textField.select();
document.execCommand('copy');
parentElement.removeChild(textField);
}
How do I copy to the clipboard in JavaScript?
In 2018, here's how you can go about it:
async copySomething(text?) {
try {
const toCopy = text || location.href;
await navigator.clipboard.writeText(toCopy);
console.log('Text or Page URL copied');
}
catch (err) {
console.error('Failed to copy: ', err);
}
}
It is used in my Angular 6+ code like so:
<button mat-menu-item (click)="copySomething()">
<span>Copy link</span>
</button>
If I pass in a string, it copies it. If nothing, it copies the page's URL.
More gymnastics to the clipboard stuff can be done too. See more information here:
Unblocking Clipboard Access
How do I copy a string to the clipboard?
Not all of the answers worked for my various python configurations so this solution only uses the subprocess module. However, copy_keyword
has to be pbcopy
for Mac or clip
for Windows:
import subprocess
subprocess.run('copy_keyword', universal_newlines=True, input='New Clipboard Value ')
Here's some more extensive code that automatically checks what the current operating system is:
import platform
import subprocess
copy_string = 'New Clipboard Value '
# Check which operating system is running to get the correct copying keyword.
if platform.system() == 'Darwin':
copy_keyword = 'pbcopy'
elif platform.system() == 'Windows':
copy_keyword = 'clip'
subprocess.run(copy_keyword, universal_newlines=True, input=copy_string)
Get current clipboard content?
You can use
window.clipboardData.getData('Text')
to get the content of user's clipboard in IE. However, in other browser you may need to use flash to get the content, since there is no standard interface to access the clipboard. May be you can have try this plugin Zero Clipboard
Copying text to the clipboard using Java
The following class allows you to copy/paste a String to/from the clipboard.
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import static java.awt.event.KeyEvent.*;
import static org.apache.commons.lang3.SystemUtils.IS_OS_MAC;
public class SystemClipboard
{
public static void copy(String text)
{
Clipboard clipboard = getSystemClipboard();
clipboard.setContents(new StringSelection(text), null);
}
public static void paste() throws AWTException
{
Robot robot = new Robot();
int controlKey = IS_OS_MAC ? VK_META : VK_CONTROL;
robot.keyPress(controlKey);
robot.keyPress(VK_V);
robot.keyRelease(controlKey);
robot.keyRelease(VK_V);
}
public static String get() throws Exception
{
Clipboard systemClipboard = getSystemClipboard();
DataFlavor dataFlavor = DataFlavor.stringFlavor;
if (systemClipboard.isDataFlavorAvailable(dataFlavor))
{
Object text = systemClipboard.getData(dataFlavor);
return (String) text;
}
return null;
}
private static Clipboard getSystemClipboard()
{
Toolkit defaultToolkit = Toolkit.getDefaultToolkit();
return defaultToolkit.getSystemClipboard();
}
}
Copy / Put text on the clipboard with FireFox, Safari and Chrome
For security reasons, Firefox doesn't allow you to place text on the clipboard. However, there is a work-around available using Flash.
function copyIntoClipboard(text) {
var flashId = 'flashId-HKxmj5';
/* Replace this with your clipboard.swf location */
var clipboardSWF = 'http://appengine.bravo9.com/copy-into-clipboard/clipboard.swf';
if(!document.getElementById(flashId)) {
var div = document.createElement('div');
div.id = flashId;
document.body.appendChild(div);
}
document.getElementById(flashId).innerHTML = '';
var content = '<embed src="' +
clipboardSWF +
'" FlashVars="clipboard=' + encodeURIComponent(text) +
'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
document.getElementById(flashId).innerHTML = content;
}
The only disadvantage is that this requires Flash to be enabled.
source is currently dead: http://bravo9.com/journal/copying-text-into-the-clipboard-with-javascript-in-firefox-safari-ie-opera-292559a2-cc6c-4ebf-9724-d23e8bc5ad8a/ (and so is it's Google cache)
How do I copy the contents of a String to the clipboard in C#?
This works for me:
You want to do:
System.Windows.Forms.Clipboard.SetText("String to be copied to Clipboard");
But it causes an error saying it must be in a single thread of ApartmentState.STA.
So let's make it run in such a thread. The code for it:
public void somethingToRunInThread()
{
System.Windows.Forms.Clipboard.SetText("String to be copied to Clipboard");
}
protected void copy_to_clipboard()
{
Thread clipboardThread = new Thread(somethingToRunInThread);
clipboardThread.SetApartmentState(ApartmentState.STA);
clipboardThread.IsBackground = false;
clipboardThread.Start();
}
After calling copy_to_clipboard()
, the string is copied into the clipboard, so you can Paste or Ctrl + V and get back the string as String to be copied to the clipboard.
How does Trello access the user's clipboard?
Something very similar can be seen on http://goo.gl when you shorten the URL.
There is a readonly input element that gets programmatically focused, with tooltip press CTRL-C to copy.
When you hit that shortcut, the input content effectively gets into the clipboard. Really nice :)
How do I cancel form submission in submit button onclick event?
This is a very old thread but it is sure to be noticed. Hence the note that the solutions offered are no longer up to date and that modern Javascript is much better.
<script>
document.getElementById(id of the form).addEventListener(
"submit",
function(event)
{
if(validData() === false)
{
event.preventDefault();
}
},
false
);
The form receives an event handler that monitors the submit. If the there called function validData (not shown here) returns a FALSE, calling the method PreventDefault, which suppresses the submit of the form and the browser returns to the input. Otherwise the form will be sent as usual.
P.S. This also works with the attribute onsubmit. Then the anonymus function function(event){...} must in the attribute onsubmit of the form. This is not really modern and you can only work with one event handler for submit. But you don't have to create an extra javascript. In addition, it can be specified directly in the source code as an attribute of the form and there is no need to wait until the form is integrated in the DOM.
How to Free Inode Usage?
My situation was that I was out of inodes and I had already deleted about everything I could.
$ df -i
Filesystem Inodes IUsed IFree IUse% Mounted on
/dev/sda1 942080 507361 11 100% /
I am on an ubuntu 12.04LTS and could not remove the old linux kernels which took up about 400,000 inodes because apt was broken because of a missing package. And I couldn't install the new package because I was out of inodes so I was stuck.
I ended up deleting a few old linux kernels by hand to free up about 10,000 inodes
$ sudo rm -rf /usr/src/linux-headers-3.2.0-2*
This was enough to then let me install the missing package and fix my apt
$ sudo apt-get install linux-headers-3.2.0-76-generic-pae
and then remove the rest of the old linux kernels with apt
$ sudo apt-get autoremove
things are much better now
$ df -i
Filesystem Inodes IUsed IFree IUse% Mounted on
/dev/sda1 942080 507361 434719 54% /
Which is more efficient, a for-each loop, or an iterator?
The foreach
underhood is creating the iterator
, calling hasNext() and calling next() to get the value; The issue with the performance comes only if you are using something that implements the RandomomAccess.
for (Iterator<CustomObj> iter = customList.iterator(); iter.hasNext()){
CustomObj custObj = iter.next();
....
}
Performance issues with the iterator-based loop is because it is:
- allocating an object even if the list is empty (
Iterator<CustomObj> iter = customList.iterator();
);
iter.hasNext()
during every iteration of the loop there is an invokeInterface virtual call (go through all the classes, then do method table lookup before the jump).
- the implementation of the iterator has to do at least 2 fields lookup in order to make
hasNext()
call figure the value: #1 get current count and #2 get total count
- inside the body loop, there is another invokeInterface virtual call
iter.next
(so: go through all the classes and do method table lookup before the jump) and as well has to do fields lookup: #1 get the index and #2 get the reference to the array to do the offset into it (in every iteration).
A potential optimiziation is to switch to an index iteration
with the cached size lookup:
for(int x = 0, size = customList.size(); x < size; x++){
CustomObj custObj = customList.get(x);
...
}
Here we have:
- one invokeInterface virtual method call
customList.size()
on the initial creation of the for loop to get the size
- the get method call
customList.get(x)
during the body for loop, which is a field lookup to the array and then can do the offset into the array
We reduced a ton of method calls, field lookups. This you don't want to do with LinkedList
or with something that is not a RandomAccess
collection obj, otherwise the customList.get(x)
is gonna turn into something that has to traverse the LinkedList
on every iteration.
This is perfect when you know that is any RandomAccess
based list collection.
.map() a Javascript ES6 Map?
I prefer to extend the map
export class UtilMap extends Map {
constructor(...args) { super(args); }
public map(supplier) {
const mapped = new UtilMap();
this.forEach(((value, key) => mapped.set(key, supplier(value, key)) ));
return mapped;
};
}
Saving an Object (Data persistence)
I think it's a pretty strong assumption to assume that the object is a class
. What if it's not a class
? There's also the assumption that the object was not defined in the interpreter. What if it was defined in the interpreter? Also, what if the attributes were added dynamically? When some python objects have attributes added to their __dict__
after creation, pickle
doesn't respect the addition of those attributes (i.e. it 'forgets' they were added -- because pickle
serializes by reference to the object definition).
In all these cases, pickle
and cPickle
can fail you horribly.
If you are looking to save an object
(arbitrarily created), where you have attributes (either added in the object definition, or afterward)… your best bet is to use dill
, which can serialize almost anything in python.
We start with a class…
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> class Company:
... pass
...
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>> with open('company.pkl', 'wb') as f:
... pickle.dump(company1, f, pickle.HIGHEST_PROTOCOL)
...
>>>
Now shut down, and restart...
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('company.pkl', 'rb') as f:
... company1 = pickle.load(f)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1378, in load
return Unpickler(file).load()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 858, in load
dispatch[key](self)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1090, in load_global
klass = self.find_class(module, name)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1126, in find_class
klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'Company'
>>>
Oops… pickle
can't handle it. Let's try dill
. We'll throw in another object type (a lambda
) for good measure.
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> class Company:
... pass
...
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>>
>>> company2 = lambda x:x
>>> company2.name = 'rhubarb'
>>> company2.value = 42
>>>
>>> with open('company_dill.pkl', 'wb') as f:
... dill.dump(company1, f)
... dill.dump(company2, f)
...
>>>
And now read the file.
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> with open('company_dill.pkl', 'rb') as f:
... company1 = dill.load(f)
... company2 = dill.load(f)
...
>>> company1
<__main__.Company instance at 0x107909128>
>>> company1.name
'banana'
>>> company1.value
40
>>> company2.name
'rhubarb'
>>> company2.value
42
>>>
It works. The reason pickle
fails, and dill
doesn't, is that dill
treats __main__
like a module (for the most part), and also can pickle class definitions instead of pickling by reference (like pickle
does). The reason dill
can pickle a lambda
is that it gives it a name… then pickling magic can happen.
Actually, there's an easier way to save all these objects, especially if you have a lot of objects you've created. Just dump the whole python session, and come back to it later.
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> class Company:
... pass
...
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>>
>>> company2 = lambda x:x
>>> company2.name = 'rhubarb'
>>> company2.value = 42
>>>
>>> dill.dump_session('dill.pkl')
>>>
Now shut down your computer, go enjoy an espresso or whatever, and come back later...
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> dill.load_session('dill.pkl')
>>> company1.name
'banana'
>>> company1.value
40
>>> company2.name
'rhubarb'
>>> company2.value
42
>>> company2
<function <lambda> at 0x1065f2938>
The only major drawback is that dill
is not part of the python standard library. So if you can't install a python package on your server, then you can't use it.
However, if you are able to install python packages on your system, you can get the latest dill
with git+https://github.com/uqfoundation/dill.git@master#egg=dill
. And you can get the latest released version with pip install dill
.
How to iterate through range of Dates in Java?
Java 8 style, using the java.time classes:
// Monday, February 29 is a leap day in 2016 (otherwise, February only has 28 days)
LocalDate start = LocalDate.parse("2016-02-28"),
end = LocalDate.parse("2016-03-02");
// 4 days between (end is inclusive in this example)
Stream.iterate(start, date -> date.plusDays(1))
.limit(ChronoUnit.DAYS.between(start, end) + 1)
.forEach(System.out::println);
Output:
2016-02-28
2016-02-29
2016-03-01
2016-03-02
Alternative:
LocalDate next = start.minusDays(1);
while ((next = next.plusDays(1)).isBefore(end.plusDays(1))) {
System.out.println(next);
}
Java 9 added the datesUntil() method:
start.datesUntil(end.plusDays(1)).forEach(System.out::println);
Java word count program
To count total words Or to count total words without repeat word count
public static void main(String[] args) {
// TODO Auto-generated method stub
String test = "I am trying to make make make";
Pattern p = Pattern.compile("\\w+");
Matcher m = p.matcher(test);
HashSet<String> hs = new HashSet<>();
int i=0;
while (m.find()) {
i++;
hs.add(m.group());
}
System.out.println("Total words Count==" + i);
System.out.println("Count without Repetation ==" + hs.size());
}
}
Output :
Total words Count==7
Count without Repeatation ==5
SQL, How to convert VARCHAR to bigint?
I think your code is right. If you run the following code it converts the string '60' which is treated as varchar and it returns integer 60, if there is integer containing string in second it works.
select CONVERT(bigint,'60') as seconds
and it returns
60
Merge two array of objects based on a key
Here's an O(n) solution using reduce and Object.assign
const joinById = ( ...lists ) =>
Object.values(
lists.reduce(
( idx, list ) => {
list.forEach( ( recod ) => {
if( idx[ recod.id ] )
idx[ recod.id ] = Object.assign( idx[ recod.id ], recod )
else
idx[ recod.id ] = recod
} )
return idx
},
{}
)
)
Each list gets reduced to a single object where the keys are ids and the values are the objects. If there's a value at the given key already, it gets object.assign called on it and the current record.
Here's the generic O(n*m) solution, where n is the number of records and m is the number of keys. This will only work for valid object keys. You can convert any value to base64 and use that if you need to.
const join = ( keys, ...lists ) =>
lists.reduce(
( res, list ) => {
list.forEach( ( record ) => {
let hasNode = keys.reduce(
( idx, key ) => idx && idx[ record[ key ] ],
res[ 0 ].tree
)
if( hasNode ) {
const i = hasNode.i
Object.assign( res[ i ].value, record )
res[ i ].found++
} else {
let node = keys.reduce( ( idx, key ) => {
if( idx[ record[ key ] ] )
return idx[ record[ key ] ]
else
idx[ record[ key ] ] = {}
return idx[ record[ key ] ]
}, res[ 0 ].tree )
node.i = res[ 0 ].i++
res[ node.i ] = {
found: 1,
value: record
}
}
} )
return res
},
[ { i: 1, tree: {} } ]
)
.slice( 1 )
.filter( node => node.found === lists.length )
.map( n => n.value )
This is essentially the same as the joinById method, except that it keeps an index object to identify records to join. The records are stored in an array and the index stores the position of the record for the given key set and the number of lists it's been found in.
Each time the same key set is encountered, the node is found in the tree, the element at it's index is updated, and the number of times it's been found is incremented.
finally, the idx object is removed from the array with the slice, any elements that weren't found in each set are removed. This makes it an inner join, you could remove this filter and have a full outer join.
finally each element is mapped to it's value, and you have the merged array.
Sequel Pro Alternative for Windows
You say you've had problems with Navicat. For the record, I use Navicat and I haven't experienced the issue you describe. You might want to dig around, see if there's a reason for your problem and/or a solution, because given the question asked, my first recommendation would have been Navicat.
But if you want alternative suggestions, here are a few that I know of and have used:
MySQL has its own tool which you can download for free, called MySQL Workbench. Download it from here: http://wb.mysql.com/. My experience is that it's powerful, but I didn't really like the UI. But that's just my personal taste.
Another free program you might want to try is HeidiSQL. It's more similar to Navicat than MySQL Workbench. A colleague of mine loves it.
(interesting to note, by the way, that MariaDB (the forked version of MySQL) is currently shipped with HeidiSQL as its GUI tool)
Finally, if you're running a web server on your machine, there's always the option of a browser-based tool like PHPMyAdmin. It's actually a surprisingly powerful piece of software.
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 to calculate md5 hash of a file using javascript
While there are JS implementations of the MD5 algorithm, older browsers are generally unable to read files from the local filesystem.
I wrote that in 2009. So what about new browsers?
With a browser that supports the FileAPI, you *can * read the contents of a file - the user has to have selected it, either with an <input>
element or drag-and-drop. As of Jan 2013, here's how the major browsers stack up:
How to use apply a custom drawable to RadioButton?
Give your radiobutton a custom style:
<style name="MyRadioButtonStyle" parent="@android:style/Widget.CompoundButton.RadioButton">
<item name="android:button">@drawable/custom_btn_radio</item>
</style>
custom_btn_radio.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:state_window_focused="false"
android:drawable="@drawable/btn_radio_on" />
<item android:state_checked="false" android:state_window_focused="false"
android:drawable="@drawable/btn_radio_off" />
<item android:state_checked="true" android:state_pressed="true"
android:drawable="@drawable/btn_radio_on_pressed" />
<item android:state_checked="false" android:state_pressed="true"
android:drawable="@drawable/btn_radio_off_pressed" />
<item android:state_checked="true" android:state_focused="true"
android:drawable="@drawable/btn_radio_on_selected" />
<item android:state_checked="false" android:state_focused="true"
android:drawable="@drawable/btn_radio_off_selected" />
<item android:state_checked="false" android:drawable="@drawable/btn_radio_off" />
<item android:state_checked="true" android:drawable="@drawable/btn_radio_on" />
</selector>
Replace the drawables with your own.
How can I get a specific parameter from location.search?
A Simple One-Line Solution:
let query = Object.assign.apply(null, location.search.slice(1).split('&').map(entry => ({ [entry.split('=')[0]]: entry.split('=')[1] })));
Expanded & Explained:
// define variable
let query;
// fetch source query
query = location.search;
// skip past the '?' delimiter
query = query.slice(1);
// split source query by entry delimiter
query = query.split('&');
// replace each query entry with an object containing the query entry
query = query.map((entry) => {
// get query entry key
let key = entry.split('=')[0];
// get query entry value
let value = entry.split('=')[1];
// define query object
let container = {};
// add query entry to object
container[key] = value;
// return query object
return container;
});
// merge all query objects
query = Object.assign.apply(null, query);
How to establish a connection pool in JDBC?
Pool
- Pooling Mechanism is the way of creating the Objects in advance. When a class is loaded.
- It improves the application
performance
[By re using same object's to perform any action on Object-Data] & memory
[allocating and de-allocating many objects creates a significant memory management overhead].
- Object clean-up is not required as we are using same Object, reducing the Garbage collection load.
« Pooling [ Object
pool, String
Constant Pool, Thread
Pool, Connection pool]
String Constant pool
- String literal pool maintains only one copy of each distinct string value. which must be immutable.
- When the intern method is invoked, it check object availability with same content in pool using equals method.
« If String-copy is available in the Pool then returns the reference.
« Otherwise, String object is added to the pool and returns the reference.
Example: String to verify Unique Object from pool.
public class StringPoolTest {
public static void main(String[] args) { // Integer.valueOf(), String.equals()
String eol = System.getProperty("line.separator"); //java7 System.lineSeparator();
String s1 = "Yash".intern();
System.out.format("Val:%s Hash:%s SYS:%s "+eol, s1, s1.hashCode(), System.identityHashCode(s1));
String s2 = "Yas"+"h".intern();
System.out.format("Val:%s Hash:%s SYS:%s "+eol, s2, s2.hashCode(), System.identityHashCode(s2));
String s3 = "Yas".intern()+"h".intern();
System.out.format("Val:%s Hash:%s SYS:%s "+eol, s3, s3.hashCode(), System.identityHashCode(s3));
String s4 = "Yas"+"h";
System.out.format("Val:%s Hash:%s SYS:%s "+eol, s4, s4.hashCode(), System.identityHashCode(s4));
}
}
Connection pool using Type-4 Driver using 3rd party libraries[ DBCP2
, c3p0
, Tomcat JDBC
]
Type 4 - The Thin driver converts JDBC calls directly into the vendor-specific database protocol Ex[Oracle - Thick, MySQL - Quora].
wiki
In Connection pool mechanism, when the class is loaded it get's the physical JDBC connection
objects and provides a wrapped physical connection object to user. PoolableConnection
is a wrapper around the actual connection.
getConnection()
pick one of the free wrapped-connection form the connection objectpool and returns it.
close()
instead of closing it returns the wrapped-connection back to pool.
Example: Using ~ DBCP2 Connection Pool with Java 7[try-with-resources
]
public class ConnectionPool {
static final BasicDataSource ds_dbcp2 = new BasicDataSource();
static final ComboPooledDataSource ds_c3p0 = new ComboPooledDataSource();
static final DataSource ds_JDBC = new DataSource();
static Properties prop = new Properties();
static {
try {
prop.load(ConnectionPool.class.getClassLoader().getResourceAsStream("connectionpool.properties"));
ds_dbcp2.setDriverClassName( prop.getProperty("DriverClass") );
ds_dbcp2.setUrl( prop.getProperty("URL") );
ds_dbcp2.setUsername( prop.getProperty("UserName") );
ds_dbcp2.setPassword( prop.getProperty("Password") );
ds_dbcp2.setInitialSize( 5 );
ds_c3p0.setDriverClass( prop.getProperty("DriverClass") );
ds_c3p0.setJdbcUrl( prop.getProperty("URL") );
ds_c3p0.setUser( prop.getProperty("UserName") );
ds_c3p0.setPassword( prop.getProperty("Password") );
ds_c3p0.setMinPoolSize(5);
ds_c3p0.setAcquireIncrement(5);
ds_c3p0.setMaxPoolSize(20);
PoolProperties pool = new PoolProperties();
pool.setUrl( prop.getProperty("URL") );
pool.setDriverClassName( prop.getProperty("DriverClass") );
pool.setUsername( prop.getProperty("UserName") );
pool.setPassword( prop.getProperty("Password") );
pool.setValidationQuery("SELECT 1");// SELECT 1(mysql) select 1 from dual(oracle)
pool.setInitialSize(5);
pool.setMaxActive(3);
ds_JDBC.setPoolProperties( pool );
} catch (IOException e) { e.printStackTrace();
} catch (PropertyVetoException e) { e.printStackTrace(); }
}
public static Connection getDBCP2Connection() throws SQLException {
return ds_dbcp2.getConnection();
}
public static Connection getc3p0Connection() throws SQLException {
return ds_c3p0.getConnection();
}
public static Connection getJDBCConnection() throws SQLException {
return ds_JDBC.getConnection();
}
}
public static boolean exists(String UserName, String Password ) throws SQLException {
boolean exist = false;
String SQL_EXIST = "SELECT * FROM users WHERE username=? AND password=?";
try ( Connection connection = ConnectionPool.getDBCP2Connection();
PreparedStatement pstmt = connection.prepareStatement(SQL_EXIST); ) {
pstmt.setString(1, UserName );
pstmt.setString(2, Password );
try (ResultSet resultSet = pstmt.executeQuery()) {
exist = resultSet.next(); // Note that you should not return a ResultSet here.
}
}
System.out.println("User : "+exist);
return exist;
}
jdbc:<DB>:<drivertype>:<HOST>:<TCP/IP PORT>:<dataBaseName>
jdbc:
oracle
:thin:@localhost:1521:myDBName
jdbc:
mysql
://localhost:3306/myDBName
connectionpool.properties
URL : jdbc:mysql://localhost:3306/myDBName
DriverClass : com.mysql.jdbc.Driver
UserName : root
Password :
Web Application: To avoid connection problem when all the connection's are closed[MySQL "wait_timeout" default 8 hours] in-order to reopen the connection with underlying DB.
You can do this to Test Every Connection by setting testOnBorrow = true and validationQuery= "SELECT 1" and donot use autoReconnect for MySQL server as it is deprecated. issue
===== ===== context.xml ===== =====
<?xml version="1.0" encoding="UTF-8"?>
<!-- The contents of this file will be loaded for a web application -->
<Context>
<Resource name="jdbc/MyAppDB" auth="Container"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
type="javax.sql.DataSource"
initialSize="5" minIdle="5" maxActive="15" maxIdle="10"
testWhileIdle="true"
timeBetweenEvictionRunsMillis="30000"
testOnBorrow="true"
validationQuery="SELECT 1"
validationInterval="30000"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/myDBName"
username="yash" password="777"
/>
</Context>
===== ===== web.xml ===== =====
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/MyAppDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
===== ===== DBOperations ===== =====
servlet « init() {}
Normal call used by sevlet « static {}
static DataSource ds;
static {
try {
Context ctx=new InitialContext();
Context envContext = (Context)ctx.lookup("java:comp/env");
ds = (DataSource) envContext.lookup("jdbc/MyAppDB");
} catch (NamingException e) { e.printStackTrace(); }
}
See these also:
What is the difference between 'my' and 'our' in Perl?
#!/usr/bin/perl -l
use strict;
# if string below commented out, prints 'lol' , if the string enabled, prints 'eeeeeeeee'
#my $lol = 'eeeeeeeeeee' ;
# no errors or warnings at any case, despite of 'strict'
our $lol = eval {$lol} || 'lol' ;
print $lol;
Take multiple lists into dataframe
@oopsi used pd.concat()
but didn't include the column names. You could do the following, which, unlike the first solution in the accepted answer, gives you control over the column order (avoids dicts, which are unordered):
import pandas as pd
lst1 = range(100)
lst2 = range(100)
lst3 = range(100)
s1=pd.Series(lst1,name='lst1Title')
s2=pd.Series(lst2,name='lst2Title')
s3=pd.Series(lst3 ,name='lst3Title')
percentile_list = pd.concat([s1,s2,s3], axis=1)
percentile_list
Out[2]:
lst1Title lst2Title lst3Title
0 0 0 0
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
6 6 6 6
7 7 7 7
8 8 8 8
...
How to get a reference to an iframe's window object inside iframe's onload handler created from parent window
You're declaring everything in the parent page. So the references to window
and document
are to the parent page's. If you want to do stuff to the iframe
's, use iframe || iframe.contentWindow
to access its window
, and iframe.contentDocument || iframe.contentWindow.document
to access its document
.
There's a word for what's happening, possibly "lexical scope": What is lexical scope?
The only context of a scope is this. And in your example, the owner of the method is doc
, which is the iframe
's document
. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.
This is how I would write it:
(function () {
var dom, win, doc, where, iframe;
iframe = document.createElement('iframe');
iframe.src = "javascript:false";
where = document.getElementsByTagName('script')[0];
where.parentNode.insertBefore(iframe, where);
win = iframe.contentWindow || iframe;
doc = iframe.contentDocument || iframe.contentWindow.document;
doc.open();
doc._l = (function (w, d) {
return function () {
w.vanishing_global = new Date().getTime();
var js = d.createElement("script");
js.src = 'test-vanishing-global.js?' + w.vanishing_global;
w.name = "foobar";
d.foobar = "foobar:" + Math.random();
d.foobar = "barfoo:" + Math.random();
d.body.appendChild(js);
};
})(win, doc);
doc.write('<body onload="document._l();"></body>');
doc.close();
})();
The aliasing of win
and doc
as w
and d
aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe
's stuff. If you want to access the parent's, you still use window
and document
.
I'm not sure what the implications are of adding methods to a document
(doc
in this case), but it might make more sense to set the _l
method on win
. That way, things can be run without a prefix...such as <body onload="_l();"></body>
How is returning the output of a function different from printing it?
you just add a return statement...
def autoparts():
parts_dict={}
list_of_parts = open('list_of_parts.txt', 'r')
for line in list_of_parts:
k, v = line.split()
parts_dict[k] = v
return parts_dict
printing out only prints out to the standard output (screen) of the application. You can also return multiple things by separating them with commas:
return parts_dict, list_of_parts
to use it:
test_dict = {}
test_dict = autoparts()
remove duplicates from sql union
Others have already answered your direct question, but perhaps you could simplify the query to eliminate the question (or have I missed something, and a query like the following will really produce substantially different results?):
select *
from calls c join users u
on c.assigned_to = u.user_id
or c.requestor_id = u.user_id
where u.dept = 4
Matplotlib (pyplot) savefig outputs blank image
Calling savefig before show() worked for me.
fig ,ax = plt.subplots(figsize = (4,4))
sns.barplot(x='sex', y='tip', color='g', ax=ax,data=tips)
sns.barplot(x='sex', y='tip', color='b', ax=ax,data=tips)
ax.legend(['Male','Female'], facecolor='w')
plt.savefig('figure.png')
plt.show()
What exactly does the "u" do? "git push -u origin master" vs "git push origin master"
The key is "argument-less git-pull". When you do a git pull
from a branch, without specifying a source remote or branch, git looks at the branch.<name>.merge
setting to know where to pull from. git push -u
sets this information for the branch you're pushing.
To see the difference, let's use a new empty branch:
$ git checkout -b test
First, we push without -u
:
$ git push origin test
$ git pull
You asked me to pull without telling me which branch you
want to merge with, and 'branch.test.merge' in
your configuration file does not tell me, either. Please
specify which branch you want to use on the command line and
try again (e.g. 'git pull <repository> <refspec>').
See git-pull(1) for details.
If you often merge with the same branch, you may want to
use something like the following in your configuration file:
[branch "test"]
remote = <nickname>
merge = <remote-ref>
[remote "<nickname>"]
url = <url>
fetch = <refspec>
See git-config(1) for details.
Now if we add -u
:
$ git push -u origin test
Branch test set up to track remote branch test from origin.
Everything up-to-date
$ git pull
Already up-to-date.
Note that tracking information has been set up so that git pull
works as expected without specifying the remote or branch.
Update: Bonus tips:
- As Mark mentions in a comment, in addition to
git pull
this setting also affects default behavior of git push
. If you get in the habit of using -u
to capture the remote branch you intend to track, I recommend setting your push.default
config value to upstream
.
git push -u <remote> HEAD
will push the current branch to a branch of the same name on <remote>
(and also set up tracking so you can do git push
after that).
How exactly does the python any() function work?
If you use any(lst)
you see that lst
is the iterable, which is a list of some items. If it contained [0, False, '', 0.0, [], {}, None]
(which all have boolean values of False
) then any(lst)
would be False
. If lst
also contained any of the following [-1, True, "X", 0.00001]
(all of which evaluate to True
) then any(lst)
would be True
.
In the code you posted, x > 0 for x in lst
, this is a different kind of iterable, called a generator expression. Before generator expressions were added to Python, you would have created a list comprehension, which looks very similar, but with surrounding []
's: [x > 0 for x in lst]
. From the lst
containing [-1, -2, 10, -4, 20]
, you would get this comprehended list: [False, False, True, False, True]
. This internal value would then get passed to the any
function, which would return True
, since there is at least one True
value.
But with generator expressions, Python no longer has to create that internal list of True(s)
and False(s)
, the values will be generated as the any
function iterates through the values generated one at a time by the generator expression. And, since any
short-circuits, it will stop iterating as soon as it sees the first True
value. This would be especially handy if you created lst
using something like lst = range(-1,int(1e9))
(or xrange
if you are using Python2.x). Even though this expression will generate over a billion entries, any
only has to go as far as the third entry when it gets to 1
, which evaluates True
for x>0
, and so any
can return True
.
If you had created a list comprehension, Python would first have had to create the billion-element list in memory, and then pass that to any
. But by using a generator expression, you can have Python's builtin functions like any
and all
break out early, as soon as a True
or False
value is seen.
Get an object attribute
Use getattr
if you have an attribute in string form:
>>> class User(object):
name = 'John'
>>> u = User()
>>> param = 'name'
>>> getattr(u, param)
'John'
Otherwise use the dot .
:
>>> class User(object):
name = 'John'
>>> u = User()
>>> u.name
'John'
How do I use tools:overrideLibrary in a build.gradle file?
it doesn't matter that you declare your minSdk in build.gradle. You have to copy overrideLibrary
in your AndroidManifest.xml
, as documented here.
<manifest
... >
<uses-sdk tools:overrideLibrary="com.example.lib1, com.example.lib2"/>
...
</manifest>
The system automatically ignores the sdkVersion declared in AndroidManifest.xml.
I hope this solve your problem.
How to run a single RSpec test?
There are many options:
rspec spec # All specs
rspec spec/models # All specs in the models directory
rspec spec/models/a_model_spec.rb # All specs in the some_model model spec
rspec spec/models/a_model_spec.rb:nn # Run the spec that includes line 'nn'
rspec -e"text from a test" # Runs specs that match the text
rspec spec --tag focus # Runs specs that have :focus => true
rspec spec --tag focus:special # Run specs that have :focus => special
rspec spec --tag focus ~skip # Run tests except those with :focus => true
SQL Server: Null VS Empty String
Be careful with nulls and checking for inequality in sql server.
For example
select * from foo where bla <> 'something'
will NOT return records where bla is null. Even though logically it should.
So the right way to check would be
select * from foo where isnull(bla,'') <> 'something'
Which of course people often forget and then get weird bugs.
Move div to new line
What about something like this.
<div id="movie_item">
<div class="movie_item_poster">
<img src="..." style="max-width: 100%; max-height: 100%;">
</div>
<div id="movie_item_content">
<div class="movie_item_content_year">year</div>
<div class="movie_item_content_title">title</div>
<div class="movie_item_content_plot">plot</div>
</div>
<div class="movie_item_toolbar">
Lorem Ipsum...
</div>
</div>
You don't have to float both movie_item_poster
AND movie_item_content
. Just float one of them...
#movie_item {
position: relative;
margin-top: 10px;
height: 175px;
}
.movie_item_poster {
float: left;
height: 150px;
width: 100px;
}
.movie_item_content {
position: relative;
}
.movie_item_content_title {
}
.movie_item_content_year {
float: right;
}
.movie_item_content_plot {
}
.movie_item_toolbar {
clear: both;
vertical-align: bottom;
width: 100%;
height: 25px;
}
Here it is as a JSFiddle.
How do you split and unsplit a window/view in Eclipse IDE?
This is possible with the menu items Window>Editor>Toggle Split Editor.
Current shortcut for splitting is:
Azerty keyboard:
- Ctrl + _ for split horizontally, and
- Ctrl + { for split vertically.
Qwerty US keyboard:
- Ctrl + Shift + - (accessing _) for split horizontally, and
- Ctrl + Shift + [ (accessing {) for split vertically.
MacOS - Qwerty US keyboard:
- ⌘ + Shift + - (accessing _) for split horizontally, and
- ⌘ + Shift + [ (accessing {) for split vertically.
On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:
- Alt + ASCII code + Ctrl then release Alt
Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.
Example of vertical split:
PS:
- The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
- The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
- The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.
Why is "using namespace std;" considered bad practice?
Do not use it globally
It is considered "bad" only when used globally. Because:
- You clutter the namespace you are programming in.
- Readers will have difficulty seeing where a particular identifier comes from, when you use many
using namespace xyz
.
- Whatever is true for other readers of your source code is even more true for the most frequent reader of it: yourself. Come back in a year or two and take a look...
- If you only talk about
using namespace std
you might not be aware of all the stuff you grab -- and when you add another #include
or move to a new C++ revision you might get name conflicts you were not aware of.
You may use it locally
Go ahead and use it locally (almost) freely. This, of course, prevents you from repetition of std::
-- and repetition is also bad.
An idiom for using it locally
In C++03 there was an idiom -- boilerplate code -- for implementing a swap
function for your classes. It was suggested that you actually use a local using namespace std
-- or at least using std::swap
:
class Thing {
int value_;
Child child_;
public:
// ...
friend void swap(Thing &a, Thing &b);
};
void swap(Thing &a, Thing &b) {
using namespace std; // make `std::swap` available
// swap all members
swap(a.value_, b.value_); // `std::stwap(int, int)`
swap(a.child_, b.child_); // `swap(Child&,Child&)` or `std::swap(...)`
}
This does the following magic:
- The compiler will choose the
std::swap
for value_
, i.e. void std::swap(int, int)
.
- If you have an overload
void swap(Child&, Child&)
implemented the compiler will choose it.
- If you do not have that overload the compiler will use
void std::swap(Child&,Child&)
and try its best swapping these.
With C++11 there is no reason to use this pattern any more. The implementation of std::swap
was changed to find a potential overload and choose it.
How to calculate number of days between two dates
http://momentjs.com/ or https://date-fns.org/
From Moment docs:
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // =1
or to include the start:
a.diff(b, 'days')+1 // =2
Beats messing with timestamps and time zones manually.
Depending on your specific use case, you can either
- Use
a/b.startOf('day')
and/or a/b.endOf('day')
to force the diff to be inclusive or exclusive at the "ends" (as suggested by @kotpal in the comments).
- Set third argument
true
to get a floating point diff which you can then Math.floor
, Math.ceil
or Math.round
as needed.
- Option 2 can also be accomplished by getting
'seconds'
instead of 'days'
and then dividing by 24*60*60
.
Getting results between two dates in PostgreSQL
No offense but to check for performance of sql I executed some of the above mentioned solutiona pgsql.
Let me share you Statistics of top 3 solution approaches that I come across.
1) Took : 1.58 MS Avg
2) Took : 2.87 MS Avg
3) Took : 3.95 MS Avg
Now try this :
SELECT * FROM table WHERE DATE_TRUNC('day', date ) >= Start Date AND DATE_TRUNC('day', date ) <= End Date
Now this solution took : 1.61 Avg.
And best solution is 1st that suggested by marco-mariani
Can't load IA 32-bit .dll on a AMD 64-bit platform
I had a problem when run red5(tomcat) on Windows x64 that previous worked under Windows x32, got next error:
INFO pool-15-thread-1 com.home.launcher.CommandLauncher - Exception in thread "main" java.lang.UnsatisfiedLinkError: C:\....\lib\Data Samolet.dll: Can't find dependent libraries
INFO pool-15-thread-1 com.home.launcher.CommandLauncher - at java.lang.ClassLoader$NativeLibrary.load(Native Method)
Problem solved when I installed Java x32 version and set next
"Environment variables"
"User variables for Home"
JAVA_HOME => C:\Program Files (x86)\Java\jdk.1.6.0_45
"System variables"
Path[at the beginning] => C:\Program Files\Java\jdk.1.8.0_60;..
What does "hashable" mean in Python?
In my understanding according to Python glossary, when you create a instance of objects that are hashable, an unchangeable value is also calculated according to the members or values of the instance.
For example, that value could then be used as a key in a dict as below:
>>> tuple_a = (1,2,3)
>>> tuple_a.__hash__()
2528502973977326415
>>> tuple_b = (2,3,4)
>>> tuple_b.__hash__()
3789705017596477050
>>> tuple_c = (1,2,3)
>>> tuple_c.__hash__()
2528502973977326415
>>> id(a) == id(c) # a and c same object?
False
>>> a.__hash__() == c.__hash__() # a and c same value?
True
>>> dict_a = {}
>>> dict_a[tuple_a] = 'hiahia'
>>> dict_a[tuple_c]
'hiahia'
we can find that the hash value of tuple_a and tuple_c are the same since they have the same members.
When we use tuple_a as the key in dict_a, we can find that the value for dict_a[tuple_c] is the same, which means that, when they are used as the key in a dict, they return the same value because the hash values are the same.
For those objects that are not hashable, the method hash is defined as None:
>>> type(dict.__hash__)
<class 'NoneType'>
I guess this hash value is calculated upon the initialization of the instance, not in a dynamic way, that's why only immutable objects are hashable. Hope this helps.
Why does IE9 switch to compatibility mode on my website?
The site at http://www.HTML-5.com/index.html does have the X-UA-Compatible meta tag but still goes into Compatibility View as indicated by the "torn page" icon in the address bar. How do you get the menu option to force IE 9 (Final Version 9.0.8112.16421) to render a page in Standards Mode? I tried right clicking that torn page icon as well as the "Alt" key trick to display the additional menu options mentioned by Rene Geuze, but those didn't work.
How do you make div elements display inline?
Having read this question and the answers a couple of times, all I can do is assume that there's been quite a bit of editing going on, and my suspicion is that you've been given the incorrect answer based on not providing enough information. My clue comes from the use of br
tag.
Apologies to Darryl. I read class="inline" as style="display: inline". You have the right answer, even if you do use semantically questionable class names ;-)
The miss use of br
to provide structural layout rather than for textual layout is far too prevalent for my liking.
If you're wanting to put more than inline elements inside those divs
then you should be floating those div
s rather than making them inline.
Floated divs:
===== ======= == **** ***** ****** +++++ ++++
===== ==== ===== ******** ***** ** ++ +++++++
=== ======== === ******* **** ****
===== ==== ===== +++++++ ++
====== == ======
Inline divs:
====== ==== ===== ===== == ==== *** ******* ***** *****
**** ++++ +++ ++ ++++ ++ +++++++ +++ ++++
If you're after the former, then this is your solution and lose those br
tags:
<div style="float: left;" >
<p>block level content or <span>inline content</span>.</p>
<p>block level content or <span>inline content</span>.</p>
</div>
<div style="float: left;" >
<p>block level content or <span>inline content</span>.</p>
<p>block level content or <span>inline content</span>.</p>
</div>
<div style="float: left;" >
<p>block level content or <span>inline content</span>.</p>
<p>block level content or <span>inline content</span>.</p>
</div>
note that the width of these divs is fluid, so feel free to put widths on them if you want to control the behavior.
Thanks,
Steve
Java for loop multiple variables
Your for
loop is malformed — it can't take 4 arguments, and you can't combine two with ;
as you did.
Use:
for(int a = 0, b = 1; a<cards.length-1; a++)
add scroll bar to table body
This is because you are adding your <tbody>
tag before <td>
in table you cannot print any data without <td>
.
So for that you have to make a <div>
say #header
with position: fixed;
header
{
position: fixed;
}
make another <div>
which will act as <tbody>
tbody
{
overflow:scroll;
}
Now your header is fixed and the body will scroll. And the header will remain there.
Angular CLI - Please add a @NgModule annotation when using latest
In my case, I created a new ChildComponent in Parentcomponent whereas both in the same module but Parent is registered in a shared module so I created ChildComponent using CLI which registered Child in the current module but my parent was registered in the shared module.
So register the ChildComponent in Shared Module manually.
NSDate get year/month/day
If you are targeting iOS 8+ you can use the new NSCalendar
convenience methods to achieve this in a more terse format.
First create an NSCalendar
and use whatever NSDate
is required.
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *date = [NSDate date];
You could extract components individually via component:fromDate:
NSInteger year = [calendar component:NSCalendarUnitYear fromDate:date];
NSInteger month = [calendar component:NSCalendarUnitMonth fromDate:date];
NSInteger day = [calendar component:NSCalendarUnitDay fromDate:date];
Or, even more succinctly, use NSInteger
pointers via getEra:year:month:day:fromDate:
NSInteger year, month, day;
[calendar getEra:nil year:&year month:&month day:&day fromDate:date];
For more information and examples check out NSDate Manipulation Made Easy in iOS 8. Disclaimer, I wrote the post.
origin 'http://localhost:4200' has been blocked by CORS policy in Angular7
If you are using spring-boot for server side coding then please add a servlet filter and add the following code of your spring-boot application. It should work. Adding "Access-Control-Allow-Headers", "*"
is mandatory. Creation of proxy.conf.json is not needed.
@Component
@Order(1)
public class MyProjectFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Access-Control-Allow-Methods", "GET,POST,PATCH,DELETE,PUT,OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Max-Age", "86400");
chain.doFilter(req, res);
}
}
Running code after Spring Boot starts
Use a SmartInitializingSingleton
bean in spring > 4.1
@Bean
public SmartInitializingSingleton importProcessor() {
return () -> {
doStuff();
};
}
As alternative a CommandLineRunner
bean can be implemented or annotating a bean method with @PostConstruct
.
Using Keras & Tensorflow with AMD GPU
This is an old question, but since I spent the last few weeks trying to figure it out on my own:
- OpenCL support for Theano is hit and miss. They added a libgpuarray back-end which appears to still be buggy (i.e., the process runs on the GPU but the answer is wrong--like 8% accuracy on MNIST for a DL model that gets ~95+% accuracy on CPU or nVidia CUDA). Also because ~50-80% of the performance boost on the nVidia stack comes from the CUDNN libraries now, OpenCL will just be left in the dust. (SEE BELOW!) :)
- ROCM appears to be very cool, but the documentation (and even a clear declaration of what ROCM is/what it does) is hard to understand. They're doing their best, but they're 4+ years behind. It does NOT NOT NOT work on an RX550 (as of this writing). So don't waste your time (this is where 1 of the weeks went :) ). At first, it appears ROCM is a new addition to the driver set (replacing AMDGPU-Pro, or augmenting it), but it is in fact a kernel module and set of libraries that essentially replace AMDGPU-Pro. (Think of this as the equivalent of Nvidia-381 driver + CUDA some libraries kind of). https://rocm.github.io/dl.html (Honestly I still haven't tested the performance or tried to get it to work with more recent Mesa drivers yet. I will do that sometime.
- Add MiOpen to ROCM, and that is essentially CUDNN. They also have some pretty clear guides for migrating. But better yet.
- They created "HIP" which is an automagical translator from CUDA/CUDNN to MiOpen. It seems to work pretty well since they lined the API's up directly to be translatable. There are concepts that aren't perfect maps, but in general it looks good.
Now, finally, after 3-4 weeks of trying to figure out OpenCL, etc, I found this tutorial to help you get started quickly. It is a step-by-step for getting hipCaffe up and running. Unlike nVidia though,
please ensure you have supported hardware!!!! https://rocm.github.io/hardware.html. Think you can get it working without their supported hardware? Good luck. You've been warned. Once you have ROCM up and running (AND RUN THE VERIFICATION TESTS), here is the hipCaffe tutorial--if you got ROCM up you'll be doing an MNIST validation test within 10 minutes--sweet!
https://rocm.github.io/ROCmHipCaffeQuickstart.html
How to determine whether a given Linux is 32 bit or 64 bit?
I was wondering about this specifically for building software in Debian (the installed Debian system can be a 32-bit version with a 32 bit kernel, libraries, etc., or it can be a 64-bit version with stuff compiled for the 64-bit rather than 32-bit compatibility mode).
Debian packages themselves need to know what architecture they are for (of course) when they actually create the package with all of its metadata, including platform architecture, so there is a packaging tool that outputs it for other packaging tools and scripts to use, called dpkg-architecture. It includes both what it's configured to build for, as well as the current host. (Normally these are the same though.) Example output on a 64-bit machine:
DEB_BUILD_ARCH=amd64
DEB_BUILD_ARCH_OS=linux
DEB_BUILD_ARCH_CPU=amd64
DEB_BUILD_GNU_CPU=x86_64
DEB_BUILD_GNU_SYSTEM=linux-gnu
DEB_BUILD_GNU_TYPE=x86_64-linux-gnu
DEB_HOST_ARCH=amd64
DEB_HOST_ARCH_OS=linux
DEB_HOST_ARCH_CPU=amd64
DEB_HOST_GNU_CPU=x86_64
DEB_HOST_GNU_SYSTEM=linux-gnu
DEB_HOST_GNU_TYPE=x86_64-linux-gnu
You can print just one of those variables or do a test against their values with command line options to dpkg-architecture.
I have no idea how dpkg-architecture deduces the architecture, but you could look at its documentation or source code (dpkg-architecture and much of the dpkg system in general are Perl).
Brew install docker does not include docker engine?
The following steps work fine on macOS Sierra 10.12.4. Note that after brew installs Docker, the docker
command (symbolic link) is not available at /usr/local/bin
. Running the Docker app for the first time creates this symbolic link. See the detailed steps below.
Install Docker.
brew cask install docker
Launch Docker.
- Press ? + Space to bring up Spotlight Search and enter
Docker
to launch Docker.
- In the Docker needs privileged access dialog box, click OK.
- Enter password and click OK.
When Docker is launched in this manner, a Docker whale icon appears in the status menu. As soon as the whale icon appears, the symbolic links for docker
, docker-compose
, docker-credential-osxkeychain
and docker-machine
are created in /usr/local/bin
.
$ ls -l /usr/local/bin/docker*
lrwxr-xr-x 1 susam domain Users 67 Apr 12 14:14 /usr/local/bin/docker -> /Users/susam/Library/Group Containers/group.com.docker/bin/docker
lrwxr-xr-x 1 susam domain Users 75 Apr 12 14:14 /usr/local/bin/docker-compose -> /Users/susam/Library/Group Containers/group.com.docker/bin/docker-compose
lrwxr-xr-x 1 susam domain Users 90 Apr 12 14:14 /usr/local/bin/docker-credential-osxkeychain -> /Users/susam/Library/Group Containers/group.com.docker/bin/docker-credential-osxkeychain
lrwxr-xr-x 1 susam domain Users 75 Apr 12 14:14 /usr/local/bin/docker-machine -> /Users/susam/Library/Group Containers/group.com.docker/bin/docker-machine
Click on the docker whale icon in the status menu and wait for it to show Docker is running.
Test that docker works fine.
$ docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
78445dd45222: Pull complete
Digest: sha256:c5515758d4c5e1e838e9cd307f6c6a0d620b5e07e6f927b07d05f6d12a1ac8d7
Status: Downloaded newer image for hello-world:latest
Hello from Docker!
This message shows that your installation appears to be working correctly.
To generate this message, Docker took the following steps:
1. The Docker client contacted the Docker daemon.
2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
3. The Docker daemon created a new container from that image which runs the
executable that produces the output you are currently reading.
4. The Docker daemon streamed that output to the Docker client, which sent it
to your terminal.
To try something more ambitious, you can run an Ubuntu container with:
$ docker run -it ubuntu bash
Share images, automate workflows, and more with a free Docker ID:
https://cloud.docker.com/
For more examples and ideas, visit:
https://docs.docker.com/engine/userguide/
$ docker version
Client:
Version: 17.03.1-ce
API version: 1.27
Go version: go1.7.5
Git commit: c6d412e
Built: Tue Mar 28 00:40:02 2017
OS/Arch: darwin/amd64
Server:
Version: 17.03.1-ce
API version: 1.27 (minimum version 1.12)
Go version: go1.7.5
Git commit: c6d412e
Built: Fri Mar 24 00:00:50 2017
OS/Arch: linux/amd64
Experimental: true
If you are going to use docker-machine
to create virtual machines, install VirtualBox.
brew cask install virtualbox
Note that if VirtualBox is not installed, then docker-machine
fails with the following error.
$ docker-machine create manager
Running pre-create checks...
Error with pre-create check: "VBoxManage not found. Make sure VirtualBox is installed and VBoxManage is in the path"
How to "properly" print a list?
Using .format
for string formatting,
mylist = ['x', 3, 'b']
print("[{0}]".format(', '.join(map(str, mylist))))
Output:
[x, 3, b]
Explanation:
map
is used to map each element of the list to string
type.
- The elements are joined together into a string with
,
as separator.
- We use
[
and ]
in the print statement to show the list braces.
Reference:
.format
for string formatting PEP-3101
How to add \newpage in Rmarkdown in a smart way?
Simply \newpage
or \pagebreak
will work, e.g.
hello world
\newpage
```{r, echo=FALSE}
1+1
```
\pagebreak
```{r, echo=FALSE}
plot(1:10)
```
This solution assumes you are knitting PDF. For HTML, you can achieve a similar effect by adding a tag <P style="page-break-before: always">
. Note that you likely won't see a page break in your browser (HTMLs don't have pages per se), but the printing layout will have it.
Download text/csv content as files from server in Angular
This is what worked for me for IE 11+, Firefox and Chrome. In safari it downloads a file but as unknown and the filename is not set.
if (window.navigator.msSaveOrOpenBlob) {
var blob = new Blob([csvDataString]); //csv data string as an array.
// IE hack; see http://msdn.microsoft.com/en-us/library/ie/hh779016.aspx
window.navigator.msSaveBlob(blob, fileName);
} else {
var anchor = angular.element('<a/>');
anchor.css({display: 'none'}); // Make sure it's not visible
angular.element(document.body).append(anchor); // Attach to document for FireFox
anchor.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURI(csvDataString),
target: '_blank',
download: fileName
})[0].click();
anchor.remove();
}
Finding common rows (intersection) in two Pandas dataframes
In SQL, this problem could be solved by several methods:
select * from df1 where exists (select * from df2 where df2.user_id = df1.user_id)
union all
select * from df2 where exists (select * from df1 where df1.user_id = df2.user_id)
or join and then unpivot (possible in SQL server)
select
df1.user_id,
c.rating
from df1
inner join df2 on df2.user_i = df1.user_id
outer apply (
select df1.rating union all
select df2.rating
) as c
Second one could be written in pandas with something like:
>>> df1 = pd.DataFrame({"user_id":[1,2,3], "rating":[10, 15, 20]})
>>> df2 = pd.DataFrame({"user_id":[3,4,5], "rating":[30, 35, 40]})
>>>
>>> df4 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df = pd.merge(df1, df2, on='user_id', suffixes=['_1', '_2'])
>>> df3 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df4 = df[['user_id', 'rating_2']].rename(columns={'rating_2':'rating'})
>>> pd.concat([df3, df4], axis=0)
user_id rating
0 3 20
0 3 30
Output (echo/print) everything from a PHP Array
If you want to format the output on your own, simply add another loop (foreach) to iterate through the contents of the current row:
while ($row = mysql_fetch_array($result)) {
foreach ($row as $columnName => $columnData) {
echo 'Column name: ' . $columnName . ' Column data: ' . $columnData . '<br />';
}
}
Or if you don't care about the formatting, use the print_r function recommended in the previous answers.
while ($row = mysql_fetch_array($result)) {
echo '<pre>';
print_r ($row);
echo '</pre>';
}
print_r() prints only the keys and values of the array, opposed to var_dump() whichs also prints the types of the data in the array, i.e. String, int, double, and so on. If you do care about the data types - use var_dump() over print_r().
npm install gives error "can't find a package.json file"
>> For Visual Studio Users using Package Manager Console <<
If you are using the Package Manager Console in Visual Studio and you want to execute:
npm install
and get:
ENOENT: no such file or directory, open
'C:\Users...\YourProject\package.json'
Verify that you are executing the command in the correct directory.
VS by default uses the solution folder when opening the Package Manager Console.
Execute dir
then you can see in which folder you currently are. Most probably in the solution folder, that's why you get this error.
Now you have to cd
to your project folder.
cd YourWebProject
Now npm install
should work now, if not, then you have another issue.
LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup
Because it hasn't been mentioned yet, this was the solution for me:
I had this error with a DLL after creating a new configuration for my project. I had to go to Project Properties -> Configuration Properties -> General
and change the Configuration Type
to Dynamic Library (.dll)
.
So if you're still having trouble after trying everything else, it's worth checking to see if the configuration type is what you expect for your project. If it's not set correctly, the compiler will be looking for the wrong main symbol. In my case, it was looking for WinMain
instead of DllMain
.
Windows equivalent of the 'tail' command
FWIW, for those just needing to snip off an indeterminate number of records from the head of the file, more > works well. This is useful just to have a smaller file to work with in the early stages of developing something.
How to enable CORS on Firefox?
I was stucked with this problem for a long time (CORS does not work in FF, but works in Chrome and others). No advice could help. Finally, i found that my local dev subdomain (like sub.example.dev) was not explicitly mentioned in /etc/hosts, thus FF just is not able to find it and shows confusing error message 'Aborted...' in dev tools panel.
Putting the exact subdomain into my local /etc/hosts fixed the problem. /etc/hosts is just a plain-text file in unix systems, so you can open it under the root user and put your subdomain in front of '127.0.0.1' ip address.
How to Correctly Check if a Process is running and Stop it
Thanks @Joey. It's what I am looking for.
I just bring some improvements:
- to take into account multiple processes
- to avoid reaching the timeout when all processes have terminated
- to package the whole in a function
function Stop-Processes {
param(
[parameter(Mandatory=$true)] $processName,
$timeout = 5
)
$processList = Get-Process $processName -ErrorAction SilentlyContinue
if ($processList) {
# Try gracefully first
$processList.CloseMainWindow() | Out-Null
# Wait until all processes have terminated or until timeout
for ($i = 0 ; $i -le $timeout; $i ++){
$AllHaveExited = $True
$processList | % {
$process = $_
If (!$process.HasExited){
$AllHaveExited = $False
}
}
If ($AllHaveExited){
Return
}
sleep 1
}
# Else: kill
$processList | Stop-Process -Force
}
}
ArrayList: how does the size increase?
Lets look at this code (jdk1.8)
@Test
public void testArraySize() throws Exception {
List<String> list = new ArrayList<>();
list.add("ds");
list.add("cx");
list.add("cx");
list.add("ww");
list.add("ds");
list.add("cx");
list.add("cx");
list.add("ww");
list.add("ds");
list.add("cx");
list.add("last");
}
1)Put break point on the line when "last" is inserted
2)Go to the add method of ArrayList
You will see
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
3) Go to ensureCapacityInternal method this method call ensureExplicitCapacity
4)
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
return true;
In our example minCapacity is equal to 11 11-10 > 0
therefore You need grow
method
5)
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
Lets describe each step:
1) oldCapacity
= 10 because we didn't put this param when ArrayList
was init ,therefore it will use default capacity(10)
2) int newCapacity = oldCapacity + (oldCapacity >> 1);
Here newCapacity is equal to oldCapacity plus oldCapacity with right shift by one
(oldCapacity is 10
this is the binary representation 00001010
moving one bit to right we will get 00000101
which is 5 in decimal therefore newCapacity
is 10 + 5 = 15
)
3)
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
For example your init capacity is 1, when you add the second element into arrayList newCapacity
will be equal to 1(oldCapacity) + 0 (moved to right by one bit) = 1
In this case newCapacity is less than minCapacity and elementData
(array object inside arrayList) can't hold new element therefore newCapacity is equal to minCapacity
4)
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
Check if array size reach MAX_ARRAY_SIZE (which is Integer.MAX - 8) Why the maximum array size of ArrayList is Integer.MAX_VALUE - 8?
5) Finally it copy old values to the newArray with length 15
SQL left join vs multiple tables on FROM line?
Well the first and second queries may yield different results because a LEFT JOIN includes all records from the first table, even if there are no corresponding records in the right table.
Add shadow to custom shape on Android
I would suggest a small improvement to Bruce's solution which is to prevent overdrawing the same shape on top of each other and to simply use stroke instead of solid.
It would look like this:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Drop Shadow Stack -->
<item>
<shape>
<padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
<stroke android:color="#02000000" android:width="1dp" />
<corners android:radius="8dp" />
</shape>
</item>
<item>
<shape>
<padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
<stroke android:color="#05000000" android:width="1dp" />
<corners android:radius="7dp" />
</shape>
</item>
<item>
<shape>
<padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
<stroke android:color="#10000000" android:width="1dp" />
<corners android:radius="6dp" />
</shape>
</item>
<item>
<shape>
<padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
<stroke android:color="#15000000" android:width="1dp" />
<corners android:radius="5dp" />
</shape>
</item>
<item>
<shape>
<padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
<stroke android:color="#20000000" android:width="1dp" />
<corners android:radius="4dp" />
</shape>
</item>
<item>
<shape>
<padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
<stroke android:color="#25000000" android:width="1dp" />
<corners android:radius="3dp" />
</shape>
</item>
<item>
<shape>
<padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
<stroke android:color="#30000000" android:width="1dp" />
<corners android:radius="3dp" />
</shape>
</item>
<!-- Background -->
<item>
<shape>
<solid android:color="#FFF" />
<corners android:radius="3dp" />
</shape>
</item>
</layer-list>
Lastly I wanted to point out for people who would like a shadow in a specific direction that all you have to do is set the top, bottom, left or right to 0dp (for a solid line) or -1dp (for nothing)
What exactly does the T and Z mean in timestamp?
The T
doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.
The Z
stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).
Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime()
method. You could have used Q
or M
or Monty Python
and the method would have returned them unchanged as well; the method only looks for patterns starting with %
to replace those with information from the datetime
object.
How to find first element of array matching a boolean condition in JavaScript?
Summary:
- For finding the first element in an array which matches a boolean condition we can use the
ES6
find()
find()
is located on Array.prototype
so it can be used on every array.
find()
takes a callback where a boolean
condition is tested. The function returns the value (not the index!)
Example:
_x000D_
_x000D_
const array = [4, 33, 8, 56, 23];
const found = array.find(element => {
return element > 50;
});
console.log(found); // 56
_x000D_
_x000D_
_x000D_
How to pad a string with leading zeros in Python 3
I suggest this ugly method but it works:
length = 1
lenghtafterpadding = 3
newlength = '0' * (lenghtafterpadding - len(str(length))) + str(length)
I came here to find a lighter solution than this one!
OSError: [Errno 8] Exec format error
OSError: [Errno 8] Exec format error
can happen if there is no shebang line at the top of the shell script and you are trying to execute the script directly. Here's an example that reproduces the issue:
>>> with open('a','w') as f: f.write('exit 0') # create the script
...
>>> import os
>>> os.chmod('a', 0b111101101) # rwxr-xr-x make it executable
>>> os.execl('./a', './a') # execute it
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/os.py", line 312, in execl
execv(file, args)
OSError: [Errno 8] Exec format error
To fix it, just add the shebang e.g., if it is a shell script; prepend #!/bin/sh
at the top of your script:
>>> with open('a','w') as f: f.write('#!/bin/sh\nexit 0')
...
>>> os.execl('./a', './a')
It executes exit 0
without any errors.
On POSIX systems, shell parses the command line i.e., your script won't see spaces around =
e.g., if script
is:
#!/usr/bin/env python
import sys
print(sys.argv)
then running it in the shell:
$ /usr/local/bin/script hostname = '<hostname>' -p LONGLIST
produces:
['/usr/local/bin/script', 'hostname', '=', '<hostname>', '-p', 'LONGLIST']
Note: no spaces around '='
. I've added quotes around <hostname>
to escape the redirection metacharacters <>
.
To emulate the shell command in Python, run:
from subprocess import check_call
cmd = ['/usr/local/bin/script', 'hostname', '=', '<hostname>', '-p', 'LONGLIST']
check_call(cmd)
Note: no shell=True
. And you don't need to escape <>
because no shell is run.
"Exec format error"
might indicate that your script
has invalid format, run:
$ file /usr/local/bin/script
to find out what it is. Compare the architecture with the output of:
$ uname -m
How do I get video durations with YouTube API version 3?
This code extracts the YouTube video duration using the YouTube API v3 by passing a video ID. It worked for me.
<?php
function getDuration($videoID){
$apikey = "YOUR-Youtube-API-KEY"; // Like this AIcvSyBsLA8znZn-i-aPLWFrsPOlWMkEyVaXAcv
$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$videoID&key=$apikey");
$VidDuration =json_decode($dur, true);
foreach ($VidDuration['items'] as $vidTime)
{
$VidDuration= $vidTime['contentDetails']['duration'];
}
preg_match_all('/(\d+)/',$VidDuration,$parts);
return $parts[0][0] . ":" .
$parts[0][1] . ":".
$parts[0][2]; // Return 1:11:46 (i.e.) HH:MM:SS
}
echo getDuration("zyeubYQxHyY"); // Video ID
?>
You can get your domain's own YouTube API key on https://console.developers.google.com and generate credentials for your own requirement.
Organizing a multiple-file Go project
Let's explorer how the go get repository_remote_url
command manages the project structure under $GOPATH
. If we do a go get github.com/gohugoio/hugo
It will clone the repository under
$GOPATH/src/repository_remote/user_name/project_name
$GOPATH/src/github.com/gohugoio/hugo
This is a nice way to create your initial project path. Now let's explorer what are the project types out there and how their inner structures are organized. All golang projects in the community can be categorized under
Libraries
(no executable binaries)
Single Project
(contains only 1 executable binary)
Tooling Projects
(contains multiple executable binaries)
Generally golang project files can be packaged under any design principles such as DDD, POD
Most of the available go projects follows this Package Oriented Design
Package Oriented Design encourage the developer to keeps the implementation only inside it's own packages, other than the /internal
package those packages can't can communicate with each other
Libraries
- Projects such as database drivers, qt can put under this category.
- Some libraries such as color, now follows a flat structure without any other packages.
- Most of these library projects manages a package called internal.
/internal
package is mainly used to hide the implementation from other projects.
- Don't have any executable binaries, so no files that contains the main func.
~/$GOPATH/
bin/
pkg/
src/
repository_remote/
user_name/
project_name/
internal/
other_pkg/
Single Project
- Projects such as hugo, etcd has a single main func in root level and.
- Target is to generate one single binary
Tooling Projects
- Projects such as kubernetes, go-ethereum has multiple main func organized under a package called cmd
cmd/
package manages the number of binaries (tools) that we want to build
~/$GOPATH/
bin/
pkg/
src/
repository_remote/
user_name/
project_name/
cmd/
binary_one/
main.go
binary_two/
main.go
binary_three/
main.go
other_pkg/
android listview get selected item
final ListView lv = (ListView) findViewById(R.id.ListView01);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));
}
});
I hope this fixes your problem.
Convert DateTime to String PHP
Its worked for me
$start_time = date_create_from_format('Y-m-d H:i:s', $start_time);
$current_date = new DateTime();
$diff = $start_time->diff($current_date);
$aa = (string)$diff->format('%R%a');
echo gettype($aa);
Close popup window
Your web_window variable must have gone out of scope when you tried to close the window. Add this line into your _openpageview function to test:
setTimeout(function(){web_window.close();},1000);
java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed
Bump...
I just had the same error. I noticed that I was invoking super.doPost(request, response);
when overriding the doPost()
method as well as explicitly invoking the superclass constructor
public ScheduleServlet() {
super();
// TODO Auto-generated constructor stub
}
As soon as I commented out the super.doPost(request, response);
from within doPost()
statement it worked perfectly...
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//super.doPost(request, response);
// More code here...
}
Needless to say, I need to re-read on super()
best practices :p
jquery find class and get the value
You can also get the value by the following way
$(document).ready(function(){
$("#start").click(function(){
alert($(this).find("input[class='myClass']").val());
});
});
python save image from url
Python code snippet to download a file from an url and save with its name
import requests
url = 'http://google.com/favicon.ico'
filename = url.split('/')[-1]
r = requests.get(url, allow_redirects=True)
open(filename, 'wb').write(r.content)
How to write oracle insert script with one field as CLOB?
Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.
note I changed the varchar2(32000) to CLOB
set serveroutput ON
CREATE TABLE testclob
(
id NUMBER,
c CLOB,
d VARCHAR2(4000)
);
DECLARE
reallybigtextstring CLOB := '123';
i INT;
BEGIN
WHILE Length(reallybigtextstring) <= 60000 LOOP
reallybigtextstring := reallybigtextstring
|| '000000000000000000000000000000000';
END LOOP;
INSERT INTO testclob
(id,
c,
d)
VALUES (0,
reallybigtextstring,
'done');
dbms_output.Put_line('I have finished inputting your clob: '
|| Length(reallybigtextstring));
END;
/
SELECT *
FROM testclob;
"I have finished inputting your clob: 60030"
How do I delete files programmatically on Android?
File file=new File(getFilePath(imageUri.getValue()));
boolean b= file.delete();
not working in my case. The issue has been resolved by using below code-
ContentResolver contentResolver = getContentResolver ();
contentResolver.delete (uriDelete,null ,null );
Add a new line to the end of a JtextArea
Are you using JTextArea
's append(String)
method to add additional text?
JTextArea txtArea = new JTextArea("Hello, World\n", 20, 20);
txtArea.append("Goodbye Cruel World\n");
ubuntu "No space left on device" but there is tons of space
It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.
Try unmounting the overflow partition:
umount /tmp
or
umount overflow
javax.faces.application.ViewExpiredException: View could not be restored
When our page is idle for x amount of time the view will expire and throw javax.faces.application.ViewExpiredException to prevent this from happening
one solution is to create CustomViewHandler that extends ViewHandler
and override restoreView method all the other methods are being delegated to the Parent
import java.io.IOException;
import javax.faces.FacesException;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
public class CustomViewHandler extends ViewHandler {
private ViewHandler parent;
public CustomViewHandler(ViewHandler parent) {
//System.out.println("CustomViewHandler.CustomViewHandler():Parent View Handler:"+parent.getClass());
this.parent = parent;
}
@Override
public UIViewRoot restoreView(FacesContext facesContext, String viewId) {
/**
* {@link javax.faces.application.ViewExpiredException}. This happens only when we try to logout from timed out pages.
*/
UIViewRoot root = null;
root = parent.restoreView(facesContext, viewId);
if(root == null) {
root = createView(facesContext, viewId);
}
return root;
}
@Override
public Locale calculateLocale(FacesContext facesContext) {
return parent.calculateLocale(facesContext);
}
@Override
public String calculateRenderKitId(FacesContext facesContext) {
String renderKitId = parent.calculateRenderKitId(facesContext);
//System.out.println("CustomViewHandler.calculateRenderKitId():RenderKitId: "+renderKitId);
return renderKitId;
}
@Override
public UIViewRoot createView(FacesContext facesContext, String viewId) {
return parent.createView(facesContext, viewId);
}
@Override
public String getActionURL(FacesContext facesContext, String actionId) {
return parent.getActionURL(facesContext, actionId);
}
@Override
public String getResourceURL(FacesContext facesContext, String resId) {
return parent.getResourceURL(facesContext, resId);
}
@Override
public void renderView(FacesContext facesContext, UIViewRoot viewId) throws IOException, FacesException {
parent.renderView(facesContext, viewId);
}
@Override
public void writeState(FacesContext facesContext) throws IOException {
parent.writeState(facesContext);
}
public ViewHandler getParent() {
return parent;
}
}
Then you need to add it to your faces-config.xml
<application>
<view-handler>com.demo.CustomViewHandler</view-handler>
</application>
Thanks for the original answer on the below link:
http://www.gregbugaj.com/?p=164
How do I create a round cornered UILabel on the iPhone?
Swift 3
If you want rounded label with background color, in addition to most of the other answers, you need to set layer
's background color as well. It does not work when setting view
background color.
label.layer.cornerRadius = 8
label.layer.masksToBounds = true
label.layer.backgroundColor = UIColor.lightGray.cgColor
If you are using auto layout, want some padding around the label and do not want to set the size of the label manually, you can create UILabel subclass and override intrinsincContentSize
property:
class LabelWithPadding: UILabel {
override var intrinsicContentSize: CGSize {
let defaultSize = super.intrinsicContentSize
return CGSize(width: defaultSize.width + 12, height: defaultSize.height + 8)
}
}
To combine the two you will also need to set label.textAlignment = center
, otherwise the text would be left aligned.
how to permit an array with strong parameters
If you have a hash structure like this:
Parameters: {"link"=>{"title"=>"Something", "time_span"=>[{"start"=>"2017-05-06T16:00:00.000Z", "end"=>"2017-05-06T17:00:00.000Z"}]}}
Then this is how I got it to work:
params.require(:link).permit(:title, time_span: [[:start, :end]])
Using the Underscore module with Node.js
As of today (April 30, 2012) you can use Underscore as usual on your Node.js code. Previous comments are right pointing that REPL interface (Node's command line mode) uses the "_" to hold the last result BUT on you are free to use it on your code files and it will work without a problem by doing the standard:
var _ = require('underscore');
Happy coding!
How to use && in EL boolean expressions in Facelets?
In addition to the answer of BalusC, use the following Java RegExp to replace &&
with and
:
Search: (#\{[^\}]*)(&&)([^\}]*\})
Replace: $1and$3
You have run this regular expression replacement multiple times to find all occurences in case you are using >2 literals in your EL expressions. Mind to replace the leading # by $ if your EL expression syntax differs.
Quadratic and cubic regression in Excel
I know that this question is a little old, but I thought that I would provide an alternative which, in my opinion, might be a little easier. If you're willing to add "temporary" columns to a data set, you can use Excel's Analysis ToolPak?Data Analysis?Regression. The secret to doing a quadratic or a cubic regression analysis is defining the Input X Range:.
If you're doing a simple linear regression, all you need are 2 columns, X & Y. If you're doing a quadratic, you'll need X_1, X_2, & Y where X_1 is the x variable and X_2 is x^2; likewise, if you're doing a cubic, you'll need X_1, X_2, X_3, & Y where X_1 is the x variable, X_2 is x^2 and X_3 is x^3. Notice how the Input X Range is from A1 to B22, spanning 2 columns.
The following image the output of the regression analysis. I've highlighted the common outputs, including the R-Squared values and all the coefficients.
Angularjs how to upload multipart form data and a file?
This is pretty must just a copy of that projects demo page and shows uploading a single file on form submit with upload progress.
(function (angular) {
'use strict';
angular.module('uploadModule', [])
.controller('uploadCtrl', [
'$scope',
'$upload',
function ($scope, $upload) {
$scope.model = {};
$scope.selectedFile = [];
$scope.uploadProgress = 0;
$scope.uploadFile = function () {
var file = $scope.selectedFile[0];
$scope.upload = $upload.upload({
url: 'api/upload',
method: 'POST',
data: angular.toJson($scope.model),
file: file
}).progress(function (evt) {
$scope.uploadProgress = parseInt(100.0 * evt.loaded / evt.total, 10);
}).success(function (data) {
//do something
});
};
$scope.onFileSelect = function ($files) {
$scope.uploadProgress = 0;
$scope.selectedFile = $files;
};
}
])
.directive('progressBar', [
function () {
return {
link: function ($scope, el, attrs) {
$scope.$watch(attrs.progressBar, function (newValue) {
el.css('width', newValue.toString() + '%');
});
}
};
}
]);
}(angular));
HTML
<form ng-submit="uploadFile()">
<div class="row">
<div class="col-md-12">
<input type="text" ng-model="model.fileDescription" />
<input type="number" ng-model="model.rating" />
<input type="checkbox" ng-model="model.isAGoodFile" />
<input type="file" ng-file-select="onFileSelect($files)">
<div class="progress" style="margin-top: 20px;">
<div class="progress-bar" progress-bar="uploadProgress" role="progressbar">
<span ng-bind="uploadProgress"></span>
<span>%</span>
</div>
</div>
<button button type="submit" class="btn btn-default btn-lg">
<i class="fa fa-cloud-upload"></i>
<span>Upload File</span>
</button>
</div>
</div>
</form>
EDIT: Added passing a model up to the server in the file post.
The form data in the input elements would be sent in the data property of the post and be available as normal form values.
Row count where data exists
This works for me. Returns the number that Excel displays in the bottom status line when a pivot
column
is filtered
and I need the count
of the visible cells
.
Global Const DashBoardSheet = "DashBoard"
Global Const ProfileColRng = "$L:$L"
.
.
.
Sub MySub()
Dim myreccnt as long
.
.
.
myreccnt = GetFilteredPivotRowCount(DashBoardSheet, ProfileColRng)
.
.
.
End Sub
Function GetFilteredPivotRowCount(sheetname As String, cntrange As String) As long
Dim reccnt As Long
reccnt = Sheets(sheetname).Range(cntrange).SpecialCells(xlCellTypeVisible).SpecialCells(xlCellTypeConstants).Count - 1
GetFilteredPivotRowCount = reccnt
End Function
Java inner class and static nested class
The Java programming language allows you to define a class within another class. Such a class is called a nested class and is illustrated here:
class OuterClass {
...
class NestedClass {
...
}
}
Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are called static nested classes. Non-static nested classes are called inner classes.
One thing that we should keep in mind is Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes only have access to other members of the enclosing class if those are static. It can not access non static members of the outer class.
As with class methods and variables, a static nested class is associated with its outer class.
For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject =
new OuterClass.StaticNestedClass();
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:
OuterClass.InnerClass innerObject = new OuterClass().new InnerClass();
Why we use nested classes
- It is a way of logically grouping classes that are only used in one place.
- It increases encapsulation.
- It can lead to more readable and maintainable code.
Source: The Java™ Tutorials - Nested Classes
Returning IEnumerable<T> vs. IQueryable<T>
A lot has been said previously, but back to the roots, in a more technical way:
IEnumerable
is a collection of objects in memory that you can enumerate - an in-memory sequence that makes it possible to iterate through (makes it way easy for within foreach
loop, though you can go with IEnumerator
only). They reside in the memory as is.
IQueryable
is an expression tree that will get translated into something else at some point with ability to enumerate over the final outcome. I guess this is what confuses most people.
They obviously have different connotations.
IQueryable
represents an expression tree (a query, simply) that will be translated to something else by the underlying query provider as soon as release APIs are called, like LINQ aggregate functions (Sum, Count, etc.) or ToList[Array, Dictionary,...]. And IQueryable
objects also implement IEnumerable
, IEnumerable<T>
so that if they represent a query the result of that query could be iterated. It means IQueryable don't have to be queries only. The right term is they are expression trees.
Now how those expressions are executed and what they turn to is all up to so called query providers (expression executors we can think them of).
In the Entity Framework world (which is that mystical underlying data source provider, or the query provider) IQueryable
expressions are translated into native T-SQL queries. Nhibernate
does similar things with them. You can write your own one following the concepts pretty well described in LINQ: Building an IQueryable Provider link, for example, and you might want to have a custom querying API for your product store provider service.
So basically, IQueryable
objects are getting constructed all the way long until we explicitly release them and tell the system to rewrite them into SQL or whatever and send down the execution chain for onward processing.
As if to deferred execution it's a LINQ
feature to hold up the expression tree scheme in the memory and send it into the execution only on demand, whenever certain APIs are called against the sequence (the same Count, ToList, etc.).
The proper usage of both heavily depends on the tasks you're facing for the specific case. For the well-known repository pattern I personally opt for returning IList
, that is IEnumerable
over Lists (indexers and the like). So it is my advice to use IQueryable
only within repositories and IEnumerable anywhere else in the code. Not saying about the testability concerns that IQueryable
breaks down and ruins the separation of concerns principle. If you return an expression from within repositories consumers may play with the persistence layer as they would wish.
A little addition to the mess :) (from a discussion in the comments))
None of them are objects in memory since they're not real types per se, they're markers of a type - if you want to go that deep. But it makes sense (and that's why even MSDN put it this way) to think of IEnumerables as in-memory collections whereas IQueryables as expression trees. The point is that the IQueryable interface inherits the IEnumerable interface so that if it represents a query, the results of that query can be enumerated. Enumeration causes the expression tree associated with an IQueryable object to be executed.
So, in fact, you can't really call any IEnumerable member without having the object in the memory. It will get in there if you do, anyways, if it's not empty. IQueryables are just queries, not the data.
How to select data from 30 days?
You should be using DATEADD
is Sql server so if try this simple select you will see the affect
Select DATEADD(Month, -1, getdate())
Result
2013-04-20 14:08:07.177
in your case try this query
SELECT name
FROM (
SELECT name FROM
Hist_answer
WHERE id_city='34324' AND datetime >= DATEADD(month,-1,GETDATE())
UNION ALL
SELECT name FROM
Hist_internet
WHERE id_city='34324' AND datetime >= DATEADD(month,-1,GETDATE())
) x
GROUP BY name ORDER BY name
Make a UIButton programmatically in Swift
Swift 4/5
let button = UIButton(frame: CGRect(x: 20, y: 20, width: 200, height: 60))
button.setTitle("Email", for: .normal)
button.backgroundColor = .white
button.setTitleColor(UIColor.black, for: .normal)
button.addTarget(self, action: #selector(self.buttonTapped), for: .touchUpInside)
myView.addSubview(button)
@objc func buttonTapped(sender : UIButton) {
//Write button action here
}
What is the meaning of {...this.props} in Reactjs
It's ES6 Spread_operator
and Destructuring_assignment
.
<div {...this.props}>
Content Here
</div>
It's equal to Class Component
const person = {
name: "xgqfrms",
age: 23,
country: "China"
};
class TestDemo extends React.Component {
render() {
const {name, age, country} = {...this.props};
// const {name, age, country} = this.props;
return (
<div>
<h3> Person Information: </h3>
<ul>
<li>name={name}</li>
<li>age={age}</li>
<li>country={country}</li>
</ul>
</div>
);
}
}
ReactDOM.render(
<TestDemo {...person}/>
, mountNode
);
or Function component
const props = {
name: "xgqfrms",
age: 23,
country: "China"
};
const Test = (props) => {
return(
<div
name={props.name}
age={props.age}
country={props.country}>
Content Here
<ul>
<li>name={props.name}</li>
<li>age={props.age}</li>
<li>country={props.country}</li>
</ul>
</div>
);
};
ReactDOM.render(
<div>
<Test {...props}/>
<hr/>
<Test
name={props.name}
age={props.age}
country={props.country}
/>
</div>
, mountNode
);
refs
Reading RFID with Android phones
A UHF RFID reader option for both Android and iOS is available from a company called U Grok It.
It is just UHF, which is "non-NFC enabled Android", if that's what you meant. My apologies if you meant an NFC reader for Android devices that don't have an NFC reader built-in.
Their reader has a range up to 7 meters (~21 feet). It connects via the audio port, not bluetooth, which has the advantage of pairing instantly, securely, and with way less of a power draw.
They have a free native SDK for Android, iOS, Cordova, and Xamarin, as well as an Android keyboard wedge.
Alternating Row Colors in Bootstrap 3 - No Table
There isn't really a way to do this without the css getting a little convoluted, but here's the cleanest solution I could put together (the breakpoints in this are just for example purposes, change them to whatever breakpoints you're actually using.) The key is :nth-of-type
(or :nth-child
-- either would work in this case.)
Smallest viewport:
@media (max-width:$smallest-breakpoint) {
.row div {
background: #eee;
}
.row div:nth-of-type(2n) {
background: #fff;
}
}
Medium viewport:
@media (min-width:$smallest-breakpoint) and (max-width:$mid-breakpoint) {
.row div {
background: #eee;
}
.row div:nth-of-type(4n+1), .row div:nth-of-type(4n+2) {
background: #fff;
}
}
Largest viewport:
@media (min-width:$mid-breakpoint) and (max-width:9999px) {
.row div {
background: #eee;
}
.row div:nth-of-type(6n+4),
.row div:nth-of-type(6n+5),
.row div:nth-of-type(6n+6) {
background: #fff;
}
}
Working fiddle here
How to create CSV Excel file C#?
I added ExportToStream so the csv didn't have to save to the hard drive first.
public Stream ExportToStream()
{
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(Export(true));
writer.Flush();
stream.Position = 0;
return stream;
}
How to use pip on windows behind an authenticating proxy
I had a similar issue, and found that my company uses NTLM proxy authentication. If you see this error in your pip.log, this is probably the issue:
Could not fetch URL http://pypi.python.org/simple/pyreadline: HTTP Error 407:
Proxy Authentication Required ( The ISA Server requires authorization to fulfill
the request. Access to the Web Proxy filter is denied. )
NTLMaps can be used to interface with the NTLM proxy server by becoming an intermediate proxy.
Download NTLMAPs, update the included server.cfg, run the main.py file, then point pip's proxy setting to 127.0.0.1:.
I also needed to change these default values in the server.cfg
file to:
LM_PART:1
NT_PART:1
# Highly experimental option. See research.txt for details.
# LM - 06820000
# NT - 05820000
# LM + NT -
NTLM_FLAGS: 07820000
http://ntlmaps.sourceforge.net/
HAX kernel module is not installed
Since most modern CPUs support virtualization natively, the reason you received such message can be because virtualization is turned off on your machine. For example, that was the case on my HP laptop - the factory setting for hardware virtualization was "Disabled". So, go to your machine's BIOS and enable virtualization.
C - casting int to char and append char to char
int myInt = 65;
char myChar = (char)myInt; // myChar should now be the letter A
char[20] myString = {0}; // make an empty string.
myString[0] = myChar;
myString[1] = myChar; // Now myString is "AA"
This should all be found in any intro to C book, or by some basic online searching.
Null & empty string comparison in Bash
First of all, note you are not using the variable correctly:
if [ "pass_tc11" != "" ]; then
# ^
# missing $
Anyway, to check if a variable is empty or not you can use -z
--> the string is empty:
if [ ! -z "$pass_tc11" ]; then
echo "hi, I am not empty"
fi
or -n
--> the length is non-zero:
if [ -n "$pass_tc11" ]; then
echo "hi, I am not empty"
fi
From man test
:
-z STRING
the length of STRING is zero
-n STRING
the length of STRING is nonzero
Samples:
$ [ ! -z "$var" ] && echo "yes"
$
$ var=""
$ [ ! -z "$var" ] && echo "yes"
$
$ var="a"
$ [ ! -z "$var" ] && echo "yes"
yes
$ var="a"
$ [ -n "$var" ] && echo "yes"
yes
Parsing Query String in node.js
node -v
v9.10.1
If you try to console log query object directly you will get error TypeError: Cannot convert object to primitive value
So I would suggest use JSON.stringify
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const path = parsedUrl.pathname, query = parsedUrl.query;
const method = req.method;
res.end("hello world\n");
console.log(`Request received on: ${path} + method: ${method} + query:
${JSON.stringify(query)}`);
console.log('query: ', query);
});
server.listen(3000, () => console.log("Server running at port 3000"));
So doing curl http://localhost:3000/foo\?fizz\=buzz
will return Request received on: /foo + method: GET + query: {"fizz":"buzz"}
How to parse JSON in Scala using standard Scala classes?
You can do like this! Very easy to parse JSON code :P
package org.sqkb.service.common.bean
import java.text.SimpleDateFormat
import org.json4s
import org.json4s.JValue
import org.json4s.jackson.JsonMethods._
//import org.sqkb.service.common.kit.{IsvCode}
import scala.util.Try
/**
*
*/
case class Order(log: String) {
implicit lazy val formats = org.json4s.DefaultFormats
lazy val json: json4s.JValue = parse(log)
lazy val create_time: String = (json \ "create_time").extractOrElse("1970-01-01 00:00:00")
lazy val site_id: String = (json \ "site_id").extractOrElse("")
lazy val alipay_total_price: Double = (json \ "alipay_total_price").extractOpt[String].filter(_.nonEmpty).getOrElse("0").toDouble
lazy val gmv: Double = alipay_total_price
lazy val pub_share_pre_fee: Double = (json \ "pub_share_pre_fee").extractOpt[String].filter(_.nonEmpty).getOrElse("0").toDouble
lazy val profit: Double = pub_share_pre_fee
lazy val trade_id: String = (json \ "trade_id").extractOrElse("")
lazy val unid: Long = Try((json \ "unid").extractOpt[String].filter(_.nonEmpty).get.toLong).getOrElse(0L)
lazy val cate_id1: Int = (json \ "cate_id").extractOrElse(0)
lazy val cate_id2: Int = (json \ "subcate_id").extractOrElse(0)
lazy val cate_id3: Int = (json \ "cate_id3").extractOrElse(0)
lazy val cate_id4: Int = (json \ "cate_id4").extractOrElse(0)
lazy val coupon_id: Long = (json \ "coupon_id").extractOrElse(0)
lazy val platform: Option[String] = Order.siteMap.get(site_id)
def time_fmt(fmt: String = "yyyy-MM-dd HH:mm:ss"): String = {
val dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
val date = dateFormat.parse(this.create_time)
new SimpleDateFormat(fmt).format(date)
}
}
What is an optional value in Swift?
Let's take the example of an NSError
, if there isn't an error being returned you'd want to make it optional to return Nil. There's no point in assigning a value to it if there isn't an error..
var error: NSError? = nil
This also allows you to have a default value. So you can set a method a default value if the function isn't passed anything
func doesntEnterNumber(x: Int? = 5) -> Bool {
if (x == 5){
return true
} else {
return false
}
}
android:layout_height 50% of the screen size
You can use android:weightSum="2"
on the parent layout combined with android:layout_height="1"
on the child layout.
<LinearLayout
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:weightSum="2"
>
<ImageView
android:layout_height="1"
android:layout_width="wrap_content" />
</LinearLayout>
How to check whether an object has certain method/property?
It is an old question, but I just ran into it.
Type.GetMethod(string name)
will throw an AmbiguousMatchException if there is more than one method with that name, so we better handle that case
public static bool HasMethod(this object objectToCheck, string methodName)
{
try
{
var type = objectToCheck.GetType();
return type.GetMethod(methodName) != null;
}
catch(AmbiguousMatchException)
{
// ambiguous means there is more than one result,
// which means: a method with that name does exist
return true;
}
}
Can't import org.apache.http.HttpResponse in Android Studio
in case you are going to start development, go fot OkHttp from square, otherwise if you need to keep your previous code running, then add legacy library to your project dependencies:
dependencies {
compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'
}
SpringMVC RequestMapping for GET parameters
You can add @RequestMapping
like so:
@RequestMapping("/userGrid")
public @ResponseBody GridModel getUsersForGrid(
@RequestParam("_search") String search,
@RequestParam String nd,
@RequestParam int rows,
@RequestParam int page,
@RequestParam String sidx)
@RequestParam String sord) {
Returning a stream from File.OpenRead()
You forgot to seek:
str.CopyTo(data);
data.Seek(0, SeekOrigin.Begin); // <-- missing line
byte[] buf = new byte[data.Length];
data.Read(buf, 0, buf.Length);
Django - Static file not found
{'document_root', settings.STATIC_ROOT}
needs to be
{'document_root': settings.STATIC_ROOT}
or you'll get an error like
dictionary update sequence element #0 has length 6; 2 is required
How do I read from parameters.yml in a controller in symfony2?
The Clean Way - 2018+, Symfony 3.4+
Since 2017 and Symfony 3.3 + 3.4 there is much cleaner way - easy to setup and use.
Instead of using container and service/parameter locator anti-pattern, you can pass parameters to class via it's constructor. Don't worry, it's not time-demanding work, but rather setup once & forget approach.
How to set it up in 2 steps?
1. app/config/services.yml
# config.yml
# config.yml
parameters:
api_pass: 'secret_password'
api_user: 'my_name'
services:
_defaults:
autowire: true
bind:
$apiPass: '%api_pass%'
$apiUser: '%api_user%'
App\:
resource: ..
2. Any Controller
<?php declare(strict_types=1);
final class ApiController extends SymfonyController
{
/**
* @var string
*/
private $apiPass;
/**
* @var string
*/
private $apiUser;
public function __construct(string $apiPass, string $apiUser)
{
$this->apiPass = $apiPass;
$this->apiUser = $apiUser;
}
public function registerAction(): void
{
var_dump($this->apiPass); // "secret_password"
var_dump($this->apiUser); // "my_name"
}
}
Instant Upgrade Ready!
In case you use older approach, you can automate it with Rector.
Read More
This is called constructor injection over services locator approach.
To read more about this, check my post How to Get Parameter in Symfony Controller the Clean Way.
(It's tested and I keep it updated for new Symfony major version (5, 6...)).
How to use log levels in java
the different log levels are helpful for tools, whose can anaylse you log files. Normally a logfile contains lots of information. To avoid an information overload (or here an stackoverflow^^) you can use the log levels for grouping the information.
Could not load file or assembly 'EntityFramework' after downgrading EF 5.0.0.0 --> 4.3.1.0
After failed attempts to find references to EntityFramework in repositories.config and elsewhere, I stumbled upon a reference in Web.config as I was editing it to help with my diagnosis.
The bindingRedirect referenced 5.0.0.0 which was no longer installed and this appeared to be the source of the exception. Honestly, I did not add this reference to Web.config and, after trying to duplicate the error in a separate project, discovered that it is not added by the NuGet package installer so, I don't know why it was there but something added it.
<dependentAssembly>
<assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
I decided to replace this with the equivalent element from a working project. NB the references to 5.0.0.0 are replaced with 4.3.1.0 in the following:
<dependentAssembly>
<assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.3.1.0" newVersion="4.3.1.0" />
</dependentAssembly>
This worked!
I then decided to remove the dependentAssembly reference for the EntityFramework in its entirety.
It still worked!
So, I'm posting this here as a self-answered question in the hope that it helps someone else. If anyone can explain to me:
- What added the dependentAssembly for EntityFramework to my Web.config
- Any consequence(s) of removing these references
I'd be interested to learn.
TCP vs UDP on video stream
There are some use cases suitable to UDP transport and others suitable to TCP transport.
The use case also dictates encoding settings for the video. When broadcasting soccer match focus is on quality and for video conference focus is on latency.
When using multicast to deliver video to your customers then UDP is used.
Requirement for multicast is expensive networking hardware between broadcasting server and customer. In practice this means if your company owns network infrastructure you can use UDP and multicast for live video streaming. Even then quality-of-service is also implemented to mark video packets and prioritize them so no packet loss happens.
Multicast will simplify broadcasting software because network hardware will handle distributing packets to customers. Customers subscribe to multicast channels and network will reconfigure to route packets to new subscriber. By default all channels are available to all customers and can be optimally routed.
This workflow places dificulty on authorization process. Network hardware does not differentiate subscribed users from other users. Solution to authorization is in encrypting video content and enabling decryption in player software when subscription is valid.
Unicast (TCP) workflow allows server to check client's credentials and only allow valid subscriptions. Even allow only certain number of simultaneous connections.
Multicast is not enabled over internet.
For delivering video over internet TCP must be used. When UDP is used developers end up re-implementing packet re-transmission, for eg. Bittorrent p2p live protocol.
"If you use TCP, the OS must buffer the unacknowledged segments for every client. This is undesirable, particularly in the case of live events".
This buffer must exist in some form. Same is true for jitter buffer on player side. It is called "socket buffer" and server software can know when this buffer is full and discard proper video frames for live streams. It is better to use unicast/TCP method because server software can implement proper frame dropping logic. Random missing packets in UDP case will just create bad user experience. like in this video: http://tinypic.com/r/2qn89xz/9
"IP multicast significantly reduces video bandwidth requirements for large audiences"
This is true for private networks, Multicast is not enabled over internet.
"Note that if TCP loses too many packets, the connection dies; thus, UDP gives you much more control for this application since UDP doesn't care about network transport layer drops."
UDP also doesn't care about dropping entire frames or group-of-frames so it does not give any more control over user experience.
"Usually a video stream is somewhat fault tolerant"
Encoded video is not fault tolerant. When transmitted over unreliable transport then forward error correction is added to video container. Good example is MPEG-TS container used in satellite video broadcast that carry several audio, video, EPG, etc. streams. This is necessary as satellite link is not duplex communication, meaning receiver can't request re-transmission of lost packets.
When you have duplex communication available it is always better to re-transmit data only to clients having packet loss then to include overhead of forward-error-correction in stream sent to all clients.
In any case lost packets are unacceptable. Dropped frames are ok in exceptional cases when bandwidth is hindered.
The result of missing packets are artifacts like this one:
Some decoders can break on streams missing packets in critical places.
Why can't static methods be abstract in Java?
The idea of having an abstract static method would be that you can't use that particular abstract class directly for that method, but only the first derivative would be allowed to implement that static method (or for generics: the actual class of the generic you use).
That way, you could create for example a sortableObject abstract class or even interface
with (auto-)abstract static methods, which defines the parameters of sort options:
public interface SortableObject {
public [abstract] static String [] getSortableTypes();
public String getSortableValueByType(String type);
}
Now you can define a sortable object that can be sorted by the main types which are the same for all these objects:
public class MyDataObject implements SortableObject {
final static String [] SORT_TYPES = {
"Name","Date of Birth"
}
static long newDataIndex = 0L ;
String fullName ;
String sortableDate ;
long dataIndex = -1L ;
public MyDataObject(String name, int year, int month, int day) {
if(name == null || name.length() == 0) throw new IllegalArgumentException("Null/empty name not allowed.");
if(!validateDate(year,month,day)) throw new IllegalArgumentException("Date parameters do not compose a legal date.");
this.fullName = name ;
this.sortableDate = MyUtils.createSortableDate(year,month,day);
this.dataIndex = MyDataObject.newDataIndex++ ;
}
public String toString() {
return ""+this.dataIndex+". "this.fullName+" ("+this.sortableDate+")";
}
// override SortableObject
public static String [] getSortableTypes() { return SORT_TYPES ; }
public String getSortableValueByType(String type) {
int index = MyUtils.getStringArrayIndex(SORT_TYPES, type);
switch(index) {
case 0: return this.name ;
case 1: return this.sortableDate ;
}
return toString(); // in the order they were created when compared
}
}
Now you can create a
public class SortableList<T extends SortableObject>
that can retrieve the types, build a pop-up menu to select a type to sort on and resort the list by getting the data from that type, as well as hainv an add function that, when a sort type has been selected, can auto-sort new items in.
Note that the instance of SortableList can directly access the static method of "T":
String [] MenuItems = T.getSortableTypes();
The problem with having to use an instance is that the SortableList may not have items yet, but already need to provide the preferred sorting.
Cheerio,
Olaf.
Equivalent to 'app.config' for a library (DLL)
Configuration files are application-scoped and not assembly-scoped. So you'll need to put your library's configuration sections in every application's configuration file that is using your library.
That said, it is not a good practice to get configuration from the application's configuration file, specially the appSettings
section, in a class library. If your library needs parameters, they should probably be passed as method arguments in constructors, factory methods, etc. by whoever is calling your library. This prevents calling applications from accidentally reusing configuration entries that were expected by the class library.
That said, XML configuration files are extremely handy, so the best compromise that I've found is using custom configuration sections. You get to put your library's configuration in an XML file that is automatically read and parsed by the framework and you avoid potential accidents.
You can learn more about custom configuration sections on MSDN and also Phil Haack has a nice article on them.
Calling a Fragment method from a parent Activity
you also call fragment method using interface like
first you create interface
public interface InterfaceName {
void methodName();
}
after creating interface you implement interface in your fragment
MyFragment extends Fragment implements InterfaceName {
@overide
void methodName() {
}
}
and you create the reference of interface in your activity
class Activityname extends AppCompatActivity {
Button click;
MyFragment fragment;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
click = findViewById(R.id.button);
fragment = new MyFragment();
click.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fragment.methodName();
}
});
}
}
How to add more than one machine to the trusted hosts list using winrm
Same as @Altered-Ego but with txt.file:
Get-Content "C:\ServerList.txt"
machineA,machineB,machineC,machineD
$ServerList = Get-Content "C:\ServerList.txt"
$currentTrustHost=(get-item WSMan:\localhost\Client\TrustedHosts).value
if ( ($currentTrustHost).Length -gt "0" ) {
$currentTrustHost+= ,$ServerList
set-item WSMan:\localhost\Client\TrustedHosts –value $currentTrustHost -Force -ErrorAction SilentlyContinue
}
else {
$currentTrustHost+= $ServerList
set-item WSMan:\localhost\Client\TrustedHosts –value $currentTrustHost -Force -ErrorAction SilentlyContinue
}
The "-ErrorAction SilentlyContinue
" is required in old PS version to avoid fake error message:
PS C:\Windows\system32> get-item WSMan:\localhost\Client\TrustedHosts
WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Client
Type Name SourceOfValue Value
---- ---- ------------- -----
System.String TrustedHosts machineA,machineB,machineC,machineD
create multiple tag docker image
You can't create tags with Dockerfiles but you can create multiple tags on your images via the command line.
Use this to list your image ids:
$ docker images
Then tag away:
$ docker tag 9f676bd305a4 ubuntu:13.10
$ docker tag 9f676bd305a4 ubuntu:saucy
$ docker tag eb601b8965b8 ubuntu:raring
...
How to Verify if file exist with VB script
There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :
Option Explicit
DIM fso
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists("C:\Program Files\conf")) Then
WScript.Echo("File exists!")
WScript.Quit()
Else
WScript.Echo("File does not exist!")
End If
WScript.Quit()
Cannot make Project Lombok work on Eclipse
I am on Eclipse Neon, and after following the above steps, it still didnt work. import lombok.Data; was not being recognized.
After about an hour of looking around, i switched the version to 1.16.14 and it worked.
Now my thought is, whether the 1 hour spent will be a good investment for long term :-)
How to set Internet options for Android emulator?
Hi me also faced same issue , solved using below steps:
cause 1:
Add internet permission in your android application
cause 2:
Check the manually your default application is able access internet or not
if not its problem of your emulator , check in your internet connection in your pc
try below method to connect net in your pc
try explicitly specifying DNS server settings, this worked for me.
In Eclipse:
Window>Preferences>Android>Launch
Default emulator options: -dns-server 8.8.8.8,8.8.4.4**
cause 3:
check : check if you are using more than one internet connection to your pc like one is LAN second one is Modem ,
so disable all lan or modem .
jQuery - setting the selected value of a select control via its text description
Select by description for jQuery v1.6+
_x000D_
_x000D_
var text1 = 'Two';_x000D_
$("select option").filter(function() {_x000D_
//may want to use $.trim in here_x000D_
return $(this).text() == text1;_x000D_
}).prop('selected', true);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<select>_x000D_
<option value="0">One</option>_x000D_
<option value="1">Two</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
var text1 = 'Two';_x000D_
$("select option").filter(function() {_x000D_
//may want to use $.trim in here_x000D_
return $(this).text() == text1;_x000D_
}).attr('selected', true);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>_x000D_
_x000D_
<select>_x000D_
<option value="0">One</option>_x000D_
<option value="1">Two</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_
Note that while this approach will work in versions that are above 1.6 but less than 1.9, it has been deprecated since 1.6. It will not work in jQuery 1.9+.
Previous versions
val()
should handle both cases.
_x000D_
_x000D_
$('select').val('1'); // selects "Two"_x000D_
$('select').val('Two'); // also selects "Two"
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>_x000D_
_x000D_
<select>_x000D_
<option value="0">One</option>_x000D_
<option value="1">Two</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_
How to run a Runnable thread in Android at defined intervals?
Kotlin with Coroutines
In Kotlin, using coroutines you can do the following:
CoroutineScope(Dispatchers.Main).launch { // Main, because UI is changed
ticker(delayMillis = 1000, initialDelayMillis = 1000).consumeEach {
tv.append("Hello World")
}
}
Try it out here!
nodeJS - How to create and read session with express
Hello I am trying to add new session values in node js like
req.session.portal = false
Passport.authenticate('facebook', (req, res, next) => {
next()
})(req, res, next)
On passport strategies I am not getting portal value in mozilla request but working fine with chrome and opera
FacebookStrategy: new PassportFacebook.Strategy({
clientID: Configuration.SocialChannel.Facebook.AppId,
clientSecret: Configuration.SocialChannel.Facebook.AppSecret,
callbackURL: Configuration.SocialChannel.Facebook.CallbackURL,
profileFields: Configuration.SocialChannel.Facebook.Fields,
scope: Configuration.SocialChannel.Facebook.Scope,
passReqToCallback: true
}, (req, accessToken, refreshToken, profile, done) => {
console.log(JSON.stringify(req.session));
How to enable C++11/C++0x support in Eclipse CDT?
Neither the hack nor the cleaner version work for Indigo. The hack is ignored, and the required configuration options are missing. For no apparent reason, build started working after not working and not providing any useful reason why. At least from the command line, I get reproducible results.
Connect over ssh using a .pem file
Use the -i
option:
ssh -i mykey.pem [email protected]
As noted in this answer, this file needs to have correct permissions set. The ssh man page says:
ssh will simply ignore a private key file if it is accessible by others.
You can change the permissions with this command:
chmod go= mykey.pem
That is, set permissions for group and others equal to the empty list of permissions.
How to run a program in Atom Editor?
I find the Script package useful for this. You can download it here.
Once installed you can run scripts in many languages directly from Atom using cmd-i
on Mac or shift-ctrl-b
on Windows or Linux.
How to parse month full form string using DateFormat in Java?
You are probably using a locale where the month names are not "January", "February", etc. but some other words in your local language.
Try specifying the locale you wish to use, for example Locale.US
:
DateFormat fmt = new SimpleDateFormat("MMMM dd, yyyy", Locale.US);
Date d = fmt.parse("June 27, 2007");
Also, you have an extra space in the date string, but actually this has no effect on the result. It works either way.
C++ Compare char array with string
You're not working with strings. You're working with pointers.
var1
is a char pointer (const char*
). It is not a string. If it is null-terminated, then certain C functions will treat it as a string, but it is fundamentally just a pointer.
So when you compare it to a char array, the array decays to a pointer as well, and the compiler then tries to find an operator == (const char*, const char*)
.
Such an operator does exist. It takes two pointers and returns true
if they point to the same address. So the compiler invokes that, and your code breaks.
IF you want to do string comparisons, you have to tell the compiler that you want to deal with strings, not pointers.
The C way of doing this is to use the strcmp
function:
strcmp(var1, "dev");
This will return zero if the two strings are equal. (It will return a value greater than zero if the left-hand side is lexicographically greater than the right hand side, and a value less than zero otherwise.)
So to compare for equality you need to do one of these:
if (!strcmp(var1, "dev")){...}
if (strcmp(var1, "dev") == 0) {...}
However, C++ has a very useful string
class. If we use that your code becomes a fair bit simpler. Of course we could create strings from both arguments, but we only need to do it with one of them:
std::string var1 = getenv("myEnvVar");
if(var1 == "dev")
{
// do stuff
}
Now the compiler encounters a comparison between string and char pointer. It can handle that, because a char pointer can be implicitly converted to a string, yielding a string/string comparison. And those behave exactly as you'd expect.
Set cURL to use local virtual hosts
Either use a real fully qualified domain name (like dev.yourdomain.com
) that pointing to 127.0.0.1
or try editing the proper hosts file (usually /etc/hosts in *nix environments).
Keeping it simple and how to do multiple CTE in a query
You certainly are able to have multiple CTEs in a single query expression. You just need to separate them with a comma. Here is an example. In the example below, there are two CTEs. One is named CategoryAndNumberOfProducts
and the second is named ProductsOverTenDollars
.
WITH CategoryAndNumberOfProducts (CategoryID, CategoryName, NumberOfProducts) AS
(
SELECT
CategoryID,
CategoryName,
(SELECT COUNT(1) FROM Products p
WHERE p.CategoryID = c.CategoryID) as NumberOfProducts
FROM Categories c
),
ProductsOverTenDollars (ProductID, CategoryID, ProductName, UnitPrice) AS
(
SELECT
ProductID,
CategoryID,
ProductName,
UnitPrice
FROM Products p
WHERE UnitPrice > 10.0
)
SELECT c.CategoryName, c.NumberOfProducts,
p.ProductName, p.UnitPrice
FROM ProductsOverTenDollars p
INNER JOIN CategoryAndNumberOfProducts c ON
p.CategoryID = c.CategoryID
ORDER BY ProductName
SQL to add column and comment in table in single command
No, you can't.
There's no reason why you would need to. This is a one-time operation and so takes only an additional second or two to actually type and execute.
If you're adding columns in your web application this is more indicative of a flaw in your data-model as you shouldn't need to be doing it.
In response to your comment that a comment is a column attribute; it may seem so but behind the scenes Oracle stores this as an attribute of an object.
SQL> desc sys.com$
Name Null? Type
----------------------------------------- -------- ----------------------------
OBJ# NOT NULL NUMBER
COL# NUMBER
COMMENT$ VARCHAR2(4000)
SQL>
The column is optional and sys.col$
does not contain comment information.
I assume, I have no knowledge, that this was done in order to only have one system of dealing with comments rather than multiple.
how to import csv data into django models
Use the Pandas library to create a dataframe of the csv data.
Name the fields either by including them in the csv file's first line or in code by using the dataframe's columns method.
Then create a list of model instances.
Finally use the django method .bulk_create() to send your list of model instances to the database table.
The read_csv function in pandas is great for reading csv files and gives you lots of parameters to skip lines, omit fields, etc.
import pandas as pd
tmp_data=pd.read_csv('file.csv',sep=';')
#ensure fields are named~ID,Product_ID,Name,Ratio,Description
#concatenate name and Product_id to make a new field a la Dr.Dee's answer
products = [
Product(
name = tmp_data.ix[row]['Name']
description = tmp_data.ix[row]['Description'],
price = tmp_data.ix[row]['price'],
)
for row in tmp_data['ID']
]
Product.objects.bulk_create(products)
I was using the answer by mmrs151 but saving each row (instance) was very slow and any fields containing the delimiting character (even inside of quotes) were not handled by the open() -- line.split(';') method.
Pandas has so many useful caveats, it is worth getting to know
Adding to an ArrayList Java
Well, you have to iterate through your abstract type Foo and that depends on the methods available on that object. You don't have to loop through the ArrayList because this object grows automatically in Java. (Don't confuse it with an array in other programming languages)
Recommended reading.
Lists in the Java Tutorial
Add views below toolbar in CoordinatorLayout
To use collapsing top ToolBar or using ScrollFlags of your own choice
we can do this way:From Material Design get rid of FrameLayout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleGravity="top"
app:layout_scrollFlags="scroll|enterAlways">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin">
<ImageView
android:id="@+id/ic_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_arrow_back" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="back"
android:textSize="16sp"
android:textStyle="bold" />
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/post_details_recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
How to change package name in android studio?
First click once on your package and then click setting icon on Android Studio.
Close/Unselect Compact Empty Middle Packages
Then, right click your package and rename it.
Thats all.
What is the most effective way to get the index of an iterator of an std::vector?
As UncleBens and Naveen have shown, there are good reasons for both. Which one is "better" depends on what behavior you want: Do you want to guarantee constant-time behavior, or do you want it to fall back to linear time when necessary?
it - vec.begin()
takes constant time, but the operator -
is only defined on random access iterators, so the code won't compile at all with list iterators, for example.
std::distance(vec.begin(), it)
works for all iterator types, but will only be a constant-time operation if used on random access iterators.
Neither one is "better". Use the one that does what you need.
Passing Arrays to Function in C++
firstarray
and secondarray
are converted to a pointer to int, when passed to printarray()
.
printarray(int arg[], ...)
is equivalent to printarray(int *arg, ...)
However, this is not specific to C++. C has the same rules for passing array names to a function.
How to get length of a string using strlen function
Use std::string::size
or std::string::length
(both are the same).
As you insist to use strlen
, you can:
int size = strlen( str.c_str() );
note the usage of std::string::c_str
, which returns const char*
.
BUT strlen
counts untill it hit \0
char and std::string
can store such chars. In other words, strlen
could sometimes lie for the size.
INNER JOIN vs LEFT JOIN performance in SQL Server
There is one important scenario that can lead to an outer join being faster than an inner join that has not been discussed yet.
When using an outer join, the optimizer is always free to drop the outer joined table from the execution plan if the join columns are the PK of the outer table, and none of the outer table columns are referenced outside of the outer join itself. For example SELECT A.* FROM A LEFT OUTER JOIN B ON A.KEY=B.KEY
and B.KEY is the PK for B. Both Oracle (I believe I was using release 10) and Sql Server (I used 2008 R2) prune table B from the execution plan.
The same is not necessarily true for an inner join: SELECT A.* FROM A INNER JOIN B ON A.KEY=B.KEY
may or may not require B in the execution plan depending on what constraints exist.
If A.KEY is a nullable foreign key referencing B.KEY, then the optimizer cannot drop B from the plan because it must confirm that a B row exists for every A row.
If A.KEY is a mandatory foreign key referencing B.KEY, then the optimizer is free to drop B from the plan because the constraints guarantee the existence of the row. But just because the optimizer can drop the table from the plan, doesn't mean it will. SQL Server 2008 R2 does NOT drop B from the plan. Oracle 10 DOES drop B from the plan. It is easy to see how the outer join will out-perform the inner join on SQL Server in this case.
This is a trivial example, and not practical for a stand-alone query. Why join to a table if you don't need to?
But this could be a very important design consideration when designing views. Frequently a "do-everything" view is built that joins everything a user might need related to a central table. (Especially if there are naive users doing ad-hoc queries that do not understand the relational model) The view may include all the relevent columns from many tables. But the end users might only access columns from a subset of the tables within the view. If the tables are joined with outer joins, then the optimizer can (and does) drop the un-needed tables from the plan.
It is critical to make sure that the view using outer joins gives the correct results. As Aaronaught has said - you cannot blindly substitute OUTER JOIN for INNER JOIN and expect the same results. But there are times when it can be useful for performance reasons when using views.
One last note - I haven't tested the impact on performance in light of the above, but in theory it seems you should be able to safely replace an INNER JOIN with an OUTER JOIN if you also add the condition <FOREIGN_KEY> IS NOT NULL to the where clause.
Hibernate Auto Increment ID
Hibernate defines five types of identifier generation strategies:
AUTO - either identity column, sequence or table depending on the underlying DB
TABLE - table holding the id
IDENTITY - identity column
SEQUENCE - sequence
identity copy – the identity is copied from another entity
Example using Table
@Id
@GeneratedValue(strategy=GenerationType.TABLE , generator="employee_generator")
@TableGenerator(name="employee_generator",
table="pk_table",
pkColumnName="name",
valueColumnName="value",
allocationSize=100)
@Column(name="employee_id")
private Long employeeId;
for more details, check the link.
Adding two Java 8 streams, or an extra element to a stream
Unfortunately this answer is probably of little or no help whatsoever, but I did a forensics analysis of the Java Lambda Mailing list to see if I could find the cause of this design. This is what I found out.
In the beginning there was an instance method for Stream.concat(Stream)
In the mailing list I can clearly see the method was originally implemented as an instance method, as you can read in this thread by Paul Sandoz, about the concat operation.
In it they discuss the issues that could arise from those cases in which the stream could be infinite and what concatenation would mean in those cases, but I do not think that was the reason for the modification.
You see in this other thread that some early users of the JDK 8 questioned about the behavior of the concat instance method when used with null arguments.
This other thread reveals, though, that the design of the concat method was under discussion.
Refactored to Streams.concat(Stream,Stream)
But without any explanation, suddenly, the methods were changed to static methods, as you can see in this thread about combining streams. This is perhaps the only mail thread that sheds a bit of light about this change, but it was not clear enough for me to determine the reason for the refactoring. But we can see they did a commit in which they suggested to move the concat
method out of Stream
and into the helper class Streams
.
Refactored to Stream.concat(Stream,Stream)
Later, it was moved again from Streams
to Stream
, but yet again, no explanation for that.
So, bottom line, the reason for the design is not entirely clear for me and I could not find a good explanation. I guess you could still ask the question in the mailing list.
Some Alternatives for Stream Concatenation
This other thread by Michael Hixson discusses/asks about other ways to combine/concat streams
To combine two streams, I should do this:
Stream.concat(s1, s2)
not this:
Stream.of(s1, s2).flatMap(x -> x)
... right?
To combine more than two streams, I should do this:
Stream.of(s1, s2, s3, ...).flatMap(x -> x)
not this:
Stream.of(s1, s2, s3, ...).reduce(Stream.empty(), Stream::concat)
... right?
react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined
so if you need want use this code )
import { useRoutes } from "./routes";
import { BrowserRouter as Router } from "react-router-dom";
export const App = () => {
const routes = useRoutes(true);
return (
<Router>
<div className="container">{routes}</div>
</Router>
);
};
// ./routes.js
import { Switch, Route, Redirect } from "react-router-dom";
export const useRoutes = (isAuthenticated) => {
if (isAuthenticated) {
return (
<Switch>
<Route path="/links" exact>
<LinksPage />
</Route>
<Route path="/create" exact>
<CreatePage />
</Route>
<Route path="/detail/:id">
<DetailPage />
</Route>
<Redirect path="/create" />
</Switch>
);
}
return (
<Switch>
<Route path={"/"} exact>
<AuthPage />
</Route>
<Redirect path={"/"} />
</Switch>
);
};