The prime example to understand the fork()
and exec()
concept is the shell,the command interpreter program that users typically executes after logging into the system.The shell interprets the first word of command line as a command name
For many commands,the shell forks and the child process execs the command associated with the name treating the remaining words on the command line as parameters to the command.
The shell allows three types of commands. First, a command can be an executable file that contains object code produced by compilation of source code (a C program for example). Second, a command can be an executable file that contains a sequence of shell command lines. Finally, a command can be an internal shell command.(instead of an executable file ex->cd,ls etc.)
You can find an introduction to file dialogs in the Java Tutorials. Java2s also has some example code.
You need to escape it: on many databases this is done by preceding it with backslash, \%
.
So abc
becomes abc\%
.
Your programming language will have a database-specific function to do this for you. For example, PHP has mysql_escape_string() for the MySQL database.
If you're using at least Java 8, see my other answer.
If you're already using Google Guava, see Sean Patrick Floyd's answer.
If you're stuck at Java 7 and don't want to include Google Guava, you can write your own (read-only) Iterables.concat()
using no more than Iterable
and Iterator
:
public static <E> Iterable<E> concat(final Iterable<? extends E> iterable1,
final Iterable<? extends E> iterable2) {
return new Iterable<E>() {
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
final Iterator<? extends E> iterator1 = iterable1.iterator();
final Iterator<? extends E> iterator2 = iterable2.iterator();
@Override
public boolean hasNext() {
return iterator1.hasNext() || iterator2.hasNext();
}
@Override
public E next() {
return iterator1.hasNext() ? iterator1.next() : iterator2.next();
}
};
}
};
}
@SafeVarargs
public static <E> Iterable<E> concat(final Iterable<? extends E>... iterables) {
return concat(Arrays.asList(iterables));
}
public static <E> Iterable<E> concat(final Iterable<Iterable<? extends E>> iterables) {
return new Iterable<E>() {
final Iterator<Iterable<? extends E>> iterablesIterator = iterables.iterator();
@Override
public Iterator<E> iterator() {
return !iterablesIterator.hasNext() ? Collections.emptyIterator()
: new Iterator<E>() {
Iterator<? extends E> iterableIterator = nextIterator();
@Override
public boolean hasNext() {
return iterableIterator.hasNext();
}
@Override
public E next() {
final E next = iterableIterator.next();
findNext();
return next;
}
Iterator<? extends E> nextIterator() {
return iterablesIterator.next().iterator();
}
Iterator<E> findNext() {
while (!iterableIterator.hasNext()) {
if (!iterablesIterator.hasNext()) {
break;
}
iterableIterator = nextIterator();
}
return this;
}
}.findNext();
}
};
}
Well, I had a similar challenge. Using the inspect element tool in Firefox, I was able to trace the markup and the CSS used to style the link when clicked. On click, the list item (li) is given a class of .open and it's the anchor tag in the class that is formatted with the grey color background.
To fix this, just add this to your stylesheet.
.nav .open > a
{
background:#759ad6;
// Put in styling
}
A moving average can also be calculated and visualized directly in a line chart by using the following code:
Example using stock price data:
import pandas_datareader.data as web
import matplotlib.pyplot as plt
import datetime
plt.style.use('ggplot')
# Input variables
start = datetime.datetime(2016, 1, 01)
end = datetime.datetime(2018, 3, 29)
stock = 'WFC'
# Extrating data
df = web.DataReader(stock,'morningstar', start, end)
df = df['Close']
print df
plt.plot(df['WFC'],label= 'Close')
plt.plot(df['WFC'].rolling(9).mean(),label= 'MA 9 days')
plt.plot(df['WFC'].rolling(21).mean(),label= 'MA 21 days')
plt.legend(loc='best')
plt.title('Wells Fargo\nClose and Moving Averages')
plt.show()
Tutorial on how to do this: https://youtu.be/XWAPpyF62Vg
You should stick to the NSInteger
data types when possible. So you'd create the number like that:
NSInteger myValue = 1;
NSNumber *number = [NSNumber numberWithInteger: myValue];
Decoding works with the integerValue
method then:
NSInteger value = [number integerValue];
This is in answer to your question...
I'd also like to know how to make it open up in Sublime Text 2 instead
For Windows:
git config --global core.editor "'C:/Program Files/Sublime Text 2/sublime_text.exe'"
Check that the path for sublime_text.exe
is correct and adjust if needed.
For Mac/Linux:
git config --global core.editor "subl -n -w"
If you get an error message such as:
error: There was a problem with the editor 'subl -n -w'.
Create the alias for subl
sudo ln -s /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/local/bin/subl
Again check that the path matches for your machine.
For Sublime Text simply save cmd S
and close the window cmd W
to return to git.
To avoid the "however" in Erandac's answer in combination of Daniel's and Salman's answers, one may use one of the following "partition workarounds"
SELECT customerID, myDate
-- partition ranking works only with CTE / from MySQL 8.0 on
, RANK() OVER (PARTITION BY customerID ORDER BY dateFrom) AS rank,
-- Erandac's method in combination of Daniel's and Salman's
-- count all items in sequence, maximum reaches row count.
, IF(customerID=@_lastRank, @_curRank:=@_curRank, @_curRank:=@_sequence+1) AS sequenceRank
, @_sequence:=@_sequence+1 as sequenceOverAll
-- Dense partition ranking, works also with MySQL 5.7
-- remember to set offset values in from clause
, IF(customerID=@_lastRank, @_nxtRank:=@_nxtRank, @_nxtRank:=@_nxtRank+1 ) AS partitionRank
, IF(customerID=@_lastRank, @_overPart:=@_overPart+1, @_overPart:=1 ) AS partitionSequence
, @_lastRank:=customerID
FROM myCustomers,
(SELECT @_curRank:=0, @_sequence:=0, @_lastRank:=0, @_nxtRank:=0, @_overPart:=0 ) r
ORDER BY customerID, myDate
The partition ranking in the 3rd variant in this code snippet will return continous ranking numbers. this will lead to a data structur similar to the rank() over partition by
result. As an example, see below. In particular, the partitionSequence will always start with 1 for each new partitionRank, using this method:
customerID myDate sequenceRank (Erandac)
| sequenceOverAll
| | partitionRank
| | | partitionSequence
| | | | lastRank
... lines ommitted for clarity
40 09.11.2016 11:19 1 44 1 44 40
40 09.12.2016 12:08 1 45 1 45 40
40 09.12.2016 12:08 1 46 1 46 40
40 09.12.2016 12:11 1 47 1 47 40
40 09.12.2016 12:12 1 48 1 48 40
40 13.10.2017 16:31 1 49 1 49 40
40 15.10.2017 11:00 1 50 1 50 40
76 01.07.2015 00:24 51 51 2 1 76
77 04.08.2014 13:35 52 52 3 1 77
79 15.04.2015 20:25 53 53 4 1 79
79 24.04.2018 11:44 53 54 4 2 79
79 08.10.2018 17:37 53 55 4 3 79
117 09.07.2014 18:21 56 56 5 1 117
119 26.06.2014 13:55 57 57 6 1 119
119 02.03.2015 10:23 57 58 6 2 119
119 12.10.2015 10:16 57 59 6 3 119
119 08.04.2016 09:32 57 60 6 4 119
119 05.10.2016 12:41 57 61 6 5 119
119 05.10.2016 12:42 57 62 6 6 119
...
After a lot of surfing, i found out the problem is GC overhead (out of memory). By adding below code to my build.gradle saved my day.
android {
dexOptions {
incremental = true;
preDexLibraries = false
javaMaxHeapSize "4g" // 2g should be also OK
}
}
reference - ProcessException: org.gradle.process.internal.ExecException finished with non-zero exit value 2
Here is a working example of above. http://jsfiddle.net/z7L6m2sc/ Now select2 has been updated the classes have change may be why you cannot get it to work. Here is the css....
.select2-dropdown.select2-dropdown--below{
width: 148px !important;
}
.select2-container--default .select2-selection--single{
padding:6px;
height: 37px;
width: 148px;
font-size: 1.2em;
position: relative;
}
.select2-container--default .select2-selection--single .select2-selection__arrow {
background-image: -khtml-gradient(linear, left top, left bottom, from(#424242), to(#030303));
background-image: -moz-linear-gradient(top, #424242, #030303);
background-image: -ms-linear-gradient(top, #424242, #030303);
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #424242), color-stop(100%, #030303));
background-image: -webkit-linear-gradient(top, #424242, #030303);
background-image: -o-linear-gradient(top, #424242, #030303);
background-image: linear-gradient(#424242, #030303);
width: 40px;
color: #fff;
font-size: 1.3em;
padding: 4px 12px;
height: 27px;
position: absolute;
top: 0px;
right: 0px;
width: 20px;
}
Theoretically, yes. Practice, not. Most kernels (incl. linux) doesn't allow you a second bind()
to an already allocated port. It weren't a really big patch to make this allowed.
Conceptionally, we should differentiate between socket and port. Sockets are bidirectional communication endpoints, i.e. "things" where we can send and receive bytes. It is a conceptional thing, there is no such field in a packet header named "socket".
Port is an identifier which is capable to identify a socket. In case of the TCP, a port is a 16 bit integer, but there are other protocols as well (for example, on unix sockets, a "port" is essentially a string).
The main problem is the following: if an incoming packet arrives, the kernel can identify its socket by its destination port number. It is a most common way, but it is not the only possibility:
Because you are working on an application server, it will be able to do that.
The regular Array structure in Javascript is a Stack (first in, last out) and can also be used as a Queue (first in, first out) depending on the calls you make.
Check this link to see how to make an Array act like a Queue:
You can use str.utf8.count
and str.utf16.count
which, I think, are the best solution
You can not give order by
because order by
does a "full scan" on a table.
The following query is better:
SELECT * FROM table WHERE id = (SELECT MAX(id) FROM table);
Implementation:
// Promisify setTimeout
const pause = (ms, cb, ...args) =>
new Promise((resolve, reject) => {
setTimeout(async () => {
try {
resolve(await cb?.(...args))
} catch (error) {
reject(error)
}
}, ms)
})
Tests:
// Test 1
pause(1000).then(() => console.log('called'))
// Test 2
pause(1000, (a, b, c) => [a, b, c], 1, 2, 3).then(value => console.log(value))
// Test 3
pause(1000, () => {
throw Error('foo')
}).catch(error => console.error(error))
Consider reformatting your file into javascript. Then you can simply load it using good old...
<script src="thefileIwantToLoad.js" defer></script>
After you install Oracle Client components on the remote server, restart SQL Server Agent from the PC Management Console or directly from Sql Server Management Studio. This will allow the service to load correctly the path to the Oracle components. Otherwise your package will work on design time but fail on run time.
Using the inline-block is better because it doesn't force the remaining elements and/or controls to be drawn in a new line.
label {
width:200px;
display: inline-block;
}
You can try the following regular expression:
\r?\n
Code:
String input = "\nab\n\n \n\ncd\nef\n\n\n\n\n";
String[] lines = input.split("\\r?\\n", -1);
int n = 1;
for(String line : lines) {
System.out.printf("\tLine %02d \"%s\"%n", n++, line);
}
Output:
Line 01 ""
Line 02 "ab"
Line 03 ""
Line 04 " "
Line 05 ""
Line 06 "cd"
Line 07 "ef"
Line 08 ""
Line 09 ""
Line 10 ""
Line 11 ""
Line 12 ""
I also had a similar exception when debugging in Eclipse. When I moused-over an object, the pop up box displayed an com.sun.jdi.InvocationException
message. The root cause for me was not the toString()
method of my class, but rather the hashCode()
method. It was causing a NullPointerException
, which caused the com.sun.jdi.InvocationException
to appear during debugging. Once I took care of the null pointer, everything worked as expected.
A div is a block element and by default 100% wide. You should just have to set the textarea width to 100%.
string XMLWriteStringWithoutIllegalCharacters(string UnfilteredString)
{
if (UnfilteredString == null)
return string.Empty;
return XmlConvert.EncodeName(UnfilteredString);
}
string XMLReadStringWithoutIllegalCharacters(string FilteredString)
{
if (UnfilteredString == null)
return string.Empty;
return XmlConvert.DecodeName(UnfilteredString);
}
This simple method replace the invalid characters with the same value but accepted in the XML context.
To write string use XMLWriteStringWithoutIllegalCharacters(string UnfilteredString).
To read string use XMLReadStringWithoutIllegalCharacters(string FilteredString).
$wherecond = "( ( ( username ='" . $username . "' OR status='" . $status . "') AND (id='" . $id . "') ) )";
$this->db->where($wherecond);
If you want to add AND and OR conditions at a time. this will work.
I believe the best way to store Lat/Lng in MySQL is to have a POINT column (2D datatype) with a SPATIAL index.
CREATE TABLE `cities` (
`zip` varchar(8) NOT NULL,
`country` varchar (2) GENERATED ALWAYS AS (SUBSTRING(`zip`, 1, 2)) STORED,
`city` varchar(30) NOT NULL,
`centre` point NOT NULL,
PRIMARY KEY (`zip`),
KEY `country` (`country`),
KEY `city` (`city`),
SPATIAL KEY `centre` (`centre`)
) ENGINE=InnoDB;
INSERT INTO `cities` (`zip`, `city`, `centre`) VALUES
('CZ-10000', 'Prague', POINT(50.0755381, 14.4378005));
Here is the PHP code to check if 'id' parameter exists in the URL or not:
if(isset($_GET['id']))
{
$slide = $_GET['id'] // Getting parameter value inside PHP variable
}
I hope it will help you.
Also, check to make sure you have enough disk space on /var/core
or wherever your core dumps get written. If the partition is almos full or at 100% disk usage then that would be the problem. My core dumps average a few gigs so you should be sure to have at least 5-10 gig available on the partition.
One option would be VistaDB. They allow databases (or even tables) to be password protected (and optionally encrypted).
Actually, only the first one is valid in HTML5
<img src='stackoverflow.png'>
Only the last two are valid in XHTML
<img src='stackoverflow.png'></img>
<img src='stackoverflow.png' />
(Though not stricly required, an alt
attribute _usually_ should also be included).
That said, your HTML5 page will probably display as intended because browsers will rewrite or interpret your html to what it thinks you meant. That may mean it turns a tag, for example, from
<div />
into <div></div>
. Or maybe it just ignores the final slash on <img ... />
.
see 2016: Serve HTML5 as XHTML 5.0 for legacy validation.
see: 2011 discussion and additional links here, though over time some bits may have changed
Partly this is because browsers try very hard to error correct. Also, because there has much confusion about self-closing tags, and void tags. Finally, The spec has changed, or hasn't always been clear, and browsers try to be backwards compatible.
So, while you can probably get away with any of the three options,
only the first adheres to the HTML5 standard, and is guaranteed to pass a HTML5 validator.
A sound strategy might be to:
Here is a list of tags that should not be closed in HTML5:
<br> <hr> <input>
<img> <link> <source>
<col> <area> <base>
<meta> <embed> <param>
<track> <wbr> <keygen> (HTML 5.2 Draft removed)
$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");
When you use PropertyConfigurator.configure(String configFilename), they are the following operation in the log4j library.
Properties props = new Properties();
FileInputStream istream = null;
try {
istream = new FileInputStream(configFileName);
props.load(istream);
istream.close();
}
catch (Exception e) {
...
It fails in reading because it looks for "Log4j.properties" from the current directory where the application is executed.
How about the way that it changes the reading part of the property file as follows, and puts "log4j.properties" on the directory to which the CLASSPATH is set.
ClassLoader loader = Thread.currentThread().getContextClassLoader();
URL url = loader.getResource("log4j.properties");
PropertyConfigurator.configure(url);
Another method of putting "Log4j.properties" in the jar file exists.
jar xvf [YourApplication].jar log4j.properties
If you are creating new array then try this :
$arr = ['key' => 'value'];
And if array is already created then try this :
$arr['key'] = 'value';
Tips of using OS-dependent function to terminate C++ thread:
std::thread::native_handle()
only can get the thread’s valid native handle type before calling join()
or detach()
. After that, native_handle()
returns 0 - pthread_cancel()
will coredump.
To effectively call native thread termination function(e.g. pthread_cancel()
), you need to save the native handle before calling std::thread::join()
or std::thread::detach()
. So that your native terminator always has a valid native handle to use.
More explanations please refer to: http://bo-yang.github.io/2017/11/19/cpp-kill-detached-thread .
CAREFUL: In the command in Lawakush Kurmi's answer (git tag -a v1.0
) the -a
flag is used. This flag tells Git to create an annotated flag. If you don't provide the flag (i.e. git tag v1.0
) then it'll create what's called a lightweight tag.
Annotated tags are recommended, because they include a lot of extra information such as:
Because of this, you should always use annotated tags.
Communicating through processes
Example:
Python: This python code block should return random temperatures.
# sensor.py
import random, time
while True:
time.sleep(random.random() * 5) # wait 0 to 5 seconds
temperature = (random.random() * 20) - 5 # -5 to 15
print(temperature, flush=True, end='')
Javascript (Nodejs): Here we will need to spawn a new child process to run our python code and then get the printed output.
// temperature-listener.js
const { spawn } = require('child_process');
const temperatures = []; // Store readings
const sensor = spawn('python', ['sensor.py']);
sensor.stdout.on('data', function(data) {
// convert Buffer object to Float
temperatures.push(parseFloat(data));
console.log(temperatures);
});
You can exchange this local variable for a global, it would be easier.
DROP PROCEDURE IF EXISTS ABC;
DELIMITER $$
CREATE PROCEDURE ABC()
BEGIN
SET @a = 0;
simple_loop: LOOP
SET @a=@a+1;
select @a;
IF @a=5 THEN
LEAVE simple_loop;
END IF;
END LOOP simple_loop;
END $$
In Java, a String is a reference to heap-allocated storage. Returning "ans" only returns the reference so there is no need for stack-allocated storage. In fact, there is no way in Java to allocate objects in stack storage.
I would change to this, though. You don't need "ans" at all.
return String.format("%d:%d", mins, secs);
Another solution: change margins. Depending on the siblings of the button, display
should be modified.
button {
display: block;
margin-left: auto;
margin-right: 0;
}
It's now possible in modern browsers to position an element fixed relative to its container. An element that has a transform property acts as the viewport for any of its fixed position child elements.
Or as the CSS Transforms Module puts it:
For elements whose layout is governed by the CSS box model, any value other than none for the transform property also causes the element to establish a containing block for all descendants. Its padding box will be used to layout for all of its absolute-position descendants, fixed-position descendants, and descendant fixed background attachments.
.context {_x000D_
width: 300px;_x000D_
height: 250px;_x000D_
margin: 100px;_x000D_
transform: translateZ(0);_x000D_
}_x000D_
.viewport {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
border: 1px solid black;_x000D_
overflow: scroll;_x000D_
}_x000D_
.centered {_x000D_
position: fixed;_x000D_
left: 50%;_x000D_
bottom: 15px;_x000D_
transform: translateX(-50%);_x000D_
}
_x000D_
<div class="context">_x000D_
<div class="viewport">_x000D_
<div class="canvas">_x000D_
_x000D_
<table>_x000D_
<tr>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
<button class="centered">OK</button>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
The AHK script is a great idea. Just for those interested I needed to change it a little bit to work for me:
SetTitleMatchMode,2 ;;; allows for a partial search
#IfWinActive, .py ;;; scope limiter to only python files
:b*:print ::print(){Left} ;;; I forget what b* does
#IfWinActive ;;; remove the scope limitation
You can call a function from within a class with:
A().method1()
Here's how I solved this problem.
Done :)
I experienced that NodeJS is hashing the UTF-8 representation of the string. Other languages (like Python, PHP or PERL...) are hashing the byte string.
We can add binary argument to use the byte string.
const crypto = require("crypto");
function sha1(data) {
return crypto.createHash("sha1").update(data, "binary").digest("hex");
}
sha1("Your text ;)");
You can try with : "\xac", "\xd1", "\xb9", "\xe2", "\xbb", "\x93", etc...
sha1("\xac") //39527c59247a39d18ad48b9947ea738396a3bc47
sha1 = crypto.createHash("sha1").update("\xac", "binary").digest("hex") //39527c59247a39d18ad48b9947ea738396a3bc47
//without:
sha1 = crypto.createHash("sha1").update("\xac").digest("hex") //f50eb35d94f1d75480496e54f4b4a472a9148752
You can use getComputedStyle()
.
var element = document.getElementById('image_1'),
style = window.getComputedStyle(element),
top = style.getPropertyValue('top');
When I was using the below command, I too was getting the same error:
node .function-hello.js
I changed my command to below command, it worked fine:
node .\function-hello.js
>>> s = "the dude is a cool dude"
>>> s.find('dude')
4
Just loop over the elements in your array.
Ex:
for(int i=0; numOfElements > i; i++)
{
outputWriter.write(array[i]);
}
//finish up down here
This works for me, found in comments:
sudo chown -R $USER /data/db
We can set font as per our requirement like,
label.font = UIFont(name: "Avenir-Light", size: 15.0)
label.font = UIFont.boldSystemFontOfSize(15)
label.font = UIFont.italicSystemFontOfSize(15)
label.font = UIFont.systemFontOfSize(17)
You can use target
attribute to send form with redirect from iframe.
Your form open tag would be something like this:
method="post" action="http://some.url.com/form_action" target="_top"
If you're on OpenWrt or using some old version of wget which doesn't gives you -i
option:
#!/bin/bash
input="text_file.txt"
while IFS= read -r line
do
wget $line
done < "$input"
Furthermore, if you don't have wget
, you can use curl
or whatever you use for downloading individual files.
If you want to start with a file you can do this
[xml]$cn = Get-Content config.xml
$cn.xml.Section.BEName
Try:
if (typeof($("#myButton").click) != "function")
{
$("#myButton").click(onButtonClicked);
}
As others also said, the += operator is a shortcut. An example:
var = 1;
var = var + 1;
#var = 2
It could also be written like so:
var = 1;
var += 1;
#var = 2
So instead of writing the first example, you can just write the second one, which would work just fine.
Try this example:
exec DBMS_LOCK.sleep(5);
This is the whole script:
SELECT TO_CHAR (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "Start Date / Time" FROM DUAL;
exec DBMS_LOCK.sleep(5);
SELECT TO_CHAR (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "End Date / Time" FROM DUAL;
To determine if the array is sparse, it may help to get a proportion of nan values
np.isnan(ndarr).sum() / ndarr.size
If that proportion exceeds a threshold, then use a sparse array, e.g. - https://sparse.pydata.org/en/latest/
what is the way to retrieve a Date object so that its always in GMT?
Instant.now()
You are using troublesome confusing old date-time classes that are now supplanted by the java.time classes.
Instant
= UTCThe Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now() ; // Current moment in UTC.
To exchange this data as text, use the standard ISO 8601 formats exclusively. These formats are sensibly designed to be unambiguous, easy to process by machine, and easy to read across many cultures by people.
The java.time classes use the standard formats by default when parsing and generating strings.
String output = instant.toString() ;
2017-01-23T12:34:56.123456789Z
If you want to see that same moment as presented in the wall-clock time of a particular region, apply a ZoneId
to get a ZonedDateTime
.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Asia/Singapore" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same simultaneous moment, same point on the timeline.
See this code live at IdeOne.com.
Notice the eight hour difference, as the time zone of Asia/Singapore
currently has an offset-from-UTC of +08:00. Same moment, different wall-clock time.
instant.toString(): 2017-01-23T12:34:56.123456789Z
zdt.toString(): 2017-01-23T20:34:56.123456789+08:00[Asia/Singapore]
Avoid the legacy java.util.Date
class. But if you must, you can convert. Look to new methods added to the old classes.
java.util.Date date = Date.from( instant ) ;
…going the other way…
Instant instant = myJavaUtilDate.toInstant() ;
For date-only, use LocalDate
.
LocalDate ld = zdt.toLocalDate() ;
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
See the documentation on MDN about expressions and operators and statements.
this
keyword:var x = function()
vs. function x()
— Function declaration syntax(function(){
…})()
— IIFE (Immediately Invoked Function Expression)(function(){…})();
work but function(){…}();
doesn't?(function(){…})();
vs (function(){…}());
!function(){…}();
- What does the exclamation mark do before the function?+function(){…}();
- JavaScript plus sign in front of function expression!
vs leading semicolon(function(window, undefined){…}(window));
someFunction()()
— Functions which return other functions=>
— Equal sign, greater than: arrow function expression syntax|>
— Pipe, greater than: Pipeline operatorfunction*
, yield
, yield*
— Star after function
or yield
: generator functions[]
, Array()
— Square brackets: array notationIf the square brackets appear on the left side of an assignment ([a] = ...
), or inside a function's parameters, it's a destructuring assignment.
{key: value}
— Curly brackets: object literal syntax (not to be confused with blocks)If the curly brackets appear on the left side of an assignment ({ a } = ...
) or inside a function's parameters, it's a destructuring assignment.
`
…${
…}
…`
— Backticks, dollar sign with curly brackets: template literals`…${…}…`
code from the node docs mean?/
…/
— Slashes: regular expression literals$
— Dollar sign in regex replace patterns: $$
, $&
, $`
, $'
, $n
()
— Parentheses: grouping operatorobj.prop
, obj[prop]
, obj["prop"]
— Square brackets or dot: property accessors?.
, ?.[]
, ?.()
— Question mark, dot: optional chaining operator::
— Double colon: bind operatornew
operator...iter
— Three dots: spread syntax; rest parameters(...args) => {}
— What is the meaning of “…args” (three dots) in a function definition?[...iter]
— javascript es6 array feature […data, 0] “spread operator”{...props}
— Javascript Property with three dots (…)++
, --
— Double plus or minus: pre- / post-increment / -decrement operatorsdelete
operatorvoid
operator+
, -
— Plus and minus: addition or concatenation, and subtraction operators; unary sign operators|
, &
, ^
, ~
— Single pipe, ampersand, circumflex, tilde: bitwise OR, AND, XOR, & NOT operators~1
equal -2
?%
— Percent sign: remainder operator&&
, ||
, !
— Double ampersand, double pipe, exclamation point: logical operators??
— Double question mark: nullish-coalescing operator**
— Double star: power operator (exponentiation)x ** 2
is equivalent to Math.pow(x, 2)
==
, ===
— Equal signs: equality operators!=
, !==
— Exclamation point and equal signs: inequality operators<<
, >>
, >>>
— Two or three angle brackets: bit shift operators?
…:
… — Question mark and colon: conditional (ternary) operator=
— Equal sign: assignment operator%=
— Percent equals: remainder assignment+=
— Plus equals: addition assignment operator&&=
, ||=
, ??=
— Double ampersand, pipe, or question mark, followed by equal sign: logical assignments||=
(or equals) in JavaScript?,
— Comma operator{
…}
— Curly brackets: blocks (not to be confused with object literal syntax)var
, let
, const
— Declaring variableslabel:
— Colon: labels#
— Hash (number sign): Private methods or private fieldsAlso, it's probably useful to note that if you have a multiple dimensional Array, you can get the respective dimension just by appending a '[0]' to the array you are querying until you arrive at the appropriate axis/tuple/dimension.
This is probably better explained with the following code:
public class Test {
public static void main(String[] args){
String[][] moo = new String[5][12];
System.out.println(moo.length); //Prints the size of the First Dimension in the array
System.out.println(moo[0].length);//Prints the size of the Second Dimension in the array
}
}
Which produces the output:
5
12
update
update
ngComponentOutlet
was added to 4.0.0-beta.3
update
There is a NgComponentOutlet
work in progress that does something similar https://github.com/angular/angular/pull/11235
RC.7
// Helper component to add dynamic components
@Component({
selector: 'dcl-wrapper',
template: `<div #target></div>`
})
export class DclWrapper {
@ViewChild('target', {read: ViewContainerRef}) target: ViewContainerRef;
@Input() type: Type<Component>;
cmpRef: ComponentRef<Component>;
private isViewInitialized:boolean = false;
constructor(private componentFactoryResolver: ComponentFactoryResolver, private compiler: Compiler) {}
updateComponent() {
if(!this.isViewInitialized) {
return;
}
if(this.cmpRef) {
// when the `type` input changes we destroy a previously
// created component before creating the new one
this.cmpRef.destroy();
}
let factory = this.componentFactoryResolver.resolveComponentFactory(this.type);
this.cmpRef = this.target.createComponent(factory)
// to access the created instance use
// this.compRef.instance.someProperty = 'someValue';
// this.compRef.instance.someOutput.subscribe(val => doSomething());
}
ngOnChanges() {
this.updateComponent();
}
ngAfterViewInit() {
this.isViewInitialized = true;
this.updateComponent();
}
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
}
Usage example
// Use dcl-wrapper component
@Component({
selector: 'my-tabs',
template: `
<h2>Tabs</h2>
<div *ngFor="let tab of tabs">
<dcl-wrapper [type]="tab"></dcl-wrapper>
</div>
`
})
export class Tabs {
@Input() tabs;
}
@Component({
selector: 'my-app',
template: `
<h2>Hello {{name}}</h2>
<my-tabs [tabs]="types"></my-tabs>
`
})
export class App {
// The list of components to create tabs from
types = [C3, C1, C2, C3, C3, C1, C1];
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, DclWrapper, Tabs, C1, C2, C3],
entryComponents: [C1, C2, C3],
bootstrap: [ App ]
})
export class AppModule {}
See also angular.io DYNAMIC COMPONENT LOADER
older versions xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
This changed again in Angular2 RC.5
I will update the example below but it's the last day before vacation.
This Plunker example demonstrates how to dynamically create components in RC.5
Update - use ViewContainerRef.createComponent()
Because DynamicComponentLoader
is deprecated, the approach needs to be update again.
@Component({
selector: 'dcl-wrapper',
template: `<div #target></div>`
})
export class DclWrapper {
@ViewChild('target', {read: ViewContainerRef}) target;
@Input() type;
cmpRef:ComponentRef;
private isViewInitialized:boolean = false;
constructor(private resolver: ComponentResolver) {}
updateComponent() {
if(!this.isViewInitialized) {
return;
}
if(this.cmpRef) {
this.cmpRef.destroy();
}
this.resolver.resolveComponent(this.type).then((factory:ComponentFactory<any>) => {
this.cmpRef = this.target.createComponent(factory)
// to access the created instance use
// this.compRef.instance.someProperty = 'someValue';
// this.compRef.instance.someOutput.subscribe(val => doSomething());
});
}
ngOnChanges() {
this.updateComponent();
}
ngAfterViewInit() {
this.isViewInitialized = true;
this.updateComponent();
}
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
}
Plunker example RC.4
Plunker example beta.17
Update - use loadNextToLocation
export class DclWrapper {
@ViewChild('target', {read: ViewContainerRef}) target;
@Input() type;
cmpRef:ComponentRef;
private isViewInitialized:boolean = false;
constructor(private dcl:DynamicComponentLoader) {}
updateComponent() {
// should be executed every time `type` changes but not before `ngAfterViewInit()` was called
// to have `target` initialized
if(!this.isViewInitialized) {
return;
}
if(this.cmpRef) {
this.cmpRef.destroy();
}
this.dcl.loadNextToLocation(this.type, this.target).then((cmpRef) => {
this.cmpRef = cmpRef;
});
}
ngOnChanges() {
this.updateComponent();
}
ngAfterViewInit() {
this.isViewInitialized = true;
this.updateComponent();
}
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
}
original
Not entirely sure from your question what your requirements are but I think this should do what you want.
The Tabs
component gets an array of types passed and it creates "tabs" for each item in the array.
@Component({
selector: 'dcl-wrapper',
template: `<div #target></div>`
})
export class DclWrapper {
constructor(private elRef:ElementRef, private dcl:DynamicComponentLoader) {}
@Input() type;
ngOnChanges() {
if(this.cmpRef) {
this.cmpRef.dispose();
}
this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) => {
this.cmpRef = cmpRef;
});
}
}
@Component({
selector: 'c1',
template: `<h2>c1</h2>`
})
export class C1 {
}
@Component({
selector: 'c2',
template: `<h2>c2</h2>`
})
export class C2 {
}
@Component({
selector: 'c3',
template: `<h2>c3</h2>`
})
export class C3 {
}
@Component({
selector: 'my-tabs',
directives: [DclWrapper],
template: `
<h2>Tabs</h2>
<div *ngFor="let tab of tabs">
<dcl-wrapper [type]="tab"></dcl-wrapper>
</div>
`
})
export class Tabs {
@Input() tabs;
}
@Component({
selector: 'my-app',
directives: [Tabs]
template: `
<h2>Hello {{name}}</h2>
<my-tabs [tabs]="types"></my-tabs>
`
})
export class App {
types = [C3, C1, C2, C3, C3, C1, C1];
}
Plunker example beta.15 (not based on your Plunker)
There is also a way to pass data along that can be passed to the dynamically created component like (someData
would need to be passed like type
)
this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) => {
cmpRef.instance.someProperty = someData;
this.cmpRef = cmpRef;
});
There is also some support to use dependency injection with shared services.
For more details see https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html
you could use something like
<select ng-model="myselect">
<option ng-repeat="o in options" ng-selected="{{o==myselect}}" value="{{o}}">
{{o}}
</option>
</select>
using ng-selected you preselect the option in case myselect was prefilled.
I prefer this method over ng-options anyway, as ng-options only works with arrays. ng-repeat also works with json-like objects.
In my opinion, most answers are trying to solve the problem asked on your question, but I don't think that's the best approach for your scenario.
How would I go about preventing the page from refreshing when pressing the send button without any data in the fields?
A .preventDefault()
does indeed not refresh the page. But I think that a simple require
on the fields you want populated with data, would solve your problem.
<form id="prospects_form" method="post">
<input id="form_name" tabindex="1" class="boxsize" type="text" name="name" placeholder="Full name*" maxlength="80" value="" required/>
<input id="form_email" tabindex="2" class="boxsize" type="text" name="email" placeholder="Email*" maxlength="100" value="" required/>
<input id="form_subject" class="boxsize" type="text" name="subject" placeholder="Subject*" maxlength="50" value="FORM: Row for OUBC" required/>
<textarea id="form_message" class="boxsize" name="message" placeholder="Message*" tabindex="3" rows="6" cols="5" maxlength="500"></textarea>
</form>
Notice the require
tag added at the end of each input
. The result will be the same: not refreshing the page without any data in the fields.
var files = Directory.GetFiles(@"E:\ftproot\sales");
First I recommand you can try use print and observe the action:
for i in range(0, 5, 1):
print i
the result:
0
1
2
3
4
You can understand the function principle.
In fact, range
scan range is from 0
to 5-1
.
It equals 0 <= i < 5
When you really understand for-loop in python, I think its time we get back to business. Let's focus your problem.
You want to use a DECREMENT for-loop in python. I suggest a for-loop tutorial for example.
for i in range(5, 0, -1):
print i
the result:
5
4
3
2
1
Thus it can be seen, it equals 5 >= i > 0
You want to implement your java code in python:
for (int index = last-1; index >= posn; index--)
It should code this:
for i in range(last-1, posn-1, -1)
And this is a Kotlin version:
editText.setOnEditorActionListener { v, actionId, event ->
if(actionId == EditorInfo.IME_ACTION_DONE){
//Put your action there
true
} else {
false
}
}
I always use the time-stamp - so its not possible, that the file exists already:
import os
import shutil
import datetime
now = str(datetime.datetime.now())[:19]
now = now.replace(":","_")
src_dir="C:\\Users\\Asus\\Desktop\\Versand Verwaltung\\Versand.xlsx"
dst_dir="C:\\Users\\Asus\\Desktop\\Versand Verwaltung\\Versand_"+str(now)+".xlsx"
shutil.copy(src_dir,dst_dir)
The concept for all these providers is much simpler than it initially appears. If you dissect a provider you and pull out the different parts it becomes very clear.
To put it simply each one of these providers is a specialized version of the other, in this order: provider
> factory
> value
/ constant
/ service
.
So long the provider does what you can you can use the provider further down the chain which would result in writing less code. If it doesn't accomplish what you want you can go up the chain and you'll just have to write more code.
This image illustrates what I mean, in this image you will see the code for a provider, with the portions highlighted showing you which portions of the provider could be used to create a factory, value, etc instead.
(source: simplygoodcode.com)
For more details and examples from the blog post where I got the image from go to: http://www.simplygoodcode.com/2015/11/the-difference-between-service-provider-and-factory-in-angularjs/
Sure there is! For instance:
<xsl:if test="not(contains($hhref, '1234'))">
<li>
<a href="{$hhref}" title="{$pdate}">
<xsl:value-of select="title"/>
</a>
</li>
</xsl:if>
The syntax is: contains(stringToSearchWithin, stringToSearchFor)
foreach (glob("classes/*.php") as $filename)
{
include $filename;
}
You usually get this error if your tables use the InnoDB engine. In that case you would have to drop the foreign key, and then do the alter table and drop the column.
But the tricky part is that you can't drop the foreign key using the column name, but instead you would have to find the name used to index it. To find that, issue the following select:
SHOW CREATE TABLE region;
This should show you the name of the index, something like this:
CONSTRAINT
region_ibfk_1
FOREIGN KEY (country_id
) REFERENCEScountry
(id
) ON DELETE NO ACTION ON UPDATE NO ACTION
Now simply issue an:
alter table region drop foreign key
region_ibfk_1
;
And finally an:
alter table region drop column country_id;
And you are good to go!
I know that this question is about 6+ years old, but the answer by @Kyle doesn't work.
Using this
setSize(width - (getInsets().left + getInsets().right), height - (getInsets().top + getInsets().bottom));
But this always work in any size:
setSize(width + 14, height + 7);
If you don't want the border to border, and only want the white area, here:
setSize(width + 16, height + 39);
Also this only works on Windows 10, for MacOS users, use @ben's answer.
Regex ids = new Regex(@"\w*Id\b", RegexOptions.None);
\b
means "word break" and \w
means any word character. So \w*Id\b
means "{stuff}Id". By not including RegexOptions.IgnoreCase
, it will be case sensitive.
With Go 1.5 they seem to have improved the cross compilation process, meaning it is built in now. No ./make.bash
-ing or brew
-ing required. The process is described here but for the TLDR-ers (like me) out there: you just set the GOOS
and the GOARCH
environment variables and run the go build.
For the even lazier copy-pasters (like me) out there, do something like this if you're on a *nix system:
env GOOS=linux GOARCH=arm go build -v github.com/path/to/your/app
You even learned the env
trick, which let you set environment variables for that command only, completely free of charge.
Use stmt.setDate(1, new java.sql.Date(cal.getTimeInMillis()))
Best way is to use NuGet package manager.
Just update the below MVC package and it should work.
I think this solution may not be efficient but it serves the purpose and adds flexibility with the border width.
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="40dp"
android:layout_gravity="center"
card_view:cardBackgroundColor="@color/some_color"
card_view:cardCornerRadius="20dp"
card_view:contentPadding="5dp"> <!-- Change it to customize the border width -->
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
card_view:cardCornerRadius="20dp"
card_view:contentPadding="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Add your UI elements -->
</RelativeLayout>
</android.support.v7.widget.CardView>
</android.support.v7.widget.CardView>
Withough testing, I'd try:
for c in session.query(Stuff).all():
c.foo = c.foo+1
session.commit()
(IIRC, commit() works without flush()).
I've found that at times doing a large query and then iterating in python can be up to 2 orders of magnitude faster than lots of queries. I assume that iterating over the query object is less efficient than iterating over a list generated by the all() method of the query object.
[Please note comment below - this did not speed things up at all].
There is also another convention, used by many open source projects including Spring.
interface User {
}
class DefaultUser implements User {
}
class AnotherClassOfUser implements User {
}
I personally do not like the "I" prefix for the simple reason that its an optional convention. So if I adopt this does IIOPConnection mean an interface for IOPConnection? What if the class does not have the "I" prefix, do I then know its not an interface..the answer here is no, because conventions are not always followed, and policing them will create more work that the convention itself saves.
Yes, you should think of defining both your functions in a Class, and making word a member. This is cleaner :
class Spam:
def oneFunction(self,lists):
category=random.choice(list(lists.keys()))
self.word=random.choice(lists[category])
def anotherFunction(self):
for letter in self.word:
print("_", end=" ")
Once you make a Class you have to Instantiate it to an Object and access the member functions
s = Spam()
s.oneFunction(lists)
s.anotherFunction()
Another approach would be to make oneFunction
return the word so that you can use oneFunction
instead of word
in anotherFunction
>>> def oneFunction(lists):
category=random.choice(list(lists.keys()))
return random.choice(lists[category])
>>> def anotherFunction():
for letter in oneFunction(lists):
print("_", end=" ")
And finally, you can also make anotherFunction
, accept word
as a parameter which you can pass from the result of calling oneFunction
>>> def anotherFunction(words):
for letter in words:
print("_",end=" ")
>>> anotherFunction(oneFunction(lists))
You can specify USER
in the Dockerfile. All subsequent actions will be performed using that account. You can specify USER
one line before the CMD
or ENTRYPOINT
if you only want to use that user when launching a container (and not when building the image). When you start a container from the resulting image, you will attach as the specified user.
you can create a shallow clone to only get the last few revisions:
git clone --depth 1 git://url
then either simply delete the .git directory or use git archive
to export your tree.
You should just set all constraints for TOP, BOTTOM and HEIGHT for each object on cell view/views and remove exists middle Y position if have. Because where you didn't this, puts artifacts on another views.
It reverts the said commit, that is, adds the commit opposite to it. If you want to checkout an earlier revision, you do:
git checkout 56e05fced214c44a37759efa2dfc25a65d8ae98d
Try to use .card-listing:hover::after
hover
and after
using ::
it wil work
You could use a semaphore.
While the condition is not met, another thread acquires the semaphore.
Your thread would try to acquire it with acquireUninterruptibly()
or tryAcquire(int permits, long timeout, TimeUnit unit)
and would be blocked.
When the condition is met, the semaphore is also released and your thread would acquire it.
You could also try using a SynchronousQueue
or a CountDownLatch
.
Adding both android:layout_centerInParent
and android:layout_centerVertical
work for me to center ImageView
both vertical and horizontal:
<ImageView
..
android:layout_centerInParent="true"
android:layout_centerVertical="true"
/>
My guess is that $_.Name does not exist.
If I were you, I'd bring the script into the ISE and run it line for line till you get there then take a look at the value of $_
If there is a good chance that the list will contain as much elements as it contains when clearing it, and if you're not in need for free memory, clearing the list is a better option. But my guess is that it probably doesn't matter. Don't try to optimize until you have detected a performance problem, and identified where it comes from.
Right click on data which you want to store
You can simply do the following:
[HttpGet]
public async Task<IActionResult> GetAsync()
{
string queryString = Request.QueryString.ToString().ToLower();
return Ok(await DoMagic.GetAuthorizationTokenAsync(new Uri($"https://someurl.com/token-endpoint{queryString}")));
}
If you need to access each element separately, simply refer to Request.Query
.
Prototype's Element library is one of the most powerful query libraries in terms of the methods. I recommend you to check out the API.
A few hints:
Checking visibility can be a pain, but you can use the Element.getStyle()
method and Element.visible()
methods combined into a custom function. With getStyle()
you can check the actual computed style.
I don't know exactly what you mean by "underneath" :) If you meant by it has a specific ancestor, for example, a wrapper div, you can use Element.up(cssRule)
:
var child = $("myparagraph");
if(!child.up("mywrapper")){
// I lost my mom!
}
else {
// I found my mom!
}
If you want to check the siblings of the child element you can do that too:
var child = $("myparagraph");
if(!child.previous("mywrapper")){
// I lost my bro!
}
else {
// I found my bro!
}
Again, Element lib can help you if I understand correctly what you mean :) You can check the actual dimensions of the viewport and the offset of your element so you can calculate if your element is "off screen".
Good luck!
I pasted a test case for prototypejs at http://gist.github.com/117125. It seems in your case we simply cannot trust in getStyle()
at all. For maximizing the reliability of the isMyElementReallyVisible function you should combine the following:
document.baseURI
returns base URL also respecting the value in <base/>
tag
https://developer.mozilla.org/en-US/docs/Web/API/Node/baseURI
I'd like to add to OJ's kind clarifications.
Virtual inheritance doesn't come without a price. Like with all things virtual, you get a performance hit. There is a way around this performance hit that is possibly less elegant.
Instead of breaking the diamond by deriving virtually, you can add another layer to the diamond, to get something like this:
B
/ \
D11 D12
| |
D21 D22
\ /
DD
None of the classes inherit virtually, all inherit publicly. Classes D21 and D22 will then hide virtual function f() which is ambiguous for DD, perhaps by declaring the function private. They'd each define a wrapper function, f1() and f2() respectively, each calling class-local (private) f(), thus resolving conflicts. Class DD calls f1() if it wants D11::f() and f2() if it wants D12::f(). If you define the wrappers inline you'll probably get about zero overhead.
Of course, if you can change D11 and D12 then you can do the same trick inside these classes, but often that is not the case.
Yes, underscores may be used anywhere in an identifier. I believe the rules are: any of a-z, A-Z, _ in the first character and those +0-9 for the following characters.
Underscore prefixes are common in C code -- a single underscore means "private", and double underscores are usually reserved for use by the compiler.
pushd
is a bash
enhancement to the POSIX-specified Bourne Shell. pushd
cannot be easily implemented as a command, because the current working directory is a feature of a process that cannot be changed by child processes. (A hypothetical pushd
command might do the chdir(2)
call and then start a new shell, but ... it wouldn't be very usable.) pushd
is a shell builtin, just like cd
.
So, either change your script to start with #!/bin/bash
or store the current working directory in a variable, do your work, then change back. Depends if you want a shell script that works on very reduced systems (say, a Debian build server) or if you're fine always requiring bash
.
The best way in javascript to do so is
function getBinaryValue(num){
return num.toString(2);
}
function checkOnces(binaryValue){
return binaryValue.toString().replace(/0/g, "").length;
}
where binaryValue is the binary String eg: 1100
Default-Values are only considered for parameters NOT given to the function.
So given a function
procedure foo( bar1 IN number DEFAULT 3,
bar2 IN number DEFAULT 5,
bar3 IN number DEFAULT 8 );
if you call this procedure with no arguments then it will behave as if called with
foo( bar1 => 3,
bar2 => 5,
bar3 => 8 );
but 'NULL' is still a parameter.
foo( 4,
bar3 => NULL );
This will then act like
foo( bar1 => 4,
bar2 => 5,
bar3 => Null );
( oracle allows you to either give the parameter in order they are specified in the procedure, specified by name, or first in order and then by name )
one way to treat NULL the same as a default value would be to default the value to NULL
procedure foo( bar1 IN number DEFAULT NULL,
bar2 IN number DEFAULT NULL,
bar3 IN number DEFAULT NULL );
and using a variable with the desired value then
procedure foo( bar1 IN number DEFAULT NULL,
bar2 IN number DEFAULT NULL,
bar3 IN number DEFAULT NULL )
AS
v_bar1 number := NVL( bar1, 3);
v_bar2 number := NVL( bar2, 5);
v_bar3 number := NVL( bar3, 8);
That would work depending on what client.get does when passed undefined as its first parameter.
Something like this would be safer:
app.get('/:key?', function(req, res, next) {
var key = req.params.key;
if (!key) {
next();
return;
}
client.get(key, function(err, reply) {
if(client.get(reply)) {
res.redirect(reply);
}
else {
res.render('index', {
link: null
});
}
});
});
There's no problem in calling next() inside the callback.
According to this, handlers are invoked in the order that they are added, so as long as your next route is app.get('/', ...) it will be called if there is no key.
Install the packages:
sudo apt-get install libaio1 libaio-dev
or
sudo yum install libaio
This becomes simpler by using git-filter-repo.
In order to move project2/sub/dir
to project1/sub/dir
:
# Create a new repo containing only the subdirectory:
git clone project2 project2_subdir
cd project2_subdir
git filter-repo --force --path sub/dir
# Merge the new repo:
cd ../project1
git remote add project2_subdir ../project2_subdir/
git merge remotes/project2_subdir/master --allow-unrelated-histories
git remote remove project2_subdir
To install the tool simply: pip3 install git-filter-repo
(more details and options in README)
# Before: (root)
.
|-- project1
| `-- 3
`-- project2
|-- 1
`-- sub
`-- dir
`-- 2
# After: (project1)
.
+-- 3
+-- sub
+-- dir
+-- 2
I will give you steps to writing and compiling code. Use this example:
public class Paycheck {
public static void main(String args[]) {
double amountInAccount;
amountInAccount = 128.57;
System.out.print("You earned $");
System.out.print(amountInAccount);
System.out.println(" at work today.");
}
}
Paycheck.java
cd Desktop
javac Paycheck.java
java Paycheck
Well, actually I inherited a project some years ago from a colleague who had decided to mix VB and C# webforms within the same project. That worked but is far from fun to maintain.
I decided that new code should be C# classes and to get them to work I had to add a subnode to the compilation part of web.config
<codeSubDirectories>
<add directoryName="VB"/>
<add directoryName="CS"/>
</codeSubDirectories>
The all VB code goes into a subfolder in the App_Code called VB and the C# code into the CS subfolder. This will produce two .dll files. It works, but code is compiled in the same order as listed in "codeSubDirectories" and therefore i.e Interfaces should be in the VB folder if used in both C# and VB.
I have both a reference to a VB and a C# compiler in
<system.codedom>
<compilers>
The project is currently updated to framework 3.5 and it still works (but still no fun to maintain..)
As "window" object is not present in nodejs environment, we could use the following lines of code :
let base64Url = token.split('.')[1]; // token you get
let base64 = base64Url.replace('-', '+').replace('_', '/');
let decodedData = JSON.parse(Buffer.from(base64, 'base64').toString('binary'));
It's working for me perfectly. Hope it helps.
In v.2.x.x , we can use align
and justify
. We have below options for setup the horizontal and vertical alignment.
PROPS align
: 'start','center','end','baseline','stretch'
PRPS justify
: 'start','center','end','space-around','space-between'
<v-container fill-height fluid>
<v-row align="center"
justify="center">
<v-col></v-col>
</v-row>
</v-container>
For more details please refer this vuetify grid-system and you could check here with working codepen demo.
You could use align-center
for layout
and fill-height
for container.
Demo with v1.x.x
new Vue({
el: '#app'
})
_x000D_
.bg{
background: gray;
color: #fff;
font-size: 18px;
}
_x000D_
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.js"></script>
<div id="app">
<v-app>
<v-container bg fill-height grid-list-md text-xs-center>
<v-layout row wrap align-center>
<v-flex>
Hello I am center to vertically using "align-center".
</v-flex>
</v-layout>
</v-container>
</v-app>
</div>
_x000D_
You could fill the dependend cell (D2) by a User Defined Function (VBA Macro Function) that takes the value of the C2-Cell as input parameter, returning the current date as ouput.
Having C2 as input parameter for the UDF in D2 tells Excel that it needs to reevaluate D2 everytime C2 changes (that is if auto-calculation of formulas is turned on for the workbook).
EDIT:
Here is some code:
For the UDF:
Public Function UDF_Date(ByVal data) As Date
UDF_Date = Now()
End Function
As Formula in D2:
=UDF_Date(C2)
You will have to give the D2-Cell a Date-Time Format, or it will show a numeric representation of the date-value.
And you can expand the formula over the desired range by draging it if you keep the C2 reference in the D2-formula relative.
Note: This still might not be the ideal solution because every time Excel recalculates the workbook the date in D2 will be reset to the current value. To make D2 only reflect the last time C2 was changed there would have to be some kind of tracking of the past value(s) of C2. This could for example be implemented in the UDF by providing also the address alonside the value of the input parameter, storing the input parameters in a hidden sheet, and comparing them with the previous values everytime the UDF gets called.
Addendum:
Here is a sample implementation of an UDF that tracks the changes of the cell values and returns the date-time when the last changes was detected. When using it, please be aware that:
The usage of the UDF is the same as described above.
The UDF works only for single cell input ranges.
The cell values are tracked by storing the last value of cell and the date-time when the change was detected in the document properties of the workbook. If the formula is used over large datasets the size of the file might increase considerably as for every cell that is tracked by the formula the storage requirements increase (last value of cell + date of last change.) Also, maybe Excel is not capable of handling very large amounts of document properties and the code might brake at a certain point.
If the name of a worksheet is changed all the tracking information of the therein contained cells is lost.
The code might brake for cell-values for which conversion to string is non-deterministic.
The code below is not tested and should be regarded only as proof of concept. Use it at your own risk.
Public Function UDF_Date(ByVal inData As Range) As Date
Dim wb As Workbook
Dim dProps As DocumentProperties
Dim pValue As DocumentProperty
Dim pDate As DocumentProperty
Dim sName As String
Dim sNameDate As String
Dim bDate As Boolean
Dim bValue As Boolean
Dim bChanged As Boolean
bDate = True
bValue = True
bChanged = False
Dim sVal As String
Dim dDate As Date
sName = inData.Address & "_" & inData.Worksheet.Name
sNameDate = sName & "_dat"
sVal = CStr(inData.Value)
dDate = Now()
Set wb = inData.Worksheet.Parent
Set dProps = wb.CustomDocumentProperties
On Error Resume Next
Set pValue = dProps.Item(sName)
If Err.Number <> 0 Then
bValue = False
Err.Clear
End If
On Error GoTo 0
If Not bValue Then
bChanged = True
Set pValue = dProps.Add(sName, False, msoPropertyTypeString, sVal)
Else
bChanged = pValue.Value <> sVal
If bChanged Then
pValue.Value = sVal
End If
End If
On Error Resume Next
Set pDate = dProps.Item(sNameDate)
If Err.Number <> 0 Then
bDate = False
Err.Clear
End If
On Error GoTo 0
If Not bDate Then
Set pDate = dProps.Add(sNameDate, False, msoPropertyTypeDate, dDate)
End If
If bChanged Then
pDate.Value = dDate
Else
dDate = pDate.Value
End If
UDF_Date = dDate
End Function
Make the insertion of the date conditional upon the range.
This has an advantage of not changing the dates unless the content of the cell is changed, and it is in the range C2:C2, even if the sheet is closed and saved, it doesn't recalculate unless the adjacent cell changes.
Adapted from this tip and @Paul S answer
Private Sub Worksheet_Change(ByVal Target As Range)
Dim R1 As Range
Dim R2 As Range
Dim InRange As Boolean
Set R1 = Range(Target.Address)
Set R2 = Range("C2:C20")
Set InterSectRange = Application.Intersect(R1, R2)
InRange = Not InterSectRange Is Nothing
Set InterSectRange = Nothing
If InRange = True Then
R1.Offset(0, 1).Value = Now()
End If
Set R1 = Nothing
Set R2 = Nothing
End Sub
Initialize empty frame with column names
import pandas as pd
col_names = ['A', 'B', 'C']
my_df = pd.DataFrame(columns = col_names)
my_df
Add a new record to a frame
my_df.loc[len(my_df)] = [2, 4, 5]
You also might want to pass a dictionary:
my_dic = {'A':2, 'B':4, 'C':5}
my_df.loc[len(my_df)] = my_dic
Append another frame to your existing frame
col_names = ['A', 'B', 'C']
my_df2 = pd.DataFrame(columns = col_names)
my_df = my_df.append(my_df2)
Performance considerations
If you are adding rows inside a loop consider performance issues. For around the first 1000 records "my_df.loc" performance is better, but it gradually becomes slower by increasing the number of records in the loop.
If you plan to do thins inside a big loop (say 10M? records or so), you are better off using a mixture of these two; fill a dataframe with iloc until the size gets around 1000, then append it to the original dataframe, and empty the temp dataframe. This would boost your performance by around 10 times.
class App():
def __init__(self):
self.root = Tkinter.Tk()
button = Tkinter.Button(self.root, text = 'root quit', command=self.quit)
button.pack()
self.root.mainloop()
def quit(self):
self.root.destroy()
app = App()
Maybe you can use arrow function (ES6+) or the simple old function declaration.
Normal function declaration type (Not ES6+):
<link href="#" onClick={function(event){ func1(event); func2();}}>Trigger here</link>
Anonymous function or arrow function type (ES6+)
<link href="#" onClick={(event) => { func1(event); func2();}}>Trigger here</link>
The second one is the shortest road that I know. Hope it helps you!
Using the first for
-loop you manually enumerate through the array by increasing an index to the length of the array, then getting the value at the current index manually.
The latter syntax is added in Java 5 and enumerates an array by using an Iterator
instance under the hoods. You then have only access to the object (not the index) and you won't be able to adjust the array while enumerating.
It's convenient when you just want to perform some actions on all objects in an array.
If you bring in to the code same library from 2 different sources that will cause the error.
If a credit card is already added to a PayPal account then it won't let you use that card to process directly with Payments Advanced. The system expects buyers to login to PayPal and just choose that credit card as their funding source if they want to pay with it.
As for testing on the sandbox, I've always used old, expired credit cards I have laying around and they seem to work fine for me.
You could always try the ones starting on page 87 of the PayFlow documentation, too. They should work.
According to w3.org (note that this link is in the long-expired draft HTML 3.0 spec):
An unordered list typically is a bulleted list of items. HTML 3.0 gives you the ability to customise the bullets, to do without bullets and to wrap list items horizontally or vertically for multicolumn lists.
The opening list tag must be
<UL>
. It is followed by an optional list header (<LH>
caption</LH>
) and then by the first list item (<LI>
). For example:<UL> <LH>Table Fruit</LH> <LI>apples <LI>oranges <LI>bananas </UL>
which could be rendered as:
Table Fruit
- apples
- oranges
- bananas
Note: Some legacy documents may include headers or plain text before the first LI element. Implementors of HTML 3.0 user agents are advised to cater for this possibility in order to handle badly formed legacy documents.
My solution was use readAsBinaryString()
and btoa()
on its result.
uploadFileToServer(event) {
var file = event.srcElement.files[0];
console.log(file);
var reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = function() {
console.log(btoa(reader.result));
};
reader.onerror = function() {
console.log('there are some problems');
};
}
I ran into the same error. My web app was pointed towards report viewer version 10.0 however if 11.0 is installed it adds a redirect in the 10.0 .dll to 11.0. This became an issue when 11.0 was uninstalled as this does not correct the redirect in the 10.0 .dll. The fix in my case was to simply uninstall and reinstall 10.0.
print("the furnace is now " + str(temperature) + "degrees!")
cast it to str
First, let me go over a few terms. If you just want your question answered, scroll down to "Answering your question".
Object identity: When you create an object, you can assign it to a variable. You can then also assign it to another variable. And another.
>>> button = Button()
>>> cancel = button
>>> close = button
>>> dismiss = button
>>> print(cancel is close)
True
In this case, cancel
, close
, and dismiss
all refer to the same object in memory. You only created one Button
object, and all three variables refer to this one object. We say that cancel
, close
, and dismiss
all refer to identical objects; that is, they refer to one single object.
Object equality: When you compare two objects, you usually don't care that it refers to the exact same object in memory. With object equality, you can define your own rules for how two objects compare. When you write if a == b:
, you are essentially saying if a.__eq__(b):
. This lets you define a __eq__
method on a
so that you can use your own comparison logic.
Rationale: Two objects have the exact same data, but are not identical. (They are not the same object in memory.) Example: Strings
>>> greeting = "It's a beautiful day in the neighbourhood."
>>> a = unicode(greeting)
>>> b = unicode(greeting)
>>> a is b
False
>>> a == b
True
Note: I use unicode strings here because Python is smart enough to reuse regular strings without creating new ones in memory.
Here, I have two unicode strings, a
and b
. They have the exact same content, but they are not the same object in memory. However, when we compare them, we want them to compare equal. What's happening here is that the unicode object has implemented the __eq__
method.
class unicode(object):
# ...
def __eq__(self, other):
if len(self) != len(other):
return False
for i, j in zip(self, other):
if i != j:
return False
return True
Note: __eq__
on unicode
is definitely implemented more efficiently than this.
Rationale: Two objects have different data, but are considered the same object if some key data is the same. Example: Most types of model data
>>> import datetime
>>> a = Monitor()
>>> a.make = "Dell"
>>> a.model = "E770s"
>>> a.owner = "Bob Jones"
>>> a.warranty_expiration = datetime.date(2030, 12, 31)
>>> b = Monitor()
>>> b.make = "Dell"
>>> b.model = "E770s"
>>> b.owner = "Sam Johnson"
>>> b.warranty_expiration = datetime.date(2005, 8, 22)
>>> a is b
False
>>> a == b
True
Here, I have two Dell monitors, a
and b
. They have the same make and model. However, they neither have the same data nor are the same object in memory. However, when we compare them, we want them to compare equal. What's happening here is that the Monitor object implemented the __eq__
method.
class Monitor(object):
# ...
def __eq__(self, other):
return self.make == other.make and self.model == other.model
When comparing to None
, always use is not
. None is a singleton in Python - there is only ever one instance of it in memory.
By comparing identity, this can be performed very quickly. Python checks whether the object you're referring to has the same memory address as the global None object - a very, very fast comparison of two numbers.
By comparing equality, Python has to look up whether your object has an __eq__
method. If it does not, it examines each superclass looking for an __eq__
method. If it finds one, Python calls it. This is especially bad if the __eq__
method is slow and doesn't immediately return when it notices that the other object is None
.
Did you not implement __eq__
? Then Python will probably find the __eq__
method on object
and use that instead - which just checks for object identity anyway.
When comparing most other things in Python, you will be using !=
.
Assuming you're using WinForms, as it was the first thing I did when I was starting C# you need to create an event to close this form.
Lets say you've got a button called myNewButton. If you double click it on WinForms designer you will create an event. After that you just have to use this.Close
private void myNewButton_Click(object sender, EventArgs e) {
this.Close();
}
And that should be it.
The only reason for this not working is that your Event is detached from button. But it should create new event if old one is no longer attached when you double click on the button in WinForms designer.
The following lines can be added either in Apache directives or in .htaccess file:
RewriteEngine on
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Don't forget to apply the apache changes if you modify the vhost.
(based on the default Drupal7 .htaccess but should work in many cases)
I do not know of a row limit, but I know tables with more than 170 million rows. You may speed it up using partitioned tables (2005+) or views that connect multiple tables.
I use a slightly more concise version:
expect(() => {
// Code block that should throw error
}).toThrow(TypeError) // Or .toThrow('expectedErrorMessage')
I found this to work very well!
function findRoot() {
return(substr($_SERVER["SCRIPT_FILENAME"], 0, (stripos($_SERVER["SCRIPT_FILENAME"], $_SERVER["SCRIPT_NAME"])+1)));
}
Use:
<?php
function findRoot() {
return(substr($_SERVER["SCRIPT_FILENAME"], 0, (stripos($_SERVER["SCRIPT_FILENAME"], $_SERVER["SCRIPT_NAME"])+1)));
}
include(findRoot() . 'Post.php');
$posts = getPosts(findRoot() . 'posts_content');
include(findRoot() . 'includes/head.php');
for ($i=(sizeof($posts)-1); 0 <= $i; $i--) {
$posts[$i]->displayArticle();
}
include(findRoot() . 'includes/footer.php');
?>
Judging by your other post: How to Get the inner text of a span in PHP. You're quite new to web programming, and need to learn about the differences between code on the client (JavaScript) and code on the server (PHP).
As for the correct approach to grabbing the span text from the client I recommend Johns answer.
These are a good place to get started.
JavaScript: https://stackoverflow.com/questions/11246/best-resources-to-learn-javascript
PHP: https://stackoverflow.com/questions/772349/what-is-a-good-online-tutorial-for-php
Also I recommend using jQuery (Once you've got some JavaScript practice) it will eliminate most of the cross-browser compatability issues that you're going to have. But don't use it as a crutch to learn on, it's good to understand JavaScript too. http://jquery.com/
I would like to expand open jfs's answer, which worked great for my problem: sorting two lists by a third, decorated list:
We can create our decorated list in any way, but in this case we will create it from the elements of one of the two original lists, that we want to sort:
# say we have the following list and we want to sort both by the algorithms name
# (if we were to sort by the string_list, it would sort by the numerical
# value in the strings)
string_list = ["0.123 Algo. XYZ", "0.345 Algo. BCD", "0.987 Algo. ABC"]
dict_list = [{"dict_xyz": "XYZ"}, {"dict_bcd": "BCD"}, {"dict_abc": "ABC"}]
# thus we need to create the decorator list, which we can now use to sort
decorated = [text[6:] for text in string_list]
# decorated list to sort
>>> decorated
['Algo. XYZ', 'Algo. BCD', 'Algo. ABC']
Now we can apply jfs's solution to sort our two lists by the third
# create and sort the list of indices
sorted_indices = list(range(len(string_list)))
sorted_indices.sort(key=decorated.__getitem__)
# map sorted indices to the two, original lists
sorted_stringList = list(map(string_list.__getitem__, sorted_indices))
sorted_dictList = list(map(dict_list.__getitem__, sorted_indices))
# output
>>> sorted_stringList
['0.987 Algo. ABC', '0.345 Algo. BCD', '0.123 Algo. XYZ']
>>> sorted_dictList
[{'dict_abc': 'ABC'}, {'dict_bcd': 'BCD'}, {'dict_xyz': 'XYZ'}]
I'd make something like this:
var request = []
while(count<10){
request.push(db.getUser(email).then(function(res) { return res; }));
count++
};
Promise.all(request).then((dataAll)=>{
for (var i = 0; i < dataAll.length; i++) {
logger.log(dataAll[i]);
}
});
in this way, dataAll is an ordered array of all element to log. And log operation will perform when all promises are done.
the toString()
converts the specified object to a string value.
You have 3 options to make your way:
1. Define a date value like '1970-01-01'
2. Select NULL from the dropdown to keep it blank.
3. Select CURRENT_TIMESTAMP to set current datetime as default value.
I had a similar issue with application/json ajax calls. In ff/IE they were fine. In chrome in the Developer Network window Status was always (pending) because a different status code was being returned.
In my case I changed my Json response to send a HttpStatusCode of 200 then Chrome was fine and the Status Text changed to 200 OK.
For example using ASP.NET Web Api
return new HttpResponseMessage(HttpStatusCode.OK ) {
Content = request.Content
};
In order for a bot to send a message, you need <client>.send()
, the client
is where the bot will send a message to(A channel, everywhere in the server, or a PM). Since you want the bot to PM a certain user, you can use message.author
as your client
. (you can replace author
as mentioned user in a message or something, etc)
Hence, the answer is: message.author.send("Your message here.")
I recommend looking up the Discord.js documentation about a certain object's properties whenever you get stuck, you might find a particular function that may serve as your solution.
I suggest using pubnub. I tried using ServiceWorkers and PushNotification from the browser however, however when I tried it webviews did not support this.
https://www.pubnub.com/docs/web-javascript/pubnub-javascript-sdk
The accepted answer work when you have a single line string(the email) but if you have a
multiline string, the error will remain.
Please look into this matter:
<!-- start: definition-->
@{
dynamic item = new System.Dynamic.ExpandoObject();
item.MultiLineString = @"a multi-line
string";
item.SingleLineString = "a single-line string";
}
<!-- end: definition-->
<a href="#" onclick="Getinfo('@item.MultiLineString')">6/16/2016 2:02:29 AM</a>
<script>
function Getinfo(text) {
alert(text);
}
</script>
Change the single-quote(') to backtick(`) in Getinfo as bellow and error will be fixed:
<a href="#" onclick="Getinfo(`@item.MultiLineString`)">6/16/2016 2:02:29 AM</a>
A little late for the party, here's how I do it
./shutdown.sh
/work/Catalina/...
./startup.sh
/webapps
and start it."mindate" attribute should be used to disable passed dates in jquery datepicker.
minDate: new Date() Or minDate: '0' is the key for this.
Ex:
$(function() {
$( "#datepicker" ).datepicker({minDate: new Date()});
});
OR
$(function() {
$( "#datepicker" ).datepicker({minDate: 0});
});
org.hibernate.hql.internal.ast.QuerySyntaxException: users is not mapped [from users]
This indicates that hibernate does not know the User
entity as "users".
@javax.persistence.Entity
@javax.persistence.Table(name = "Users")
public class User {
The @Table
annotation sets the table name to be "Users" but the entity name is still referred to in HQL as "User".
To change both, you should set the name of the entity:
// this sets the name of the table and the name of the entity
@javax.persistence.Entity(name = "Users")
public class User implements Serializable{
See my answer here for more info: Hibernate table not mapped error
It's simple. I did it the following way to get a string with unique values (from two columns of an output sheet):
Dim startpoint, endpoint, ArrCount As Integer
Dim SentToArr() As String
'created by running the first part (check for new entries)
startpoint = ThisWorkbook.Sheets("temp").Range("A1").Value
'set counter on 0
Arrcount = 0
'last filled row in BG
endpoint = ThisWorkbook.Sheets("BG").Range("G1047854").End(xlUp).Row
'create arr with all data - this could be any data you want!
With ThisWorkbook.Sheets("BG")
For i = startpoint To endpoint
ArrCount = ArrCount + 1
ReDim Preserve SentToArr(1 To ArrCount)
SentToArr(ArrCount) = .Range("A" & i).Value
'get prep
ArrCount = ArrCount + 1
ReDim Preserve SentToArr(1 To ArrCount)
SentToArr(ArrCount) = .Range("B" & i).Value
Next i
End With
'iterate the arr and get a key (l) in each iteration
For l = LBound(SentToArr) To UBound(SentToArr)
Key = SentToArr(l)
'iterate one more time and compare the first key (l) with key (k)
For k = LBound(SentToArr) To UBound(SentToArr)
'if key = the new key from the second iteration and the position is different fill it as empty
If Key = SentToArr(k) And Not k = l Then
SentToArr(k) = ""
End If
Next k
Next l
'iterate through all 'unique-made' values, if the value of the pos is
'empty, skip - you could also create a new array by using the following after the IF below - !! dont forget to reset [ArrCount] as well:
'ArrCount = ArrCount + 1
'ReDim Preserve SentToArr(1 To ArrCount)
'SentToArr(ArrCount) = SentToArr(h)
For h = LBound(SentToArr) To UBound(SentToArr)
If SentToArr(h) = "" Then GoTo skipArrayPart
GetEmailArray = GetEmailArray & "; " & SentToArr(h)
skipArrayPart:
Next h
'some clean up
If Left(GetEmailArray, 2) = "; " Then
GetEmailArray = Right(GetEmailArray, Len(GetEmailArray) - 2)
End If
'show us the money
MsgBox GetEmailArray
Access requires parentheses in the FROM
clause for queries which include more than one join. Try it this way ...
FROM
((tbl_employee
INNER JOIN tbl_netpay
ON tbl_employee.emp_id = tbl_netpay.emp_id)
INNER JOIN tbl_gross
ON tbl_employee.emp_id = tbl_gross.emp_ID)
INNER JOIN tbl_tax
ON tbl_employee.emp_id = tbl_tax.emp_ID;
If possible, use the Access query designer to set up your joins. The designer will add parentheses as required to keep the db engine happy.
I use the AbsoluteUri and you can get it like this:
string myURI = Request.Url.AbsoluteUri;
if (!WebSecurity.IsAuthenticated) {
Response.Redirect("~/Login?returnUrl="
+ Request.Url.AbsoluteUri );
Then after you login:
var returnUrl = Request.QueryString["returnUrl"];
if(WebSecurity.Login(username,password,true)){
Context.RedirectLocal(returnUrl);
It works well for me.
I am surprised nobody suggested
(numerator + denominator - 1) // denominator
for integer division with rounding up. Used to be the common way for C/C++/CUDA (cf. divup
)
From the docs:
urllib.quote(string[, safe])
Replace special characters in string using the %xx escape. Letters, digits, and the characters '_.-' are never quoted. By default, this function is intended for quoting the path section of the URL.The optional safe parameter specifies additional characters that should not be quoted — its default value is '/'
That means passing '' for safe will solve your first issue:
>>> urllib.quote('/test')
'/test'
>>> urllib.quote('/test', safe='')
'%2Ftest'
About the second issue, there is a bug report about it here. Apparently it was fixed in python 3. You can workaround it by encoding as utf8 like this:
>>> query = urllib.quote(u"Müller".encode('utf8'))
>>> print urllib.unquote(query).decode('utf8')
Müller
By the way have a look at urlencode
The same, except replace urllib.quote
with urllib.parse.quote
.
1.'update to reversion' check 'only this item' under the directory 2.update again check 'Fully recursive'
ALTER SCHEMA TargetSchema
TRANSFER SourceSchema.TableName;
If you want to move all tables into a new schema, you can use the undocumented (and to be deprecated at some point, but unlikely!) sp_MSforeachtable
stored procedure:
exec sp_MSforeachtable "ALTER SCHEMA TargetSchema TRANSFER ?"
Ref.: ALTER SCHEMA
other way to compile using -Xlint:unchecked through command line
javac abc.java -Xlint:unchecked
it will show the unchecked and unsafe warnings.
Normally you would select IDs using the ID selector #
, but for more complex matches you can use the attribute-starts-with selector (as a jQuery selector, or as a CSS3 selector):
div[id^="player_"]
If you are able to modify that HTML, however, you should add a class to your player div
s then target that class. You'll lose the additional specificity offered by ID selectors anyway, as attribute selectors share the same specificity as class selectors. Plus, just using a class makes things much simpler.
You can set a default encoding-set whenever you run eclipse.exe.
-Dfile.encoding=UTF-8
If you want to modify the original array instead of returning a new array, use .push()
...
array1.push.apply(array1, array2);
array1.push.apply(array1, array3);
I used .apply
to push the individual members of arrays 2
and 3
at once.
or...
array1.push.apply(array1, array2.concat(array3));
To deal with large arrays, you can do this in batches.
for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
array1.push.apply(array1, to_add.slice(n, n+300));
}
If you do this a lot, create a method or function to handle it.
var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);
Object.defineProperty(Array.prototype, "pushArrayMembers", {
value: function() {
for (var i = 0; i < arguments.length; i++) {
var to_add = arguments[i];
for (var n = 0; n < to_add.length; n+=300) {
push_apply(this, slice_call(to_add, n, n+300));
}
}
}
});
and use it like this:
array1.pushArrayMembers(array2, array3);
var push_apply = Function.apply.bind([].push);_x000D_
var slice_call = Function.call.bind([].slice);_x000D_
_x000D_
Object.defineProperty(Array.prototype, "pushArrayMembers", {_x000D_
value: function() {_x000D_
for (var i = 0; i < arguments.length; i++) {_x000D_
var to_add = arguments[i];_x000D_
for (var n = 0; n < to_add.length; n+=300) {_x000D_
push_apply(this, slice_call(to_add, n, n+300));_x000D_
}_x000D_
}_x000D_
}_x000D_
});_x000D_
_x000D_
var array1 = ['a','b','c'];_x000D_
var array2 = ['d','e','f'];_x000D_
var array3 = ['g','h','i'];_x000D_
_x000D_
array1.pushArrayMembers(array2, array3);_x000D_
_x000D_
document.body.textContent = JSON.stringify(array1, null, 4);
_x000D_
I think your problem is that it's closing the document that calls the macro before sending the command to quit the application.
Your solution in that case is to not send a command to close the workbook. Instead, you could set the "Saved" state of the workbook to true, which would circumvent any messages about closing an unsaved book. Note: this does not save the workbook; it just makes it look like it's saved.
ThisWorkbook.Saved = True
and then, right after
Application.Quit
That entire block is misplaced.
class Example(object):
def main(self):
print "Hello World!"
if __name__ == '__main__':
Example().main()
But you really shouldn't be using a class just to run your main code.
It's definitely conceivable but I am not sure we're there yet. In the meantime, I'd recommend using something like Silverlight with IIS Smooth Streaming. Silverlight is plugin-based, but it works on Windows/OSX/Linux. Some day the HTML5 <video>
element will be the way to go, but that will lack support for a little while.
Control Panel>System and Security>Windows Firewall>Allowed Programs-> then check all " World Wide Web Services(Http) tab".
Its worked for me
My solution on using ObjectId
// usermodel.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const ObjectId = Schema.Types.ObjectId
let UserSchema = new Schema({
username: {
type: String
},
events: [{
type: ObjectId,
ref: 'Event' // Reference to some EventSchema
}]
})
UserSchema.set('autoIndex', true)
module.exports = mongoose.model('User', UserSchema)
Using mongoose's populate method
// controller.js
const mongoose = require('mongoose')
const User = require('./usermodel.js')
let query = User.findOne({ name: "Person" })
query.exec((err, user) => {
if (err) {
console.log(err)
}
user.events = events
// user.events is now an array of events
})
Whenever you're confused, I would suggest consulting the Javadoc as the first place for your clarification.
From the javadoc about System
, here's what the doc says:
public final class System
extends Object
The System class contains several useful class fields and methods. It cannot be instantiated.
Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
Since:
JDK1.0
Regarding System.out
public static final PrintStream out
The "standard" output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user.
For simple stand-alone Java applications, a typical way to write a line of output data is:
System.out.println(data)
You can do this way -
int[] terms = new int[400];
for (int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}
Alternatively, you can use Lists - the advantage with lists being, you don't need to know the array size when instantiating the list.
List<int> termsList = new List<int>();
for (int runs = 0; runs < 400; runs++)
{
termsList.Add(value);
}
// You can convert it back to an array if you would like to
int[] terms = termsList.ToArray();
Using numpy, you can define the following:
import numpy as np
def cart2pol(x, y):
rho = np.sqrt(x**2 + y**2)
phi = np.arctan2(y, x)
return(rho, phi)
def pol2cart(rho, phi):
x = rho * np.cos(phi)
y = rho * np.sin(phi)
return(x, y)
I ran into this issue by having mismatched build variants. A Dynamic Delivery module was on the debug variant while the remaining modules were on release. Simply changing the Dynamic Delivery module to release, rebuilding, and installing, fixed the issue.
Here's typescript version. works on "react-router-dom": "^4.3.1"
export const AppRouter: React.StatelessComponent = () => {
return (
<BrowserRouter>
<Switch>
<Route exact path="/problem/:problemId" render={props => <ProblemPage {...props.match.params} />} />
<Route path="/" exact component={App} />
</Switch>
</BrowserRouter>
);
};
and component
export class ProblemPage extends React.Component<ProblemRouteTokens> {
public render(): JSX.Element {
return <div>{this.props.problemId}</div>;
}
}
where ProblemRouteTokens
export interface ProblemRouteTokens { problemId: string; }
I had this error and the other fixes didn't help me, but changing the CPU type the emulator used did get it working.
Create a new emulator and try using mips or arm for the cpu selection
cd apache-tomcat-6.0.43 ====: Go to Tomcat Directory
sh bin/startup.sh =====: Start the tomcat on Linux
sh bin/shutdown.sh ======:Shut Down the tomcat on Linux
tail -f logs/catelina.out ====: Check the logs
As a follow-up to the accepted answer, this is a minimal definition of the IHTMLScriptElement
interface which does not require to include additional type libraries:
[ComImport, ComVisible(true), Guid(@"3050f28b-98b5-11cf-bb82-00aa00bdce0b")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
[TypeLibType(TypeLibTypeFlags.FDispatchable)]
public interface IHTMLScriptElement
{
[DispId(1006)]
string text { set; [return: MarshalAs(UnmanagedType.BStr)] get; }
}
So a full code inside a WebBrowser control derived class would look like:
protected override void OnDocumentCompleted(
WebBrowserDocumentCompletedEventArgs e)
{
base.OnDocumentCompleted(e);
// Disable text selection.
var doc = Document;
if (doc != null)
{
var heads = doc.GetElementsByTagName(@"head");
if (heads.Count > 0)
{
var scriptEl = doc.CreateElement(@"script");
if (scriptEl != null)
{
var element = (IHTMLScriptElement)scriptEl.DomElement;
element.text =
@"function disableSelection()
{
document.body.onselectstart=function(){ return false; };
document.body.ondragstart=function() { return false; };
}";
heads[0].AppendChild(scriptEl);
doc.InvokeScript(@"disableSelection");
}
}
}
}
I fixed this with below steps:
Update for Swift 3:
// Create the AlertController and add its actions like button in ActionSheet
let actionSheetController = UIAlertController(title: "Please select", message: "Option to select", preferredStyle: .actionSheet)
let cancelActionButton = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
print("Cancel")
}
actionSheetController.addAction(cancelActionButton)
let saveActionButton = UIAlertAction(title: "Save", style: .default) { action -> Void in
print("Save")
}
actionSheetController.addAction(saveActionButton)
let deleteActionButton = UIAlertAction(title: "Delete", style: .default) { action -> Void in
print("Delete")
}
actionSheetController.addAction(deleteActionButton)
self.present(actionSheetController, animated: true, completion: nil)
Starting in version 0.7.9 you can use the filter operator .isnot
instead of comparing constraints, like this:
query.filter(User.name.isnot(None))
This method is only necessary if pep8 is a concern.
source: sqlalchemy documentation
composer dump-autoload
PATH vendor/composer/autoload_classmap.php
php artisan dump-autoload
I came accross the same problem and solved.
As said before you need to create your custom WebViewClient and override the shouldInterceptRequest method.
WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request)
That method should issue a webView.loadUrl while returning an "empty" WebResourceResponse.
Something like this:
@Override
public boolean shouldInterceptRequest(WebView view, WebResourceRequest request) {
// Check for "recursive request" (are yor header set?)
if (request.getRequestHeaders().containsKey("Your Header"))
return null;
// Add here your headers (could be good to import original request header here!!!)
Map<String, String> customHeaders = new HashMap<String, String>();
customHeaders.put("Your Header","Your Header Value");
view.loadUrl(url, customHeaders);
return new WebResourceResponse("", "", null);
}
You can use C style string formatting:
"%d:%d:d" % (hours, minutes, seconds)
See here, especially: https://web.archive.org/web/20120415173443/http://diveintopython3.ep.io/strings.html
Here is Kotlin version.
Thanks you :)
fun unSafeOkHttpClient() :OkHttpClient.Builder {
val okHttpClient = OkHttpClient.Builder()
try {
// Create a trust manager that does not validate certificate chains
val trustAllCerts: Array<TrustManager> = arrayOf(object : X509TrustManager {
override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?){}
override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {}
override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
})
// Install the all-trusting trust manager
val sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCerts, SecureRandom())
// Create an ssl socket factory with our all-trusting manager
val sslSocketFactory = sslContext.socketFactory
if (trustAllCerts.isNotEmpty() && trustAllCerts.first() is X509TrustManager) {
okHttpClient.sslSocketFactory(sslSocketFactory, trustAllCerts.first() as X509TrustManager)
okHttpClient.hostnameVerifier { _, _ -> true }
}
return okHttpClient
} catch (e: Exception) {
return okHttpClient
}
}
Note on granting permissions via MMC, Certs, Select Cert, right-click, all-tasks, "Manage Private Keys"
Manage Private Keys is only on the menu list for Personal... So if you've put your cert in Trusted People, etc. you're out of luck.
We found a way around this which worked for us. Drag and drop the cert to Personal, do the Manage Private Keys thing to grant permissions. Remember to set to use object-type built-ins and use the local machine not domain. We granted rights to the DefaultAppPool user and left it at that.
Once you're done, drag and drop the cert back where ever you originally had it. Presto.
Based on Spencer Rathbun's answer, using bash:
true &>/dev/null </dev/tcp/127.0.0.1/$PORT && echo open || echo closed
I needed to indent two rows to allow for a larger first word in a para. A cumbersome one-off solution is to place text in an SVG element and position this the same as an <img>. Using float and the SVG's height tag defines how many rows will be indented e.g.
<p style="color: blue; font-size: large; padding-top: 4px;">
<svg height="44" width="260" style="float:left;margin-top:-8px;"><text x="0" y="36" fill="blue" font-family="Verdana" font-size="36">Lorum Ipsum</text></svg>
dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p>
Yes it is cumbersome but it is also independent of the width of the containing div.
The above answer was to my own query to allow the first word(s) of a para to be larger and positioned over two rows. To simply indent the first two lines of a para you could replace all the SVG tags with the following single pixel img:
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" style="float:left;width:260px;height:44px;" />
Here is my code that is finally working
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Threading;
class TelnetTest
{
static void Main(string[] args)
{
TelnetTest tt = new TelnetTest();
tt.tcpClient = new TcpClient("myserver", 23);
tt.ns = tt.tcpClient.GetStream();
tt.connectHost("admin", "admin");
tt.sendCommand();
tt.tcpClient.Close();
}
public void connectHost(string user, string passwd) {
bool i = true;
while (i)
{
Console.WriteLine("Connecting.....");
Byte[] output = new Byte[1024];
String responseoutput = String.Empty;
Byte[] cmd = System.Text.Encoding.ASCII.GetBytes("\n");
ns.Write(cmd, 0, cmd.Length);
Thread.Sleep(1000);
Int32 bytes = ns.Read(output, 0, output.Length);
responseoutput = System.Text.Encoding.ASCII.GetString(output, 0, bytes);
Console.WriteLine("Responseoutput: " + responseoutput);
Regex objToMatch = new Regex("login:");
if (objToMatch.IsMatch(responseoutput)) {
cmd = System.Text.Encoding.ASCII.GetBytes(user + "\r");
ns.Write(cmd, 0, cmd.Length);
}
Thread.Sleep(1000);
bytes = ns.Read(output, 0, output.Length);
responseoutput = System.Text.Encoding.ASCII.GetString(output, 0, bytes);
Console.Write(responseoutput);
objToMatch = new Regex("Password");
if (objToMatch.IsMatch(responseoutput))
{
cmd = System.Text.Encoding.ASCII.GetBytes(passwd + "\r");
ns.Write(cmd, 0, cmd.Length);
}
Thread.Sleep(1000);
bytes = ns.Read(output, 0, output.Length);
responseoutput = System.Text.Encoding.ASCII.GetString(output, 0, bytes);
Console.Write("Responseoutput: " + responseoutput);
objToMatch = new Regex("#");
if (objToMatch.IsMatch(responseoutput))
{
i = false;
}
}
Console.WriteLine("Just works");
}
}
Konrad said:
As a consequence, a purely functional program always yields the same value for an input, and the order of evaluation is not well-defined; which means that uncertain values like user input or random values are hard to model in purely functional languages.
The order of evaluation in a purely functional program may be hard(er) to reason about (especially with laziness) or even unimportant but I think that saying it is not well defined makes it sound like you can't tell if your program is going to work at all!
Perhaps a better explanation would be that control flow in functional programs is based on when the value of a function's arguments are needed. The Good Thing about this that in well written programs, state becomes explicit: each function lists its inputs as parameters instead of arbitrarily munging global state. So on some level, it is easier to reason about order of evaluation with respect to one function at a time. Each function can ignore the rest of the universe and focus on what it needs to do. When combined, functions are guaranteed to work the same[1] as they would in isolation.
... uncertain values like user input or random values are hard to model in purely functional languages.
The solution to the input problem in purely functional programs is to embed an imperative language as a DSL using a sufficiently powerful abstraction. In imperative (or non-pure functional) languages this is not needed because you can "cheat" and pass state implicitly and order of evaluation is explicit (whether you like it or not). Because of this "cheating" and forced evaluation of all parameters to every function, in imperative languages 1) you lose the ability to create your own control flow mechanisms (without macros), 2) code isn't inherently thread safe and/or parallelizable by default, 3) and implementing something like undo (time travel) takes careful work (imperative programmer must store a recipe for getting the old value(s) back!), whereas pure functional programming buys you all these things—and a few more I may have forgotten—"for free".
I hope this doesn't sound like zealotry, I just wanted to add some perspective. Imperative programming and especially mixed paradigm programming in powerful languages like C# 3.0 are still totally effective ways to get things done and there is no silver bullet.
[1] ... except possibly with respect memory usage (cf. foldl and foldl' in Haskell).
Old post, but I ran into this so if you're trying to output something to Output in a WPF project in Visual Studio, the contemporary method is:
Include this:
using System.Diagnostics;
And then:
Debug.WriteLine("something");
You can actually simplify this by removing the v-on
directives:
<input type="radio" name="optionsRadios" id="optionsRadios1" value="1" v-model="srStatus">
And use the watch
method to listen for the change:
new Vue ({
el: "#app",
data: {
cases: [
{ name: 'case A', status: '1' },
{ name: 'case B', status: '0' },
{ name: 'case C', status: '1' }
],
activeCases: [],
srStatus: ''
},
watch: {
srStatus: function(val, oldVal) {
for (var i = 0; i < this.cases.length; i++) {
if (this.cases[i].status == val) {
this.activeCases.push(this.cases[i]);
alert("Fired! " + val);
}
}
}
}
});
Sounds like you want to use BitmapDrawable
From the documentation:
A
Drawable
that wraps a bitmap and can be tiled, stretched, or aligned. You can create aBitmapDrawable
from a file path, an input stream, through XML inflation, or from aBitmap
object.
In the Windows command prompt you can disable tab completion, by launching it thusly:
cmd.exe /f:off
Then the tab character will be echoed to the screen and work as you expect. Or you can disable the tab completion character, or modify what character is used for tab completion by modifying the registry.
The cmd.exe
help page explains it:
You can enable or disable file name completion for a particular invocation of CMD.EXE with the /F:ON or /F:OFF switch. You can enable or disable completion for all invocations of CMD.EXE on a machine and/or user logon session by setting either or both of the following REG_DWORD values in the registry using REGEDIT.EXE:
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\CompletionChar HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\PathCompletionChar and/or HKEY_CURRENT_USER\Software\Microsoft\Command Processor\CompletionChar HKEY_CURRENT_USER\Software\Microsoft\Command Processor\PathCompletionChar
with the hex value of a control character to use for a particular function (e.g. 0x4 is Ctrl-D and 0x6 is Ctrl-F). The user specific settings take precedence over the machine settings. The command line switches take precedence over the registry settings.
If completion is enabled with the /F:ON switch, the two control characters used are Ctrl-D for directory name completion and Ctrl-F for file name completion. To disable a particular completion character in the registry, use the value for space (0x20) as it is not a valid control character.
private DataTable CreateDataTable(IList<T> item)
{
Type type = typeof(T);
var properties = type.GetProperties();
DataTable dataTable = new DataTable();
foreach (PropertyInfo info in properties)
{
dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
}
foreach (T entity in item)
{
object[] values = new object[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
values[i] = properties[i].GetValue(entity);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
I was running JUNIT 5 and was also referencing Hamcrest external jar. But Hamcrest is also part of JUNIT 5 library. So, I have to change the order of external Hamecrest jar file up the JUNIT 5 library in build path.
On linux, find dblink.sql, then execute in the postgresql console something like this to create all required functions:
\i /usr/share/postgresql/8.4/contrib/dblink.sql
you might need to install the contrib packages: sudo apt-get install postgresql-contrib
hash_map is a non-standard extension. unordered_map is part of std::tr1, and will be moved into the std namespace for C++0x. http://en.wikipedia.org/wiki/Unordered_map_%28C%2B%2B%29
protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[columnIndex].Visible = false;
}
HeaderText
for the GridViewColumn
and then find the column using that HeaderText
.
protected void UsersGrid_RowCreated(object sender, GridViewRowEventArgs e)
{
((DataControlField)UsersGrid.Columns
.Cast<DataControlField>()
.Where(fld => fld.HeaderText == "Email")
.SingleOrDefault()).Visible = false;
}
Some of the answers have already provided various approaches related to getting rid of the create extension and comment on extensions. For me, the following command line seemed to work and be the simplest approach to solve the problem:
cat /tmp/backup.sql.gz | gunzip - | \
grep -v -E '(CREATE\ EXTENSION|COMMENT\ ON)' | \
psql --set ON_ERROR_STOP=on -U db_user -h localhost my_db
Some notes
When working with HTTP it's almost always more useful to refer to HttpURLConnection
rather than the base class URLConnection
(since URLConnection
is an abstract class when you ask for URLConnection.openConnection()
on a HTTP URL that's what you'll get back anyway).
Then you can instead of relying on URLConnection#setDoOutput(true)
to implicitly set the request method to POST instead do httpURLConnection.setRequestMethod("POST")
which some might find more natural (and which also allows you to specify other request methods such as PUT, DELETE, ...).
It also provides useful HTTP constants so you can do:
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
You can also declare class variables as None which will prevent propagation. This is useful when you need a well defined class and want to prevent AttributeErrors. For example:
>>> class TestClass(object):
... t = None
...
>>> test = TestClass()
>>> test.t
>>> test2 = TestClass()
>>> test.t = 'test'
>>> test.t
'test'
>>> test2.t
>>>
Also if you need defaults:
>>> class TestClassDefaults(object):
... t = None
... def __init__(self, t=None):
... self.t = t
...
>>> test = TestClassDefaults()
>>> test.t
>>> test2 = TestClassDefaults([])
>>> test2.t
[]
>>> test.t
>>>
Of course still follow the info in the other answers about using mutable vs immutable types as the default in __init__
.
A few things you could use:
dir()
will give you the list of in scope variables:globals()
will give you a dictionary of global variableslocals()
will give you a dictionary of local variablesI used the Command_Line_Tools_OS_X_10.XX_for_Xcode_7.2.dmg
and therefore had to download the latest version from here.
On VS Code, just click the "Space: 4" on the downright corner and change it to tab when editing your Makefile.
A Singleton candidate must satisfy three requirements:
If your proposed Singleton has only one or two of these requirements, a redesign is almost always the correct option.
For example, a printer spooler is unlikely to be called from more than one place (the Print menu), so you can use mutexes to solve the concurrent access problem.
A simple logger is the most obvious example of a possibly-valid Singleton, but this can change with more complex logging schemes.
For correct work your shape should be with selector and item tags
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#ffffff" />
<stroke android:width="1dp"
android:color="@color/shape_border_active"/>
</shape>
</item>
</selector>
To update entries other than appsettings
, simply use XmlDocument
.
public static void UpdateAppConfig(string tagName, string attributeName, string value)
{
var doc = new XmlDocument();
doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
var tags = doc.GetElementsByTagName(tagName);
foreach (XmlNode item in tags)
{
var attribute = item.Attributes[attributeName];
if (!ReferenceEquals(null, attribute))
attribute.Value = value;
}
doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}
This is how you call it:
Utility.UpdateAppConfig("endpoint", "address", "http://localhost:19092/NotificationSvc/Notification.svc");
Utility.UpdateAppConfig("network", "host", "abc.com.au");
This method can be improved to cater for appSettings values as well.
You need to specify the executable path of Git in the Git Settings, as mentionned in the per-requesites:
The Git integration plugin is enabled and the location of the Git executable file is correctly specified on the Git page of the Settings dialog box.
As long as you see "a message indicating that the Git execution path is not correct", the rest of the instructions won't work.
Path to Git executable
In this text box, specify the path to the Git executable file.
Type the path manually or click the Browse button to open theSelect Path - Git Configuration
dialog box and select the location of the Git executable file in the directories tree.
See "Where is git.exe located?" for the path of Git on Windows.
with Git for Windows:
C:\Program Files\Git\mingw64\bin
OR
c:\path\to\PortableGit-2.6.2-64-bit\usr\bin
OR
c:\path\to\PortableGit-2.x.\mingw64\bin
With GitHub Desktop:
%USERPROFILE%\AppData\Local\GitHub\PORTAB~1\bin\git.exe
Update 2020, three years later:
As noted by Daniel Connelly in the comments
IntelliJ now lets people install it through the path specified in the help above (just look for the "
Download Now
" button on the Git menu).
If you download Git from the website, a version that IntelliJ does not support will be installed.
If you are using android.app.ActionBar and android.app.Activity you should change the app theme in application tag:
< application
android:theme="@android:style/Theme.Holo.Light">
Working example is given below,
MyService.class
public class MyService extends Service implements SpeechDelegate, Speech.stopDueToDelay {
public static SpeechDelegate delegate;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO do something useful
try {
if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
((AudioManager) Objects.requireNonNull(
getSystemService(Context.AUDIO_SERVICE))).setStreamMute(AudioManager.STREAM_SYSTEM, true);
}
} catch (Exception e) {
e.printStackTrace();
}
Speech.init(this);
delegate = this;
Speech.getInstance().setListener(this);
if (Speech.getInstance().isListening()) {
Speech.getInstance().stopListening();
} else {
System.setProperty("rx.unsafe-disable", "True");
RxPermissions.getInstance(this).request(permission.RECORD_AUDIO).subscribe(granted -> {
if (granted) { // Always true pre-M
try {
Speech.getInstance().stopTextToSpeech();
Speech.getInstance().startListening(null, this);
} catch (SpeechRecognitionNotAvailable exc) {
//showSpeechNotSupportedDialog();
} catch (GoogleVoiceTypingDisabledException exc) {
//showEnableGoogleVoiceTyping();
}
} else {
Toast.makeText(this, R.string.permission_required, Toast.LENGTH_LONG).show();
}
});
}
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
@Override
public void onStartOfSpeech() {
}
@Override
public void onSpeechRmsChanged(float value) {
}
@Override
public void onSpeechPartialResults(List<String> results) {
for (String partial : results) {
Log.d("Result", partial+"");
}
}
@Override
public void onSpeechResult(String result) {
Log.d("Result", result+"");
if (!TextUtils.isEmpty(result)) {
Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onSpecifiedCommandPronounced(String event) {
try {
if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
((AudioManager) Objects.requireNonNull(
getSystemService(Context.AUDIO_SERVICE))).setStreamMute(AudioManager.STREAM_SYSTEM, true);
}
} catch (Exception e) {
e.printStackTrace();
}
if (Speech.getInstance().isListening()) {
Speech.getInstance().stopListening();
} else {
RxPermissions.getInstance(this).request(permission.RECORD_AUDIO).subscribe(granted -> {
if (granted) { // Always true pre-M
try {
Speech.getInstance().stopTextToSpeech();
Speech.getInstance().startListening(null, this);
} catch (SpeechRecognitionNotAvailable exc) {
//showSpeechNotSupportedDialog();
} catch (GoogleVoiceTypingDisabledException exc) {
//showEnableGoogleVoiceTyping();
}
} else {
Toast.makeText(this, R.string.permission_required, Toast.LENGTH_LONG).show();
}
});
}
}
@Override
public void onTaskRemoved(Intent rootIntent) {
//Restarting the service if it is removed.
PendingIntent service =
PendingIntent.getService(getApplicationContext(), new Random().nextInt(),
new Intent(getApplicationContext(), MyService.class), PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
assert alarmManager != null;
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, service);
super.onTaskRemoved(rootIntent);
}
}
For more details,
Hope this will help someone in future.
If you previously installed Git, open a git-bash and try the command from there.
This works for me.
{
"files.associations": {"*.bitesize": "yaml"}
}
In case someone is looking for how to configure MongoDB with authentication using docker-compose
, here is a sample configuration using environment variables:
version: "3.3"
services:
db:
image: mongo
environment:
- MONGO_INITDB_ROOT_USERNAME=admin
- MONGO_INITDB_ROOT_PASSWORD=<YOUR_PASSWORD>
ports:
- "27017:27017"
When running docker-compose up
your mongo instance is run automatically with auth enabled. You will have a admin database with the given password.
mysqldump
has options for CSV formatting:
--fields-terminated-by=name
Fields in the output file are terminated by the given
--lines-terminated-by=name
Lines in the output file are terminated by the given
The name
should contain one of the following:
`--fields-terminated-by`
\t
or "\""
`--fields-enclosed-by=name`
Fields in the output file are enclosed by the given
and
--lines-terminated-by
\r
\n
\r\n
Naturally you should mysqldump each table individually.
I suggest you gather all table names in a text file. Then, iterate through all tables running mysqldump. Here is a script that will dump and gzip 10 tables at a time:
MYSQL_USER=root
MYSQL_PASS=rootpassword
MYSQL_CONN="-u${MYSQL_USER} -p${MYSQL_PASS}"
SQLSTMT="SELECT CONCAT(table_schema,'.',table_name)"
SQLSTMT="${SQLSTMT} FROM information_schema.tables WHERE table_schema NOT IN "
SQLSTMT="${SQLSTMT} ('information_schema','performance_schema','mysql')"
mysql ${MYSQL_CONN} -ANe"${SQLSTMT}" > /tmp/DBTB.txt
COMMIT_COUNT=0
COMMIT_LIMIT=10
TARGET_FOLDER=/path/to/csv/files
for DBTB in `cat /tmp/DBTB.txt`
do
DB=`echo "${DBTB}" | sed 's/\./ /g' | awk '{print $1}'`
TB=`echo "${DBTB}" | sed 's/\./ /g' | awk '{print $2}'`
DUMPFILE=${DB}-${TB}.csv.gz
mysqldump ${MYSQL_CONN} -T ${TARGET_FOLDER} --fields-terminated-by="," --fields-enclosed-by="\"" --lines-terminated-by="\r\n" ${DB} ${TB} | gzip > ${DUMPFILE}
(( COMMIT_COUNT++ ))
if [ ${COMMIT_COUNT} -eq ${COMMIT_LIMIT} ]
then
COMMIT_COUNT=0
wait
fi
done
if [ ${COMMIT_COUNT} -gt 0 ]
then
wait
fi
This error occur when you don't correctly write blocks. Forgetting a ":", or not using "Tab" button for blocks and use spaces. When you are transporting a code from one editor to another editor,it can happen. And never forget this: errors aren't always on that line. I came here for this, but I've forgotten an except after a try. because of my unstandard editor, it happend. But it's possible in normal editor.
There's another way with post
instead of ajax
var jqxhr = $.post( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});