All the 3 first ways are identical. You have make sure that if t
is a matrix you add .
before using multiplication or the power.
for matrix:
t= [1 2 3;2 3 4;3 4 5];
tp=t.*t;
x=exp(-(t.^2));
y=exp(-(t.*t));
z=exp(-(tp));
gives the results:
x =
0.3679 0.0183 0.0001
0.0183 0.0001 0.0000
0.0001 0.0000 0.0000
y =
0.3679 0.0183 0.0001
0.0183 0.0001 0.0000
0.0001 0.0000 0.0000
z=
0.3679 0.0183 0.0001
0.0183 0.0001 0.0000
0.0001 0.0000 0.0000
And using a scalar:
p=3;
pp=p^2;
x=exp(-(p^2));
y=exp(-(p*p));
z=exp(-pp);
gives the results:
x =
1.2341e-004
y =
1.2341e-004
z =
1.2341e-004
Python's power operator is **
and Euler's number is math.e
, so:
from math import e
x.append(1-e**(-value1**2/2*value2**2))
The exponential function is e^x
where e
is a mathematical constant called Euler's number, approximately 2.718281
. This value has a close mathematical relationship with pi
and the slope of the curve e^x
is equal to its value at every point. np.exp()
calculates e^x
for each value of x
in your input array.
You can get the PID of a particular process like MySQL by using following commands: ps -e | pgrep mysql
This command will give you the PID of MySQL rocess. e.g, 13954 Now, type following command on terminal. kill -9 13954 This will kill the process of MySQL.
Workbooks.open("E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm")
Or, in a more structured way...
Sub openwb()
Dim sPath As String, sFile As String
Dim wb As Workbook
sPath = "E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\"
sFile = sPath & "D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm"
Set wb = Workbooks.Open(sFile)
End Sub
Put the data into a Pivot Table and do a top n filter on it
private int compareLists(List<String> list1, List<String> list2){
Collections.sort(list1);
Collections.sort(list2);
int maxIteration = 0;
if(list1.size() == list2.size() || list1.size() < list2.size()){
maxIteration = list1.size();
} else {
maxIteration = list2.size();
}
for (int index = 0; index < maxIteration; index++) {
int result = list1.get(index).compareTo(list2.get(index));
if (result == 0) {
continue;
} else {
return result;
}
}
return list1.size() - list2.size();
}
From your comment to gnibbler answer, i'd say you want a list of pairs of key-value sorted by value:
sorted(data.items(), key=lambda x:x[1])
Light red fill with dark red text.
{'bg_color': '#FFC7CE', 'font_color': '#9C0006'})
Light yellow fill with dark yellow text.
{'bg_color': '#FFEB9C', 'font_color': '#9C6500'})
Green fill with dark green text.
{'bg_color': '#C6EFCE', 'font_color': '#006100'})
a piece of code who work with python to read rs232 just in case somedoby else need it
ser = serial.Serial('/dev/tty.usbserial', 9600, timeout=0.5)
ser.write('*99C\r\n')
time.sleep(0.1)
ser.close()
var inputs = document.querySelectorAll("input[type=text]") ||
(function() {
var ret=[], elems = document.getElementsByTagName('input'), i=0,l=elems.length;
for (;i<l;i++) {
if (elems[i].type.toLowerCase() === "text") {
ret.push(elems[i]);
}
}
return ret;
}());
This is a solution
var s = '[description:"aoeu" uuid:"123sth"]';
var re = /\s*([^[:]+):\"([^"]+)"/g;
var m;
while (m = re.exec(s)) {
console.log(m[1], m[2]);
}
This is based on lawnsea's answer, but shorter.
Notice that the `g' flag must be set to move the internal pointer forward across invocations.
Use toCharArray() method. It splits the string into an array of characters:
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#toCharArray%28%29
String str = "aabbab";
char[] chs = str.toCharArray();
There is no way.
This question is basically a duplicate of Is there a way to hide the new HTML5 spinbox controls shown in Google Chrome & Opera? but maybe not a full duplicate, since the motivation is given.
If the purpose is “browser's awareness of the content being purely numeric”, then you need to consider what that would really mean. The arrows, or spinners, are part of making numeric input more comfortable in some cases. Another part is checking that the content is a valid number, and on browsers that support HTML5 input enhancements, you might be able to do that using the pattern
attribute. That attribute may also affect a third input feature, namely the type of virtual keyboard that may appear.
For example, if the input should be exactly five digits (like postal numbers might be, in some countries), then <input type="text" pattern="[0-9]{5}">
could be adequate. It is of course implementation-dependent how it will be handled.
My solution: I opened the references folder in Solution Explorer (showing all files), and for each assembly that the installation complained about (the name of the assembly may not be exactly the same as the filename of the assembly - within object explorer, but easy enough to figure out), I changed the Copy Local to True. I ended up needing to do that with each Microsoft Office/COM-related assembly.
For php7, I compare parameters type as well, you can have two constructors with same number of parameters but different type.
trait GenericConstructorOverloadTrait
{
/**
* @var array Constructors metadata
*/
private static $constructorsCache;
/**
* Generic constructor
* GenericConstructorOverloadTrait constructor.
*/
public function __construct()
{
$params = func_get_args();
$numParams = func_num_args();
$finish = false;
if(!self::$constructorsCache){
$class = new \ReflectionClass($this);
$constructors = array_filter($class->getMethods(),
function (\ReflectionMethod $method) {
return preg_match("/\_\_construct[0-9]+/",$method->getName());
});
self::$constructorsCache = $constructors;
}
else{
$constructors = self::$constructorsCache;
}
foreach($constructors as $constructor){
$reflectionParams = $constructor->getParameters();
if(count($reflectionParams) != $numParams){
continue;
}
$matched = true;
for($i=0; $i< $numParams; $i++){
if($reflectionParams[$i]->hasType()){
$type = $reflectionParams[$i]->getType()->__toString();
}
if(
!(
!$reflectionParams[$i]->hasType() ||
($reflectionParams[$i]->hasType() &&
is_object($params[$i]) &&
$params[$i] instanceof $type) ||
($reflectionParams[$i]->hasType() &&
$reflectionParams[$i]->getType()->__toString() ==
gettype($params[$i]))
)
) {
$matched = false;
break;
}
}
if($matched){
call_user_func_array(array($this,$constructor->getName()),
$params);
$finish = true;
break;
}
}
unset($constructor);
if(!$finish){
throw new \InvalidArgumentException("Cannot match construct by params");
}
}
}
To use it:
class MultiConstructorClass{
use GenericConstructorOverloadTrait;
private $param1;
private $param2;
private $param3;
public function __construct1($param1, array $param2)
{
$this->param1 = $param1;
$this->param2 = $param2;
}
public function __construct2($param1, array $param2, \DateTime $param3)
{
$this->__construct1($param1, $param2);
$this->param3 = $param3;
}
/**
* @return \DateTime
*/
public function getParam3()
{
return $this->param3;
}
/**
* @return array
*/
public function getParam2()
{
return $this->param2;
}
/**
* @return mixed
*/
public function getParam1()
{
return $this->param1;
}
}
You can import the css file on App.vue, inside the style tag.
<style>
@import './assets/styles/yourstyles.css';
</style>
Also, make sure you have the right loaders installed, if you need any.
I had a list of lists of equal length. Even then Ignacio Vazquez-Abrams
's answer didn't work out for me. I got a 1-D numpy array whose elements are lists. If you faced the same problem, you can use the below method
Use numpy.vstack
import numpy as np
np_array = np.empty((0,4), dtype='float')
for i in range(10)
row_data = ... # get row_data as list
np_array = np.vstack((np_array, np.array(row_data)))
Remove both VALUES and the parenthesis.
INSERT INTO Table2 (LongIntColumn2, CurrencyColumn2)
SELECT LongIntColumn1, Avg(CurrencyColumn) FROM Table1 GROUP BY LongIntColumn1
Most databases have a native UUID type these days to make working with them easier. If yours doesn't, they're just 128-bit numbers, so you can use BINARY(16), and if you need the text format frequently, e.g. for troubleshooting, then add a calculated column to generate it automatically from the binary column. There is no good reason to store the (much larger) text form.
There is simpler approach to decode a ByteBuffer
into a String
without any problems, mentioned by Andy Thomas.
String s = StandardCharsets.UTF_8.decode(byteBuffer).toString();
I did also write a Single Linked List based on some tutorial, which has the basic two Node and Linked List classes, and some additional methods for insertion, delete, reverse, sorting, and such.
It's not the best or easiest, works OK though.
"""
Single Linked List (SLL):
A simple object-oriented implementation of Single Linked List (SLL)
with some associated methods, such as create list, count nodes, delete nodes, and such.
"""
class Node:
"""
Instantiates a node
"""
def __init__(self, value):
"""
Node class constructor which sets the value and link of the node
"""
self.info = value
self.link = None
class SingleLinkedList:
"""
Instantiates the SLL class
"""
def __init__(self):
"""
SLL class constructor which sets the value and link of the node
"""
self.start = None
def create_single_linked_list(self):
"""
Reads values from stdin and appends them to this list and creates a SLL with integer nodes
"""
try:
number_of_nodes = int(input(" Enter a positive integer between 1-50 for the number of nodes you wish to have in the list: "))
if number_of_nodes <= 0 or number_of_nodes > 51:
print(" The number of nodes though must be an integer between 1 to 50!")
self.create_single_linked_list()
except Exception as e:
print(" Error: ", e)
self.create_single_linked_list()
try:
for _ in range(number_of_nodes):
try:
data = int(input(" Enter an integer for the node to be inserted: "))
self.insert_node_at_end(data)
except Exception as e:
print(" Error: ", e)
except Exception as e:
print(" Error: ", e)
def count_sll_nodes(self):
"""
Counts the nodes of the linked list
"""
try:
p = self.start
n = 0
while p is not None:
n += 1
p = p.link
if n >= 1:
print(f" The number of nodes in the linked list is {n}")
else:
print(f" The SLL does not have a node!")
except Exception as e:
print(" Error: ", e)
def search_sll_nodes(self, x):
"""
Searches the x integer in the linked list
"""
try:
position = 1
p = self.start
while p is not None:
if p.info == x:
print(f" YAAAY! We found {x} at position {position}")
return True
#Increment the position
position += 1
#Assign the next node to the current node
p = p.link
else:
print(f" Sorry! We couldn't find {x} at any position. Maybe, you might want to use option 9 and try again later!")
return False
except Exception as e:
print(" Error: ", e)
def display_sll(self):
"""
Displays the list
"""
try:
if self.start is None:
print(" Single linked list is empty!")
return
display_sll = " Single linked list nodes are: "
p = self.start
while p is not None:
display_sll += str(p.info) + "\t"
p = p.link
print(display_sll)
except Exception as e:
print(" Error: ", e)
def insert_node_in_beginning(self, data):
"""
Inserts an integer in the beginning of the linked list
"""
try:
temp = Node(data)
temp.link = self.start
self.start = temp
except Exception as e:
print(" Error: ", e)
def insert_node_at_end(self, data):
"""
Inserts an integer at the end of the linked list
"""
try:
temp = Node(data)
if self.start is None:
self.start = temp
return
p = self.start
while p.link is not None:
p = p.link
p.link = temp
except Exception as e:
print(" Error: ", e)
def insert_node_after_another(self, data, x):
"""
Inserts an integer after the x node
"""
try:
p = self.start
while p is not None:
if p.info == x:
break
p = p.link
if p is None:
print(f" Sorry! {x} is not in the list.")
else:
temp = Node(data)
temp.link = p.link
p.link = temp
except Exception as e:
print(" Error: ", e)
def insert_node_before_another(self, data, x):
"""
Inserts an integer before the x node
"""
try:
# If list is empty
if self.start is None:
print(" Sorry! The list is empty.")
return
# If x is the first node, and new node should be inserted before the first node
if x == self.start.info:
temp = Node(data)
temp.link = p.link
p.link = temp
# Finding the reference to the prior node containing x
p = self.start
while p.link is not None:
if p.link.info == x:
break
p = p.link
if p.link is not None:
print(f" Sorry! {x} is not in the list.")
else:
temp = Node(data)
temp.link = p.link
p.link = temp
except Exception as e:
print(" Error: ", e)
def insert_node_at_position(self, data, k):
"""
Inserts an integer in k position of the linked list
"""
try:
# if we wish to insert at the first node
if k == 1:
temp = Node(data)
temp.link = self.start
self.start = temp
return
p = self.start
i = 1
while i < k-1 and p is not None:
p = p.link
i += 1
if p is None:
print(f" The max position is {i}")
else:
temp = Node(data)
temp.link = self.start
self.start = temp
except Exception as e:
print(" Error: ", e)
def delete_a_node(self, x):
"""
Deletes a node of a linked list
"""
try:
# If list is empty
if self.start is None:
print(" Sorry! The list is empty.")
return
# If there is only one node
if self.start.info == x:
self.start = self.start.link
# If more than one node exists
p = self.start
while p.link is not None:
if p.link.info == x:
break
p = p.link
if p.link is None:
print(f" Sorry! {x} is not in the list.")
else:
p.link = p.link.link
except Exception as e:
print(" Error: ", e)
def delete_sll_first_node(self):
"""
Deletes the first node of a linked list
"""
try:
if self.start is None:
return
self.start = self.start.link
except Exception as e:
print(" Error: ", e)
def delete_sll_last_node(self):
"""
Deletes the last node of a linked list
"""
try:
# If the list is empty
if self.start is None:
return
# If there is only one node
if self.start.link is None:
self.start = None
return
# If there is more than one node
p = self.start
# Increment until we find the node prior to the last node
while p.link.link is not None:
p = p.link
p.link = None
except Exception as e:
print(" Error: ", e)
def reverse_sll(self):
"""
Reverses the linked list
"""
try:
prev = None
p = self.start
while p is not None:
next = p.link
p.link = prev
prev = p
p = next
self.start = prev
except Exception as e:
print(" Error: ", e)
def bubble_sort_sll_nodes_data(self):
"""
Bubble sorts the linked list on integer values
"""
try:
# If the list is empty or there is only one node
if self.start is None or self.start.link is None:
print(" The list has no or only one node and sorting is not required.")
end = None
while end != self.start.link:
p = self.start
while p.link != end:
q = p.link
if p.info > q.info:
p.info, q.info = q.info, p.info
p = p.link
end = p
except Exception as e:
print(" Error: ", e)
def bubble_sort_sll(self):
"""
Bubble sorts the linked list
"""
try:
# If the list is empty or there is only one node
if self.start is None or self.start.link is None:
print(" The list has no or only one node and sorting is not required.")
end = None
while end != self.start.link:
r = p = self.start
while p.link != end:
q = p.link
if p.info > q.info:
p.link = q.link
q.link = p
if p != self.start:
r.link = q.link
else:
self.start = q
p, q = q, p
r = p
p = p.link
end = p
except Exception as e:
print(" Error: ", e)
def sll_has_cycle(self):
"""
Tests the list for cycles using Tortoise and Hare Algorithm (Floyd's cycle detection algorithm)
"""
try:
if self.find_sll_cycle() is None:
return False
else:
return True
except Exception as e:
print(" Error: ", e)
def find_sll_cycle(self):
"""
Finds cycles in the list, if any
"""
try:
# If there is one node or none, there is no cycle
if self.start is None or self.start.link is None:
return None
# Otherwise,
slowR = self.start
fastR = self.start
while slowR is not None and fastR is not None:
slowR = slowR.link
fastR = fastR.link.link
if slowR == fastR:
return slowR
return None
except Exception as e:
print(" Error: ", e)
def remove_cycle_from_sll(self):
"""
Removes the cycles
"""
try:
c = self.find_sll_cycle()
# If there is no cycle
if c is None:
return
print(f" There is a cycle at node: ", c.info)
p = c
q = c
len_cycles = 0
while True:
len_cycles += 1
q = q.link
if p == q:
break
print(f" The cycle length is {len_cycles}")
len_rem_list = 0
p = self.start
while p != q:
len_rem_list += 1
p = p.link
q = q.link
print(f" The number of nodes not included in the cycle is {len_rem_list}")
length_list = len_rem_list + len_cycles
print(f" The SLL length is {length_list}")
# This for loop goes to the end of the SLL, and set the last node to None and the cycle is removed.
p = self.start
for _ in range(length_list-1):
p = p.link
p.link = None
except Exception as e:
print(" Error: ", e)
def insert_cycle_in_sll(self, x):
"""
Inserts a cycle at a node that contains x
"""
try:
if self.start is None:
return False
p = self.start
px = None
prev = None
while p is not None:
if p.info == x:
px = p
prev = p
p = p.link
if px is not None:
prev.link = px
else:
print(f" Sorry! {x} is not in the list.")
except Exception as e:
print(" Error: ", e)
def merge_using_new_list(self, list2):
"""
Merges two already sorted SLLs by creating new lists
"""
merge_list = SingleLinkedList()
merge_list.start = self._merge_using_new_list(self.start, list2.start)
return merge_list
def _merge_using_new_list(self, p1, p2):
"""
Private method of merge_using_new_list
"""
if p1.info <= p2.info:
Start_merge = Node(p1.info)
p1 = p1.link
else:
Start_merge = Node(p2.info)
p2 = p2.link
pM = Start_merge
while p1 is not None and p2 is not None:
if p1.info <= p2.info:
pM.link = Node(p1.info)
p1 = p1.link
else:
pM.link = Node(p2.info)
p2 = p2.link
pM = pM.link
#If the second list is finished, yet the first list has some nodes
while p1 is not None:
pM.link = Node(p1.info)
p1 = p1.link
pM = pM.link
#If the second list is finished, yet the first list has some nodes
while p2 is not None:
pM.link = Node(p2.info)
p2 = p2.link
pM = pM.link
return Start_merge
def merge_inplace(self, list2):
"""
Merges two already sorted SLLs in place in O(1) of space
"""
merge_list = SingleLinkedList()
merge_list.start = self._merge_inplace(self.start, list2.start)
return merge_list
def _merge_inplace(self, p1, p2):
"""
Merges two already sorted SLLs in place in O(1) of space
"""
if p1.info <= p2.info:
Start_merge = p1
p1 = p1.link
else:
Start_merge = p2
p2 = p2.link
pM = Start_merge
while p1 is not None and p2 is not None:
if p1.info <= p2.info:
pM.link = p1
pM = pM.link
p1 = p1.link
else:
pM.link = p2
pM = pM.link
p2 = p2.link
if p1 is None:
pM.link = p2
else:
pM.link = p1
return Start_merge
def merge_sort_sll(self):
"""
Sorts the linked list using merge sort algorithm
"""
self.start = self._merge_sort_recursive(self.start)
def _merge_sort_recursive(self, list_start):
"""
Recursively calls the merge sort algorithm for two divided lists
"""
# If the list is empty or has only one node
if list_start is None or list_start.link is None:
return list_start
# If the list has two nodes or more
start_one = list_start
start_two = self._divide_list(self_start)
start_one = self._merge_sort_recursive(start_one)
start_two = self._merge_sort_recursive(start_two)
start_merge = self._merge_inplace(start_one, start_two)
return start_merge
def _divide_list(self, p):
"""
Divides the linked list into two almost equally sized lists
"""
# Refers to the third nodes of the list
q = p.link.link
while q is not None and p is not None:
# Increments p one node at the time
p = p.link
# Increments q two nodes at the time
q = q.link.link
start_two = p.link
p.link = None
return start_two
def concat_second_list_to_sll(self, list2):
"""
Concatenates another SLL to an existing SLL
"""
# If the second SLL has no node
if list2.start is None:
return
# If the original SLL has no node
if self.start is None:
self.start = list2.start
return
# Otherwise traverse the original SLL
p = self.start
while p.link is not None:
p = p.link
# Link the last node to the first node of the second SLL
p.link = list2.start
def test_merge_using_new_list_and_inplace(self):
"""
"""
LIST_ONE = SingleLinkedList()
LIST_TWO = SingleLinkedList()
LIST_ONE.create_single_linked_list()
LIST_TWO.create_single_linked_list()
print("1?? The unsorted first list is: ")
LIST_ONE.display_sll()
print("2?? The unsorted second list is: ")
LIST_TWO.display_sll()
LIST_ONE.bubble_sort_sll_nodes_data()
LIST_TWO.bubble_sort_sll_nodes_data()
print("1?? The sorted first list is: ")
LIST_ONE.display_sll()
print("2?? The sorted second list is: ")
LIST_TWO.display_sll()
LIST_THREE = LIST_ONE.merge_using_new_list(LIST_TWO)
print("The merged list by creating a new list is: ")
LIST_THREE.display_sll()
LIST_FOUR = LIST_ONE.merge_inplace(LIST_TWO)
print("The in-place merged list is: ")
LIST_FOUR.display_sll()
def test_all_methods(self):
"""
Tests all methods of the SLL class
"""
OPTIONS_HELP = """
Select a method from 1-19:
?? (1) Create a single liked list (SLL).
?? (2) Display the SLL.
?? (3) Count the nodes of SLL.
?? (4) Search the SLL.
?? (5) Insert a node at the beginning of the SLL.
?? (6) Insert a node at the end of the SLL.
?? (7) Insert a node after a specified node of the SLL.
?? (8) Insert a node before a specified node of the SLL.
?? (9) Delete the first node of SLL.
?? (10) Delete the last node of the SLL.
?? (11) Delete a node you wish to remove.
?? (12) Reverse the SLL.
?? (13) Bubble sort the SLL by only exchanging the integer values.
?? (14) Bubble sort the SLL by exchanging links.
?? (15) Merge sort the SLL.
?? (16) Insert a cycle in the SLL.
?? (17) Detect if the SLL has a cycle.
?? (18) Remove cycle in the SLL.
?? (19) Test merging two bubble-sorted SLLs.
?? (20) Concatenate a second list to the SLL.
?? (21) Exit.
"""
self.create_single_linked_list()
while True:
print(OPTIONS_HELP)
UI_OPTION = int(input(" Enter an integer for the method you wish to run using the above help: "))
if UI_OPTION == 1:
data = int(input(" Enter an integer to be inserted at the end of the list: "))
x = int(input(" Enter an integer to be inserted after that: "))
self.insert_node_after_another(data, x)
elif UI_OPTION == 2:
self.display_sll()
elif UI_OPTION == 3:
self.count_sll_nodes()
elif UI_OPTION == 4:
data = int(input(" Enter an integer to be searched: "))
self.search_sll_nodes(data)
elif UI_OPTION == 5:
data = int(input(" Enter an integer to be inserted at the beginning: "))
self.insert_node_in_beginning(data)
elif UI_OPTION == 6:
data = int(input(" Enter an integer to be inserted at the end: "))
self.insert_node_at_end(data)
elif UI_OPTION == 7:
data = int(input(" Enter an integer to be inserted: "))
x = int(input(" Enter an integer to be inserted before that: "))
self.insert_node_before_another(data, x)
elif UI_OPTION == 8:
data = int(input(" Enter an integer for the node to be inserted: "))
k = int(input(" Enter an integer for the position at which you wish to insert the node: "))
self.insert_node_before_another(data, k)
elif UI_OPTION == 9:
self.delete_sll_first_node()
elif UI_OPTION == 10:
self.delete_sll_last_node()
elif UI_OPTION == 11:
data = int(input(" Enter an integer for the node you wish to remove: "))
self.delete_a_node(data)
elif UI_OPTION == 12:
self.reverse_sll()
elif UI_OPTION == 13:
self.bubble_sort_sll_nodes_data()
elif UI_OPTION == 14:
self.bubble_sort_sll()
elif UI_OPTION == 15:
self.merge_sort_sll()
elif UI_OPTION == 16:
data = int(input(" Enter an integer at which a cycle has to be formed: "))
self.insert_cycle_in_sll(data)
elif UI_OPTION == 17:
if self.sll_has_cycle():
print(" The linked list has a cycle. ")
else:
print(" YAAAY! The linked list does not have a cycle. ")
elif UI_OPTION == 18:
self.remove_cycle_from_sll()
elif UI_OPTION == 19:
self.test_merge_using_new_list_and_inplace()
elif UI_OPTION == 20:
list2 = self.create_single_linked_list()
self.concat_second_list_to_sll(list2)
elif UI_OPTION == 21:
break
else:
print(" Option must be an integer, between 1 to 21.")
print()
if __name__ == '__main__':
# Instantiates a new SLL object
SLL_OBJECT = SingleLinkedList()
SLL_OBJECT.test_all_methods()
You need to enable deep object dirty checking. By default angular only checks the reference of the top level variable that you watch.
App.directive('d3Visualization', function() {
return {
restrict: 'E',
scope: {
val: '='
},
link: function(scope, element, attrs) {
scope.$watch('val', function(newValue, oldValue) {
if (newValue)
console.log("I see a data change!");
}, true);
}
}
});
see Scope. The third parameter of the $watch function enables deep dirty checking if it's set to true.
Take note that deep dirty checking is expensive. So if you just need to watch the children array instead of the whole data
variable the watch the variable directly.
scope.$watch('val.children', function(newValue, oldValue) {}, true);
version 1.2.x introduced $watchCollection
Shallow watches the properties of an object and fires whenever any of the properties change (for arrays, this implies watching the array items; for object maps, this implies watching the properties)
scope.$watchCollection('val.children', function(newValue, oldValue) {});
The line
$location.absUrl() == 'http://www.google.com';
is wrong. First == makes a comparison, and what you are probably trying to do is an assignment, which is with simple = and not double ==.
And because absUrl() getter only. You can use url(), which can be used as a setter or as a getter if you want.
reference : http://docs.angularjs.org/api/ng.$location
Can you show code which you use for setting date object? Anyway< you can use this code for intialisation of date:
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2011-01-01 00:00:00")
My solution is:
I hope this can help.
I'm using Zend Studio. It has decent syntax highlighting, code completion and such. But the best part is that you can debug PHP code, either with a standalone PHP interpreter, or even on a live web server as you "browse" along your pages. You get the usual Visual Studio keys, breakpoints, watches and call stack, which is almost indispensable for bug hunting. No more "alert()"-cluttered debugged source code :)
I think it is better if you just created it like this:
var arr = [];
arr = {
key1: 'value1',
key2:'value2'
};
For more info, take a look at this:
You can use ES6 destructuring assignment like so:
let a = 10;
let b = 20;
[a, b] = [b, a];
console.log(a, b); // a = 20, b = 10
While setting the value in the constructor would work, using the Doctrine Lifecycle events might be a better solution.
By leveraging the prePersist
Lifecycle Event, you could set your default value on your entity only on initial persist.
.rainbow {_x000D_
background-image: -webkit-gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );_x000D_
background-image: gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );_x000D_
color:transparent;_x000D_
-webkit-background-clip: text;_x000D_
background-clip: text;_x000D_
}
_x000D_
<h2><span class="rainbow">Rainbows are colorful and scalable and lovely</span></h2>
_x000D_
Try this: edited
@echo off
set "comd=dir /b /s *.zip"
set "pathName="
set /p "pathName=Enter The Value: "
cd /d "%pathName%"
%comd%
pause
You can get the ident of the current running thread. The ident could be reused for other threads, if the current thread ends.
When you crate an instance of Thread, a name is given implicit to the thread, which is the pattern: Thread-number
The name has no meaning and the name don't have to be unique. The ident of all running threads is unique.
import threading
def worker():
print(threading.current_thread().name)
print(threading.get_ident())
threading.Thread(target=worker).start()
threading.Thread(target=worker, name='foo').start()
The function threading.current_thread() returns the current running thread. This object holds the whole information of the thread.
Maybe a simpler solution is to set an overlay in front of your map using FrameLayout
or RelativeLayout
and treating them as regular buttons in your activity. You should declare your layers in back to front order, e.g., map before buttons. I modified your layout, simplified it a little bit. Try the following layout and see if it works for you:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapActivity" >
<fragment xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:scrollbars="vertical"
class="com.google.android.gms.maps.SupportMapFragment"/>
<RadioGroup
android:id="@+id/radio_group_list_selector"
android:layout_width="match_parent"
android:layout_height="48dp"
android:orientation="horizontal"
android:background="#80000000"
android:padding="4dp" >
<RadioButton
android:id="@+id/radioPopular"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="@string/Popular"
android:gravity="center_horizontal|center_vertical"
android:layout_weight="1"
android:background="@drawable/shape_radiobutton"
android:textColor="@color/textcolor_radiobutton" />
<View
android:id="@+id/VerticalLine"
android:layout_width="1dip"
android:layout_height="match_parent"
android:background="#aaa" />
<RadioButton
android:id="@+id/radioAZ"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:text="@string/AZ"
android:layout_weight="1"
android:background="@drawable/shape_radiobutton2"
android:textColor="@color/textcolor_radiobutton" />
<View
android:id="@+id/VerticalLine"
android:layout_width="1dip"
android:layout_height="match_parent"
android:background="#aaa" />
<RadioButton
android:id="@+id/radioCategory"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:text="@string/Category"
android:layout_weight="1"
android:background="@drawable/shape_radiobutton2"
android:textColor="@color/textcolor_radiobutton" />
<View
android:id="@+id/VerticalLine"
android:layout_width="1dip"
android:layout_height="match_parent"
android:background="#aaa" />
<RadioButton
android:id="@+id/radioNearBy"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:text="@string/NearBy"
android:layout_weight="1"
android:background="@drawable/shape_radiobutton3"
android:textColor="@color/textcolor_radiobutton" />
</RadioGroup>
</FrameLayout>
First, don't use print
s for logging, there is astable, proven and well-thought out stdlib module to do that: logging
. You definitely should use it instead.
Second, don't be tempted to do a mess with unrelated tools when there is native and simple approach. Here it is:
log = logging.getLogger(__name__)
try:
call_code_that_fails()
except MyError:
log.exception('Any extra info you want to see in your logs')
That's it. You are done now.
What log.exception
is actually doing is just a call to log.error
(that is, log event with level ERROR
) and print traceback then.
Well, here is some considerations:
traceback
or call logger with exc_info=True
or get their hands dirty with sys.exc_info
?Well, just because! They all exist for different purposes. For example, traceback.print_exc
's output is a little bit different from tracebacks produced by the interpreter itself. If you use it, you will confuse anyone who reads your logs, they will be banging their heads against them.
Passing exc_info=True
to log calls is just inappropriate. But, it is useful when catching recoverable errors and you want to log them (using, e.g INFO
level) with tracebacks as well, because log.exception
produces logs of only one level - ERROR
.
And you definitely should avoid messing with sys.exc_info
as much as you can. It's just not a public interface, it's an internal one - you can use it if you definitely know what you are doing. It is not intended for just printing exceptions.
The key distinction is repeating a captured group instead of capturing a repeated group.
As you have already found out, the difference is that repeating a captured group captures only the last iteration. Capturing a repeated group captures all iterations.
In PCRE (PHP):
((?:\w+)+),?
Match 1, Group 1. 0-5 HELLO
Match 2, Group 1. 6-11 THERE
Match 3, Group 1. 12-20 BRUTALLY
Match 4, Group 1. 21-26 CRUEL
Match 5, Group 1. 27-32 WORLD
Since all captures are in Group 1, you only need $1
for substitution.
I used the following general form of this regular expression:
((?:{{RE}})+)
Example at regex101
While both of the above answers work well if key,value are strings, I had a situation to append a string and integer (jq errors using the above expressions)
Requirement: To construct a url out below json
pradeep@seleniumframework>curl http://192.168.99.103:8500/v1/catalog/service/apache-443 | jq .[0]
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 251 100 251 0 0 155k 0 --:--:-- --:--:-- --:--:-- 245k
{
"Node": "myconsul",
"Address": "192.168.99.103",
"ServiceID": "4ce41e90ede4:compassionate_wozniak:443",
"ServiceName": "apache-443",
"ServiceTags": [],
"ServiceAddress": "",
"ServicePort": 1443,
"ServiceEnableTagOverride": false,
"CreateIndex": 45,
"ModifyIndex": 45
}
Solution:
curl http://192.168.99.103:8500/v1/catalog/service/apache-443 |
jq '.[0] | "http://" + .Address + ":" + "\(.ServicePort)"'
Write property value as a array of strings. Like example given over here https://gun.io/blog/multi-line-strings-in-json/. This will help.
We can always use array of strings for multiline strings like following.
{
"singleLine": "Some singleline String",
"multiline": ["Line one", "line Two", "Line Three"]
}
And we can easily iterate array to display content in multi line fashion.
Swift 3
If you need the object use:
array.first{$0.name == "Foo"}
(If you have more than one object named "Foo" then first
will return the first object from an unspecified ordering)
Global $myArr;
$myArr = array();
function someFuntion(){
global $myArr;
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal;
}
Be forewarned, generally people stick away from globals as it has some downsides.
You could try this
function someFuntion($myArr){
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal;
return $myArr;
}
$myArr = someFunction($myArr);
That would make it so you aren't relying on Globals.
You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start()
. The headers will be sent automatically when any HTML is output.
Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.
Move the session_start()
to the top of your document :
<?php session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php'; // more PHP code here.
based on @nicolas answer.. Pure CSS should the trick, it will only show the error message on blur
<input type="email" id="input-email" required
placeholder="Email address" class="form-control" name="email"
ng-model="userData.email">
<p ng-show="form.email.$error.email" class="bg-danger">This is not a valid email.</p>
CSS
.ng-invalid:focus ~ .bg-danger {
display:none;
}
Doing this fixed my issue
<script type="text/javascript">
function SubmitFrm(){
var Searchtxt = document.getElementById("txtSearch").value;
window.location = "http://www.mysite.com/search/?Query=" + Searchtxt;
}
</script>
I changed .value();
to .value;
taking out the ()
I did not change anything in my text field or submit button
<input name="txtSearch" type="text" id="txtSearch" class="field" />
<input type="submit" name="btnSearch" value="" id="btnSearch" class="btn" onclick="javascript:SubmitFrm()" />
Works like a charm.
The answer above is correct, but the path is slightly off, try this instead:
%AppData%\..\Local\Temp\TFSTemp
CREATE OR REPLACE PROCEDURE ADDEMP
(xml IN CLOB)
AS
BEGIN
INSERT INTO EMPLOYEE (EMPID,EMPNAME,EMPDETAIL,CREATEDBY,CREATED)
SELECT
ExtractValue(column_value,'/ROOT/EMPID') AS EMPID
,ExtractValue(column_value,'/ROOT/EMPNAME') AS EMPNAME
,ExtractValue(column_value,'/ROOT/EMPDETAIL') AS EMPDETAIL
,ExtractValue(column_value,'/ROOT/CREATEDBY') AS CREATEDBY
,ExtractValue(column_value,'/ROOT/CREATEDDATE') AS CREATEDDATE
FROM TABLE(XMLSequence( XMLType(xml))) XMLDUMMAY;
COMMIT;
END;
The discussion here gives the answer:
Actually, the specific discussion I witnessed did in fact hinge over functional purity. In an expression, there are frequently assumptions made about not having side-effects. Having ForEach is specifically inviting side-effects rather than just putting up with them. -- Keith Farmer (Partner)
Basically the decision was made to keep the extension methods functionally "pure". A ForEach would encourage side-effects when using the Enumerable extension methods, which was not the intent.
In my case I have these messages when I show the sherlock action bar inderterminate progressbar. Since its not my library, I decided to hide the Choreographer outputs.
You can hide the Choreographer outputs onto the Logcat view, using this filter expression :
tag:^((?!Choreographer).*)$
I used a regex explained elsewhere : Regular expression to match a line that doesn't contain a word?
Please walk me through the commands I should run to figure this out.
The simplest test you can do is to perform 1000 requests, 10 at a time (which approximately simulates 10 concurrent users getting 100 pages each - over the length of the test).
ab -n 1000 -c 10 -k -H "Accept-Encoding: gzip, deflate" http://www.example.com/
-n 1000
is the number of requests to make.
-c 10
tells AB to do 10 requests at a time, instead of 1 request at a time, to better simulate concurrent visitors (vs. sequential visitors).
-k
sends the KeepAlive
header, which asks the web server to not shut down the connection after each request is done, but to instead keep reusing it.
I'm also sending the extra header Accept-Encoding: gzip, deflate
because mod_deflate is almost always used to compress the text/html output 25%-75% - the effects of which should not be dismissed due to it's impact on the overall performance of the web server (i.e., can transfer 2x the data in the same amount of time, etc).
Results:
Benchmarking www.example.com (be patient)
Completed 100 requests
...
Finished 1000 requests
Server Software: Apache/2.4.10
Server Hostname: www.example.com
Server Port: 80
Document Path: /
Document Length: 428 bytes
Concurrency Level: 10
Time taken for tests: 1.420 seconds
Complete requests: 1000
Failed requests: 0
Keep-Alive requests: 995
Total transferred: 723778 bytes
HTML transferred: 428000 bytes
Requests per second: 704.23 [#/sec] (mean)
Time per request: 14.200 [ms] (mean)
Time per request: 1.420 [ms] (mean, across all concurrent requests)
Transfer rate: 497.76 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 0.1 0 1
Processing: 5 14 7.5 12 77
Waiting: 5 14 7.5 12 77
Total: 5 14 7.5 12 77
Percentage of the requests served within a certain time (ms)
50% 12
66% 14
75% 15
80% 16
90% 24
95% 29
98% 36
99% 41
100% 77 (longest request)
For the simplest interpretation, ignore everything BUT this line:
Requests per second: 704.23 [#/sec] (mean)
Multiply that by 60, and you have your requests per minute.
To get real world results, you'll want to test Wordpress instead of some static HTML or index.php file because you need to know how everything performs together: including complex PHP code, and multiple MySQL queries...
For example here is the results of testing a fresh install of Wordpress on the same system and WAMP environment (I'm using WampDeveloper, but there are also Xampp, WampServer, and others)...
Requests per second: 18.68 [#/sec] (mean)
That's 37x slower now!
After the load test, there are a number of things you can do to improve the overall performance (Requests Per Second), and also make the web server more stable under greater load (e.g., increasing the -n
and the -c
tends to crash Apache), that you can read about here:
In such cases, you can convert the values of enum to a List and stream through it. Something like below examples. I would recommend using filter().
Using ForEach:
List<Category> category = Arrays.asList(Category.values());
category.stream().forEach(eachCategory -> {
if(eachCategory.toString().equals("3")){
String name = eachCategory.name();
}
});
Or, using Filter:
When you want to find with code:
List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.toString().equals("3")).findAny().orElse(null);
System.out.println(category.toString() + " " + category.name());
When you want to find with name:
List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.name().equals("Apple")).findAny().orElse(null);
System.out.println(category.toString() + " " + category.name());
Hope it helps! I know this is a very old post, but someone can get help.
As suggested above the inclusion of
/usr/lib/openmpi/include
in the include path takes care of this (in my case)
You can also get BLOB object directly from XMLHttpRequest. Setting responseType to blob makes the trick. Here is my code:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost/image.jpg");
xhr.responseType = "blob";
xhr.onload = response;
xhr.send();
And the response function looks like this:
function response(e) {
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
document.querySelector("#image").src = imageUrl;
}
We just have to make an empty image element in HTML:
<img id="image"/>
if you don't have multi line properties and a very simple need, a few lines of code can solve it for you:
File t.properties
:
a=b
c=d
e=f
Python code:
with open("t.properties") as f:
l = [line.split("=") for line in f.readlines()]
d = {key.strip(): value.strip() for key, value in l}
I am using debounce NPM package and implemented like this:
<input @input="debounceInput">
methods: {
debounceInput: debounce(function (e) {
this.$store.dispatch('updateInput', e.target.value)
}, config.debouncers.default)
}
Using lodash and the example in the question, the implementation looks like this:
<input v-on:input="debounceInput">
methods: {
debounceInput: _.debounce(function (e) {
this.filterKey = e.target.value;
}, 500)
}
I like prettyPhoto
prettyPhoto is a jQuery lightbox clone. Not only does it support images, it also support for videos, flash, YouTube, iframes and ajax. It’s a full blown media lightbox
I had exactly the same problem lately, and I installed Wireshark (it is a network monitoring tool). You can see everything with this, except encrypted traffic (HTTPS).
The ld returned 1 exit status
error is the consequence of previous errors. In your example there is an earlier error - undefined reference to 'clrscr'
- and this is the real one. The exit status error just signals that the linking step in the build process encountered some errors. Normally exit status 0
means success, and exit status
> 0 means errors.
When you build your program, multiple tools may be run as separate steps to create the final executable. In your case one of those tools is ld
, which first reports the error it found (clrscr
reference missing), and then it returns the exit status. Since the exit status is > 0, it means an error and is reported.
In many cases tools return as the exit status the number of errors they encountered. So if ld tool finds two errors, its exit status would be 2.
Try it ..
UPDATE PRODUCTION a
SET (name, count) = (
SELECT name, count
FROM STAGING b
WHERE a.ID = b.ID)
WHERE EXISTS (SELECT 1
FROM STAGING b
WHERE a.ID=b.ID
);
I recommend the Wordpress plugin Magic Liquidizer Responsive Table.
Yes you can use CASE
UPDATE table
SET columnB = CASE fieldA
WHEN columnA=1 THEN 'x'
WHEN columnA=2 THEN 'y'
ELSE 'z'
END
WHERE columnC = 1
window
is the whole browser's application window. document
is the webpage shown that is actually loaded.
window.innerWidth
and window.innerHeight
will take scrollbars into account which may not be what you want.
document.documentElement
is the full webpage without the top scrollbar. document.documentElement.clientWidth
returns document width size without y scrollbar.
document.documentElement.clientHeight
returns document height size without x scrollbar.
I have encountered this issue in various forms, but this time it was a new one:
In this case, I had providers names collision - the same provider name existed in my app and another of my apps.
I found the answer to the second part of my questions. Yes, a class can implement an interface that is in a different class as long that the interface is declared as public.
You would think that simply authenticating a user in Active Directory would be a pretty simple process using LDAP in PHP without the need for a library. But there are a lot of things that can complicate it pretty fast:
It's actually easier in most cases to use a LDAP library supporting the above. I ultimately ended up rolling my own library which handles all the above points: LdapTools (Well, not just for authentication, it can do much more). It can be used like the following:
use LdapTools\Configuration;
use LdapTools\DomainConfiguration;
use LdapTools\LdapManager;
$domain = (new DomainConfiguration('example.com'))
->setUsername('username') # A separate AD service account used by your app
->setPassword('password')
->setServers(['dc1', 'dc2', 'dc3'])
->setUseTls(true);
$config = new Configuration($domain);
$ldap = new LdapManager($config);
if (!$ldap->authenticate($username, $password, $message)) {
echo "Error: $message";
} else {
// Do something...
}
The authenticate call above will:
There are other libraries to do this too (Such as Adldap2). However, I felt compelled enough to provide some additional information as the most up-voted answer is actually a security risk to rely on with no input validation done and not using TLS.
Debug.WriteLine() can be used as well.
For both Python 3 and Python 2, this works:
try:
from urllib.request import Request, urlopen # Python 3
except ImportError:
from urllib2 import Request, urlopen # Python 2
req = Request('http://api.company.com/items/details?country=US&language=en')
req.add_header('apikey', 'xxx')
content = urlopen(req).read()
print(content)
The testing suite doesn't make an attempt at using the imported timeit
so it's hard to tell what the intent was. Nonetheless, this is a canonical answer so a complete example of timeit
seems in order, elaborating on Martijn's answer.
The docs for timeit
offer many examples and flags worth checking out. The basic usage on the command line is:
$ python -mtimeit "all(True for _ in range(1000))"
2000 loops, best of 5: 161 usec per loop
$ python -mtimeit "all([True for _ in range(1000)])"
2000 loops, best of 5: 116 usec per loop
Run with -h
to see all options. Python MOTW has a great section on timeit
that shows how to run modules via import and multiline code strings from the command line.
In script form, I typically use it like this:
import argparse
import copy
import dis
import inspect
import random
import sys
import timeit
def test_slice(L):
L[:]
def test_copy(L):
L.copy()
def test_deepcopy(L):
copy.deepcopy(L)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--n", type=int, default=10 ** 5)
parser.add_argument("--trials", type=int, default=100)
parser.add_argument("--dis", action="store_true")
args = parser.parse_args()
n = args.n
trials = args.trials
namespace = dict(L = random.sample(range(n), k=n))
funcs_to_test = [x for x in locals().values()
if callable(x) and x.__module__ == __name__]
print(f"{'-' * 30}\nn = {n}, {trials} trials\n{'-' * 30}\n")
for func in funcs_to_test:
fname = func.__name__
fargs = ", ".join(inspect.signature(func).parameters)
stmt = f"{fname}({fargs})"
setup = f"from __main__ import {fname}"
time = timeit.timeit(stmt, setup, number=trials, globals=namespace)
print(inspect.getsource(globals().get(fname)))
if args.dis:
dis.dis(globals().get(fname))
print(f"time (s) => {time}\n{'-' * 30}\n")
You can pretty easily drop in the functions and arguments you need. Use caution when using impure functions and take care of state.
Sample output:
$ python benchmark.py --n 10000
------------------------------
n = 10000, 100 trials
------------------------------
def test_slice(L):
L[:]
time (s) => 0.015502399999999972
------------------------------
def test_copy(L):
L.copy()
time (s) => 0.01651419999999998
------------------------------
def test_deepcopy(L):
copy.deepcopy(L)
time (s) => 2.136012
------------------------------
With text-wrap, browser support is relatively weak (as you might expect from from a draft spec).
You are better off taking steps to ensure the data doesn't have long strings of non-white-space.
So, I was messing around with something similar to this recently, and I came up with the following solution, which uses a way of getting input that rejects junk, before it's even checked in any logical way.
read_single_keypress()
courtesy https://stackoverflow.com/a/6599441/4532996
def read_single_keypress() -> str:
"""Waits for a single keypress on stdin.
-- from :: https://stackoverflow.com/a/6599441/4532996
"""
import termios, fcntl, sys, os
fd = sys.stdin.fileno()
# save old state
flags_save = fcntl.fcntl(fd, fcntl.F_GETFL)
attrs_save = termios.tcgetattr(fd)
# make raw - the way to do this comes from the termios(3) man page.
attrs = list(attrs_save) # copy the stored version to update
# iflag
attrs[0] &= ~(termios.IGNBRK | termios.BRKINT | termios.PARMRK
| termios.ISTRIP | termios.INLCR | termios. IGNCR
| termios.ICRNL | termios.IXON )
# oflag
attrs[1] &= ~termios.OPOST
# cflag
attrs[2] &= ~(termios.CSIZE | termios. PARENB)
attrs[2] |= termios.CS8
# lflag
attrs[3] &= ~(termios.ECHONL | termios.ECHO | termios.ICANON
| termios.ISIG | termios.IEXTEN)
termios.tcsetattr(fd, termios.TCSANOW, attrs)
# turn off non-blocking
fcntl.fcntl(fd, fcntl.F_SETFL, flags_save & ~os.O_NONBLOCK)
# read a single keystroke
try:
ret = sys.stdin.read(1) # returns a single character
except KeyboardInterrupt:
ret = 0
finally:
# restore old state
termios.tcsetattr(fd, termios.TCSAFLUSH, attrs_save)
fcntl.fcntl(fd, fcntl.F_SETFL, flags_save)
return ret
def until_not_multi(chars) -> str:
"""read stdin until !(chars)"""
import sys
chars = list(chars)
y = ""
sys.stdout.flush()
while True:
i = read_single_keypress()
_ = sys.stdout.write(i)
sys.stdout.flush()
if i not in chars:
break
y += i
return y
def _can_you_vote() -> str:
"""a practical example:
test if a user can vote based purely on keypresses"""
print("can you vote? age : ", end="")
x = int("0" + until_not_multi("0123456789"))
if not x:
print("\nsorry, age can only consist of digits.")
return
print("your age is", x, "\nYou can vote!" if x >= 18 else "Sorry! you can't vote")
_can_you_vote()
You can find the complete module here.
Example:
$ ./input_constrain.py
can you vote? age : a
sorry, age can only consist of digits.
$ ./input_constrain.py
can you vote? age : 23<RETURN>
your age is 23
You can vote!
$ _
Note that the nature of this implementation is it closes stdin as soon as something that isn't a digit is read. I didn't hit enter after a
, but I needed to after the numbers.
You could merge this with the thismany()
function in the same module to only allow, say, three digits.
With Vue.js:
<textarea name="story" :placeholder="'Enter story\n next line\n more'"></textarea>
A quick way to do it is by:
public boolean isStringAlpha(String aString) {
int charCount = 0;
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (aString.length() == 0) {
return false; //zero length string ain't alpha
}
for (int i = 0; i < aString.length(); i++) {
for (int j = 0; j < alphabet.length(); j++) {
if (aString.substring(i, i + 1).equals(alphabet.substring(j, j + 1))
|| aString.substring(i, i + 1).equals(alphabet.substring(j, j + 1).toLowerCase())) {
charCount++;
}
}
if (charCount != (i + 1)) {
System.out.println("\n**Invalid input! Enter alpha values**\n");
return false;
}
}
return true;
}
Because you don't have to run the whole aString
to check if it isn't an alpha String.
For me this problem occurred because I had a some invalid character in my Groovy script. In our case this was an extra blank line after the closing bracket of the script.
Are you using the right chat_id and including your bot's token after "bot" in the address? (api.telegram.org/bottoken/sendMessage)
This page explains a few things about sending (down in "sendMessage" section) - basic stuff, but I often forget the basics.
To quote:
In order to use the sendMessage method we need to use the proper chat_id.
First things first let's send the /start command to our bot via a Telegram client.
After sent this command let's perform a getUpdates commands.
curl -s \
-X POST \ https://api.telegram.org/bot<token>/getUpdates \ | jq .
The response will be like the following
{ "result": [
{
"message": {
"text": "/start",
"date": 1435176541,
"chat": {
"username": "yourusername",
"first_name": "yourfirstname",
"id": 65535
},
"from": {
"username": "yourusername",
"first_name": "yourfirstname",
"id": 65535
},
"message_id": 1
},
"update_id": 714636917
} ], "ok": true }
We are interested in the property result.message[0].chat.id, save this information elsewhere.
Please note that this is only an example, you may want to set up some automatism to handle those informations Now how we can send a message ? It's simple let's check out this snippet.
curl -s \
-X POST \ https://api.telegram.org/bot<token>/sendMessage \
-d text="A message from your bot" \
-d chat_id=65535 \ | jq .
Where chat_id is the piece of information saved before.
I hope that helps.
datetime has fields hour
and minute
. So to get the hours and minutes, you would use t1.hour
and t1.minute
.
However, when you subtract two datetimes, the result is a timedelta, which only has the days
and seconds
fields. So you'll need to divide and multiply as necessary to get the numbers you need.
There were (at time of posting) one or two little typos in the accepted answer above, so here's the cleaned up version. In this example I'm stopping the CPU profiler when receiving Ctrl+C.
// capture ctrl+c and stop CPU profiler
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for sig := range c {
log.Printf("captured %v, stopping profiler and exiting..", sig)
pprof.StopCPUProfile()
os.Exit(1)
}
}()
Use ==
:
pip install django_modeltranslation==0.4.0-beta2
I was having a problem where setting element.Visible = true in my code behind wasn't having any effect on the actual screen. The solution for me was to wrap the area of my page where I wanted to show the div in an ASP UpdatePanel, which is used to cause partial screen updates.
http://msdn.microsoft.com/en-us/library/bb399001.aspx
Having the element runat=server gave me access to it from the codebehind, and placing it in the UpdatePanel let it actually be updated on the screen.
Building from Ben's plugin this version handles select and you can pass an option to allowSubmit. ie. $("#form").enterAsTab({ 'allowSubmit': true});
This will allow enter to submit the form if the submit button is handling the event.
(function( $ ){
$.fn.enterAsTab = function( options ) {
var settings = $.extend( {
'allowSubmit': false
}, options);
this.find('input, select').live("keypress", {localSettings: settings}, function(event) {
if (settings.allowSubmit) {
var type = $(this).attr("type");
if (type == "submit") {
return true;
}
}
if (event.keyCode == 13 ) {
var inputs = $(this).parents("form").eq(0).find(":input:visible:not(disabled):not([readonly])");
var idx = inputs.index(this);
if (idx == inputs.length - 1) {
idx = -1;
} else {
inputs[idx + 1].focus(); // handles submit buttons
}
try {
inputs[idx + 1].select();
}
catch(err) {
// handle objects not offering select
}
return false;
}
});
return this;
};
})( jQuery );
As non-root user ideally:
scp -r src $host:$path
If you already some of the content on $host consider using rsync with ssh as a tunnel.
/Allan
if ((ModifierKeys == Keys.Control) && ((e.KeyChar & (char)Keys.F) != 0))
{
// CTRL+F pressed !
}
Try the livequery plugin. That seems to work for something similar I am doing.
for jQuery
we can use below:
by input name:
$('input[name="textboxname"]').val('some value');
by input class:
$('input[type=text].textboxclass').val('some value');
by input id:
$('#textboxid').val('some value');
Short answer...yes. You can use an anonymous class when you initialize a variable. Take a look at this question: Anonymous vs named inner classes? - best practices?
You can't do this without JavaScript. Stackoverflow is using the jQuery JavaScript library which attachs functions to HTML elements on page load.
Here's how you could do it with vanilla JavaScript:
<textarea onkeydown="if (event.keyCode == 13) { this.form.submit(); return false; }"></textarea>
Keycode 13 is the enter key.
Here's how you could do it with jQuery like as Stackoverflow does:
<textarea class="commentarea"></textarea>
with
$(document).ready(function() {
$('.commentarea').keydown(function(event) {
if (event.which == 13) {
this.form.submit();
event.preventDefault();
}
});
});
I'm late to the party here, but if you're dealing with integers of a fixed length you can just do integer comparison:
SELECT * FROM books WHERE price > 89999 AND price < 90100;
Since you are new to Android development you may not know about Content Providers, which are database abstractions. They may not be the right thing for your project, but you should check them out: http://developer.android.com/guide/topics/providers/content-providers.html
If Java is installed on your 11G then you can do it in a java class and call it from your PL/SQL, but I am not sure that it does not require also a specific grant to call java.
I assume that the main idea is to find if number is negative and display it in correct format.
For those who use PHP5.3 might be interested in using Number Formatter Class - http://php.net/manual/en/class.numberformatter.php. This function, as well as range of other useful things, can format your number.
$profitLoss = 25000 - 55000;
$a= new \NumberFormatter("en-UK", \NumberFormatter::CURRENCY);
$a->formatCurrency($profitLoss, 'EUR');
// would display (€30,000.00)
Here also a reference to why brackets are used for negative numbers: http://www.open.edu/openlearn/money-management/introduction-bookkeeping-and-accounting/content-section-1.7
I solved this problem by changing the data type. If you see the 'Energy Supply per Capita' is a numerical type while the 'Citable docs per Capita' is an object type. I converted the column to float using astype. I had the same problem with some np functions: count_nonzero
and sum
worked while mean
and std
didn't.
PHP has JSON_PRETTY_PRINT option since 5.4.0 (release date 01-Mar-2012).
This should do the job:
$json = json_decode($string);
echo json_encode($json, JSON_PRETTY_PRINT);
See http://www.php.net/manual/en/function.json-encode.php
Note: Don't forget to echo "<pre>" before and "</pre>" after, if you're printing it in HTML to preserve formatting ;)
Open atom editor and then press Alt and menu bar will appear. Now click on View tab and then click on Toggle Menu Bar as seen on this screenshot.
You can simply make the start_date required using
<input type="submit" value="Submit" required />
You don't even need the checkform() then.
Thanks
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
http://www.tutorialspoint.com/mysql/mysql-date-time-functions.htm
use Date function directly. Hope it works
var input = document.getElementById ("IdofInput");
input.placeholder = "No need to fill this field";
You can find out more about placeholder
here: http://help.dottoro.com/ljgugboo.php
Had the same issue. It was fixed after I entered my mac user password and hit Always Allow.
Make Sure in left panel App review tab selected (Your app is currently live and available to the public.) tab is ON and App status is GREEN
Happy Programming
$('#div1').attr('class')
will return a string of the classes. Turn it into an array of class names
var classNames = $('#div1').attr('class').split(' ');
EDIT: (for laravel)
Just Came across this issue while working on a project in laravel. My tables were messed up, needed to frequent changes on columns. Once the tables were there I wasn't able to run php artisan migrate
anymore.
I've done following to get rid of the issue-
$ composer dump-autoload -o
php artisan migrate
Previous Comment, regarding lumen
[Well, pretty late to the party (and possibly a different party than what I was looking for). I banged my head, screamed out loud and by the grace of gray skull just found a solution.]
I'm developing an restful app using lumen and I'm new to it. This is my first project/experiment using laraval and lumen. My dependencies-
"require": {
"php": ">=5.6.4",
"laravel/lumen-framework": "5.4.*",
"vlucas/phpdotenv": "~2.2",
"barryvdh/laravel-cors": "^0.8.6",
"league/fractal": "^0.13.0"
},
"require-dev": {
"fzaninotto/faker": "~1.4",
"phpunit/phpunit": "~5.0",
"mockery/mockery": "~0.9.4"
}
Anyway, everything was fine until yesterday night but suddenly phpunit
started complaining about an already existed table.
Caused by
PDOException: SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'items' already exists
Duh! Items
table should exist in the database, or else how am i supposed to save items!
Anyway the problem only persisted in the test classes, but strangely not in the browser (I checked with chrome, firefox and postman altering headers). I was getting JSON responses with data as expected.
I dropped the database and recreated it with lots of migrate
, refresh
, rollback
. Everything was fine but in phpunit
.
Out of desperation I removed my migration files (of course I took a backup first ) then hit phpunit
in the terminal. Same thing all over again.
Suddenly I remembered that I put a different database name in the phpunit.xml
file for testing purpose only. I checked that database and guess what! There was a table named items
. I removed this table manually, run phpunit
, everything started working just fine.
I'm documenting my experience for future references only and with hope this might help someone in future.
The best solution I have found is:
this.focus();
self.opener=this;
self.close();
The beauty of Visual Studio Code is
Ctrl + Shift + P
Hit it and search anything you want.
In your case, hit Ctrl + Shift + P and type fold all.
.ui-slider .ui-slider-handle{
width:50px;
height:50px;
background:url(../images/slider_grabber.png) no-repeat; overflow: hidden;
position:absolute;
top: -10px;
border-style:none;
}
I was having issue with connecting to MS SQL 2005 using Windows Authentication. I was able to solve the issue with help from this and other forums. Here is what I did:
My environment: Windows XP clinet hosting Apache Tomcat 6 with MS SQL 2005 backend on Windows 2003
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()
.
just use replace
:
In [106]:
df.replace('N/A',np.NaN)
Out[106]:
x y
0 10 12
1 50 11
2 18 NaN
3 32 13
4 47 15
5 20 NaN
What you're trying is called chain indexing: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
You can use loc
to ensure you operate on the original dF:
In [108]:
df.loc[df['y'] == 'N/A','y'] = np.nan
df
Out[108]:
x y
0 10 12
1 50 11
2 18 NaN
3 32 13
4 47 15
5 20 NaN
Reference: https://metamug.com/blog/eclipse-gson-class-not-found
I figured out the issue. The linked server was created correctly. However, after the server was upgraded and switched the server name in sys.servers
still had the old server name.
I had to drop the old server name and add the new server name to sys.servers
on the new server
sp_dropserver 'Server_A'
GO
sp_addserver 'Server',local
GO
To add the answer provided by @Cody Brocious
In the context of virtualization where you are emulating a new system(CPU , I/O etc ) to a virtual machine we can see the following categories of emulators.
Interpretation: bochs is an example of interpreter , it is a x86 PC emulator,it takes each instruction from guest system translates it in another set of instruction( of the host ISA) to produce the intended effect.Yes it is very slow , it doesn't cache anything so every instruction goes through the same cycle.
Dynamic emalator: Qemu is a dynamic emulator. It does on the fly translation of guest instruction also caches results.The best part is that executes as many instructions as possible directly on the host system so that emulation is faster. Also as mentioned by Cody, it divides the code into blocks ( 1 single flow of execution).
Static emulator: As far I know there are no static emulator that can be helpful in virtualization.
Both array_push
and the method you described will work.
$cart = array();
$cart[] = 13;
$cart[] = 14;
// etc
//Above is correct. but below one is for further understanding
$cart = array();
for($i=0;$i<=5;$i++){
$cart[] = $i;
}
echo "<pre>";
print_r($cart);
echo "</pre>";
Is the same as:
<?php
$cart = array();
array_push($cart, 13);
array_push($cart, 14);
// Or
$cart = array();
array_push($cart, 13, 14);
?>
HSQLDB is a good candidate (the fact that it is used in OpenOffice may convinced some of you), but for such a small personnal application, why not using an object database (instead of a classic relationnal database) ?
I used DB4O in one of my projects, and I'm very satisfied with it. Being object-oriented, you don't need the whole Hibernate layer, and can directly insert/update/delete/query objects ! Moreover, you don't need to worry about the schema, you directly work with the objects and DB4O does the rest !
I agree that it may take some time to get used to this new type of database, but check the DB40 tutorial to see how easy it makes working with the DB !
EDIT: As said in the comments, DB4O handles automatically the newer versions of the classes. Moreover, a tool for browsing and updating the database outside of the application is available here : http://code.google.com/p/db4o-om/
I want to give a more generalized answer. One that will handle any case when you want to select only the first item in a LEFT JOIN.
You can use a subquery that GROUP_CONCATS what you want (sorted, too!), then just split the GROUP_CONCAT'd result and take only its first item, like so...
LEFT JOIN Person ON Person.id = (
SELECT SUBSTRING_INDEX(
GROUP_CONCAT(FirstName ORDER BY FirstName DESC SEPARATOR "_" ), '_', 1)
) FROM Person
);
Since we have DESC as our ORDER BY option, this will return a Person id for someone like "Zack". If we wanted someone with the name like "Andy", we would change ORDER BY FirstName DESC to ORDER BY FirstName ASC.
This is nimble, as this places the power of ordering totally within your hands. But, after much testing, it will not scale well in a situation with lots of users and lots of data.
It is, however, useful in running data-intensive reports for admin.
Use the My Class :)
My.Computer.Name
as for the IP address quick google search
Private Sub GetIPAddress()
Dim strHostName As String
Dim strIPAddress As String
strHostName = System.Net.Dns.GetHostName()
strIPAddress = System.Net.Dns.GetHostByName(strHostName).AddressList(0).ToString()
MessageBox.Show("Host Name: " & strHostName & "; IP Address: " & strIPAddress)
End Sub
@robert-hurst has a cleaner approach.
However, this solution may also be used, in places when you actually want to have a copy of Data Url after copying. For example, when you are building a website that uses lots of image/canvas operations.
// select canvas elements
var sourceCanvas = document.getElementById("some-unique-id");
var destCanvas = document.getElementsByClassName("some-class-selector")[0];
//copy canvas by DataUrl
var sourceImageData = sourceCanvas.toDataURL("image/png");
var destCanvasContext = destCanvas.getContext('2d');
var destinationImage = new Image;
destinationImage.onload = function(){
destCanvasContext.drawImage(destinationImage,0,0);
};
destinationImage.src = sourceImageData;
var e = jQuery.Event("keypress");
e.which = 13; //choose the one you want
e.keyCode = 13;
$("#theInputToTest").trigger(e);
There are two differences between static inner and non static inner classes.
In case of declaring member fields and methods, non static inner class cannot have static fields and methods. But, in case of static inner class, can have static and non static fields and method.
The instance of non static inner class is created with the reference of object of outer class, in which it has defined, this means it has enclosing instance. But the instance of static inner class is created without the reference of Outer class, which means it does not have enclosing instance.
See this example
class A
{
class B
{
// static int x; not allowed here
}
static class C
{
static int x; // allowed here
}
}
class Test
{
public static void main(String… str)
{
A a = new A();
// Non-Static Inner Class
// Requires enclosing instance
A.B obj1 = a.new B();
// Static Inner Class
// No need for reference of object to the outer class
A.C obj2 = new A.C();
}
}
Go to this link
Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download
Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.
I had the same problem with Tensorflow 2.0.0 in PyCharm. PyCharm did not recognize tensorflow.keras; I updated my PyCharm and the problem was resolved!
The difference between these two methods is:
parseXxx()
returns the primitive typevalueOf()
returns a wrapper object reference of the type.My solution
jQuery code
$('#my_form_id').on('submit', function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
var msg_error = 'An error has occured. Please try again later.';
var msg_timeout = 'The server is not responding';
var message = '';
var form = $('#my_form_id');
$.ajax({
data: formData,
async: false,
cache: false,
processData: false,
contentType: false,
url: form.attr('action'),
type: form.attr('method'),
error: function(xhr, status, error) {
if (status==="timeout") {
alert(msg_timeout);
} else {
alert(msg_error);
}
},
success: function(response) {
alert(response);
},
timeout: 7000
});
});
Instead of what you have written, you can write it directly in the SelectedIndexChanged event of the dropdownlist control, e.g.
protected void ddlleavetype_SelectedIndexChanged(object sender, EventArgs e)
{
//code goes here
}
To answer your questions in a easy way:
a) String.length();
b) String.charAt(/* String index */);
In Sql Server
You can do this using cross apply
Select
ColumnA,
ColumnB,
c.calccolumn1 As calccolumn1,
c.calccolumn1 / ColumnC As calccolumn2
from t42
cross apply (select (ColumnA + ColumnB) as calccolumn1) as c
if you are talking about just types, as other people said, parseInt() etc will return the correct type. Also, if for any reason the value could be both a number or a string and you don't want to call parseInt(), typeof expressions will also cast to the correct type:
function f(value:number|string){
if(typeof value==='number'){
// value : number
}else {
// value : string
}
}
another Swift 3 Example. The provided solution did not work for me.
private func playVideo(from file:String) {
let file = file.components(separatedBy: ".")
guard let path = Bundle.main.path(forResource: file[0], ofType:file[1]) else {
debugPrint( "\(file.joined(separator: ".")) not found")
return
}
let player = AVPlayer(url: URL(fileURLWithPath: path))
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer)
player.play()
}
useage:
playVideo(from: "video.extension")
Note: Check Copy Bundle Resources under Build Phases to ensure that the video is available to the Project.
You could do something like this:
my $data = <<END;
1) Scheme ID: abc-456-hu5t10 (High priority) *
2) Scheme ID: frt-78f-hj542w (Balanced)
3) Scheme ID: 23f-f974-nm54w (super formula run) *
END
foreach (split(/\n/,$data)) {
$_ =~ /Scheme ID: ([a-z0-9-]+)\s+\(([^)]+)\)\s*(\*)?/ || next;
my ($id,$word,$star) = ($1,$2,$3);
print "$id $word $star\n";
}
The key thing is the Regular expression:
Scheme ID: ([a-z0-9-]+)\s+\(([^)]+)\)\s*(\*)?
Which breaks up as follows.
The fixed String "Scheme ID: ":
Scheme ID:
Followed by one or more of the characters a-z, 0-9 or -. We use the brackets to capture it as $1:
([a-z0-9-]+)
Followed by one or more whitespace characters:
\s+
Followed by an opening bracket (which we escape) followed by any number of characters which aren't a close bracket, and then a closing bracket (escaped). We use unescaped brackets to capture the words as $2:
\(([^)]+)\)
Followed by some spaces any maybe a *, captured as $3:
\s*(\*)?
An example with VBScript (.vbs)
Sub sety(wsh, action, typey, vary, value)
Dim wu
Set wu = wsh.Environment(typey)
wui = wu.Item(vary)
Select Case action
Case "ls"
WScript.Echo wui
Case "del"
On Error Resume Next
wu.remove(vary)
On Error Goto 0
Case "set"
wu.Item(vary) = value
Case "add"
If wui = "" Then
wu.Item(vary) = value
ElseIf InStr(UCase(";" & wui & ";"), UCase(";" & value & ";")) = 0 Then
wu.Item(vary) = value & ";" & wui
End If
Case Else
WScript.Echo "Bad action"
End Select
End Sub
Dim wsh, args
Set wsh = WScript.CreateObject("WScript.Shell")
Set args = WScript.Arguments
Select Case WScript.Arguments.Length
Case 3
value = ""
Case 4
value = args(3)
Case Else
WScript.Echo "Arguments - 0: ls,del,set,add; 1: user,system, 2: variable; 3: value"
value = "```"
End Select
If Not value = "```" Then
' 0: ls,del,set,add; 1: user,system, 2: variable; 3: value
sety wsh, args(0), args(1), UCase(args(2)), value
End If
This is available in String::Util with the trim
method:
Editor's note: String::Util
is not a core module, but you can install it from CPAN with [sudo] cpan String::Util
.
use String::Util 'trim';
my $str = " hello ";
$str = trim($str);
print "string is now: '$str'\n";
prints:
string is now 'hello'
However it is easy enough to do yourself:
$str =~ s/^\s+//;
$str =~ s/\s+$//;
what worked for me
goto Settings -> Additional Settings -> Developer options -> Revoke USB Debugging Authorizations.
Kill adb.exe in the taskmanager (CTRL + SHIFT + ESCAPE)
Install again, watch for popups (accept RSA signature and install) Everything will work now
Setting up insets in Interface Builder like shown in the screenshot below
Will result in something like this:
More generally, you can also convert the new data into an array and use something like concat:
var newData = this.state.data.concat([data]);
this.setState({data: newData})
This pattern is actually used in Facebook's ToDo demo app (see the section "An Application") at https://facebook.github.io/react/.
a[title="My site"] {
color: red;
}
This also works with any attribute you want to add for instance:
HTML
<div class="my_class" anything="whatever">My Stuff</div>
CSS
.my_class[anything="whatever"] {
color: red;
}
See it work at: http://jsfiddle.net/vpYWE/1/
It could be used as a wrapper function for returning a reference to a private constant data type. For example in a linked list you have the constants tail and head, and if you want to determine if a node is a tail or head node, then you can compare it with the value returned by that function.
Though any optimizer would most likely optimize it out anyway...
See http://msdn.microsoft.com/en-us/library/ms187928.aspx
You can concatenate it:
SELECT CONVERT(VARCHAR(10), GETDATE(), 104) + ' ' + CONVERT(VARCHAR(8), GETDATE(), 108)
$("#DateOfBirth").datepicker({
yearRange: "-100:+0",
changeMonth: true,
changeYear: true,
});
yearRange: '1950:2013', // specifying a hard coded year range or this way
yearRange: "-100:+0", // last hundred years
It will help to show drop down for year and month selection.
You can get the Class reference of any class during run time through the Java Reflection Concept.
Check the Below Code. Explanation is given below
Here is one example that uses returned Class to create an instance of AClass:
package com.xyzws;
class AClass {
public AClass() {
System.out.println("AClass's Constructor");
}
static {
System.out.println("static block in AClass");
}
}
public class Program {
public static void main(String[] args) {
try {
System.out.println("The first time calls forName:");
Class c = Class.forName("com.xyzws.AClass");
AClass a = (AClass)c.newInstance();
System.out.println("The second time calls forName:");
Class c1 = Class.forName("com.xyzws.AClass");
} catch (ClassNotFoundException e) {
// ...
} catch (InstantiationException e) {
// ...
} catch (IllegalAccessException e) {
// ...
}
}
}
The printed output is
The first time calls forName:
static block in AClass
AClass's Constructor
The second time calls forName:
The class has already been loaded so there is no second "static block in AClass"
The Explanation is below
Class.ForName is called to get a Class Object
By Using the Class Object we are creating the new instance of the Class.
Any doubts about this let me know
You can scale the image with pygame.transform.scale
:
import pygame
picture = pygame.image.load(filename)
picture = pygame.transform.scale(picture, (1280, 720))
You can then get the bounding rectangle of picture
with
rect = picture.get_rect()
and move the picture with
rect = rect.move((x, y))
screen.blit(picture, rect)
where screen
was set with something like
screen = pygame.display.set_mode((1600, 900))
To allow your widgets to adjust to various screen sizes, you could make the display resizable:
import os
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((500, 500), HWSURFACE | DOUBLEBUF | RESIZABLE)
pic = pygame.image.load("image.png")
screen.blit(pygame.transform.scale(pic, (500, 500)), (0, 0))
pygame.display.flip()
while True:
pygame.event.pump()
event = pygame.event.wait()
if event.type == QUIT:
pygame.display.quit()
elif event.type == VIDEORESIZE:
screen = pygame.display.set_mode(
event.dict['size'], HWSURFACE | DOUBLEBUF | RESIZABLE)
screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0))
pygame.display.flip()
Indexing in python starting from 0. You wrote [1:] this would not return you a first char in any case - this will return you a rest(except first char) of string.
If you have the following structure:
mylist = ['base', 'sample', 'test']
And want to get fist char for the first one string(item):
myList[0][0]
>>> b
If all first chars:
[x[0] for x in myList]
>>> ['b', 's', 't']
If you have a text:
text = 'base sample test'
text.split()[0][0]
>>> b
Define a single Method without type like void add(Set ii){}
You can mention the type while calling the method based on your choice. It will work for any type of set.
I had the same problem as deke. I forgot to include the most important script: angular.js :)
<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
HTML 5 does support iframes. There were a few interesting attributes added like "sandbox" and "srcdoc".
http://www.w3schools.com/html5/tag_iframe.asp
or you can use
<object data="framed.html" type="text/html"><p>This is the fallback code!</p></object>
The solution that worked for me personally was:
in the build.gradle
defaultConfig {
multiDexEnabled true
}
dexOptions {
javaMaxHeapSize "4g"
}
class CountryListView(ListView):
model = Country
def render_to_response(self, context, **response_kwargs):
return HttpResponse(json.dumps(list(self.get_queryset().values_list('code', flat=True))),mimetype="application/json")
fixed the problem
also mimetype is important.
You are trying to access pop as if was a list or a tupple, but pop is not. It's a method.
In android studio 3.0 they have introduced android-profiler to help you to understand how your app uses CPU, memory, network, and battery resources.
https://developer.android.com/studio/profile/android-profiler
Here is a very simple way to do it by hand. You could also use the <algorithm>
, as Peter suggests.
#include <iostream>
int find(int arr[], int len, int seek)
{
for (int i = 0; i < len; ++i)
{
if (arr[i] == seek) return i;
}
return -1;
}
int main()
{
int arr[ 5 ] = { 4, 1, 3, 2, 6 };
int x = find(arr,5,3);
std::cout << x << std::endl;
}
Can't find anything simple and elegant just yet, but I have one idea: If you know the type of the property you wish to set, you can write your own default(T)
. There are two cases - T
is a value type, and T
is a reference type. You can see this by checking T.IsValueType
. If T
is a reference type, then you can simply set it to null
. If T
is a value type, then it will have a default parameterless constructor that you can call to get a "blank" value.
Code which disable chrome extensions for ones, who uses DesiredCapabilities to set browser flags :
desired_capabilities['chromeOptions'] = {
"args": ["--disable-extensions"],
"extensions": []
}
webdriver.Chrome(desired_capabilities=desired_capabilities)
If your dbname, username, password, etc strings lengths exceed values outlined at https://dev.mysql.com/doc/refman/5.7/en/grant-tables.html#grant-tables-scope-column-properties , you might also fail to log in, as this was in my case.
In my opinion this solution is very nice:
$("#dialog").dialog({
open: function(event, ui) {
$("input").blur();
}
});
Found here: unable-to-remove-autofocus-in-ui-dialog
I found the following as the simplest method:
You can also specify context location relatively to current classpath, which may be preferable
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
One way is to create a DateTime
object and use it for formatting:
new DateTime(myTimeSpan.Ticks).ToString(myCustomFormat)
// or using String.Format:
String.Format("{0:HHmmss}", new DateTime(myTimeSpan.Ticks))
This is the way I know. I hope someone can suggest a better way.
Here is a 'YouTube-video-id' like id generator e.g. "UcBKmq2XE5a"
StringBuilder builder = new StringBuilder();
Enumerable
.Range(65, 26)
.Select(e => ((char)e).ToString())
.Concat(Enumerable.Range(97, 26).Select(e => ((char)e).ToString()))
.Concat(Enumerable.Range(0, 10).Select(e => e.ToString()))
.OrderBy(e => Guid.NewGuid())
.Take(11)
.ToList().ForEach(e => builder.Append(e));
string id = builder.ToString();
It creates random ids of size 11 characters. You can increase/decrease that as well, just change the parameter of Take method.
0.001% duplicates in 100 million.
I used:
Tel: <a href="tel:+123 123456789">+123 123456789</a>
and the result is:
Tel: +123 123456789
Where "Tel:" stands for pure text and only the number is coded and clickable.
Removing *.snap (mine is *.markers), --clean-data or move workspace folder seems all did not work for me.
As my eclipse stopped working after I installed and switched my keyborad input to HIME, I went back to fctix and it worked.
If you want to set something on a timer, you can use JavaScript's setTimeout
or setInterval
methods:
setTimeout ( expression, timeout );
setInterval ( expression, interval );
Where expression
is a function and timeout
and interval
are integers in milliseconds. setTimeout
runs the timer once and runs the expression
once whereas setInterval will run the expression
every time the interval
passes.
So in your case it would work something like this:
setInterval(function() {
//call $.ajax here
}, 5000); //5 seconds
As far as the Ajax goes, see jQuery's ajax()
method. If you run an interval, there is nothing stopping you from calling the same ajax()
from other places in your code.
If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:
setInterval()
returns an integer which is the ID of the interval.
var id = setInterval(function() {
//call $.ajax here
}, 30000); // 30 seconds
If you store that ID in a variable, you can then call clearInterval(id)
which will stop the progression.
Then you can reinstantiate the setInterval()
call after you've completed your ajax form submission.
Sorry, to rehash an old question, but this was the first Stack Overflow question/answer that popped up on Google.
This post (which came up first on Google) talks about using the more updated syntax for PostgreSQL 10: https://blog.2ndquadrant.com/postgresql-10-identity-columns/
which happens to be:
CREATE TABLE test_new (
id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
);
Hope that helps :)
I had the same problem for Winforms.
The solution for me is:
Install-Package Microsoft.ReportViewer.Runtime.Winforms
That URL works fine. The message you report is normal when you look at it in a browser. My copy of Eclipse has no problems talking to it. If yours does, I suspect a proxy configuration error in your copy of eclipse.
copy mysql-connector-java-5.1.24-bin.jar
Paste it into \Apache Software Foundation\Tomcat 6.0\lib\<--here-->
Restart Your Server from Eclipes.
Done
Simplest Understanding for default export
is
Export
is ES6's feature which is used to Export a module(file) and use it in some other module(file).
Default Export:
default export
is the convention if you want to export only one object(variable, function, class) from the file(module).Export or Named Export:
It is used to export the object(variable, function, calss) with the same name.
It is used to export multiple objects from one file.
It cannot be renamed when importing in another file, it must have the same name that was used to export it, but we can create its alias by using as
operator.
In React, Vue and many other frameworks the Export is mostly used to export reusable components to make modular based applications.
In my case, answers of taciosd and Netero pointed in the correct direction. By analyzing:
gradle assembleDebug --stacktrace --debug
Linux:
./gradlew assembleDebug --stacktrace --debug
i found out that one filepath in the assets folder was too long and aapt.exe stopped by returning 1 (and no specific error message) when processing that file. It seems that files with non ASCII characters in names are not accepted as well.
try this instead $(".video-divs.focused")
. This works if you are looking for video-divs that are focused.
If anybody still wants this, Java regex for support Unicode? is a good one. It's for when you want ONLY letters (no matter what encoding - japaneese, sweedish) iside an EditText. Later, you can check it using Matcher
and Pattern.compile()
for i=1,#target do
game.Players.target[i].Character:BreakJoints()
end
Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:
game.Players.target.1.Character:BreakJoints()
Which is completely incorrect.
c = game.Players:GetChildren()
Never use "Players:GetChildren()", it is not guaranteed to return only players.
Instead use:
c = Game.Players:GetPlayers()
if msg:lower()=="me" then
table.insert(people, source)
return people
Here you add the player's name in the list "people", where you in the other places adds the player object.
Fixed code:
local Admins = {"FakeNameHereSoNoStalkers"}
function Kill(Players)
for i,Player in ipairs(Players) do
if Player.Character then
Player.Character:BreakJoints()
end
end
end
function IsAdmin(Player)
for i,AdminName in ipairs(Admins) do
if Player.Name:lower() == AdminName:lower() then return true end
end
return false
end
function GetPlayers(Player,Msg)
local Targets = {}
local Players = Game.Players:GetPlayers()
if Msg:lower() == "me" then
Targets = { Player }
elseif Msg:lower() == "all" then
Targets = Players
elseif Msg:lower() == "others" then
for i,Plr in ipairs(Players) do
if Plr ~= Player then
table.insert(Targets,Plr)
end
end
else
for i,Plr in ipairs(Players) do
if Plr.Name:lower():sub(1,Msg:len()) == Msg then
table.insert(Targets,Plr)
end
end
end
return Targets
end
Game.Players.PlayerAdded:connect(function(Player)
if IsAdmin(Player) then
Player.Chatted:connect(function(Msg)
if Msg:lower():sub(1,6) == ":kill " then
Kill(GetPlayers(Player,Msg:sub(7)))
end
end)
end
end)
You could use a ArrayList instead of array. So that you can add n number of elements
List<Integer> myVar = new ArrayList<Integer>();
My take on this for future people watching this:
This could also happen if you're using: <?
instead of <?php
.
This page from Microsoft's Excel VBA documentation helped me: https://docs.microsoft.com/en-us/office/vba/api/excel.xlpastetype
It gives a bunch of options to customize how you paste. For instance, you could xlPasteAll (probably what you're looking for), or xlPasteAllUsingSourceTheme, or even xlPasteAllExceptBorders.
I finally found a solution. I wasted hours just trying to figure what this issue was. I tried deleting all those files suggested above and it didn't work for me, I tried adding new inbound rules to firewall for myslqd.exe and it didn't work. The thing that is causing this error is MySQL port is misconfigured and the fix was really simple. if you are using Wamp or Xampp go to Main Folder/Bin/mysql/mysql/ and find a file named my.ini
Open my.ini file press CTRL + F and inside it search for PORT and change whatever value of port to - 3306 and save file;
After that go to Wamp icon at the bottom of the taskbar (system tray) and left click choose mysql option and click "test port 3306 used" and see if it gives you any error. you can also click use other port other than whatever is shown there and port 3306.
Goodluck. if it works comment.
There is a trick for this. All you have to do is to use RelativeLayout
instead of LinearLayout
as the main container. It's important to have android:layout_gravity="fill_horizontal"
set for it. That should do it.
It should be implemented as a free, non-friend functions, especially if, like most things these days, the output is mainly used for diagnostics and logging. Add const accessors for all the things that need to go into the output, and then have the outputter just call those and do formatting.
I've actually taken to collecting all of these ostream output free functions in an "ostreamhelpers" header and implementation file, it keeps that secondary functionality far away from the real purpose of the classes.
You can try to get index or position of list or array first, then use for loop to assign current array to a temp list, filter out unwanted item and store wanted item back to original array
removeItem(index) {
var tempList = this.uploadFile;
this.uploadFile = [];
for (var j = 0; j < tempList.length; j++) {
if (j != index)
this.uploadFile.push(tempList[j]);
}
}
I just found the solution, kind of answering to my own question in case anyone else stumbles upon it.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, "body goes here" );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
$result=curl_exec ($ch);
For the few people asking for a generic method, this should help you (5 years later :p).
For my below example, I'm pulling the RequestMapping URL value from methods that have the RequestMapping annotation. To adapt this for fields, just change the
for (Method method: clazz.getMethods())
to
for (Field field: clazz.getFields())
And swap usage of RequestMapping for whatever annotation you are looking to read. But make sure that the annotation has @Retention(RetentionPolicy.RUNTIME).
public static String getRequestMappingUrl(final Class<?> clazz, final String methodName)
{
// Only continue if the method name is not empty.
if ((methodName != null) && (methodName.trim().length() > 0))
{
RequestMapping tmpRequestMapping;
String[] tmpValues;
// Loop over all methods in the class.
for (Method method: clazz.getMethods())
{
// If the current method name matches the expected method name, then keep going.
if (methodName.equalsIgnoreCase(method.getName()))
{
// Try to extract the RequestMapping annotation from the current method.
tmpRequestMapping = method.getAnnotation(RequestMapping.class);
// Only continue if the current method has the RequestMapping annotation.
if (tmpRequestMapping != null)
{
// Extract the values from the RequestMapping annotation.
tmpValues = tmpRequestMapping.value();
// Only continue if there are values.
if ((tmpValues != null) && (tmpValues.length > 0))
{
// Return the 1st value.
return tmpValues[0];
}
}
}
}
}
// Since no value was returned, log it and return an empty string.
logger.error("Failed to find RequestMapping annotation value for method: " + methodName);
return "";
}
The best way to solve your problem is to set the UseSystemPasswordChar
property to true. Then, the Caps-lock message is shown when the user enters the field and the Caps-Lock is on (at least for Vista and Windows 7).
Another alternative is to set the PasswordChar
property to a character value (* for example). This also triggers the automatic Caps-Lock handling.
You might want to check if the websecurity of vpn client is the issue. I uninstalled it and it worked fine..Found the solution here https://superuser.com/questions/471089/svn-connection-not-successful
First we must ensure that the desired attribute is loaded, and then output it. Use this:
$product = Mage::getModel('catalog/product')->load('<product_id>', array('<attribute_code>'));
$attributeValue = $product->getResource()->getAttribute('<attribute_code>')->getFrontend()->getValue($product);
I don't have Express Management Studio on this machine, so I'm going based on memory. I think you need to set the column as "IDENTITY", and there should be a [+] under properties where you can expand, and set auto-increment to true.
Use PDFiumViewer. I searched for a long time till I came up with a similar solution, then I found this clean piece of code that does not rely on sending raw files to the printer (which is bad if they get interpreted as text files..) or using Acrobat or Ghostscript as a helper (both would need to be installed, which is a hassle):
https://stackoverflow.com/a/41751184/586754
PDFiumViewer comes via nuget, the code example above is complete. Pass in null values for using the default printer.
Use button
tag instead of input
and use pull-right
class.
pull-right
class totally messes up both of your buttons, but you can fix this by defining custom margin on the right side.
<button class="btn btn-primary pull-right btn-sm RbtnMargin" type="button">Save</button>
<button class="btn btn-primary pull-right btn-sm" type="button">Cancel</button>
Then use the following CSS for the class
.RbtnMargin { margin-left: 5px; }
For those looking to use axios-mock-adapter in place of the mockfetch example in the Redux documentation for async testing, I successfully used the following:
describe('SignInUser', () => {
var history = {
push: function(str) {
expect(str).toEqual('/feed');
}
}
it('Dispatches authorization', () => {
let mock = new MockAdapter(axios);
mock.onPost(`${ROOT_URL}/auth/signin`, {
email: '[email protected]',
password: 'test'
}).reply(200, {token: 'testToken' });
const expectedActions = [ { type: types.AUTH_USER } ];
const store = mockStore({ auth: [] });
return store.dispatch(actions.signInUser({
email: '[email protected]',
password: 'test',
}, history)).then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
});
In order to test a successful case for signInUser
in file actions/index.js:
export const signInUser = ({ email, password }, history) => async dispatch => {
const res = await axios.post(`${ROOT_URL}/auth/signin`, { email, password })
.catch(({ response: { data } }) => {
...
});
if (res) {
dispatch({ type: AUTH_USER }); // Test verified this
localStorage.setItem('token', res.data.token); // Test mocked this
history.push('/feed'); // Test mocked this
}
}
Given that this is being done with jest, the localstorage call had to be mocked. This was in file src/setupTests.js:
const localStorageMock = {
removeItem: jest.fn(),
getItem: jest.fn(),
setItem: jest.fn(),
clear: jest.fn()
};
global.localStorage = localStorageMock;
I had to go look for ojdbc compatible with version on oracle that was installed this fixed my problem, my bad was thinking one ojdbc would work for all
Suppose df is a pandas DataFrame then to get number of non-null values and data types of all column at once use:
df.info()
You can cast the int to an enum
(MyColour)2
There is also the option of Enum.Parse
(MyColour)Enum.Parse(typeof(MyColour), "Red")
If you can't know the progress you should not fake it by abusing a progress bar, instead just display some sort of busy icon like en.wikipedia.org/wiki/Throbber#Spinning_wheel Show it when starting the task and hide it when it's finished. That would make for a more "honest" GUI.
I also use Stefan Petre’s http://www.eyecon.ro/bootstrap-datepicker and it does not work with Bootstrap 3 without modification. Note that http://eternicode.github.io/bootstrap-datepicker/ is a fork of Stefan Petre's code.
You have to change your markup (the sample markup will not work) to use the new CSS and form grid layout in Bootstrap 3. Also, you have to modify some CSS and JavaScript in the actual bootstrap-datepicker implementation.
Here is my solution:
<div class="form-group row">
<div class="col-xs-8">
<label class="control-label">My Label</label>
<div class="input-group date" id="dp3" data-date="12-02-2012" data-date-format="mm-dd-yyyy">
<input class="form-control" type="text" readonly="" value="12-02-2012">
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
</div>
</div>
</div>
CSS changes in datepicker.css on lines 176-177:
.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {
Javascript change in datepicker-bootstrap.js on line 34:
this.component = this.element.is('.date') ? this.element.find('.input-group-addon') : false;
UPDATE
Using the newer code from http://eternicode.github.io/bootstrap-datepicker/ the changes are as follows:
CSS changes in datepicker.css on lines 446-447:
.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {
Javascript change in datepicker-bootstrap.js on line 46:
this.component = this.element.is('.date') ? this.element.find('.input-group-addon, .btn') : false;
Finally, the JavaScript to enable the datepicker (with some options):
$(".input-group.date").datepicker({ autoclose: true, todayHighlight: true });
Tested with Bootstrap 3.0 and JQuery 1.9.1. Note that this fork is better to use than the other as it is more feature rich, has localization support and auto-positions the datepicker based on the control position and window size, avoiding the picker going off the screen which was a problem with the older version.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries
for (var [key, item] of someArray.entries()) { ... }
In TS this requires targeting ES2015 since it requires the runtime to support iterators, which ES5 runtimes don't. You can of course use something like Babel to make the output work on ES5 runtimes.
As far as I know, it's not possible in IE because it uses the OS component.
Here is a link where the control is replaced, but I don't know if thats what you want to do.
<select>
Something New, Part 1So you've built a beautiful, standards-compliant site utilizing the latest and
greatest CSS techniques. You've mastered control of styling every element, but
in the back of your mind, a little voice is nagging you about how ugly your
<select>
s are. Well, today we're going to explore a way to silence that
little voice and truly complete our designs. With a little DOM scripting and
some creative CSS, you too can make your <select>
s beautiful… and you won't
have to sacrifice accessibility, usability or graceful degradation.
We all know the <select>
is just plain ugly. In fact, many try to limit its
use to avoid its classic web circa 1994 inset borders. We should not avoid
using the <select>
though--it is an important part of the current form
toolset; we should embrace it. That said, some creative thinking can improve
it.
<select>
We'll use a simple for our example:
<select id="something" name="something">
<option value="1">This is option 1</option>
<option value="2">This is option 2</option>
<option value="3">This is option 3</option>
<option value="4">This is option 4</option>
<option value="5">This is option 5</option>
</select>
[Note: It is implied that this <select>
is in the context of a complete
form.]
So we have five <option>
s within a <select>
. This <select>
has a
uniquely assigned id
of "something." Depending on the browser/platform
you're viewing it on, your <select>
likely looks roughly like this:
(source: easy-designs.net)
or this
(source: easy-designs.net)
Let's say we want to make it look a little more modern, perhaps like this:
(source: easy-designs.net)
So how do we do it? Keeping the basic <select>
is not an option. Apart from
basic background color, font and color adjustments, you don't really have a
lot of control over the .
However, we can mimic the superb functionality of a <select>
in a new form
control without sacrificing semantics, usability or accessibility. In order to
do that, we need to examine the nature of a <select>
.
A <select>
is, essentially, an unordered list of choices in which you can
choose a single value to submit along with the rest of a form. So, in essence,
it's a <ul>
on steroids. Continuing with that line of thinking, we can
replace the <select>
with an unordered list, as long as we give it some
enhanced functionality. As <ul>
s can be styled in a myriad of different
ways, we're almost home free. Now the questions becomes "how to ensure that we
maintain the functionality of the <select>
when using a <ul>
?" In other
words, how do we submit the correct value along with the form, if we
are no longer using a form control?
Enter the DOM. The final step in the process is making the <ul>
function/feel like a <select>
, and we can accomplish that with
JavaScript/ECMA Script and a little clever CSS. Here is the basic list of
requirements we need to have a functional faux <select>
:
With this plan, we can begin to tackle each part in succession.
So first we need to collect all of the attributes and s out of the and rebuild it as a . We accomplish this by running the following JS:
function selectReplacement(obj) {
var ul = document.createElement('ul');
ul.className = 'selectReplacement';
// collect our object's options
var opts = obj.options;
// iterate through them, creating <li>s
for (var i=0; i<opts.length; i++) {
var li = document.createElement('li');
var txt = document.createTextNode(opts[i].text);
li.appendChild(txt);
ul.appendChild(li);
}
// add the ul to the form
obj.parentNode.appendChild(ul);
}
You might be thinking "now what happens if there is a selected <option>
already?" We can account for this by adding another loop before we create the
<li>
s to look for the selected <option>
, and then store that value in
order to class
our selected <li>
as "selected":
…
var opts = obj.options;
// check for the selected option (default to the first option)
for (var i=0; i<opts.length; i++) {
var selectedOpt;
if (opts[i].selected) {
selectedOpt = i;
break; // we found the selected option, leave the loop
} else {
selectedOpt = 0;
}
}
for (var i=0; i<opts.length; i++) {
var li = document.createElement('li');
var txt = document.createTextNode(opts[i].text);
li.appendChild(txt);
if (i == selectedOpt) {
li.className = 'selected';
}
ul.appendChild(li);
…
[Note: From here on out, option 5 will be selected, to demonstrate this functionality.]
Now, we can run this function on every <select>
on the page (in our case,
one) with the following:
function setForm() {
var s = document.getElementsByTagName('select');
for (var i=0; i<s.length; i++) {
selectReplacement(s[i]);
}
}
window.onload = function() {
setForm();
}
We are nearly there; let's add some style.
I don't know about you, but I am a huge fan of CSS dropdowns (especially the
Suckerfish variety). I've been
working with them for some time now and it finally dawned on me that a
<select>
is pretty much like a dropdown menu, albeit with a little more
going on under the hood. Why not apply the same stylistic theory to our
faux-<select>
? The basic style goes something like this:
ul.selectReplacement {
margin: 0;
padding: 0;
height: 1.65em;
width: 300px;
}
ul.selectReplacement li {
background: #cf5a5a;
color: #fff;
cursor: pointer;
display: none;
font-size: 11px;
line-height: 1.7em;
list-style: none;
margin: 0;
padding: 1px 12px;
width: 276px;
}
ul.selectOpen li {
display: block;
}
ul.selectOpen li:hover {
background: #9e0000;
color: #fff;
}
Now, to handle the "selected" list item, we need to get a little craftier:
ul.selectOpen li {
display: block;
}
ul.selectReplacement li.selected {
color: #fff;
display: block;
}
ul.selectOpen li.selected {
background: #9e0000;
display: block;
}
ul.selectOpen li:hover,
ul.selectOpen li.selected:hover {
background: #9e0000;
color: #fff;
}
Notice that we are not using the :hover pseudo-class for the <ul>
to make it
open, instead we are class
-ing it as "selectOpen". The reason for this is
two-fold:
<select>
behave like a real <select>
, we need the list to open in an onclick
event and not on a simple mouse-over.To implement this, we can take what we learned from Suckerfish and apply it to
our own JavaScript by dynamically assigning and removing this class
in
``onclickevents for the list items. To do this right, we will need the
ability to change the
onclick` events for each list item on the fly to switch
between the following two actions:
<select>
when clicking the selected/default option when the list is collapsed; and<select>
.We will create a function called selectMe()
to handle the reassignment of
the "selected" class
, reassignment of the onclick
events for the list
items, and the collapsing of the faux-<select>
:
As the original Suckerfish taught us, IE will not recognize a hover state on
anything apart from an <a>
, so we need to account for that by augmenting
some of our code with what we learned from them. We can attach onmouseover and
onmouseout events to the "selectReplacement" class
-ed <ul>
and its
<li>
s:
function selectReplacement(obj) {
…
// create list for styling
var ul = document.createElement('ul');
ul.className = 'selectReplacement';
if (window.attachEvent) {
ul.onmouseover = function() {
ul.className += ' selHover';
}
ul.onmouseout = function() {
ul.className =
ul.className.replace(new RegExp(" selHover\\b"), '');
}
}
…
for (var i=0; i<opts.length; i++) {
…
if (i == selectedOpt) {
li.className = 'selected';
}
if (window.attachEvent) {
li.onmouseover = function() {
this.className += ' selHover';
}
li.onmouseout = function() {
this.className =
this.className.replace(new RegExp(" selHover\\b"), '');
}
}
ul.appendChild(li);
}
Then, we can modify a few selectors in the CSS, to handle the hover for IE:
ul.selectReplacement:hover li,
ul.selectOpen li {
display: block;
}
ul.selectReplacement li.selected {
color: #fff;
display: block;
}
ul.selectReplacement:hover li.selected**,
ul.selectOpen li.selected** {
background: #9e0000;
display: block;
}
ul.selectReplacement li:hover,
ul.selectReplacement li.selectOpen,
ul.selectReplacement li.selected:hover {
background: #9e0000;
color: #fff;
cursor: pointer;
}
Now we have a list behaving like a <select>
; but we still
need a means of changing the selected list item and updating the value of the
associated form element.
We already have a "selected" class
we can apply to our selected list item,
but we need a way to go about applying it to a <li>
when it is clicked on
and removing it from any of its previously "selected" siblings. Here's the JS
to accomplish this:
function selectMe(obj) {
// get the <li>'s siblings
var lis = obj.parentNode.getElementsByTagName('li');
// loop through
for (var i=0; i<lis.length; i++) {
// not the selected <li>, remove selected class
if (lis[i] != obj) {
lis[i].className='';
} else { // our selected <li>, add selected class
lis[i].className='selected';
}
}
}
[Note: we can use simple className
assignment and emptying because we are in
complete control of the <li>
s. If you (for some reason) needed to assign
additional classes to your list items, I recommend modifying the code to
append and remove the "selected" class to your className
property.]
Finally, we add a little function to set the value of the original <select>
(which will be submitted along with the form) when an <li>
is clicked:
function setVal(objID, selIndex) {
var obj = document.getElementById(objID);
obj.selectedIndex = selIndex;
}
We can then add these functions to the onclick
event of our <li>
s:
…
for (var i=0; i<opts.length; i++) {
var li = document.createElement('li');
var txt = document.createTextNode(opts[i].text);
li.appendChild(txt);
li.selIndex = opts[i].index;
li.selectID = obj.id;
li.onclick = function() {
setVal(this.selectID, this.selIndex);
selectMe(this);
}
if (i == selectedOpt) {
li.className = 'selected';
}
ul.appendChild(li);
}
…
There you have it. We have created our functional faux-. As we have
not hidden the original
yet, we can [watch how it
behaves](files/4.html) as we choose different options from our
faux-
. Of course, in the final version, we don't want the original
to show, so we can hide it by
class`-ing it as "replaced," adding
that to the JS here:
function selectReplacement(obj) {
// append a class to the select
obj.className += ' replaced';
// create list for styling
var ul = document.createElement('ul');
…
Then, add a new CSS rule to hide the
select.replaced {
display: none;
}
With the application of a few images to finalize the design (link not available) , we are good to go!
And here is another link to someone that says it can't be done.
Try this
SELECT ID, Name
FROM Table1
WHERE ID NOT IN (SELECT ID FROM Table2)
Try wrapping your FileWriter
in a BufferedWriter
:
BufferedWriter bw = new BufferedWriter(writer);
bw.newLine();
Javadocs for BufferedWriter here.
The easiest way to change the background color of the jumbotron
If you want to change the background color of your jumbotron, then for that you can apply a background color to it using one of your custom class.
HTML Code:
<div class="jumbotron myclass">
<h1>My Heading</h1>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
</div>
CSS Code:
<style>
.myclass{
background-color: red;
}
</style>
Chrome uses the same Internet Options as IE.
Try opening your Internet Options and removing the URL from "Trusted Sites." This should regenerate a 401 call for credentials when you restart the browser and visit the URL again.
You may need to remove it from "Intranet Sites" as well.
sometime it happens when you try to (run or create) a .jar file under /libs folder by right click it in android studio. you can select the dropdown in top of android stuio and change it to app. This will work
From http://spreadsheetpage.com/index.php/tip/making_an_exact_copy_of_a_range_of_formulas_take_2:
Note: If the paste operation back to Excel doesn't work correctly, chances are that you've used Excel's Text-to-Columns feature recently, and Excel is trying to be helpful by remembering how you last parsed your data. You need to fire up the Convert Text to Columns Wizard. Choose the Delimited option and click Next. Clear all of the Delimiter option checkmarks except Tab.
Or, from http://spreadsheetpage.com/index.php/tip/making_an_exact_copy_of_a_range_of_formulas/:
If you're a VBA programmer, you can simply execute the following code:
With Sheets("Sheet1")
.Range("A11:D20").Formula = .Range("A1:D10").Formula
End With
If your software uses a ProxySelector
(for example for using a PAC-script instead of a static host/port) and your HTTPComponents is version 4.3 or above then you can use your ProxySelector
for your HttpClient
like this:
ProxySelector myProxySelector = ...;
HttpClient myHttpClient = HttpClientBuilder.create().setRoutePlanner(new SystemDefaultRoutePlanner(myProxySelector))).build();
And then do your requests as usual:
HttpGet myRequest = new HttpGet("/");
myHttpClient.execute(myRequest);
I've tried this and it works:
yourelement.next().val();
yourelement could be:
$('#elementIdName').next().val();
good luck!
You can use r libraries for 3 D plotting.
Steps are:
First create a data frame using data.frame() command.
Create a 3D plot by using scatterplot3D library.
Or You can also rotate your chart using rgl library by plot3d() command.
Alternately you can use plot3d() command from rcmdr library.
In MATLAB, you can use surf(), mesh() or surfl() command as per your requirement.
[http://in.mathworks.com/help/matlab/examples/creating-3-d-plots.html]
If you mean the first and last entry of the array when talking about a.first and a.last, it goes like this:
foreach ($arr_nav as $inner_array) {
echo reset($inner_array); //apple, orange, pear
echo end($inner_array); //My Apple, View All Oranges, A Pear
}
arrays in PHP have an internal pointer which you can manipulate with reset, next, end. Retrieving keys/values works with key and current, but using each might be better in many cases..
Just FYI, I noticed this information from the jQuery documentation which I believe applies to this issue:
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.
Changing the hosts file like @thanix didn't work for me, but the extension mentioned by @dkruchok did solve the problem.
I am getting day
, month
and year
using dedicated functions moment().date(), moment().month() and moment().year() of momentjs
.
let day = moment('2014-07-28', 'YYYY/MM/DD').date();_x000D_
let month = 1 + moment('2014-07-28', 'YYYY/MM/DD').month();_x000D_
let year = moment('2014-07-28', 'YYYY/MM/DD').year();_x000D_
_x000D_
console.log(day);_x000D_
console.log(month);_x000D_
console.log(year);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
_x000D_
I don't know why there are 48 upvotes for @Chris Schmitz answer which is not 100% correct.
Month is in form of array and starts from 0 so to get exact value we should use 1 + moment().month()
The inspect.isclass is probably the best solution, and it's really easy to see how it's actually implemented
def isclass(object):
"""Return true if the object is a class.
Class objects provide these attributes:
__doc__ documentation string
__module__ name of module in which this class was defined"""
return isinstance(object, (type, types.ClassType))
Some context additional about basic authentication, it consists in a header which contains the key/value pair:
Authorization: Basic Z2VybWFuOmdlcm1hbg==
where "Authorization" is the headers key, and the headers value has a string ( "Basic" word plus blank space) concatenated to "Z2VybWFuOmdlcm1hbg==", which are the user and password in base 64 joint by double dot
String name = "username";
String password = "secret";
String authString = name + ":" + password;
String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
...
objectXXX.header("Authorization", "Basic " + authStringEnc);
Buttons do not resize their inner images.
My solution does not require code manipulation.
It uses a layout with TextView and ImageView.
The background of the layout should have the red 3d drawable.
You may need to define the android:scaleType xml attribute.
Example:
<LinearLayout
android:id="@+id/list_item"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:padding="2dp" >
<ImageView
android:layout_width="50dp"
android:layout_height="fill_parent"
android:src="@drawable/camera" />
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:lines="1"
android:gravity="center_vertical"
android:text="Hello - primary" />
</LinearLayout>
BTW:
Good luck