Make sure that you've installed the latest HAXM revision. I had the same blank screen problem with version 1.0.1 while 1.0.8 was already available. The installer can be downloaded via the SDK tools, to actually install the module you would have to execute
android-sdk-directory\extras\intel\Hardware_Accelerated_Execution_Manager\intelhaxm.exe
Oneliner for doing all of the above operations:
for i in `ls -A .`; do if [ $i != ".git" ]; then rm -rf $i; fi; done; mv .git/* .; rm -rf .git; git config --bool core.bare true
(don't blame me if something blows up and you didn't have backups :P)
The block approach avoids running the lookup algorithm for every key:
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL* stop) {
NSLog(@"%@ => %@", key, value);
}];
Even though NSDictionary
is implemented as a hashtable (which means that the cost of looking up an element is O(1)
), lookups still slow down your iteration by a constant factor.
My measurements show that for a dictionary d
of numbers ...
NSMutableDictionary* dict = [NSMutableDictionary dictionary];
for (int i = 0; i < 5000000; ++i) {
NSNumber* value = @(i);
dict[value.stringValue] = value;
}
... summing up the numbers with the block approach ...
__block int sum = 0;
[dict enumerateKeysAndObjectsUsingBlock:^(NSString* key, NSNumber* value, BOOL* stop) {
sum += value.intValue;
}];
... rather than the loop approach ...
int sum = 0;
for (NSString* key in dict)
sum += [dict[key] intValue];
... is about 40% faster.
EDIT: The new SDK (6.1+) appears to optimise loop iteration, so the loop approach is now about 20% faster than the block approach, at least for the simple case above.
I don't have Python 2.7 installed, but in Python 3.3 calling Popen
with stdout
set to sys.stdout
worked just fine. Not before I had escaped the backslashes in the path, though.
>>> import subprocess
>>> import sys
>>> p = subprocess.Popen(['powershell.exe', 'C:\\Temp\\test.ps1'], stdout=sys.stdout)
>>> Hello World
_
@RequestMapping(value="/add/image", method=RequestMethod.POST)
public ResponseEntity upload(@RequestParam("id") Long id, HttpServletResponse response, HttpServletRequest request)
{
try {
MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest)request;
Iterator<String> it=multipartRequest.getFileNames();
MultipartFile multipart=multipartRequest.getFile(it.next());
String fileName=id+".png";
String imageName = fileName;
byte[] bytes=multipart.getBytes();
BufferedOutputStream stream= new BufferedOutputStream(new FileOutputStream("src/main/resources/static/image/book/"+fileName));;
stream.write(bytes);
stream.close();
return new ResponseEntity("upload success", HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity("Upload fialed", HttpStatus.BAD_REQUEST);
}
}
I figured it out. Need to use echo in PHP instead of return.
<?php
$output = some_function();
echo $output;
?>
And the jQ:
success: function(data) {
doSomething(data);
}
Here's one RegExp that does the trick.
'good_luck_buddy' . split(/^.*?_/)[1]
First it forces the match to start from the start with the '^'. Then it matches any number of characters which are not '_', in other words all characters before the first '_'.
The '?' means a minimal number of chars that make the whole pattern match are matched by the '.*?' because it is followed by '_', which is then included in the match as its last character.
Therefore this split() uses such a matching part as its 'splitter' and removes it from the results. So it removes everything up till and including the first '_' and gives you the rest as the 2nd element of the result. The first element is "" representing the part before the matched part. It is "" because the match starts from the beginning.
There are other RegExps that work as well like /_(.*)/ given by Chandu in a previous answer.
The /^.*?_/ has the benefit that you can understand what it does without having to know about the special role capturing groups play with replace().
In Win7 (and Vista I think), you can Shift+Right Click
the file in question and select Copy as path
to get the full network path. Note: if the shared drive is mapped to a letter, you will get that path instead (ie: X:\someguy\somefile.xls
)
input.next() takes in the first whitsepace-delimited word of the input string. So by design it does what you've described. Try input.nextLine()
.
I actually did a research in this topic for months in my free time and came up with a benchmark and here is a code to benchmark all the different ways to read a File line by line.The individual performance may vary based on the underlying system. I ran on a windows 10 Java 8 Intel i5 HP laptop:Here is the code.
import java.io.*;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.stream.Stream;
public class ReadComplexDelimitedFile {
private static long total = 0;
private static final Pattern FIELD_DELIMITER_PATTERN = Pattern.compile("\\^\\|\\^");
@SuppressWarnings("unused")
private void readFileUsingScanner() {
String s;
try (Scanner stdin = new Scanner(new File(this.getClass().getResource("input.txt").getPath()))) {
while (stdin.hasNextLine()) {
s = stdin.nextLine();
String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
total = total + fields.length;
}
} catch (Exception e) {
System.err.println("Error");
}
}
//Winner
private void readFileUsingCustomBufferedReader() {
try (CustomBufferedReader stdin = new CustomBufferedReader(new FileReader(new File(this.getClass().getResource("input.txt").getPath())))) {
String s;
while ((s = stdin.readLine()) != null) {
String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
total += fields.length;
}
} catch (Exception e) {
System.err.println("Error");
}
}
private void readFileUsingBufferedReader() {
try (BufferedReader stdin = new BufferedReader(new FileReader(new File(this.getClass().getResource("input.txt").getPath())))) {
String s;
while ((s = stdin.readLine()) != null) {
String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
total += fields.length;
}
} catch (Exception e) {
System.err.println("Error");
}
}
private void readFileUsingLineReader() {
try (LineNumberReader stdin = new LineNumberReader(new FileReader(new File(this.getClass().getResource("input.txt").getPath())))) {
String s;
while ((s = stdin.readLine()) != null) {
String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
total += fields.length;
}
} catch (Exception e) {
System.err.println("Error");
}
}
private void readFileUsingStreams() {
try (Stream<String> stream = Files.lines((new File(this.getClass().getResource("input.txt").getPath())).toPath())) {
total += stream.mapToInt(s -> FIELD_DELIMITER_PATTERN.split(s, 0).length).sum();
} catch (IOException e1) {
e1.printStackTrace();
}
}
private void readFileUsingBufferedReaderFileChannel() {
try (FileInputStream fis = new FileInputStream(this.getClass().getResource("input.txt").getPath())) {
try (FileChannel inputChannel = fis.getChannel()) {
try (CustomBufferedReader stdin = new CustomBufferedReader(Channels.newReader(inputChannel, "UTF-8"))) {
String s;
while ((s = stdin.readLine()) != null) {
String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
total = total + fields.length;
}
}
} catch (Exception e) {
System.err.println("Error");
}
} catch (Exception e) {
System.err.println("Error");
}
}
public static void main(String args[]) {
//JVM wamrup
for (int i = 0; i < 100000; i++) {
total += i;
}
// We know scanner is slow-Still warming up
ReadComplexDelimitedFile readComplexDelimitedFile = new ReadComplexDelimitedFile();
List<Long> longList = new ArrayList<>(50);
for (int i = 0; i < 50; i++) {
total = 0;
long startTime = System.nanoTime();
//readComplexDelimitedFile.readFileUsingScanner();
long stopTime = System.nanoTime();
long timeDifference = stopTime - startTime;
longList.add(timeDifference);
}
System.out.println("Time taken for readFileUsingScanner");
longList.forEach(System.out::println);
// Actual performance test starts here
longList = new ArrayList<>(10);
for (int i = 0; i < 10; i++) {
total = 0;
long startTime = System.nanoTime();
readComplexDelimitedFile.readFileUsingBufferedReaderFileChannel();
long stopTime = System.nanoTime();
long timeDifference = stopTime - startTime;
longList.add(timeDifference);
}
System.out.println("Time taken for readFileUsingBufferedReaderFileChannel");
longList.forEach(System.out::println);
longList.clear();
for (int i = 0; i < 10; i++) {
total = 0;
long startTime = System.nanoTime();
readComplexDelimitedFile.readFileUsingBufferedReader();
long stopTime = System.nanoTime();
long timeDifference = stopTime - startTime;
longList.add(timeDifference);
}
System.out.println("Time taken for readFileUsingBufferedReader");
longList.forEach(System.out::println);
longList.clear();
for (int i = 0; i < 10; i++) {
total = 0;
long startTime = System.nanoTime();
readComplexDelimitedFile.readFileUsingStreams();
long stopTime = System.nanoTime();
long timeDifference = stopTime - startTime;
longList.add(timeDifference);
}
System.out.println("Time taken for readFileUsingStreams");
longList.forEach(System.out::println);
longList.clear();
for (int i = 0; i < 10; i++) {
total = 0;
long startTime = System.nanoTime();
readComplexDelimitedFile.readFileUsingCustomBufferedReader();
long stopTime = System.nanoTime();
long timeDifference = stopTime - startTime;
longList.add(timeDifference);
}
System.out.println("Time taken for readFileUsingCustomBufferedReader");
longList.forEach(System.out::println);
longList.clear();
for (int i = 0; i < 10; i++) {
total = 0;
long startTime = System.nanoTime();
readComplexDelimitedFile.readFileUsingLineReader();
long stopTime = System.nanoTime();
long timeDifference = stopTime - startTime;
longList.add(timeDifference);
}
System.out.println("Time taken for readFileUsingLineReader");
longList.forEach(System.out::println);
}
}
I had to rewrite BufferedReader to avoid synchronized and a couple of boundary conditions that is not needed.(Atleast that's what I felt.It is not unit tested so use it at your own risk.)
import com.sun.istack.internal.NotNull;
import java.io.*;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* Reads text from a character-input stream, buffering characters so as to
* provide for the efficient reading of characters, arrays, and lines.
* <p>
* <p> The buffer size may be specified, or the default size may be used. The
* default is large enough for most purposes.
* <p>
* <p> In general, each read request made of a Reader causes a corresponding
* read request to be made of the underlying character or byte stream. It is
* therefore advisable to wrap a CustomBufferedReader around any Reader whose read()
* operations may be costly, such as FileReaders and InputStreamReaders. For
* example,
* <p>
* <pre>
* CustomBufferedReader in
* = new CustomBufferedReader(new FileReader("foo.in"));
* </pre>
* <p>
* will buffer the input from the specified file. Without buffering, each
* invocation of read() or readLine() could cause bytes to be read from the
* file, converted into characters, and then returned, which can be very
* inefficient.
* <p>
* <p> Programs that use DataInputStreams for textual input can be localized by
* replacing each DataInputStream with an appropriate CustomBufferedReader.
*
* @author Mark Reinhold
* @see FileReader
* @see InputStreamReader
* @see java.nio.file.Files#newBufferedReader
* @since JDK1.1
*/
public class CustomBufferedReader extends Reader {
private final Reader in;
private char cb[];
private int nChars, nextChar;
private static final int INVALIDATED = -2;
private static final int UNMARKED = -1;
private int markedChar = UNMARKED;
private int readAheadLimit = 0; /* Valid only when markedChar > 0 */
/**
* If the next character is a line feed, skip it
*/
private boolean skipLF = false;
/**
* The skipLF flag when the mark was set
*/
private boolean markedSkipLF = false;
private static int defaultCharBufferSize = 8192;
private static int defaultExpectedLineLength = 80;
private ReadWriteLock rwlock;
/**
* Creates a buffering character-input stream that uses an input buffer of
* the specified size.
*
* @param in A Reader
* @param sz Input-buffer size
* @throws IllegalArgumentException If {@code sz <= 0}
*/
public CustomBufferedReader(@NotNull final Reader in, int sz) {
super(in);
if (sz <= 0)
throw new IllegalArgumentException("Buffer size <= 0");
this.in = in;
cb = new char[sz];
nextChar = nChars = 0;
rwlock = new ReentrantReadWriteLock();
}
/**
* Creates a buffering character-input stream that uses a default-sized
* input buffer.
*
* @param in A Reader
*/
public CustomBufferedReader(@NotNull final Reader in) {
this(in, defaultCharBufferSize);
}
/**
* Fills the input buffer, taking the mark into account if it is valid.
*/
private void fill() throws IOException {
int dst;
if (markedChar <= UNMARKED) {
/* No mark */
dst = 0;
} else {
/* Marked */
int delta = nextChar - markedChar;
if (delta >= readAheadLimit) {
/* Gone past read-ahead limit: Invalidate mark */
markedChar = INVALIDATED;
readAheadLimit = 0;
dst = 0;
} else {
if (readAheadLimit <= cb.length) {
/* Shuffle in the current buffer */
System.arraycopy(cb, markedChar, cb, 0, delta);
markedChar = 0;
dst = delta;
} else {
/* Reallocate buffer to accommodate read-ahead limit */
char ncb[] = new char[readAheadLimit];
System.arraycopy(cb, markedChar, ncb, 0, delta);
cb = ncb;
markedChar = 0;
dst = delta;
}
nextChar = nChars = delta;
}
}
int n;
do {
n = in.read(cb, dst, cb.length - dst);
} while (n == 0);
if (n > 0) {
nChars = dst + n;
nextChar = dst;
}
}
/**
* Reads a single character.
*
* @return The character read, as an integer in the range
* 0 to 65535 (<tt>0x00-0xffff</tt>), or -1 if the
* end of the stream has been reached
* @throws IOException If an I/O error occurs
*/
public char readChar() throws IOException {
for (; ; ) {
if (nextChar >= nChars) {
fill();
if (nextChar >= nChars)
return (char) -1;
}
return cb[nextChar++];
}
}
/**
* Reads characters into a portion of an array, reading from the underlying
* stream if necessary.
*/
private int read1(char[] cbuf, int off, int len) throws IOException {
if (nextChar >= nChars) {
/* If the requested length is at least as large as the buffer, and
if there is no mark/reset activity, and if line feeds are not
being skipped, do not bother to copy the characters into the
local buffer. In this way buffered streams will cascade
harmlessly. */
if (len >= cb.length && markedChar <= UNMARKED && !skipLF) {
return in.read(cbuf, off, len);
}
fill();
}
if (nextChar >= nChars) return -1;
int n = Math.min(len, nChars - nextChar);
System.arraycopy(cb, nextChar, cbuf, off, n);
nextChar += n;
return n;
}
/**
* Reads characters into a portion of an array.
* <p>
* <p> This method implements the general contract of the corresponding
* <code>{@link Reader#read(char[], int, int) read}</code> method of the
* <code>{@link Reader}</code> class. As an additional convenience, it
* attempts to read as many characters as possible by repeatedly invoking
* the <code>read</code> method of the underlying stream. This iterated
* <code>read</code> continues until one of the following conditions becomes
* true: <ul>
* <p>
* <li> The specified number of characters have been read,
* <p>
* <li> The <code>read</code> method of the underlying stream returns
* <code>-1</code>, indicating end-of-file, or
* <p>
* <li> The <code>ready</code> method of the underlying stream
* returns <code>false</code>, indicating that further input requests
* would block.
* <p>
* </ul> If the first <code>read</code> on the underlying stream returns
* <code>-1</code> to indicate end-of-file then this method returns
* <code>-1</code>. Otherwise this method returns the number of characters
* actually read.
* <p>
* <p> Subclasses of this class are encouraged, but not required, to
* attempt to read as many characters as possible in the same fashion.
* <p>
* <p> Ordinarily this method takes characters from this stream's character
* buffer, filling it from the underlying stream as necessary. If,
* however, the buffer is empty, the mark is not valid, and the requested
* length is at least as large as the buffer, then this method will read
* characters directly from the underlying stream into the given array.
* Thus redundant <code>CustomBufferedReader</code>s will not copy data
* unnecessarily.
*
* @param cbuf Destination buffer
* @param off Offset at which to start storing characters
* @param len Maximum number of characters to read
* @return The number of characters read, or -1 if the end of the
* stream has been reached
* @throws IOException If an I/O error occurs
*/
public int read(char cbuf[], int off, int len) throws IOException {
int n = read1(cbuf, off, len);
if (n <= 0) return n;
while ((n < len) && in.ready()) {
int n1 = read1(cbuf, off + n, len - n);
if (n1 <= 0) break;
n += n1;
}
return n;
}
/**
* Reads a line of text. A line is considered to be terminated by any one
* of a line feed ('\n'), a carriage return ('\r'), or a carriage return
* followed immediately by a linefeed.
*
* @param ignoreLF If true, the next '\n' will be skipped
* @return A String containing the contents of the line, not including
* any line-termination characters, or null if the end of the
* stream has been reached
* @throws IOException If an I/O error occurs
* @see java.io.LineNumberReader#readLine()
*/
String readLine(boolean ignoreLF) throws IOException {
StringBuilder s = null;
int startChar;
bufferLoop:
for (; ; ) {
if (nextChar >= nChars)
fill();
if (nextChar >= nChars) { /* EOF */
if (s != null && s.length() > 0)
return s.toString();
else
return null;
}
boolean eol = false;
char c = 0;
int i;
/* Skip a leftover '\n', if necessary */
charLoop:
for (i = nextChar; i < nChars; i++) {
c = cb[i];
if ((c == '\n')) {
eol = true;
break charLoop;
}
}
startChar = nextChar;
nextChar = i;
if (eol) {
String str;
if (s == null) {
str = new String(cb, startChar, i - startChar);
} else {
s.append(cb, startChar, i - startChar);
str = s.toString();
}
nextChar++;
return str;
}
if (s == null)
s = new StringBuilder(defaultExpectedLineLength);
s.append(cb, startChar, i - startChar);
}
}
/**
* Reads a line of text. A line is considered to be terminated by any one
* of a line feed ('\n'), a carriage return ('\r'), or a carriage return
* followed immediately by a linefeed.
*
* @return A String containing the contents of the line, not including
* any line-termination characters, or null if the end of the
* stream has been reached
* @throws IOException If an I/O error occurs
* @see java.nio.file.Files#readAllLines
*/
public String readLine() throws IOException {
return readLine(false);
}
/**
* Skips characters.
*
* @param n The number of characters to skip
* @return The number of characters actually skipped
* @throws IllegalArgumentException If <code>n</code> is negative.
* @throws IOException If an I/O error occurs
*/
public long skip(long n) throws IOException {
if (n < 0L) {
throw new IllegalArgumentException("skip value is negative");
}
rwlock.readLock().lock();
long r = n;
try{
while (r > 0) {
if (nextChar >= nChars)
fill();
if (nextChar >= nChars) /* EOF */
break;
if (skipLF) {
skipLF = false;
if (cb[nextChar] == '\n') {
nextChar++;
}
}
long d = nChars - nextChar;
if (r <= d) {
nextChar += r;
r = 0;
break;
} else {
r -= d;
nextChar = nChars;
}
}
} finally {
rwlock.readLock().unlock();
}
return n - r;
}
/**
* Tells whether this stream is ready to be read. A buffered character
* stream is ready if the buffer is not empty, or if the underlying
* character stream is ready.
*
* @throws IOException If an I/O error occurs
*/
public boolean ready() throws IOException {
rwlock.readLock().lock();
try {
/*
* If newline needs to be skipped and the next char to be read
* is a newline character, then just skip it right away.
*/
if (skipLF) {
/* Note that in.ready() will return true if and only if the next
* read on the stream will not block.
*/
if (nextChar >= nChars && in.ready()) {
fill();
}
if (nextChar < nChars) {
if (cb[nextChar] == '\n')
nextChar++;
skipLF = false;
}
}
} finally {
rwlock.readLock().unlock();
}
return (nextChar < nChars) || in.ready();
}
/**
* Tells whether this stream supports the mark() operation, which it does.
*/
public boolean markSupported() {
return true;
}
/**
* Marks the present position in the stream. Subsequent calls to reset()
* will attempt to reposition the stream to this point.
*
* @param readAheadLimit Limit on the number of characters that may be
* read while still preserving the mark. An attempt
* to reset the stream after reading characters
* up to this limit or beyond may fail.
* A limit value larger than the size of the input
* buffer will cause a new buffer to be allocated
* whose size is no smaller than limit.
* Therefore large values should be used with care.
* @throws IllegalArgumentException If {@code readAheadLimit < 0}
* @throws IOException If an I/O error occurs
*/
public void mark(int readAheadLimit) throws IOException {
if (readAheadLimit < 0) {
throw new IllegalArgumentException("Read-ahead limit < 0");
}
rwlock.readLock().lock();
try {
this.readAheadLimit = readAheadLimit;
markedChar = nextChar;
markedSkipLF = skipLF;
} finally {
rwlock.readLock().unlock();
}
}
/**
* Resets the stream to the most recent mark.
*
* @throws IOException If the stream has never been marked,
* or if the mark has been invalidated
*/
public void reset() throws IOException {
rwlock.readLock().lock();
try {
if (markedChar < 0)
throw new IOException((markedChar == INVALIDATED)
? "Mark invalid"
: "Stream not marked");
nextChar = markedChar;
skipLF = markedSkipLF;
} finally {
rwlock.readLock().unlock();
}
}
public void close() throws IOException {
rwlock.readLock().lock();
try {
in.close();
} finally {
cb = null;
rwlock.readLock().unlock();
}
}
public Stream<String> lines() {
Iterator<String> iter = new Iterator<String>() {
String nextLine = null;
@Override
public boolean hasNext() {
if (nextLine != null) {
return true;
} else {
try {
nextLine = readLine();
return (nextLine != null);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
@Override
public String next() {
if (nextLine != null || hasNext()) {
String line = nextLine;
nextLine = null;
return line;
} else {
throw new NoSuchElementException();
}
}
};
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
iter, Spliterator.ORDERED | Spliterator.NONNULL), false);
}
}
And now the results:
Time taken for readFileUsingBufferedReaderFileChannel 2902690903 1845190694 1894071377 1815161868 1861056735 1867693540 1857521371 1794176251 1768008762 1853089582
Time taken for readFileUsingBufferedReader 2022837353 1925901163 1802266711 1842689572 1899984555 1843101306 1998642345 1821242301 1820168806 1830375108
Time taken for readFileUsingStreams 1992855461 1930827034 1850876033 1843402533 1800378283 1863581324 1810857226 1798497108 1809531144 1796345853
Time taken for readFileUsingCustomBufferedReader 1759732702 1765987214 1776997357 1772999486 1768559162 1755248431 1744434555 1750349867 1740582606 1751390934
Time taken for readFileUsingLineReader 1845307174 1830950256 1829847321 1828125293 1827936280 1836947487 1832186310 1820276327 1830157935 1829171481
Process finished with exit code 0
Inference: The test was run on a 200 MB file. The test was repeated several times. The data looked like this
Start Date^|^Start Time^|^End Date^|^End Time^|^Event Title ^|^All Day Event^|^No End Time^|^Event Description^|^Contact ^|^Contact Email^|^Contact Phone^|^Location^|^Category^|^Mandatory^|^Registration^|^Maximum^|^Last Date To Register
9/5/2011^|^3:00:00 PM^|^9/5/2011^|^^|^Social Studies Dept. Meeting^|^N^|^Y^|^Department meeting^|^Chris Gallagher^|^[email protected]^|^814-555-5179^|^High School^|^2^|^N^|^N^|^25^|^9/2/2011
Bottomline not much difference between BufferedReader and my CustomReader and it is very miniscule and hence you can use this to read your file.
Trust me you don't have to break your head.use BufferedReader with readLine,it is properly tested.At worst if you feel you can improve it just override and change it to StringBuilder instead of StringBuffer just to shave off half a second
To be efficient, and random, it might be best to have two different queries.
Something like...
SELECT table_id FROM table
Then, in your chosen language, pick a random id, then pull that row's data.
SELECT * FROM table WHERE table_id = $rand_id
But that's not really a good idea if you're expecting to have lots of rows in the table. It would be better if you put some kind of limit on what you randomly select from. For publications, maybe randomly pick from only items posted within the last year.
#logo {
width: 400px;
height: 200px;
/*Scale down will take the necessary specified space that is 400px x 200px without stretching the image*/
object-fit:scale-down;
}
You can try something like Routes.js
import React, { Component } from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom';
import FrontPage from './FrontPage';
import Dashboard from './Dashboard';
import AboutPage from './AboutPage';
import Backend from './Backend';
import Homepage from './Homepage';
import UserPage from './UserPage';
class Routes extends Component {
render() {
return (
<div>
<Route exact path="/" component={FrontPage} />
<Route exact path="/home" component={Homepage} />
<Route exact path="/about" component={AboutPage} />
<Route exact path="/admin" component={Backend} />
<Route exact path="/admin/home" component={Dashboard} />
<Route exact path="/users" component={UserPage} />
</div>
)
}
}
export default Routes
App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { BrowserRouter as Router, Route } from 'react-router-dom'
import Routes from './Routes';
class App extends Component {
render() {
return (
<div className="App">
<Router>
<Routes/>
</Router>
</div>
);
}
}
export default App;
I think you can achieve the same from here also.
Try this.. very easy to understand & implementation...
You can download sample code directly here https://github.com/Tech-Dev-Mobile/Json-Sample
- (void)simpleJsonParsingPostMetod
{
#warning set webservice url and parse POST method in JSON
//-- Temp Initialized variables
NSString *first_name;
NSString *image_name;
NSData *imageData;
//-- Convert string into URL
NSString *urlString = [NSString stringWithFormat:@"demo.com/your_server_db_name/service/link"];
NSMutableURLRequest *request =[[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
//-- Append data into posr url using following method
NSMutableData *body = [NSMutableData data];
//-- For Sending text
//-- "firstname" is keyword form service
//-- "first_name" is the text which we have to send
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",@"firstname"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@",first_name] dataUsingEncoding:NSUTF8StringEncoding]];
//-- For sending image into service if needed (send image as imagedata)
//-- "image_name" is file name of the image (we can set custom name)
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition:form-data; name=\"file\"; filename=\"%@\"\r\n",image_name] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//-- Sending data into server through URL
[request setHTTPBody:body];
//-- Getting response form server
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//-- JSON Parsing with response data
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
NSLog(@"Result = %@",result);
}
Swift 3 syntax:
tableView.tableFooterView = UIView(frame: .zero)
Swift syntax: < 2.0
tableView.tableFooterView = UIView(frame: CGRect.zeroRect)
Swift 2.0 syntax:
tableView.tableFooterView = UIView(frame: CGRect.zero)
Check this answer: https://stackoverflow.com/a/7346598/1764509
$.getJSON("test.json", function(json) {
console.log(json); // this will show the info it in firebug console
});
If you are developing a cordova app, make sure to change the version and bundle identifier in the config.xml
as well
When using a glob pattern, a question mark represents a single character and an asterisk represents a sequence of zero or more characters:
if [[ $gg == ????grid* ]] ; then echo $gg; fi
When using a regular expression, a dot represents a single character and an asterisk represents zero or more of the preceding character. So ".*
" represents zero or more of any character, "a*
" represents zero or more "a", "[0-9]*
" represents zero or more digits. Another useful one (among many) is the plus sign which represents one or more of the preceding character. So "[a-z]+
" represents one or more lowercase alpha character (in the C locale - and some others).
if [[ $gg =~ ^....grid.*$ ]] ; then echo $gg; fi
$('#id').removeAttr('required');?????
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
Suppose you have following lines of code
MyUrl = "www.google.com" #Your url goes here
urllib.urlretrieve(MyUrl)
If you are receiving following error message
AttributeError: module 'urllib' has no attribute 'urlretrieve'
Then you should try following code to fix the issue:
import urllib.request
MyUrl = "www.google.com" #Your url goes here
urllib.request.urlretrieve(MyUrl)
The current answer is outdated. Here's the up-to-date flow:
The approach outlined here still works (10.12.2020) as confirmed by alexwhan.
We will use the YouTube Data API for our example. Make changes accordingly.
Make sure you have enabled your desired API for your project.
https://console.cloud.google.com/apis/credentials
https://oauth.pstmn.io/v1/callback
We will use the file later to authenticate Postman.
Click here to see the settings
You can find everything else you need in your .json file.
Ignore the browser message "Not safe" etc. This will be shown until your app has been screened by Google officials. In this case it will always be shown since Postman is the app.
Base on @ashakirov answer, here is my extension to show/hide view with fade animation
fun View.fadeVisibility(visibility: Int, duration: Long = 400) {
val transition: Transition = Fade()
transition.duration = duration
transition.addTarget(this)
TransitionManager.beginDelayedTransition(this.parent as ViewGroup, transition)
this.visibility = visibility
}
Example using
view.fadeVisibility(View.VISIBLE)
view.fadeVisibility(View.GONE, 2000)
i believe you can use
CREATE TABLE test (
id INTEGER PRIMARY KEY AUTOINCREMENT,
t TIMESTAMP
DEFAULT CURRENT_TIMESTAMP
);
as of version 3.1 (source)
Here is a YouTube video that explains exactly what you're wanting to do: Save and load a Keras model
There are three different saving methods that Keras makes available. These are described in the video link above (with examples), as well as below.
First, the reason you're receiving the error is because you're calling load_model
incorrectly.
To save and load the weights of the model, you would first use
model.save_weights('my_model_weights.h5')
to save the weights, as you've displayed. To load the weights, you would first need to build your model, and then call load_weights
on the model, as in
model.load_weights('my_model_weights.h5')
Another saving technique is model.save(filepath)
. This save
function saves:
To load this saved model, you would use the following:
from keras.models import load_model
new_model = load_model(filepath)'
Lastly, model.to_json()
, saves only the architecture of the model. To load the architecture, you would use
from keras.models import model_from_json
model = model_from_json(json_string)
It happens because Build Tools revision 24.4.1 doesn't exist.
The latest version is 23.0.2.
These tools is included in the SDK package and installed in the <sdk>/build-tools/
directory.
Don't confuse the Android SDK Tools with SDK Build Tools.
Change in your build.gradle
android {
buildToolsVersion "23.0.2"
// ...
}
I suggest to use the name of the computer, e.g.http://mymac:1337/
. Works for me perfect without any configuration required and I don't have to care about changing IP addresses due DHCP.
For set grouped style in ui itself:-Select the TableView then change the "style"(in attribute inspector)) from plain to Grouped.
Its very simple:
"@+..." - create new
"@..." - link on existing
Source: https://developer.android.com/guide/topics/resources/layout-resource.html#idvalue
You can use with this format (tested on Laravel 5.5). In my case I used it for gettting the data of database connections and use on Controller:
$User = env('DB_USERNAMEchild','');
$Pass = env('DB_PASSWORDchild','');
The second parameter can be null, or set any default in case of DB_USERNAMEchild is null.
Your .env file can be the same:
DB_HOST=localhost
DB_DATABASE=FATHERBD
DB_USERNAME=root
DB_PASSWORD=password
DB_DATABASEchild=ZTEST
DB_USERNAMEchild=root
DB_PASSWORDchild=passwordofchild
You can change the last line to following (assuming you want to return 0 when there is nothing in db):
return OrdersPerHour == null ? 0 : OrdersPerHour.Value;
if a device has an SD card, you use:
Environment.getExternalStorageState()
if you don't have an SD card, you use:
Environment.getDataDirectory()
if there is no SD card, you can create your own directory on the device locally.
//if there is no SD card, create new directory objects to make directory on device
if (Environment.getExternalStorageState() == null) {
//create new file directory object
directory = new File(Environment.getDataDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(Environment.getDataDirectory()
+ "/Robotium-Screenshots/");
/*
* this checks to see if there are any previous test photo files
* if there are any photos, they are deleted for the sake of
* memory
*/
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length != 0) {
for (int ii = 0; ii <= dirFiles.length; ii++) {
dirFiles[ii].delete();
}
}
}
// if no directory exists, create new directory
if (!directory.exists()) {
directory.mkdir();
}
// if phone DOES have sd card
} else if (Environment.getExternalStorageState() != null) {
// search for directory on SD card
directory = new File(Environment.getExternalStorageDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(
Environment.getExternalStorageDirectory()
+ "/Robotium-Screenshots/");
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length > 0) {
for (int ii = 0; ii < dirFiles.length; ii++) {
dirFiles[ii].delete();
}
dirFiles = null;
}
}
// if no directory exists, create new directory to store test
// results
if (!directory.exists()) {
directory.mkdir();
}
}// end of SD card checking
add permissions on your manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Happy coding..
I had same issue in my case, the cause was connection was not embedded and incompatibility of Oracle Client.
SOLUTION:
My Environment:SQL SERVER 2014 64bit Oracle Client 32 bit
For include/embed Connection
for SQL SSIS Catalog/Job schedule set the configuration follow steps in picture
I tried to post detail step by step pictures, but Stack Overflow does not allow that due to reputation. Hope I later will update this post.
A solution is to add captures for the preceding and following text:
str.replace(/(.*name="\w+)(\d+)(\w+".*)/, "$1!NEW_ID!$3")
Use one way flow syntax property binding:
<div [innerHTML]="comment"></div>
From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script>
tag but keeps safe content such as the <b>
element."
If you install macports you can install gcc select, and then choose your gcc version.
/opt/local/bin/port install gcc_select
To see your versions use
port select --list gcc
To select a version use
sudo port select --set gcc gcc40
Hey Having trouble viewing documents produced on Windows?
You can try a fine solution easy:
yum install curl cabextract xorg-x11-font-utils fontconfig
After this I need reboot my system CentOS6.
As Jon Skeet already said, java.util.Date
does not have a time zone. A Date
object represents a number of milliseconds since January 1, 1970, 12:00 AM, UTC. It does not contain time zone information.
When you format a Date object into a string, for example by using SimpleDateFormat
, then you can set the time zone on the DateFormat
object to let it know in which time zone you want to display the date and time:
Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Use Madrid's time zone to format the date in
df.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
System.out.println("Date and time in Madrid: " + df.format(date));
If you want the local time zone of the computer that your program is running on, use:
df.setTimeZone(TimeZone.getDefault());
Mozilla Developer Network has a nice description and example of onbeforeunload.
If you want to warn the user before leaving the page if your page is dirty (i.e. if user has entered some data):
window.addEventListener('beforeunload', function(e) {
var myPageIsDirty = ...; //you implement this logic...
if(myPageIsDirty) {
//following two lines will cause the browser to ask the user if they
//want to leave. The text of this dialog is controlled by the browser.
e.preventDefault(); //per the standard
e.returnValue = ''; //required for Chrome
}
//else: user is allowed to leave without a warning dialog
});
Put a Console.Read() as the last line in your program. That will prevent it from closing until you press a key
static void Main(string[] args)
{
StringAddString s = new StringAddString();
Console.Read();
}
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 was looking to do this myself, and I wasnt satisfied with any of the answers provided simply because, I believe, they are quadratic time, and I need to do this on lists hundreds of items long.
I ended up extending jquery, and my solution uses jquery, but could easily be modified to use straight javascript.
I only access each item twice, and perform one linearithmic sort, so this should, I think, work out to be a lot faster on large datasets, though I freely confess I could be mistaken there:
sortList: function() {
if (!this.is("ul") || !this.length)
return
else {
var getData = function(ul) {
var lis = ul.find('li'),
liData = {
liTexts : []
};
for(var i = 0; i<lis.length; i++){
var key = $(lis[i]).text().trim().toLowerCase().replace(/\s/g, ""),
attrs = lis[i].attributes;
liData[key] = {},
liData[key]['attrs'] = {},
liData[key]['html'] = $(lis[i]).html();
liData.liTexts.push(key);
for (var j = 0; j < attrs.length; j++) {
liData[key]['attrs'][attrs[j].nodeName] = attrs[j].nodeValue;
}
}
return liData;
},
processData = function (obj){
var sortedTexts = obj.liTexts.sort(),
htmlStr = '';
for(var i = 0; i < sortedTexts.length; i++){
var attrsStr = '',
attributes = obj[sortedTexts[i]].attrs;
for(attr in attributes){
var str = attr + "=\'" + attributes[attr] + "\' ";
attrsStr += str;
}
htmlStr += "<li "+ attrsStr + ">" + obj[sortedTexts[i]].html+"</li>";
}
return htmlStr;
};
this.html(processData(getData(this)));
}
}
Just check the implementation of source code by command click:
private void initWindowDecorActionBar() {
Window window = getWindow();
// Initializing the window decor can change window feature flags.
// Make sure that we have the correct set before performing the test below.
window.getDecorView();
if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
return;
}
mActionBar = new WindowDecorActionBar(this);
mActionBar.setDefaultDisplayHomeAsUpEnabled(mEnableDefaultActionBarUp);
mWindow.setDefaultIcon(mActivityInfo.getIconResource());
mWindow.setDefaultLogo(mActivityInfo.getLogoResource());
}
requestWindowFeature(Window.FEATURE_ACTION_BAR); Fixed my issue as I saw requestWindowFeature(Window.FEATURE_ACTION_BAR) is failing; code is open source use it !!
Basically a modified syntax of function declaration/definitions:
a2dd.h
class A2DD
{
private:
int gx;
int gy;
public:
A2DD(int x,int y);
int getSum();
};
a2dd.cpp
A2DD::A2DD(int x,int y)
{
gx = x;
gy = y;
}
int A2DD::getSum()
{
return gx + gy;
}
In your case removing ./ should solve the issue. I had another case wherein I was using a directory from the parent directory and docker can only access files present below the directory where Dockerfile is present so if I have a directory structure /root/dir and Dockerfile /root/dir/Dockerfile
I cannot copy do the following
COPY root/src /opt/src
I admire all these efforts to convert a menu to a menubar because I detest trying to hack CSS. It just feels like I'm meddling with powers I can't possibly ever understand! I think it's much easier to add the menubar files available at the menubar branch of jquery ui.
I downloaded the full jquery ui css bundled file from the jquery ui download site
In the head of my document I put the jquery ui css file that contains everything (I'm on version 1.9.x at the moment) followed by the specific CSS file for the menubar widget downloaded from the menubar branch of jquery ui
<link type="text/css" href="css/jquery-ui.css" rel="stylesheet" />
<link type="text/css" href="css/jquery.ui.menubar.css" rel="stylesheet" />
Don't forget the images folder with all the little icons used by jQuery UI needs to be in the same folder as the jquery-ui.css file.
Then at the end the body I have:
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.9.0.custom.min.js"></script>
<script type="text/javascript" src="js/menubar/jquery.ui.menubar.js"></script>
That's a copy of an up-to-date version of jQuery, followed by a copy of the jQuery UI file, then the menubar module downloaded from the menubar branch of jquery ui
The menubar CSS file is refreshingly short:
.ui-menubar { list-style: none; margin: 0; padding-left: 0; }
.ui-menubar-item { float: left; }
.ui-menubar .ui-button { float: left; font-weight: normal; border-top-width: 0 !important; border-bottom-width: 0 !important; margin: 0; outline: none; }
.ui-menubar .ui-menubar-link { border-right: 1px dashed transparent; border-left: 1px dashed transparent; }
.ui-menubar .ui-menu { width: 200px; position: absolute; z-index: 9999; font-weight: normal; }
but the menubar JavaScript file is 328 lines - too long to quote here. With it, you can simply call menubar() like this example:
$("#menu").menubar({
autoExpand: true,
menuIcon: true,
buttons: true,
select: select
});
As I said, I admire all the attempts to hack the menu object to turn it into a horizontal bar, but I found all of them lacked some standard feature of a horizontal menu bar. I'm not sure why this widget is not bundled with jQuery UI yet, but presumably there are still some bugs to iron out. For instance, I tried it in IE 7 Quirks Mode and the positioning was strange, but it looks great in Firefox, Safari and IE 8+.
var QueryNew = _context.Appointments.Include(x => x.Employee).Include(x => x.city).Where(x => x.CreatedOn >= FromDate).Where(x => x.CreatedOn <= ToDate).Where(x => x.IsActive == true).ToList();
Due to updates and changes overtime, version compatibility start causing issues with configuration.
Your webpack.config.js should be like this you can also configure how ever you dim fit.
var path = require('path');
var webpack = require("webpack");
module.exports = {
entry: './src/js/app.js',
devtool: 'source-map',
mode: 'development',
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: ["babel-loader"]
},{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}]
},
output: {
path: path.resolve(__dirname, './src/vendor'),
filename: 'bundle.min.js'
}
};
Another Thing to notice it's the change of args, you should read babel documentation https://babeljs.io/docs/en/presets
.babelrc
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
NB: you have to make sure you have the above @babel/preset-env & @babel/preset-react installed in your package.json dependencies
char a[2]
defines an array of char
's. a
is a pointer to the memory at the beginning of the array and using ==
won't actually compare the contents of a
with 'ab'
because they aren't actually the same types, 'ab'
is integer type. Also 'ab'
should be "ab"
otherwise you'll have problems here too. To compare arrays of char you'd want to use strcmp.
Something that might be illustrative is looking at the typeid
of 'ab'
:
#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
int some_int =5;
std::cout << typeid('ab').name() << std::endl;
std::cout << typeid(some_int).name() << std::endl;
return 0;
}
on my system this returns:
i
i
showing that 'ab'
is actually evaluated as an int.
If you were to do the same thing with a std::string then you would be dealing with a class and std::string has operator ==
overloaded and will do a comparison check when called this way.
If you wish to compare the input with the string "ab" in an idiomatic c++ way I suggest you do it like so:
#include <iostream>
#include <string>
using namespace std;
int main(){
string a;
cout<<"enter ab ";
cin>>a;
if(a=="ab"){
cout<<"correct";
}
return 0;
}
This one is due to:
if(a=='ab')
, here, a
is const char*
type (ie : array of char)
'ab'
is a constant value,which isn't evaluated as string (because of single quote) but will be evaluated as integer.
Since char
is a primitive type inherited from C, no operator ==
is defined.
the good code should be:
if(strcmp(a,"ab")==0)
, then you'll compare a const char*
to another const char*
using strcmp
.
I use this query here to get all relevant info (relevant for me, at least :-)) from SQL Server:
SELECT
SERVERPROPERTY('productversion') as 'Product Version',
SERVERPROPERTY('productlevel') as 'Product Level',
SERVERPROPERTY('edition') as 'Product Edition',
SERVERPROPERTY('buildclrversion') as 'CLR Version',
SERVERPROPERTY('collation') as 'Default Collation',
SERVERPROPERTY('instancename') as 'Instance',
SERVERPROPERTY('lcid') as 'LCID',
SERVERPROPERTY('servername') as 'Server Name'
That gives you an output something like this:
Product Version Product Level Product Edition CLR Version
10.0.2531.0 SP1 Developer Edition (64-bit) v2.0.50727
Default Collation Instance LCID Server Name
Latin1_General_CI_AS NULL 1033 *********
Align vertically is difficult because text descent and ascent happened, lots of guys used Paint.getTextBounds() to retrieve the TextWidth and TextHeight, but it doesn't make the text center very much. Here we can use Paint.measureText() to calculate the TextWidth, the TextHeight we simply do subtracting with descent and ascent, then we got the most approach TextSize, the following work is fairly easy for each other.
// the Paint instance(should be assign as a field of class).
Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setTextSize(getResources().getDimension(R.dimen.btn_textsize));
// the display area.
Rect areaRect = new Rect(0, 0, 240, 60);
// draw the background style (pure color or image)
mPaint.setColor(Color.BLACK);
yourCanvas.drawRect(areaRect, mPaint);
String pageTitle = "????";
RectF bounds = new RectF(areaRect);
// measure text width
bounds.right = mPaint.measureText(pageTitle, 0, pageTitle.length());
// measure text height
bounds.bottom = mPaint.descent() - mPaint.ascent();
bounds.left += (areaRect.width() - bounds.right) / 2.0f;
bounds.top += (areaRect.height() - bounds.bottom) / 2.0f;
mPaint.setColor(Color.WHITE);
yourCanvas.drawText(pageTitle, bounds.left, bounds.top - mPaint.ascent(), mPaint);
By the way, we highly recommend use RectF rather than Rect because the positions need more accurate values, in my experience, RectF done the top&bottom deviation just one pixel on xhdpi device, Rect would be two more.
Please use
HashMap<Integer, myObject> myMap = new HashMap<Integer, myObject>();
Unfortunately, none of the above answers worked for me, although all answers lead to the solution and eventually to my solution, here is the snippet if it helps someone. Thanks
This can be solved with the bash file, due to the layered architecture of the Docker, cron service doesn't get initiated with RUN/CMD/ENTRYPOINT commands.
Simply add a bash file which will initiate the cron and other services (if required)
DockerFile
FROM gradle:6.5.1-jdk11 AS build
# apt
RUN apt-get update
RUN apt-get -y install cron
# Setup cron to run every minute to print (you can add/update your cron here)
RUN touch /var/log/cron-1.log
RUN (crontab -l ; echo "* * * * * echo testing cron.... >> /var/log/cron-1.log 2>&1") | crontab
# entrypoint.sh
RUN chmod +x entrypoint.sh
CMD ["bash","entrypoint.sh"]
entrypoint.sh
#!/bin/sh
service cron start & tail -f /var/log/cron-2.log
If any other service is also required to run along with cron then add that service with &
in the same command, for example: /opt/wildfly/bin/standalone.sh & service cron start & tail -f /var/log/cron-2.log
Once you will get into the docker container there you can see that testing cron....
will be getting printed every minute in file: /var/log/cron-1.log
The main reason for this is when the database is open somewhere else.
This could be as already said by many others:
When recently I had the same problem although different versions, I started to search for the reason.
In my case I had an excel file that queried data from the database.
In case the excel file is opened before the database, access would give this error.
Conclusion:
Check all files/connections related to the database. An open ODBC connection or query used in excel (my case) open the mdb file and will make it readonly.
Disclaimer- The main source of some definitions are wikipedia, any suggestion to improve my answer is welcome.
Although this post has an accepted answer and is a good one I was still in confusion and would like to add some more clarification regarding the difference between these terms.
(1)FULL BINARY TREE- A full binary tree is a binary tree in which every node other than the leaves has two children.This is also called strictly binary tree.
The above two are the examples of full or strictly binary tree.
(2)COMPLETE BINARY TREE- Now, the definition of complete binary tree is quite ambiguous, it states :- A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. It can have between 1 and 2h nodes, as far left as possible, at the last level h
Notice the lines in italic.
The ambiguity lies in the lines in italics , "except possibly the last" which means that the last level may also be completely filled , i.e this exception need not always be satisfied. If the exception doesn't hold then it is exactly like the second image I posted, which can also be called as perfect binary tree. So, a perfect binary tree is also full and complete but not vice-versa which will be clear by one more definition I need to state:
ALMOST COMPLETE BINARY TREE- When the exception in the definition of complete binary tree holds then it is called almost complete binary tree or nearly complete binary tree . It is just a type of complete binary tree itself , but a separate definition is necessary to make it more unambiguous.
So an almost complete binary tree will look like this, you can see in the image the nodes are as far left as possible so it is more like a subset of complete binary tree , to say more rigorously every almost complete binary tree is a complete binary tree but not vice versa . :
Updated 2021
Bootstrap 5
Custom file input no longer exists so to change Choose file...
you'd need to use JS or some CSS like this.
Bootstrap 4.4
Displaying the selected filename can also be done with plain JavaScript. Here's an example that assumes the standard custom-file-input with label that is the next sibling element to the input...
document.querySelector('.custom-file-input').addEventListener('change',function(e){
var fileName = document.getElementById("myInput").files[0].name;
var nextSibling = e.target.nextElementSibling
nextSibling.innerText = fileName
})
https://codeply.com/p/LtpNZllird
Bootstrap 4.1+
Now in Bootstrap 4.1 the "Choose file..." placeholder text is set in the custom-file-label
:
<div class="custom-file" id="customFile" lang="es">
<input type="file" class="custom-file-input" id="exampleInputFile" aria-describedby="fileHelp">
<label class="custom-file-label" for="exampleInputFile">
Select file...
</label>
</div>
Changing the "Browse" button text requires a little extra CSS or SASS. Also notice how language translation works using the lang=""
attribute.
.custom-file-input ~ .custom-file-label::after {
content: "Button Text";
}
https://codeply.com/go/gnVCj66Efp (CSS)
https://codeply.com/go/2Mo9OrokBQ (SASS)
Another Bootstrap 4.1 Option
Alternatively you can use this custom file input plugin
https://www.codeply.com/go/uGJOpHUd8L/file-input
Bootstrap 4 Alpha 6 (Original Answer)
I think there are 2 separate issues here..
<label class="custom-file" id="customFile">
<input type="file" class="custom-file-input">
<span class="custom-file-control form-control-file"></span>
</label>
1 - How the change the initial placeholder and button text
In Bootstrap 4, the initial placeholder value is set on the custom-file-control
with a CSS pseudo ::after
element based on the HTML language. The initial file button (which isn't really a button but looks like one) is set with a CSS pseudo ::before
element. These values can be overridden with CSS..
#customFile .custom-file-control:lang(en)::after {
content: "Select file...";
}
#customFile .custom-file-control:lang(en)::before {
content: "Click me";
}
2 - How to get the selected filename value, and update the input to show the value.
Once a file is selected, the value can be obtained using JavaScript/jQuery.
$('.custom-file-input').on('change',function(){
var fileName = $(this).val();
})
However, since the placeholder text for the input is a pseudo element, there's no easy way to manipulate this with Js/jQuery. You can however, have a another CSS class that hides the pseudo content once the file is selected...
.custom-file-control.selected:lang(en)::after {
content: "" !important;
}
Use jQuery to toggle the .selected
class on the .custom-file-control
once the file is selected. This will hide the initial placeholder value. Then put the filename value in the .form-control-file
span...
$('.custom-file-input').on('change',function(){
var fileName = $(this).val();
$(this).next('.form-control-file').addClass("selected").html(fileName);
})
You can then handle the file upload or re-selection as needed.
Don't know much VB.NET syntax but here's and idea
Dim source As New Bitmap("C:\image.png")
Dim target As New Bitmap(size.Width, size.Height, PixelFormat.Format24bppRgb)
Using graphics As Graphics = Graphics.FromImage(target)
graphics.DrawImage(source, new Size(48, 48))
End Using
I agree with the other answerers that in most cases (almost always) it is necessary to sanitize Your input.
But consider such code (it is for a REST controller):
$method = $_SERVER['REQUEST_METHOD'];
switch ($method) {
case 'GET':
return $this->doGet($request, $object);
case 'POST':
return $this->doPost($request, $object);
case 'PUT':
return $this->doPut($request, $object);
case 'DELETE':
return $this->doDelete($request, $object);
default:
return $this->onBadRequest();
}
It would not be very useful to apply sanitizing here (although it would not break anything, either).
So, follow recommendations, but not blindly - rather understand why they are for :)
A warning about the Jquery Caret plugin.
It will conflict with the Masked Input plugin (or vice versa). Fortunately the Masked Input plugin includes a caret() function of its own, which you can use very similarly to the Caret plugin for your basic needs - $(element).caret().begin or .end
There are two ways to connect your Android device with ADB over TCP?
Follow this steps
First use below command to get your device IP Address
adb shell ifconfig
OUTPUT of above command
wlan0 Link encap:UNSPEC Driver icnss
inet addr:XXX.XXX.X.XX Bcast:XXX.XXX.X.XXX
With the help you above command you will find the IP Address of connected device
Now use below command
adb tcpip 5555
The above command will restart this TCP port: 5555
Now use below command to connect your device
adb connect XXX.XXX.X.XXX:5555
^^^ ^^^ ^ ^^^
IP Address of device
You can use Android Studio Plugin Android device with ADB
Android WiFi ADB - IntelliJ/Android Studio Plugin
IntelliJ and Android Studio plugin created to quickly connect your Android device over WiFi to install, run and debug your applications without a USB connected. Press one button and forget about your USB cable
Please check this article for more information
First of all you can't overload initialize(*args)
as it's not called in all cases.
Your best option is to put your defaults into your migration:
add_column :accounts, :max_users, :integer, :default => 10
Second best is to place defaults into your model but this will only work with attributes that are initially nil. You may have trouble as I did with boolean
columns:
def after_initialize
if new_record?
max_users ||= 10
end
end
You need the new_record?
so the defaults don't override values loaded from the datbase.
You need ||=
to stop Rails from overriding parameters passed into the initialize method.
In Google Map API V2
You have LatLng
objects so you can't use distanceTo
(yet).
You can then use the following code considering oldPosition and newPosition are LatLng
objects :
// The computed distance is stored in results[0].
//If results has length 2 or greater, the initial bearing is stored in results[1].
//If results has length 3 or greater, the final bearing is stored in results[2].
float[] results = new float[1];
Location.distanceBetween(oldPosition.latitude, oldPosition.longitude,
newPosition.latitude, newPosition.longitude, results);
For more informations about the Location
class see this link
Check it out -
<input type="button" id="btnclick" value="click" />
var intervalA;
var intervalB;
$(document).ready(function () {
$('#btnclick').click(function () {
blinkFont();
setTimeout(function () {
clearInterval(intervalA);
clearInterval(intervalB);
}, 5000);
});
});
function blinkFont() {
document.getElementById("blink").style.color = "red"
document.getElementById("blink").style.background = "black"
intervalA = setTimeout("blinkFont()", 500);
}
function setblinkFont() {
document.getElementById("blink").style.color = "black"
document.getElementById("blink").style.background = "red"
intervalB = setTimeout("blinkFont()", 500);
}
</script>
<div id="blink" class="live-chat">
<span>This is blinking text and background</span>
</div>
Use string literal operator if C++14 (operator ""s
)
using namespace std::string_literals;
throw std::exception("Could not load config file '"s + configfile + "'"s);
or define your own if in C++11. For instance
std::string operator ""_s(const char * str, std::size_t len) {
return std::string(str, str + len);
}
Your throw statement will then look like this
throw std::exception("Could not load config file '"_s + configfile + "'"_s);
which looks nice and clean.
As Suhel Meman said in the comments:
SELECT column1, column2, column3 FROM table 1
UNION
SELECT column1, column2, column3 FROM table 2
...
would work.
But all your SELECTS
would have to consist of the same amount of columns. And because you are displaying it in one resulting table they should contain the same information.
What you might want to do, is a JOIN on Product ID or something like that. This way you would get more columns, which makes more sense most of the time.
You can add an auto generated id field in the table and select by this id
SELECT * FROM CUSTOMER WHERE CUSTOMER_ID = 3;
I have used a very simple solution. I have included a HTML element, that calls the method, in my Vue Component that I select, using Vanilla JS, and I trigger click!
In the Vue Component, I have included something like the following:
<span data-id="btnReload" @click="fetchTaskList()"><i class="fa fa-refresh"></i></span>
That I use using Vanilla JS:
const btnReload = document.querySelector('[data-id="btnReload"]');
btnReload.click();
.shadow {
-moz-box-shadow: 3px 3px 5px 6px #ccc;
-webkit-box-shadow: 3px 3px 5px 6px #ccc;
box-shadow: 3px 3px 5px 6px #ccc;
}
Use -regex
:
From the man page:
-regex pattern
File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named './fubar3', you can use the
regular expression '.*bar.' or '.*b.*3', but not 'b.*r3'.
Also, I don't believe find
supports regex extensions such as \d
. You need to use [0-9]
.
find . -regex '.*test\.log\.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]\.zip'
This worked for me
<div style="display: flex; position: absolute; width: 100%;">
<div style="white-space: nowrap; overflow: hidden;text-overflow: ellipsis;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi.
</div>
</div>
Adding position:absolute
to the parent container made it work.
PS: This is for anyone looking for a solution to dynamically truncating text.
EDIT: This was meant to be an answer for this question but since they are related and it could help someone on this question I shall also leave it here instead of deleting it.
I use this feature often enough that I add a custom button to the command bar.
According to the angularjs event docs the receiving end should be containing arguments with a structure like
@params
-- {Object} event being the event object containing info on the event
-- {Object} args that are passed by the callee (Note that this can only be one so better to send in a dictionary object always)
$scope.$on('fooEvent', function (event, args) { console.log(args) });
From your code
Also if you are trying to get a shared piece of information to be available accross different controllers there is an another way to achieve that and that is angular services.Since the services are singletons information can be stored and fetched across controllers.Simply create getter and setter functions in that service, expose these functions, make global variables in the service and use them to store the info
reinterpret_cast
cannot be used for this conversion, the code will not compile. According to C++03 standard section 5.2.10-1:
Conversions that can be performed explicitly using reinterpret_cast are listed below. No other conversion can be performed explicitly using reinterpret_cast.
This conversion is not listed in that section. Even this is invalid:
long l = reinterpret_cast<long>(i)
static_cast
is the one which has to be used here. See this and this SO questions.
//Data Table
protected DataTable tblDynamic
{
get
{
return (DataTable)ViewState["tblDynamic"];
}
set
{
ViewState["tblDynamic"] = value;
}
}
//DynamicReport_GetUserType() function for getting data from DB
System.Data.DataSet ds = manage.DynamicReport_GetUserType();
tblDynamic = ds.Tables[13];
//Add Column as "TypeName"
tblDynamic.Columns.Add(new DataColumn("TypeName", typeof(string)));
//fill column data against ds.Tables[13]
for (int i = 0; i < tblDynamic.Rows.Count; i++)
{
if (tblDynamic.Rows[i]["Type"].ToString()=="A")
{
tblDynamic.Rows[i]["TypeName"] = "Apple";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "B")
{
tblDynamic.Rows[i]["TypeName"] = "Ball";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "C")
{
tblDynamic.Rows[i]["TypeName"] = "Cat";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "D")
{
tblDynamic.Rows[i]["TypeName"] = "Dog;
}
}
To extend Rodrigo's solution a little - for requests that are executed frequently, you may only want to display the loading image if the request takes more than a minimum time interval, otherwise the image will be continually popping up and quickly disappearing
var loading = false;
$.ajaxSetup({
beforeSend: function () {
// Display loading icon if AJAX call takes >1 second
loading = true;
setTimeout(function () {
if (loading) {
// show loading image
}
}, 1000);
},
complete: function () {
loading = false;
// hide loading image
}
});
I was importing also some projects from VS2010 to VS 2012. I had the same errors. The errors disappeared when I set back Properties > Config. Properties > General > Platform Toolset to v100 (VS2010). That might not be the correct approach, however.
replace
event.preventDefault();
return false;
with
event.stopPropagation();
event.stopPropagation()
Stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.
event.preventDefault()
Prevents the browser from executing the default action. Use the method isDefaultPrevented to know whether this method was ever called (on that event object).
You need Linq - System.Xml.Linq to be precise.
You can create XML using XElement from scratch - that should pretty much sort you out.
Most probably, you didn't install any SQL Server Engine service. If no SQL Server engine is installed, no service will appear in the SQL Server Configuration Manager tool. Consider that the packages SQLManagementStudio_Architecture_Language.exe
and SQLEXPR_Architecture_Language.exe
, available in the Microsoft site contain, respectively only the Management Studio GUI Tools and the SQL Server engine.
If you want to have a full featured SQL Server installation, with the database engine and Management Studio, download the installer file of SQL Server with Advanced Services. Moreover, to have a sample database in order to perform some local tests, use the Adventure Works database.
Considering the package of SQL Server with Advanced Services, at the beginning at the installation you should see something like this (the screenshot below is about SQL Server 2008 Express, but the feature selection is very similar). The checkbox next to "Database Engine Services" must be checked. In the next steps, you will be able to configure the instance settings and other options.
Execute again the installation process and select the database engine services in the feature selection step. At the end of the installation, you should be able to see the SQL Server services in the SQL Server Configuration Manager.
First, Lateral and Cross Apply is same thing. Therefore you may also read about Cross Apply. Since it was implemented in SQL Server for ages, you will find more information about it then Lateral.
Second, according to my understanding, there is nothing you can not do using subquery instead of using lateral. But:
Consider following query.
Select A.*
, (Select B.Column1 from B where B.Fk1 = A.PK and Limit 1)
, (Select B.Column2 from B where B.Fk1 = A.PK and Limit 1)
FROM A
You can use lateral in this condition.
Select A.*
, x.Column1
, x.Column2
FROM A LEFT JOIN LATERAL (
Select B.Column1,B.Column2,B.Fk1 from B Limit 1
) x ON X.Fk1 = A.PK
In this query you can not use normal join, due to limit clause. Lateral or Cross Apply can be used when there is not simple join condition.
There are more usages for lateral or cross apply but this is most common one I found.
If Symfony 4 or 5, juste use this code (Where name is the name of your field):
$request->request->get('name');
Android’s new In-App Review system launched which lets developers ask for Play store reviews without leaving the app.
To check design guidelines and when to display a review card, refer to the official document
To implement:
implementation 'com.google.android.play:core:1.8.0'
Create a ReviewManager instance and request ReviewInfo object. The ReviewInfo object to be pre-cached and then can trigger "launchReviewFlow" to present the Review card to the user.
private var reviewInfo: ReviewInfo? = null
val manager = ReviewManagerFactory.create(context)
val request = manager.requestReviewFlow()
requestFlow.addOnCompleteListener { request ->
if (request.isSuccessful) {
//Received ReviewInfo object
reviewInfo = request.result
} else {
//Problem in receiving object
reviewInfo = null
}
reviewInfo?.let {
val flow = reviewManager.launchReviewFlow(this@MainActivity, it)
flow.addOnCompleteListener {
//Irrespective of the result, the app flow should continue
}
}
Note : It is suggested to show the review flow after the user has experienced enough of your app or game.
When to request an in-app review:
Few points before testing this:
While testing new functionalities, mostly we create a new project that would have new ApplicationId, make sure you give an ApplicationId that is already released and available in the play store.
If you have given feedback in the past for your app, in-app review API’s launchReviewFlow will not present any Review card. It simply triggers a success event.
Due to quota limitations, calling a launchReviewFlow method might not always display a dialog. It should not be linked with any click event.
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="#">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</div>
and for the css
@media ( min-width: 768px ) {
.navbar > .container {
text-align: center;
}
.navbar-header,.navbar-brand,.navbar .navbar-nav,.navbar .navbar-nav > li {
float: none;
display: inline-block;
}
.collapse.navbar-collapse {
width: auto;
clear: none;
}
}
see it live http://www.bootply.com/103172
I had the same issue. It seems the easiest solution is to just remove the remote, readd it, and fetch.
If you mean by literally putting one on the top of the other, one on the top (Same X, Y positions, but different Z position), try using the z-index
CSS attribute. This should work (untested)
<div>
<div style='z-index: 1'>1</div>
<div style='z-index: 2'>2</div>
<div style='z-index: 3'>3</div>
<div style='z-index: 4'>4</div>
</div>
This should show 4 on the top of 3, 3 on the top of 2, and so on. The higher the z-index is, the higher the element is positioned on the z-axis. I hope this helped you :)
You can use vertical-align and floating.
In most cases you want to vertical-align: middle, the image.
Here is a test: http://www.w3schools.com/cssref/tryit.asp?filename=trycss_vertical-align
vertical-align: baseline|length|sub|super|top|text-top|middle|bottom|text-bottom|initial|inherit;
For middle, the definition is: The element is placed in the middle of the parent element.
So you might want to apply that to all elements within the element.
Abstract example with clearer table and column names:
UPDATE tableName t1
INNER JOIN tableName t2 ON t2.ref_column = t1.ref_column
SET t1.column_to_update = t2.column_desired_value
As suggested by @Nico
Hope this help someone.
You can't achieve what you want with arrays. Use vectors instead, and read about the std::remove algorithm. Something like:
std::remove(array, array+5, 3)
will work on your array, but it will not shorten it (why -- because it's impossible). With vectors, it'd be something like
v.erase(std::remove(v.begin(), v.end(), 3), v.end())
Tools > Manage Add-ons, right click "Name" header and enable the "In Folder" section. go to the directory for the plugin you're interested in. Right click the plugin file, and click "remove".
You have a JSON object that contains an Array. You need to access the array results
. Change your code to:
this.data = res.json().results
This may be a bit of effort but you could download my open-source wiki project from codeplex:
http://shuttlewiki.codeplex.com
It contains a CompressJavascript project (and CompressCSS) that uses the http://yuicompressor.codeplex.com/ project.
The code should be self-explanatory but it makes combining and compressing the files a bit simnpler --- for me anyway :)
The ShuttleWiki project shows how to use it in the post-build event.
One problem with the
SELECT SQL_NO_CACHE * FROM TABLE
method is that it seems to only prevent the result of your query from being cached. However, if you're querying a database that is actively being used with the query you want to test, then other clients may cache your query, affecting your results. I am continuing to research ways around this, will edit this post if I figure one out.
WARNING:
The syntax list(groupby(...)) won't work the way that you intend. It seems to destroy the internal iterator objects, so using
for x in list(groupby(range(10))):
print(list(x[1]))
will produce:
[]
[]
[]
[]
[]
[]
[]
[]
[]
[9]
Instead, of list(groupby(...)), try [(k, list(g)) for k,g in groupby(...)], or if you use that syntax often,
def groupbylist(*args, **kwargs):
return [(k, list(g)) for k, g in groupby(*args, **kwargs)]
and get access to the groupby functionality while avoiding those pesky (for small data) iterators all together.
Remove the declaration from AppModule
, but update the AppModule
configuration to import your AddEventModule
.
.....
import { AddEventModule } from './add-event.module'; // <-- don't forget to import the AddEventModule class
@NgModule({
declarations: [
MyApp,
HomePage,
Login,
Register,
//AddEvent, <--- remove this
EventDetails
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
HttpModule,
AngularFireModule.initializeApp(config),
AddEventModule, // <--- add this import here
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
Login,
Register,
AddEvent,
EventDetails
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}, Eventdata, AuthProvider
]
})
export class AppModule {}
Also,
Note that it's important that your AddEventModule
exports the AddEvent
component if you want to use it outside that module. Luckily, you already have that configured, but if it was omitted, you would've gotten an error if you tried to use the AddEvent
component in another component of your AppModule
While binding a databound control, you can evaluate a field of the row in your data source with eval() function.
For example you can add a column to your gridview like that :
<asp:BoundField DataField="YourFieldName" />
And alternatively, this is the way with eval :
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lbl" runat="server" Text='<%# Eval("YourFieldName") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
It seems a little bit complex, but it's flexible, because you can set any property of the control with the eval() function :
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='<%# "ShowDetails.aspx?id="+Eval("Id") %>'
Text='<%# Eval("Text", "{0}") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
You've accidentally set "Pause on Exceptions" to all/uncaught exceptions.
Go to the "Sources" tab. At the bottom toolbar, toggle the button that looks like the pause symbol surrounded by a circle (4th button from the left) until the color of the circle turns black to turn it off.
main()
{
int *arr[5];
int i=31, j=5, k=19, l=71, m;
arr[0]=&i;
arr[1]=&j;
arr[2]=&k;
arr[3]=&l;
arr[4]=&m;
for(m=0; m<=4; m++)
{
printf("%d",*(arr[m]));
}
return 0;
}
If you have 32-bit Windows, this method is not working without following settings.
- Run prompt cmd.exe (important : Run As Administrator)
- type bcdedit.exe and run
- Look at the "increaseuserva" params and there is no then write following statement
- bcdedit /set increaseuserva 3072
- and again step 2 and check params
We added this settings and this block started.
if exist "$(DevEnvDir)..\tools\vsvars32.bat" (
call "$(DevEnvDir)..\tools\vsvars32.bat"
editbin /largeaddressaware "$(TargetPath)"
)
More info - command increaseuserva
: https://docs.microsoft.com/en-us/windows-hardware/drivers/devtest/bcdedit--set
I have a shared hosting on GoDaddy. I needed an answer to this question, too, and after searching around I found that it is possible.
I wrote an .htaccess file, put it in the same folder as my action page. Here are the contents of the .htaccess file:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
Here is my ajax call:
$.ajax({
url: 'http://www.mydomain.com/myactionpagefolder/gbactionpage.php', //server script to process data
type: 'POST',
xhr: function() { // custom xhr
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
}
return myXhr;
},
//Ajax events
beforeSend: beforeSendHandler,
success: completeHandler,
error: errorHandler,
// Form data
data: formData,
//Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false
});
See this article for reference:
Header set Access-Control-Allow-Origin in .htaccess doesn't work
Use this FAQ page: Apache log4net Frequently Asked Questions
About 3/4 of the way down it tells you how to enable log4net debugging by using application tracing. This will tell you where your issue is.
The basics are:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
</configuration>
And you see the trace in the standard output
The BrainFuck language. It really is!
As well as /etc/profile
which others have mentioned, some Linux systems now use a directory /etc/profile.d/
; any .sh
files in there will be sourced by /etc/profile
. It's slightly neater to keep your custom environment stuff in these files than to just edit /etc/profile
.
Also an option which is quite similar to joaquin answer:
import random
from matplotlib import pyplot
#random data
x = [random.gauss(3,1) for _ in range(400)]
y = [random.gauss(4,2) for _ in range(400)]
#plot both histograms(range from -10 to 10), bins set to 100
pyplot.hist([x,y], bins= 100, range=[-10,10], alpha=0.5, label=['x', 'y'])
#plot legend
pyplot.legend(loc='upper right')
#show it
pyplot.show()
Gives the following output:
Model.select(:rating).distinct
In my opinion, to answer this question, you need to think in terms of project life cycle and version control. In other words, does the parent pom have its own life cycle i.e. can it be released separately of the other modules or not?
If the answer is yes (and this is the case of most projects that have been mentioned in the question or in comments), then the parent pom needs his own module from a VCS and from a Maven point of view and you'll end up with something like this at the VCS level:
root
|-- parent-pom
| |-- branches
| |-- tags
| `-- trunk
| `-- pom.xml
`-- projectA
|-- branches
|-- tags
`-- trunk
|-- module1
| `-- pom.xml
|-- moduleN
| `-- pom.xml
`-- pom.xml
This makes the checkout a bit painful and a common way to deal with that is to use svn:externals
. For example, add a trunks
directory:
root
|-- parent-pom
| |-- branches
| |-- tags
| `-- trunk
| `-- pom.xml
|-- projectA
| |-- branches
| |-- tags
| `-- trunk
| |-- module1
| | `-- pom.xml
| |-- moduleN
| | `-- pom.xml
| `-- pom.xml
`-- trunks
With the following externals definition:
parent-pom http://host/svn/parent-pom/trunk
projectA http://host/svn/projectA/trunk
A checkout of trunks
would then result in the following local structure (pattern #2):
root/
parent-pom/
pom.xml
projectA/
Optionally, you can even add a pom.xml
in the trunks
directory:
root
|-- parent-pom
| |-- branches
| |-- tags
| `-- trunk
| `-- pom.xml
|-- projectA
| |-- branches
| |-- tags
| `-- trunk
| |-- module1
| | `-- pom.xml
| |-- moduleN
| | `-- pom.xml
| `-- pom.xml
`-- trunks
`-- pom.xml
This pom.xml
is a kind of "fake" pom: it is never released, it doesn't contain a real version since this file is never released, it only contains a list of modules. With this file, a checkout would result in this structure (pattern #3):
root/
parent-pom/
pom.xml
projectA/
pom.xml
This "hack" allows to launch of a reactor build from the root after a checkout and make things even more handy. Actually, this is how I like to setup maven projects and a VCS repository for large builds: it just works, it scales well, it gives all the flexibility you may need.
If the answer is no (back to the initial question), then I think you can live with pattern #1 (do the simplest thing that could possibly work).
Now, about the bonus questions:
- Where is the best place to define the various shared configuration as in source control, deployment directories, common plugins etc. (I'm assuming the parent but I've often been bitten by this and they've ended up in each project rather than a common one).
Honestly, I don't know how to not give a general answer here (like "use the level at which you think it makes sense to mutualize things"). And anyway, child poms can always override inherited settings.
- How do the maven-release plugin, hudson and nexus deal with how you set up your multi-projects (possibly a giant question, it's more if anyone has been caught out when by how a multi-project build has been set up)?
The setup I use works well, nothing particular to mention.
Actually, I wonder how the maven-release-plugin deals with pattern #1 (especially with the <parent>
section since you can't have SNAPSHOT dependencies at release time). This sounds like a chicken or egg problem but I just can't remember if it works and was too lazy to test it.
If you're hoping to use background-image: url(...);
, I don't think you can. However, if you want to play with layering, you can do something like this:
<img class="bg" src="..." />
And then some CSS:
.bg
{
width: 100%;
z-index: 0;
}
You can now layer content above the stretched image by playing with z-indexes and such. One quick note, the image can't be contained in any other elements for the width: 100%;
to apply to the whole page.
Here's a quick demo if you can't rely on background-size
: http://jsfiddle.net/bB3Uc/
Use a ArrayAdapter backed by an ArrayList. To change the data, just update the data in the list and call adapter.notifyDataSetChanged().
Try this one, I think this will works for you
update ud
set ud.assid = sale.assid
from ud
Inner join sale on ud.id = sale.udid
where sale.udid is not null
Probably it's not be correct, and a little bit longer, but I solved this problem (Android Studio) by using this:
System.out.println("Some text here");
Like this:
try {
...code here...
} catch(Exception e) {
System.out.println("Error desc: " + e.getMessage());
}
I use another approach.
Just try to find all a
where id
starts from some substring.
JS
$('a[id^=v-photos-tab]').click(function () {
alert("Handler for .click() called.");
});
HTML
<a class="nav-item nav-link active show" id="v-photos-tab-3a623245-7dc7-4a22-90d0-62705ad0c62b" data-toggle="pill" href="#v-photos-3a623245-7dc7-4a22-90d0-62705ad0c62b" role="tab" aria-controls="v-requestbase-photos" aria-selected="true"><span>Cool photos</span></a>
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
SqlCommand cmd = new SqlCommand("Delete From userTable (userName,age,birthPLace)");
GridView1.DataBind();
}
create a global temp table with a GUID in the name dynamically. Then you can work with it in your code, via dyn sql, without worry that another process calling same sproc will use it. This is useful when you dont know what to expect from the underlying selected table each time it runs so you cannot created a temp table explicitly beforehand. ie - you need to use SELECT * INTO syntax
DECLARE @TmpGlobalTable varchar(255) = 'SomeText_' + convert(varchar(36),NEWID())
-- select @TmpGlobalTable
-- build query
SET @Sql =
'SELECT * INTO [##' + @TmpGlobalTable + '] FROM SomeTable'
EXEC (@Sql)
EXEC ('SELECT * FROM [##' + @TmpGlobalTable + '] ')
EXEC ('DROP TABLE [##' + @TmpGlobalTable + ']')
PRINT 'Dropped Table ' + @TmpGlobalTable
Recursively delete all children of the file ...
public static void DeleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory()) {
for (File child : fileOrDirectory.listFiles()) {
DeleteRecursive(child);
}
}
fileOrDirectory.delete();
}
One con I can think of is if you need really fast access to your data in your view (for example, game animation data like bone positions.) It is very inefficient to keep a layer of separation in this case.
Otherwise, for most other applications which are more data driven than graphics driven, it seems like a logical way to drive a UI.
Nowadays, animating text color is included in the jQuery UI Effects Core. It's pretty small. You can make a custom download here: http://jqueryui.com/download - but you don't actually need anything but the effects core itself (not even the UI core), and it brings with it different easing functions as well.
Setting the active menu, they have the many ways to do that. Now, I share you a way to set active menu by CSS.
<a href="index.php?id=home">Home</a>
<a href="index.php?id=news">News</a>
<a href="index.php?id=about">About</a>
Now, you only set $_request["id"] == "home"
thì echo "class='active'"
, then we can do same with others.
<a href="index.php?id=home" <?php if($_REQUEST["id"]=="home"){echo "class='active'";}?>>Home</a>
<a href="index.php?id=news" <?php if($_REQUEST["id"]=="news"){echo "class='active'";}?>>News</a>
<a href="index.php?id=about" <?php if($_REQUEST["id"]=="about"){echo "class='active'";}?>>About</a>
I think it is useful with you.
You can use echo
, and redirect the output to a text file (see notes below):
rem Saved in D:\Temp\WriteText.bat
@echo off
echo This is a test> test.txt
echo 123>> test.txt
echo 245.67>> test.txt
Output:
D:\Temp>WriteText D:\Temp>type test.txt This is a test 123 245.67 D:\Temp>
Notes:
@echo off
turns off printing of each command to the console>
or >>
will write to the current directory (the directory the code is being run in).echo This is a test > test.txt
uses one >
to overwrite any file that already exists with new content.echo
statements use two >>
characters to append to the text file (add to), instead of overwriting it.type test.txt
simply types the file output to the command window. def jsonFile = new File('File Path');
JsonSlurper jsonSlurper = new JsonSlurper();
def parseJson = jsonSlurper.parse(jsonFile)
String json = JsonOutput.toJson(parseJson)
def prettyJson = JsonOutput.prettyPrint(json)
println(prettyJson)
if(A == "haha" && B == "hihi") {
//hahahihi?
}
if(A == "haha" || B != "hihi") {
//hahahihi!?
}
Open angular.json file
1.change from
"schematics": {}
to
"schematics": {
"@schematics/angular:component": {
"styleext": "scss"
}
}
"src/styles.css"
to
"src/styles.scss"
then check and rename all .css
files and update component.ts files styleUrls from .css to .scss
Some general notes.
$obj | Select-Object
? $obj | Select-Object -Property *
The latter will show all non-intrinsic, non-compiler-generated properties. The former does not appear to (always) show all Property types (in my tests, it does appear to show the CodeProperty
MemberType
consistently though -- no guarantees here).
Get-Member
does not get static members by default. You also cannot (directly) get them along with the non-static members. That is, using the switch causes only static members to be returned:
PS Y:\Power> $obj | Get-Member -Static
TypeName: System.IsFire.TurnUpProtocol
Name MemberType Definition
---- ---------- ----------
Equals Method static bool Equals(System.Object objA, System.Object objB)
...
Use the -Force
.
The
Get-Member
command uses the Force parameter to add the intrinsic members and compiler-generated members of the objects to the display.Get-Member
gets these members, but it hides them by default.
PS Y:\Power> $obj | Get-Member -Static
TypeName: System.IsFire.TurnUpProtocol
Name MemberType Definition
---- ---------- ----------
...
pstypenames CodeProperty System.Collections.ObjectModel.Collection...
psadapted MemberSet psadapted {AccessRightType, AccessRuleType,...
...
ConvertTo-Json
for depth and readable "serialization"I do not necessary recommend saving objects using JSON (use Export-Clixml
instead).
However, you can get a more or less readable output from ConvertTo-Json
, which also allows you to specify depth.
Note that not specifying Depth
implies -Depth 2
PS Y:\Power> ConvertTo-Json $obj -Depth 1
{
"AllowSystemOverload": true,
"AllowLifeToGetInTheWay": false,
"CantAnyMore": true,
"LastResortOnly": true,
...
And if you aren't planning to read it you can -Compress
it (i.e. strip whitespace)
PS Y:\Power> ConvertTo-Json $obj -Depth 420 -Compress
-InputObject
if you can (and are willing)99.9% of the time when using PowerShell: either the performance won't matter, or you don't care about the performance. However, it should be noted that avoiding the pipe when you don't need it can save some overhead and add some speed (piping, in general, is not super-efficient).
That is, if you all you have is a single $obj
handy for printing (and aren't too lazy like me sometimes to type out -InputObject
):
# select is aliased (hardcoded) to Select-Object
PS Y:\Power> select -Property * -InputObject $obj
# gm is aliased (hardcoded) to Get-Member
PS Y:\Power> gm -Force -InputObject $obj
Caveat for Get-Member -InputObject
:
If $obj is a collection (e.g. System.Object[]
), You end up getting information about the collection object itself:
PS Y:\Power> gm -InputObject $obj,$obj2
TypeName: System.Object[]
Name MemberType Definition
---- ---------- ----------
Count AliasProperty Count = Length
...
If you want to Get-Member
for each TypeName
in the collection (N.B. for each TypeName
, not for each object--a collection of N objects with all the same TypeName
will only print 1 table for that TypeName
, not N tables for each object)......just stick with piping it in directly.
The other answers are from before 2012, and they focus on "hacking" PowerShell 1.0 or PowerShell 2.0 into targeting newer versions of the .NET Framework and Common Language Runtime (CLR).
However, as has been written in many comments, since 2012 (when PowerShell 3.0 came) a much better solution is to install the newest version of PowerShell. It will automatically target CLR v4.0.30319
. This means .NET 4.0, 4.5, 4.5.1, 4.5.2, or 4.6 (expected in 2015) since all of these versions are in-place replacements of each other. Use $PSVersionTable
or see the Determine installed PowerShell version thread if you are unsure of your PowerShell version.
At the time of writing, the newest version of PowerShell is 4.0, and it can be downloaded with the Windows Management Framework (Google search link).
I had a similar problem.
Issue was there was a trigger on the table that would write changes to an audit log table. Columns were missing in audit log table.
Aside from getting decode
and encode
backwards, I think part of the answer here is actually don't use the ascii
encoding. It's probably not what you want.
To begin with, think of str
like you would a plain text file. It's just a bunch of bytes with no encoding actually attached to it. How it's interpreted is up to whatever piece of code is reading it. If you don't know what this paragraph is talking about, go read Joel's The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets right now before you go any further.
Naturally, we're all aware of the mess that created. The answer is to, at least within memory, have a standard encoding for all strings. That's where unicode
comes in. I'm having trouble tracking down exactly what encoding Python uses internally for sure, but it doesn't really matter just for this. The point is that you know it's a sequence of bytes that are interpreted a certain way. So you only need to think about the characters themselves, and not the bytes.
The problem is that in practice, you run into both. Some libraries give you a str
, and some expect a str
. Certainly that makes sense whenever you're streaming a series of bytes (such as to or from disk or over a web request). So you need to be able to translate back and forth.
Enter codecs
: it's the translation library between these two data types. You use encode
to generate a sequence of bytes (str
) from a text string (unicode
), and you use decode
to get a text string (unicode
) from a sequence of bytes (str
).
For example:
>>> s = "I look like a string, but I'm actually a sequence of bytes. \xe2\x9d\xa4"
>>> codecs.decode(s, 'utf-8')
u"I look like a string, but I'm actually a sequence of bytes. \u2764"
What happened here? I gave Python a sequence of bytes, and then I told it, "Give me the unicode
version of this, given that this sequence of bytes is in 'utf-8'
." It did as I asked, and those bytes (a heart character) are now treated as a whole, represented by their Unicode codepoint.
Let's go the other way around:
>>> u = u"I'm a string! Really! \u2764"
>>> codecs.encode(u, 'utf-8')
"I'm a string! Really! \xe2\x9d\xa4"
I gave Python a Unicode string, and I asked it to translate the string into a sequence of bytes using the 'utf-8'
encoding. So it did, and now the heart is just a bunch of bytes it can't print as ASCII; so it shows me the hexadecimal instead.
We can work with other encodings, too, of course:
>>> s = "I have a section \xa7"
>>> codecs.decode(s, 'latin1')
u'I have a section \xa7'
>>> codecs.decode(s, 'latin1')[-1] == u'\u00A7'
True
>>> u = u"I have a section \u00a7"
>>> u
u'I have a section \xa7'
>>> codecs.encode(u, 'latin1')
'I have a section \xa7'
('\xa7'
is the section character, in both
Unicode and Latin-1.)
So for your question, you first need to figure out what encoding your str
is in.
Did it come from a file? From a web request? From your database? Then the source determines the encoding. Find out the encoding of the source and use that to translate it into a unicode
.
s = [get from external source]
u = codecs.decode(s, 'utf-8') # Replace utf-8 with the actual input encoding
Or maybe you're trying to write it out somewhere. What encoding does the destination expect? Use that to translate it into a str
. UTF-8 is a good choice for plain text documents; most things can read it.
u = u'My string'
s = codecs.encode(u, 'utf-8') # Replace utf-8 with the actual output encoding
[Write s out somewhere]
Are you just translating back and forth in memory for interoperability or something? Then just pick an encoding and stick with it; 'utf-8'
is probably the best choice for that:
u = u'My string'
s = codecs.encode(u, 'utf-8')
newu = codecs.decode(s, 'utf-8')
In modern programming, you probably never want to use the 'ascii'
encoding for any of this. It's an extremely small subset of all possible characters, and no system I know of uses it by default or anything.
Python 3 does its best to make this immensely clearer simply by changing the names. In Python 3, str
was replaced with bytes
, and unicode
was replaced with str
.
A neatish way to do this would be to put this into a function:
int yourfunc() {
while(true) {
switch(msg->state) {
case MSGTYPE: // ...
break;
// ... more stuff ...
case DONE:
return;
}
}
}
Optionally (but 'bad practices'): as already suggested you could use a goto, or throw an exception inside the switch.
For those like me, who were looking for a pure Python solution without pandas
or numpy
involved, check out the following GitHub project: https://github.com/ThomIves/MatrixInverse.
It generously provides a very good explanation of how the process looks like "behind the scenes". The author has nicely described the step-by-step approach and presented some practical examples, all easy to follow.
This is just a little code snippet from there to illustrate the approach very briefly (AM
is the source matrix, IM
is the identity matrix of the same size):
def invert_matrix(AM, IM):
for fd in range(len(AM)):
fdScaler = 1.0 / AM[fd][fd]
for j in range(len(AM)):
AM[fd][j] *= fdScaler
IM[fd][j] *= fdScaler
for i in list(range(len(AM)))[0:fd] + list(range(len(AM)))[fd+1:]:
crScaler = AM[i][fd]
for j in range(len(AM)):
AM[i][j] = AM[i][j] - crScaler * AM[fd][j]
IM[i][j] = IM[i][j] - crScaler * IM[fd][j]
return IM
But please do follow the entire thing, you'll learn a lot more than just copy-pasting this code! There's a Jupyter notebook as well, btw.
Hope that helps someone, I personally found it extremely useful for my very particular task (Absorbing Markov Chain) where I wasn't able to use any non-standard packages.
<div class="row">
<div class="col-md-6">
<img src="/assets/images/ebook2.png" alt="" class="img-fluid">
</div>
<div class="col-md-6 my-auto">
<h3>Heading</h3>
<p>Some text.</p>
</div>
</div>
This line is where the magic happens <div class="col-md-6 my-auto">
, the my-auto
will center the content of the column. This works great with situations like the code sample above where you might have a variable sized image and need to have the text in the column to the right line up with it.
You are just updating the value of i
in the loop. The value of i
should also be added each time.
It is never a good idea to update the value of i
inside the for
loop. The for
loop index should only be used as a counter. In your case, changing the value of i
inside the loop will cause all sorts of confusion.
Create variable total
that holds the sum of the numbers up to i
.
So
for (int i = 0; i < positiveInteger; i++)
total += i;
let input = 12345664
const output = []
while (input !== 0) {
const roundedInput = Math.floor(input / 10)
output.push(input - roundedInput * 10)
input = roundedInput
}
console.log(output)
It can be done without printing magic strings and using TextFinder. Here's some info on it.
Basically you need a .jar file from http://yourserver.com/cli available in shell scripts, then you can use the following command to mark a build unstable:
java -jar jenkins-cli.jar set-build-result unstable
To mark build unstable on error, you can use:
failing_cmd cmd_args || java -jar jenkins-cli.jar set-build-result unstable
The problem is that jenkins-cli.jar has to be available from shell script. You can either put it in easy-to-access path, or download in via job's shell script:
wget ${JENKINS_URL}jnlpJars/jenkins-cli.jar
The LINQy way
String.Concat( "223232-1.jpg".TakeWhile(c => c != '-') )
(But, you do need to test for null ;)
Use the -I
flag to gcc properly.
gcc -I/path/to/openssl/ -o Opentest -lcrypto Opentest.c
The -I
should point to the directory containing the openssl
folder.
Try passing columns of the DataFrame
directly to matplotlib, as in the examples below, instead of extracting them as numpy arrays.
df = pd.DataFrame(np.random.randn(10,2), columns=['col1','col2'])
df['col3'] = np.arange(len(df))**2 * 100 + 100
In [5]: df
Out[5]:
col1 col2 col3
0 -1.000075 -0.759910 100
1 0.510382 0.972615 200
2 1.872067 -0.731010 500
3 0.131612 1.075142 1000
4 1.497820 0.237024 1700
plt.scatter(df.col1, df.col2, s=df.col3)
# OR (with pandas 0.13 and up)
df.plot(kind='scatter', x='col1', y='col2', s=df.col3)
colors = np.where(df.col3 > 300, 'r', 'k')
plt.scatter(df.col1, df.col2, s=120, c=colors)
# OR (with pandas 0.13 and up)
df.plot(kind='scatter', x='col1', y='col2', s=120, c=colors)
However, the easiest way I've found to create a scatter plot with legend is to call plt.scatter
once for each point type.
cond = df.col3 > 300
subset_a = df[cond].dropna()
subset_b = df[~cond].dropna()
plt.scatter(subset_a.col1, subset_a.col2, s=120, c='b', label='col3 > 300')
plt.scatter(subset_b.col1, subset_b.col2, s=60, c='r', label='col3 <= 300')
plt.legend()
From what I can tell, matplotlib simply skips points with NA x/y coordinates or NA style settings (e.g., color/size). To find points skipped due to NA, try the isnull
method: df[df.col3.isnull()]
To split a list of points into many types, take a look at numpy select
, which is a vectorized if-then-else implementation and accepts an optional default value. For example:
df['subset'] = np.select([df.col3 < 150, df.col3 < 400, df.col3 < 600],
[0, 1, 2], -1)
for color, label in zip('bgrm', [0, 1, 2, -1]):
subset = df[df.subset == label]
plt.scatter(subset.col1, subset.col2, s=120, c=color, label=str(label))
plt.legend()
I'm not familiar with grep but with Select-String you can do:
Get-ChildItem filename.txt | Select-String -Pattern <regexPattern>
You can also do that with Get-Content:
(Get-Content filename.txt) -match 'pattern'
You can use curly braces like expression with both double quotes and single quotes for space i.e.,
{" "} or {' '}
You can also use ES6 template literals i.e.,
` <li></li>` or ` ${value}`
You can also use   like below (inside span)
<span>sample text </span>
You can also use   in dangerouslySetInnerHTML when printing html content
<div dangerouslySetInnerHTML={{__html: 'sample html text: '}} />
This is a simple circle as a drawable in Android.
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
android:color="#666666"/>
<size
android:width="120dp"
android:height="120dp"/>
</shape>
You should read the XML file using specific XML modules. That way you can edit the XML document in memory and rewrite your changed XML document into the file.
Here is a quick start: http://docs.python.org/library/xml.dom.minidom.html
There are a lot of other XML utilities, which one is best depends on the nature of your XML file and in which way you want to edit it.
I use vagrant ssh
command with git ssh
on windows 7, 8.1 and Windows 10.
To install only download msysgit from msysgit project page.
And to run ssh.exe
only include the bin folter
to windows environment variables or install git from Git Download page and copy the msysgit bin folter
to C:\Program Files\Git\bin
.
// just pass your tested function name instead of myFunctionName
if ( $.isFunction($.fn.myFunctionName) ) {
console.log( 'write your code here.' );
}
Try pasting this to .htaccess and it should work.
php_value post_max_size 2000M
php_value upload_max_filesize 2500M
php_value max_execution_time 6000000
php_value max_input_time 6000000
php_value memory_limit 2500M
If you want to do this with a PHP script instead of having to run C code (or you're on a Mac like me and you can't be arsed compiling with Xcode only to wait a year for it to open), here's a PHP function that you can use to remove the embedding permissions from the font:
function convertRestrictedFont($filename) {
$font = fopen($filename,'r+');
if ($font === false) {
throw new Exception('Could not open font file.');
}
fseek($font, 12, 0);
while (!feof($font)) {
$type = '';
for ($i = 0; $i < 4; $i++) {
$type .= fgetc($font);
if (feof($font)) {
fclose($font);
throw new Exception('Could not read the table definitions of the font.');
}
}
if ($type == 'OS/2') {
// Save the location of the table definition
// containing the checksum and pointer to the data
$os2TableDefinition = ftell($font);
$checksum = 0;
for ($i = 0; $i < 4; $i++) {
fgetc($font);
if (feof($font)) {
fclose($font);
throw new Exception('Could not read the OS/2 table header of the font.');
}
}
// Get the pointer to the OS/2 table data
$os2TablePointer = ord(fgetc($font)) << 24;
$os2TablePointer |= ord(fgetc($font)) << 16;
$os2TablePointer |= ord(fgetc($font)) << 8;
$os2TablePointer |= ord(fgetc($font));
$length = ord(fgetc($font)) << 24;
$length |= ord(fgetc($font)) << 16;
$length |= ord(fgetc($font)) << 8;
$length |= ord(fgetc($font));
if (fseek($font, $os2TablePointer + 8, 0) !== 0) {
fclose($font);
throw new Exception('Could not read the embeddable type of the font.');
}
// Read the fsType before overriding it
$fsType = ord(fgetc($font)) << 8;
$fsType |= ord(fgetc($font));
error_log('Installable Embedding: ' . ($fsType == 0));
error_log('Reserved: ' . ($fsType & 1));
error_log('Restricted License: ' . ($fsType & 2));
error_log('Preview & Print: ' . ($fsType & 4));
error_log('Editable Embedding: ' . ($fsType & 8));
error_log('Reserved: ' . ($fsType & 16));
error_log('Reserved: ' . ($fsType & 32));
error_log('Reserved: ' . ($fsType & 64));
error_log('Reserved: ' . ($fsType & 128));
error_log('No subsetting: ' . ($fsType & 256));
error_log('Bitmap embedding only: ' . ($fsType & 512));
error_log('Reserved: ' . ($fsType & 1024));
error_log('Reserved: ' . ($fsType & 2048));
error_log('Reserved: ' . ($fsType & 4096));
error_log('Reserved: ' . ($fsType & 8192));
error_log('Reserved: ' . ($fsType & 16384));
error_log('Reserved: ' . ($fsType & 32768));
fseek($font, ftell($font) - 2);
// Set the two bytes of fsType to 0
fputs($font, chr(0), 1);
fputs($font, chr(0), 1);
// Go to the beginning of the OS/2 table data
fseek($font, $os2TablePointer, 0);
// Generate a new checksum based on the changed
for ($i = 0; $i < $length; $i++) {
$checksum += ord(fgetc($font));
}
fseek($font, $os2TableDefinition, 0);
fputs($font, chr($checksum >> 24), 1);
fputs($font, chr(255 & ($checksum >> 16)), 1);
fputs($font, chr(255 & ($checksum >> 8)), 1);
fputs($font, chr(255 & $checksum), 1);
fclose($font);
return true;
}
for ($i = 0; $i < 12; $i++) {
fgetc($font);
if (feof($font)) {
fclose($font);
throw new Exception('Could not skip a table definition of the font.');
}
}
}
fclose($font);
return false;
}
Make sure to backup your font file before running this code and don't blame me if it corrupts.
Original source in C can be found here.
The answer depends on the presence of other shapes, level of noise if any and invariance you want to provide for (e.g. rotation, scaling, etc). These requirements will define not only the algorithm but also required pre-procesing stages to extract features.
Template matching that was suggested above works well when shapes aren't rotated or scaled and when there are no similar shapes around; in other words, it finds a best translation in the image where template is located:
double minVal, maxVal;
Point minLoc, maxLoc;
Mat image, template, result; // template is your shape
matchTemplate(image, template, result, CV_TM_CCOEFF_NORMED);
minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc); // maxLoc is answer
Geometric hashing is a good method to get invariance in terms of rotation and scaling; this method would require extraction of some contour points.
Generalized Hough transform can take care of invariance, noise and would have minimal pre-processing but it is a bit harder to implement than other methods. OpenCV has such transforms for lines and circles.
In the case when number of shapes is limited calculating moments or counting convex hull vertices may be the easiest solution: openCV structural analysis
Or you can do this way :
((TextView)findViewById(R.id.this_is_the_id_of_textview)).setText("Test");
You could use mapvalues()
from the plyr package.
Initial data:
dat <- data.frame(HouseType = c("Semi", "Single", "Row", "Single", "Apartment", "Apartment", "Row"))
> dat
HouseType
1 Semi
2 Single
3 Row
4 Single
5 Apartment
6 Apartment
7 Row
Lookup / crosswalk table:
lookup <- data.frame(type_text = c("Semi", "Single", "Row", "Apartment"), type_num = c(1, 2, 3, 4))
> lookup
type_text type_num
1 Semi 1
2 Single 2
3 Row 3
4 Apartment 4
Create the new variable:
dat$house_type_num <- plyr::mapvalues(dat$HouseType, from = lookup$type_text, to = lookup$type_num)
Or for simple replacements you can skip creating a long lookup table and do this directly in one step:
dat$house_type_num <- plyr::mapvalues(dat$HouseType,
from = c("Semi", "Single", "Row", "Apartment"),
to = c(1, 2, 3, 4))
Result:
> dat
HouseType house_type_num
1 Semi 1
2 Single 2
3 Row 3
4 Single 2
5 Apartment 4
6 Apartment 4
7 Row 3
in my case, the war file generated didn't pick up the properties file so had to clean install again in IntelliJ editor.
aggregate(speed~dive,data=df,FUN=mean)
dive speed
1 dive1 0.7059729
2 dive2 0.5473777
try this
function global_func(...args){
for(let i of args){
console.log(i)
}
}
global_func('task_name', 'action', [{x: 'x'},{x: 'x'}], {x: 'x'}, ['x1','x2'], 1, null, undefined, false, true)
//task_name
//action
//(2) [{...},
// {...}]
// {
// x:"x"
// }
//(2) [
// "x1",
// "x2"
// ]
//1
//null
//undefined
//false
//true
//func
A simple return
statement will 'stop' or return the function; in precise terms, it 'returns' function execution to the point at which the function was called - the function is terminated without further action.
That means you could have a number of places throughout your function where it might return. Like this:
def player():
# do something here
check_winner_variable = check_winner() # check something
if check_winner_variable == '1':
return
second_test_variable = second_test()
if second_test_variable == '1':
return
# let the computer do something
computer()
With SharePoint 2013 new library, I managed to do something like this:
private void UploadToSharePoint(string p, out string newUrl) //p is path to file to load
{
string siteUrl = "https://myCompany.sharepoint.com/site/";
//Insert Credentials
ClientContext context = new ClientContext(siteUrl);
SecureString passWord = new SecureString();
foreach (var c in "mypassword") passWord.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials("myUserName", passWord);
Web site = context.Web;
//Get the required RootFolder
string barRootFolderRelativeUrl = "Shared Documents/foo/bar";
Folder barFolder = site.GetFolderByServerRelativeUrl(barRootFolderRelativeUrl);
//Create new subFolder to load files into
string newFolderName = baseName + DateTime.Now.ToString("yyyyMMddHHmm");
barFolder.Folders.Add(newFolderName);
barFolder.Update();
//Add file to new Folder
Folder currentRunFolder = site.GetFolderByServerRelativeUrl(barRootFolderRelativeUrl + "/" + newFolderName);
FileCreationInformation newFile = new FileCreationInformation { Content = System.IO.File.ReadAllBytes(@p), Url = Path.GetFileName(@p), Overwrite = true };
currentRunFolder.Files.Add(newFile);
currentRunFolder.Update();
context.ExecuteQuery();
//Return the URL of the new uploaded file
newUrl = siteUrl + barRootFolderRelativeUrl + "/" + newFolderName + "/" + Path.GetFileName(@p);
}
This will insert a new element after the input field with id "password".
$(document).ready(function(){
var newInput = $("<input name='new_field' type='text'>");
$('input#password').after(newInput);
});
Not sure if this answers your question.
If you're doing some performance tuning it's often recommended to set both -XX:PermSize
and -XX:MaxPermSize
to the same value to increase JVM
efficiency.
Here is some information:
You can also specify -XX:+CMSClassUnloadingEnabled
to enable class unloading
option if you are using CMS
GC
. It may help to decrease the probability of Java.lang.OutOfMemoryError: PermGen space
Simply sleeping for 10 seconds or using threading.Timer(10,foo)
will result in start time drift. (You may not care about this, or it may be a significant source of problems depending on your exact situation.) There can be two causes for this - inaccuracies in the wake up time of your thread or execution time for your function.
You can see some results at the end of this post, but first an example of how to fix it. You need to track when your function should next be called as opposed to when it actually got called and account for the difference.
Here's a version that drifts slightly:
import datetime, threading
def foo():
print datetime.datetime.now()
threading.Timer(1, foo).start()
foo()
Its output looks like this:
2013-08-12 13:05:36.483580
2013-08-12 13:05:37.484931
2013-08-12 13:05:38.485505
2013-08-12 13:05:39.486945
2013-08-12 13:05:40.488386
2013-08-12 13:05:41.489819
2013-08-12 13:05:42.491202
2013-08-12 13:05:43.492486
2013-08-12 13:05:44.493865
2013-08-12 13:05:45.494987
2013-08-12 13:05:46.496479
2013-08-12 13:05:47.497824
2013-08-12 13:05:48.499286
2013-08-12 13:05:49.500232
You can see that the sub-second count is constantly increasing and thus, the start time is "drifting".
This is code that correctly accounts for drift:
import datetime, threading, time
next_call = time.time()
def foo():
global next_call
print datetime.datetime.now()
next_call = next_call+1
threading.Timer( next_call - time.time(), foo ).start()
foo()
Its output looks like this:
2013-08-12 13:21:45.292565
2013-08-12 13:21:47.293000
2013-08-12 13:21:48.293939
2013-08-12 13:21:49.293327
2013-08-12 13:21:50.293883
2013-08-12 13:21:51.293070
2013-08-12 13:21:52.293393
Here you can see that there is no longer any increase in the sub-second times.
If your events are occurring really frequently you may want to run the timer in a single thread, rather than starting a new thread for each event. While accounting for drift this would look like:
import datetime, threading, time
def foo():
next_call = time.time()
while True:
print datetime.datetime.now()
next_call = next_call+1;
time.sleep(next_call - time.time())
timerThread = threading.Thread(target=foo)
timerThread.start()
However your application will not exit normally, you'll need to kill the timer thread. If you want to exit normally when your application is done, without manually killing the thread, you should use
timerThread = threading.Thread(target=foo)
timerThread.daemon = True
timerThread.start()
I have recently encountered this problem. Here are the steps to resolve
<servers>_x000D_
<server>_x000D_
<id>serverId</id>_x000D_
<username>username</username>_x000D_
<password>password</password>_x000D_
</server>_x000D_
</servers>
_x000D_
<repositories>_x000D_
<repository>_x000D_
<id>serverId</id> _x000D_
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>_x000D_
</repository>_x000D_
</repositories>
_x000D_
<profiles>_x000D_
<profile>_x000D_
<repositories>_x000D_
<repository>_x000D_
<id>serverId</id>_x000D_
<name>aliyun</name>_x000D_
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>_x000D_
</repository>_x000D_
</repositories>_x000D_
</profile>_x000D_
</profiles>
_x000D_
Note that you should ensure that the id of the server tag should be the same as the id of the repository tag.
With Android Studio 3+:
You should just be able to simply copy the jar file to the libs folder right under the app folder.
... myproject\app\libs\myfile.jar
Then select Project Files from the drop-down on the Projects window, right click on the project, select Synchronize to see the file in Project Files. It will automatically add the dependencies in the gradle file (Module:app).
dependencies {
...
implementation files('libs/myfile.jar')
Here is another solution:
Go to the Project Files view (select Project Files from the dropdown).
Select New... Directory, create a folder named libs right under app.
Open up File Explorer, copy and paste your jar file into the libs folder.
In Android Studio, right click on the jar file, and select Add as a Library... from the popup menu.
You should see the file listed in the dependencies list in the gradle file:
dependencies {
...
implementation files('libs/myfile.jar')
}
Open up your java file, and add the import statement there:
import com.xxx.xxx;
XDebug changed some configuration settings.
Old settings:
xdebug.remote_enable = 1
xdebug.remote_autostart = 1
xdebug.remote_port = 9000
New settings:
xdebug.mode=debug
xdebug.start_with_request=yes
xdebug.client_port=9000
So you should paste the latter in php.ini file. More info: XDebug Changed Configuration Settings
I have a similar solution to @Satheesh using React hooks:
State initialization:
const [enteredText, setEnteredText] = useState('');
Input tag:
<input type="text" value={enteredText} (event handler, classNames, etc.) />
Inside the event handler function, after updating the object with data from input form, call:
setEnteredText('');
Note: This is described as 'two-way binding'
It acts as curly bracket. We have to keep the number of white spaces consistent through out the program.
Example 1:
def main():
print "we are in main function"
print "print 2nd line"
main()
Result:
We are in main function
print 2nd line
Example 2:
def main():
print "we are in main function"
print "print 2nd line"
main()
Result:
print 2nd line
We are in main function
Here, in the 1st program, both the statement comes under the main function since both have equal number of white spaces while in the 2nd program, the 1st line is printed later because the main function is called after the 2nd line Note - The 2nd line has no white space, so it is independent of the main function.
If using Angular >= 1.4, here's the cleanest solution I've found that doesn't rely on anything custom or external:
angular.module('yourModule')
.config(function ($httpProvider, $httpParamSerializerJQLikeProvider){
$httpProvider.defaults.transformRequest.unshift($httpParamSerializerJQLikeProvider.$get());
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
});
And then you can do this anywhere in your app:
$http({
method: 'POST',
url: '/requesturl',
data: {
param1: 'value1',
param2: 'value2'
}
});
And it will correctly serialize the data as param1=value1¶m2=value2
and send it to /requesturl
with the application/x-www-form-urlencoded; charset=utf-8
Content-Type header as it's normally expected with POST requests on endpoints.
From what I understand, you struggle with what to put into your template.
I'll show an example:
<ul>
{% for guest in guests %}
<li>{{ guest.name }} <a href="{{ path('your_delete_route_name',{'id': guest.id}) }}">[[DELETE]]</a></li>
{% endfor %}
</ul>
Now what happens is it iterates over every object within guests (you'll have to rename this if your object collection is named otherwise!), shows the name and places the correct link. The route name might be different.
You can see your current session settings by querying nls_session_parameters
:
select value
from nls_session_parameters
where parameter = 'NLS_NUMERIC_CHARACTERS';
VALUE
----------------------------------------
.,
That may differ from the database defaults, which you can see in nls_database_parameters
.
In this session your query errors:
select to_number('100,12') from dual;
Error report -
SQL Error: ORA-01722: invalid number
01722. 00000 - "invalid number"
I could alter my session, either directly with alter session
or by ensuring my client is configured in a way that leads to the setting the string needs (it may be inherited from a operating system or Java locale, for example):
alter session set NLS_NUMERIC_CHARACTERS = ',.';
select to_number('100,12') from dual;
TO_NUMBER('100,12')
-------------------
100,12
In SQL Developer you can set your preferred value in Tool->Preferences->Database->NLS.
But I can also override that session setting as part of the query, with the optional third nlsparam parameter to to_number()
; though that makes the optional second fmt parameter necessary as well, so you'd need to be able pick a suitable format:
alter session set NLS_NUMERIC_CHARACTERS = '.,';
select to_number('100,12', '99999D99', 'NLS_NUMERIC_CHARACTERS='',.''')
from dual;
TO_NUMBER('100,12','99999D99','NLS_NUMERIC_CHARACTERS='',.''')
--------------------------------------------------------------
100.12
By default the result is still displayed with my session settings, so the decimal separator is still a period.
It seems to me that you want to change the contents of menu inside a local method, and this method is called at any time, whenever an event is occurred, or in the activity UI thread.
Why don't you take the instance of Menu in the global variable in onPrepareOptionsMenu when this is overridden and use in this method of yours. Be sure that this method is called whenever an event is occurred (like button click), or in the activity UI thread, handler or async-task post-execute.
You should know in advance the index of this menu item you want to change. After clearing the menu, you need to inflate the menu XML and update your item's name or icon.
You can also use guava Table implementation for this.
Table represents a special map where two keys can be specified in combined fashion to refer to a single value. It is similar to creating a map of maps.
//create a table
Table<String, String, String> employeeTable = HashBasedTable.create();
//initialize the table with employee details
employeeTable.put("IBM", "101","Mahesh");
employeeTable.put("IBM", "102","Ramesh");
employeeTable.put("IBM", "103","Suresh");
employeeTable.put("Microsoft", "111","Sohan");
employeeTable.put("Microsoft", "112","Mohan");
employeeTable.put("Microsoft", "113","Rohan");
employeeTable.put("TCS", "121","Ram");
employeeTable.put("TCS", "122","Shyam");
employeeTable.put("TCS", "123","Sunil");
//get Map corresponding to IBM
Map<String,String> ibmEmployees = employeeTable.row("IBM");
Rather than using a bunch of if-statements, enums lend themselves well to switch statements
I use some enum/switch combinations in the level builder I am building for my game.
EDIT: Another thing, I see you want syntax similar to;
if(day == Days.Saturday)
etc
You can do this in C++:
if(day == Days::Saturday)
etc
Here is a very simple example:
EnumAppState.h
#ifndef ENUMAPPSTATE_H
#define ENUMAPPSTATE_H
enum eAppState
{
STARTUP,
EDIT,
ZONECREATION,
SHUTDOWN,
NOCHANGE
};
#endif
Somefile.cpp
#include "EnumAppState.h"
eAppState state = eAppState::STARTUP;
switch(state)
{
case STARTUP:
//Do stuff
break;
case EDIT:
//Do stuff
break;
case ZONECREATION:
//Do stuff
break;
case SHUTDOWN:
//Do stuff
break;
case NOCHANGE:
//Do stuff
break;
}
Only window is supported yes but you could use a plugin for it: http://benalman.com/projects/jquery-resize-plugin/
Make your life easier with dotenv-webpack. Simply install it npm install dotenv-webpack --save-dev
, then create an .env
file in your application's root (remember to add this to .gitignore
before you git push
). Open this file, and set some environmental variables there, like for example:
ENV_VAR_1=1234
ENV_VAR_2=abcd
ENV_VAR_3=1234abcd
Now, in your webpack config add:
const Dotenv = require('dotenv-webpack');
const webpackConfig = {
node: { global: true, fs: 'empty' }, // Fix: "Uncaught ReferenceError: global is not defined", and "Can't resolve 'fs'".
output: {
libraryTarget: 'umd' // Fix: "Uncaught ReferenceError: exports is not defined".
},
plugins: [new Dotenv()]
};
module.exports = webpackConfig; // Export all custom Webpack configs.
Only const Dotenv = require('dotenv-webpack');
, plugins: [new Dotenv()]
, and of course module.exports = webpackConfig; // Export all custom Webpack configs.
are required. However, in some scenarios you might get some errors. For these you have the solution as well implying how you can fix certain error.
Now, wherever you want you can simply use process.env.ENV_VAR_1
, process.env.ENV_VAR_2
, process.env.ENV_VAR_3
in your application.
I've found that some of the suggested answers which drill down into the MemberExpression
/UnaryExpression
don't capture nested/subproperties.
ex) o => o.Thing1.Thing2
returns Thing1
rather than Thing1.Thing2
.
This distinction is important if you're trying to work with EntityFramework DbSet.Include(...)
.
I've found that just parsing the Expression.ToString()
seems to work fine, and comparatively quickly. I compared it against the UnaryExpression
version, and even getting ToString
off of the Member/UnaryExpression
to see if that was faster, but the difference was negligible. Please correct me if this is a terrible idea.
/// <summary>
/// Given an expression, extract the listed property name; similar to reflection but with familiar LINQ+lambdas. Technique @via https://stackoverflow.com/a/16647343/1037948
/// </summary>
/// <remarks>Cheats and uses the tostring output -- Should consult performance differences</remarks>
/// <typeparam name="TModel">the model type to extract property names</typeparam>
/// <typeparam name="TValue">the value type of the expected property</typeparam>
/// <param name="propertySelector">expression that just selects a model property to be turned into a string</param>
/// <param name="delimiter">Expression toString delimiter to split from lambda param</param>
/// <param name="endTrim">Sometimes the Expression toString contains a method call, something like "Convert(x)", so we need to strip the closing part from the end</param>
/// <returns>indicated property name</returns>
public static string GetPropertyName<TModel, TValue>(this Expression<Func<TModel, TValue>> propertySelector, char delimiter = '.', char endTrim = ')') {
var asString = propertySelector.ToString(); // gives you: "o => o.Whatever"
var firstDelim = asString.IndexOf(delimiter); // make sure there is a beginning property indicator; the "." in "o.Whatever" -- this may not be necessary?
return firstDelim < 0
? asString
: asString.Substring(firstDelim+1).TrimEnd(endTrim);
}//-- fn GetPropertyNameExtended
(Checking for the delimiter might even be overkill)
Demonstration + Comparison code -- https://gist.github.com/zaus/6992590
First Rename your AndroidManifest.xml file
android:label="Your App Name"
Second
Rename Your Application Name in Pubspec.yaml file
name: Your Application Name
Third Change Your Application logo
flutter_icons:
android: "launcher_icon"
ios: true
image_path: "assets/path/your Application logo.formate"
Fourth Run
flutter pub pub run flutter_launcher_icons:main
public static void PrintFileToDefaultPrinter(string FilePath)
{
try
{
var file = File.ReadAllBytes(FilePath);
var printQueue = LocalPrintServer.GetDefaultPrintQueue();
using (var job = printQueue.AddJob())
using (var stream = job.JobStream)
{
stream.Write(file, 0, file.Length);
}
}
catch (Exception)
{
throw;
}
}
The lexically scoped integer
pragma forces Perl to use integer arithmetic in its scope:
print 3.0/2.1 . "\n"; # => 1.42857142857143
{
use integer;
print 3.0/2.1 . "\n"; # => 1
}
print 3.0/2.1 . "\n"; # => 1.42857142857143
You can have this if you are trying to manifest your application that it has a dependancy on the Microsoft.Windows.Common-Controls assembly. You do this when you want to load Version 6 of the common controls library - so that visual styles are applied to common controls.
You probably followed Microsoft's original documentation way back from Windows XP days, and added the following to your application's manifest:
<!-- Dependancy on Common Controls version 6 -->
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="X86"
publicKeyToken="6595b64144ccf1df"
language="*"/>
</dependentAssembly>
</dependency>
Windows XP is no longer the OS, and you're no longer a 32-bit application. In the intervening 17 years Microsoft updated their documentation; now it's time for you to update your manifest:
<!-- Dependancy on Common Controls version 6 -->
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="*"
publicKeyToken="6595b64144ccf1df"
language="*"/>
</dependentAssembly>
</dependency>
Raymond Chen has a lovely history of the Common Controls:
If you're pointing the config at a domain (eg fabrikam.com), do an NSLOOKUP to ensure all the responding IPs are valid, and can be connected to on port 389:
NSLOOKUP fabrikam.com
Test-NetConnection <IP returned from NSLOOKUP> -port 389
How about this:
$ seq 1 100000 | tail -n +10000 | head -n 10
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
It uses tail
to output from the 10,000th line and onwards and then head
to only keep 10 lines.
The same (almost) result with sed
:
$ seq 1 100000 | sed -n '10000,10010p'
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
This one has the advantage of allowing you to input the line range directly.
In Kotlin Android EditText listener is set using,
val searchTo : EditText = findViewById(R.id.searchTo)
searchTo.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable) {
// you can call or do what you want with your EditText here
// yourEditText...
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
})
So normally you would create a backing variable in the class and toggle it on click and tie a class binding to the variable. Something like:
@Component(
selector:'foo',
template:`<a (click)="onClick()"
[class.selected]="wasClicked">Link</a>
`)
export class MyComponent {
wasClicked = false;
onClick() {
this.wasClicked= !this.wasClicked;
}
}
Here is the same solution than Rukshan but in sass (in order to keep your grid configuration) for special case that don't work with Ross Allen solution (when you can't have a parent div.row)
@mixin make-grid-offset-right($class) {
@for $index from 0 through $grid-columns {
.col-#{$class}-offset-right-#{$index} {
margin-right: percentage(($index / $grid-columns));
}
}
}
@include make-grid-offset-right(xs);
@media (min-width: $screen-sm-min) {
@include make-grid-offset-right(sm);
}
@media (min-width: $screen-md-min) {
@include make-grid-offset-right(md);
}
@media (min-width: $screen-lg-min) {
@include make-grid-offset-right(lg);
}
Good list. The Angry Ninjas Starter Kit will have a Cocos2d-X update soon.
wait
releases the lock and sleep
doesn't. A thread in waiting state is eligible for waking up as soon as notify
or notifyAll
is called. But in case of sleep
the thread keeps the lock and it'll only be eligible once the sleep time is over.
using this we can add two array with out any loop.
I believe if you have 2 arrays of the same type that you want to combine into one of array, there's a very simple way to do that.
Here's the code:
String[] TextFils = Directory.GetFiles(basePath, "*.txt");
String[] ExcelFils = Directory.GetFiles(basePath, "*.xls");
String[] finalArray = TextFils.Concat(ExcelFils).ToArray();
or
String[] Fils = Directory.GetFiles(basePath, "*.txt");
String[] ExcelFils = Directory.GetFiles(basePath, "*.xls");
Fils = Fils.Concat(ExcelFils).ToArray();
I would recommend EclipseUML from Omondo for general usage, although I did experience some problems a few months back, with my web projects. They had a free edition at one point in time, but that is supposedly no longer promoted.
If you are really keen on reverse engineering sequence diagrams from source code, I would recommend jTracert.
As far as Eclipse projects themselves are concerned, the Eclipse UML2 Tools project might support reverse engineering, although I've have never seen its use in practice.
The MoDisco (Model Discovery) project Eclipse GMT project seems to be clearer in achieving your objective. The list of technology specific tools would be a good place to start with.
An alternative to the already provided ways is to simply filter on the column like so
df = df.where(F.col('columnNameHere').isNull())
This has the added benefit that you don't have to add another column to do the filtering and it's quick on larger data sets.
Extending @oopbase's answer with return;
statement.
Let's consider a use case of traditional authentication system where we store login information into the session. On each page we check for active session like,
/* Some Import Statements here. */
if(null == session || !session.getAttribute("is_login").equals("1")) {
response.sendRedirect("http://domain.com/login");
}
// ....
session.getAttribute("user_id");
// ....
/* Some More JSP+Java+HTML code here */
It looks fine at first glance however; It has one issue. If your server has expired session due to time limit and user is trying to access the page he might get error if you have not written your code in try..catch
block or handled if(null != session.getAttribute("attr_name"))
everytime.
So by putting a return;
statement I stopped further execution and forced to redirect page to certain location.
if(null == session || !session.getAttribute("is_login").equals("1")) {
response.sendRedirect("http://domain.com/login");
return;
}
Note that Use of redirection may vary based on the requirements. Nowadays people don't use such authentication system. (Modern approach - Token Based Authentication) It's just an simple example to understand where and how to place redirection(s).
sdleihssirhc's answer is of course the correct one for the case in the question, but just as a reference if you need to select elements that don't have a certain class, you can use the not selector:
// select all divs that don't have class test
$( 'div' ).not( ".test" );
$( 'div:not(.test)' ); // <-- alternative
My issue ended up being visual studio catching an unhandled exception and preventing the script from running any further. Because I was running in the IDE, it looked like there was an issue when there wasn't. Autocomplete was working just fine. I added a try/catch block and that made the IDE happy.
$.ajax({
url: "/MyController/MyAction",
type: "POST",
dataType: "json",
data: { prefix: request.term },
success: function (data) {
try {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name };
}))
} catch (err) { }
}
})
Since filter
returns a QuerySet
, you can use count to check how many results were returned. This is assuming you don't actually need the results.
num_results = User.objects.filter(email = cleaned_info['username']).count()
After looking at the documentation though, it's better to just call len on your filter if you are planning on using the results later, as you'll only be making one sql query:
A count() call performs a SELECT COUNT(*) behind the scenes, so you should always use count() rather than loading all of the record into Python objects and calling len() on the result (unless you need to load the objects into memory anyway, in which case len() will be faster).
num_results = len(user_object)
REQUEST:
$.ajax({
url: "http://localhost:8079/students/add/",
type: "POST",
crossDomain: true,
data: JSON.stringify(somejson),
dataType: "json",
success: function (response) {
var resp = JSON.parse(response)
alert(resp.status);
},
error: function (xhr, status) {
alert("error");
}
});
RESPONSE:
response = HttpResponse(json.dumps('{"status" : "success"}'))
response.__setitem__("Content-type", "application/json")
response.__setitem__("Access-Control-Allow-Origin", "*")
return response
I guess I found a simpler solution
temp1 = pd.melt(df1, id_vars=["location"], var_name='Date', value_name='Value')
temp2 = pd.melt(df1, id_vars=["name"], var_name='Date', value_name='Value')
Concat whole temp1
with temp2
's column name
temp1['new_column'] = temp2['name']
You now have what you asked for.
Unsigned variables are variables which are internally represented without a mathematical sign (plus or minus) can store 'zero' or positive values only. Let us say the unsigned variable is n bits in size, then it can represent 2^n (2 power n) values - 0 through (2^n -1). A signed variable on the other hand, 'loses' one bit for representing the sign, so it can store values from -(2^(n-1) -1) through (2^(n-1)) including zero. Thus, a signed variable can store positive values, negative values and zero.
P.S.:
Internally, the mathematical sign may be represented in one's complement form, two's complement form or with a sign bit (eg: 0 -> +, 1-> -)
All these methods effectively divide the range of representable values in n bits (2^n) into three parts, positive, negative and zero.
This is just my two cents worth.
I hope this helps.
Note: You don't need to check if your service is running, CheckIfServiceIsRunning()
, because bindService()
will start it if it isn't running.
Also: if you rotate the phone you don't want it to bindService()
again, because onCreate()
will be called again. Be sure to define onConfigurationChanged()
to prevent this.
You can change the passphrase for your private key by doing:
ssh-keygen -f ~/.ssh/id_rsa -p
as long as you did not commit you can type
git merge --abort
just as the command line suggested.
var
just tells the compiler to infer the type you wanted at compile time...it cannot infer from null
(though there are cases it could).
So, no you are not allowed to do this.
When you say "some empty value"...if you mean:
var s = string.Empty;
//
var s = "";
Then yes, you may do that, but not null
.
du -S
du have another useful option: -S, --separate-dirs
telling du not include size of subdirectories - handy on some occasions.
Example 1 - shows only the file sizes in a directory:
du -Sh *
3,1G 10/CR2
280M 10
Example 2 - shows the file sizes and subdirectories in directory:
du -h *
3,1G 10/CR2
3,4G 10
I had trouble using the above, and I needed the IP address from a controller. I used the following in the end:
System.Web.HttpContext.Current.Request.UserHostAddress
Add this link:
/usr/local/lib/*.so.*
The total is:
g++ -o main.out main.cpp -I /usr/local/include -I /usr/local/include/opencv -I /usr/local/include/opencv2 -L /usr/local/lib /usr/local/lib/*.so /usr/local/lib/*.so.*
You can do it directly from eclipse using the Navigator view (Window -> Show View -> Navigator). In the Navigator view select the project and open it so that you can see the file .project
. Right click -> Open. You will get a XML editor view. Edit the content of the node natures
and insert a new child nature
with org.eclipse.jdt.core.javanature
as content. Save.
Now create a file .classpath
, it will open in the XML editor. Add a node named classpath
, add a child named classpathentry
with the attributes kind
with content con
and another one named path
and content org.eclipse.jdt.launching.JRE_CONTAINER
. Save-
Much easier: copy the files .project
and .classpath
from an existing Java project and edit the node result name
to the name of this project. Maybe you have to refresh the project (F5).
You'll get the same result as with the solution of Chris Marasti-Georg.
public void setHeight(DataGridView src)
{
src.Height= src.ColumnHeadersVisible ? src.ColumnHeadersHeight : 0 + src.Rows.OfType<DataGridViewRow>().Where(row => row.Visible).Sum(row => row.Height);
}
Do it in the controller
$timeout(function(){
$scope.checked = true;
}, 1);
_x000D_
then remove ng-checked.
use this to clear the previous keyboard buffer before scanning the string it will solve your problem scanner.nextLine();//this is to clear the keyboard buffer