Take a look at the following system stored procedures, which you can run in SQLServer Management Studio (SSMS):
Also, in SSMS, you can view locks and processes in different ways:
Different versions of SSMS put the activity monitor in different places. For example, SSMS 2008 and 2012 have it in the context menu when you right-click on a server node.
Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:
sudo apt-get install bison flex
There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.
I know that this is an old question but I am just going to place this here:
To prevent skype from using port 80 and port 443, open the Skype window, then click on the Tools menu and select Options.
Click on the Advanced tab, and go to the Connection sub-tab.
Uncheck the checkbox for Use port 80 and 443 as an alternative for additional incoming connections option.
Click on the Save button and then restart Skype.
After you restart skype, skype wont use port 88 or 443 anymore.
Hope this might help someone.
One thing I wish to point out here, and that is, despite what the Apple engineers have stated in their own WWDC 2015 video here:
https://developer.apple.com/videos/play/wwdc2015/407/
Apple keeps changing their mind on the subject, which tells us that there is no single right answer to this question. To show that even Apple engineers are split on this subject, take a look at Apple's most recent sample code, and you'll see some people use weak, and some don't.
This Apple Pay example uses weak: https://developer.apple.com/library/ios/samplecode/Emporium/Listings/Emporium_ProductTableViewController_swift.html#//apple_ref/doc/uid/TP40016175-Emporium_ProductTableViewController_swift-DontLinkElementID_8
As does this picture-in-picture example: https://developer.apple.com/library/ios/samplecode/AVFoundationPiPPlayer/Listings/AVFoundationPiPPlayer_PlayerViewController_swift.html#//apple_ref/doc/uid/TP40016166-AVFoundationPiPPlayer_PlayerViewController_swift-DontLinkElementID_4
As does the Lister example: https://developer.apple.com/library/ios/samplecode/Lister/Listings/Lister_ListCell_swift.html#//apple_ref/doc/uid/TP40014701-Lister_ListCell_swift-DontLinkElementID_57
As does the Core Location example: https://developer.apple.com/library/ios/samplecode/PotLoc/Listings/Potloc_PotlocViewController_swift.html#//apple_ref/doc/uid/TP40016176-Potloc_PotlocViewController_swift-DontLinkElementID_6
As does the view controller previewing example: https://developer.apple.com/library/ios/samplecode/ViewControllerPreviews/Listings/Projects_PreviewUsingDelegate_PreviewUsingDelegate_DetailViewController_swift.html#//apple_ref/doc/uid/TP40016546-Projects_PreviewUsingDelegate_PreviewUsingDelegate_DetailViewController_swift-DontLinkElementID_5
As does the HomeKit example: https://developer.apple.com/library/ios/samplecode/HomeKitCatalog/Listings/HMCatalog_Homes_Action_Sets_ActionSetViewController_swift.html#//apple_ref/doc/uid/TP40015048-HMCatalog_Homes_Action_Sets_ActionSetViewController_swift-DontLinkElementID_23
All those are fully updated for iOS 9, and all use weak outlets. From this we learn that A. The issue is not as simple as some people make it out to be. B. Apple has changed their mind repeatedly, and C. You can use whatever makes you happy :)
Special thanks to Paul Hudson (author of www.hackingwithsift.com) who gave me the clarification, and references for this answer.
I hope this clarifies the subject a bit better!
Take care.
There is no built-in functionality for this. This count is in its whole user-specific. Maintain a counter or whatever.
toString
is a method, so you should add parenthesis ()
to make the function call.
> a = [1,2,3]
[ 1, 2, 3 ]
> a.toString()
'1,2,3'
Besides, if you want to use strings as keys, then you should consider using a Object
instead of Array
, and use JSON.stringify
to return a string.
> var aa = {}
> aa['a'] = 'aaa'
> JSON.stringify(aa)
'{"a":"aaa","b":"bbb"}'
I think the key is to copy the module to the standard paths.
Once that is done, modprobe only accepts the module name, so leave off the path and ".ko" extension.
First a link to some documentation of fork()
http://pubs.opengroup.org/onlinepubs/009695399/functions/fork.html
The pid is provided by the kernel. Every time the kernel create a new process it will increase the internal pid counter and assign the new process this new unique pid and also make sure there are no duplicates. Once the pid reaches some high number it will wrap and start over again.
So you never know what pid you will get from fork(), only that the parent will keep it's unique pid and that fork will make sure that the child process will have a new unique pid. This is stated in the documentation provided above.
If you continue reading the documentation you will see that fork() return 0 for the child process and the new unique pid of the child will be returned to the parent. If the child want to know it's own new pid you will have to query for it using getpid().
pid_t pid = fork()
if(pid == 0) {
printf("this is a child: my new unique pid is %d\n", getpid());
} else {
printf("this is the parent: my pid is %d and I have a child with pid %d \n", getpid(), pid);
}
and below is some inline comments on your code
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
pid_t pid1, pid2, pid3;
pid1=0, pid2=0, pid3=0;
pid1= fork(); /* A */
if(pid1 == 0){
/* This is child A */
pid2=fork(); /* B */
pid3=fork(); /* C */
} else {
/* This is parent A */
/* Child B and C will never reach this code */
pid3=fork(); /* D */
if(pid3==0) {
/* This is child D fork'ed from parent A */
pid2=fork(); /* E */
}
if((pid1 == 0)&&(pid2 == 0)) {
/* pid1 will never be 0 here so this is dead code */
printf("Level 1\n");
}
if(pid1 !=0) {
/* This is always true for both parent and child E */
printf("Level 2\n");
}
if(pid2 !=0) {
/* This is parent E (same as parent A) */
printf("Level 3\n");
}
if(pid3 !=0) {
/* This is parent D (same as parent A) */
printf("Level 4\n");
}
}
return 0;
}
DECLARE @EndTime AS DATETIME, @StartTime AS DATETIME
SELECT @StartTime = '2013-03-08 08:00:00', @EndTime = '2013-03-08 08:30:00'
SELECT CAST(@EndTime - @StartTime AS TIME)
Result: 00:30:00.0000000
Format result as you see fit.
If you really want it to look more semantic like having the <body>
in the middle you can use the <main>
element. With all the recent advances the <body>
element is not as semantic as it once was but you just have to think of it as a wrapper in which the view port sees.
<html>
<head>
</head>
<body>
<header>
</header>
<main>
<section></section>
<article></article>
</main>
<footer>
</footer>
<body>
</html>
Conventions:
Tools:
Update: Since Python 3.5 you can use type hints which is a compact, machine-readable syntax:
from typing import Dict, Union
def foo(i: int, d: Dict[str, Union[str, int]]) -> int:
"""
Explanation: this function takes two arguments: `i` and `d`.
`i` is annotated simply as `int`. `d` is a dictionary with `str` keys
and values that can be either `str` or `int`.
The return type is `int`.
"""
The main advantage of this syntax is that it is defined by the language and that it's unambiguous, so tools like PyCharm can easily take advantage from it.
For a long time, CMake had the add_definitions
command for this purpose. However, recently the command has been superseded by a more fine grained approach (separate commands for compile definitions, include directories, and compiler options).
An example using the new add_compile_definitions:
add_compile_definitions(OPENCV_VERSION=${OpenCV_VERSION})
add_compile_definitions(WITH_OPENCV2)
Or:
add_compile_definitions(OPENCV_VERSION=${OpenCV_VERSION} WITH_OPENCV2)
The good part about this is that it circumvents the shabby trickery CMake has in place for add_definitions
. CMake is such a shabby system, but they are finally finding some sanity.
Find more explanation on which commands to use for compiler flags here: https://cmake.org/cmake/help/latest/command/add_definitions.html
Likewise, you can do this per-target as explained in Jim Hunziker's answer.
I saw answers using the http, https, and request modules. I'd like to add one using yet another native NodeJS module that supports either the http or https protocol:
I've referenced the official NodeJS API, as well as some of the other answers on this question for something I'm doing. The following was the test I wrote to try it out, which worked as intended:
import * as fs from 'fs';
import * as _path from 'path';
import * as http2 from 'http2';
/* ... */
async function download( host, query, destination )
{
return new Promise
(
( resolve, reject ) =>
{
// Connect to client:
const client = http2.connect( host );
client.on( 'error', error => reject( error ) );
// Prepare a write stream:
const fullPath = _path.join( fs.realPathSync( '.' ), destination );
const file = fs.createWriteStream( fullPath, { flags: "wx" } );
file.on( 'error', error => reject( error ) );
// Create a request:
const request = client.request( { [':path']: query } );
// On initial response handle non-success (!== 200) status error:
request.on
(
'response',
( headers/*, flags*/ ) =>
{
if( headers[':status'] !== 200 )
{
file.close();
fs.unlink( fullPath, () => {} );
reject( new Error( `Server responded with ${headers[':status']}` ) );
}
}
);
// Set encoding for the payload:
request.setEncoding( 'utf8' );
// Write the payload to file:
request.on( 'data', chunk => file.write( chunk ) );
// Handle ending the request
request.on
(
'end',
() =>
{
file.close();
client.close();
resolve( { result: true } );
}
);
/*
You can use request.setTimeout( 12000, () => {} ) for aborting
after period of inactivity
*/
// Fire off [flush] the request:
request.end();
}
);
}
Then, for example:
/* ... */
let downloaded = await download( 'https://gitlab.com', '/api/v4/...', 'tmp/tmpFile' );
if( downloaded.result )
{
// Success!
}
// ...
External References
EDIT Information
function
declaration, which our contributor has so promptly added. Thanks!In modern browsers, the classList API is supported.
This allows for a (vanilla) JavaScript function like this:
var addClasses;
addClasses = function (selector, classArray) {
'use strict';
var className, element, elements, i, j, lengthI, lengthJ;
elements = document.querySelectorAll(selector);
// Loop through the elements
for (i = 0, lengthI = elements.length; i < lengthI; i += 1) {
element = elements[i];
// Loop through the array of classes to add one class at a time
for (j = 0, lengthJ = classArray.length; j < lengthJ; j += 1) {
className = classArray[j];
element.classList.add(className);
}
}
};
Modern browsers (not IE) support passing multiple arguments to the classList::add
function, which would remove the need for the nested loop, simplifying the function a bit:
var addClasses;
addClasses = function (selector, classArray) {
'use strict';
var classList, className, element, elements, i, j, lengthI, lengthJ;
elements = document.querySelectorAll(selector);
// Loop through the elements
for (i = 0, lengthI = elements.length; i < lengthI; i += 1) {
element = elements[i];
classList = element.classList;
// Pass the array of classes as multiple arguments to classList::add
classList.add.apply(classList, classArray);
}
};
Usage
addClasses('.button', ['large', 'primary']);
Functional version
var addClassesToElement, addClassesToSelection;
addClassesToElement = function (element, classArray) {
'use strict';
classArray.forEach(function (className) {
element.classList.add(className);
});
};
addClassesToSelection = function (selector, classArray) {
'use strict';
// Use Array::forEach on NodeList to iterate over results.
// Okay, since we’re not trying to modify the NodeList.
Array.prototype.forEach.call(document.querySelectorAll(selector), function (element) {
addClassesToElement(element, classArray)
});
};
// Usage
addClassesToSelection('.button', ['button', 'button--primary', 'button--large'])
The classList::add
function will prevent multiple instances of the same CSS class as opposed to some of the previous answers.
Resources on the classList API:
If you're using at least Java 8, see my other answer.
If you're already using Google Guava, see Sean Patrick Floyd's answer.
If you're stuck at Java 7 and don't want to include Google Guava, you can write your own (read-only) Iterables.concat()
using no more than Iterable
and Iterator
:
public static <E> Iterable<E> concat(final Iterable<? extends E> iterable1,
final Iterable<? extends E> iterable2) {
return new Iterable<E>() {
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
final Iterator<? extends E> iterator1 = iterable1.iterator();
final Iterator<? extends E> iterator2 = iterable2.iterator();
@Override
public boolean hasNext() {
return iterator1.hasNext() || iterator2.hasNext();
}
@Override
public E next() {
return iterator1.hasNext() ? iterator1.next() : iterator2.next();
}
};
}
};
}
@SafeVarargs
public static <E> Iterable<E> concat(final Iterable<? extends E>... iterables) {
return concat(Arrays.asList(iterables));
}
public static <E> Iterable<E> concat(final Iterable<Iterable<? extends E>> iterables) {
return new Iterable<E>() {
final Iterator<Iterable<? extends E>> iterablesIterator = iterables.iterator();
@Override
public Iterator<E> iterator() {
return !iterablesIterator.hasNext() ? Collections.emptyIterator()
: new Iterator<E>() {
Iterator<? extends E> iterableIterator = nextIterator();
@Override
public boolean hasNext() {
return iterableIterator.hasNext();
}
@Override
public E next() {
final E next = iterableIterator.next();
findNext();
return next;
}
Iterator<? extends E> nextIterator() {
return iterablesIterator.next().iterator();
}
Iterator<E> findNext() {
while (!iterableIterator.hasNext()) {
if (!iterablesIterator.hasNext()) {
break;
}
iterableIterator = nextIterator();
}
return this;
}
}.findNext();
}
};
}
Worked liked a charm for me:
matplotlib.rcParams['figure.figsize'] = (20, 10)
Thought of adding an answer for Angular 8:
For looping you can do:
<ng-container *ngFor="let item of BATCH_FILE_HEADERS | keyvalue: keepOriginalOrder">
<th nxHeaderCell>{{'upload.bulk.headings.'+item.key |translate}}</th>
</ng-container>
Also if you need the above array to keep the original order then declare this inside your class:
public keepOriginalOrder = (a, b) => a.key;
This is what you need:
=NOT(ISERROR(MATCH(<cell in col A>,<column B>, 0))) ## pseudo code
For the first cell of A, this would be:
=NOT(ISERROR(MATCH(A2,$B$2:$B$5, 0)))
Enter formula (and drag down) as follows:
You will get:
%s
indicates a conversion type of string when using python's string formatting capabilities. More specifically, %s
converts a specified value to a string using the str()
function. Compare this with the %r
conversion type that uses the repr()
function for value conversion.
Take a look at the docs for string formatting.
You can also try dism /online /Enable-Feature /FeatureName:TelnetClient
Run this command with "Run as an administrator"
You can use charAt() function to find out spaces in string.
public class Test {
public static void main(String args[]) {
String fav="Hi Testing 12 3";
int counter=0;
for( int i=0; i<fav.length(); i++ ) {
if(fav.charAt(i) == ' ' ) {
counter++;
}
}
System.out.println("Number of spaces "+ counter);
//This will print Number of spaces 4
}
}
Important point about volatile
:
synchronized
and volatile
and locks.synchronized
variable. Using synchronized
keyword with a variable is illegal and will result in compilation error. Instead of using the synchronized
variable in Java, you can use the java volatile
variable, which will instruct JVM threads to read the value of volatile
variable from main memory and don’t cache it locally.volatile
keyword.Example usage of volatile
:
public class Singleton {
private static volatile Singleton _instance; // volatile variable
public static Singleton getInstance() {
if (_instance == null) {
synchronized (Singleton.class) {
if (_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
}
We are creating instance lazily at the time the first request comes.
If we do not make the _instance
variable volatile
then the Thread which is creating the instance of Singleton
is not able to communicate to the other thread. So if Thread A is creating Singleton instance and just after creation, the CPU corrupts etc, all other threads will not be able to see the value of _instance
as not null and they will believe it is still assigned null.
Why does this happen? Because reader threads are not doing any locking and until the writer thread comes out of a synchronized block, the memory will not be synchronized and value of _instance
will not be updated in main memory. With the Volatile keyword in Java, this is handled by Java itself and such updates will be visible by all reader threads.
Conclusion:
volatile
keyword is also used to communicate the content of memory between threads.
Example usage of without volatile:
public class Singleton{
private static Singleton _instance; //without volatile variable
public static Singleton getInstance(){
if(_instance == null){
synchronized(Singleton.class){
if(_instance == null) _instance = new Singleton();
}
}
return _instance;
}
The code above is not thread-safe. Although it checks the value of instance once again within the synchronized block (for performance reasons), the JIT compiler can rearrange the bytecode in a way that the reference to the instance is set before the constructor has finished its execution. This means the method getInstance() returns an object that may not have been initialized completely. To make the code thread-safe, the keyword volatile can be used since Java 5 for the instance variable. Variables that are marked as volatile get only visible to other threads once the constructor of the object has finished its execution completely.
Source
volatile
usage in Java:
The fail-fast iterators are typically implemented using a volatile
counter on the list object.
Iterator
is created, the current value of the counter is embedded in the Iterator
object.Iterator
operation is performed, the method compares the two counter values and throws a ConcurrentModificationException
if they are different.The implementation of fail-safe iterators is typically light-weight. They typically rely on properties of the specific list implementation's data structures. There is no general pattern.
You can pass the event as argument to the function and then prevent the default behaviour.
var OnSubmitTest = React.createClass({
render: function() {
doSomething = function(event){
event.preventDefault();
alert('it works!');
}
return <form onSubmit={this.doSomething}>
<button>Click me</button>
</form>;
}
});
If you want to call the incremented number directly in a function, this solution works bettter:
Function inc(ByRef data As Integer)
data = data + 1
inc = data
End Function
for example:
Wb.Worksheets(mySheet).Cells(myRow, inc(myCol))
If the function inc()
returns no value, the above line will generate an error.
I found the error occurred when a breakpoint is on a line that can't be broken on. I didn't show the tool-tip in effort to show the line directly after does not have that error.
assuming you have a SQL table called mydata - you can load data from a csv file as follows:
COPY MYDATA FROM '<PATH>/MYDATA.CSV' CSV HEADER;
For more details refer to: http://www.postgresql.org/docs/9.2/static/sql-copy.html
The spec says seconds:
http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-4.2.2
expires_in
OPTIONAL. The lifetime in seconds of the access token. For
example, the value "3600" denotes that the access token will
expire in one hour from the time the response was generated.
I agree with OP that it's careless for Google to not document this.
I think the proper way to use **kwargs
in Python when it comes to default values is to use the dictionary method setdefault
, as given below:
class ExampleClass:
def __init__(self, **kwargs):
kwargs.setdefault('val', value1)
kwargs.setdefault('val2', value2)
In this way, if a user passes 'val' or 'val2' in the keyword args
, they will be used; otherwise, the default values that have been set will be used.
If you ran into this issue when using TypeScript, you may need to add skipLibCheck: true
in your tsconfig.json
file.
A big part of the REST philosophy is to exploit as many standard features of the HTTP protocol as possible when designing your API. Applying that philosophy to authentication, client and server would utilize standard HTTP authentication features in the API.
Login screens are great for human user use cases: visit a login screen, provide user/password, set a cookie, client provides that cookie in all future requests. Humans using web browsers can't be expected to provide a user id and password with each individual HTTP request.
But for a REST API, a login screen and session cookies are not strictly necessary, since each request can include credentials without impacting a human user; and if the client does not cooperate at any time, a 401
"unauthorized" response can be given. RFC 2617 describes authentication support in HTTP.
TLS (HTTPS) would also be an option, and would allow authentication of the client to the server (and vice versa) in every request by verifying the public key of the other party. Additionally this secures the channel for a bonus. Of course, a keypair exchange prior to communication is necessary to do this. (Note, this is specifically about identifying/authenticating the user with TLS. Securing the channel by using TLS / Diffie-Hellman is always a good idea, even if you don't identify the user by its public key.)
An example: suppose that an OAuth token is your complete login credentials. Once the client has the OAuth token, it could be provided as the user id in standard HTTP authentication with each request. The server could verify the token on first use and cache the result of the check with a time-to-live that gets renewed with each request. Any request requiring authentication returns 401
if not provided.
You can use the -f operator
$a = "{0:D}" -f (get-date)
$a = "{0:dddd}" -f (get-date)
Spécificator Type Example (with [datetime]::now)
d Short date 26/09/2002
D Long date jeudi 26 septembre 2002
t Short Hour 16:49
T Long Hour 16:49:31
f Date and hour jeudi 26 septembre 2002 16:50
F Long Date and hour jeudi 26 septembre 2002 16:50:51
g Default Date 26/09/2002 16:52
G Long default Date and hour 26/09/2009 16:52:12
M Month Symbol 26 septembre
r Date string RFC1123 Sat, 26 Sep 2009 16:54:50 GMT
s Sortable string date 2009-09-26T16:55:58
u Sortable string date universal local hour 2009-09-26 16:56:49Z
U Sortable string date universal GMT hour samedi 26 septembre 2009 14:57:22 (oups)
Y Year symbol septembre 2002
Spécificator Type Example Output Example
dd Jour {0:dd} 10
ddd Name of the day {0:ddd} Jeu.
dddd Complet name of the day {0:dddd} Jeudi
f, ff, … Fractions of seconds {0:fff} 932
gg, … position {0:gg} ap. J.-C.
hh Hour two digits {0:hh} 10
HH Hour two digits (24 hours) {0:HH} 22
mm Minuts 00-59 {0:mm} 38
MM Month 01-12 {0:MM} 12
MMM Month shortcut {0:MMM} Sep.
MMMM complet name of the month {0:MMMM} Septembre
ss Seconds 00-59 {0:ss} 46
tt AM or PM {0:tt} ““
yy Years, 2 digits {0:yy} 02
yyyy Years {0:yyyy} 2002
zz Time zone, 2 digits {0:zz} +02
zzz Complete Time zone {0:zzz} +02:00
: Separator {0:hh:mm:ss} 10:43:20
/ Separator {0:dd/MM/yyyy} 10/12/2002
#include ...
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsScene scene;
QGraphicsView view(&scene);
QGraphicsPixmapItem item(QPixmap("c:\\test.png"));
scene.addItem(&item);
view.show();
return a.exec();
}
This should work. :) List of supported formats can be found here
Named pipes is a windows system for inter-process communication. In the case of SQL server, if the server is on the same machine as the client, then it is possible to use named pipes to tranfer the data, as opposed to TCP/IP.
I know @Martyn does not want full code, but I think this annotation its good for this question:
10 Open Source Android Apps which every Android developer must look into
Foursquared for Android is open-source, and have an interesting code pattern interacting with the foursquare REST API.
It just exits the method at that point. Once return
is executed, the rest of the code won't be executed.
eg.
public void test(int n) {
if (n == 1) {
return;
}
else if (n == 2) {
doStuff();
return;
}
doOtherStuff();
}
Note that the compiler is smart enough to tell you some code cannot be reached:
if (n == 3) {
return;
youWillGetAnError(); //compiler error here
}
Some of these answers are quite complicated, this is a bit easier:
$.fn.blink = function(time) {
var time = typeof time == 'undefined' ? 200 : time;
this.hide(0).delay(time).show(0);
}
$('#msg').blink();
This way you can set the initial day of the week.
moment.locale('en', {
week: {
dow: 6
}
});
moment.locale('en');
Make sure to use it with moment().weekday(1);
instead of moment.isoWeekday(1)
... and so you should do something like this:
set(tuple ((a,b) for a in range(3)) for b in range(3))
... and if needed convert back to list
Note your code contains Dir("thesentence")
which should be Dir(thesentence)
.
Change your code to this
Sub test()
thesentence = InputBox("Type the filename with full extension", "Raw Data File")
Range("A1").Value = thesentence
If Dir(thesentence) <> "" Then
MsgBox "File exists."
Else
MsgBox "File doesn't exist."
End If
End Sub
Using the int value 1002
seems to work for PHP 5.3.0:
public static function createDB() {
$dbHost="localhost";
$dbName="project";
$dbUser="admin";
$dbPassword="whatever";
$dbOptions=array(1002 => 'SET NAMES utf8',);
return new DB($dbHost, $dbName, $dbUser, $dbPassword,$dbOptions);
}
function createConnexion() {
return new PDO(
"mysql:host=$this->dbHost;dbname=$this->dbName",
$this->dbUser,
$this->dbPassword,
$this->dbOptions);
}
You can use process.stdout.write()
:
process.stdout.write("hello: ");
See the docs for details.
You might try using display: block or display: inline-block. A nice tutorial can be found here: http://robertnyman.com/2010/02/24/css-display-inline-block-why-it-rocks-and-why-it-sucks/
First make sure you have SessionMiddleware
and AuthenticationMiddleware
middlewares added to your MIDDLEWARE_CLASSES
setting.
The current user
is in request
object, you can get it by:
def sample_view(request):
current_user = request.user
print current_user.id
request.user
will give you a User
object representing the currently logged-in user. If a user isn't currently logged in, request.user
will be set to an instance of AnonymousUser
. You can tell them apart with the field is_authenticated
, like so:
if request.user.is_authenticated:
# Do something for authenticated users.
else:
# Do something for anonymous users.
You want to read raw lines to avoid problems with backslashes in the input (use -r
):
while read -r line; do
printf "<%s>\n" "$line"
done < file.txt
This will keep whitespace within the line, but removes leading and trailing whitespace. To keep those as well, set the IFS empty, as in
while IFS= read -r line; do
printf "%s\n" "$line"
done < file.txt
This now is an equivalent of cat < file.txt
as long as file.txt
ends with a newline.
Note that you must double quote "$line"
in order to keep word splitting from splitting the line into separate words--thus losing multiple whitespace sequences.
if you are using Spring version of 3.1 or newer you can specify "produces" in @RequestMapping
annotation. Example below works for me out of box. No need of register converter or anything else if you have web mvc enabled (@EnableWebMvc
).
@ResponseBody
@RequestMapping(value = "/photo2", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
public byte[] testphoto() throws IOException {
InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg");
return IOUtils.toByteArray(in);
}
If you're only getting these to manually pass into df.set_index()
, that's unnecessary. Just directly do df.set_index['your_col_name', drop=False]
, already.
It's very rare in pandas that you need to get an index as a Python list (unless you're doing something pretty funky, or else passing them back to NumPy), so if you're doing this a lot, it's a code smell that you're doing something wrong.
So, something like
DECLARE @i AS FLOAT = 2
SELECT @i / 3
SELECT CAST(@i / 3 AS DECIMAL(18,2))
I would however recomend that this be done in the UI/Report layer, as this will cuase loss of precision.
Function Remainder(Dividend As Variant, Divisor As Variant) As Variant
Remainder = Dividend - Divisor * Int(Dividend / Divisor)
End Function
This function always works and is the exact copy of the Excel function.
if you need a init.py file in your folder make a copy of the folder and delete init.py in that one to run your tests it works for local projects. If you need to run test regularly see if you can move your init.py to a separate file.
Since --with-ssl is not recognized anymore I just installed the libssl-dev
.
For debian based systems:
sudo apt-get install libssl-dev
For CentOS and RHEL
sudo yum install openssl-devel
To restart the make first clean up by:
make clean
Then start again and execute the following commands one after the other:
./configure
make
make test
make install
For further information on OpenSSL visit the Ubuntu Help Page on OpenSSL.
You used wrong letter case for year in line:
@JsonFormat(pattern = "YYYY-MM-dd HH:mm")
Should be:
@JsonFormat(pattern = "yyyy-MM-dd HH:mm")
With this change everything is working as expected.
Add "lodash.clonedeep": "^4.5.0"
to your package.json
. Then use like this:
import * as _ from 'lodash';
...
const copy = _.cloneDeep(original)
alert(document.documentElement.outerHTML);
I like using Google's Guava Joiner for this, e.g.:
Joiner.on(", ").skipNulls().join("Harry", null, "Ron", "Hermione");
would produce the same String as:
new String("Harry, Ron, Hermione");
ETA: Java 8 has similar support now:
String.join(", ", "Harry", "Ron", "Hermione");
Can't see support for skipping null values, but that's easily worked around.
Here are 4 items, with their index
0 1 2 3
K C A E
You want to move K to between A and E -- you might think position 3. You have be careful about your indexing here, because after the remove, all the indexes get updated.
So you remove item 0 first, leaving
0 1 2
C A E
Then you insert at 3
0 1 2 3
C A E K
To get the correct result, you should have used index 2. To make things consistent, you will need to send to (indexToMoveTo-1) if indexToMoveTo > indexToMove
, e.g.
bool moveUp = (listInstance.IndexOf(itemToMoveTo) > indexToMove);
listInstance.Remove(itemToMove);
listInstance.Insert(indexToMoveTo, moveUp ? (itemToMoveTo - 1) : itemToMoveTo);
This may be related to your problem. Note my code is untested!
EDIT: Alternatively, you could Sort
with a custom comparer (IComparer
) if that's applicable to your situation.
If you are developing for a modern browser, Instead of parsing the url parameters yourself- you can use the built in URL
functions to do it for you like this:
const parser = new URL(url || window.location);
parser.searchParams.set(key, value);
window.location = parser.href;
public ActionResult GetAjaxValue()
{
return Content("string value");
}
If we are use chosen dropdown list, then we can use below css(No JS/JQuery require)
<select chosen="{width: '100%'}" ng-
model="modelName" class="form-control input-
sm"
ng-
options="persons.persons as
persons.persons for persons in
jsonData"
ng-
change="anyFunction(anyParam)"
required>
<option value=""> </option>
</select>
<style>
.chosen-container .chosen-drop {
border-bottom: 0;
border-top: 1px solid #aaa;
top: auto;
bottom: 40px;
}
.chosen-container.chosen-with-drop .chosen-single {
border-top-left-radius: 0px;
border-top-right-radius: 0px;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
background-image: none;
}
.chosen-container.chosen-with-drop .chosen-drop {
border-bottom-left-radius: 0px;
border-bottom-right-radius: 0px;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
box-shadow: none;
margin-bottom: -16px;
}
</style>
For the usual usages of label
and input
, it's just easier to wrap input into a label like this:
import React from 'react'
const Field = props => (
<label>
<span>{props.label}</span>
<input type="text"/>
</label>
)
It's also makes it possible in checkboxes/radiobuttons to apply padding to root element and still getting feedback of click on input.
Accessing a name and assigning a name are different. In your case, you are just accessing a name.
If you assign to a variable within a function, that variable is assumed to be local unless you declare it global. In the absence of that, it is assumed to be global.
>>> x = 1 # global
>>> def foo():
print x # accessing it, it is global
>>> foo()
1
>>> def foo():
x = 2 # local x
print x
>>> x # global x
1
>>> foo() # prints local x
2
if you are using django use forloop.counter
instead of loop.counter
<ul>
{% for user in userlist %}
<li>
{{ user }} {{forloop.counter}}
</li>
{% if forloop.counter == 1 %}
This is the First user
{% endif %}
{% endfor %}
</ul>
It is also possible to have the third color (center). And different kinds of shapes.
For example in drawable/gradient.xml:
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#000000"
android:centerColor="#5b5b5b"
android:endColor="#000000"
android:angle="0" />
</shape>
This gives you black - gray - black (left to right) which is my favorite dark background atm.
Remember to add gradient.xml as background in your layout xml:
android:background="@drawable/gradient"
It is also possible to rotate, with:
angle="0"
gives you a vertical line
and with
angle="90"
gives you a horizontal line
Possible angles are:
0, 90, 180, 270.
Also there are few different kind of shapes:
android:shape="rectangle"
Rounded shape:
android:shape="oval"
and problably a few more.
Hope it helps, cheers!
You can set the output to a temporary file and the read the data from the file after that you can delete the temporary file.
echo %date%>temp.txt
set /p myVarDate= < temp.txt
echo Date is %myVarDate%
del temp.txt
In this variable myVarDate
contains the output of command.
var str = "";
for (var x = 0; x < 3; x++) {
(function() { // here's an anonymous function
for (var y = 0; y < 3; y++) {
for (var z = 0; z < 3; z++) {
// you have access to 'x' because of closures
str += "x=" + x + " y=" + y + " z=" + z + "<br />";
if (x == z && z == 2) {
return;
}
}
}
})(); // here, you execute your anonymous function
}
How's that? :)
Our computer science professor urged us to never use inline in a c++ program. When asked why, he kindly explained to us that modern compilers should detect when to use inline automatically.
So yes, the inline can be an optimization technique to be used wherever possible, but apparently this is something that is already done for you whenever it's possible to inline a function anyways.
make easy install again by downloading selenium webdriver from its website it is not installed properly.
Edit 1: extract the .tar.gz folder go inside the directory and run python setup.py install from terminal.make sure you have installed setuptools.
(\d+)\s+(\(.*?\))?\s?Z
Note the escaped parentheses, and the ?
(zero or once) quantifiers. Any of the groups you don't want to capture can be (?:
non-capture groups).
I agree about the spaces. \s
is a better option there. I also changed the quantifier to insure there are digits at the beginning. As far as newlines, that would depend on context: if the file is parsed line by line it won't be a problem. Another option is to anchor the start and end of the line (add a ^
at the front and a $
at the end).
I had the same error here but with glassfish server. Maybe it can help. I needed to configure the glassfish-web.xml file with the content inside the <resources>
from glassfish-resources.xml. As I got another error I could find this annotation in the server log:
Caused by: java.lang.RuntimeException: Error in parsing WEB-INF/glassfish-web.xml for archive [file:/C:/Users/Win/Documents/NetBeansProjects/svad/build/web/]: The xml element should be [glassfish-web-app] rather than [resources]
All I did then was to change the <resources>
tag and apply <glassfish-web-app>
in the glassfish-web.xml file.
If your table t1 and it's backup t2 have many columns, here's a compact way to do it.
In addition, my related problem was that only some of the columns were modified and many rows had no edits to these columns, so I wanted to leave those alone - basically restore a subset of columns from a backup of the entire table. If you want to just restore all rows, skip the where clause.
Of course the simpler way would be to delete and insert as select, but in my case I needed a solution with just updates.
The trick is that when you do select * from a pair of tables with duplicate column names, the 2nd one will get named _1. So here's what I came up with:
update (
select * from t1 join t2 on t2.id = t1.id
where id in (
select id from (
select id, col1, col2, ... from t2
minus select id, col1, col2, ... from t1
)
)
) set col1=col1_1, col2=col2_1, ...
I had the same problem and I solved in a slightly different way from the others. I am using angular 1.4.4.
In my case, I have a shell template that creates a CSS Bootstrap panel:
<div class="class-container panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">{{title}} </h3>
</div>
<div class="panel-body">
<sp-panel-body panelbodytpl="{{panelbodytpl}}"></sp-panel-body>
</div>
</div>
I want to include panel body templates depending on the route.
angular.module('MyApp')
.directive('spPanelBody', ['$compile', function($compile){
return {
restrict : 'E',
scope : true,
link: function (scope, element, attrs) {
scope.data = angular.fromJson(scope.data);
element.append($compile('<ng-include src="\'' + scope.panelbodytpl + '\'"></ng-include>')(scope));
}
}
}]);
I then have the following template included when the route is #/students
:
<div class="students-wrapper">
<div ng-controller="StudentsIndexController as studentCtrl" class="row">
<div ng-repeat="student in studentCtrl.students" class="col-sm-6 col-md-4 col-lg-3">
<sp-panel
title="{{student.firstName}} {{student.middleName}} {{student.lastName}}"
panelbodytpl="{{'/student/panel-body.html'}}"
data="{{student}}"
></sp-panel>
</div>
</div>
</div>
The panel-body.html template as follows:
Date of Birth: {{data.dob * 1000 | date : 'dd MMM yyyy'}}
Sample data in the case someone wants to have a go:
var student = {
'id' : 1,
'firstName' : 'John',
'middleName' : '',
'lastName' : 'Smith',
'dob' : 1130799600,
'current-class' : 5
}
Java9 has an "Ahead of time" compiler that does several optimizations at compile-time, rather than runtime, which can be seen as inlining.
ht editor can disassemble binaries in many formats. It is similar to Hiew, but open source.
To disassemble, open a binary, then press F6 and then select elf/image.
Or... you could simply use inverted logic. Let false
mean true
and vice versa.
Code sample
// bool[] isVisible = Enumerable.Repeat(true, 1000000).ToArray();
bool[] isHidden = new bool[1000000]; // Crazy-fast initialization!
// if (isVisible.All(v => v))
if (isHidden.All(v => !v))
{
// Do stuff!
}
To change the Android-x86 screen resolution on VirtualBox you need to:
Add custom screen resolution:
Android <6.0:
VBoxManage setextradata "VM_NAME_HERE" "CustomVideoMode1" "320x480x16"
Android >=6.0:
VBoxManage setextradata "VM_NAME_HERE" "CustomVideoMode1" "320x480x32"
Figure out what is the ‘hex’-value for your VideoMode
:
2.1. Start the VM
2.2. In GRUB menu enter a (Android >=6.0: e)
2.3. In the next screen append vga=ask
and press Enter
2.4. Find your resolution and write down/remember the 'hex'-value for Mode
column
Translate the value to decimal notation (for example 360
hex is 864
in decimal).
Go to menu.lst
and modify it:
4.1. From the GRUB menu select Debug Mode
4.2. Input the following:
mount -o remount,rw /mnt
cd /mnt/grub
vi menu.lst
4.3. Add vga=864
(if your ‘hex’-value is 360
). Now it should look like this:
kernel /android-2.3-RC1/kernel quiet root=/dev/ram0 androidboot_hardware=eeepc acpi_sleep=s3_bios,s3_mode DPI=160 UVESA_MODE=320x480 SRC=/android-2.3-RC1 SDCARD=/data/sdcard.img vga=864
4.4. Save it:
:wq
Unmount and reboot:
cd /
umount /mnt
reboot -f
Hope this helps.
@jeb
And after using this, the stderr seems to be inaccessible
No, try this:
@echo off 2>Nul 3>Nul 4>Nul
ben ali
mubarak 2>&1
gadeffi
..next ?
echo hello Tunisia
pause
But why it works?
sorry, i answer the question in frensh:
( la redirection par 3> est spécial car elle persiste, on va l'utiliser pour capturer le flux des erreurs 2> est on va le transformer en un flux persistant à l'ade de 3> ceci va nous permettre d'avoir une gestion des erreur pour tout notre environement de script..par la suite si on veux recuperer le flux 'stderr' il faut faire une autre redirection du handle 2> au handle 1> qui n'est autre que la console.. )
Swift 5
let desiredIndex: Int = 7
let substring = str[String.Index(encodedOffset: desiredIndex)...]
This substring variable will give you the result.
Simply here Int is converted to Index and then you can split the strings. Unless you will get errors.
File extensions do not have any bearing or impact on the content of the file. You can hold YAML content in files with any extension: .yml
, .yaml
or indeed anything else.
The (rather sparse) YAML FAQ recommends that you use .yaml
in preference to .yml
, but for historic reasons many Windows programmers are still scared of using extensions with more than three characters and so opt to use .yml
instead.
So, what really matters is what is inside the file, rather than what its extension is.
Add the file to a formData
object, and set the Content-Type
header to multipart/form-data
.
var formData = new FormData();
var imagefile = document.querySelector('#file');
formData.append("image", imagefile.files[0]);
axios.post('upload_file', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
You can use http_build_query()
to do that.
Generates a URL-encoded query string from the associative (or indexed) array provided.
you can use json_decode
function
foreach (json_decode($response) as $area)
{
print_r($area); // this is your area from json response
}
See this fiddle
Replace .on()
with once()
. Using once()
removes event listeners when the event is handled by the same function.
If this doesn't fix it, then reinstall restler with this in your package.json "restler": "git://github.com/danwrong/restler.git#9d455ff14c57ddbe263dbbcd0289d76413bfe07d"
This has to do with restler 0.10 misbehaving with node. you can see the issue closed on git here: https://github.com/danwrong/restler/issues/112 However, npm has yet to update this, so that is why you have to refer to the git head.
I use SwitchToThisWindow to bring the application to the forefront as in this example:
static class Program
{
[DllImport("User32.dll", SetLastError = true)]
static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
bool createdNew;
int iP;
Process currentProcess = Process.GetCurrentProcess();
Mutex m = new Mutex(true, "XYZ", out createdNew);
if (!createdNew)
{
// app is already running...
Process[] proc = Process.GetProcessesByName("XYZ");
// switch to other process
for (iP = 0; iP < proc.Length; iP++)
{
if (proc[iP].Id != currentProcess.Id)
SwitchToThisWindow(proc[0].MainWindowHandle, true);
}
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new form());
GC.KeepAlive(m);
}
you can not increase array size dynamically better you copy into new array
. Use System.arrayCopy
for that, it better than copying each element into new array. For reference
Why is System.arraycopy native in Java?.
private static Object resizeArray (Object oldArray, int newSize) {
int oldSize = java.lang.reflect.Array.getLength(oldArray);
Class elementType = oldArray.getClass().getComponentType();
Object newArray = java.lang.reflect.Array.newInstance(
elementType, newSize);
int preserveLength = Math.min(oldSize, newSize);
if (preserveLength > 0)
System.arraycopy(oldArray, 0, newArray, 0, preserveLength);
return newArray;
}
You will have to add it through code. Try this:
// 1.create UIView programmetically
var myView = UIView(frame: CGRectMake(100, 100, 100, 100))
// 2.add myView to UIView hierarchy
self.view.addSubview(myView)
// 3. add action to myView
let gesture = UITapGestureRecognizer(target: self, action: "someAction:")
// or for swift 2 +
let gestureSwift2AndHigher = UITapGestureRecognizer(target: self, action: #selector (self.someAction (_:)))
self.myView.addGestureRecognizer(gesture)
func someAction(sender:UITapGestureRecognizer){
// do other task
}
// or for Swift 3
func someAction(_ sender:UITapGestureRecognizer){
// do other task
}
// or for Swift 4
@objc func someAction(_ sender:UITapGestureRecognizer){
// do other task
}
// update for Swift UI
Text("Tap me!")
.tapAction {
print("Tapped!")
}
Integer
refers to the reference, that is, when comparing references you're comparing if they point to the same object, not value. Hence, the issue you're seeing. The reason it works so well with plain int
types is that it unboxes the value contained by the Integer
.
May I add that if you're doing what you're doing, why have the if
statement to begin with?
mismatch = ( cdiCt != null && cdsCt != null && !cdiCt.equals( cdsCt ) );
just add .setMaster("local")
to your code as shown below:
val conf = new SparkConf().setAppName("Second").setMaster("local")
It worked for me ! Happy coding !
If you'd like something a bit more readable, you can do this:
A = np.squeeze(np.asarray(M))
Equivalently, you could also do: A = np.asarray(M).reshape(-1)
, but that's a bit less easy to read.
Although, I had all proper babel loaders in my .babelrc config file. This build script with parcel-bundler was producing the unexpected token error < and mime type errors in the browser console for me on manual page refresh.
"scripts": {
"build": "parcel build ui/index.html --public-url ./",
"dev": "parcel watch ui/index.html"
}
Updating the build script fixed the issues for me.
"scripts": {
"build": "parcel build ui/index.html",
"ui": "parcel watch ui/index.html"
}
Hibernate also is picky about the capitalization. By default it's going to be the class name with the First letter Capitalized. So if your class is called FooBar
, don't pass "foobar"
. You have to pass "FooBar"
with that exact capitalization for it to work.
Following directive could be used with Reactive-Forms to trim all form fields so standart Validators.required
work fine:
@Directive({
selector: '[formControl], [formControlName]',
})
export class TrimFormFieldsDirective {
@Input() type: string;
constructor(@Optional() private formControlDir: FormControlDirective,
@Optional() private formControlName: FormControlName) {}
@HostListener('blur')
@HostListener('keydown.enter')
trimValue() {
const control = this.formControlDir?.control || this.formControlName?.control;
if (typeof control.value === 'string' && this.type !== 'password') {
control.setValue(control.value.trim());
}
}
}
On iOS, it currently does not matter if you use int
or NSInteger
. It will matter more if/when iOS moves to 64-bits.
Simply put, NSInteger
s are int
s in 32-bit code (and thus 32-bit long) and long
s on 64-bit code (long
s in 64-bit code are 64-bit wide, but 32-bit in 32-bit code). The most likely reason for using NSInteger
instead of long
is to not break existing 32-bit code (which uses int
s).
CGFloat
has the same issue: on 32-bit (at least on OS X), it's float
; on 64-bit, it's double
.
Update: With the introduction of the iPhone 5s, iPad Air, iPad Mini with Retina, and iOS 7, you can now build 64-bit code on iOS.
Update 2: Also, using NSInteger
s helps with Swift code interoperability.
var list = (from t in ctn.Items
where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
orderby t.Delivery.SubmissionDate
select t).Take(5);
l = Location.find(:id => id, :select => "name, website, city", :limit => 1)
...or...
l = Location.find_by_sql(:conditions => ["SELECT name, website, city FROM locations WHERE id = ? LIMIT 1", id])
This reference doc gives you the entire list of options you can use with .find
, including how to limit by number, id, or any other arbitrary column/constraint.
l = Location.where(["id = ?", id]).select("name, website, city").first
Ref: Active Record Query Interface
You can also swap the order of these chained calls, doing .select(...).where(...).first
- all these calls do is construct the SQL query and then send it off.
The rule for the caret is:
A caret at the line end, appends the next line, the first character of the appended line will be escaped.
You can use the caret multiple times, but the complete line must not exceed the maximum line length of ~8192 characters (Windows XP, Windows Vista, and Windows 7).
echo Test1
echo one ^
two ^
three ^
four^
*
--- Output ---
Test1
one two three four*
echo Test2
echo one & echo two
--- Output ---
Test2
one
two
echo Test3
echo one & ^
echo two
--- Output ---
Test3
one
two
echo Test4
echo one ^
& echo two
--- Output ---
Test4
one & echo two
To suppress the escaping of the next character you can use a redirection.
The redirection has to be just before the caret. But there exist one curiosity with redirection before the caret.
If you place a token at the caret the token is removed.
echo Test5
echo one <nul ^
& echo two
--- Output ---
Test5
one
two
echo Test6
echo one <nul ThisTokenIsLost^
& echo two
--- Output ---
Test6
one
two
And it is also possible to embed line feeds into the string:
setlocal EnableDelayedExpansion
set text=This creates ^
a line feed
echo Test7: %text%
echo Test8: !text!
--- Output ---
Test7: This creates
Test8: This creates
a line feed
The empty line is important for the success. This works only with delayed expansion, else the rest of the line is ignored after the line feed.
It works, because the caret at the line end ignores the next line feed and escapes the next character, even if the next character is also a line feed (carriage returns are always ignored in this phase).
Based on Stack Overflow questions Unix cut, remove first token and https://stackoverflow.com/a/15903654/781312:
(octal=$(echo -n ? | od -t o1 | head -1 | cut -d' ' -f2- | sed -e 's#\([0-9]\+\) *#\\0\1#g')
echo Octal representation is following $octal
echo -e "$octal")
Output is the following.
Octal representation is following \0342\0230\0240
?
You might want to consider abstracting it out into a function like this:
function dialog(message, yesCallback, noCallback) {
$('.title').html(message);
var dialog = $('#modal_dialog').dialog();
$('#btnYes').click(function() {
dialog.dialog('close');
yesCallback();
});
$('#btnNo').click(function() {
dialog.dialog('close');
noCallback();
});
}
You can then use it like this:
dialog('Are you sure you want to do this?',
function() {
// Do something
},
function() {
// Do something else
}
);
Function attributes can be used to write light-weight closures that wrap code and associated data together:
#!/usr/bin/env python
SW_DELTA = 0
SW_MARK = 1
SW_BASE = 2
def stopwatch():
import time
def _sw( action = SW_DELTA ):
if action == SW_DELTA:
return time.time() - _sw._time
elif action == SW_MARK:
_sw._time = time.time()
return _sw._time
elif action == SW_BASE:
return _sw._time
else:
raise NotImplementedError
_sw._time = time.time() # time of creation
return _sw
# test code
sw=stopwatch()
sw2=stopwatch()
import os
os.system("sleep 1")
print sw() # defaults to "SW_DELTA"
sw( SW_MARK )
os.system("sleep 2")
print sw()
print sw2()
1.00934004784
2.00644397736
3.01593494415
Use the requests library, pretty print the results so you can better locate the keys/values you want to extract, and then use nested for loops to parse the data. In the example I extract step by step driving directions.
import json, requests, pprint
url = 'http://maps.googleapis.com/maps/api/directions/json?'
params = dict(
origin='Chicago,IL',
destination='Los+Angeles,CA',
waypoints='Joplin,MO|Oklahoma+City,OK',
sensor='false'
)
data = requests.get(url=url, params=params)
binary = data.content
output = json.loads(binary)
# test to see if the request was valid
#print output['status']
# output all of the results
#pprint.pprint(output)
# step-by-step directions
for route in output['routes']:
for leg in route['legs']:
for step in leg['steps']:
print step['html_instructions']
//vanilla php
Class Date {
public static function date_added($time){
date_default_timezone_set('Africa/Lagos');//or choose your location
return date('l F Y g:i:s ',$time);
}
}
SELECT s.id, s.name, LENGTH(s.name) len, ASCII(s.name) ASCCCI FROM table_name s ORDER BY ASCCCI,len,NAME ASC;
Not forgetting
.equalsIgnoreCase(String)
if you're not worried about that sort of thing...
"Reuse types" is not always the problem when this error occurs.
When adding a reference to an older service, click 'advanced' and there 'Add Web Reference'. Now link to your wsdl and everything should be working.
I would rather prefer using only comprehension lists:
[[int(y) for y in x] for x in T1]
This is how i did it. I have a nav block that is below the header once you scroll the page down it 'sticks' to the top of the window. If you scroll back to top, nav goes back in it's place I use position:fixed in CSS for non mobile platforms and iOS5. Other Mobile versions do have that 'lag' until screen stops scrolling before it's set.
// css
#sticky.stick {
width:100%;
height:50px;
position: fixed;
top: 0;
z-index: 1;
}
// jquery
//sticky nav
function sticky_relocate() {
var window_top = $(window).scrollTop();
var div_top = $('#sticky-anchor').offset().top;
if (window_top > div_top)
$('#sticky').addClass('stick');
else
$('#sticky').removeClass('stick');
}
$(window).scroll(function(event){
// sticky nav css NON mobile way
sticky_relocate();
var st = $(this).scrollTop();
// sticky nav iPhone android mobile way iOS<5
if (navigator.userAgent.match(/OS 5(_\d)+ like Mac OS X/i)) {
//do nothing uses sticky_relocate() css
} else if ( navigator.userAgent.match(/(iPod|iPhone|iPad)/i) || navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) ) {
var window_top = $(window).scrollTop();
var div_top = $('#sticky-anchor').offset().top;
if (window_top > div_top) {
$('#sticky').css({'top' : st , 'position' : 'absolute' });
} else {
$('#sticky').css({'top' : 'auto' });
}
};
The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.
Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.
If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/
is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/
or http://s3-external-1.amazonaws.com/bucket/
.¹
The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].
S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com
. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.
If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.
However... the two endpoints do not offer the same functionality.
Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.
Choose the correct type of endpoint (REST or web site) for your application:
http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff
¹ s3-external-1.amazonaws.com
has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com
. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2
had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1
so s3-external-2
appears to have no purpose except backwards-compatibility.
I realize this is stale for a while and an answer had been selected, but how about the alternative to allow the foreign key to be NULL and then choose ON DELETE SET NULL.
Basically, your table should be changed like so:
ALTER TABLE 'bericht'
DROP FOREIGN KEY 'your_foreign_key';
ALTER TABLE 'bericht'
ADD CONSTRAINT 'your_foreign_key' FOREIGN KEY ('column_foreign_key') REFERENCES 'other_table' ('column_parent_key') ON UPDATE CASCADE ON DELETE SET NULL;
Personally I would recommend using both "ON UPDATE CASCADE" as well as "ON DELETE SET NULL" to avoid unnecessary complications, however your set up may dictate a different approach.
Hope this helps.
This works for me on a similar issue where I failed to delete the user due to the reference. Thank you
@ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST,CascadeType.REFRESH})
Try use :before and :after (ie9+)
#wrapper{
width:400px;
height:400px;
margin:0 auto;
border: 1px #000 solid;
position:relative;}
#wrapper:after,
#wrapper:before{
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
content:'';
background: #1e5799;
background: -moz-linear-gradient(top, #1e5799 0%, #2989d8 50%, #207cca 51%, #7db9e8 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#1e5799), color-stop(50%,#2989d8), color-stop(51%,#207cca), color-stop(100%,#7db9e8));
background: -webkit-linear-gradient(top, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%);
background: -o-linear-gradient(top, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%);
background: -ms-linear-gradient(top, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%);
background: linear-gradient(to bottom, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%);
opacity:1;
z-index:-1;
-webkit-transition: all 2s ease-out;
-moz-transition: all 2s ease-out;
-ms-transition: all 2s ease-out;
-o-transition: all 2s ease-out;
transition: all 2s ease-out;
}
#wrapper:after{
opacity:0;
background: #87e0fd;
background: -moz-linear-gradient(top, #87e0fd 0%, #53cbf1 40%, #05abe0 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#87e0fd), color-stop(40%,#53cbf1), color-stop(100%,#05abe0));
background: -webkit-linear-gradient(top, #87e0fd 0%,#53cbf1 40%,#05abe0 100%);
background: -o-linear-gradient(top, #87e0fd 0%,#53cbf1 40%,#05abe0 100%);
background: -ms-linear-gradient(top, #87e0fd 0%,#53cbf1 40%,#05abe0 100%);
background: linear-gradient(to bottom, #87e0fd 0%,#53cbf1 40%,#05abe0 100%);
}
#wrapper:hover:before{opacity:0;}
#wrapper:hover:after{opacity:1;}
I was also having above doubt, what worked for me is
ALTER TABLE `your_table` CHANGE `property` `property`
VARCHAR(whatever_you_want) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;
Run dos2unix or similar utility on it to remove the carriage returns (^M).
This message indicates that your file has dos-style lineendings:
-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory
Utilities like dos2unix
will fix it:
dos2unix <backup.bash >improved-backup.sh
Or, if no such utility is installed, you can accomplish the same thing with translate:
tr -d "\015\032" <backup.bash >improved-backup.sh
As for how those characters got there in the first place, @MadPhysicist had some good comments.
I think that the Import-Module
is trying to find the module in the default directory C:\Windows\System32\WindowsPowerShell\v1.0\Modules
.
Try to put the full path, or copy it to C:\Windows\System32\WindowsPowerShell\v1.0\Modules
You can use this syntax to add an index and control the kind of index (HASH or BTREE).
create index your_index_name on your_table_name(your_column_name) using HASH;
or
create index your_index_name on your_table_name(your_column_name) using BTREE;
You can learn about differences between BTREE and HASH indexes here: http://dev.mysql.com/doc/refman/5.5/en/index-btree-hash.html
You can use =A4, in case A4 is having long formula
Everyone has overcomplicated this answer:
some_int = <256 bit integer>
some_bytes = some_int.to_bytes(32, sys.byteorder)
my_bytearray = bytearray(some_bytes)
You just need to know the number of bytes that you are trying to convert. In my use cases, normally I only use this large of numbers for crypto, and at that point I have to worry about modulus and what-not, so I don't think this is a big problem to be required to know the max number of bytes to return.
Since you are doing it as 768-bit math, then instead of 32 as the argument it would be 96.
Yes you can, just pass the integer param to the split method
String stSplit = "apple=fruit table price=5"
stSplit.split("=", 2);
Here is a java doc reference : String#split(java.lang.String, int)
There are various way to concatenate strings in kotlin Example -
a = "Hello" , b= "World"
Using + operator
a+b
Using plus()
operator
a.plus(b)
Note - + is internally converted to .plus() method only
In above 2 methods, a new string object is created as strings are immutable. if we want to modify the existing string, we can use StringBuilder
StringBuilder str = StringBuilder("Hello").append("World")
You can access user data directly in the twig template without requesting anything in the controller. The user is accessible like that : app.user
.
Now, you can access every property of the user. For example, you can access the username like that : app.user.username
.
Warning, if the user is not logged, the app.user
is null.
If you want to check if the user is logged, you can use the is_granted
twig function. For example, if you want to check if the user has ROLE_ADMIN
, you just have to do is_granted("ROLE_ADMIN")
.
So, in every of your pages you can do :
{% if is_granted("ROLE") %}
Hi {{ app.user.username }}
{% endif %}
You might have an undefined property in the object.
If using the method of Object.keys(data).length
is used those properties will also be counted.
You might want to filter them out out.
Object.keys(data).filter((v) => {return data[v] !== undefined}).length
Here is one way that I hope is easy to understand:
$(document).ready(function() {
$("#chkdwn2").click(function() {
if ($(this).is(":checked")) {
$("#dropdown").prop("disabled", true);
} else {
$("#dropdown").prop("disabled", false);
}
});
});
You were on the right track, but there were some problems with the code you posted. First of all, there was no closing bracket for the while loop. Secondly, $line_of_text would be overwritten with every loop iteration, which is fixed by changing the = to a .= in the loop. Third, you're exploding the literal characters '\n' and not an actual newline; in PHP, single quotes will denote literal characters, but double quotes will actually interpret escaped characters and variables.
<?php
$file = fopen("members.txt", "r");
$i = 0;
while (!feof($file)) {
$line_of_text .= fgets($file);
}
$members = explode("\n", $line_of_text);
fclose($file);
print_r($members);
?>
If you use the NetBeans IDE (latest version at this time is 6.5.1), you can use it to create a basic GUI java application using File->New Project and choose the Java category then Java Desktop Application.
Once created, you will have a simple bare bones GUI app which contains an about box that can be opened using a menu selection. You should be able to adapt this to your needs and learn how to open a dialog from a button click.
You will be able to edit the dialog visually. Delete the items that are there and add some text areas. Play around with it and come back with more questions if you get stuck :)
As an augmentation to the other answers, on Mac OS X, the "Preferences" menu is under Eclipse, not Window (unlike Windows/Linux Eclipse distributions). Everything else is still the same as pointed out by other answers past this point.
IE: Java Formatter available under:
Eclipse > | # Not Window!
Preferences > |
Java > |
Code Style > |
Formatter |
From here, edit the formatter and the tab policy can be set under "Indentation".
This seems like the best choice to me:
val1, val2, ignored1, ignored2 = some_function()
It's not cryptic or ugly (like the func()[index] method), and clearly states your purpose.
Open up your git bash and type
echo $HOME
This shall be the same folder as you get when you open your command window (cmd) and type
echo %USERPROFILE%
And – of course – the .ssh
folder shall be present on THAT directory.
Ahh... nevermind. It's always the search after the question is posed that yields the answer. My object that is being serialized is obj
and has already been defined. Adding an XMLSerializerNamespace with a single empty namespace to the collection does the trick.
In VB like this:
Dim xs As New XmlSerializer(GetType(cEmploymentDetail))
Dim ns As New XmlSerializerNamespaces()
ns.Add("", "")
Dim settings As New XmlWriterSettings()
settings.OmitXmlDeclaration = True
Using ms As New MemoryStream(), _
sw As XmlWriter = XmlWriter.Create(ms, settings), _
sr As New StreamReader(ms)
xs.Serialize(sw, obj, ns)
ms.Position = 0
Console.WriteLine(sr.ReadToEnd())
End Using
in C# like this:
//Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
//Add an empty namespace and empty value
ns.Add("", "");
//Create the serializer
XmlSerializer slz = new XmlSerializer(someType);
//Serialize the object with our own namespaces (notice the overload)
slz.Serialize(myXmlTextWriter, someObject, ns);
On a Scientific Linux 6.7 system, the man page on rsync says:
--ignore-times don't skip files that match size and time
I have two files with identical contents, but with different creation dates:
[root@windstorm ~]# ls -ls /tmp/master/usercron /tmp/new/usercron
4 -rwxrwx--- 1 root root 1595 Feb 15 03:45 /tmp/master/usercron
4 -rwxrwx--- 1 root root 1595 Feb 16 04:52 /tmp/new/usercron
[root@windstorm ~]# diff /tmp/master/usercron /tmp/new/usercron
[root@windstorm ~]# md5sum /tmp/master/usercron /tmp/new/usercron
368165347b09204ce25e2fa0f61f3bbd /tmp/master/usercron
368165347b09204ce25e2fa0f61f3bbd /tmp/new/usercron
With --size-only
, the two files are regarded the same:
[root@windstorm ~]# rsync -v --size-only -n /tmp/new/usercron /tmp/master/usercron
sent 29 bytes received 12 bytes 82.00 bytes/sec
total size is 1595 speedup is 38.90 (DRY RUN)
With --ignore-times
, the two files are regarded different:
[root@windstorm ~]# rsync -v --ignore-times -n /tmp/new/usercron /tmp/master/usercron
usercron
sent 32 bytes received 15 bytes 94.00 bytes/sec
total size is 1595 speedup is 33.94 (DRY RUN)
So it does not looks like --ignore-times
has any effect at all.
What will you have? You'll probably end up with a default search and a search that you load from somewhere. Default search requires a default constructor, so make one like Dismissile has already suggested.
If you load the search criteria from elsewhere, then you should probably have some mapping logic.
can use html5 mark tag within paragraph and heading tag.
<p>lorem ipsum <mark>Highlighted Text</mark> dolor sit.</p>
_x000D_
When you want to check the condition at the beginning of the loop, simply negate the condition on a standard while
loop:
while(!cond) { ... }
If you need it at the end, use a do
... while
loop and negate the condition:
do { ... } while(!cond);
What you need is properly a service:
.factory('DataLayer', ['$http',
function($http) {
var factory = {};
var locations;
factory.getLocations = function(success) {
if(locations){
success(locations);
return;
}
$http.get('locations/locations.json').success(function(data) {
locations = data;
success(locations);
});
};
return factory;
}
]);
The locations
would be cached in the service which worked as singleton model. This is the right way to fetch data.
Use this service DataLayer
in your controller and directive is ok as following:
appControllers.controller('dummyCtrl', function ($scope, DataLayer) {
DataLayer.getLocations(function(data){
$scope.locations = data;
});
});
.directive('map', function(DataLayer) {
return {
restrict: 'E',
replace: true,
template: '<div></div>',
link: function(scope, element, attrs) {
DataLayer.getLocations(function(data) {
angular.forEach(data, function(location, key){
//do something
});
});
}
};
});
If you want "insert or replace" semantics, use this syntax:
A[key] = value; // <-- insert or replace semantics
It's more efficient and readable than calls involving "ContainsKey()" or "Remove()" prior to "Add()".
So in your case:
rct3Features[items[0]] = items[1];
You're using the declarative style of specifying your pipeline, so you must not use try/catch blocks (which are for Scripted Pipelines), but the post section. See: https://jenkins.io/doc/book/pipeline/syntax/#post-conditions
Hard links are very useful when doing incremental backups. See rsnapshot, for example. The idea is to do copy using hard links:
The new backup will not take up any extra space apart from any changes you've made, since all the incremental backups will point to the same set of inodes for files which haven't changed.
Are you running Skype? This has been the best solution I have found to get rid of the "cannot empty the clipboard error" in Excel 2007 & 2010. Delete the Skype add-on in IE and/or Firefox and good-bye annoying error!
In reply to rjacobs7 post on February 28, 2011
Cannot clear clipboard error - Windows 7, Excel 2010 - This error occurs nearly every time a drag and drop of cell contents is attempted. I've had this same error over the past 10 years on older computers and older versions of Windows and Office. It has now reoccurred with a new laptop running Windows 7 64 bit and Office 2010. The issue can be replicated only if a browser - IE or Firefox - is open at the same time that Excel is open. Having Word and/or Outlook open at the same time will not cause the problem to occur unless a browser is also open. This error is extremely irritating and no solutions from Microsoft or other posts on this issue resolve it.
I have a solution - at least for me! Delete the Skype add-in in IE and Firefox and the "cannot clear clipboard" error after a drag and drop goes away when IE and/or Firefox are running. Apparently some sort of memory-management issue with Skype, Office and the browsers.
I found the most simple approach by changing the default encoding of the whole script to be 'UTF-8':
import sys
reload(sys)
sys.setdefaultencoding('utf8')
any open
, print
or other statement will just use utf8
.
Works at least for Python 2.7.9
.
Thx goes to https://markhneedham.com/blog/2015/05/21/python-unicodeencodeerror-ascii-codec-cant-encode-character-uxfc-in-position-11-ordinal-not-in-range128/ (look at the end).
You're very close already, you just need to return the new object that you want. In this case, the same one except with the launches value incremented by 10:
var rockets = [_x000D_
{ country:'Russia', launches:32 },_x000D_
{ country:'US', launches:23 },_x000D_
{ country:'China', launches:16 },_x000D_
{ country:'Europe(ESA)', launches:7 },_x000D_
{ country:'India', launches:4 },_x000D_
{ country:'Japan', launches:3 }_x000D_
];_x000D_
_x000D_
var launchOptimistic = rockets.map(function(elem) {_x000D_
return {_x000D_
country: elem.country,_x000D_
launches: elem.launches+10,_x000D_
} _x000D_
});_x000D_
_x000D_
console.log(launchOptimistic);
_x000D_
It is actually possible only using CSS, however, the image you use to replace must be the same size as the original facebook log in button. Fortunately Facebook delivers the button in different sizes.
From facebook:
size - Different sized buttons: small, medium, large, xlarge - the default is medium. https://developers.facebook.com/docs/reference/plugins/login/
Set the login iframe opacity to 0 and show a background image in the parent div
.fb_iframe_widget iframe {
opacity: 0;
}
.fb_iframe_widget {
background-image: url(another-button.png);
background-repeat: no-repeat;
}
If you use an image that is bigger than the original facebook button, the part of the image that is outside the width and height of the original button will not be clickable.
You should add more details about your distribution, for example under Ubuntu the right way to do this is to add a custom .conf
file to /etc/ld.so.conf.d
, for example
sudo gedit /etc/ld.so.conf.d/randomLibs.conf
inside the file you are supposed to write the complete path to the directory that contains all the libraries that you wish to add to the system, for example
/home/linux/myLocalLibs
remember to add only the path to the dir, not the full path for the file, all the libs inside that path will be automatically indexed.
Save and run sudo ldconfig
to update the system with this libs.
Did you include "Management Tools" as a chosen option during setup?
Ensure this option is selected, and SQL Server Management Studio will be installed on the machine.
Easy:
print my_queryset.query
For example:
from django.contrib.auth.models import User
print User.objects.filter(last_name__icontains = 'ax').query
It should also be mentioned that if you have DEBUG = True, then all of your queries are logged, and you can get them by accessing connection.queries:
from django.db import connections
connections['default'].queries
The django debug toolbar project uses this to present the queries on a page in a neat manner.
You need to declare out
as a byte array with a length equal to the lengths of ciphertext
and mac
added together, and then copy ciphertext
over the beginning of out
and mac
over the end, using arraycopy.
byte[] concatenateByteArrays(byte[] a, byte[] b) {
byte[] result = new byte[a.length + b.length];
System.arraycopy(a, 0, result, 0, a.length);
System.arraycopy(b, 0, result, a.length, b.length);
return result;
}
On OSX, I used MacPorts to address the same problem when connecting to my siteground database. Siteground appears to be using 5.0.77mm0.1-log, but creating a new user account didn't fix the problem. This is what did
sudo port install php5-mysql -mysqlnd +mysql5
This downgrades the mysql driver that php will use.
Following madlep's answer you can also just copy one directory from another branch with the directory blob.
git checkout other-branch app/**
As to the op's question if you've only changed one file in there this will work fine ^_^
I had a requirement to provide a report showing details by month where the date field was formatted as date & time, I simply changed the formatting of the date column to "General" and then used the following formula in a new column,
=CONCATENATE(YEAR(C2),MONTH(C2))
Following code can be used to initialize mapper in REST client mock. The mapper
field is private and needs to be set during unit test setup.
import org.mockito.internal.util.reflection.FieldSetter;
new FieldSetter(client, Client.class.getDeclaredField("mapper")).set(new Mapper());
background.xml in drawable folder.
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF"/>
<stroke
android:width="3dp"
android:color="#0FECFF" />
//specify gradient
<gradient
android:startColor="#ffffffff"
android:endColor="#110000FF"
android:angle="90"/>
<padding
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp"/>
<corners
android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
</shape>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="210dp"
android:orientation="vertical"
android:layout_marginBottom="10dp"
android:background="@drawable/background">
$(this).closest('form').find('input,textarea,select').not(':image').prop('disabled', true);
export PATH=$PATH:/usr/local/mysql/bin/
should fix the issue for you as the system is not able to find the mysql_config file.
This can now also happen in Node.js as of version 14.
It happens when you declare your package type as module in your package.json
. If you do this, certain CommonJS variables can't be used, including require
.
To fix this, remove "type": "module"
from your package.json
and make sure you don't have any files ending with .mjs
.
You can use serializeArray
[docs] and add the additional data:
var data = $('#myForm').serializeArray();
data.push({name: 'wordlist', value: wordlist});
$.post("page.php", data);
Try this code. This does what you want.
LOGIC
""
with blanks and write to the new file at the same time.CODE (TRIED AND TESTED)
Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" _
(ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long
Private Const MAX_PATH As Long = 260
'~~> Change this where and how you want to save the file
Const FlName = "C:\Users\Siddharth Rout\Desktop\MyWorkbook.txt"
Sub Sample()
Dim tmpFile As String
Dim MyData As String, strData() As String
Dim entireline As String
Dim filesize As Integer
'~~> Create a Temp File
tmpFile = TempPath & Format(Now, "ddmmyyyyhhmmss") & ".txt"
ActiveWorkbook.SaveAs Filename:=tmpFile _
, FileFormat:=xlText, CreateBackup:=False
'~~> Read the entire file in 1 Go!
Open tmpFile For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
strData() = Split(MyData, vbCrLf)
'~~> Get a free file handle
filesize = FreeFile()
'~~> Open your file
Open FlName For Output As #filesize
For i = LBound(strData) To UBound(strData)
entireline = Replace(strData(i), """", "")
'~~> Export Text
Print #filesize, entireline
Next i
Close #filesize
MsgBox "Done"
End Sub
Function TempPath() As String
TempPath = String$(MAX_PATH, Chr$(0))
GetTempPath MAX_PATH, TempPath
TempPath = Replace(TempPath, Chr$(0), "")
End Function
SNAPSHOTS
Actual Workbook
After Saving
You could use the setTimeout()
function:
// Your delay in milliseconds
var delay = 1000;
setTimeout(function(){ window.location = URL; }, delay);
search
⇒ find something anywhere in the string and return a match object.
match
⇒ find something at the beginning of the string and return a match object.
melt()
from the reshape2 package gets you close ...
library(reshape2)
(res <- melt(as.data.frame(mat), id="time"))
# time variable value
# 1 0.0 C_0 0.1
# 2 0.5 C_0 0.2
# 3 1.0 C_0 0.3
# 4 0.0 C_1 0.3
# 5 0.5 C_1 0.4
# 6 1.0 C_1 0.5
... although you may want to post-process its results to get your preferred column names and ordering.
setNames(res[c("variable", "time", "value")], c("name", "time", "val"))
# name time val
# 1 C_0 0.0 0.1
# 2 C_0 0.5 0.2
# 3 C_0 1.0 0.3
# 4 C_1 0.0 0.3
# 5 C_1 0.5 0.4
# 6 C_1 1.0 0.5
Edit: thought of something else.
You say you're creating a form dynamically - do you really mean a <form> and its contents 'cause asp.net takes issue with multiple forms on a page and it's already creating one uberform for you.
If you need to concatenate paths with quotes, you can use =
to replace quotes in a variable. This does not require you to know if the path already contains quotes or not. If there are no quotes, nothing is changed.
@echo off
rem Paths to combine
set DIRECTORY="C:\Directory with spaces"
set FILENAME="sub directory\filename.txt"
rem Combine two paths
set COMBINED="%DIRECTORY:"=%\%FILENAME:"=%"
echo %COMBINED%
rem This is just to illustrate how the = operator works
set DIR_WITHOUT_SPACES=%DIRECTORY:"=%
echo %DIR_WITHOUT_SPACES%
Data Flow Diagrams The formal, structured analysis approach employs the data-flow diagram (DFD) to assist in the functional decomposition process. I learned structured analysis techniques from DeMarco [7], and those techniques are representative of present conventions. To summarize, DFD's are comprised of four components:
The full paramiko distribution ships with a lot of good demos.
In the demos subdirectory, demo.py
and interactive.py
have full interactive TTY examples which would probably be overkill for your situation.
In your example above ssh_stdin
acts like a standard Python file object, so ssh_stdin.write
should work so long as the channel is still open.
I've never needed to write to stdin, but the docs suggest that a channel is closed as soon as a command exits, so using the standard stdin.write
method to send a password up probably won't work. There are lower level paramiko commands on the channel itself that give you more control - see how the SSHClient.exec_command
method is implemented for all the gory details.
The language specification says on p.64f
A construct of the form < T > ( ... ) => { ... } could be parsed as an arrow function expression with a type parameter or a type assertion applied to an arrow function with no type parameter. It is resolved as the former[..]
example:
// helper function needed because Backbone-couchdb's sync does not return a jqxhr
let fetched = <
R extends Backbone.Collection<any> >(c:R) => {
return new Promise(function (fulfill, reject) {
c.fetch({reset: true, success: fulfill, error: reject})
});
};
Solution:
That's it! Thanks Arjun Paudel for the link. Here's the solution as found on XNA Creator's Club Online. It's by Stephen Styrchak.
The following error suggests me to believe that you are compiling for 64bit:
The 'Microsoft .ACE.OELDB.12.0' provider is not registered on the local machine
I dont have express edition but are following steps valid in 2008 express?
http://forums.xna.com/forums/t/4377.aspx#22601
http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/ed374d4f-5677-41cb-bfe0-198e68810805/?prof=required
- Arjun Paudel
In VC# Express
, this property is missing, but you can still create an x86 configuration if you know where to look.
It looks like a long list of steps, but once you know where these things are it's a lot easier. Anyone who only has VC# Express
will probably find this useful. Once you know about Configuration Manager
, it'll be much more intuitive the next time.
1.In VC# Express 2005, go to Tools -> Options
.
2.In the bottom-left corner of the Options dialog, check the box that says, "Show all settings"
.
3.In the tree-view on the left hand side, select "Projects and Solutions"
.
4.In the options on the right, check the box that says, "Show advanced build configuraions."
5.Click OK
.
6.Go to Build -> Configuration Manager
...
7.In the Platform column next to your project, click the combobox and select "<New...>"
.
8.In the "New platform" setting, choose "x86"
.
9.Click OK
.
10.Click Close
.
There, now you have an x86 configuration! Easy as pie! :-)
I also recommend using Configuration Manager
to delete the Any CPU platform. You really don't want that if you ever have depedencies on 32-bit native DLLs (even indirect dependencies).
Stephen Styrchak | XNA Game Studio Developer http://forums.xna.com/forums/p/4377/22601.aspx#22601
=> here my solution with the following features
public ResourceStatus Status
{
get { return _status; }
set
{
_status = value;
Notify(Npcea.Status,Npcea.Comments);
}
}
Ok. I think I found the proper solution:
v = [x[0]-x[1] for x in zip(t[1:],t[:-1])]
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.
REST
RESTs sweet spot is when you are exposing a public API over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.
SOAP
SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.
Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.
Reference: http://spf13.com/post/soap-vs-rest
And finally: What they could be referring to is REST vs. RPC See this: http://encosia.com/rest-vs-rpc-in-asp-net-web-api-who-cares-it-does-both/
__VA_ARGS__
is the standard way to do it. Don't use compiler-specific hacks if you don't have to.
I'm really annoyed that I can't comment on the original post. In any case, C++ is not a superset of C. It is really silly to compile your C code with a C++ compiler. Don't do what Donny Don't does.
I was having this problem when running from c#, on Windows 7, the "Interactive Services Detection" service was popping up when running a hidden powershell window as the SYSTEM account.
Using the "CreateNoWindow" parameter prevented the ISD service popping up it's warning.
process.StartInfo = new ProcessStartInfo("powershell.exe",
String.Format(@" -NoProfile -ExecutionPolicy unrestricted -encodedCommand ""{0}""",encodedCommand))
{
WorkingDirectory = executablePath,
UseShellExecute = false,
CreateNoWindow = true
};
In Bootstrap 4 you have to use 'max-width' attribute and then it works perfectly.
<div id="modal_dialog" class="modal fade" tabindex="-1" role="dialog" style="display: none;">
<div class="modal-dialog" style="max-width: 1350px!important;" role="document">
<div class="modal-content">
<div class="modal-body">
Sample text
</div>
</div>
</div>
Do you want coordinates relative to the screen or the application?
If it's within the application just use:
Mouse.GetPosition(Application.Current.MainWindow);
If not, I believe you can add a reference to System.Windows.Forms
and use:
System.Windows.Forms.Control.MousePosition;
2^8 = 256 Characters. A character in binary is a series of 8 ( 0 or 1).
|----------------------------------------------------------|
| |
| Type | Storage | Minimum Value | Maximum Value |
| | (Bytes) | (Signed/Unsigned) | (Signed/Unsigned)|
| | | | |
|---------|---------|-------------------|------------------|
| | | | |
| | | | |
| TINYINT | 1 | -128 - 0 | 127 - 255 |
| | | | |
|----------------------------------------------------------|
When you make your URL /about-us/
(with the trailing slash), it's easy to start with a single file index.html
and then later expand it and add more files (e.g. our-CEO-john-doe.jpg
) or even build a hierarchy under it (e.g. /about-us/company/
, /about-us/products/
, etc.) as needed, without changing the published URL. This gives you a great flexibility.
Unfortunately, MySQL does not explicitly support that (except for dumping and reloading database again).
From http://dev.mysql.com/doc/refman/5.1/en/rename-database.html:
13.1.32. RENAME DATABASE Syntax
RENAME {DATABASE | SCHEMA} db_name TO new_db_name;
This statement was added in MySQL 5.1.7 but was found to be dangerous and was removed in MySQL 5.1.23. ... Use of this statement could result in loss of database contents, which is why it was removed. Do not use RENAME DATABASE in earlier versions in which it is present.
It used to be installed with the .NET framework. MsBuild v12.0 (2013) is now bundled as a stand-alone utility and has it's own installer.
http://www.microsoft.com/en-us/download/confirmation.aspx?id=40760
To reference the location of MsBuild.exe from within an MsBuild script, use the default $(MsBuildToolsPath) property.
php artisan make:controller admin/CategoryController
Here admin is sub directory under app/Http/Controllers and CategoryController is controller you want to create inside directory
I'm not exactly sure what's causing this. You can try looking in your socket.py (mine is a different version, so line numbers from the trace don't match, and I'm afraid some other details might not match as well).
Anyway, it seems like a good practice to put your url fetching code in a try: ... except: ...
block, and handle this with a short pause and a retry. The URL you're trying to fetch may be down, or too loaded, and that's stuff you'll only be able to handle in with a retry anyway.
Bootstrap 3 has been released since this question was originally answered in January, so if you are a BS3 user, please refer to the BS3 documentation. For those still on BS2, the original answer still applies. If you are interested in switching from 2 to 3, see the migration guide.
From the bootstrap 2 docs:
Make any row "fluid" by changing .row to .row-fluid. The column classes stay the exact same, making it easy to flip between fixed and fluid grids.
Code
<div class="row-fluid">
<div class="span4">...</div>
<div class="span8">...</div>
</div>
This, in conjunction with setting the width of your container to a fluid value, should allow you to get your desired layout.
You can use the properties tab in eclipse to set various values.
here are all the possible values
Check here for explanations: http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputType
For iPhone cocoa-touch projects:
I had this problem and thanks to Eric Farraro's comment, I was able to get it resolved. I was importing a class WSHelper.h in many of my other classes. But I also was importing some of those same classes in my WSHelper.h (circular like Eric said). So, to fix this I moved the imports from my WSHelper.h file to my WSHelper.m file as they weren't really needed in the .h file anyway.
Delete Vendor then composer install
I tried this on Mac OSX with Chrome 42.0.2311.90 (64-bit) and this works by using CMD + /
The version of the notebook server is 3.1.0-cbccb68 and is running on:
Python 2.7.9 |Anaconda 2.1.0 (x86_64)| (default, Dec 15 2014, 10:37:34)
[GCC 4.2.1 (Apple Inc. build 5577)]
Could it be a browser related problem? Did you try Firefox or IE?
Couldn't get bootstrap datepicker to work until I wrap the textbox with position relative element as shown here:
<span style="position: relative">
<input type="text" placeholder="click to show datepicker" id="pickyDate"/>
</span>
To figure out the modular multiplicative inverse I recommend using the Extended Euclidean Algorithm like this:
def multiplicative_inverse(a, b):
origA = a
X = 0
prevX = 1
Y = 1
prevY = 0
while b != 0:
temp = b
quotient = a/b
b = a%b
a = temp
temp = X
a = prevX - quotient * X
prevX = temp
temp = Y
Y = prevY - quotient * Y
prevY = temp
return origA + prevY
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
add these dependencies and enable these modules. that should help
private static final ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();
check the ff post for your solution and don't forget to mark this when you fine this helpful
http://errorbank.blogspot.com/2011/03/list-all-foreign-keys-references-for.html
SELECT
o.conname AS constraint_name,
(SELECT nspname FROM pg_namespace WHERE oid=m.relnamespace) AS source_schema,
m.relname AS source_table,
(SELECT a.attname FROM pg_attribute a WHERE a.attrelid = m.oid AND a.attnum = o.conkey[1] AND a.attisdropped = false) AS source_column,
(SELECT nspname FROM pg_namespace WHERE oid=f.relnamespace) AS target_schema,
f.relname AS target_table,
(SELECT a.attname FROM pg_attribute a WHERE a.attrelid = f.oid AND a.attnum = o.confkey[1] AND a.attisdropped = false) AS target_column
FROM
pg_constraint o LEFT JOIN pg_class f ON f.oid = o.confrelid LEFT JOIN pg_class m ON m.oid = o.conrelid
WHERE
o.contype = 'f' AND o.conrelid IN (SELECT oid FROM pg_class c WHERE c.relkind = 'r');
Right click on the ribbon and choose Customize the ribbon
. From the Choose commands from:
drop down, select Commands not in the ribbon
.
That is where I found the Document location
command.
Good question. I've been using
List<string> myStrings = new List<string>{ "ours", "mine", "yours"};
string joinedString = string.Join(", ", myStrings.ToArray());
It's not LINQ, but it works.
Here look at how I done it; Jsfiddle
With the Code I put in, I managed to get it working on Webkit (Chrome/Safari) and Firefox. I don't know if it works with the latest version of Opera. Yes it does work under the latest version of Opera.
#wrapper {
width: 300px; height: 300px;
border-radius: 100px;
overflow: hidden;
position: absolute; /* this breaks the overflow:hidden in Chrome/Opera */
}
#box {
width: 300px; height: 300px;
background-color: #cde;
border-radius: 100px;
-webkit-border-radius: 100px;
-moz-border-radius: 100px;
-o-border-radius: 100px;
}
Agree with Jewes, XmlReader is the better way to go, especially if working with a larger XML document or processing multiple in a loop - no need to parse the entire document if you only need the document root.
Here's a simplified version, using XmlReader and MoveToContent().
http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.movetocontent.aspx
using (XmlReader xmlReader = XmlReader.Create(p_fileName))
{
if (xmlReader.MoveToContent() == XmlNodeType.Element)
rootNodeName = xmlReader.Name;
}
Cannot override constructor. Constructor can be regarded as static, subclass cannot override its super constructor.
Of course, you could call protected-method in super class constructor, then overide it in subclass to change super class constructor. However, many persons suggest not to use the trick, in order to protect super class constructor behavior. For instance, FindBugs will warn you that a constructor calls a non-final method.
As well as execute immediate you can also use
DBMS_UTILITY.EXEC_DDL_STATEMENT('TRUNCATE TABLE tablename;');
The statement fails because the stored proc is executing DDL and some instances of DDL could invalidate the stored proc. By using the execute immediate or exec_ddl approaches the DDL is implemented through unparsed code.
When doing this you neeed to look out for the fact that DDL issues an implicit commit both before and after execution.
Forget about the react first:
This is not related to react and let us understand the basic concepts of Java Script. For Example you have written following function in java script (name is A).
function a() {
};
Q.1) How to call the function that we have defined?
Ans: a();
Q.2) How to pass reference of function so that we can call it latter?
Ans: let fun = a;
Now coming to your question, you have used paranthesis with function name, mean that function will be called when following statement will be render.
<td><span onClick={this.toggle()}>Details</span></td>
_x000D_
Then How to correct it?
Simple!! Just remove parenthesis. By this way you have given the reference of that function to onClick event. It will call back your function only when your component is clicked.
<td><span onClick={this.toggle}>Details</span></td>
_x000D_
One suggestion releated to react:
Avoid using inline function as suggested by someone in answers, it may cause performance issue.
Avoid following code, It will create instance of same function again and again whenever function will be called (lamda statement creates new instance every time).
Note: and no need to pass event (e) explicitly to the function. you can access it with in the function without passing it.
{<td><span onClick={(e) => this.toggle(e)}>Details</span></td>}
_x000D_
https://cdb.reacttraining.com/react-inline-functions-and-performance-bdff784f5578
Simply do this...hope it help
$fifteendaysago = date_create('15 days ago');
echo date_format($fifteendaysago, 'Y-m-d');
given :
array=("something to search for" "a string" "test2000")
elem="a string"
then a simple check of :
if c=$'\x1E' && p="${c}${elem} ${c}" && [[ ! "${array[@]/#/${c}} ${c}" =~ $p ]]; then
echo "$elem exists in array"
fi
where
c is element separator
p is regex pattern
(The reason for assigning p separately, rather than using the expression directly inside [[ ]] is to maintain compatibility for bash 4)
This may be the good solution for you: change the code like this very little change
.box{
position: relative;
}
.box:hover .hidden{
opacity: 1;
width:500px;
}
.box .hidden{
background: yellow;
height: 334px;
position: absolute;
top: 0;
left: 0;
width: 0;
opacity: 0;
transition: all 1s ease;
}
See demo here
Try this. hope this will help.
String cls0;
String cls1;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
cls0 = in.nextLine();
System.out.println("Enter a string");
cls1 = in.nextLine();
d <- 5
for(i in 1:10) {
nam <- paste("A", i, sep = "")
assign(nam, rnorm(3)+d)
}
One solution would be to use the key of your items to remove them -- you can both the keys and the values, when looping using foreach.
For instance :
$arr = array(
'a' => 123,
'b' => 456,
'c' => 789,
);
foreach ($arr as $key => $item) {
if ($item == 456) {
unset($arr[$key]);
}
}
var_dump($arr);
Will give you this array, in the end :
array
'a' => int 123
'c' => int 789
Which means that, in your case, something like this should do the trick :
foreach($images as $key => $image)
{
if($image == 'http://i27.tinypic.com/29yk345.gif' ||
$image == 'http://img3.abload.de/img/10nx2340fhco.gif' ||
$image == 'http://i42.tinypic.com/9pp2456x.gif')
{
unset($images[$key]);
}
}
After creating a second project in the workspace in eclipse, I had this problem. I believe it is because I created it with a different SDK version and this ovewrote the android-support-v7-appcompat library.
I tried to clean everything up but to no avail. Ultimately, the suggestion above to edit project.properties and change target=android-21 and set my project to Android 5.0, fixed it.