**in create url page**
$data = array(
'car' => 'Suzuki',
'Model' => '1976'
);
$query = http_build_query(array('myArray' => $data));
$url=urlencode($query);
echo" <p><a href=\"index2.php?data=".$url."\"> Send </a><br /> </p>";
**in received page**
parse_str($_GET['data']);
echo $myArray['car'];
echo '<br/>';
echo $myArray['model'];
In general, there is no way to know when something on another site has been changed. If the site offers an RSS feed, you should try that. If the site does not offer an RSS feed (or if the RSS feed doesn't include the information you're looking for), then you have to scrape and compare.
You can have only one default export which you declare like:
export default App;
or
export default class App extends React.Component {...
and later do import App from './App'
If you want to export something more you can use named exports which you declare without default
keyword like:
export {
About,
Contact,
}
or:
export About;
export Contact;
or:
export const About = class About extends React.Component {....
export const Contact = () => (<div> ... </div>);
and later you import them like:
import App, { About, Contact } from './App';
EDIT:
There is a mistake in the tutorial as it is not possible to make 3 default exports in the same main.js
file. Other than that why export anything if it is no used outside the file?. Correct main.js
:
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory, IndexRoute } from 'react-router'
class App extends React.Component {
...
}
class Home extends React.Component {
...
}
class About extends React.Component {
...
}
class Contact extends React.Component {
...
}
ReactDOM.render((
<Router history = {browserHistory}>
<Route path = "/" component = {App}>
<IndexRoute component = {Home} />
<Route path = "home" component = {Home} />
<Route path = "about" component = {About} />
<Route path = "contact" component = {Contact} />
</Route>
</Router>
), document.getElementById('app'))
EDIT2:
another thing is that this tutorial is based on react-router-V3 which has different api than v4.
$('#pass').focus(function() {
$('#pass').replaceWith("<input id='password' size='70' type='password' value='' name='password'>");
$('#password').focus();
});
<input id='pass' size='70' type='text' value='password' name='password'>
export GOROOT=/usr/lib/go
export GOPATH=$HOME/go
export PATH=$PATH:$GOROOT/bin
And you may want to check by $ go env
Flayway don't recognize the direct environment variables into the application.properties (Spring-Boot V2.1). e.g
spring.datasource.url=jdbc:mysql://${DB_HOSTNAME}:${DB_PORT}/${DB_DATABASE}
spring.datasource.username=${DB_USER}
spring.datasource.password=${DB_PASS}
To solve this issue I did this environment variables, usually I create the file .env:
SPRING_DATASOURCE_URL=jdbc:mysql://127.0.0.1:3306/place
SPRING_DATASOURCE_USERNAME=root
SPRING_DATASOURCE_PASSWORD=root
And export the variables to my environment:
export $(cat .env | xargs)
And finally just run the command
mvn spring-boot:run
Or run your jar file
java -jar target/your-file.jar
There another approach here: https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/maven-plugin/examples/run-env-variables.html
When a module is loaded from a file in Python, __file__
is set to its path. You can then use that with other functions to find the directory that the file is located in.
Taking your examples one at a time:
A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.
B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.
C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.
You can see the various values returned from these here:
import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))
and make sure you run it from different locations (such as ./text.py
, ~/python/text.py
and so forth) to see what difference that makes.
I just want to address some confusion first. __file__
is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.
http://docs.python.org/reference/datamodel.html shows many of the special methods and attributes, if not all of them.
In this case __file__
is an attribute of a module (a module object). In Python a .py
file is a module. So import amodule
will have an attribute of __file__
which means different things under difference circumstances.
Taken from the docs:
__file__
is the pathname of the file from which the module was loaded, if it was loaded from a file. The__file__
attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.
In your case the module is accessing it's own __file__
attribute in the global namespace.
To see this in action try:
# file: test.py
print globals()
print __file__
And run:
python test.py
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py
According to CanIUse you should have it with multiple prefixes.
$('div').css({
"-webkit-transform":"translate(100px,100px)",
"-ms-transform":"translate(100px,100px)",
"transform":"translate(100px,100px)"
});?
By latest document, you can use rdd.collect().foreach(println) on the driver to display all, but it may cause memory issues on the driver, best is to use rdd.take(desired_number)
https://spark.apache.org/docs/2.2.0/rdd-programming-guide.html
To print all elements on the driver, one can use the collect() method to first bring the RDD to the driver node thus: rdd.collect().foreach(println). This can cause the driver to run out of memory, though, because collect() fetches the entire RDD to a single machine; if you only need to print a few elements of the RDD, a safer approach is to use the take(): rdd.take(100).foreach(println).
We chose a combination of Mongo/Dynamo for a healthcare product. Basically mongo allows better searching, but the hosted Dynamo is great because its HIPAA compliant without any extra work. So we host the mongo portion with no personal data on a standard setup and allow amazon to deal with the HIPAA portion in terms of infrastructure. We can query certain items from mongo which bring up documents with pointers (ID's) of the relatable Dynamo document.
The main reason we chose to do this using mongo instead of hosting the entire application on dynamo was for 2 reasons. First, we needed to preform location based searches which mongo is great at and at the time, Dynamo was not, but they do have an option now.
Secondly was that some documents were unstructured and we did not know ahead of time what the data would be, so for example lets say user a inputs a document in the "form" collection like this: {"username": "user1", "email": "[email protected]"}. And another user puts this in the same collection {"phone": "813-555-3333", "location": [28.1234,-83.2342]}. With mongo we can search any of these dynamic and unknown fields at any time, with Dynamo, you could do this but would have to make a index every time a new field was added that you wanted searchable. So if you have never had a phone field in your Dynamo document before and then all of the sudden, some one adds it, its completely unsearchable.
Now this brings up another point in which you have mentioned. Sometimes choosing the right solution for the job does not always mean choosing the best product for the job. For example you may have a client who needs and will use the system you created for 10+ years. Going with a SaaS/IaaS solution that is good enough to get the job done may be a better option as you can rely on amazon to have up-kept and maintained their systems over the long haul.
As SQLite has limited support to ALTER TABLE so you can only ADD column at end of the table OR CHANGE TABLE_NAME in SQLite.
Here is the Best Answer of HOW TO DELETE COLUMN FROM SQLITE?
SELECT * from new WHERE date < DATE_ADD(now(),interval -1 day);
+
means "one or more characters" and without the plus it means "one character." In your case both result in the same output.
Yes you can (this is how I understand the original question). Here is how I did it. Just tie it into outside context. For example:
//javascript
my_function = null;
//jquery
$(function() {
function my_fun(){
/.. some operations ../
}
my_function = my_fun;
})
//just js
function js_fun () {
my_function(); //== call jquery function - just Reference is globally defined not function itself
}
I encountered this same problem when trying to access methods of the object, that was instantiated on DOM object ready only. Works. My example:
MyControl.prototype = {
init: function {
// init something
}
update: function () {
// something useful, like updating the list items of control or etc.
}
}
MyCtrl = null;
// create jquery plug-in
$.fn.aControl = function () {
var control = new MyControl(this);
control.init();
MyCtrl = control; // here is the trick
return control;
}
now you can use something simple like:
function() = {
MyCtrl.update(); // yes!
}
According to the documentation, just like with any css selector, you can specify as many conditions as you want, and they are treated as logical 'OR'.
This example returns a list of all div elements within the document with a class of either "note" or "alert":
var matches = document.querySelectorAll("div.note, div.alert");
source: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
Meanwhile to get the 'AND' functionality you can for example simply use a multiattribute selector, as jquery says:
https://api.jquery.com/multiple-attribute-selector/
ex. "input[id][name$='man']"
specifies both id and name of the element and both conditions must be met. For classes it's as obvious as ".class1.class2
" to require object of 2 classes.
All possible combinations of both are valid, so you can easily get equivalent of more sophisticated 'OR' and 'AND' expressions.
Straight after the $wpdb->insert()
that does the insert, do this:
$lastid = $wpdb->insert_id;
More information about how to do things the WordPress way can be found in the WordPress codex. The details above were found here on the wpdb class page
Event extension is very appropriate. It is a port of Libevent library which is designed for event-driven I/O, mainly for networking.
I have written a sample HTTP client that allows to schedule a number of HTTP requests and run them asynchronously.
This is a sample HTTP client class based on Event extension.
The class allows to schedule a number of HTTP requests, then run them asynchronously.
<?php
class MyHttpClient {
/// @var EventBase
protected $base;
/// @var array Instances of EventHttpConnection
protected $connections = [];
public function __construct() {
$this->base = new EventBase();
}
/**
* Dispatches all pending requests (events)
*
* @return void
*/
public function run() {
$this->base->dispatch();
}
public function __destruct() {
// Destroy connection objects explicitly, don't wait for GC.
// Otherwise, EventBase may be free'd earlier.
$this->connections = null;
}
/**
* @brief Adds a pending HTTP request
*
* @param string $address Hostname, or IP
* @param int $port Port number
* @param array $headers Extra HTTP headers
* @param int $cmd A EventHttpRequest::CMD_* constant
* @param string $resource HTTP request resource, e.g. '/page?a=b&c=d'
*
* @return EventHttpRequest|false
*/
public function addRequest($address, $port, array $headers,
$cmd = EventHttpRequest::CMD_GET, $resource = '/')
{
$conn = new EventHttpConnection($this->base, null, $address, $port);
$conn->setTimeout(5);
$req = new EventHttpRequest([$this, '_requestHandler'], $this->base);
foreach ($headers as $k => $v) {
$req->addHeader($k, $v, EventHttpRequest::OUTPUT_HEADER);
}
$req->addHeader('Host', $address, EventHttpRequest::OUTPUT_HEADER);
$req->addHeader('Connection', 'close', EventHttpRequest::OUTPUT_HEADER);
if ($conn->makeRequest($req, $cmd, $resource)) {
$this->connections []= $conn;
return $req;
}
return false;
}
/**
* @brief Handles an HTTP request
*
* @param EventHttpRequest $req
* @param mixed $unused
*
* @return void
*/
public function _requestHandler($req, $unused) {
if (is_null($req)) {
echo "Timed out\n";
} else {
$response_code = $req->getResponseCode();
if ($response_code == 0) {
echo "Connection refused\n";
} elseif ($response_code != 200) {
echo "Unexpected response: $response_code\n";
} else {
echo "Success: $response_code\n";
$buf = $req->getInputBuffer();
echo "Body:\n";
while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
echo $s, PHP_EOL;
}
}
}
}
}
$address = "my-host.local";
$port = 80;
$headers = [ 'User-Agent' => 'My-User-Agent/1.0', ];
$client = new MyHttpClient();
// Add pending requests
for ($i = 0; $i < 10; $i++) {
$client->addRequest($address, $port, $headers,
EventHttpRequest::CMD_GET, '/test.php?a=' . $i);
}
// Dispatch pending requests
$client->run();
This is a sample script on the server side.
<?php
echo 'GET: ', var_export($_GET, true), PHP_EOL;
echo 'User-Agent: ', $_SERVER['HTTP_USER_AGENT'] ?? '(none)', PHP_EOL;
php http-client.php
Sample Output
Success: 200
Body:
GET: array (
'a' => '1',
)
User-Agent: My-User-Agent/1.0
Success: 200
Body:
GET: array (
'a' => '0',
)
User-Agent: My-User-Agent/1.0
Success: 200
Body:
GET: array (
'a' => '3',
)
...
(Trimmed.)
Note, the code is designed for long-term processing in the CLI SAPI.
For custom protocols, consider using low-level API, i.e. buffer events, buffers. For SSL/TLS communications, I would recommend the low-level API in conjunction with Event's ssl context. Examples:
Although Libevent's HTTP API is simple, it is not as flexible as buffer events. For example, the HTTP API currently doesn't support custom HTTP methods. But it is possible to implement virtually any protocol using the low-level API.
I have also written a sample of another HTTP client using Ev extension with sockets in non-blocking mode. The code is slightly more verbose than the sample based on Event, because Ev is a general purpose event loop. It doesn't provide network-specific functions, but its EvIo
watcher is capable of listening to a file descriptor encapsulated into the socket resource, in particular.
This is a sample HTTP client based on Ev extension.
Ev extension implements a simple yet powerful general purpose event loop. It doesn't provide network-specific watchers, but its I/O watcher can be used for asynchronous processing of sockets.
The following code shows how HTTP requests can be scheduled for parallel processing.
<?php
class MyHttpRequest {
/// @var MyHttpClient
private $http_client;
/// @var string
private $address;
/// @var string HTTP resource such as /page?get=param
private $resource;
/// @var string HTTP method such as GET, POST etc.
private $method;
/// @var int
private $service_port;
/// @var resource Socket
private $socket;
/// @var double Connection timeout in seconds.
private $timeout = 10.;
/// @var int Chunk size in bytes for socket_recv()
private $chunk_size = 20;
/// @var EvTimer
private $timeout_watcher;
/// @var EvIo
private $write_watcher;
/// @var EvIo
private $read_watcher;
/// @var EvTimer
private $conn_watcher;
/// @var string buffer for incoming data
private $buffer;
/// @var array errors reported by sockets extension in non-blocking mode.
private static $e_nonblocking = [
11, // EAGAIN or EWOULDBLOCK
115, // EINPROGRESS
];
/**
* @param MyHttpClient $client
* @param string $host Hostname, e.g. google.co.uk
* @param string $resource HTTP resource, e.g. /page?a=b&c=d
* @param string $method HTTP method: GET, HEAD, POST, PUT etc.
* @throws RuntimeException
*/
public function __construct(MyHttpClient $client, $host, $resource, $method) {
$this->http_client = $client;
$this->host = $host;
$this->resource = $resource;
$this->method = $method;
// Get the port for the WWW service
$this->service_port = getservbyname('www', 'tcp');
// Get the IP address for the target host
$this->address = gethostbyname($this->host);
// Create a TCP/IP socket
$this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (!$this->socket) {
throw new RuntimeException("socket_create() failed: reason: " .
socket_strerror(socket_last_error()));
}
// Set O_NONBLOCK flag
socket_set_nonblock($this->socket);
$this->conn_watcher = $this->http_client->getLoop()
->timer(0, 0., [$this, 'connect']);
}
public function __destruct() {
$this->close();
}
private function freeWatcher(&$w) {
if ($w) {
$w->stop();
$w = null;
}
}
/**
* Deallocates all resources of the request
*/
private function close() {
if ($this->socket) {
socket_close($this->socket);
$this->socket = null;
}
$this->freeWatcher($this->timeout_watcher);
$this->freeWatcher($this->read_watcher);
$this->freeWatcher($this->write_watcher);
$this->freeWatcher($this->conn_watcher);
}
/**
* Initializes a connection on socket
* @return bool
*/
public function connect() {
$loop = $this->http_client->getLoop();
$this->timeout_watcher = $loop->timer($this->timeout, 0., [$this, '_onTimeout']);
$this->write_watcher = $loop->io($this->socket, Ev::WRITE, [$this, '_onWritable']);
return socket_connect($this->socket, $this->address, $this->service_port);
}
/**
* Callback for timeout (EvTimer) watcher
*/
public function _onTimeout(EvTimer $w) {
$w->stop();
$this->close();
}
/**
* Callback which is called when the socket becomes wriable
*/
public function _onWritable(EvIo $w) {
$this->timeout_watcher->stop();
$w->stop();
$in = implode("\r\n", [
"{$this->method} {$this->resource} HTTP/1.1",
"Host: {$this->host}",
'Connection: Close',
]) . "\r\n\r\n";
if (!socket_write($this->socket, $in, strlen($in))) {
trigger_error("Failed writing $in to socket", E_USER_ERROR);
return;
}
$loop = $this->http_client->getLoop();
$this->read_watcher = $loop->io($this->socket,
Ev::READ, [$this, '_onReadable']);
// Continue running the loop
$loop->run();
}
/**
* Callback which is called when the socket becomes readable
*/
public function _onReadable(EvIo $w) {
// recv() 20 bytes in non-blocking mode
$ret = socket_recv($this->socket, $out, 20, MSG_DONTWAIT);
if ($ret) {
// Still have data to read. Append the read chunk to the buffer.
$this->buffer .= $out;
} elseif ($ret === 0) {
// All is read
printf("\n<<<<\n%s\n>>>>", rtrim($this->buffer));
fflush(STDOUT);
$w->stop();
$this->close();
return;
}
// Caught EINPROGRESS, EAGAIN, or EWOULDBLOCK
if (in_array(socket_last_error(), static::$e_nonblocking)) {
return;
}
$w->stop();
$this->close();
}
}
/////////////////////////////////////
class MyHttpClient {
/// @var array Instances of MyHttpRequest
private $requests = [];
/// @var EvLoop
private $loop;
public function __construct() {
// Each HTTP client runs its own event loop
$this->loop = new EvLoop();
}
public function __destruct() {
$this->loop->stop();
}
/**
* @return EvLoop
*/
public function getLoop() {
return $this->loop;
}
/**
* Adds a pending request
*/
public function addRequest(MyHttpRequest $r) {
$this->requests []= $r;
}
/**
* Dispatches all pending requests
*/
public function run() {
$this->loop->run();
}
}
/////////////////////////////////////
// Usage
$client = new MyHttpClient();
foreach (range(1, 10) as $i) {
$client->addRequest(new MyHttpRequest($client, 'my-host.local', '/test.php?a=' . $i, 'GET'));
}
$client->run();
Suppose http://my-host.local/test.php
script is printing the dump of $_GET
:
<?php
echo 'GET: ', var_export($_GET, true), PHP_EOL;
Then the output of php http-client.php
command will be similar to the following:
<<<<
HTTP/1.1 200 OK
Server: nginx/1.10.1
Date: Fri, 02 Dec 2016 12:39:54 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: close
X-Powered-By: PHP/7.0.13-pl0-gentoo
1d
GET: array (
'a' => '3',
)
0
>>>>
<<<<
HTTP/1.1 200 OK
Server: nginx/1.10.1
Date: Fri, 02 Dec 2016 12:39:54 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: close
X-Powered-By: PHP/7.0.13-pl0-gentoo
1d
GET: array (
'a' => '2',
)
0
>>>>
...
(trimmed)
Note, in PHP 5 the sockets extension may log warnings for EINPROGRESS
, EAGAIN
, and EWOULDBLOCK
errno
values. It is possible to turn off the logs with
error_reporting(E_ERROR);
I just want to do something like
file_get_contents()
, but not wait for the request to finish before executing the rest of my code.
The code that is supposed to run in parallel with the network requests can be executed within a the callback of an Event timer, or Ev's idle watcher, for instance. You can easily figure it out by watching the samples mentioned above. Otherwise, I'll add another example :)
The first one creates a single lambda function and calls it ten times.
The second one doesn't call the function. It creates 10 different lambda functions. It puts all of those in a list. To make it equivalent to the first you need:
[(lambda x: x*x)(x) for x in range(10)]
Or better yet:
[x*x for x in range(10)]
JSON is perfectly capable of expressing lists of integers, and the JSON you have posted is valid. You can simply separate the integers by commas:
{
"Id": "610",
"Name": "15",
"Description": "1.99",
"ItemModList": [42, 47, 139]
}
Try
<html style="width:100%; height:100%; margin: 0; padding: 0;">
<body style="overflow:hidden; width:100%; height:100%; margin:0; padding:0;">
Well, I've received this error today on Windows 8 64-bit out of the blue, for the first time, and it turns out my my.ini had been reset, and the bin/mysqld file had been deleted, among other items in the "Program Files/MySQL/MySQL Server 5.6"
folder.
To fix it, I had to run the MySQL installer again, installing only the server, and copy a recent version of the my.ini file from "ProgramData/MySQL/MySQL Server 5.6"
, named my_2014-03-28T15-51-20.ini
in my case (don't know how or why that got copied there so recently) back into "Program Files/MySQL/MySQL Server 5.6"
.
The only change to the system since MySQL worked was the installation of Native Instruments' Traktor 2 and a Traktor Audio 2 sound card, which really shouldn't have caused this problem, and no one else has used the system besides me. If anyone has a clue, it would be kind of you to comment to prevent this for me and anyone else who has encountered this.
Even though Caffeine Coma's issue was resolved, I would like to offer another potential cause for the title not showing up on a UIButton.
If you set an image for the UIButton using
- (void)setImage:(UIImage *)image forState:(UIControlState)state
It can cover the title. I found this out the hard way and imagine some of you end up reading this page for the same reason.
Use this method instead
- (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state
for the button image and the title will not be affected.
I tested this with programmatically created buttons and buttons created in a .xib
I had the same problem. For some reason --initialize
did not work.
After about 5 hours of trial and error with different parameters, configs and commands I found out that the problem was caused by the file system.
I wanted to run a database on a large USB HDD drive. Drives larger than 2 TB are GPT partitioned! Here is a bug report with a solution:
https://bugs.mysql.com/bug.php?id=28913
In short words: Add the following line to your my.ini:
innodb_flush_method=normal
I had this problem with mysql 5.7 on Windows.
I hit this today after the following sequence:
The problem was in addition to not saving changes to the new file, it didn't save changes to the project, so after reopening Visual Studio the file was not part of the project. The Show All Files command in Solution Explorer, or Add → Existing Item..., resolved the problem.
I know it is kind an old post, but I've had the same problem and couldn't understand why your code didn't work. After a LOT of tests I've found out why.
It seems like fpm receives the full path from nginx and tries to find the files in the fpm container, so it must be the exactly the same as server.root
in the nginx config, even if it doesn't exist in the nginx container.
To demonstrate:
docker-compose.yml
nginx:
build: .
ports:
- "80:80"
links:
- fpm
fpm:
image: php:fpm
ports:
- ":9000"
# seems like fpm receives the full path from nginx
# and tries to find the files in this dock, so it must
# be the same as nginx.root
volumes:
- ./:/complex/path/to/files/
/etc/nginx/conf.d/default.conf
server {
listen 80;
# this path MUST be exactly as docker-compose.fpm.volumes,
# even if it doesn't exist in this dock.
root /complex/path/to/files;
location / {
try_files $uri /index.php$is_args$args;
}
location ~ ^/.+\.php(/|$) {
fastcgi_pass fpm:9000;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
Dockerfile
FROM nginx:latest
COPY ./default.conf /etc/nginx/conf.d/
In modern browsers you do not need JQuery for this. Instead use
document.querySelectorAll('option:checked')
Or specify any DOM element instead of document
In a comment you wrote
i want to show that there is a difference in local and github repo
As already mentioned in another answer, you should do a git fetch origin
first. Then, if the remote is ahead of your current branch, you can list all commits between your local branch and the remote with
git log master..origin/master --stat
If your local branch is ahead:
git log origin/master..master --stat
--stat
shows a list of changed files as well.
If you want to explicitly list the additions and deletions, use git diff
:
git diff master origin/master
Add the param declation at the top of ps1 file
test.ps1
param(
# Our preferred encoding
[parameter(Mandatory=$false)]
[ValidateSet("UTF8","Unicode","UTF7","ASCII","UTF32","BigEndianUnicode")]
[string]$Encoding = "UTF8"
)
write ("Encoding : {0}" -f $Encoding)
result
C:\temp> .\test.ps1 -Encoding ASCII
Encoding : ASCII
I'm late i think :] soory,
If you are here like me searching for the solution when this error occurs with mysqldump
instead of mysql, try this solution that i found on a german website out there by chance, so i wanted to share with homeless people who got headaches like me.
So the problem occurs because the lack -databases
parameter before the database name
So your command must look like this:
mysqldump -pdbpass -udbuser --databases dbname
Another cause of the problem in my case was that i'm developping on local and the root
user doesn't have a password, so in this case you must use --password=
instead of -pdbpass
, so my final command was:
mysqldump -udbuser --password= --databases dbname
Link to the complete thread (in German) : https://marius.bloggt-in-braunschweig.de/2016/04/29/solution-mysqldump-no-database-selected-when-selecting-the-database/
CN
= Common NameOU
= Organizational UnitDC
= Domain ComponentThese are all parts of the X.500 Directory Specification, which defines nodes in a LDAP directory.
You can also read up on LDAP data Interchange Format (LDIF
), which is an alternate format.
You read it from right to left, the right-most component is the root of the tree, and the left most component is the node (or leaf) you want to reach.
Each =
pair is a search criteria.
With your example query
("CN=Dev-India,OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com");
In effect the query is:
From the com
Domain Component, find the google
Domain Component, and then inside it the gl
Domain Component and then inside it the gp
Domain Component.
In the gp
Domain Component, find the Organizational Unit called Distribution Groups
and then find the the object that has a common name of Dev-India
.
You can achieve the effect using a container element, then just set the containing elements margin to 0 auto
and it will be centered.
Markup
<div id="header">
<div id="headerContent">
Header text
</div>
</div>
CSS
#header{
width:100%;
background: url(yourimage);
}
#headerContent{
margin: 0 auto; width: 960px;
}
On MAC delete this folder:
~/Library/Application Support/Google/AndroidStudio4.1
I present a fully worked example on how building a shared library
and using it under Python
by means of ctypes
. I consider the Windows
case and deal with DLLs
. Two steps are needed:
The shared library
I consider is the following and is contained in the testDLL.cpp
file. The only function testDLL
just receives an int
and prints it.
#include <stdio.h>
?
extern "C" {
?
__declspec(dllexport)
?
void testDLL(const int i) {
printf("%d\n", i);
}
?
} // extern "C"
To build a DLL
with Visual Studio
from the command line run
"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\vsdevcmd"
to set the include path and then run
cl.exe /D_USRDLL /D_WINDLL testDLL.cpp /MT /link /DLL /OUT:testDLL.dll
to build the DLL.
DLL
from the IDEAlternatively, the DLL
can be build using Visual Studio
as follows:
Under Python, do the following
import os
import sys
from ctypes import *
lib = cdll.LoadLibrary('testDLL.dll')
lib.testDLL(3)
This is what helped me. My navigation bar is in the body tag. Entire code for navigation bar is in nav.html
file (without any html or body tag, only the code for navigation bar). In the target page, this goes in the head
tag:
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
Then in the body tag, a container is made with an unique id and a javascript block to load the nav.html
into the container, as follows:
<!--Navigation bar-->
<div id="nav-placeholder">
</div>
<script>
$(function(){
$("#nav-placeholder").load("nav.html");
});
</script>
<!--end of Navigation bar-->
Based on this answer, here's a minimal solution if you're already using Bootstrap:
div.scrollable-table-wrapper {
height: 500px;
overflow: auto;
thead tr th {
position: sticky;
top: 0;
}
}
<div class="scrollable-table-wrapper">
<table class="table">
<thead>...</thead>
<tbody>...</tbody>
</table>
</div>
Tested on Bootstrap v3
If your $VARIABLE
is a string containing spaces or other special characters, and single square brackets are used (which is a shortcut for the test
command), then the string may be split out into multiple words. Each of these is treated as a separate argument.
So that one variable is split out into many arguments:
VARIABLE=$(/some/command);
# returns "hello world"
if [ $VARIABLE == 0 ]; then
# fails as if you wrote:
# if [ hello world == 0 ]
fi
The same will be true for any function call that puts down a string containing spaces or other special characters.
Wrap the variable output in double quotes, forcing it to stay as one string (therefore one argument). For example,
VARIABLE=$(/some/command);
if [ "$VARIABLE" == 0 ]; then
# some action
fi
Simple as that. But skip to "Also beware..." below if you also can't guarantee your variable won't be an empty string, or a string that contains nothing but whitespace.
Or, an alternate fix is to use double square brackets (which is a shortcut for the new test
command).
This exists only in bash (and apparently korn and zsh) however, and so may not be compatible with default shells called by /bin/sh
etc.
This means on some systems, it might work from the console but not when called elsewhere, like from cron
, depending on how everything is configured.
It would look like this:
VARIABLE=$(/some/command);
if [[ $VARIABLE == 0 ]]; then
# some action
fi
If your command contains double square brackets like this and you get errors in logs but it works from the console, try swapping out the [[
for an alternative suggested here, or, ensure that whatever runs your script uses a shell that supports [[
aka new test
.
[: unary operator expected
errorIf you're seeing the "too many arguments" error, chances are you're getting a string from a function with unpredictable output. If it's also possible to get an empty string (or all whitespace string), this would be treated as zero arguments even with the above "quick fix", and would fail with [: unary operator expected
It's the same 'gotcha' if you're used to other languages - you don't expect the contents of a variable to be effectively printed into the code like this before it is evaluated.
Here's an example that prevents both the [: too many arguments
and the [: unary operator expected
errors: replacing the output with a default value if it is empty (in this example, 0
), with double quotes wrapped around the whole thing:
VARIABLE=$(/some/command);
if [ "${VARIABLE:-0}" == 0 ]; then
# some action
fi
(here, the action will happen if $VARIABLE is 0, or empty. Naturally, you should change the 0 (the default value) to a different default value if different behaviour is wanted)
Final note: Since [
is a shortcut for test
, all the above is also true for the error test: too many arguments
(and also test: unary operator expected
)
I was trying to do this with stacked plot bars. The code that worked for me was.
# Code to plot. Notice the variable ax.
ax = df.groupby('target').count().T.plot.bar(stacked=True, figsize=(10, 6))
ax.legend(bbox_to_anchor=(1.1, 1.05))
# Loop to add on each bar a tag in position
for rect in ax.patches:
height = rect.get_height()
ypos = rect.get_y() + height/2
ax.text(rect.get_x() + rect.get_width()/2., ypos,
'%d' % int(height), ha='center', va='bottom')
java 7+
In my humble opinion since I am fan of plain java, I would suggest something that it is a combination of the aforementioned answers. Maybe I am late for the party. Here is the code:
String sampleText = "test" + System.getProperty("line.separator");
Files.write(Paths.get(filePath), sampleText.getBytes(StandardCharsets.UTF_8),
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
If the file doesn't exist, it creates it and if already exists it appends the sampleText to the existing file. Using this, saves you from adding unnecessary libs to your classpath.
I found this error while connecting ec2 instance with ssh. and it comes if i write wrong user name.
eg. for ubuntu I need to use ubuntu as user name and for others I need to use ec2-user.
If you want a good format the next statement is the best:
dataframe_prediction.to_csv('filename.csv', sep=',', encoding='utf-8', index=False)
In this case you have got a csv file with ',' as separate between columns and utf-8 format. In addition, numerical index won't appear.
Add following code in your click listener function,
NextFragment nextFrag= new NextFragment();
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.Layout_container, nextFrag, "findThisFragment")
.addToBackStack(null)
.commit();
The string "findThisFragment"
can be used to find the fragment later, if you need.
Example for String Methods
Given a list of filenames, we want to rename all the files with extension hpp to the extension h. To do this, we would like to generate a new list called newfilenames, consisting of the new filenames. Fill in the blanks in the code using any of the methods you’ve learned thus far, like a for loop or a list comprehension.
filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
# Generate newfilenames as a list containing the new filenames
# using as many lines of code as your chosen method requires.
newfilenames = []
for i in filenames:
if i.endswith(".hpp"):
x = i.replace("hpp", "h")
newfilenames.append(x)
else:
newfilenames.append(i)
print(newfilenames)
# Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]
The simplest way I've found is to use the Kafdrop REST API /topic/topicName
and specify the key: "Accept"
/ value: "application/json"
header in order to get back a JSON response.
I figured out the answer to the question I had that brought me to this page. Since no one has actually suggested the answer to my question, I thought I'd post it.
class k:
pass
a = k()
k2 = a.__class__
a2 = k2()
At this point, a and a2 are both instances of the same class (class k).
The function you need is CInt
.
ie CInt(PrinterLabel)
See Type Conversion Functions (Visual Basic) on MSDN
Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!
This will display the three images side by side if the images are not too wide.
<p float="left">
<img src="/img1.png" width="100" />
<img src="/img2.png" width="100" />
<img src="/img3.png" width="100" />
</p>
Two things to keep in mind Content-Type and the Encoding
1) What if the file is css
if (/.(css)$/.test(path)) {
res.writeHead(200, {'Content-Type': 'text/css'});
res.write(data, 'utf8');
}
2) What if the file is jpg/png
if (/.(jpg)$/.test(path)) {
res.writeHead(200, {'Content-Type': 'image/jpg'});
res.end(data,'Base64');
}
Above one is just a sample code to explain the answer and not the exact code pattern.
WebClient is a higher-level abstraction built on top of HttpWebRequest to simplify the most common tasks. For instance, if you want to get the content out of an HttpWebResponse, you have to read from the response stream:
var http = (HttpWebRequest)WebRequest.Create("http://example.com");
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
With WebClient, you just do DownloadString
:
var client = new WebClient();
var content = client.DownloadString("http://example.com");
Note: I left out the using
statements from both examples for brevity. You should definitely take care to dispose your web request objects properly.
In general, WebClient is good for quick and dirty simple requests and HttpWebRequest is good for when you need more control over the entire request.
Something like
create or replace procedure my_proc( p_rc OUT SYS_REFCURSOR )
as
begin
open p_rc
for select 1 col1
from dual;
end;
/
variable rc refcursor;
exec my_proc( :rc );
print rc;
will work in SQL*Plus or SQL Developer. I don't have any experience with Embarcardero Rapid XE2 so I have no idea whether it supports SQL*Plus commands like this.
Try this:
CSS
.style1{
background-color:red;
color:white;
font-size:44px;
}
HTML
<div id="foo">hello world!</div>
<img src="zoom.png" onclick="myFunction()" />
Javascript
function myFunction()
{
document.getElementById('foo').setAttribute("class", "style1");
}
You will use the following query:
SELECT * FROM [table] GROUP BY NUMBER;
Where [table]
is the name of the table.
This provides a unique listing for the NUMBER
column however the other columns may be meaningless depending on the vendor implementation; which is to say they may not together correspond to a specific row or rows.
find_java.exe doesn't seem to like the openjdk "java -version" output. I edited find_java.bat like this:
for /f %%a in ('%~dps0\find_java.exe -s') do set java_exe=%%a
set java_exe="C:\Program Files (x86)\AdoptOpenJDK\jdk-8.0.242.08-hotspot\bin\java.exe"
rem ...
for /f %%a in ('%~dps0\find_java.exe -s -w') do set javaw_exe=%%a
set javaw_exe="C:\Program Files (x86)\AdoptOpenJDK\jdk-8.0.242.08-hotspot\bin\javaw.exe"
Windows Subsystem for Linux did not exist when this question was asked. It gave these results in my test:
uname -s -> Linux
uname -o -> GNU/Linux
uname -r -> 4.4.0-17763-Microsoft
This means that you need uname -r to distinguish it from native Linux.
In Ubuntu /etc/init.d has been replaced by /usr/lib/systemd. Scripts can still be started and stoped by 'service'. But the primary command is now 'systemctl'. The chkconfig command was left behind, and now you do this with systemctl.
So instead of:
chkconfig enable apache2
You should look for the service name, and then enable it
systemctl status apache2
systemctl enable apache2.service
Systemd has become more friendly about figuring out if you have a systemd script, or an /etc/init.d script, and doing the right thing.
Freddy's answer helped me a lot to get this working. For the sake of completeness here's how you could implement hashing of the token:
private string ComputeHash(Guid input)
{
byte[] source = input.ToByteArray();
var encoder = new SHA256Managed();
byte[] encoded = encoder.ComputeHash(source);
return Convert.ToBase64String(encoded);
}
In CreateAsync
:
var guid = Guid.NewGuid();
...
_refreshTokens.TryAdd(ComputeHash(guid), refreshTokenTicket);
context.SetToken(guid.ToString());
ReceiveAsync
:
public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
Guid token;
if (Guid.TryParse(context.Token, out token))
{
AuthenticationTicket ticket;
if (_refreshTokens.TryRemove(ComputeHash(token), out ticket))
{
context.SetTicket(ticket);
}
}
}
Android Device Monitor was deprecated in Android Studio 3.1 and removed from Android Studio 3.2. To start the standalone Device Monitor application in Android Studio 3.1 and lower you can run android-sdk/tools/monitor.bat
Aaaand another answer here. :) Since I couldn't make the others quite work.
My solution both handles escaped quotes (double occurrences), and it does not include delimiters in the match.
Note that I have been matching against '
instead of "
as that was my scenario, but simply replace them in the pattern for the same effect.
Here goes (remember to use the "ignore whitespace" flag /x
if you use the commented version below) :
# Only include if previous char was start of string or delimiter
(?<=^|,)
(?:
# 1st option: empty quoted string (,'',)
'{2}
|
# 2nd option: nothing (,,)
(?:)
|
# 3rd option: all but quoted strings (,123,)
# (included linebreaks to allow multiline matching)
[^,'\r\n]+
|
# 4th option: quoted strings (,'123''321',)
# start pling
'
(?:
# double quote
'{2}
|
# or anything but quotes
[^']+
# at least one occurance - greedy
)+
# end pling
'
)
# Only include if next char is delimiter or end of string
(?=,|$)
Single line version:
(?<=^|,)(?:'{2}|(?:)|[^,'\r\n]+|'(?:'{2}|[^']+)+')(?=,|$)
This snippet works in IE7 at least
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Test</title>
<style>
#foo {
position: fixed;
bottom: 0;
right: 0;
}
</style>
</head>
<body>
<div id="foo">Hello World</div>
</body>
</html>
If your hardware is 32-bit only, then no. If you have 64 bit hardware and a 32-bit operating system, then maybe. See Hardware and Firmware Requirements for 64-Bit Guest Operating Systems for details. It has nothing to do with one vs. multiple processors.
Here's a pure-numpy implementation. It's about 5× faster than using itertools.
import numpy as np
def cartesian(arrays, out=None):
"""
Generate a cartesian product of input arrays.
Parameters
----------
arrays : list of array-like
1-D arrays to form the cartesian product of.
out : ndarray
Array to place the cartesian product in.
Returns
-------
out : ndarray
2-D array of shape (M, len(arrays)) containing cartesian products
formed of input arrays.
Examples
--------
>>> cartesian(([1, 2, 3], [4, 5], [6, 7]))
array([[1, 4, 6],
[1, 4, 7],
[1, 5, 6],
[1, 5, 7],
[2, 4, 6],
[2, 4, 7],
[2, 5, 6],
[2, 5, 7],
[3, 4, 6],
[3, 4, 7],
[3, 5, 6],
[3, 5, 7]])
"""
arrays = [np.asarray(x) for x in arrays]
dtype = arrays[0].dtype
n = np.prod([x.size for x in arrays])
if out is None:
out = np.zeros([n, len(arrays)], dtype=dtype)
m = n / arrays[0].size
out[:,0] = np.repeat(arrays[0], m)
if arrays[1:]:
cartesian(arrays[1:], out=out[0:m, 1:])
for j in xrange(1, arrays[0].size):
out[j*m:(j+1)*m, 1:] = out[0:m, 1:]
return out
You need to install ENU\x64\SQLEXPRWT_x64_ENU.exe which is Express with Tools (RTM release. SP1 release can be found here).
As the page states
Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express) This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.
So install this and use the management studio included with it.
John Gordon's answer was the first of dozens of half-explained / documented answers I tried, from many, many sites, that actually worked. Thank You Mr Gordon. Sorry I don't have the points to up-tick your answer.
I would like to add, for other newbies to node-route-file-splitting, that the use of the anonymous function for 'index' is what one will more often see, so using John's example for the main.js, the functionally-equivalent code one would normally find is:
app.get('/',(req, res) {
res.render('index', { title: 'Express' });
});
I somehow had this issue after I lost internet connection. I was able to fix it by updating the Maven indexes in Eclipse and then selecting my project and updating the Snapshots/releases.
Just encode html using Base64 algorithm before adding html to the JSON and decode html using Base64 when you read.
byte[] utf8 = htmlMessage.getBytes("UTF8");
htmlMessage= new String(new Base64().encode(utf8));
byte[] dec = new Base64().decode(htmlMessage.getBytes());
htmlMessage = new String(dec , "UTF8");
You can also pass value directly via URL.
If you want to call method
public static void calling(string name){....}
then you should call usingHttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create("http://localhost:****/Report/calling?name=Priya);
webrequest.Method = "GET";
webrequest.ContentType = "application/text";
Just make sure you are using ?Object = value
in URL
Is it that
success()
returns earlier thancomplete()
?
Yes; the AJAX success()
method runs before the complete()
method.
Below is a diagram illustrating the process flow:
It is important to note that
The success()
(Local Event) is only called if the request was successful (no errors from the server, no errors with the data).
On the other hand, the complete()
(Local Event) is called regardless of if the request was successful, or not. You will always receive a complete callback, even for synchronous requests.
... more details on AJAX Events here.
TO Copy The Folder I Use Two Text Box To Know The Place Of Folder And Anther Text Box To Know What The Folder To Copy It And This Is The Code
MessageBox.Show("The File is Create in The Place Of The Programe If you Don't Write The Place Of copy And You write Only Name Of Folder");// It Is To Help The User TO Know
if (Fromtb.Text=="")
{
MessageBox.Show("Ples You Should Write All Text Box");
Fromtb.Select();
return;
}
else if (Nametb.Text == "")
{
MessageBox.Show("Ples You Should Write The Third Text Box");
Nametb.Select();
return;
}
else if (Totb.Text == "")
{
MessageBox.Show("Ples You Should Write The Second Text Box");
Totb.Select();
return;
}
string fileName = Nametb.Text;
string sourcePath = @"" + Fromtb.Text;
string targetPath = @"" + Totb.Text;
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
//when The User Write The New Folder It Will Create
MessageBox.Show("The File is Create in "+" "+Totb.Text);
}
System.IO.File.Copy(sourceFile, destFile, true);
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
foreach (string s in files)
{
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
MessageBox.Show("The File is copy To " + Totb.Text);
}
Use the aggregate MAX(signin)
grouped by id. This will list the most recent signin
for each id
.
SELECT
id,
MAX(signin) AS most_recent_signin
FROM tbl
GROUP BY id
To get the whole single record, perform an INNER JOIN
against a subquery which returns only the MAX(signin)
per id.
SELECT
tbl.id,
signin,
signout
FROM tbl
INNER JOIN (
SELECT id, MAX(signin) AS maxsign FROM tbl GROUP BY id
) ms ON tbl.id = ms.id AND signin = maxsign
WHERE tbl.id=1
Extending on pkozlowski.opensource's answer and using javascript array's
builtin filter method a prettified solution could be this:
.filter('weDontLike', function(){
return function(items, name){
return items.filter(function(item) {
return item.name != name;
});
};
});
Here's the jsfiddle link.
More on Array filter here.
Try this, but i don't sure that will work every where :)
public enum MyEnum {
A("Start There"),
B("Start Here");
MyEnum(String name) {
try {
Field fieldName = getClass().getSuperclass().getDeclaredField("name");
fieldName.setAccessible(true);
fieldName.set(this, name);
fieldName.setAccessible(false);
} catch (Exception e) {}
}
}
What will you do when a user hits ALT + F4 or closes it from Task Manager
Why don't you keep track if they did not complete it in a cookie or the DB and when they visit next time just bring the same screen back...:BTW..you haven't finished filling this form out..."
Of course if you were around before the dotcom bust you would remember porn storms, where if you closed 1 window 15 others would open..so yes there is code that will detect a window closing but if you hit ALT + F4 twice it will close the child and the parent (if it was a popup)
First off: My problem isn't the exact same as yours, but this post is the first thing that comes up in google for the Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'
error at the time I wrote this. The solution may be useful to people searching for this error as I did not find this specific solution anywhere online.
In my case, I used Xampp/Apache and PHP sqlsrv to try to connect to an MSSQL database using Windows Authentication and received the Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'
error you described. I finally found the problem to be the Apache service itself running under the user "LOCAL SERVICE" instead of the user account I was logged in as. In other words, it literally was using an anonymous account. The solution was to go into services.msc, right click the Apache service, go to Properties, go to the Log On tab, and enter the credentials for the user. This falls in line with your problem related to SPN's as your SPN's are set up to run from a specific user on the domain. So if the correct SPN is not running, windows authentication will default to the wrong user (likely the "LOCAL SERVICE" user) and give you the Anonymous error.
Here's where it's different from your problem. None of the computers on the local network are on a Domain, they are only on a Workgroup. To use Windows Authentication with a Workgroup, both the computer with the server (in my case MSSQL Server) and the computer with the service requesting data (in my case Apache) needed to have a user with an identical name and identical password.
To summarize, The Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'
error in both our cases seems to be caused by a service not running and/or not on the right user. Ensuring the right SPN or other Service is running and under the correct user should solve the anonymous part of the problem.
How about this algorithm? Split text on whitespace, then trim punctuation. This carefully removes punctuation from the edge of words, without harming apostrophes inside words such as we're
.
>>> text
"'Oh, you can't help that,' said the Cat: 'we're all mad here. I'm mad. You're mad.'"
>>> text.split()
["'Oh,", 'you', "can't", 'help', "that,'", 'said', 'the', 'Cat:', "'we're", 'all', 'mad', 'here.', "I'm", 'mad.', "You're", "mad.'"]
>>> import string
>>> [word.strip(string.punctuation) for word in text.split()]
['Oh', 'you', "can't", 'help', 'that', 'said', 'the', 'Cat', "we're", 'all', 'mad', 'here', "I'm", 'mad', "You're", 'mad']
With the modal open in the browser window, use the browser's console to try
$('#myModal').modal('hide');
If it works (and the modal closes) then you know that your close Javascript is not being sent from the server to the browser correctly.
If it doesn't work then you need to investigate further on the client what is happening. Eg make sure that there aren't two elements with the same id. Eg does it work the first time after page load but not the second time?
Browser's console: firebug for firefox, the debugging console for Chrome or Safari, etc.
You can use the variables name itself to check if a value is an integer. for example:
#include <iostream>
using namespace std;
int main (){
int firstvariable;
int secondvariable;
float float1;
float float2;
cout << "Please enter two integers and then press Enter:" << endl;
cin >> firstvariable;
cin >> secondvariable;
if(firstvariable && secondvariable){
cout << "Time for some simple mathematical operations:\n" << endl;
cout << "The sum:\n " << firstvariable << "+" << secondvariable
<<"="<< firstvariable + secondvariable << "\n " << endl;
}else{
cout << "\n[ERROR\tINVALID INPUT]\n";
return 1;
}
return 0;
}
Any other way to import this lib? I can simply copy-paste source code into my source or create JAR out of it?
Complete Steps for importing a library in Android Studio 1.1
Add the following line with your module name
compile project(':internal_project_name')
Taken from: how to add library in Android Studio
When you create CSS style using Dreamweaver for web designing, Dreamweaver adds a default code such as
@charset “utf-8";
Try removing this from your stylesheet, the background image or colour should display properly
The driver you are using is the MS SQL server 2008 driver (sqljdbc4.jar). As stated in the MSDN page it requires Java 6+ to work.
http://msdn.microsoft.com/en-us/library/ms378526.aspx
sqljdbc4.jar class library requires a Java Runtime Environment (JRE) of version 6.0 or later.
I'd suggest using the 2005 driver which I beleive is in (sqljdbc.jar) or as Oxbow_Lakes says try the jTDS driver (http://jtds.sourceforge.net/).
If you hit problems where column names are ambiguous, you can do:
date_field = Note.arel_table[:date]
Note.where(user_id: current_user.id, notetype: p[:note_type]).
where(date_field.gt(p[:date])).
order(date_field.asc(), Note.arel_table[:created_at].asc())
<script type="text/javascript">
top.frames['DetailFrame'].location = top.frames['DetailFrame'].location;
</script>
You might also try giving the full path to the binary you're trying to run. That solved my problem when trying to use ImageMagick
.
Here's the code I put together based on example from this blog: LINK and this source: LINK.
import com.sun.jndi.ldap.LdapCtxFactory;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Iterator;
import javax.naming.Context;
import javax.naming.AuthenticationException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import static javax.naming.directory.SearchControls.SUBTREE_SCOPE;
class App2 {
public static void main(String[] args) {
if (args.length != 4 && args.length != 2) {
System.out.println("Purpose: authenticate user against Active Directory and list group membership.");
System.out.println("Usage: App2 <username> <password> <domain> <server>");
System.out.println("Short usage: App2 <username> <password>");
System.out.println("(short usage assumes 'xyz.tld' as domain and 'abc' as server)");
System.exit(1);
}
String domainName;
String serverName;
if (args.length == 4) {
domainName = args[2];
serverName = args[3];
} else {
domainName = "xyz.tld";
serverName = "abc";
}
String username = args[0];
String password = args[1];
System.out
.println("Authenticating " + username + "@" + domainName + " through " + serverName + "." + domainName);
// bind by using the specified username/password
Hashtable props = new Hashtable();
String principalName = username + "@" + domainName;
props.put(Context.SECURITY_PRINCIPAL, principalName);
props.put(Context.SECURITY_CREDENTIALS, password);
DirContext context;
try {
context = LdapCtxFactory.getLdapCtxInstance("ldap://" + serverName + "." + domainName + '/', props);
System.out.println("Authentication succeeded!");
// locate this user's record
SearchControls controls = new SearchControls();
controls.setSearchScope(SUBTREE_SCOPE);
NamingEnumeration<SearchResult> renum = context.search(toDC(domainName),
"(& (userPrincipalName=" + principalName + ")(objectClass=user))", controls);
if (!renum.hasMore()) {
System.out.println("Cannot locate user information for " + username);
System.exit(1);
}
SearchResult result = renum.next();
List<String> groups = new ArrayList<String>();
Attribute memberOf = result.getAttributes().get("memberOf");
if (memberOf != null) {// null if this user belongs to no group at all
for (int i = 0; i < memberOf.size(); i++) {
Attributes atts = context.getAttributes(memberOf.get(i).toString(), new String[] { "CN" });
Attribute att = atts.get("CN");
groups.add(att.get().toString());
}
}
context.close();
System.out.println();
System.out.println("User belongs to: ");
Iterator ig = groups.iterator();
while (ig.hasNext()) {
System.out.println(" " + ig.next());
}
} catch (AuthenticationException a) {
System.out.println("Authentication failed: " + a);
System.exit(1);
} catch (NamingException e) {
System.out.println("Failed to bind to LDAP / get account information: " + e);
System.exit(1);
}
}
private static String toDC(String domainName) {
StringBuilder buf = new StringBuilder();
for (String token : domainName.split("\\.")) {
if (token.length() == 0)
continue; // defensive check
if (buf.length() > 0)
buf.append(",");
buf.append("DC=").append(token);
}
return buf.toString();
}
}
import UIKit
@IBDesignable
class RoundedButton: UIButton {
@IBInspectable var cornerRadius: CGFloat = 8
@IBInspectable var borderColor: UIColor? = .lightGray
override func draw(_ rect: CGRect) {
layer.cornerRadius = cornerRadius
layer.masksToBounds = true
layer.borderWidth = 1
layer.borderColor = borderColor?.cgColor
}
}
$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
ADD COLUMN `ping_status` INT(1) NOT NULL
AFTER `<TABLE COLUMN BEFORE THIS COLUMN>`";
I believe you need to have ADD COLUMN
and use AFTER
, not BEFORE
.
In case you want to place column at the beginning of a table, use the FIRST
statement:
$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
ADD COLUMN `ping_status` INT(1) NOT NULL
FIRST";
Do you mean include javascript variable values in the query string of the URL?
Yes:
window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat="+var1+"&lon="+var2+"&setLatLon="+varEtc;
In my case, I was updating the server-sided datatable twice and it gives me this error. Hope it helps someone.
A simple for loop?
for i in range(3):
do()
Or, if you're interested in the results and want to collect them, with the bonus of being a 1 liner:
vals = [do() for _ in range(3)]
In DOS/Windows Batch most commands return an exitCode, called "errorlevel", that is a value that customarily is equal to zero if the command ends correctly, or a number greater than zero if ends because an error, with greater numbers for greater errors (hence the name).
There are a couple methods to check that value, but the original one is:
IF ERRORLEVEL value command
Previous IF test if the errorlevel returned by the previous command was GREATER THAN OR EQUAL the given value and, if this is true, execute the command. For example:
verify bad-param
if errorlevel 1 echo Errorlevel is greater than or equal 1
echo The value of errorlevel is: %ERRORLEVEL%
Findstr command return 0 if the string was found and 1 if not:
CD C:\MyFolder
findstr /c:"stringToCheck" fileToCheck.bat
IF ERRORLEVEL 1 XCOPY "C:\OtherFolder\fileToCheck.bat" "C:\MyFolder" /s /y
Previous code will copy the file if the string was NOT found in the file.
CD C:\MyFolder
findstr /c:"stringToCheck" fileToCheck.bat
IF NOT ERRORLEVEL 1 XCOPY "C:\OtherFolder\fileToCheck.bat" "C:\MyFolder" /s /y
Previous code copy the file if the string was found. Try this:
findstr "string" file
if errorlevel 1 (
echo String NOT found...
) else (
echo String found
)
import subprocess as sp
for v in str(sp.check_output('powershell "gps | where {$_.MainWindowTitle}"')).split(' '):
if len(v) is not 0 and '-' not in v and '\\r\\' not in v and 'iTunes' in v: print('Found !')
Yes, headers are encrypted. It's written here.
Everything in the HTTPS message is encrypted, including the headers, and the request/response load.
type normal division first and then type shift + S->d
If you want to overwrite only one file:
git fetch
git checkout origin/master <filepath>
If you want to overwrite all changed files:
git fetch
git reset --hard origin/master
(This assumes that you're working on master
locally and you want the changes on the origin's master
- if you're on a branch, substitute that in instead.)
DateTime.Now.ToShortTimeString().ToString()
This Will give you DateTime as 10:50PM
I realize the following suggestion doesn't answer your question, but the simplest method I have found to capture a rapidly-changing DirectX view, is to plug a video camera into the S-video port of the video card, and record the images as a movie. Then transfer the video from the camera back to an MPG, WMV, AVI etc. file on the computer.
New method in Django 3
you can use Field.choices Enumeration Types new update in django3 like this :
from django.db import models
class Status(models.TextChoices):
UNPUBLISHED = 'UN', 'Unpublished'
PUBLISHED = 'PB', 'Published'
class Book(models.Model):
status = models.CharField(
max_length=2,
choices=Status.choices,
default=Status.UNPUBLISHED,
)
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<fork>true</fork>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
It uses the normal trash bin of your system. So you can grab it our of there.
In Windows you find it in the explorer, in Linux it is as well in Konquerer / Nemo / ...
var defaultsettings = {
ajaxsettings: {
...
},
uisettings: {
...
}
};
I was getting this error because of the new Google Universal Analytics code, particularly caused by using the Remarketing lists on Analytics.
Here's how I fixed it.
1) Log into Google Analytics
2) Click "Admin" in top menu
3) In "Property" column, click "Property Settings"
4) Make sure "Enable Display Advertiser Features" is "On"
5) Click "Save" at bottom
6) Click ".js Tracking Info" in left menu
7) Click "Tracking Code"
8) Update your website's tracking code
When you run the debugger again, hopefully it will be taken care of.
iframe doesn't have onclick event but we can implement this by using iframe's onload event and javascript like this...
function iframeclick() {
document.getElementById("theiframe").contentWindow.document.body.onclick = function() {
document.getElementById("theiframe").contentWindow.location.reload();
}
}
<iframe id="theiframe" src="youriframe.html" style="width: 100px; height: 100px;" onload="iframeclick()"></iframe>
I hope it will helpful to you....
Text inside an ifdef/endif
or ifndef/endif
pair will be left in or removed by the pre-processor depending on the condition. ifdef
means "if the following is defined" while ifndef
means "if the following is not defined".
So:
#define one 0
#ifdef one
printf("one is defined ");
#endif
#ifndef one
printf("one is not defined ");
#endif
is equivalent to:
printf("one is defined ");
since one
is defined so the ifdef
is true and the ifndef
is false. It doesn't matter what it's defined as. A similar (better in my opinion) piece of code to that would be:
#define one 0
#ifdef one
printf("one is defined ");
#else
printf("one is not defined ");
#endif
since that specifies the intent more clearly in this particular situation.
In your particular case, the text after the ifdef
is not removed since one
is defined. The text after the ifndef
is removed for the same reason. There will need to be two closing endif
lines at some point and the first will cause lines to start being included again, as follows:
#define one 0
+--- #ifdef one
| printf("one is defined "); // Everything in here is included.
| +- #ifndef one
| | printf("one is not defined "); // Everything in here is excluded.
| | :
| +- #endif
| : // Everything in here is included again.
+--- #endif
I had a similar error, right after the first instantiation of Django (v3.0.3). All recommendations here did not work apart from:
db.sqlite3
file and lose the data there, if any,python manage.py makemigrations
python manage.py migrate
Btw, if you want to just test PostgreSQL:
docker run --rm --name django-postgres \
-e POSTGRES_PASSWORD=mypassword \
-e PGPORT=5432 \
-e POSTGRES_DB=myproject \
-p 5432:5432 \
postgres:9.6.17-alpine
Change the settings.py
to add this DATABASES
:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'myproject',
'USER': 'postgres',
'PASSWORD': 'mypassword',
'HOST': 'localhost',
'PORT': '5432',
}
}
...and add database adapter:
pip install psycopg2-binary
Then the usual:
python manage.py makemigrations
python manage.py migrate
Exceptions bubble up the stack. If a caller calls a method that throws a checked exception, like IOException, it must also either catch the exception, or itself throw it.
In the case of the first block:
filecontent()
{
setGUI();
setRegister();
showfile();
setTitle("FileData");
setVisible(true);
setSize(300, 300);
/*
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
*/
}
You would have to include a try catch block:
filecontent()
{
setGUI();
setRegister();
try {
showfile();
}
catch (IOException e) {
// Do something here
}
setTitle("FileData");
setVisible(true);
setSize(300, 300);
/*
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
*/
}
In the case of the second:
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == submit)
{
showfile();
}
}
You cannot throw IOException from this method as its signature is determined by the interface, so you must catch the exception within:
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==submit)
{
try {
showfile();
}
catch (IOException e) {
// Do something here
}
}
}
Remember, the showFile() method is throwing the exception; that's what the "throws" keyword indicates that the method may throw that exception. If the showFile() method is throwing, then whatever code calls that method must catch, or themselves throw the exception explicitly by including the same throws IOException addition to the method signature, if it's permitted.
If the method is overriding a method signature defined in an interface or superclass that does not also declare that the method may throw that exception, you cannot declare it to throw an exception.
You need to put arguments before my_script.R
and use -
on the arguments, e.g.
R CMD BATCH -blabla my_script.R
commandArgs()
will receive -blabla
as a character string in this case. See the help for details:
$ R CMD BATCH --help
Usage: R CMD BATCH [options] infile [outfile]
Run R non-interactively with input from infile and place output (stdout
and stderr) to another file. If not given, the name of the output file
is the one of the input file, with a possible '.R' extension stripped,
and '.Rout' appended.
Options:
-h, --help print short help message and exit
-v, --version print version info and exit
--no-timing do not report the timings
-- end processing of options
Further arguments starting with a '-' are considered as options as long
as '--' was not encountered, and are passed on to the R process, which
by default is started with '--restore --save --no-readline'.
See also help('BATCH') inside R.
Several ways.
From the shell
python someFile.py
From inside IDLE, hit F5.
If you're typing interactively, try this: (Python 2 only!)
>>> variables= {}
>>> execfile( "someFile.py", variables )
>>> print variables # globals from the someFile module
For Python3, use:
>>> exec(open("filename.py").read())
input[type="text"]
{
background: transparent;
border: none;
}
Nobody will even know it's there.
If all you need is the coordinates here is a drawing tool I like to use - move the polygon or re-shape it and the coordinates will display right below the map: jsFiddle here.
Also, here is a Codepen
JS
var bermudaTriangle;
function initialize() {
var myLatLng = new google.maps.LatLng(33.5190755, -111.9253654);
var mapOptions = {
zoom: 12,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.RoadMap
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var triangleCoords = [
new google.maps.LatLng(33.5362475, -111.9267386),
new google.maps.LatLng(33.5104882, -111.9627875),
new google.maps.LatLng(33.5004686, -111.9027061)
];
// Construct the polygon
bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
draggable: true,
editable: true,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
bermudaTriangle.setMap(map);
google.maps.event.addListener(bermudaTriangle, "dragend", getPolygonCoords);
google.maps.event.addListener(bermudaTriangle.getPath(), "insert_at", getPolygonCoords);
google.maps.event.addListener(bermudaTriangle.getPath(), "remove_at", getPolygonCoords);
google.maps.event.addListener(bermudaTriangle.getPath(), "set_at", getPolygonCoords);
}
function getPolygonCoords() {
var len = bermudaTriangle.getPath().getLength();
var htmlStr = "";
for (var i = 0; i < len; i++) {
htmlStr += bermudaTriangle.getPath().getAt(i).toUrlValue(5) + "<br>";
}
document.getElementById('info').innerHTML = htmlStr;
}
HTML
<body onload="initialize()">
<h3>Drag or re-shape for coordinates to display below</h3>
<div id="map-canvas">
</div>
<div id="info">
</div>
</body>
CSS
#map-canvas {
width: auto;
height: 350px;
}
#info {
position: absolute;
font-family: arial, sans-serif;
font-size: 18px;
font-weight: bold;
}
Maybe not the best solution, (will rewrite history) but you could also do git reset --hard <hash of detached head commit>
.
When you just want to execute one or several HTTP requests without having to wait for the response, there is a simple PHP solution, as well.
In the calling script:
$socketcon = fsockopen($host, 80, $errno, $errstr, 10);
if($socketcon) {
$socketdata = "GET $remote_house/script.php?parameters=... HTTP 1.1\r\nHost: $host\r\nConnection: Close\r\n\r\n";
fwrite($socketcon, $socketdata);
fclose($socketcon);
}
// repeat this with different parameters as often as you like
On the called script.php, you can invoke these PHP functions in the first lines:
ignore_user_abort(true);
set_time_limit(0);
This causes the script to continue running without time limit when the HTTP connection is closed.
<EditText
android:id="@+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="DD/MM/YYYY"
android:inputType="date"
android:focusable="false"/>
<EditText
android:id="@+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="00:00"
android:inputType="time"
android:focusable="false"/>
JAVA FILE
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText selectDate,selectTime;
private int mYear, mMonth, mDay, mHour, mMinute;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectDate=(EditText)findViewById(R.id.date);
selectTime=(EditText)findViewById(R.id.time);
selectDate.setOnClickListener(this);
selectTime.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (view == selectDate) {
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
selectDate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
if (view == selectTime) {
// Get Current Time
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog timePickerDialog = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
selectTime.setText(hourOfDay + ":" + minute);
}
}, mHour, mMinute, false);
timePickerDialog.show();
}
}
}
I have the same problem after update visual studio, so this is how do I solve the problem.
Hope this helpful for anyone who has this problem.
it seems
command args overwrite environment variable
Makefile
send:
echo $(MESSAGE1) $(MESSAGE2)
Run example
$ MESSAGE1=YES MESSAGE2=NG make send MESSAGE2=OK
echo YES OK
YES OK
In addition to Jhonson's list, also check library's folders
In visual studio, select Tools > Options from the main menu. select Projects and Solutions > VC++ Directories. Select x64 from the Platform dropdown.
$(VCInstallDir)lib\AMD64;
$(VCInstallDir)atlmfc\lib\amd64;
$(WindowsSdkDir)lib\x64;
Had same issue with Firefox. I switched over to Chrome with options and all has been fine since.
ChromeOptions options = new ChromeOptions();
options.AddArgument("no-sandbox");
ChromeDriver driver = new ChromeDriver(ChromeDriverService.CreateDefaultService(), options, TimeSpan.FromMinutes(3));
driver.Manage().Timeouts().PageLoad.Add(System.TimeSpan.FromSeconds(30));
In case you want to return a string in 00:00 format...
convertMinsToHrsMins: function (minutes) {
var h = Math.floor(minutes / 60);
var m = minutes % 60;
h = h < 10 ? '0' + h : h;
m = m < 10 ? '0' + m : m;
return h + ':' + m;
}
Thanks for the up-votes. Here's a slightly tidier ES6 version :)
const convertMinsToHrsMins = (mins) => {
let h = Math.floor(mins / 60);
let m = mins % 60;
h = h < 10 ? '0' + h : h;
m = m < 10 ? '0' + m : m;
return `${h}:${m}`;
}
If you want to print more than a single result, just select rows into a temporary table, then select from that temp table into a buffer, then print the buffer:
drop table if exists #temp
-- we just want to see our rows, not how many were inserted
set nocount on
select * into #temp from MyTable
-- note: SSMS will only show 8000 chars
declare @buffer varchar(MAX) = ''
select @buffer = @buffer + Col1 + ' ' + Col2 + CHAR(10) from #temp
print @buffer
MySQL 5.5 on Ubuntu 14.04 required slightly different commands as recommended here. In a nutshell:
sudo /etc/init.d/mysql stop
sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking &
mysql -u root
And then from the MySQL prompt
FLUSH PRIVILEGES;
SET PASSWORD FOR root@'localhost' = PASSWORD('password');
UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';
FLUSH PRIVILEGES;
And the cited source offers an alternate method as well.
A string to char array is as simple as
String str = "someString";
char[] charArray = str.toCharArray();
Can you explain a little more on what you are trying to do?
* Update *
if I am understanding your new comment, you can use a byte array and example is provided.
byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();
for (byte b : bytes) {
System.out.format("0x%x ", b);
}
With the following output
0x65 0x10 0xf3 0x29
In easy (practical) terms:
Copying an object means copying its "static" members and calling the new
operator for its dynamic objects. Right?
class A
{
int i, *p;
public:
A(const A& a) : i(a.i), p(new int(*a.p)) {}
~A() { delete p; }
};
However, to move an object (I repeat, in a practical point of view) implies only to copy the pointers of dynamic objects, and not to create new ones.
But, is that not dangerous? Of course, you could destruct a dynamic object twice (segmentation fault). So, to avoid that, you should "invalidate" the source pointers to avoid destructing them twice:
class A
{
int i, *p;
public:
// Movement of an object inside a copy constructor.
A(const A& a) : i(a.i), p(a.p)
{
a.p = nullptr; // pointer invalidated.
}
~A() { delete p; }
// Deleting NULL, 0 or nullptr (address 0x0) is safe.
};
Ok, but if I move an object, the source object becomes useless, no? Of course, but in certain situations that's very useful. The most evident one is when I call a function with an anonymous object (temporal, rvalue object, ..., you can call it with different names):
void heavyFunction(HeavyType());
In that situation, an anonymous object is created, next copied to the function parameter, and afterwards deleted. So, here it is better to move the object, because you don't need the anonymous object and you can save time and memory.
This leads to the concept of an "rvalue" reference. They exist in C++11 only to detect if the received object is anonymous or not. I think you do already know that an "lvalue" is an assignable entity (the left part of the =
operator), so you need a named reference to an object to be capable to act as an lvalue. A rvalue is exactly the opposite, an object with no named references. Because of that, anonymous object and rvalue are synonyms. So:
class A
{
int i, *p;
public:
// Copy
A(const A& a) : i(a.i), p(new int(*a.p)) {}
// Movement (&& means "rvalue reference to")
A(A&& a) : i(a.i), p(a.p)
{
a.p = nullptr;
}
~A() { delete p; }
};
In this case, when an object of type A
should be "copied", the compiler creates a lvalue reference or a rvalue reference according to if the passed object is named or not. When not, your move-constructor is called and you know the object is temporal and you can move its dynamic objects instead of copying them, saving space and memory.
It is important to remember that "static" objects are always copied. There's no ways to "move" a static object (object in stack and not on heap). So, the distinction "move"/ "copy" when an object has no dynamic members (directly or indirectly) is irrelevant.
If your object is complex and the destructor has other secondary effects, like calling to a library's function, calling to other global functions or whatever it is, perhaps is better to signal a movement with a flag:
class Heavy
{
bool b_moved;
// staff
public:
A(const A& a) { /* definition */ }
A(A&& a) : // initialization list
{
a.b_moved = true;
}
~A() { if (!b_moved) /* destruct object */ }
};
So, your code is shorter (you don't need to do a nullptr
assignment for each dynamic member) and more general.
Other typical question: what is the difference between A&&
and const A&&
? Of course, in the first case, you can modify the object and in the second not, but, practical meaning? In the second case, you can't modify it, so you have no ways to invalidate the object (except with a mutable flag or something like that), and there is no practical difference to a copy constructor.
And what is perfect forwarding? It is important to know that a "rvalue reference" is a reference to a named object in the "caller's scope". But in the actual scope, a rvalue reference is a name to an object, so, it acts as a named object. If you pass an rvalue reference to another function, you are passing a named object, so, the object isn't received like a temporal object.
void some_function(A&& a)
{
other_function(a);
}
The object a
would be copied to the actual parameter of other_function
. If you want the object a
continues being treated as a temporary object, you should use the std::move
function:
other_function(std::move(a));
With this line, std::move
will cast a
to an rvalue and other_function
will receive the object as a unnamed object. Of course, if other_function
has not specific overloading to work with unnamed objects, this distinction is not important.
Is that perfect forwarding? Not, but we are very close. Perfect forwarding is only useful to work with templates, with the purpose to say: if I need to pass an object to another function, I need that if I receive a named object, the object is passed as a named object, and when not, I want to pass it like a unnamed object:
template<typename T>
void some_function(T&& a)
{
other_function(std::forward<T>(a));
}
That's the signature of a prototypical function that uses perfect forwarding, implemented in C++11 by means of std::forward
. This function exploits some rules of template instantiation:
`A& && == A&`
`A&& && == A&&`
So, if T
is a lvalue reference to A
(T = A&), a
also (A& && => A&). If T
is a rvalue reference to A
, a
also (A&& && => A&&). In both cases, a
is a named object in the actual scope, but T
contains the information of its "reference type" from the caller scope's point of view. This information (T
) is passed as template parameter to forward
and 'a' is moved or not according to the type of T
.
I use this for MessageFormat (using Java 1.4). That way I am sure that I have no concatenations that are hard to extract when doing internationalization
i18n
String msg = "${message}";
Object[] params = {${params}};
MessageFormat.format(msg, params);
Also for logging:
log
if(logger.isDebugEnabled()){
String msg = "${message}"; //NLS-1
Object[] params = {${params}};
logger.debug(MessageFormat.format(msg, params));
}
First of all, you do not have to develop any form yourself : phpMyAdmin, depending on its configuration (i.e. config.inc.php
) will display an identification form, asking for a login and password.
To get that form, you should not use :
$cfg['Servers'][$i]['auth_type'] = 'config';
But you should use :
$cfg['Servers'][$i]['auth_type'] = 'cookie';
(At least, that's what I have on a server which prompts for login/password, using a form)
For more informations, you can take a look at the documentation :
'config'
authentication ($auth_type = 'config'
) is the plain old way: username and password are stored in config.inc.php.'cookie'
authentication mode ($auth_type = 'cookie'
) as introduced in 2.2.3 allows you to log in as any valid MySQL user with the help of cookies.
Username and password are stored in cookies during the session and password is deleted when it ends.
It's not at all clear what you're up to. Your function getAll() should return a List<Car>, not a Car. Otherwise, why call it getAll?
If you have
Car[] arrayOfCars
and want a List, you can simply do this:
List<Car> listOfCars = Arrays.asList(arrayOfCars);
Arrays is documented Here.
This works like a charm, fast and accurate:
function replace_string_in_file($filename, $string_to_replace, $replace_with){
$content=file_get_contents($filename);
$content_chunks=explode($string_to_replace, $content);
$content=implode($replace_with, $content_chunks);
file_put_contents($filename, $content);
}
Usage:
$filename="users/data/letter.txt";
$string_to_replace="US$";
$replace_with="Yuan";
replace_string_in_file($filename, $string_to_replace, $replace_with);
// never forget about EXPLODE when it comes about string parsing // it's a powerful and fast tool
The version of the errorHandler middleware bundled with some (perhaps older?) versions of express seems to have the status code hardcoded. The version documented here: http://www.senchalabs.org/connect/errorHandler.html on the other hand lets you do what you are trying to do. So, perhaps trying upgrading to the latest version of express/connect.
Find the Run button present on the top of the Eclipse, then select Run Configuration -> Arguments, in VM arguments section just mention the heap size you want to extend as below:
-Xmx1024m
$(<img />).attr('src','http://somedomain.com/image.jpg');
Should be better than ajax because if its a gallery and you are looping through a list of pics, if the image is already in cache, it wont send another request to server. It will request in the case of jQuery/ajax and return a HTTP 304 (Not modified) and then use original image from cache if its already there. The above method reduces an empty request to server after the first loop of images in the gallery.
With resources, there's built-in support for providing alternatives for different languages, OS versions, screen orientations, etc., as described here. None of that is available with assets. Also, many parts of the API support the use of resource identifiers. Finally, the names of the resources are turned into constant field names that are checked at compile time, so there's less of an opportunity for mismatches between the code and the resources themselves. None of that applies to assets.
So why have an assets folder at all? If you want to compute the asset you want to use at run time, it's pretty easy. With resources, you would have to declare a list of all the resource IDs that might be used and compute an index into the the list. (This is kind of awkward and introduces opportunities for error if the set of resources changes in the development cycle.) (EDIT: you can retrieve a resource ID by name using getIdentifier
, but this loses the benefits of compile-time checking.) Assets can also be organized into a folder hierarchy, which is not supported by resources. It's a different way of managing data. Although resources cover most of the cases, assets have their occasional use.
One other difference: resources defined in a library project are automatically imported to application projects that depend on the library. For assets, that doesn't happen; asset files must be present in the assets directory of the application project(s). [EDIT: With Android's new Gradle-based build system (used with Android Studio), this is no longer true. Asset directories for library projects are packaged into the .aar files, so assets defined in library projects are merged into application projects (so they do not have to be present in the application's /assets
directory if they are in a referenced library).]
EDIT: Yet another difference arises if you want to package a custom font with your app. There are API calls to create a Typeface
from a font file stored in the file system or in your app's assets/
directory. But there is no API to create a Typeface
from a font file stored in the res/
directory (or from an InputStream
, which would allow use of the res/
directory). [NOTE: With Android O (now available in alpha preview) you will be able to include custom fonts as resources. See the description here of this long-overdue feature. However, as long as your minimum API level is 25 or less, you'll have to stick with packaging custom fonts as assets rather than as resources.]
It will be found in /usr/local/mysql
if you use the mysql binaries or dmg to install it on your system instead of using MAMP
Got the answer: I should not use parentheses after return ()
. This works:
return <div> <Search_Bar /> </div>
If you want to write multiline, then return ( ...
Your starting parenthesis should be on the same line as return
.
Other answers are over complicating things. This question is simply logic question. Just get your statement right.
$boolString = 'false';
$result = 'true' === $boolString;
Now your answer will be either
false
, if the string was 'false'
, true
, if your string was 'true'
.I have to note that filter_var( $boolString, FILTER_VALIDATE_BOOLEAN );
still will be a better option if you need to have strings like on/yes/1
as alias for true
.
#!/bin/bash
file_location=/home/test/$1.json
if [ -e $policy ]; then
echo "File $1.json already exists!"
else
cat > $file_location <<EOF
{
"contact": {
"name": "xyz",
"phonenumber": "xxx-xxx-xxxx"
}
}
EOF
fi
This code checks if the given JSON file of the user is present in test home directory or not. If it's not present it will create it with the content. You can modify the file location and content according to your needs.
Simple extension method to copy all the public properties. Works for any objects and does not require class to be [Serializable]
. Can be extended for other access level.
public static void CopyTo( this object S, object T )
{
foreach( var pS in S.GetType().GetProperties() )
{
foreach( var pT in T.GetType().GetProperties() )
{
if( pT.Name != pS.Name ) continue;
( pT.GetSetMethod() ).Invoke( T, new object[]
{ pS.GetGetMethod().Invoke( S, null ) } );
}
};
}
CURDATE()
will give current date while NOW()
will give full date time.
Run the queries, and you will find out whats the difference between them.
SELECT NOW(); -- You will get 2010-12-09 17:10:18
SELECT CURDATE(); -- You will get 2010-12-09
This link will be of interest to you: http://msdn.microsoft.com/en-us/library/ds8bxk2a.aspx
For http connections, the WebRequest and WebResponse classes use SSL to communicate with web hosts that support SSL. The decision to use SSL is made by the WebRequest class, based on the URI it is given. If the URI begins with "https:", SSL is used; if the URI begins with "http:", an unencrypted connection is used.
Display:flex apply flex layout to the flex items or children of the container only. So, the container itself stays a block level element and thus takes up the entire width of the screen.
This causes every flex container to move to a new line on the screen.
Display:inline-flex apply flex layout to the flex items or children as well as to the container itself. As a result the container behaves as an inline flex element just like the children do and thus takes up the width required by its items/children only and not the entire width of the screen.
This causes two or more flex containers one after another, displayed as inline-flex, align themselves side by side on the screen until the whole width of the screen is taken.
To start server locally paste the below code in package.json and run npm start in command line.
"scripts": {
"start": "http-server -c-1 -p 8081"
},
With JDK,
You can also use jinfo to connect to the JVM for the <PROCESS_ID>
in question and get the value for MaxHeapSize:
jinfo -flag MaxHeapSize <PROCESS_ID>
I think you meant print test.sorted_word_list
instead of print test.sort_word_list
.
In addition list.sort()
sorts a list in place and returns None
, so you probably want to change sort_word_list()
to do the following:
self.sorted_word_list = sorted(self.word_list)
You should also consider either renaming your num_words()
function, or changing the attribute that the function assigns to, because currently you overwrite the function with an integer on the first call.
<script type="text/javascript">
// front end cache bust
var cacheBust = ['js/StrUtil.js', 'js/protos.common.js', 'js/conf.js', 'bootstrap_ECP/js/init.js'];
for (i=0; i < cacheBust.length; i++){
var el = document.createElement('script');
el.src = cacheBust[i]+"?v=" + Math.random();
document.getElementsByTagName('head')[0].appendChild(el);
}
</script>
You can attach to a running process with gdb -p PID
.
@Grantismo gives a great overview of Android sync components.
SyncManagerAndroid library provides a simple 2-way sync implementation to plug into the Android Sync framework (AbstractThreadedSyncAdapter.OnPerformSync).
The easiest is setting a program variable (see GDB: assignment):
(gdb) l
6 {
7 int i;
8 struct file *f, *ftmp;
9
(gdb) set variable i = 10
(gdb) p i
$1 = 10
Or you can just update arbitrary (writable) location by address:
(gdb) set {int}0x83040 = 4
There's more. Read the manual.
Encoding.ASCII.GetString(buf);
My ~/.gradle/caches/
folder was using 14G.
After using the following solution, it went from 14G to 1.7G.
$ rm -rf ~/.gradle/caches/transforms-*
$ rm -rf ~/.gradle/caches/build-cache-*
Bonus
This command shows you in detail the used cache space
$ sudo du -ah --max-depth = 1 ~/.gradle/caches/ | sort -hr
Why not just use, toggleClass on click?
js:
$(this).toggleClass("up");
css:
button.up {
-webkit-transform: rotate(180deg);
-moz-transform: rotate(180deg);
-ms-transform: rotate(180deg);
-o-transform: rotate(180deg);
transform: rotate(180deg);
/* IE6–IE9 */
filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.9914448613738104, M12=-0.13052619222005157,M21=0.13052619222005157, M22=0.9914448613738104, sizingMethod='auto expand');
zoom: 1;
}
you can also add this to the css:
button{
-webkit-transition: all 500ms ease-in-out;
-moz-transition: all 500ms ease-in-out;
-o-transition: all 500ms ease-in-out;
-ms-transition: all 500ms ease-in-out;
}
which will add the animation.
PS...
to answer your original question:
you said that it rotates but never stops. When using set timeout you need to make sure you have a condition that will not call settimeout or else it will run forever. So for your code:
<script type="text/javascript">
$(function() {
var $elie = $("#bkgimg");
rotate(0);
function rotate(degree) {
// For webkit browsers: e.g. Chrome
$elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
// For Mozilla browser: e.g. Firefox
$elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});
/* add a condition here for the extremity */
if(degree < 180){
// Animate rotation with a recursive call
setTimeout(function() { rotate(++degree); },65);
}
}
});
</script>
string name;
char *c_string;
getline(cin, name);
c_string = new char[name.length()];
for (int index = 0; index < name.length(); index++){
c_string[index] = name[index];
}
c_string[name.length()] = '\0';//add the null terminator at the end of
// the char array
I know this is not the predefined method but thought it may be useful to someone nevertheless.
Your command should include the url parameter as stated in the script usage comments. The main function has 2 parameters, url and out (which is set to a default value) C:\python23\python "C:\PathToYourScript\SCRIPT.py" http://yoururl.com "C:\OptionalOutput\"
For a SOAP 1.2 Webservice, I normally use
curl --header "content-type: application/soap+xml" --data @filetopost.xml http://domain/path
MULTIPROCESSING
- The multiprocessing library in Python uses separate memory space, multiple CPU cores, bypasses GIL limitations in CPython, child processes are killable (ex. function calls in program) and is much easier to use.
- Some caveats of the module are a larger memory footprint and IPC’s a little more complicated with more overhead.
MULTITHREADING
- The multithreading library is lightweight, shares memory, responsible for responsive UI and is used well for I/O bound applications.
- The module isn’t killable and is subject to the GIL.
- Multiple threads live in the same process in the same space, each thread will do a specific task, have its own code, own stack memory, instruction pointer, and share heap memory.
- If a thread has a memory leak it can damage the other threads and parent process.
Example of Multi-threading and Multiprocessing using Python
Python 3 has the facility of Launching parallel tasks. This makes our work easier.
It has for thread pooling and Process pooling.
The following gives an insight:
ThreadPoolExecutor Example
import concurrent.futures
import urllib.request
URLS = ['http://www.foxnews.com/',
'http://www.cnn.com/',
'http://europe.wsj.com/',
'http://www.bbc.co.uk/',
'http://some-made-up-domain.com/']
# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
with urllib.request.urlopen(url, timeout=timeout) as conn:
return conn.read()
# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
# Start the load operations and mark each future with its URL
future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
for future in concurrent.futures.as_completed(future_to_url):
url = future_to_url[future]
try:
data = future.result()
except Exception as exc:
print('%r generated an exception: %s' % (url, exc))
else:
print('%r page is %d bytes' % (url, len(data)))
ProcessPoolExecutor
import concurrent.futures
import math
PRIMES = [
112272535095293,
112582705942171,
112272535095293,
115280095190773,
115797848077099,
1099726899285419]
def is_prime(n):
if n % 2 == 0:
return False
sqrt_n = int(math.floor(math.sqrt(n)))
for i in range(3, sqrt_n + 1, 2):
if n % i == 0:
return False
return True
def main():
with concurrent.futures.ProcessPoolExecutor() as executor:
for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
print('%d is prime: %s' % (number, prime))
if __name__ == '__main__':
main()
Please follow the way like below:
.selectParent {_x000D_
width:120px;_x000D_
overflow:hidden; _x000D_
}_x000D_
.selectParent select { _x000D_
display: block;_x000D_
width: 100%;_x000D_
padding: 2px 25px 2px 2px; _x000D_
border: none; _x000D_
background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") right center no-repeat; _x000D_
appearance: none; _x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none; _x000D_
}_x000D_
.selectParent.left select {_x000D_
direction: rtl;_x000D_
padding: 2px 2px 2px 25px;_x000D_
background-position: left center;_x000D_
}_x000D_
/* for IE and Edge */ _x000D_
select::-ms-expand { _x000D_
display: none; _x000D_
}
_x000D_
<div class="selectParent">_x000D_
<select>_x000D_
<option value="1">Option 1</option>_x000D_
<option value="2">Option 2</option> _x000D_
</select>_x000D_
</div>_x000D_
<br />_x000D_
<div class="selectParent left">_x000D_
<select>_x000D_
<option value="1">Option 1</option>_x000D_
<option value="2">Option 2</option> _x000D_
</select>_x000D_
</div>
_x000D_
The following will order your data depending on both column in descending order.
ORDER BY article_rating DESC, article_time DESC
Changing a CheckBox appearance to Button will give you difficulty in adjustments. You cannot change its dimensions because its size depends on the size of your text or image.
You can try this: (initialize the count variable first to 1 | int count = 1)
private void settingsBtn_Click(object sender, EventArgs e)
{
count++;
if (count % 2 == 0)
{
settingsPanel.Show();
}
else
{
settingsPanel.Hide();
}
}
It's very simple but it works.
Warning: This will work well with buttons that are occasionally used (i.e. settings), the value of count in int/long may be overloaded when used more than it's capacity without closing the app's process. (Check data type ranges: http://msdn.microsoft.com/en-us/library/s3f49ktz.aspx)
The Good News: If you're running an app that is not intended for use 24/7 all-year round, I think this is helpful. Important thing is that when the app's process ended and you run it again, the count will reset to 1.
Modules Preconditions:
The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (
precondition="managedHandler"
) only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />
If you remove the attribute
precondition="managedHandler"
, Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "
managedHandler
" precondition.To enable all managed modules to run for all requests without configuring each module entry to remove the "
managedHandler
" precondition, use therunAllManagedModulesForAllRequests
property in the<modules>
section:<modules runAllManagedModulesForAllRequests="true" />
When you use this property, the "
managedHandler
" precondition has no effect and all managed modules run for all requests.
Copied from IIS Modules Overview: Preconditions
You can use a function like this to do the conversion:
function toDegrees (angle) {
return angle * (180 / Math.PI);
}
Note that functions like sin
, cos
, and so on do not return angles, they take angles as input. It seems to me that it would be more useful to you to have a function that converts a degree input to radians, like this:
function toRadians (angle) {
return angle * (Math.PI / 180);
}
which you could use to do something like tan(toRadians(45))
.
Oh sure. Use a temp table. If you want a single, not-very-performant statement that "works" you can go with:
DELETE FROM MyTable WHERE NOT RowID IN
(SELECT
(SELECT TOP 1 RowID FROM MyTable mt2
WHERE mt2.Col1 = mt.Col1
AND mt2.Col2 = mt.Col2
AND mt2.Col3 = mt.Col3)
FROM MyTable mt)
Basically, for each row in the table, the sub-select finds the top RowID of all rows that are exactly like the row under consideration. So you end up with a list of RowIDs that represent the "original" non-duplicated rows.
Solution 1. Set your TableLayout tl as class member variable, only call TableLayout tl=(TableLayout)findViewById(R.id.maintable);
when you initiate the class. When button clicked use tl directly, eg. tl.addView(row), don't call FindViewById anymore. So the next new row wouldn't replace the previous new row.
Solution 2. Everytime after button click save your updated data into an array, and then re-render your whole table layout by loop through the array.
You have to modify the control template instead of ItemsPanelTemplate:
<ItemsControl >
<ItemsControl.Template>
<ControlTemplate>
<ScrollViewer x:Name="ScrollViewer" Padding="{TemplateBinding Padding}">
<ItemsPresenter />
</ScrollViewer>
</ControlTemplate>
</ItemsControl.Template>
</ItemsControl>
Maybe, your code does not working because StackPanel has own scrolling functionality. Try to use StackPanel.CanVerticallyScroll property.
One option is to directly input the character you're interested in using hex or octal notation:
printf "\x41\n"
printf "\101\n"
EDIT: This answer is old and likely out of date. Just a heads up so it doesn't lead folks astray. I no longer use Angular so I'm not in a good position to make improvements.
It's actually pretty good logic but you can simplify things a bit.
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.model = { name: 'World' };
$scope.name = "Felipe";
});
app.directive('myDirective', function($compile) {
return {
restrict: 'AE', //attribute or element
scope: {
myDirectiveVar: '=',
//bindAttr: '='
},
template: '<div class="some">' +
'<input ng-model="myDirectiveVar"></div>',
replace: true,
//require: 'ngModel',
link: function($scope, elem, attr, ctrl) {
console.debug($scope);
//var textField = $('input', elem).attr('ng-model', 'myDirectiveVar');
// $compile(textField)($scope.$parent);
}
};
});
<body ng-controller="MainCtrl">
This scope value <input ng-model="name">
<my-directive my-directive-var="name"></my-directive>
</body>
.some {
border: 1px solid #cacaca;
padding: 10px;
}
You can see it in action with this Plunker.
Here's what I see:
EDIT As mentioned by Mark in his comment, there's no reason that you can't use ng-model, just to keep with convention.
In general, your directives should use the isolated scope (which you did correctly) and use the '=' type scope if you want a value in your directive to always map to a value in the parent scope.
The first one will be implemented:
Collection.Where(x => x.Age == 10)
.Where(x => x.Name == "Fido") // applied to the result of the previous
.Where(x => x.Fat == true) // applied to the result of the previous
As opposed to the much simpler (and far fasterpresumably faster):
// all in one fell swoop
Collection.Where(x => x.Age == 10 && x.Name == "Fido" && x.Fat == true)
As for the order preservation, see this ActiveMQ page. In short: order is preserved for single consumers, but with multiple consumers order of delivery is not guaranteed.
Dim inputString As String = "ra"
Enumerable.Range(0, arr.Length).Where(Function(x) arr(x).ToLower().Contains(inputString.ToLower()))
I had the same problem before, and fixed that, the steps could be found on this Fixing error "GLIBCXX_3.4.15" on matlab
You need to call $compile
on the HTML string before inserting it into the DOM so that angular gets a chance to perform the binding.
In your fiddle, it would look something like this.
$("#dynamicContent").html(
$compile(
"<button ng-click='count = count + 1' ng-init='count=0'>Increment</button><span>count: {{count}} </span>"
)(scope)
);
Obviously, $compile
must be injected into your controller for this to work.
Read more in the $compile
documentation.
a proper solution with streams and error handling is below:
const fs = require('fs')
const stream = require('stream')
app.get('/report/:chart_id/:user_id',(req, res) => {
const r = fs.createReadStream('path to file') // or any other way to get a readable stream
const ps = new stream.PassThrough() // <---- this makes a trick with stream error handling
stream.pipeline(
r,
ps, // <---- this makes a trick with stream error handling
(err) => {
if (err) {
console.log(err) // No such file or any other kind of error
return res.sendStatus(400);
}
})
ps.pipe(res) // <---- this makes a trick with stream error handling
})
with Node older then 10 you will need to use pump instead of pipeline.
You can for example just add a "col-xs-12" class to the <ul>
which holds the list items:
<div class="col-md-6" data-toggle="dropdown">
First column
<ul class="dropdown-menu col-xs-12" role="menu" aria-labelledby="dLabel">
<li>Insert your menus here</li>
<li>Insert your menus here</li>
<li>Insert your menus here</li>
<li>Insert your menus here</li>
<li>Insert your menus here</li>
<li>Insert your menus here</li>
</ul>
</div>
This worked ok on any screen resolution in my site. The class will match the list width to it's containing div I believe:
Untested and unsure if this will work, but why not do a few if statements
before, to set variables for the switch statement
.
var small, big;
if(scrollLeft < 1000){
//add some token to the page
//call it small
}
switch (//reference token/) {
case (small):
//do stuff
break;
case (big):
//do stuff;
break;
}
How was the database exported?
If it was exported using exp
and a full schema was exported, then
Create the user:
create user <username> identified by <password> default tablespace <tablespacename> quota unlimited on <tablespacename>;
Grant the rights:
grant connect, create session, imp_full_database to <username>;
Start the import with imp
:
imp <username>/<password>@<hostname> file=<filename>.dmp log=<filename>.log full=y;
If it was exported using expdp
, then start the import with impdp
:
impdp <username>/<password> directory=<directoryname> dumpfile=<filename>.dmp logfile=<filename>.log full=y;
Looking at the error log, it seems you have not specified the directory, so Oracle tries to find the dmp
file in the default directory (i.e., E:\app\Vensi\admin\oratest\dpdump\
).
Either move the export file to the above path or create a directory object to pointing to the path where the dmp
file is present and pass the object name to the impdp
command above.
You can't just change the delimiters from ---- BEGIN SSH2 PUBLIC KEY ----
to -----BEGIN RSA PUBLIC KEY-----
and expect that it will be sufficient to convert from one format to another (which is what you've done in your example).
This article has a good explanation about both formats.
What you get in an RSA PUBLIC KEY
is closer to the content of a PUBLIC KEY
, but you need to offset the start of your ASN.1 structure to reflect the fact that PUBLIC KEY
also has an indicator saying which type of key it is (see RFC 3447). You can see this using openssl asn1parse
and -strparse 19
, as described in this answer.
EDIT: Following your edit, your can get the details of your RSA PUBLIC KEY
structure using grep -v -- ----- | tr -d '\n' | base64 -d | openssl asn1parse -inform DER
:
0:d=0 hl=4 l= 266 cons: SEQUENCE
4:d=1 hl=4 l= 257 prim: INTEGER :FB1199FF0733F6E805A4FD3B36CA68E94D7B974621162169C71538A539372E27F3F51DF3B08B2E111C2D6BBF9F5887F13A8DB4F1EB6DFE386C92256875212DDD00468785C18A9C96A292B067DDC71DA0D564000B8BFD80FB14C1B56744A3B5C652E8CA0EF0B6FDA64ABA47E3A4E89423C0212C07E39A5703FD467540F874987B209513429A90B09B049703D54D9A1CFE3E207E0E69785969CA5BF547A36BA34D7C6AEFE79F314E07D9F9F2DD27B72983AC14F1466754CD41262516E4A15AB1CFB622E651D3E83FA095DA630BD6D93E97B0C822A5EB4212D428300278CE6BA0CC7490B854581F0FFB4BA3D4236534DE09459942EF115FAA231B15153D67837A63
265:d=1 hl=2 l= 3 prim: INTEGER :010001
To decode the SSH key format, you need to use the data format specification in RFC 4251 too, in conjunction with RFC 4253:
The "ssh-rsa" key format has the following specific encoding: string "ssh-rsa" mpint e mpint n
For example, at the beginning, you get 00 00 00 07 73 73 68 2d 72 73 61
. The first four bytes (00 00 00 07
) give you the length. The rest is the string itself: 73=s, 68=h, ... -> 73 73 68 2d 72 73 61
=ssh-rsa
, followed by the exponent of length 1 (00 00 00 01 25
) and the modulus of length 256 (00 00 01 00 7f ...
).
As a oneliner guide:
minSdkVersion <= targetSdkVersion <= compileSdkVersion
Ideally:
minSdkVersion (lowest possible) <= targetSdkVersion == compileSdkVersion (latest SDK)
If you are facing this issue after changing password in phpmyadmin,
paste the old password (passwd before change) in xampp\phpMyAdmin\config.inc.php
:
$cfg['Servers'][$i]['password'] = '**old password here**';
Hope, it would work :)
I would use JPA's constructor expression feature. See also following answer:
JPQL Constructor Expression - org.hibernate.hql.ast.QuerySyntaxException:Table is not mapped
Following the example in the question, it would be something like this.
SELECT DISTINCT new com.mypackage.MyNameType(c.name) from Customer c
Angular-UI's project includes a ui-validate directive, which will probably help you with this. It let's you specify a function to call to do the validation.
Have a look at the demo page: http://angular-ui.github.com/, search down to the Validate heading.
From the demo page:
<input ng-model="email" ui-validate='{blacklist : notBlackListed}'>
<span ng-show='form.email.$error.blacklist'>This e-mail is black-listed!</span>
then in your controller:
function ValidateCtrl($scope) {
$scope.blackList = ['[email protected]','[email protected]'];
$scope.notBlackListed = function(value) {
return $scope.blackList.indexOf(value) === -1;
};
}
This works too: class = "browser-default"
You can force it (browser permitting, I imagine) by inserting line breaks in the HTML source, like this:
<INPUT value="Line 1
Line 2">
Of course working out where to place the line breaks is not necessarily trivial...
If you can use an HTML <BUTTON>
instead of an <INPUT>
, such that the button label is the element's content rather than its value
attribute, placing that content inside a <SPAN>
with a width
attribute that is a few pixels narrower than that of the button seems to do the trick (even in IE6 :-).
$http.delete
method doesn't accept request body.
You can try this workaround :
$http( angular.merge({}, config || {}, {
method : 'delete',
url : _url,
data : _data
}));
where in config
you can pass config data like headers etc.
Here is an updated answer which works in Access 2010 VBA using Data Access Objects (DAO). The table's name is held in TableDef.Name. The collection of all table definitions is held in TableDefs. Here is a quick example of looping through the table names:
Dim db as Database
Dim td as TableDef
Set db = CurrentDb()
For Each td In db.TableDefs
YourSubTakingTableName(td.Name)
Next td
grep "^-X" file
It will grep and pick all the lines form the file. ^ in the grep"^" indicates a line starting with
Textareas shouldn't wrap by default, but you can set wrap="soft" to explicitly disable wrap:
<textarea name="nowrap" cols="30" rows="3" wrap="soft"></textarea>
EDIT: The "wrap" attribute is not officially supported. I got it from the german SELFHTML page (an english source is here) that says IE 4.0 and Netscape 2.0 support it. I also tested it in FF 3.0.7 where it works as supposed. Things have changed here, SELFHTML is now a wiki and the english source link is dead.
EDIT2: If you want to be sure every browser supports it, you can use CSS to change wrap behaviour:
Using Cascading Style Sheets (CSS), you can achieve the same effect with
white-space: nowrap; overflow: auto;
. Thus, the wrap attribute can be regarded as outdated.
From here (seems to be an excellent page with information about textarea).
EDIT3: I'm not sure when it changed (according to the comments, must've been around 2014), but wrap
is now an official HTML5 attribute, see w3schools. Changed the answer to match this.
To search the commit log (across all branches) for the given text:
git log --all --grep='Build 0051'
To search the actual content of commits through a repo's history, use:
git grep 'Build 0051' $(git rev-list --all)
to show all instances of the given text, the containing file name, and the commit sha1.
Finally, as a last resort in case your commit is dangling and not connected to history at all, you can search the reflog itself with the -g
flag (short for --walk-reflogs
:
git log -g --grep='Build 0051'
EDIT: if you seem to have lost your history, check the reflog
as your safety net. Look for Build 0051 in one of the commits listed by
git reflog
You may have simply set your HEAD
to a part of history in which the 'Build 0051' commit is not visible, or you may have actually blown it away. The git-ready reflog article may be of help.
To recover your commit from the reflog: do a git checkout of the commit you found (and optionally make a new branch or tag of it for reference)
git checkout 77b1f718d19e5cf46e2fab8405a9a0859c9c2889
# alternative, using reflog (see git-ready link provided)
# git checkout HEAD@{10}
git checkout -b build_0051 # make a new branch with the build_0051 as the tip
See gjvdkamp
's answer below; this feature now exists in C#
var @switch = new Dictionary<Type, Action> {
{ typeof(Type1), () => ... },
{ typeof(Type2), () => ... },
{ typeof(Type3), () => ... },
};
@switch[typeof(MyType)]();
It's a little less flexible as you can't fall through cases, continue etc. But I rarely do so anyway.
If you need not equal object condition use cross join sequences:
var query = from obj1 in set1
from obj2 in set2
where obj1.key1 == obj2.key2 && obj1.key3.contains(obj2.key5) [...conditions...]
It's because the tab is a naming container aswell... your update should be update="Search:insTable:display"
What you can do aswell is just place your dialog outside the form and still inside the tab then it would be: update="Search:display"
Unfortunately, the most popular answer did not work for me entirely. I had to add .select_option
to end of the statement
select("option_name_here", from: "organizationSelect").select_option
without the select_option
, no select was being performed
In general, one may sort a dict like so:
for k in sorted(d):
print k, d[k]
For the specific case in the question, having a "drop in replacement" for d.iteritems(), add a function like:
def sortdict(d, **opts):
# **opts so any currently supported sorted() options can be passed
for k in sorted(d, **opts):
yield k, d[k]
and so the ending line changes from
return dict.iteritems()
to
return sortdict(dict)
or
return sortdict(dict, reverse = True)
MySQL will also report "Column count doesn't match value count at row 1" if you try to insert multiple rows without delimiting the row sets in the VALUES section with parentheses, like so:
INSERT INTO `receiving_table`
(id,
first_name,
last_name)
VALUES
(1002,'Charles','Babbage'),
(1003,'George', 'Boole'),
(1001,'Donald','Chamberlin'),
(1004,'Alan','Turing'),
(1005,'My','Widenius');
This should do what you want:
sed 's/two.*/BLAH/'
$ echo " one two three five
> four two five five six
> six one two seven four" | sed 's/two.*/BLAH/'
one BLAH
four BLAH
six one BLAH
The $
is unnecessary because the .*
will finish at the end of the line anyways, and the g
at the end is unnecessary because your first match will be the first two
to the end of the line.
What solves my problem: I am using 64 bit Windows 7, so I thought I could install 64 bit Wamp. After I Installed the 32-bit version the error does not appear. So something in the developing process at Wamp went wrong...
best way is
button.setBackgroundResource(android.R.drawable.ic_delete);
OR this for Drawable left and something like that for right etc.
int imgResource = R.drawable.left_img;
button.setCompoundDrawablesWithIntrinsicBounds(imgResource, 0, 0, 0);
and
getResources().getDrawable()
is now deprecated
The Stack is an area of memory for keeping temporary data. Stack is used by the CALL instruction to keep the return address for procedures The return RET instruction gets this value from the stack and returns to that offset. The same thing happens when an INT instruction calls an interrupt. It stores in the Stack the flag register, code segment and offset. The IRET instruction is used to return from interrupt call.
The Stack is a Last In First Out (LIFO) memory. Data is placed onto the Stack with a PUSH instruction and removed with a POP instruction. The Stack memory is maintained by two registers: the Stack Pointer (SP) and the Stack Segment (SS) register. When a word of data is PUSHED onto the stack the the High order 8-bit Byte is placed in location SP-1 and the Low 8-bit Byte is placed in location SP-2. The SP is then decremented by 2. The SP addds to the (SS x 10H) register, to form the physical stack memory address. The reverse sequence occurs when data is POPPED from the Stack. When a word of data is POPPED from the stack the the High order 8-bit Byte is obtained in location SP-1 and the Low 8-bit Byte is obtained in location SP-2. The SP is then incremented by 2.
You can try
Session::put('variable_Name', "Your Data Save Successfully !");
Session::get('variable_Name');
If you allow me, it works fine also for multi-attachments, the 1st above answer of NINCOMPOOP, with just a little modification like follows:
DataSource source,source2,source3,source4, ...;
source = new FileDataSource(myfile);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(myfile);
multipart.addBodyPart(messageBodyPart);
source2 = new FileDataSource(myfile2);
messageBodyPart.setDataHandler(new DataHandler(source2));
messageBodyPart.setFileName(myfile2);
multipart.addBodyPart(messageBodyPart);
source3 = new FileDataSource(myfile3);
messageBodyPart.setDataHandler(new DataHandler(source3));
messageBodyPart.setFileName(myfile3);
multipart.addBodyPart(messageBodyPart);
source4 = new FileDataSource(myfile4);
messageBodyPart.setDataHandler(new DataHandler(source4));
messageBodyPart.setFileName(myfile4);
multipart.addBodyPart(messageBodyPart);
...
message.setContent(multipart);
You would use the os module system method.
You just put in the string form of the command, the return value is the windows enrivonment variable COMSPEC
For example:
os.system('python') opens up the windows command prompt and runs the python interpreter
could you try doing JSON.stringify(obj);
Like this
var stringify = JSON.stringify(obj);
fs.writeFileSync('./data.json', stringify , 'utf-8');
The following link demonstrates how to render seveveral Standard Android view objects with an animated checkbox on the right by setting the right drawable.
Set the background to get a ripple effect.
[link to website with example checkbox on right and left side.][1] http://landenlabs.com/android/uicomponents/uicomponents.html#checkbox
<Button
android:id="@+id/p2Button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/transparent_ripple"
android:drawableRight="@drawable/checkline"
android:gravity="left|center_vertical"
android:text="Button"
android:textAllCaps="false"
android:textColor="@android:color/white"
android:textSize="@dimen/buttonTextSize" />
<android.support.v7.widget.AppCompatButton
android:id="@+id/p2Button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/transparent_ripple"
android:drawableRight="@drawable/checkline"
android:gravity="left|center_vertical"
android:text="AppCompatButton"
android:textAllCaps="false"
android:textColor="@android:color/white"
android:textSize="@dimen/buttonTextSize" />
<TextView
android:id="@+id/p2TextView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/transparent_ripple"
android:drawableRight="@drawable/checkline"
android:gravity="left|center_vertical"
android:hapticFeedbackEnabled="true"
android:text="TextView"
android:textColor="@android:color/white"
android:textSize="@dimen/buttonTextSize" />
<android.support.v7.widget.AppCompatTextView
android:id="@+id/p2TextView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/transparent_ripple"
android:drawableRight="@drawable/checkline"
android:gravity="left|center_vertical"
android:hapticFeedbackEnabled="true"
android:text="AppCompatTextView"
android:textColor="@android:color/white"
android:textSize="@dimen/buttonTextSize" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@android:color/white" />
<CheckBox
android:id="@+id/p2Checkbox1"
android:layout_width="match_parent"
android:layout_height="@dimen/buttonHeight"
android:background="@drawable/transparent_ripple"
android:button="@null"
android:checked="true"
android:drawableRight="@drawable/checkline"
android:gravity="left|center_vertical"
android:text="CheckBox"
android:textColor="@android:color/white"
android:textSize="@dimen/buttonTextSize" />
<android.support.v7.widget.AppCompatCheckBox
android:id="@+id/p2Checkbox2"
android:layout_width="match_parent"
android:layout_height="@dimen/buttonHeight"
android:background="@drawable/transparent_ripple"
android:button="@null"
android:checked="true"
android:drawableRight="@drawable/checkline"
android:gravity="left|center_vertical"
android:text="AppCompatCheckBox"
android:textColor="@android:color/white"
android:textSize="@dimen/buttonTextSize" />
<android.support.v7.widget.AppCompatCheckedTextView
android:id="@+id/p2Checkbox3"
android:layout_width="match_parent"
android:layout_height="@dimen/buttonHeight"
android:background="@drawable/transparent_ripple"
android:checkMark="@drawable/checkline"
android:checked="true"
android:gravity="left|center_vertical"
android:text="AppCompatCheckedTextView"
android:textColor="@android:color/white"
android:textSize="@dimen/buttonTextSize" />
<!-- android:checkMark="?android:attr/listChoiceIndicatorMultiple" -->
<CheckedTextView
android:id="@+id/p2Checkbox4"
android:layout_width="match_parent"
android:layout_height="@dimen/buttonHeight"
android:background="@drawable/transparent_ripple"
android:checkMark="@drawable/checkline"
android:checked="true"
android:gravity="left|center_vertical"
android:text="CheckedTextView"
android:textColor="@android:color/white"
android:textSize="@dimen/buttonTextSize" />
<CheckBox
android:id="@+id/p2Checkbox5"
android:layout_width="match_parent"
android:layout_height="@dimen/buttonHeight"
android:background="@drawable/transparent_ripple"
android:checked="true"
android:gravity="center_vertical|end"
android:text="CheckBox"
android:textColor="@android:color/white"
android:textSize="@dimen/buttonTextSize" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@android:color/white" />
<ToggleButton
android:id="@+id/p2ToggleButton1"
android:layout_width="match_parent"
android:layout_height="@dimen/buttonHeight"
android:background="@drawable/transparent_ripple"
android:checked="true"
android:drawableRight="@drawable/checkline"
android:gravity="center_vertical|left"
android:textAllCaps="false"
android:textColor="@android:color/white"
android:textOff="ToggleButtonOff"
android:textOn="ToggleButtonOn"
android:textSize="@dimen/buttonTextSize" />
<ToggleButton
android:id="@+id/p2ToggleButton2"
android:layout_width="match_parent"
android:layout_height="@dimen/buttonHeight"
android:background="@drawable/transparent_ripple"
android:checked="true"
android:drawableRight="@drawable/btn_check_material_anim"
android:gravity="center_vertical|left"
android:textAllCaps="false"
android:textColor="@android:color/white"
android:textOff="ToggleBtnnAnimOff"
android:textOn="ToggleBtnnAnimOn"
android:textSize="@dimen/buttonTextSize" />
Sample checkline.xml (in drawable, see link for animated version in drawable-v21)
Sample transparent_ripple.xml (in drawable-v21)
<!-- Limit ripple to view object, can also use shape such as oval -->
<item android:id="@android:id/mask" android:drawable="@android:color/white" />
<item>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
android:enterFadeDuration="200"
android:exitFadeDuration="200">
<item android:state_pressed="true">
<shape android:shape="rectangle">
<solid android:color="#80c0c000" />
</shape>
</item>
</selector>
</item>
Sample transparent_ripple.xml (in drawable, highlight only no ripple available
<item android:state_pressed="true">
<shape android:shape="rectangle">
<solid android:color="#80c0c000" />
</shape>
</item>
<item>
<shape android:shape="rectangle">
<solid android:color="@android:color/transparent" />
</shape>
</item>
I could be wrong, but I'm pretty sure that the "interrupt kernel" button just sends a SIGINT signal to the code that you're currently running (this idea is supported by Fernando's comment here), which is the same thing that hitting CTRL+C would do. Some processes within python handle SIGINTs more abruptly than others.
If you desperately need to stop something that is running in iPython Notebook and you started iPython Notebook from a terminal, you can hit CTRL+C twice in that terminal to interrupt the entire iPython Notebook server. This will stop iPython Notebook alltogether, which means it won't be possible to restart or save your work, so this is obviously not a great solution (you need to hit CTRL+C twice because it's a safety feature so that people don't do it by accident). In case of emergency, however, it generally kills the process more quickly than the "interrupt kernel" button.
In my case, the problem turned out to be that the keyfile was behind a 301 Moved Permanently redirect, which the curl command failed to follow. I fixed it by using wget
instead:
wget URL
sudo apt-key add FILENAME
...where FILENAME is the file name that wget
outputs after it downloads the file.
Update: Alternatively, you can use curl -L
to make curl follow redirects.
The following works:
(
echo "From: ${from}";
echo "To: ${to}";
echo "Subject: ${subject}";
echo "Content-Type: text/html";
echo "MIME-Version: 1.0";
echo "";
echo "${message}";
) | sendmail -t
For troubleshooting msmtp, which is compatible with sendmail
, see: