Here's a simple approach using ng-init
that doesn't even require a custom directive. It's worked well for me in certain scenarios e.g. needing to auto-scroll a div of ng-repeated items to a particular item on page load, so the scrolling function needs to wait until the ng-repeat
has finished rendering to the DOM before it can fire.
<div ng-controller="MyCtrl">
<div ng-repeat="thing in things">
thing: {{ thing }}
</div>
<div ng-init="fireEvent()"></div>
</div>
myModule.controller('MyCtrl', function($scope, $timeout){
$scope.things = ['A', 'B', 'C'];
$scope.fireEvent = function(){
// This will only run after the ng-repeat has rendered its things to the DOM
$timeout(function(){
$scope.$broadcast('thingsRendered');
}, 0);
};
});
Note that this is only useful for functions you need to call one time after the ng-repeat renders initially. If you need to call a function whenever the ng-repeat contents are updated then you'll have to use one of the other answers on this thread with a custom directive.
there is a ngcontentloaded
event, I think you can use it
.directive('directiveExample', function(){
return {
restrict: 'A',
link: function(scope, elem, attrs){
$$window = $ $window
init = function(){
contentHeight = elem.outerHeight()
//do the things
}
$$window.on('ngcontentloaded',init)
}
}
});
To change vector image color you can directly use android:tint="@color/colorAccent"
<ImageView
android:id="@+id/ivVectorImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_account_circle_black_24dp"
android:tint="@color/colorAccent" />
To change color programatically
ImageView ivVectorImage = (ImageView) findViewById(R.id.ivVectorImage);
ivVectorImage.setColorFilter(getResources().getColor(R.color.colorPrimary));
First of all, I would not make any changes directly in the "main" repo. If you really want to have a "main" repo, then you should only push to it, never change it directly.
Regarding the error you are getting, have you tried git pull
from your local repo, and then git push
to the main repo? What you are currently doing (if I understood it well) is forcing the push and then losing your changes in the "main" repo. You should merge the changes locally first.
You could use the xpath :
//div[@class="measure-tab" and .//span[contains(., "someText")]]
Input :
<root>
<div class="measure-tab">
<td> someText</td>
</div>
<div class="measure-tab">
<div>
<div2>
<span>someText2</span>
</div2>
</div>
</div>
</root>
Output :
Element='<div class="measure-tab">
<div>
<div2>
<span>someText2</span>
</div2>
</div>
</div>'
Just use a Reverse Proxy in your apache configuration (directly):
ProxyPass /foo http://foo.example.com/bar
ProxyPassReverse /foo http://foo.example.com/bar
Python lacks the tail recursion optimizations common in functional languages like lisp. In Python, recursion is limited to 999 calls (see sys.getrecursionlimit).
If 999 depth is more than you are expecting, check if the implementation lacks a condition that stops recursion, or if this test may be wrong for some cases.
I dare to say that in Python, pure recursive algorithm implementations are not correct/safe. A fib() implementation limited to 999 is not really correct. It is always possible to convert recursive into iterative, and doing so is trivial.
It is not reached often because in many recursive algorithms the depth tend to be logarithmic. If it is not the case with your algorithm and you expect recursion deeper than 999 calls you have two options:
1) You can change the recursion limit with sys.setrecursionlimit(n)
until the maximum allowed for your platform:
sys.setrecursionlimit(limit)
:Set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.
The highest possible limit is platform-dependent. A user may need to set the limit higher when she has a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash.
2) You can try to convert the algorithm from recursive to iterative. If recursion depth is bigger than allowed by your platform, it is the only way to fix the problem. There are step by step instructions on the Internet and it should be a straightforward operation for someone with some CS education. If you are having trouble with that, post a new question so we can help.
CTRL-F6 in Eclipse, like ALT-TAB (on windows), brings up a list of tabs/windows available (if you keep the CTRL / ALT key depressed) and highlights the one you will jump to when you let go of this key. You do not have to select the window. If you want to traverse several tabs at once hold down the CTRL button and tap the TAB button. This is identical behaviour to ALT-TAB on Windows.
In this sense, CTRL-SHIFT-F6 in eclipse is the ALT-SHIFT-TAB analog. Personally, I change these bindings in Eclipse to be like Visual Studio. I.e. CTRL-TAB and CTRL-SHIFT-TAB and I do it like this:
Window>Preferences>General>Keys
Then set "Next Editor"=Ctrl+Tab and "Previous Editor"=Ctrl+Shift+Tab. Don't forget to click "Unbind Command" before setting the new binding.
This is CTRL-PageDown to go right, CTRL-PageUp to go left. Frustratingly, when you get to the end of the list of tabs (say far right hand tab) and then try to go right again Eclipse does not cycle round to the first tab (far left) like most browsers would.
You can create such form where label and form control are side using two method -
1. Inline form layout
<form class="form-inline" role="form">
<div class="form-group">
<label for="inputEmail">Email</label>
<input type="email" class="form-control" id="inputEmail" placeholder="Email">
</div>
<div class="form-group">
<label for="inputPassword">Password</label>
<input type="password" class="form-control" id="inputPassword" placeholder="Password">
</div>
<button type="reset" class="btn btn-default">Reset</button>
<button type="submit" class="btn btn-primary">Login</button>
</form>
2. Horizontal Form Layout
<form class="form-horizontal">
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label for="inputEmail" class="control-label col-xs-3">Email</label>
<div class="col-xs-9">
<input type="email" class="form-control" id="inputEmail" placeholder="Email">
</div>
</div>
</div>
<div class="col-sm-5">
<div class="form-group">
<label for="inputPassword" class="control-label col-xs-3">Password</label>
<div class="col-xs-9">
<input type="password" class="form-control" id="inputPassword" placeholder="Password">
</div>
</div>
</div>
<div class="col-sm-3">
<button type="reset" class="btn btn-default">Reset</button>
<button type="submit" class="btn btn-primary">Login</button>
</div>
</div>
</form>
You can check out this page for more information and live demo - http://www.tutorialrepublic.com/twitter-bootstrap-tutorial/bootstrap-forms.php
This is an old Q, but a modern solution without flexbox or position absolute works like this.
margin-left: 50%;
transform: translateX(-50%);
.outer {_x000D_
border: 1px solid green;_x000D_
margin: 20px auto;_x000D_
width: 20%;_x000D_
padding: 10px 0;_x000D_
/* overflow: hidden; */_x000D_
}_x000D_
_x000D_
.inner {_x000D_
width: 150%;_x000D_
background-color: gold;_x000D_
/* Set left edge of inner element to 50% of the parent element */_x000D_
margin-left: 50%; _x000D_
/* Move to the left by 50% of own width */_x000D_
transform: translateX(-50%); _x000D_
}
_x000D_
<div class="outer">_x000D_
<div class="inner">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos exercitationem error nemo amet cum quia eaque alias nihil, similique laboriosam enim expedita fugit neque earum et esse ad, dolores sapiente sit cumque vero odit! Ullam corrupti iure eum similique magnam voluptatum ipsam. Maxime ad cumque ut atque suscipit enim quidem. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi impedit esse modi, porro quibusdam voluptate dolores molestias, sit dolorum veritatis laudantium rem, labore et nobis ratione. Ipsum, aliquid totam repellendus non fugiat id magni voluptate, doloribus tenetur illo mollitia. Voluptatum.</div>_x000D_
</div>
_x000D_
So why does it work?
At first glance it seems that we shift 50% to the right and then 50% to the left again. That would result in zero shift, so what?
But the 50% are not the same, because context is important. If you use relative units, a margin will be calculated as percentage of the width of the parent element, while the transform will be 50% relative to the same element.
We have this situation before we add the CSS
+-------------------------------------------+
| Parent element P of E |
| |
+-----------------------------------------------------------+
| Element E |
+-----------------------------------------------------------+
| |
+-------------------------------------------+
With the added style margin-left: 50%
we have
+-------------------------------------------+
| Parent element P of E |
| |
| +-----------------------------------------------------------+
| | Element E |
| +-----------------------------------------------------------+
| | |
+---------------------|---------------------+
|========= a ========>|
a is 50% width of P
And the transform: translateX(-50%)
shifts back to the left
+-------------------------------------------+
| Parent element P of E |
| |
+-----------------------------------------------------------+
| Element E | |
+-----------------------------------------------------------+
|<============ b ===========| |
| | |
+--------------------|----------------------+
|========= a =======>|
a is 50% width of P
b is 50% width of E
Unfortunately this does only work for horizontal centering as the margin percentage calculation is always relative to the width. I.e. not only margin-left
and margin-right
, but also margin-top
and margin-bottom
are calculated with respect to width.
Browser compatibility should be no problem: https://caniuse.com/#feat=transforms2d
As described by the link I've given in comment, this
$('p[MyTag]').each(function(index) {
document.write(index + ': ' + $(this).text() + "<br>");});
works (playable example).
Just to complete, you could send 3 arguments like this:
objShell.Run "TestScript.vbs 42 ""an arg containing spaces"" foo"
This issue occurred for me after installing a pod via Podfile and pod install
. After trying a bunch of different fixes I finally just imported the Pod manually (dragging the necessary files into my project) and that solved the problem.
In simple way you can go with explode($delimiter, $string)
;
But in a broad way, with Manual Programming :
$string = "ab,cdefg,xyx,ht623";
$resultArr = [];
$strLength = strlen($string);
$delimiter = ',';
$j = 0;
$tmp = '';
for ($i = 0; $i < $strLength; $i++) {
if($delimiter === $string[$i]) {
$j++;
$tmp = '';
continue;
}
$tmp .= $string[$i];
$resultArr[$j] = $tmp;
}
Outpou : print_r($resultArr);
Array
(
[0] => ab
[1] => cdefg
[2] => xyx
[3] => ht623
)
PHP has SOAP support. Just call
$client = new SoapClient($url);
to connect to the SoapServer and then you can get list of functions and call functions simply by doing...
$client->__getTypes();
$client->__getFunctions();
$result = $client->functionName();
for more http://www.php.net/manual/en/soapclient.soapclient.php
All answers here did not work for me. Instead, to add a space at the end of a string in XML
i did this
<string name="more_store">more store<b> </b> </string>
If one only cares about whitespace at the beginning and end of the string (but not in the middle), then another option is to use String.trim():
" your string contents ".trim();
// => "your string contents"
The clearest way would be to explicitly set i
. For example:
i = 0
while i < 100:
i += 1
try:
# do stuff
except MyException:
continue
For just add an alpha channel to s_img I just use cv2.addWeighted before the line
l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img
as following:
s_img=cv2.addWeighted(l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]],0.5,s_img,0.5,0)
This is a simpler one
$('#some_select_box').find('option:selected').remove().end();
I had this happen in a worksheet today. Neither F9 nor turning on Iterative Calculation made the cells in question update, but double-clicking the cell and pressing Enter did. I searched the Excel Help and found this in the help article titled Change formula recalculation, iteration, or precision:
- CtrlAltF9:
- Recalculate all formulas in all open workbooks, regardless of whether they have changed since the last recalculation.
- CtrlShiftAltF9:
- Check dependent formulas, and then recalculate all formulas in all open workbooks, regardless of whether they have changed since the last recalculation.
So I tried CtrlShiftAltF9, and sure enough, all of my non-recalculating formulas finally recalculated!
First, is 40 collisions for 130 words hashed to 0..99 bad? You can't expect perfect hashing if you are not taking steps specifically for it to happen. An ordinary hash function won't have fewer collisions than a random generator most of the time.
A hash function with a good reputation is MurmurHash3.
Finally, regarding the size of the hash table, it really depends what kind of hash table you have in mind, especially, whether buckets are extensible or one-slot. If buckets are extensible, again there is a choice: you choose the average bucket length for the memory/speed constraints that you have.
glob.glob()
is definitely the way to do it (as per Ignacio). However, if you do need more complicated matching, you can do it with a list comprehension and re.match()
, something like so:
files = [f for f in os.listdir('.') if re.match(r'[0-9]+.*\.jpg', f)]
More flexible, but as you note, less efficient.
I have a very simple answer which works:
set-executionpolicy unrestricted
I found this solution following the link that was given as part of error message: About Execution Policies
<input name='id[]' type='checkbox' value='".$shopnumb."\'>
<input name='id[]' type='checkbox' value='".$shopnumb."\'>
<input name='id[]' type='checkbox' value='".$shopnumb."\'>
$id = implode(',',$_POST['id']);
echo $id
you cannot echo an array because it will just print out Array. If you wanna print out an array use print_r
.
print_r($_POST['id']);
The following is what I came up with. It's similer to Riccardo C.'s, in this thread, except it prints the numbers in order instead of in reverse. I also made the LinkedList object a Python Iterator in order to print the list out like you would a normal Python list.
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
def __str__(self):
return str(self.data)
class LinkedList:
def __init__(self):
self.head = None
self.curr = None
self.tail = None
def __iter__(self):
return self
def next(self):
if self.head and not self.curr:
self.curr = self.head
return self.curr
elif self.curr.next:
self.curr = self.curr.next
return self.curr
else:
raise StopIteration
def append(self, data):
n = Node(data)
if not self.head:
self.head = n
self.tail = n
else:
self.tail.next = n
self.tail = self.tail.next
# Add 5 nodes
ll = LinkedList()
for i in range(1, 6):
ll.append(i)
# print out the list
for n in ll:
print n
"""
Example output:
$ python linked_list.py
1
2
3
4
5
"""
In case you cannot use different stylesheet by dynamically loading it, you can use this function to modify CSS class. Hope it helps you...
function changeCss(className, classValue) {
// we need invisible container to store additional css definitions
var cssMainContainer = $('#css-modifier-container');
if (cssMainContainer.length == 0) {
var cssMainContainer = $('<div id="css-modifier-container"></div>');
cssMainContainer.hide();
cssMainContainer.appendTo($('body'));
}
// and we need one div for each class
classContainer = cssMainContainer.find('div[data-class="' + className + '"]');
if (classContainer.length == 0) {
classContainer = $('<div data-class="' + className + '"></div>');
classContainer.appendTo(cssMainContainer);
}
// append additional style
classContainer.html('<style>' + className + ' {' + classValue + '}</style>');
}
This function will take any class name and replace any previously set values with the new value. Note, you can add multiple values by passing the following into classValue: "background: blue; color:yellow"
.
The standard approach suggested by Nate Kohl, just using vector, sort + unique:
sort( vec.begin(), vec.end() );
vec.erase( unique( vec.begin(), vec.end() ), vec.end() );
doesn't work for a vector of pointers.
Look carefully at this example on cplusplus.com.
In their example, the "so called duplicates" moved to the end are actually shown as ? (undefined values), because those "so called duplicates" are SOMETIMES "extra elements" and SOMETIMES there are "missing elements" that were in the original vector.
A problem occurs when using std::unique()
on a vector of pointers to objects (memory leaks, bad read of data from HEAP, duplicate frees, which cause segmentation faults, etc).
Here's my solution to the problem: replace std::unique()
with ptgi::unique()
.
See the file ptgi_unique.hpp below:
// ptgi::unique()
//
// Fix a problem in std::unique(), such that none of the original elts in the collection are lost or duplicate.
// ptgi::unique() has the same interface as std::unique()
//
// There is the 2 argument version which calls the default operator== to compare elements.
//
// There is the 3 argument version, which you can pass a user defined functor for specialized comparison.
//
// ptgi::unique() is an improved version of std::unique() which doesn't looose any of the original data
// in the collection, nor does it create duplicates.
//
// After ptgi::unique(), every old element in the original collection is still present in the re-ordered collection,
// except that duplicates have been moved to a contiguous range [dupPosition, last) at the end.
//
// Thus on output:
// [begin, dupPosition) range are unique elements.
// [dupPosition, last) range are duplicates which can be removed.
// where:
// [] means inclusive, and
// () means exclusive.
//
// In the original std::unique() non-duplicates at end are moved downward toward beginning.
// In the improved ptgi:unique(), non-duplicates at end are swapped with duplicates near beginning.
//
// In addition if you have a collection of ptrs to objects, the regular std::unique() will loose memory,
// and can possibly delete the same pointer multiple times (leading to SEGMENTATION VIOLATION on Linux machines)
// but ptgi::unique() won't. Use valgrind(1) to find such memory leak problems!!!
//
// NOTE: IF you have a vector of pointers, that is, std::vector<Object*>, then upon return from ptgi::unique()
// you would normally do the following to get rid of the duplicate objects in the HEAP:
//
// // delete objects from HEAP
// std::vector<Object*> objects;
// for (iter = dupPosition; iter != objects.end(); ++iter)
// {
// delete (*iter);
// }
//
// // shrink the vector. But Object * pointers are NOT followed for duplicate deletes, this shrinks the vector.size())
// objects.erase(dupPosition, objects.end));
//
// NOTE: But if you have a vector of objects, that is: std::vector<Object>, then upon return from ptgi::unique(), it
// suffices to just call vector:erase(, as erase will automatically call delete on each object in the
// [dupPosition, end) range for you:
//
// std::vector<Object> objects;
// objects.erase(dupPosition, last);
//
//==========================================================================================================
// Example of differences between std::unique() vs ptgi::unique().
//
// Given:
// int data[] = {10, 11, 21};
//
// Given this functor: ArrayOfIntegersEqualByTen:
// A functor which compares two integers a[i] and a[j] in an int a[] array, after division by 10:
//
// // given an int data[] array, remove consecutive duplicates from it.
// // functor used for std::unique (BUGGY) or ptgi::unique(IMPROVED)
//
// // Two numbers equal if, when divided by 10 (integer division), the quotients are the same.
// // Hence 50..59 are equal, 60..69 are equal, etc.
// struct ArrayOfIntegersEqualByTen: public std::equal_to<int>
// {
// bool operator() (const int& arg1, const int& arg2) const
// {
// return ((arg1/10) == (arg2/10));
// }
// };
//
// Now, if we call (problematic) std::unique( data, data+3, ArrayOfIntegersEqualByTen() );
//
// TEST1: BEFORE UNIQ: 10,11,21
// TEST1: AFTER UNIQ: 10,21,21
// DUP_INX=2
//
// PROBLEM: 11 is lost, and extra 21 has been added.
//
// More complicated example:
//
// TEST2: BEFORE UNIQ: 10,20,21,22,30,31,23,24,11
// TEST2: AFTER UNIQ: 10,20,30,23,11,31,23,24,11
// DUP_INX=5
//
// Problem: 21 and 22 are deleted.
// Problem: 11 and 23 are duplicated.
//
//
// NOW if ptgi::unique is called instead of std::unique, both problems go away:
//
// DEBUG: TEST1: NEW_WAY=1
// TEST1: BEFORE UNIQ: 10,11,21
// TEST1: AFTER UNIQ: 10,21,11
// DUP_INX=2
//
// DEBUG: TEST2: NEW_WAY=1
// TEST2: BEFORE UNIQ: 10,20,21,22,30,31,23,24,11
// TEST2: AFTER UNIQ: 10,20,30,23,11,31,22,24,21
// DUP_INX=5
//
// @SEE: look at the "case study" below to understand which the last "AFTER UNIQ" results with that order:
// TEST2: AFTER UNIQ: 10,20,30,23,11,31,22,24,21
//
//==========================================================================================================
// Case Study: how ptgi::unique() works:
// Remember we "remove adjacent duplicates".
// In this example, the input is NOT fully sorted when ptgi:unique() is called.
//
// I put | separatators, BEFORE UNIQ to illustrate this
// 10 | 20,21,22 | 30,31 | 23,24 | 11
//
// In example above, 20, 21, 22 are "same" since dividing by 10 gives 2 quotient.
// And 30,31 are "same", since /10 quotient is 3.
// And 23, 24 are same, since /10 quotient is 2.
// And 11 is "group of one" by itself.
// So there are 5 groups, but the 4th group (23, 24) happens to be equal to group 2 (20, 21, 22)
// So there are 5 groups, and the 5th group (11) is equal to group 1 (10)
//
// R = result
// F = first
//
// 10, 20, 21, 22, 30, 31, 23, 24, 11
// R F
//
// 10 is result, and first points to 20, and R != F (10 != 20) so bump R:
// R
// F
//
// Now we hits the "optimized out swap logic".
// (avoid swap because R == F)
//
// // now bump F until R != F (integer division by 10)
// 10, 20, 21, 22, 30, 31, 23, 24, 11
// R F // 20 == 21 in 10x
// R F // 20 == 22 in 10x
// R F // 20 != 30, so we do a swap of ++R and F
// (Now first hits 21, 22, then finally 30, which is different than R, so we swap bump R to 21 and swap with 30)
// 10, 20, 30, 22, 21, 31, 23, 24, 11 // after R & F swap (21 and 30)
// R F
//
// 10, 20, 30, 22, 21, 31, 23, 24, 11
// R F // bump F to 31, but R and F are same (30 vs 31)
// R F // bump F to 23, R != F, so swap ++R with F
// 10, 20, 30, 22, 21, 31, 23, 24, 11
// R F // bump R to 22
// 10, 20, 30, 23, 21, 31, 22, 24, 11 // after the R & F swap (22 & 23 swap)
// R F // will swap 22 and 23
// R F // bump F to 24, but R and F are same in 10x
// R F // bump F, R != F, so swap ++R with F
// R F // R and F are diff, so swap ++R with F (21 and 11)
// 10, 20, 30, 23, 11, 31, 22, 24, 21
// R F // aftter swap of old 21 and 11
// R F // F now at last(), so loop terminates
// R F // bump R by 1 to point to dupPostion (first duplicate in range)
//
// return R which now points to 31
//==========================================================================================================
// NOTES:
// 1) the #ifdef IMPROVED_STD_UNIQUE_ALGORITHM documents how we have modified the original std::unique().
// 2) I've heavily unit tested this code, including using valgrind(1), and it is *believed* to be 100% defect-free.
//
//==========================================================================================================
// History:
// 130201 dpb [email protected] created
//==========================================================================================================
#ifndef PTGI_UNIQUE_HPP
#define PTGI_UNIQUE_HPP
// Created to solve memory leak problems when calling std::unique() on a vector<Route*>.
// Memory leaks discovered with valgrind and unitTesting.
#include <algorithm> // std::swap
// instead of std::myUnique, call this instead, where arg3 is a function ptr
//
// like std::unique, it puts the dups at the end, but it uses swapping to preserve original
// vector contents, to avoid memory leaks and duplicate pointers in vector<Object*>.
#ifdef IMPROVED_STD_UNIQUE_ALGORITHM
#error the #ifdef for IMPROVED_STD_UNIQUE_ALGORITHM was defined previously.. Something is wrong.
#endif
#undef IMPROVED_STD_UNIQUE_ALGORITHM
#define IMPROVED_STD_UNIQUE_ALGORITHM
// similar to std::unique, except that this version swaps elements, to avoid
// memory leaks, when vector contains pointers.
//
// Normally the input is sorted.
// Normal std::unique:
// 10 20 20 20 30 30 20 20 10
// a b c d e f g h i
//
// 10 20 30 20 10 | 30 20 20 10
// a b e g i f g h i
//
// Now GONE: c, d.
// Now DUPS: g, i.
// This causes memory leaks and segmenation faults due to duplicate deletes of same pointer!
namespace ptgi {
// Return the position of the first in range of duplicates moved to end of vector.
//
// uses operator== of class for comparison
//
// @param [first, last) is a range to find duplicates within.
//
// @return the dupPosition position, such that [dupPosition, end) are contiguous
// duplicate elements.
// IF all items are unique, then it would return last.
//
template <class ForwardIterator>
ForwardIterator unique( ForwardIterator first, ForwardIterator last)
{
// compare iterators, not values
if (first == last)
return last;
// remember the current item that we are looking at for uniqueness
ForwardIterator result = first;
// result is slow ptr where to store next unique item
// first is fast ptr which is looking at all elts
// the first iterator moves over all elements [begin+1, end).
// while the current item (result) is the same as all elts
// to the right, (first) keeps going, until you find a different
// element pointed to by *first. At that time, we swap them.
while (++first != last)
{
if (!(*result == *first))
{
#ifdef IMPROVED_STD_UNIQUE_ALGORITHM
// inc result, then swap *result and *first
// THIS IS WHAT WE WANT TO DO.
// BUT THIS COULD SWAP AN ELEMENT WITH ITSELF, UNCECESSARILY!!!
// std::swap( *first, *(++result));
// BUT avoid swapping with itself when both iterators are the same
++result;
if (result != first)
std::swap( *first, *result);
#else
// original code found in std::unique()
// copies unique down
*(++result) = *first;
#endif
}
}
return ++result;
}
template <class ForwardIterator, class BinaryPredicate>
ForwardIterator unique( ForwardIterator first, ForwardIterator last, BinaryPredicate pred)
{
if (first == last)
return last;
// remember the current item that we are looking at for uniqueness
ForwardIterator result = first;
while (++first != last)
{
if (!pred(*result,*first))
{
#ifdef IMPROVED_STD_UNIQUE_ALGORITHM
// inc result, then swap *result and *first
// THIS COULD SWAP WITH ITSELF UNCECESSARILY
// std::swap( *first, *(++result));
//
// BUT avoid swapping with itself when both iterators are the same
++result;
if (result != first)
std::swap( *first, *result);
#else
// original code found in std::unique()
// copies unique down
// causes memory leaks, and duplicate ptrs
// and uncessarily moves in place!
*(++result) = *first;
#endif
}
}
return ++result;
}
// from now on, the #define is no longer needed, so get rid of it
#undef IMPROVED_STD_UNIQUE_ALGORITHM
} // end ptgi:: namespace
#endif
And here is the UNIT Test program that I used to test it:
// QUESTION: in test2, I had trouble getting one line to compile,which was caused by the declaration of operator()
// in the equal_to Predicate. I'm not sure how to correctly resolve that issue.
// Look for //OUT lines
//
// Make sure that NOTES in ptgi_unique.hpp are correct, in how we should "cleanup" duplicates
// from both a vector<Integer> (test1()) and vector<Integer*> (test2).
// Run this with valgrind(1).
//
// In test2(), IF we use the call to std::unique(), we get this problem:
//
// [dbednar@ipeng8 TestSortRoutes]$ ./Main7
// TEST2: ORIG nums before UNIQUE: 10, 20, 21, 22, 30, 31, 23, 24, 11
// TEST2: modified nums AFTER UNIQUE: 10, 20, 30, 23, 11, 31, 23, 24, 11
// INFO: dupInx=5
// TEST2: uniq = 10
// TEST2: uniq = 20
// TEST2: uniq = 30
// TEST2: uniq = 33427744
// TEST2: uniq = 33427808
// Segmentation fault (core dumped)
//
// And if we run valgrind we seen various error about "read errors", "mismatched free", "definitely lost", etc.
//
// valgrind --leak-check=full ./Main7
// ==359== Memcheck, a memory error detector
// ==359== Command: ./Main7
// ==359== Invalid read of size 4
// ==359== Invalid free() / delete / delete[]
// ==359== HEAP SUMMARY:
// ==359== in use at exit: 8 bytes in 2 blocks
// ==359== LEAK SUMMARY:
// ==359== definitely lost: 8 bytes in 2 blocks
// But once we replace the call in test2() to use ptgi::unique(), all valgrind() error messages disappear.
//
// 130212 dpb [email protected] created
// =========================================================================================================
#include <iostream> // std::cout, std::cerr
#include <string>
#include <vector> // std::vector
#include <sstream> // std::ostringstream
#include <algorithm> // std::unique()
#include <functional> // std::equal_to(), std::binary_function()
#include <cassert> // assert() MACRO
#include "ptgi_unique.hpp" // ptgi::unique()
// Integer is small "wrapper class" around a primitive int.
// There is no SETTER, so Integer's are IMMUTABLE, just like in JAVA.
class Integer
{
private:
int num;
public:
// default CTOR: "Integer zero;"
// COMPRENSIVE CTOR: "Integer five(5);"
Integer( int num = 0 ) :
num(num)
{
}
// COPY CTOR
Integer( const Integer& rhs) :
num(rhs.num)
{
}
// assignment, operator=, needs nothing special... since all data members are primitives
// GETTER for 'num' data member
// GETTER' are *always* const
int getNum() const
{
return num;
}
// NO SETTER, because IMMUTABLE (similar to Java's Integer class)
// @return "num"
// NB: toString() should *always* be a const method
//
// NOTE: it is probably more efficient to call getNum() intead
// of toString() when printing a number:
//
// BETTER to do this:
// Integer five(5);
// std::cout << five.getNum() << "\n"
// than this:
// std::cout << five.toString() << "\n"
std::string toString() const
{
std::ostringstream oss;
oss << num;
return oss.str();
}
};
// convenience typedef's for iterating over std::vector<Integer>
typedef std::vector<Integer>::iterator IntegerVectorIterator;
typedef std::vector<Integer>::const_iterator ConstIntegerVectorIterator;
// convenience typedef's for iterating over std::vector<Integer*>
typedef std::vector<Integer*>::iterator IntegerStarVectorIterator;
typedef std::vector<Integer*>::const_iterator ConstIntegerStarVectorIterator;
// functor used for std::unique or ptgi::unique() on a std::vector<Integer>
// Two numbers equal if, when divided by 10 (integer division), the quotients are the same.
// Hence 50..59 are equal, 60..69 are equal, etc.
struct IntegerEqualByTen: public std::equal_to<Integer>
{
bool operator() (const Integer& arg1, const Integer& arg2) const
{
return ((arg1.getNum()/10) == (arg2.getNum()/10));
}
};
// functor used for std::unique or ptgi::unique on a std::vector<Integer*>
// Two numbers equal if, when divided by 10 (integer division), the quotients are the same.
// Hence 50..59 are equal, 60..69 are equal, etc.
struct IntegerEqualByTenPointer: public std::equal_to<Integer*>
{
// NB: the Integer*& looks funny to me!
// TECHNICAL PROBLEM ELSEWHERE so had to remove the & from *&
//OUT bool operator() (const Integer*& arg1, const Integer*& arg2) const
//
bool operator() (const Integer* arg1, const Integer* arg2) const
{
return ((arg1->getNum()/10) == (arg2->getNum()/10));
}
};
void test1();
void test2();
void printIntegerStarVector( const std::string& msg, const std::vector<Integer*>& nums );
int main()
{
test1();
test2();
return 0;
}
// test1() uses a vector<Object> (namely vector<Integer>), so there is no problem with memory loss
void test1()
{
int data[] = { 10, 20, 21, 22, 30, 31, 23, 24, 11};
// turn C array into C++ vector
std::vector<Integer> nums(data, data+9);
// arg3 is a functor
IntegerVectorIterator dupPosition = ptgi::unique( nums.begin(), nums.end(), IntegerEqualByTen() );
nums.erase(dupPosition, nums.end());
nums.erase(nums.begin(), dupPosition);
}
//==================================================================================
// test2() uses a vector<Integer*>, so after ptgi:unique(), we have to be careful in
// how we eliminate the duplicate Integer objects stored in the heap.
//==================================================================================
void test2()
{
int data[] = { 10, 20, 21, 22, 30, 31, 23, 24, 11};
// turn C array into C++ vector of Integer* pointers
std::vector<Integer*> nums;
// put data[] integers into equivalent Integer* objects in HEAP
for (int inx = 0; inx < 9; ++inx)
{
nums.push_back( new Integer(data[inx]) );
}
// print the vector<Integer*> to stdout
printIntegerStarVector( "TEST2: ORIG nums before UNIQUE", nums );
// arg3 is a functor
#if 1
// corrected version which fixes SEGMENTATION FAULT and all memory leaks reported by valgrind(1)
// I THINK we want to use new C++11 cbegin() and cend(),since the equal_to predicate is passed "Integer *&"
// DID NOT COMPILE
//OUT IntegerStarVectorIterator dupPosition = ptgi::unique( const_cast<ConstIntegerStarVectorIterator>(nums.begin()), const_cast<ConstIntegerStarVectorIterator>(nums.end()), IntegerEqualByTenPointer() );
// DID NOT COMPILE when equal_to predicate declared "Integer*& arg1, Integer*& arg2"
//OUT IntegerStarVectorIterator dupPosition = ptgi::unique( const_cast<nums::const_iterator>(nums.begin()), const_cast<nums::const_iterator>(nums.end()), IntegerEqualByTenPointer() );
// okay when equal_to predicate declared "Integer* arg1, Integer* arg2"
IntegerStarVectorIterator dupPosition = ptgi::unique(nums.begin(), nums.end(), IntegerEqualByTenPointer() );
#else
// BUGGY version that causes SEGMENTATION FAULT and valgrind(1) errors
IntegerStarVectorIterator dupPosition = std::unique( nums.begin(), nums.end(), IntegerEqualByTenPointer() );
#endif
printIntegerStarVector( "TEST2: modified nums AFTER UNIQUE", nums );
int dupInx = dupPosition - nums.begin();
std::cout << "INFO: dupInx=" << dupInx <<"\n";
// delete the dup Integer* objects in the [dupPosition, end] range
for (IntegerStarVectorIterator iter = dupPosition; iter != nums.end(); ++iter)
{
delete (*iter);
}
// shrink the vector
// NB: the Integer* ptrs are NOT followed by vector::erase()
nums.erase(dupPosition, nums.end());
// print the uniques, by following the iter to the Integer* pointer
for (IntegerStarVectorIterator iter = nums.begin(); iter != nums.end(); ++iter)
{
std::cout << "TEST2: uniq = " << (*iter)->getNum() << "\n";
}
// remove the unique objects from heap
for (IntegerStarVectorIterator iter = nums.begin(); iter != nums.end(); ++iter)
{
delete (*iter);
}
// shrink the vector
nums.erase(nums.begin(), nums.end());
// the vector should now be completely empty
assert( nums.size() == 0);
}
//@ print to stdout the string: "info_msg: num1, num2, .... numN\n"
void printIntegerStarVector( const std::string& msg, const std::vector<Integer*>& nums )
{
std::cout << msg << ": ";
int inx = 0;
ConstIntegerStarVectorIterator iter;
// use const iterator and const range!
// NB: cbegin() and cend() not supported until LATER (c++11)
for (iter = nums.begin(), inx = 0; iter != nums.end(); ++iter, ++inx)
{
// output a comma seperator *AFTER* first
if (inx > 0)
std::cout << ", ";
// call Integer::toString()
std::cout << (*iter)->getNum(); // send int to stdout
// std::cout << (*iter)->toString(); // also works, but is probably slower
}
// in conclusion, add newline
std::cout << "\n";
}
2017 Update: Henry's answer may be a little off the mark here. If you look for data-channel-external-id
in the source code you may find more than one ID, and only the first occurrence is actually correct. Get the channel_id
used in <link rel="alternate" type="application/rss+xml" title="RSS" href="https://www.youtube.com/feeds/videos.xml?channel_id=<VALUE_HERE">
instead.
The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).
WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.
For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:
ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.
Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.
In the scenarios listed below you should go for WCF:
WEB API is a framework for developing RESTful/HTTP services.
There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.
HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.
Here's a very pragmatic idiom:
(cd $dir) || return # Is this a directory,
# and do we have access?
I typically wrap it in a function:
can_use_as_dir() {
(cd ${1:?pathname expected}) || return
}
Or:
assert_dir_access() {
(cd ${1:?pathname expected}) || exit
}
The nice thing about this approach is that I do not have to think of a good error message.
cd
will give me a standard one line message to standard error already. It will also give more information than I will be able to provide. By performing the cd
inside a subshell ( ... )
, the command does not affect the current directory of the caller. If the directory exists, this subshell and the function are just a no-op.
Next is the argument that we pass to cd
: ${1:?pathname expected}
. This is a more elaborate form of parameter substitution which is explained in more detail below.
Tl;dr: If the string passed into this function is empty, we again exit from the subshell ( ... )
and return from the function with the given error message.
Quoting from the ksh93
man page:
${parameter:?word}
If
parameter
is set and is non-null then substitute its value; otherwise, printword
and exit from the shell (if not interactive). Ifword
is omitted then a standard message is printed.
and
If the colon
:
is omitted from the above expressions, then the shell only checks whether parameter is set or not.
The phrasing here is peculiar to the shell documentation, as word
may refer to any reasonable string, including whitespace.
In this particular case, I know that the standard error message 1: parameter not set
is not sufficient, so I zoom in on the type of value that we expect here - the pathname
of a directory.
A philosophical note:
The shell is not an object oriented language, so the message says pathname
, not directory
. At this level, I'd rather keep it simple - the arguments to a function are just strings.
If it is only to add a new tuple and you are sure that there are no collisions in the inner dictionary, you can do this:
def addNameToDictionary(d, tup):
if tup[0] not in d:
d[tup[0]] = {}
d[tup[0]][tup[1]] = [tup[2]]
You can do this:
conf.CreateMap<SourceType, DestinationType>()
.ForSourceMember(x => x.SourceProperty, y => y.Ignore());
Or, in latest version of Automapper, you simply want to tell Automapper to not validate the field
conf.CreateMap<SourceType, DestinationType>()
.ForSourceMember(x => x.SourceProperty, y => y.DoNotValidate());
There are pre-release (beta) versions of NCover available for free. They work fine for most cases, especially when combined with NCoverExplorer.
SQL> -- original . . .
SQL> select
2 to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ) dt
3 from dual;
DT
----------------------------------------
Friday the 13th of May , 2016
SQL>
SQL> -- collapse repeated spaces . . .
SQL> select
2 regexp_replace(
3 to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ),
4 ' * *', ' ') datesp
5 from dual;
DATESP
----------------------------------------
Friday the 13th of May , 2016
SQL>
SQL> -- and space before commma . . .
SQL> select
2 regexp_replace(
3 to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ),
4 ' *(,*) *', '\1 ') datesp
5 from dual;
DATESP
----------------------------------------
Friday the 13th of May, 2016
SQL>
SQL> -- space before punctuation . . .
SQL> select
2 regexp_replace(
3 to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ),
4 ' *([.,/:;]*) *', '\1 ') datesp
5 from dual;
DATESP
----------------------------------------
Friday the 13th of May, 2016
The original question addresses a specific narrow use case. For those who need more generic answers here are some examples:
Given the dataframe below:
import pandas as pd
import numpy as np
df = pd.DataFrame([['dog', 'hound', 5],
['cat', 'ragdoll', 1]],
columns=['animal', 'type', 'age'])
In[1]:
Out[1]:
animal type age
----------------------
0 dog hound 5
1 cat ragdoll 1
Below we are adding a new description
column as a concatenation of other columns by using the +
operation which is overridden for series. Fancy string formatting, f-strings etc won't work here since the +
applies to scalars and not 'primitive' values:
df['description'] = 'A ' + df.age.astype(str) + ' years old ' \
+ df.type + ' ' + df.animal
In [2]: df
Out[2]:
animal type age description
-------------------------------------------------
0 dog hound 5 A 5 years old hound dog
1 cat ragdoll 1 A 1 years old ragdoll cat
We get 1 years
for the cat (instead of 1 year
) which we will be fixing below using conditionals.
Here we are replacing the original animal
column with values from other columns, and using np.where
to set a conditional substring based on the value of age
:
# append 's' to 'age' if it's greater than 1
df.animal = df.animal + ", " + df.type + ", " + \
df.age.astype(str) + " year" + np.where(df.age > 1, 's', '')
In [3]: df
Out[3]:
animal type age
-------------------------------------
0 dog, hound, 5 years hound 5
1 cat, ragdoll, 1 year ragdoll 1
A more flexible approach is to call .apply()
on an entire dataframe rather than on a single column:
def transform_row(r):
r.animal = 'wild ' + r.type
r.type = r.animal + ' creature'
r.age = "{} year{}".format(r.age, r.age > 1 and 's' or '')
return r
df.apply(transform_row, axis=1)
In[4]:
Out[4]:
animal type age
----------------------------------------
0 wild hound dog creature 5 years
1 wild ragdoll cat creature 1 year
In the code above the transform_row(r)
function takes a Series
object representing a given row (indicated by axis=1
, the default value of axis=0
will provide a Series
object for each column). This simplifies processing since we can access the actual 'primitive' values in the row using the column names and have visibility of other cells in the given row/column.
A file object is an instance of Blob but a blob object is not an instance of File
new File([], 'foo.txt').constructor.name === 'File' //true
new File([], 'foo.txt') instanceof File // true
new File([], 'foo.txt') instanceof Blob // true
new Blob([]).constructor.name === 'Blob' //true
new Blob([]) instanceof Blob //true
new Blob([]) instanceof File // false
new File([], 'foo.txt').constructor.name === new Blob([]).constructor.name //false
If you must convert a file object to a blob object, you can create a new Blob object using the array buffer of the file. See the example below.
let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];
let reader = new FileReader();
reader.onload = function(e) {
let blob = new Blob([new Uint8Array(e.target.result)], {type: file.type });
console.log(blob);
};
reader.readAsArrayBuffer(file);
As pointed by @bgh you can also use the arrayBuffer method of the File object. See the example below.
let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];
file.arrayBuffer().then((arrayBuffer) => {
let blob = new Blob([new Uint8Array(arrayBuffer)], {type: file.type });
console.log(blob);
});
If your environment supports async/await you can use a one-liner like below
let fileToBlob = async (file) => new Blob([new Uint8Array(await file.arrayBuffer())], {type: file.type });
console.log(await fileToBlob(new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'})));
You should not use your domain models
in your views. ViewModels
are the correct way to do it.
You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.
If you never heard of viewmodels, take a look at this.
No, you're not on the right track. A good rule of thumb is: make everything as private as possible. This makes your class more encapsulated, and allows for changing the internals of the class without affecting the code using your class.
If you design your class to be inheritable, then carefully choose what may be overridden and accessible from subclasses, and make that protected (and final, talking of Java, if you want to make it accessible but not overridable). But be aware that, as soon as you accept to have subclasses of your class, and there is a protected field or method, this field or method is part of the public API of the class, and may not be changed later without breaking subclasses.
A class that is not intended to be inherited should be made final (in Java). You might relax some access rules (private to protected, final to non-final) for the sake of unit-testing, but then document it, and make it clear that although the method is protected, it's not supposed to be overridden.
now
is a class method in the class datetime
in the module datetime
. So you need
datetime.datetime.now()
Or you can use a different import
from datetime import datetime
Done this way allows you to use datetime.now
as per the code in the question.
I often just open the console and look for the solution in the objects methods. Quite often it's already there:
>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello s'
Short answer: Use string.replace()
.
Teylyn's answer worked great for me, but I had to modify it a bit to get proper results. I want to provide an extended explanation for whoever would need it.
My setup was as follows:
I put the following formula in cell A1 of Sheet3:
=iferror(vlookup(Sheet1!A$1;Sheet2!$A$1:$D$50;column(A1);false);Sheet1!A1)
Read this as follows: Take the value of the first column in Sheet1 (old data). Look up in Sheet2 (updated rows). If present, output the value from the indicated column in Sheet2. On error, output the value for the current column of Sheet1.
Notes:
In my version of the formula, ";" is used as parameter separator instead of ",". That is because I am located in Europe and we use the "," as decimal separator. Change ";" back to "," if you live in a country where "." is the decimal separator.
A$1: means always take column 1 when copying the formula to a cell in a different column. $A$1 means: always take the exact cell A1, even when copying the formula to a different row or column.
After pasting the formula in A1, I extended the range to columns B, C, etc., until the full width of my table was reached. Because of the $-signs used, this gives the following formula's in cells B1, C1, etc.:
=IFERROR(VLOOKUP('Sheet1'!$A1;'Sheet2'!$A$1:$D$50;COLUMN(B1);FALSE);'Sheet1'!B1)
=IFERROR(VLOOKUP('Sheet1'!$A1;'Sheet2'!$A$1:$D$50;COLUMN(C1);FALSE);'Sheet1'!C1)
and so forth. Note that the lookup is still done in the first column. This is because VLOOKUP needs the lookup data to be sorted on the column where the lookup is done. The output column is however the column where the formula is pasted.
Next, select a rectangle in Sheet 3 starting at A1 and having the size of the data in Sheet1 (same number of rows and columns). Press Ctrl-D to copy the formulas of the first row to all selected cells.
Cells A2, A3, etc. will get these formulas:
=IFERROR(VLOOKUP('Sheet1'!$A2;'Sheet2'!$A$1:$D$50;COLUMN(A2);FALSE);'Sheet1'!A2)
=IFERROR(VLOOKUP('Sheet1'!$A3;'Sheet2'!$A$1:$D$50;COLUMN(A3);FALSE);'Sheet1'!A3)
Because of the use of $-signs, the lookup area is constant, but input data is used from the current row.
For me it worked using flexbox, which is in my opinion the cleanest solution.
Add a css class around the parent div / element with :
.parent {
display: flex;
}
and for the button use:
.button {
justify-content: center;
}
You should use a parent div, otherwise the button doesn't 'know' what the middle of the page / element is.
If this is not working, try :
#wrapper {
display:flex;
justify-content: center;
}
Motif: *args
and **kwargs
serves as a placeholder for the arguments that need to be passed to a function call
using *args
and **kwargs
to call a function
def args_kwargs_test(arg1, arg2, arg3):
print "arg1:", arg1
print "arg2:", arg2
print "arg3:", arg3
Now we'll use *args
to call the above defined function
#args can either be a "list" or "tuple"
>>> args = ("two", 3, 5)
>>> args_kwargs_test(*args)
arg1: two
arg2: 3
arg3: 5
Now, using **kwargs
to call the same function
#keyword argument "kwargs" has to be a dictionary
>>> kwargs = {"arg3":3, "arg2":'two', "arg1":5}
>>> args_kwargs_test(**kwargs)
arg1: 5
arg2: two
arg3: 3
Bottomline : *args
has no intelligence, it simply interpolates the passed args to the parameters(in left-to-right order) while **kwargs
behaves intelligently by placing the appropriate value @ the required place
I faced similar problem a while ago and decided to write Eclipse plug-in that shows complete build path dependency tree of a Java project (although not in graphic mode - result is written into file). The plug-in's sources are here http://github.com/PetrGlad/dependency-tree
//form/descendant::input[@type='submit']
Regarding your last question. Most likely you cant solve this inside a single MSI. If you are using registry/system folders or anything related, the MSI itself must be aware of this and you must prepare a 64bit MSI to properly install on 32 bit machine.
There is a possibility that you can make you product installed as a 32 it application and still be able to make it run as 64 bit one, but i think that may be somewhat hard to achieve.
that being said i think you should be able to keep a single code base for everything. In my current work place we have managed to do so. (but it did took some juggling to make everything play together)
Hope this helps. Heres a link to some info related to 32/64 bit issues: http://blog.typemock.com/2008/07/registry-on-windows-64-bit-double-your.html
A few of the options are deprecated as of today. So watch out for those.
If you try <input onkeypress="blockSpecialCharacters(event)" />
, an IDE like WebStorm
will slash out event and tell you:
Deprecated symbol used, consults docs for better alternative
Then when you get to the JavaScript, console.log(e.keyCode)
will also give keyCode and say:
Deprecated symbol used, consults docs for better alternative
Anyways I did it using jQuery.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>
<input id="theInput" />
<script>
function blockSpecialCharacters(e) {
let key = e.key;
let keyCharCode = key.charCodeAt(0);
// 0-9
if(keyCharCode >= 48 && keyCharCode <= 57) {
return key;
}
// A-Z
if(keyCharCode >= 65 && keyCharCode <= 90) {
return key;
}
// a-z
if(keyCharCode >= 97 && keyCharCode <= 122) {
return key;
}
return false;
}
$('#theInput').keypress(function(e) {
blockSpecialCharacters(e);
});
</script>
The input may be as follows:
a="50"
b=50
c=50.1
d="50.1"
The input of this function can be everything!
Finds whether the given variable is numeric. Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal (e.g. 0xf4c3b00c) and binary (e.g. 0b10100111001) notation is not allowed.
is_numeric function
import ast
import numbers
def is_numeric(obj):
if isinstance(obj, numbers.Number):
return True
elif isinstance(obj, str):
nodes = list(ast.walk(ast.parse(obj)))[1:]
if not isinstance(nodes[0], ast.Expr):
return False
if not isinstance(nodes[-1], ast.Num):
return False
nodes = nodes[1:-1]
for i in range(len(nodes)):
#if used + or - in digit :
if i % 2 == 0:
if not isinstance(nodes[i], ast.UnaryOp):
return False
else:
if not isinstance(nodes[i], (ast.USub, ast.UAdd)):
return False
return True
else:
return False
test:
>>> is_numeric("54")
True
>>> is_numeric("54.545")
True
>>> is_numeric("0x45")
True
is_float function
Finds whether the given variable is float. float strings consist of optional sign, any number of digits, ...
import ast
def is_float(obj):
if isinstance(obj, float):
return True
if isinstance(obj, int):
return False
elif isinstance(obj, str):
nodes = list(ast.walk(ast.parse(obj)))[1:]
if not isinstance(nodes[0], ast.Expr):
return False
if not isinstance(nodes[-1], ast.Num):
return False
if not isinstance(nodes[-1].n, float):
return False
nodes = nodes[1:-1]
for i in range(len(nodes)):
if i % 2 == 0:
if not isinstance(nodes[i], ast.UnaryOp):
return False
else:
if not isinstance(nodes[i], (ast.USub, ast.UAdd)):
return False
return True
else:
return False
test:
>>> is_float("5.4")
True
>>> is_float("5")
False
>>> is_float(5)
False
>>> is_float("5")
False
>>> is_float("+5.4")
True
what is ast?
use str.isdigit() method
>>> a=454
>>> a.isdigit()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'isdigit'
>>> a="454"
>>> a.isdigit()
True
detect int value:
>>> isinstance("54", int)
False
>>> isinstance(54, int)
True
>>>
detect float:
>>> isinstance("45.1", float)
False
>>> isinstance(45.1, float)
True
Use IIF.
<asp:Label ID="Label18" Text='<%# IIF(Eval("item") Is DBNull.Value,"0", Eval("item") %>'
runat="server"></asp:Label>
This is the method I'm using in a project I am currently working on.
var exec = require('child_process').exec;
function execute(command, callback){
exec(command, function(error, stdout, stderr){ callback(stdout); });
};
Example of retrieving a git user:
module.exports.getGitUser = function(callback){
execute("git config --global user.name", function(name){
execute("git config --global user.email", function(email){
callback({ name: name.replace("\n", ""), email: email.replace("\n", "") });
});
});
};
I am using code on xfce - did the following to fix the Tab key behavior:
File -> Preferences -> Settings
search for "keyboard.dispatch"
copy to right panel and change value from "code" to "keyCode"
Reload code
For right labels use ax.yaxis.set_label_position("right")
, i.e.:
f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
ax.yaxis.set_label_position("right")
plt.plot([2,3,4,5])
ax.set_xlabel("$x$ /mm")
ax.set_ylabel("$y$ /mm")
plt.show()
I think its also possible with adhoc queries you can export result to excel file and then import that file into your datatable object or use it as it is and then import the excel file into the second database have a look at this link this can help u alot.
http://vscontrols.blogspot.com/2010/09/import-and-export-excel-to-sql-server.html
You are both using closures.
I 'm going with the Wikipedia definition here:
In computer science, a closure (also lexical closure or function closure) is a function or reference to a function together with a referencing environment—a table storing a reference to each of the non-local variables (also called free variables) of that function. A closure—unlike a plain function pointer—allows a function to access those non-local variables even when invoked outside of its immediate lexical scope.
Your friend's attempt clearly uses the variable i
, which is non-local, by taking its value and making a copy to store into the local i2
.
Your own attempt passes i
(which at the call site is in scope) to an anonymous function as an argument. This is not a closure so far, but then that function returns another function that references the same i2
. Since inside the inner anonymous function i2
is not a local, this creates a closure.
When a treatment of text must be done to just extract data from it, I always think first to the regexes, because:
as far as I know, regexes have been invented for that
iterating over lines appears clumsy to me: it essentially consists to search the newlines then to search the data to extract in each line; that makes two searches instead of a direct unique one with a regex
way of bringing regexes into play is easy; only the writing of a regex string to be compiled into a regex object is sometimes hard, but in this case the treatment with an iteration over lines will be complicated too
For the problem discussed here, a regex solution is fast and easy to write:
import re
names = re.findall('\S+',open(filename).read())
I compared the speeds of several solutions:
import re
from time import clock
A,AA,B1,B2,BS,reg = [],[],[],[],[],[]
D,Dsh,C1,C2 = [],[],[],[]
F1,F2,F3 = [],[],[]
def nonblank_lines(f):
for l in f:
line = l.rstrip()
if line: yield line
def short_nonblank_lines(f):
for l in f:
line = l[0:-1]
if line: yield line
for essays in xrange(50):
te = clock()
with open('raa.txt') as f:
names_listA = [line.strip() for line in f if line.strip()] # Felix Kling
A.append(clock()-te)
te = clock()
with open('raa.txt') as f:
names_listAA = [line[0:-1] for line in f if line[0:-1]] # Felix Kling with line[0:-1]
AA.append(clock()-te)
#-------------------------------------------------------
te = clock()
with open('raa.txt') as f_in:
namesB1 = [ name for name in (l.strip() for l in f_in) if name ] # aaronasterling without list()
B1.append(clock()-te)
te = clock()
with open('raa.txt') as f_in:
namesB2 = [ name for name in (l[0:-1] for l in f_in) if name ] # aaronasterling without list() and with line[0:-1]
B2.append(clock()-te)
te = clock()
with open('raa.txt') as f_in:
namesBS = [ name for name in f_in.read().splitlines() if name ] # a list comprehension with read().splitlines()
BS.append(clock()-te)
#-------------------------------------------------------
te = clock()
with open('raa.txt') as f:
xreg = re.findall('\S+',f.read()) # eyquem
reg.append(clock()-te)
#-------------------------------------------------------
te = clock()
with open('raa.txt') as f_in:
linesC1 = list(line for line in (l.strip() for l in f_in) if line) # aaronasterling
C1.append(clock()-te)
te = clock()
with open('raa.txt') as f_in:
linesC2 = list(line for line in (l[0:-1] for l in f_in) if line) # aaronasterling with line[0:-1]
C2.append(clock()-te)
#-------------------------------------------------------
te = clock()
with open('raa.txt') as f_in:
yD = [ line for line in nonblank_lines(f_in) ] # aaronasterling update
D.append(clock()-te)
te = clock()
with open('raa.txt') as f_in:
yDsh = [ name for name in short_nonblank_lines(f_in) ] # nonblank_lines with line[0:-1]
Dsh.append(clock()-te)
#-------------------------------------------------------
te = clock()
with open('raa.txt') as f_in:
linesF1 = filter(None, (line.rstrip() for line in f_in)) # aaronasterling update 2
F1.append(clock()-te)
te = clock()
with open('raa.txt') as f_in:
linesF2 = filter(None, (line[0:-1] for line in f_in)) # aaronasterling update 2 with line[0:-1]
F2.append(clock()-te)
te = clock()
with open('raa.txt') as f_in:
linesF3 = filter(None, f_in.read().splitlines()) # aaronasterling update 2 with read().splitlines()
F3.append(clock()-te)
print 'names_listA == names_listAA==namesB1==namesB2==namesBS==xreg\n is ',\
names_listA == names_listAA==namesB1==namesB2==namesBS==xreg
print 'names_listA == yD==yDsh==linesC1==linesC2==linesF1==linesF2==linesF3\n is ',\
names_listA == yD==yDsh==linesC1==linesC2==linesF1==linesF2==linesF3,'\n\n\n'
def displ((fr,it,what)): print fr + str( min(it) )[0:7] + ' ' + what
map(displ,(('* ', A, '[line.strip() for line in f if line.strip()] * Felix Kling\n'),
(' ', B1, ' [name for name in (l.strip() for l in f_in) if name ] aaronasterling without list()'),
('* ', C1, 'list(line for line in (l.strip() for l in f_in) if line) * aaronasterling\n'),
('* ', reg, 're.findall("\S+",f.read()) * eyquem\n'),
('* ', D, '[ line for line in nonblank_lines(f_in) ] * aaronasterling update'),
(' ', Dsh, '[ line for line in short_nonblank_lines(f_in) ] nonblank_lines with line[0:-1]\n'),
('* ', F1 , 'filter(None, (line.rstrip() for line in f_in)) * aaronasterling update 2\n'),
(' ', B2, ' [name for name in (l[0:-1] for l in f_in) if name ] aaronasterling without list() and with line[0:-1]'),
(' ', C2, 'list(line for line in (l[0:-1] for l in f_in) if line) aaronasterling with line[0:-1]\n'),
(' ', AA, '[line[0:-1] for line in f if line[0:-1] ] Felix Kling with line[0:-1]\n'),
(' ', BS, '[name for name in f_in.read().splitlines() if name ] a list comprehension with read().splitlines()\n'),
(' ', F2 , 'filter(None, (line[0:-1] for line in f_in)) aaronasterling update 2 with line[0:-1]'),
(' ', F3 , 'filter(None, f_in.read().splitlines() aaronasterling update 2 with read().splitlines()'))
)
Solution with regex is straightforward and neat. Though, it isn't among the fastest ones. The solution of aaronasterling with filter() is surprisigly fast for me (I wasn't aware of this particular filter()'s speed) and times of optimized solutions go down until 27 % of the biggest time. I wonder what makes the miracle of the filter-splitlines association:
names_listA == names_listAA==namesB1==namesB2==namesBS==xreg
is True
names_listA == yD==yDsh==linesC1==linesC2==linesF1==linesF2==linesF3
is True
* 0.08266 [line.strip() for line in f if line.strip()] * Felix Kling
0.07535 [name for name in (l.strip() for l in f_in) if name ] aaronasterling without list()
* 0.06912 list(line for line in (l.strip() for l in f_in) if line) * aaronasterling
* 0.06612 re.findall("\S+",f.read()) * eyquem
* 0.06486 [ line for line in nonblank_lines(f_in) ] * aaronasterling update
0.05264 [ line for line in short_nonblank_lines(f_in) ] nonblank_lines with line[0:-1]
* 0.05451 filter(None, (line.rstrip() for line in f_in)) * aaronasterling update 2
0.04689 [name for name in (l[0:-1] for l in f_in) if name ] aaronasterling without list() and with line[0:-1]
0.04582 list(line for line in (l[0:-1] for l in f_in) if line) aaronasterling with line[0:-1]
0.04171 [line[0:-1] for line in f if line[0:-1] ] Felix Kling with line[0:-1]
0.03265 [name for name in f_in.read().splitlines() if name ] a list comprehension with read().splitlines()
0.03638 filter(None, (line[0:-1] for line in f_in)) aaronasterling update 2 with line[0:-1]
0.02198 filter(None, f_in.read().splitlines() aaronasterling update 2 with read().splitlines()
But this problem is particular, the most simple of all: only one name in each line. So the solutions are only games with lines, splitings and [0:-1] cuts.
On the contrary, regex doesn't matter with lines, it straightforwardly finds the desired data: I consider it is a more natural way of resolution, applying from the simplest to the more complex cases, and hence is often the way to be prefered in treatments of texts.
EDIT
I forgot to say that I use Python 2.7 and I measured the above times with a file containing 500 times the following chain
SMITH
JONES
WILLIAMS
TAYLOR
BROWN
DAVIES
EVANS
WILSON
THOMAS
JOHNSON
ROBERTS
ROBINSON
THOMPSON
WRIGHT
WALKER
WHITE
EDWARDS
HUGHES
GREEN
HALL
LEWIS
HARRIS
CLARKE
PATEL
JACKSON
WOOD
TURNER
MARTIN
COOPER
HILL
WARD
MORRIS
MOORE
CLARK
LEE
KING
BAKER
HARRISON
MORGAN
ALLEN
JAMES
SCOTT
PHILLIPS
WATSON
DAVIS
PARKER
PRICE
BENNETT
YOUNG
GRIFFITHS
MITCHELL
KELLY
COOK
CARTER
RICHARDSON
BAILEY
COLLINS
BELL
SHAW
MURPHY
MILLER
COX
RICHARDS
KHAN
MARSHALL
ANDERSON
SIMPSON
ELLIS
ADAMS
SINGH
BEGUM
WILKINSON
FOSTER
CHAPMAN
POWELL
WEBB
ROGERS
GRAY
MASON
ALI
HUNT
HUSSAIN
CAMPBELL
MATTHEWS
OWEN
PALMER
HOLMES
MILLS
BARNES
KNIGHT
LLOYD
BUTLER
RUSSELL
BARKER
FISHER
STEVENS
JENKINS
MURRAY
DIXON
HARVEY
Well, it partly depends what you want to happen if you're actually in a derived class.
For example, suppose SuperClass
is in A.jar and SubClass
is in B.jar, and you're executing code in an instance method declared in SuperClass
but where this
refers to an instance of SubClass
. If you use this.getClass().getResource()
it will look relative to SubClass
, in B.jar. I suspect that's usually not what's required.
Personally I'd probably use Foo.class.getResourceAsStream(name)
most often - if you already know the name of the resource you're after, and you're sure of where it is relative to Foo
, that's the most robust way of doing it IMO.
Of course there are times when that's not what you want, too: judge each case on its merits. It's just the "I know this resource is bundled with this class" is the most common one I've run into.
Webpack configuration is being handled by react-scripts. You can find all webpack config inside node_modules react-scripts/config.
And If you want to customize webpack config, you can follow this customize-webpack-config
I finally figured out a solution and create a Kotlin class for it
object KeyboardUtils {
fun showKeyboard(editText: EditText) {
editText.requestFocus()
val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(editText, 0)
}
fun hideKeyboard(editText: EditText) {
val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(editText.windowToken, 0)
}
}
You can also wrap the output of a cmdlet (or pipeline) in @()
to ensure that what you get back is an array rather than a single item.
For instance, dir usually returns a list, but depending on the options, it might return a single object. If you are planning on iterating through the results with a foreach-object, you need to make sure you get a list back. Here's a contrived example:
$results = @( dir c:\autoexec.bat)
One more thing... an empty array (like to initialize a variable) is denoted @()
.
Along with JFileChooser is possible use this:
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
for have a Look and Feel like Windows.
for others settings, view here: https://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html#available
Figured out a workaround: I renamed my lgpl2.1_license.txt
to lgpl2.1_license.txt.py
, and put some triple quotes around the text. Now I don't need to use the data_files
option nor to specify any absolute paths. Making it a Python module is ugly, I know, but I consider it less ugly than specifying absolute paths.
Don't have ECMAScript 2018?
My goal was to make it work as similar as possible to what we are used to with named groups. Whereas in ECMAScript 2018 you can place ?<groupname>
inside the group to indicate a named group, in my solution for older javascript, you can place (?!=<groupname>)
inside the group to do the same thing. So it's an extra set of parenthesis and an extra !=
. Pretty close!
I wrapped all of it into a string prototype function
Features
Instructions
(?!={groupname})
inside each group you want to name()
by putting ?:
at the beginning of that group. These won't be named.arrays.js
// @@pattern - includes injections of (?!={groupname}) for each group
// @@returns - an object with a property for each group having the group's match as the value
String.prototype.matchWithGroups = function (pattern) {
var matches = this.match(pattern);
return pattern
// get the pattern as a string
.toString()
// suss out the groups
.match(/<(.+?)>/g)
// remove the braces
.map(function(group) {
return group.match(/<(.+)>/)[1];
})
// create an object with a property for each group having the group's match as the value
.reduce(function(acc, curr, index, arr) {
acc[curr] = matches[index + 1];
return acc;
}, {});
};
usage
function testRegGroups() {
var s = '123 Main St';
var pattern = /((?!=<house number>)\d+)\s((?!=<street name>)\w+)\s((?!=<street type>)\w+)/;
var o = s.matchWithGroups(pattern); // {'house number':"123", 'street name':"Main", 'street type':"St"}
var j = JSON.stringify(o);
var housenum = o['house number']; // 123
}
result of o
{
"house number": "123",
"street name": "Main",
"street type": "St"
}
Had the exact same problem that is described herein. No matter what I did, following the above examples, to change the location of my WSDL file (in our case from a web server), it was still referencing the original location embedded within the source tree of the server process.
After MANY hours trying to debug this, I noticed that the Exception was always being thrown from the exact same line (in my case 41). Finally this morning, I decided to just send my source client code to our trade partner so they can at least understand how the code looks, but perhaps build their own. To my shock and horror I found a bunch of class files mixed in with my .java files within my client source tree. How bizarre!! I suspect these were a byproduct of the JAX-WS client builder tool.
Once I zapped those silly .class files and performed a complete clean and rebuild of the client code, everything works perfectly!! Redonculous!!
YMMV, Andrew
You only need vanilla JS to find uniques with Array.some and Array.reduce. With ES2015 syntax it's only 62 characters.
a.reduce((c, v) => b.some(w => w === v) ? c : c.concat(v)), b)
Array.some and Array.reduce are supported in IE9+ and other browsers. Just change the fat arrow functions for regular functions to support in browsers that don't support ES2015 syntax.
var a = [1,2,3];
var b = [4,5,6];
// .reduce can return a subset or superset
var uniques = a.reduce(function(c, v){
// .some stops on the first time the function returns true
return (b.some(function(w){ return w === v; }) ?
// if there's a match, return the array "c"
c :
// if there's no match, then add to the end and return the entire array
c.concat(v)}),
// the second param in .reduce is the starting variable. This is will be "c" the first time it runs.
b);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
I assume you're using RollingFileAppender? In which case, it has a property called MaxBackupIndex
which you can set to limit the number of files. For example:
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log
log4j.appender.R.MaxFileSize=100KB
log4j.appender.R.MaxBackupIndex=7
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
As per Where is Maven Installed on Ubuntu it will first create your settings.xml on /usr/share/maven2/, then you can copy to your home folder as jens mentioned
$ cp /usr/share/maven3/conf/settings.xml ~/.m2/settings.xml
You can specify GLOBIGNORE
and use the pattern *
GLOBIGNORE='ignore1:ignore2' scp -r source/* remoteurl:remoteDir
You may wish to have general rules which you combine or override by using export GLOBIGNORE
, but for ad-hoc usage simply the above will do. The :
character is used as delimiter for multiple values.
DateTime.remove({}, callback)
The empty object will match all of them.
In order to install any package,we must first find the setup.exe file.I could not locate this file.so i downloaded this file (or you can do a wget).I am on windows64 bit.So ,if you go to https://cygwin.com/install.html ,you can download setup-x86_64.exe file from the install and updates section,move this setup-x86_64.exe to your c:/cygwin64,and then run it from there ( setup-x86_64.exe -q -P curl)
The correct way would be to specify the input as per your requirement which will give you more flexibility.
The present definition includes the following
LTS : 'h:mm:ss A',
LT : 'h:mm A',
L : 'MM/DD/YYYY',
LL : 'MMMM D, YYYY',
LLL : 'MMMM D, YYYY h:mm A',
LLLL : 'dddd, MMMM D, YYYY h:mm A'
You can use any of these or change the input passed into moment().format().
For example, for your case you can pass moment.utc(dateTime).format('MMMM D, YYYY')
.
This is actually redundant except in cases where you want to override the defaults. All of these settings are implied defaults.
You can verify that by checking your effective POM using this command
mvn help:effective-pom
<finalName>name</finalName>
<directory>target</directory>
<outputDirectory>target/classes</outputDirectory>
<testOutputDirectory>target/test-classes</testOutputDirectory>
<sourceDirectory>src/main/java</sourceDirectory>
<testSourceDirectory>src/test/java</testSourceDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/resources</directory>
</testResource>
</testResources>
For example, if i want to point to a different test resource path or resource path you should use this otherwise you don't.
<resources>
<resource>
<directory>/home/josh/desktop/app_resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>/home/josh/desktop/test_resources</directory>
</testResource>
</testResources>
try something like :
var focusout = false;
$("#Button1").click(function () {
if (focusout == true) {
focusout = false;
return;
}
else {
GetInfo();
}
});
$("#Text1").focusout(function () {
focusout = true;
GetInfo();
});
in my case I added such cyclic resource:
<drawable name="above_shadow">@drawable/above_shadow</drawable>
then changed to
<drawable name="some_name">@drawable/other_name</drawable>
and it worked
select * from
(select
ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType ORDER BY tblFruit_FruitType DESC) as tt
,*
from tblFruit
) a
where a.tt=1
ryeguy, I am currently developing a similar application and my threads number is set to 15. Unfortunately if I increase it at 20, it crashes. So, yes, I think the best way to handle this is to measure whether or not your current configuration allows more or less than a number X of threads.
pip
is designed to upgrade python packages and not to upgrade python itself. pip
shouldn't try to upgrade python when you ask it to do so.
Don't type pip install python
but use an installer instead.
The extension below will allow you to load a Storyboard
and it's associated UIViewController
. Example: If you have a UIViewController
named ModalAlertViewController
and a storyboard named "ModalAlert" e.g.
let vc: ModalAlertViewController = UIViewController.loadStoryboard("ModalAlert")
Will load both the Storyboard
and UIViewController
and vc
will be of type ModalAlertViewController
. Note Assumes that the storyboard's Storyboard ID has the same name as the storyboard and that the storyboard has been marked as Is Initial View Controller.
extension UIViewController {
/// Loads a `UIViewController` of type `T` with storyboard. Assumes that the storyboards Storyboard ID has the same name as the storyboard and that the storyboard has been marked as Is Initial View Controller.
/// - Parameter storyboardName: Name of the storyboard without .xib/nib suffix.
static func loadStoryboard<T: UIViewController>(_ storyboardName: String) -> T? {
let storyboard = UIStoryboard(name: storyboardName, bundle: nil)
if let vc = storyboard.instantiateViewController(withIdentifier: storyboardName) as? T {
vc.loadViewIfNeeded() // ensures vc.view is loaded before returning
return vc
}
return nil
}
}
if you want to ask the user number of lines first:
//array to save line by line
let xInputs = [];
const getInput = async (resolve)=>{
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout,
});
readline.on('line',(line)=>{
readline.close();
xInputs.push(line);
resolve(line);
})
}
const getMultiInput = (numberOfInputLines,callback)=>{
let i = 0;
let p = Promise.resolve();
for (; i < numberOfInputLines; i++) {
p = p.then(_ => new Promise(resolve => getInput(resolve)));
}
p.then(()=>{
callback();
});
}
//get number of lines
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
readline.on('line',(line)=>{
getMultiInput(line,()=>{
//get here the inputs from xinputs array
});
readline.close();
})
_x000D_
You can use toArray() api as follows,
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("ListItem1");
stringList.add("ListItem2");
String[] stringArray = new String[stringList.size()];
stringArray = stringList.toArray(stringList);
Values from the array are,
for(String value : stringList)
{
System.out.println(value);
}
Use insert() to insert an element before a given position.
For instance, with
arr = ['A','B','C']
arr.insert(0,'D')
arr becomes ['D','A','B','C']
because D
is inserted before the element at index 0.
Now, for
arr = ['A','B','C']
arr.insert(4,'D')
arr becomes ['A','B','C','D']
because D
is inserted before the element at index 4 (which is 1 beyond the end of the array).
However, if you are looking to generate all permutations of an array, there are ways to do this already built into Python. The itertools package has a permutation generator.
Here's some example code:
import itertools
arr = ['A','B','C']
perms = itertools.permutations(arr)
for perm in perms:
print perm
will print out
('A', 'B', 'C')
('A', 'C', 'B')
('B', 'A', 'C')
('B', 'C', 'A')
('C', 'A', 'B')
('C', 'B', 'A')
Just in case someone has the same pb. :
I couldn't unmount the mount point (here /mnt
) of a chroot jail.
Here are the commands I typed to investigate :
$ umount /mnt
umount: /mnt: target is busy.
$ df -h | grep /mnt
/dev/mapper/VGTout-rootFS 4.8G 976M 3.6G 22% /mnt
$ fuser -vm /mnt/
USER PID ACCESS COMMAND
/mnt: root kernel mount /mnt
$ lsof +f -- /dev/mapper/VGTout-rootFS
$
As you can notice, even lsof
returns nothing.
Then I had the idea to type this :
$ df -ah | grep /mnt
/dev/mapper/VGTout-rootFS 4.8G 976M 3.6G 22% /mnt
dev 2.9G 0 2.9G 0% /mnt/dev
$ umount /mnt/dev
$ umount /mnt
$ df -ah | grep /mnt
$
Here it was a /mnt/dev
bind to /dev
that I had created to be able to repair my system inside from the chroot jail.
After umounting it, my pb. is now solved.
Use:
git remote prune <remote>
Where <remote>
is a remote source name like origin or upstream.
Example: git remote prune origin
If you want to $broadcast
use the $rootScope
:
$scope.startScanner = function() {
$rootScope.$broadcast('scanner-started');
}
And then to receive, use the $scope
of your controller:
$scope.$on('scanner-started', function(event, args) {
// do what you want to do
});
If you want you can pass arguments when you $broadcast
:
$rootScope.$broadcast('scanner-started', { any: {} });
And then receive them:
$scope.$on('scanner-started', function(event, args) {
var anyThing = args.any;
// do what you want to do
});
Documentation for this inside the Scope docs.
First thing Correctly specify all settings in the .ENV file for Mail.
I LOST 6 HOURS FOR THIS
Example
MAIL_DRIVER=smtp
MAIL_MAILER=smtp
MAIL_HOST=smtp.yandex.ru
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=password //Create password for Apps in settings. NOT PASTE YOUR REAL MAIL PASSWORD
MAIL_ENCRYPTION=SSL
[email protected]
MAIL_FROM_NAME="${APP_NAME}"
Please try below:
DECLARE @Today DATETIME;
SET @Today = '12/5/2007';
SET LANGUAGE Italian;
SELECT DATENAME(month, @Today) AS 'Month Name';
SET LANGUAGE us_english;
SELECT DATENAME(month, @Today) AS 'Month Name' ;
GO
Reference:
https://docs.microsoft.com/en-us/sql/t-sql/statements/set-language-transact-sql
PHP's strlen()
function returns the number of ASCII characters.
strlen('borsc')
-> 5 (bytes)
strlen('boršc')
-> 7 (bytes)
$limit_in_kBytes = 20000;
$pointer = 0;
while(strlen($your_string) > (($pointer + 1) * $limit_in_kBytes)){
$str_to_handle = substr($your_string, ($pointer * $limit_in_kBytes ), $limit_in_kBytes);
// here you can handle (0 - n) parts of string
$pointer++;
}
$str_to_handle = substr($your_string, ($pointer * $limit_in_kBytes), $limit_in_kBytes);
// here you can handle last part of string
.. or you can use a function like this:
function parseStrToArr($string, $limit_in_kBytes){
$ret = array();
$pointer = 0;
while(strlen($string) > (($pointer + 1) * $limit_in_kBytes)){
$ret[] = substr($string, ($pointer * $limit_in_kBytes ), $limit_in_kBytes);
$pointer++;
}
$ret[] = substr($string, ($pointer * $limit_in_kBytes), $limit_in_kBytes);
return $ret;
}
$arr = parseStrToArr($your_string, $limit_in_kBytes = 20000);
String.Format("Hi We have these flights for you: {0}. Which one do you want",
flights);
EDIT: you can even save the "template" string separately (for instance you could store it in a configuration file and retrieve it from there), like this:
string flights = "Flight A, B,C,D";
string template = @"Hi We have these flights for you: {0}. Which one do you want";
Console.WriteLine(String.Format(template, flights));
EDIT2: whoops, sorry I see that @DanPuzey had already suggested something very similar to my EDIT (but somewhat better)
I think I know this one...
Try sending your JSON as JSON by using PHP's header() function:
/**
* Send as JSON
*/
header("Content-Type: application/json", true);
Though you are passing valid JSON, jQuery's $.ajax doesn't think so because it's missing the header.
jQuery used to be fine without the header, but it was changed a few versions back.
ALSO
Be sure that your script is returning valid JSON. Use Firebug or Google Chrome's Developer Tools to check the request's response in the console.
UPDATE
You will also want to update your code to sanitize the $_POST to avoid sql injection attacks. As well as provide some error catching.
if (isset($_POST['get_member'])) {
$member_id = mysql_real_escape_string ($_POST["get_member"]);
$query = "SELECT * FROM `members` WHERE `id` = '" . $member_id . "';";
if ($result = mysql_query( $query )) {
$row = mysql_fetch_array($result);
$type = $row['type'];
$name = $row['name'];
$fname = $row['fname'];
$lname = $row['lname'];
$email = $row['email'];
$phone = $row['phone'];
$website = $row['website'];
$image = $row['image'];
/* JSON Row */
$json = array( "type" => $type, "name" => $name, "fname" => $fname, "lname" => $lname, "email" => $email, "phone" => $phone, "website" => $website, "image" => $image );
} else {
/* Your Query Failed, use mysql_error to report why */
$json = array('error' => 'MySQL Query Error');
}
/* Send as JSON */
header("Content-Type: application/json", true);
/* Return JSON */
echo json_encode($json);
/* Stop Execution */
exit;
}
Use continue;
instead of break;
to enter the next iteration of the loop without executing any more of the contained code.
foreach (Item item in myItemsList)
{
if (item.Name == string.Empty)
{
// Display error message and move to next item in list. Skip/ignore all validation
// that follows beneath
continue;
}
if (item.Weight > 100)
{
// Display error message and move to next item in list. Skip/ignore all validation
// that follows beneath
continue;
}
}
Official docs are here, but they don't add very much color.
\tag
also works in align*
. Example:
\begin{align*}
a(x)^{2} &= bx\tag{1}\\
a(x)^{2} &= b\tag{2}\\
ax &= b\tag{3}\\
a(x)^{2}+bx &= c\tag{4}\\
a(x)^{2}+c &= bx\tag{5}\\
a(x)^{2} &= bx+c\tag{6}\\ \\
Where\quad a, b, c \, \in N
\end{align*}
Output:
No, private fields are not inherited. The only reason is that subclass can not access them directly.
With Scala there is a nice Wrapper spoiwo
You can do it like this:
Workbook(mySheet.withColumns(
Column(autoSized = true),
Column(width = new Width(100, WidthUnit.Character)),
Column(width = new Width(100, WidthUnit.Character)))
)
Try cast (columnName as unsigned)
unsigned is positive value only
If you want to include negative value, then cast (columnName as signed)
,
The difference between sign (negative include) and unsigned (twice the size of sign, but non-negative)
Making use of the tricks in "Getting the last argument passed to a shell script" we can make a simple shell function that should work no matter how many files you want to move:
# Bash only
mvdir() { mkdir -p "${@: -1}" && mv "$@"; }
# Other shells may need to search for the last argument
mvdir() { for last; do true; done; mkdir -p "$last" && mv "$@"; }
You could skip the use of buttord, and instead just pick an order for the filter and see if it meets your filtering criterion. To generate the filter coefficients for a bandpass filter, give butter() the filter order, the cutoff frequencies Wn=[low, high]
(expressed as the fraction of the Nyquist frequency, which is half the sampling frequency) and the band type btype="band"
.
Here's a script that defines a couple convenience functions for working with a Butterworth bandpass filter. When run as a script, it makes two plots. One shows the frequency response at several filter orders for the same sampling rate and cutoff frequencies. The other plot demonstrates the effect of the filter (with order=6) on a sample time series.
from scipy.signal import butter, lfilter
def butter_bandpass(lowcut, highcut, fs, order=5):
nyq = 0.5 * fs
low = lowcut / nyq
high = highcut / nyq
b, a = butter(order, [low, high], btype='band')
return b, a
def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
b, a = butter_bandpass(lowcut, highcut, fs, order=order)
y = lfilter(b, a, data)
return y
if __name__ == "__main__":
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import freqz
# Sample rate and desired cutoff frequencies (in Hz).
fs = 5000.0
lowcut = 500.0
highcut = 1250.0
# Plot the frequency response for a few different orders.
plt.figure(1)
plt.clf()
for order in [3, 6, 9]:
b, a = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = freqz(b, a, worN=2000)
plt.plot((fs * 0.5 / np.pi) * w, abs(h), label="order = %d" % order)
plt.plot([0, 0.5 * fs], [np.sqrt(0.5), np.sqrt(0.5)],
'--', label='sqrt(0.5)')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Gain')
plt.grid(True)
plt.legend(loc='best')
# Filter a noisy signal.
T = 0.05
nsamples = T * fs
t = np.linspace(0, T, nsamples, endpoint=False)
a = 0.02
f0 = 600.0
x = 0.1 * np.sin(2 * np.pi * 1.2 * np.sqrt(t))
x += 0.01 * np.cos(2 * np.pi * 312 * t + 0.1)
x += a * np.cos(2 * np.pi * f0 * t + .11)
x += 0.03 * np.cos(2 * np.pi * 2000 * t)
plt.figure(2)
plt.clf()
plt.plot(t, x, label='Noisy signal')
y = butter_bandpass_filter(x, lowcut, highcut, fs, order=6)
plt.plot(t, y, label='Filtered signal (%g Hz)' % f0)
plt.xlabel('time (seconds)')
plt.hlines([-a, a], 0, T, linestyles='--')
plt.grid(True)
plt.axis('tight')
plt.legend(loc='upper left')
plt.show()
Here are the plots that are generated by this script:
Old question but worth adding an answer if using .NET Core 3.0 or later. JSON serialization/deserialization is built into the framework (System.Text.Json), so you don't have to use third party libraries any more. Here's an example based off the top answer given by @Icarus
using System;
using System.Collections.Generic;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var json = "[{\"Name\":\"John Smith\", \"Age\":35}, {\"Name\":\"Pablo Perez\", \"Age\":34}]";
// use the built in Json deserializer to convert the string to a list of Person objects
var people = System.Text.Json.JsonSerializer.Deserialize<List<Person>>(json);
foreach (var person in people)
{
Console.WriteLine(person.Name + " is " + person.Age + " years old.");
}
}
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
}
}
In my case I had an async void
Method and I replaced with async Task
,so the test run as i expected :
[TestMethod]
public async void SendTest(){}
replace with :
[TestMethod]
public async Task SendTest(){}
A simple solution is to install jshon
library :
jshon -l < /tmp/test.json
2
A StaticResource will be resolved and assigned to the property during the loading of the XAML which occurs before the application is actually run. It will only be assigned once and any changes to resource dictionary ignored.
A DynamicResource assigns an Expression object to the property during loading but does not actually lookup the resource until runtime when the Expression object is asked for the value. This defers looking up the resource until it is needed at runtime. A good example would be a forward reference to a resource defined later on in the XAML. Another example is a resource that will not even exist until runtime. It will update the target if the source resource dictionary is changed.
viewdata: is a dictionary used to store data between View and controller , u need to cast the view data object to its corresponding model in the view to be able to retrieve data from it ...
ViewBag: is a dynamic property similar in its working to the view data, However it is better cuz it doesn't need to be casted to its corressponding model before using it in the view ...
You have to add the size of the legend box to the ylim range
#Plot an empty graph and legend to get the size of the legend
x <-1:10
y <-11:20
plot(x,y,type="n", xaxt="n", yaxt="n")
my.legend.size <-legend("topright",c("Series1","Series2","Series3"),plot = FALSE)
#custom ylim. Add the height of legend to upper bound of the range
my.range <- range(y)
my.range[2] <- 1.04*(my.range[2]+my.legend.size$rect$h)
#draw the plot with custom ylim
plot(x,y,ylim=my.range, type="l")
my.legend.size <-legend("topright",c("Series1","Series2","Series3"))
You could use git reset
(see docs)
Try this code it is already built in c#
int lastDay = DateTime.DaysInMonth (2014, 2);
and the first day is always 1.
Good Luck!
As pointed out by Martijn, glob can only do this through the **
operator introduced in Python 3.5. Since the OP explicitly asked for the glob module, the following will return a lazy evaluation iterator that behaves similarly
import os, glob, itertools
configfiles = itertools.chain.from_iterable(glob.iglob(os.path.join(root,'*.txt'))
for root, dirs, files in os.walk('C:/Users/sam/Desktop/file1/'))
Note that you can only iterate once over configfiles
in this approach though. If you require a real list of configfiles that can be used in multiple operations you would have to create this explicitly by using list(configfiles)
.
I just had a situation that was similar to this, involving the DataTables JQuery library with scrolling enabled.
What turned out to be had nothing to do with Z-indices, but with one of the enclosing divs having the CSS overflow property set as hidden.
I fixed it by adding an event to my element triggering the popover which also changed the overflow property of the responsible div to visible.
You can create a div with the exact same size as the image.
<div class="imageContainer">Some Text</div>
use the css background-image property to show the image
.imageContainer {
width:200px;
height:200px;
background-image: url(locationoftheimage);
}
note: this slichtly tampers the semantics of your document. If needed use javascript to inject the div in the place of a real image.
setting the content-type to undefined would make javascript pass the header data As it is , and over writing the default angular $httpProvider header configurations. Angular $http Documentation
$http({url:url,method:"POST", headers:{'Content-Type':undefined}).then(success,failure);
I use:
var lastPart = path.replace(/\\$/,'').split('\\').pop();
It replaces the last \
so it also works with folders.
I note that the question is simply, "Is there any other way to break all of the loops?" I don't see any qualification but that it not be goto
, in particular the OP didn't ask for a good way. So, how about we longjmp
out of the inner loop? :-)
#include <stdio.h>
#include <setjmp.h>
int main(int argc, char* argv[]) {
int counter = 0;
jmp_buf look_ma_no_goto;
if (!setjmp(look_ma_no_goto)) {
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if (i == 500 && j == 500) {
longjmp(look_ma_no_goto, 1);
}
counter++;
}
}
}
printf("counter=%d\n", counter);
}
The setjmp
function returns twice. The first time, it returns 0 and the program executes the nested for loops. Then when the both i
and j
are 500, it executes longjmp
, which causes setjmp
to return again with the value 1, skipping over the loop.
Not only will longjmp
get you out of nested loops, it works with nested functions too!
While I agree with Tim and Oben Sonne that you should use an XML library, there are ways to still manipulate it as a simple string object.
I likely would not try to use a single file pointer for what you are describing, and instead read the file into memory, edit it, then write it out.:
inFile = open('file.xml', 'r')
data = inFile.readlines()
inFile.close()
# some manipulation on `data`
outFile = open('file.xml', 'w')
outFile.writelines(data)
outFile.close()
There are two steps to fix this.
First edit phpMyAdmin/libraries/DatabaseInterface.class.php
Change:
if (PMA_MYSQL_INT_VERSION > 50503) {
$default_charset = 'utf8mb4';
$default_collation = 'utf8mb4_general_ci';
} else {
$default_charset = 'utf8';
$default_collation = 'utf8_general_ci';
}
To:
//if (PMA_MYSQL_INT_VERSION > 50503) {
// $default_charset = 'utf8mb4';
// $default_collation = 'utf8mb4_general_ci';
//} else {
$default_charset = 'utf8';
$default_collation = 'utf8_general_ci';
//}
Then delete this cookie from your browser "pma_collation_connection".
Or delete all Cookies.
Then restart your phpMyAdmin.
(It would be nice if phpMyAdmin allowed you to set the charset and collation per server in the config.inc.php)
In linux,
sudo vi /etc/sysconfig/jenkins
set following configuration with any available port
JENKINS_PORT="8082"
Check your line endings! If you see an error about the file not being found, followed by this "premature of end headers" error in your Apache log - it may be that you have Windows line endings in your script in instead of Unix style. I ran into that problem / solution.
Dirkgently gives an excellent description of integer division in C99, but you should also know that in C89 integer division with a negative operand has an implementation-defined direction.
From the ANSI C draft (3.3.5):
If either operand is negative, whether the result of the / operator is the largest integer less than the algebraic quotient or the smallest integer greater than the algebraic quotient is implementation-defined, as is the sign of the result of the % operator. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.
So watch out with negative numbers when you are stuck with a C89 compiler.
It's a fun fact that C99 chose truncation towards zero because that was how FORTRAN did it. See this message on comp.std.c.
To remote server
mysqldump mydbname | ssh host2 "mysql mydbcopy"
To local server
mysqldump mydbname | mysql mydbcopy
Another solution could be to use Number object parser like this:
let result = Number(new Date("2012-02-10T13:19:11+0000"));_x000D_
let resultWithGetTime = (new Date("2012-02-10T13:19:11+0000")).getTime();_x000D_
console.log(result);_x000D_
console.log(resultWithGetTime);
_x000D_
This converts to milliseconds just like getTime()
on Date
object
While compiling in RHEL 6.2 (x86_64), I installed both 32bit and 64bit libstdc++-dev packages, but I had the "c++config.h no such file or directory" problem.
Resolution:
The directory /usr/include/c++/4.4.6/x86_64-redhat-linux
was missing.
I did the following:
cd /usr/include/c++/4.4.6/
mkdir x86_64-redhat-linux
cd x86_64-redhat-linux
ln -s ../i686-redhat-linux 32
I'm now able to compile 32bit binaries on a 64bit OS.
Post Value from
Intent ii = new Intent(this, GameStartPage.class);
// ii.putExtra("pkgName", B2MAppsPKGName);
ii.putExtra("pkgName", YourValue);
ii.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(ii);
Get Value from
pkgn = getIntent().getExtras().getString("pkgName");
It really depends on what you're trying to accomplish in your code. I've heard that it's just stuff of urban legend that there is any performance difference between VB.NET, C# and managed C++. However, I've found, at least in string comparisons, that managed C++ beats the pants off of C#, which in turn beats the pants off of VB.NET.
I've by no means done any exhaustive comparisons in algorithmic complexity between the languages. I'm also just using the default settings in each of the languages. In VB.NET I'm using settings to require declaration of variables, etc. Here is the code I'm using for managed C++: (As you can see, this code is quite simple). I'm running the same in the other languages in Visual Studio 2013 with .NET 4.6.2.
#include "stdafx.h"
using namespace System;
using namespace System::Diagnostics;
bool EqualMe(String^ first, String^ second)
{
return first->Equals(second);
}
int main(array<String ^> ^args)
{
Stopwatch^ sw = gcnew Stopwatch();
sw->Start();
for (int i = 0; i < 100000; i++)
{
EqualMe(L"one", L"two");
}
sw->Stop();
Console::WriteLine(sw->ElapsedTicks);
return 0;
}
Greg's answer is right. Note that in Python 3.0 you'll have to do
sorted(dict.items())
as iteritems
will be gone.
It occurred to me that you may have actually be asking how to implement the +
operator for dictionaries, the following seems to work:
>>> class Dict(dict):
... def __add__(self, other):
... copy = self.copy()
... copy.update(other)
... return copy
... def __radd__(self, other):
... copy = other.copy()
... copy.update(self)
... return copy
...
>>> default_data = Dict({'item1': 1, 'item2': 2})
>>> default_data + {'item3': 3}
{'item2': 2, 'item3': 3, 'item1': 1}
>>> {'test1': 1} + Dict(test2=2)
{'test1': 1, 'test2': 2}
Note that this is more overhead then using dict[key] = value
or dict.update()
, so I would recommend against using this solution unless you intend to create a new dictionary anyway.
In my case it was a Chrome extension and Firefox add-on by Avira called "Avira Browser Safety". I had problems with version 1.7.4. In my specific case I wanted to login to a website called gliffy.com for making diagrams, but after logging in I got an blank page. If you use F12 (console) in Chrome you can see all these ERR_BLOCKED_BY_CLIENT (and other) errors.
A Structure of a standerd .gitignore file for Xcode project >
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
Icon?
ehthumbs.db
Thumbs.db
build/
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
!default.xcworkspace
xcuserdata
profile
*.moved-aside
DerivedData
.idea/
double example = 3.1416789645;
double output = Convert.ToDouble(example.ToString("N3"));
Just add water style="display:none";
to the <div>
Fiddles I say: http://jsfiddle.net/krY56/13/
jQuery:
function toggler(divId) {
$("#" + divId).toggle();
}
Preferred to have a CSS Class .hidden
.hidden {
display:none;
}
There's a .val()
method:
If you've got an input with an id of txtEmail
you can use the following code to access the value of the text box:
$("#txtEmail").val()
You can also use the val(string)
method to set that value:
$("#txtEmail").val("something")
You can always try doing it manually from the command prompt. Navigate to the path of the file and type:
gcc filename.c -o filename
The only time you need to set it (or not) is if you need to explicitly check that a variable a
is set exactly to null
or undefined
.
if(a === null) {
}
...is not the same as:
if(a === undefined) {
}
That said, a == null && a == undefined
will return true
.
Try this,
IFS=''
while read line
do
echo $line
done < file.txt
EDIT:
From man bash
IFS - The Internal Field Separator that is used for word
splitting after expansion and to split lines into words
with the read builtin command. The default value is
``<space><tab><newline>''
Without For loop:
Dim newColumn As New Data.DataColumn("Foo", GetType(System.String))
newColumn.DefaultValue = "Your DropDownList value"
table.Columns.Add(newColumn)
C#:
System.Data.DataColumn newColumn = new System.Data.DataColumn("Foo", typeof(System.String));
newColumn.DefaultValue = "Your DropDownList value";
table.Columns.Add(newColumn);
I had issues with trying to delete a returned JSON object and found that it was actually a string. If you JSON.parse() before deleting you can be sure your key will get deleted.
let obj;
console.log(this.getBody()); // {"AED":3.6729,"AZN":1.69805,"BRL":4.0851}
obj = this.getBody();
delete obj["BRL"];
console.log(obj) // {"AED":3.6729,"AZN":1.69805,"BRL":4.0851}
obj = JSON.parse(this.getBody());
delete obj["BRL"];
console.log(obj) // {"AED":3.6729,"AZN":1.69805}
To get body content from javascript ,i have tried the following code:
var frameObj = document.getElementById('id_description_iframe');
var frameContent = frameObj.contentWindow.document.body.innerHTML;
where "id_description_iframe" is your iframe's id. This code is working fine for me.
As Jakob pointed out, android:popupBackground
is the key attribute for the dropdown (opened state of the Spinner), but instead of using just a colour, I got the best results with a 9-patch drawable like this:
menu_dropdown_panel.9.png
Note that it's very easy to generate this 9-patch image for the background colour of your choice, for example using this online tool as I explained in this answer!
So, my Spinner XML definition looks like:
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/navigationBlue"
android:spinnerMode="dropdown"
android:popupBackground="@drawable/menu_dropdown_panel"
/>
And the result:
(For custom fonts, as in the screenshot above, a custom SpinnerAdapter is needed too.)
Works at least on Android 4.0+ (API level 14+).
Try with:
eval $(aws ecr get-login --no-include-email | sed 's|https://||')
before push.
in a Visual Basic Macro you would use
pName = ActiveWorkbook.Path ' the path of the currently active file
wbName = ActiveWorkbook.Name ' the file name of the currently active file
shtName = ActiveSheet.Name ' the name of the currently selected worksheet
The first sheet in a workbook can be referenced by
ActiveWorkbook.Worksheets(1)
so after deleting the [Report] tab you would use
ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name
to "work on that sheet later on" you can create a range object like
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]
and continue working on MySheet(rowNum, colNum)
etc. ...
shortcut creation of a range object without defining shtName:
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]
I am doing integration test, and needed this to debug the generated SQL statement in Entity Framework Core 2.1, so I use DebugLoggerProvider
or ConsoleLoggerProvider
like so:
[Fact]
public async Task MyAwesomeTest
{
//setup log to debug sql queries
var loggerFactory = new LoggerFactory();
loggerFactory.AddProvider(new DebugLoggerProvider());
loggerFactory.AddProvider(new ConsoleLoggerProvider(new ConsoleLoggerSettings()));
var builder = new DbContextOptionsBuilder<DbContext>();
builder
.UseSqlServer("my connection string") //"Server=.;Initial Catalog=TestDb;Integrated Security=True"
.UseLoggerFactory(loggerFactory);
var dbContext = new DbContext(builder.Options);
........
Here is a sample output from Visual Studio console:
I know this is an old post, but I really hate that there is only one answer here that suggests not mixing html and php. Instead of mixing content one should use template systems, or create a basic template system themselves.
In the php
<?php
$var1 = 'Alice'; $var2 = 'apples'; $var3 = 'lunch'; $var4 = 'Bob';
if ($var1 == 'Alice') {
$html = file_get_contents('/path/to/file.html'); //get the html template
$template_placeholders = array('##variable1##', '##variable2##', '##variable3##', '##variable4##'); // variable placeholders inside the template
$template_replace_variables = array($var1, $var2, $var3, $var4); // the variables to pass to the template
$html_output = str_replace($template_placeholders, $template_replace_variables, $html); // replace the placeholders with the actual variable values.
}
echo $html_output;
?>
In the html (/path/to/file.html)
<p>##variable1## ate ##variable2## for ##variable3## with ##variable4##.</p>
The output of this would be:
Alice ate apples for lunch with Bob.
Use <include />
tag.
<include
android:id="@+id/some_id_if_needed"
layout="@layout/some_layout"/>
Also, read Creating Reusable UI Components and Merging Layouts articles.
This error occur when you don't correctly write blocks. Forgetting a ":", or not using "Tab" button for blocks and use spaces. When you are transporting a code from one editor to another editor,it can happen. And never forget this: errors aren't always on that line. I came here for this, but I've forgotten an except after a try. because of my unstandard editor, it happend. But it's possible in normal editor.
The accepted solution here is incorrect. Try this in the HTML:
onchange="setTwoNumberDecimal(this)"
and the function to look like:
function setTwoNumberDecimal(el) {
el.value = parseFloat(el.value).toFixed(2);
};
max-height
.PrimaryNav-container {
...
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease;
...
}
.PrimaryNav.PrimaryNav--isOpen .PrimaryNav-container {
max-height: 300px;
}
Just add this function and call it, it will convert List to DataTable.
public static DataTable ToDataTable<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
//Get all the properties
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
//Defining type of data column gives proper data table
var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
//Setting column names as Property names
dataTable.Columns.Add(prop.Name, type);
}
foreach (T item in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
//inserting property values to datatable rows
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
//put a breakpoint here and check datatable
return dataTable;
}
you can get the nodejs configuration from http://nodejs.org/
The important thing you need to keep in your mind is about its configuration in file app.js which consists of port number host and other settings these are settings working for me
backendSettings = { "scheme":"https / http ", "host":"Your website url", "port":49165, //port number 'sslKeyPath': 'Path for key', 'sslCertPath': 'path for SSL certificate', 'sslCAPath': '', "resource":"/socket.io", "baseAuthPath": '/nodejs/', "publishUrl":"publish", "serviceKey":"", "backend":{ "port":443, "scheme": 'https / http', //whatever is your website scheme "host":"host name", "messagePath":"/nodejs/message/"}, "clientsCanWriteToChannels":false, "clientsCanWriteToClients":false, "extensions":"", "debug":false, "addUserToChannelUrl": 'user/channel/add/:channel/:uid', "publishMessageToContentChannelUrl": 'content/token/message', "transports":["websocket", "flashsocket", "htmlfile", "xhr-polling", "jsonp-polling"], "jsMinification":true, "jsEtag":true, "logLevel":1};
In this if you are getting "Error: listen EADDRINUSE" then please change the port number i.e, here I am using "49165" so you can use other port such as 49170 or some other port.
For this you can refer to the following article
http://www.a2hosting.com/kb/installable-applications/manual-installations/installing-node-js-on-shared-hosting-accounts
Hey guys this is a good way of link w/ image and has lot of props in case you want to css attribute for example replace "alt" or "title" etc.....also including a logical restriction (?)
<%= link_to image_tag("#{request.ssl? ? @image_domain_secure : @image_domain}/images/linkImage.png", {:alt=>"Alt title", :title=>"Link title"}) , "http://www.site.com"%>
Hope this helps!
So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.
protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.my_layout); Bitmap bitmap = getIntent().getParcelableExtra("image"); ImageView imageView = (ImageView) findViewById(R.id.imageview); imageView.setImageBitmap(bitmap); }
You are more vulnerable to attacks if using eval
: JSON is a subset of Javascript and json.parse just parses JSON whereas eval
would leave the door open to all JS expressions.
curl -X PUT -d 'new_value' URL_PATH/key
where,
X - option to be used for request command
d - option to be used in order to put data on remote url
URL_PATH - remote url
new_value - value which we want to put to the server's key
Under iOS 8 and iOS 9 this location is now:
~/Library/Logs/CoreSimulator/<DEVICE_CODE>
So, the following will work:
tail -f ~/Library/Logs/CoreSimulator/<DEVICE_CODE>/system.log
The DEVICE_CODE
value can be found via the following console command:
instruments -s devices
The other answers were good but they involve javascript or they doesn't center the video horizontally AND vertically.
You can use this full CSS solution to have a video that simulate the background-size: cover property:
video {
position: fixed; // Make it full screen (fixed)
right: 0;
bottom: 0;
z-index: -1; // Put on background
min-width: 100%; // Expand video
min-height: 100%;
width: auto; // Keep aspect ratio
height: auto;
top: 50%; // Vertical center offset
left: 50%; // Horizontal center offset
-webkit-transform: translate(-50%,-50%);
-moz-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
transform: translate(-50%,-50%); // Cover effect: compensate the offset
background: url(bkg.jpg) no-repeat; // Background placeholder, not always needed
background-size: cover;
}
The best way for converting to Numpy Array is using '.to_numpy(self, dtype=None, copy=False)'. It is new in version 0.24.0.Refrence
You can also use '.array'.Refrence
Pandas .as_matrix deprecated since version 0.23.0.
Your DOS command 2> nul
Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.
The standard Web Storage, does not say anything about the restoring any of these. So there won't be any standard way to do it. You have to go through the way the browsers implement these, or find a way to backup these before you delete them.
Use pathlib
From Python3.4 onwards.
from pathlib import Path
Path('my_file.mp3').suffix == '.mp3'
Sorry for bumping an old question. I found this via google.
Its also worth noting that its possible to use more than one selector, thus you can target any form element, and not just one specific type.
eg.
$('#myform input,#myform textarea').first().focus();
This will focus the first input or textarea it finds, and of course you can add other selectors into the mix as well. Handy if you can't be certain of a specific element type being first, or if you want something a bit general/reusable.
Starting Python 3.8
, the standard library provides the NormalDist
object as part of the statistics
module:
from statistics import NormalDist
def confidence_interval(data, confidence=0.95):
dist = NormalDist.from_samples(data)
z = NormalDist().inv_cdf((1 + confidence) / 2.)
h = dist.stdev * z / ((len(data) - 1) ** .5)
return dist.mean - h, dist.mean + h
This:
Creates a NormalDist
object from the data sample (NormalDist.from_samples(data)
, which gives us access to the sample's mean and standard deviation via NormalDist.mean
and NormalDist.stdev
.
Compute the Z-score
based on the standard normal distribution (represented by NormalDist()
) for the given confidence using the inverse of the cumulative distribution function (inv_cdf
).
Produces the confidence interval based on the sample's standard deviation and mean.
This assumes the sample size is big enough (let's say more than ~100 points) in order to use the standard normal distribution rather than the student's t distribution to compute the z
value.
Since this questions seems to still get quite a lot of views, it might be useful to note that for Spring 4+ it's easiest to start using Spring Boot
and the Spring Boot starter POMs.
Using Spring Boot there's less dependencies to manage (and thus fewer conflicts), and setting up a working, well integrated Spring Context is a whole lot easier. I highly recommend it.
From here:
The function
ord()
gets the int value of the char. And in case you want to convert back after playing with the number, functionchr()
does the trick.
>>> ord('a')
97
>>> chr(97)
'a'
>>> chr(ord('a') + 3)
'd'
>>>
In Python 2, there was also the unichr
function, returning the Unicode character whose ordinal is the unichr
argument:
>>> unichr(97)
u'a'
>>> unichr(1234)
u'\u04d2'
In Python 3 you can use chr
instead of unichr
.
You can use Create USer to create a user
CREATE LOGIN sam
WITH PASSWORD = '340$Uuxwp7Mcxo7Khy';
USE AdventureWorks;
CREATE USER sam FOR LOGIN sam;
GO
and to Grant (Read-only access) you can use the following
GRANT SELECT TO sam
Hope that helps.
Basically, it depends on the TableModel that you are using for your JTable. If you are using the DefaultTableModel
then you can do it in two ways:
DefaultTableModel dm = (DefaultTableModel)table.getModel();
dm.getDataVector().removeAllElements();
dm.fireTableDataChanged(); // notifies the JTable that the model has changed
or
DefaultTableModel dm = (DefaultTableModel)table.getModel();
while(dm.getRowCount() > 0)
{
dm.removeRow(0);
}
See the JavaDoc of DefaultTableModel for more details
How do I create a new column with Groupby().Sum()?
There are two ways - one straightforward and the other slightly more interesting.
GroupBy.transform()
with 'sum'
@Ed Chum's answer can be simplified, a bit. Call DataFrame.groupby
rather than Series.groupby
. This results in simpler syntax.
# The setup.
df[['Date', 'Data3']]
Date Data3
0 2015-05-08 5
1 2015-05-07 8
2 2015-05-06 6
3 2015-05-05 1
4 2015-05-08 50
5 2015-05-07 100
6 2015-05-06 60
7 2015-05-05 120
df.groupby('Date')['Data3'].transform('sum')
0 55
1 108
2 66
3 121
4 55
5 108
6 66
7 121
Name: Data3, dtype: int64
It's a tad faster,
df2 = pd.concat([df] * 12345)
%timeit df2['Data3'].groupby(df['Date']).transform('sum')
%timeit df2.groupby('Date')['Data3'].transform('sum')
10.4 ms ± 367 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
8.58 ms ± 559 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
GroupBy.sum()
+ Series.map()
I stumbled upon an interesting idiosyncrasy in the API. From what I tell, you can reproduce this on any major version over 0.20 (I tested this on 0.23 and 0.24). It seems like you consistently can shave off a few milliseconds of the time taken by transform
if you instead use a direct function of GroupBy
and broadcast it using map
:
df.Date.map(df.groupby('Date')['Data3'].sum())
0 55
1 108
2 66
3 121
4 55
5 108
6 66
7 121
Name: Date, dtype: int64
Compare with
df.groupby('Date')['Data3'].transform('sum')
0 55
1 108
2 66
3 121
4 55
5 108
6 66
7 121
Name: Data3, dtype: int64
My tests show that map
is a bit faster if you can afford to use the direct GroupBy
function (such as mean
, min
, max
, first
, etc). It is more or less faster for most general situations upto around ~200 thousand records. After that, the performance really depends on the data.
(Left: v0.23, Right: v0.24)
Nice alternative to know, and better if you have smaller frames with smaller numbers of groups. . . but I would recommend transform
as a first choice. Thought this was worth sharing anyway.
Benchmarking code, for reference:
import perfplot
perfplot.show(
setup=lambda n: pd.DataFrame({'A': np.random.choice(n//10, n), 'B': np.ones(n)}),
kernels=[
lambda df: df.groupby('A')['B'].transform('sum'),
lambda df: df.A.map(df.groupby('A')['B'].sum()),
],
labels=['GroupBy.transform', 'GroupBy.sum + map'],
n_range=[2**k for k in range(5, 20)],
xlabel='N',
logy=True,
logx=True
)
You can't. Variables defined inside a method are local to that method.
If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).
Looks like you're using instance methods instead of static ones.
If you don't want to create an object, you should declare all your methods static, so something like
private static void methodName(Argument args...)
If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.
private static int[][] array = new int[3][5];
Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.
Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.
Here's a final (shortened) example of what your code should be like:
public class Test3 {
//Use this array in your methods
private static int[][] scores = new int[3][5];
/* Rather than just "Scores" name it so people know what
* to expect
*/
private static void createScores() {
//Code...
}
//Other methods...
/* Since you're now using static methods, you don't
* have to initialise an object and call its methods.
*/
public static void main(String[] args){
createScores();
MD(); //Don't know what these do
sumD(); //so I'll leave them.
}
}
Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.
without using the System.arraycopy method you can delete an element from an array with the following
int i = 0;
int x = 0;
while(i < oldArray.length){
if(oldArray[i] == 3)i++;
intArray[x] = oldArray[i];
i++;
x++;
}
where 3 is the value you want to remove.
This might work for you:
cat <<! | sed '/aaa=\(bbb\|ccc\|ddd\)/!s/\(aaa=\).*/\1xxx/'
> aaa=bbb
> aaa=ccc
> aaa=ddd
> aaa=[something else]
!
aaa=bbb
aaa=ccc
aaa=ddd
aaa=xxx
It looks like you're running this on Windows (given your H://log.txt
file path).
Try using \r\n
instead of just \n
.
Honestly, \n
is fine; you're probably viewing the log file in notepad or something else that doesn't render non-Windows newlines. Try opening it in a different viewer/editor (e.g. Wordpad).
Different order make it works :)
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />
In the few words - function returns something. You can use function in SQL query. Procedure is part of code to do something with data but you can not invoke procedure from query, you have to run it in PL/SQL block.
just use like this to make anything to center
android:layout_gravity="center"
android:gravity="center"
updated :
android:layout_gravity="center|right"
android:gravity="center|right"
Updated : Just remove MarginBottom from your textview.. Do like this.. for your textView
<LinearLayout
android:id="@+id/linearLayout5"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center" >
<TextView
android:id="@+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center|right"
android:text="hello"
android:textSize="20dp" />
</LinearLayout>
If you are referring to ActiveRecord objects, you have (more than) two ways of doing this:
E.G.
class AddSsl < ActiveRecord::Migration
def self.up
add_column :accounts, :ssl_enabled, :boolean, :default => true
end
def self.down
remove_column :accounts, :ssl_enabled
end
end
More info here: http://api.rubyonrails.org/classes/ActiveRecord/Migration.html
E.G. before_validation_on_create
More info here: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html#M002147
Even though this answer is late, i have summarized the differences below,
Observable:
function
that takes an observer
and returns a function Observer: an object with next, error.
subscribe/unsubscribe
to its data stream, emit
next value to the observer, notify
the observer about errors
and
inform the observer about the stream completion
function to handle next value
,errors and
end of stream(ui events,http responses,data with web sockets).multiple values
over timecancel-able/retry-able
and supports operators such as map,filter,reduce
etc.Observable.create()
- returns Observable that can invoke methods on
-Observer Observable.from()
- converts an array or iterable into
-Observable Observable.fromEvent()
- converts an event into Observable
-Observable.fromPromise()
- converts a Promise into Observable
-Observable.range()
- returns a sequence of integers in the speci?ed rangePromise:
A promise represents a task that will finish in the future;
Promises become resolved by a value
;
Promises get rejected by exceptions;
Not cancellable
and it returns a single value
A promise expose a function (then)
-then returns a new promise
;
-allows for the attachment
of that will be executed based on
state
;
-handlers
are guaranteed
to execute in order attached
;
Maybe you can use float:right;:
.one {_x000D_
padding-left: 1em;_x000D_
text-color: white;_x000D_
display:inline; _x000D_
}_x000D_
.two {_x000D_
background-color: #00ffff;_x000D_
}_x000D_
.pull-right{_x000D_
float:right;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div class="row">_x000D_
<h3 class="one">Text</h3>_x000D_
<button class="btn btn-secondary pull-right">Button</button>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
If you are looking for something in production winston is probably the best choice.
If you just want to do dev stuff quickly, output directly to a file (I think this works only for *nix systems):
nohup node simple-server.js > output.log &
@CarlosLanderas is correct depending on where you've placed the DIV control. The DIV by the way is not technically an ASP control, which is why you cannot find it directly like other controls. But the best way around this is to turn it into an ASP control.
Use asp:Panel instead. It is rendered into a <div>
tag anyway...
<asp:Panel id="divSubmitted" runat="server" style="text-align:center" visible="false">
<asp:Label ID="labSubmitted" runat="server" Text="Roll Call Submitted"></asp:Label>
</asp:Panel>
And in code behind, simply find the Panel control as per normal...
Panel DivCtl1 = (Panel)gvRollCall.FooterRow.FindControl("divSubmitted");
if (DivCtl1 != null)
DivCtl1.Visible = true;
Please note that I've used FooterRow, as my "psuedo div" is inside the footer row of a Gridview control.
Good coding!
This is what I did on windows.
openssl x509 -outform der -in yourPemFilename.pem -out certfileOutName.crt
openssl rsa -in yourPemFilename.pem -out keyfileOutName.key
This one helped me,
res.format({
json:function(){
var responseData = {};
responseData['status'] = 200;
responseData['outputPath'] = outputDirectoryPath;
responseData['sourcePath'] = url;
responseData['message'] = 'Scraping of requested resource initiated.';
responseData['logfile'] = logFileName;
res.json(JSON.stringify(responseData));
}
});
Use Guzzle. It's a "PHP HTTP client that makes it easy to work with HTTP/1.1 and takes the pain out of consuming web services". Working with Guzzle is much easier than working with cURL.
Here's an example from the Web site:
$client = new GuzzleHttp\Client();
$res = $client->get('https://api.github.com/user', [
'auth' => ['user', 'pass']
]);
echo $res->getStatusCode(); // 200
echo $res->getHeader('content-type'); // 'application/json; charset=utf8'
echo $res->getBody(); // {"type":"User"...'
var_export($res->json()); // Outputs the JSON decoded data
SELECT from_unixtime( UNIX_TIMESTAMP(fild_with_timestamp) ) from "your_table"
This work for me
Actually you don't have to create an image at all. drawImage()
will accept a Canvas
as well as an Image
object.
//grab the context from your destination canvas
var destCtx = destinationCanvas.getContext('2d');
//call its drawImage() function passing it the source canvas directly
destCtx.drawImage(sourceCanvas, 0, 0);
Way faster than using an ImageData
object or Image
element.
Note that sourceCanvas
can be a HTMLImageElement, HTMLVideoElement, or a HTMLCanvasElement. As mentioned by Dave in a comment below this answer, you cannot use a canvas drawing context as your source. If you have a canvas drawing context instead of the canvas element it was created from, there is a reference to the original canvas element on the context under context.canvas
.
Here is a jsPerf to demonstrate why this is the only right way to clone a canvas: http://jsperf.com/copying-a-canvas-element
After applying : Tools > preferences > Graphics > Backend > Automatic Just restart the kernel
And you will surely get Interactive Plot. Happy Coding!
With Project JUnion you can use structs in Java by annotating a class with @Struct annotation
@Struct
class Member {
string FirstName;
string LastName;
int BirthYear;
}
More info at the project's website: https://tehleo.github.io/junion/
This is a simple example of JSON parsing by taking example of google map API. This will return City name of given zip code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.Net;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
WebClient client = new WebClient();
string jsonstring;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
jsonstring = client.DownloadString("http://maps.googleapis.com/maps/api/geocode/json?address="+txtzip.Text.Trim());
dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);
Response.Write(dynObj.results[0].address_components[1].long_name);
}
}
}
To get the form that the submit is inside why not just
this.form
Easiest & quickest path to the result.
The easiest way to fix this was to press (CTRL) and (,) in VS Code to open Settings.
After that, on the search bar search for code runner, then scroll down and search for Run In Terminal and check that box as highlighted in the below image:
You need module.exports:
Exports
An object which is shared between all instances of the current module and made accessible through require(). exports is the same as the module.exports object. See src/node.js for more information. exports isn't actually a global but rather local to each module.
For example, if you would like to expose variableName
with value "variableValue"
on sourceFile.js
then you can either set the entire exports as such:
module.exports = { variableName: "variableValue" };
Or you can set the individual value with:
module.exports.variableName = "variableValue";
To consume that value in another file, you need to require(...)
it first (with relative pathing):
const sourceFile = require('./sourceFile');
console.log(sourceFile.variableName);
Alternatively, you can deconstruct it.
const { variableName } = require('./sourceFile');
// current directory --^
// ../ would be one directory down
// ../../ is two directories down
If all you want out of the file is variableName
then
const variableName = 'variableValue'
module.exports = variableName
const variableName = require('./sourceFile')
Since Node.js version 8.9.0, you can also use ECMAScript Modules with varying levels of support. The documentation.
--experimental-modules
Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements within ES module code:
- Files ending in
.mjs
.
.js
when the nearest parent package.json
file contains a top-level field "type"
with a value of "module"
.--eval
or --print
, or piped to node via STDIN, with the flag --input-type=module
.Once you have it setup, you can use import
and export
.
Using the example above, there are two approaches you can take
// This is a named export of variableName
export const variableName = 'variableValue'
// Alternatively, you could have exported it as a default.
// For sake of explanation, I'm wrapping the variable in an object
// but it is not necessary.
// You can actually omit declaring what variableName is here.
// { variableName } is equivalent to { variableName: variableName } in this case.
export default { variableName: variableName }
// There are three ways of importing.
// If you need access to a non-default export, then
// you use { nameOfExportedVariable }
import { variableName } from './sourceFile'
console.log(variableName) // 'variableValue'
// Otherwise, you simply provide a local variable name
// for what was exported as default.
import sourceFile from './sourceFile'
console.log(sourceFile.variableName) // 'variableValue'
// The third way of importing is for situations where there
// isn't a default export but you want to warehouse everything
// under a single variable. Say you have:
export const a = 'A'
export const b = 'B'
// Then you can import all exports under a single variable
// with the usage of * as:
import * as sourceFileWithoutDefault from './sourceFileWithoutDefault'
console.log(sourceFileWithoutDefault.a) // 'A'
console.log(sourceFileWithoutDefault.b) // 'B'
// You can use this approach even if there is a default export:
import * as sourceFile from './sourceFile'
// Default exports are under the variable default:
console.log(sourceFile.default) // { variableName: 'variableValue' }
// As well as named exports:
console.log(sourceFile.variableName) // 'variableValue
Waterfall methodology is a sequential design process. This means that as each of the eight stages (conception, initiation, analysis, design, construction, testing, implementation, and maintenance) are completed, the developers move on to the next step.
As this process is sequential, once a step has been completed, developers can’t go back to a previous step – not without scratching the whole project and starting from the beginning. There’s no room for change or error, so a project outcome and an extensive plan must be set in the beginning and then followed careful
ACP Agile Certification came about as a “solution” to the disadvantages of the waterfall methodology. Instead of a sequential design process, the Agile methodology follows an incremental approach. Developers start off with a simplistic project design, and then begin to work on small modules. The work on these modules is done in weekly or monthly sprints, and at the end of each sprint, project priorities are evaluated and tests are run. These sprints allow for bugs to be discovered, and customer feedback to be incorporated into the design before the next sprint is run.
The process, with its lack of initial design and steps, is often criticized for its collaborative nature that focuses on principles rather than process.
512 is your best bet. It's used elsewhere and is a nice even number (half of 1024).
Here is how you can do it succinctly in Kotlin:
fun String.isPhoneNumber() =
length in 4..10 && all { it.isDigit() }
Makefiles and build files are about automating your build. If you use a script like MSBuild or NAnt, you can build your project or solution directly from command line. This in turn makes it possible to automate the build, have it run by a build server.
Besides building your solution it is typical that a build script includes task to run unit tests, report code coverage and complexity and more.
The best solution I've found in this is to create a lookup table with the possible values as a primary key, and create a foreign key to the lookup table.
By using CHMOD yes:
For Recursive file:
chmod -R 777 foldername or pathname
For non recursive:
chmod 777 foldername or pathname
try
var fs = require("fs");
var sampleObject = { your data };
fs.writeFile("./object.json", JSON.stringify(sampleObject, null, 4), (err) => {
if (err) { console.error(err); return; };
console.log("File has been created");
});
:: savevars.bat
:: Use $ to prefix any important variable to save it for future runs.
@ECHO OFF
SETLOCAL
REM Load variables
IF EXIST config.txt FOR /F "delims=" %%A IN (config.txt) DO SET "%%A"
REM Change variables
IF NOT DEFINED $RunCount (
SET $RunCount=1
) ELSE SET /A $RunCount+=1
REM Display variables
SET $
REM Save variables
SET $>config.txt
ENDLOCAL
PAUSE
EXIT /B
Output:
$RunCount=1
$RunCount=2
$RunCount=3
The technique outlined above can also be used to share variables among multiple batch files.
The following code example written in Java will allow you to execute any command on a foreign computer through SSH from within a java program. You will need to include the com.jcraft.jsch jar file.
/*
* SSHManager
*
* @author cabbott
* @version 1.0
*/
package cabbott.net;
import com.jcraft.jsch.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
public class SSHManager
{
private static final Logger LOGGER =
Logger.getLogger(SSHManager.class.getName());
private JSch jschSSHChannel;
private String strUserName;
private String strConnectionIP;
private int intConnectionPort;
private String strPassword;
private Session sesConnection;
private int intTimeOut;
private void doCommonConstructorActions(String userName,
String password, String connectionIP, String knownHostsFileName)
{
jschSSHChannel = new JSch();
try
{
jschSSHChannel.setKnownHosts(knownHostsFileName);
}
catch(JSchException jschX)
{
logError(jschX.getMessage());
}
strUserName = userName;
strPassword = password;
strConnectionIP = connectionIP;
}
public SSHManager(String userName, String password,
String connectionIP, String knownHostsFileName)
{
doCommonConstructorActions(userName, password,
connectionIP, knownHostsFileName);
intConnectionPort = 22;
intTimeOut = 60000;
}
public SSHManager(String userName, String password, String connectionIP,
String knownHostsFileName, int connectionPort)
{
doCommonConstructorActions(userName, password, connectionIP,
knownHostsFileName);
intConnectionPort = connectionPort;
intTimeOut = 60000;
}
public SSHManager(String userName, String password, String connectionIP,
String knownHostsFileName, int connectionPort, int timeOutMilliseconds)
{
doCommonConstructorActions(userName, password, connectionIP,
knownHostsFileName);
intConnectionPort = connectionPort;
intTimeOut = timeOutMilliseconds;
}
public String connect()
{
String errorMessage = null;
try
{
sesConnection = jschSSHChannel.getSession(strUserName,
strConnectionIP, intConnectionPort);
sesConnection.setPassword(strPassword);
// UNCOMMENT THIS FOR TESTING PURPOSES, BUT DO NOT USE IN PRODUCTION
// sesConnection.setConfig("StrictHostKeyChecking", "no");
sesConnection.connect(intTimeOut);
}
catch(JSchException jschX)
{
errorMessage = jschX.getMessage();
}
return errorMessage;
}
private String logError(String errorMessage)
{
if(errorMessage != null)
{
LOGGER.log(Level.SEVERE, "{0}:{1} - {2}",
new Object[]{strConnectionIP, intConnectionPort, errorMessage});
}
return errorMessage;
}
private String logWarning(String warnMessage)
{
if(warnMessage != null)
{
LOGGER.log(Level.WARNING, "{0}:{1} - {2}",
new Object[]{strConnectionIP, intConnectionPort, warnMessage});
}
return warnMessage;
}
public String sendCommand(String command)
{
StringBuilder outputBuffer = new StringBuilder();
try
{
Channel channel = sesConnection.openChannel("exec");
((ChannelExec)channel).setCommand(command);
InputStream commandOutput = channel.getInputStream();
channel.connect();
int readByte = commandOutput.read();
while(readByte != 0xffffffff)
{
outputBuffer.append((char)readByte);
readByte = commandOutput.read();
}
channel.disconnect();
}
catch(IOException ioX)
{
logWarning(ioX.getMessage());
return null;
}
catch(JSchException jschX)
{
logWarning(jschX.getMessage());
return null;
}
return outputBuffer.toString();
}
public void close()
{
sesConnection.disconnect();
}
}
For testing.
/**
* Test of sendCommand method, of class SSHManager.
*/
@Test
public void testSendCommand()
{
System.out.println("sendCommand");
/**
* YOU MUST CHANGE THE FOLLOWING
* FILE_NAME: A FILE IN THE DIRECTORY
* USER: LOGIN USER NAME
* PASSWORD: PASSWORD FOR THAT USER
* HOST: IP ADDRESS OF THE SSH SERVER
**/
String command = "ls FILE_NAME";
String userName = "USER";
String password = "PASSWORD";
String connectionIP = "HOST";
SSHManager instance = new SSHManager(userName, password, connectionIP, "");
String errorMessage = instance.connect();
if(errorMessage != null)
{
System.out.println(errorMessage);
fail();
}
String expResult = "FILE_NAME\n";
// call sendCommand for each command and the output
//(without prompts) is returned
String result = instance.sendCommand(command);
// close only after all commands are sent
instance.close();
assertEquals(expResult, result);
}
In my experience, I always just use an external program to generate the graph (mathematica, gnuplot, matlab, etc.) and export the graph as a pdf or eps file. Then I include it into the document with includegraphics
.
In your link.php your echo
statement must be like this:
echo '<a href="pass.php?link=' . $a . '>Link 1</a>';
echo '<a href="pass.php?link=' . $b . '">Link 2</a>';
Then in your pass.php you cannot use $a
because it was not initialized with your intended string value.
You can directly compare it to a string like this:
if($_GET['link'] == 'Link1')
Another way is to initialize the variable first to the same thing you did with link.php. And, a much better way is to include the $a
and $b
variables in a single PHP file, then include that in all pages where you are going to use those variables as Tim Cooper mention on his post. You can also include this in a session.
// image from res/drawable
int resID = getResources().getIdentifier("my_image",
"drawable", getPackageName());
// view
int resID = getResources().getIdentifier("my_resource",
"id", getPackageName());
// string
int resID = getResources().getIdentifier("my_string",
"string", getPackageName());
The difference is the amount of memory allocated to each integer, and how large a number they each can store.
Be careful with the answers above. sqljdbc4.jar is not distributed with under a public license which is why it is difficult to include it in a jar for runtime and distribution. See my answer below for more details and a much better solution. Your life will become much easier as mine did once I found this answer.
A character in Java is a Unicode code-unit which is treated as an unsigned number. So if you perform c = (char)b
the value you get is 2^16 - 56 or 65536 - 56.
Or more precisely, the byte is first converted to a signed integer with the value 0xFFFFFFC8
using sign extension in a widening conversion. This in turn is then narrowed down to 0xFFC8
when casting to a char
, which translates to the positive number 65480
.
From the language specification:
5.1.4. Widening and Narrowing Primitive Conversion
First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).
To get the right point use char c = (char) (b & 0xFF)
which first converts the byte value of b
to the positive integer 200
by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8
becomes 0x000000C8
or the positive number 200
in decimals.
Above is a direct explanation of what happens during conversion between the byte
, int
and char
primitive types.
If you want to encode/decode characters from bytes, use Charset
, CharsetEncoder
, CharsetDecoder
or one of the convenience methods such as new String(byte[] bytes, Charset charset)
or String#toBytes(Charset charset)
. You can get the character set (such as UTF-8 or Windows-1252) from StandardCharsets
.
You can use variable by using keyword "use ($category_id)"
$category_id = array('223','15');
Products::whereIn('id', function($query) use ($category_id){
$query->select('paper_type_id')
->from(with(new ProductCategory)->getTable())
->whereIn('category_id', $category_id )
->where('active', 1);
})->get();