Had such a problem when executing forking in php for command line. In my case from time to time the php killed the child process. To fix this, just wait for the process to complete using the command pcntl_wait($status);
here's a piece of code for a visual example:
#!/bin/php -n
<?php
error_reporting(E_ALL & ~E_NOTICE);
ini_set("log_errors", 1);
ini_set('error_log', '/media/logs/php/fork.log');
$ski = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 5)), 0, 5);
error_log(getmypid().' '.$ski.' start my php');
$pid = pcntl_fork();
if($pid) {
error_log(getmypid().' '.$ski.' start 2');
// Wait for children to return. Otherwise they
// would turn into "Zombie" processes
// !!!!!! add this !!!!!!
pcntl_wait($status);
// !!!!!! add this !!!!!!
} else {
error_log(getmypid().' '.$ski.' start 3');
//[03-Apr-2020 12:13:47 UTC] PHP Warning: Error while sending QUERY packet. PID=18048 in /speed/sport/fortest.php on line 22457
mysqli_query($con,$query,MYSQLI_ASYNC);
error_log(getmypid().' '.$ski.' sleep child');
sleep(15);
exit;
}
error_log(getmypid().' '.$ski.'end my php');
exit(0);
?>
This Error comes due to same table exist in 2 database like you have a database for project1 and in which you have table emp and again you have another database like project2 and in which you have table emp then when you try to insert something inside the database with-out your database name then you will get an error like about
Solution for that when you use mysql query then also mention database name along with table name.
OR
Don't Use Reserved key words like KEY as column name
I've found the liquibase.database.typeconversion.core.AbstractTypeConverter
class.
It lists all types that can be used:
protected DataType getDataType(String columnTypeString, Boolean autoIncrement, String dataTypeName, String precision, String additionalInformation) {
// Translate type to database-specific type, if possible
DataType returnTypeName = null;
if (dataTypeName.equalsIgnoreCase("BIGINT")) {
returnTypeName = getBigIntType();
} else if (dataTypeName.equalsIgnoreCase("NUMBER") || dataTypeName.equalsIgnoreCase("NUMERIC")) {
returnTypeName = getNumberType();
} else if (dataTypeName.equalsIgnoreCase("BLOB")) {
returnTypeName = getBlobType();
} else if (dataTypeName.equalsIgnoreCase("BOOLEAN")) {
returnTypeName = getBooleanType();
} else if (dataTypeName.equalsIgnoreCase("CHAR")) {
returnTypeName = getCharType();
} else if (dataTypeName.equalsIgnoreCase("CLOB")) {
returnTypeName = getClobType();
} else if (dataTypeName.equalsIgnoreCase("CURRENCY")) {
returnTypeName = getCurrencyType();
} else if (dataTypeName.equalsIgnoreCase("DATE") || dataTypeName.equalsIgnoreCase(getDateType().getDataTypeName())) {
returnTypeName = getDateType();
} else if (dataTypeName.equalsIgnoreCase("DATETIME") || dataTypeName.equalsIgnoreCase(getDateTimeType().getDataTypeName())) {
returnTypeName = getDateTimeType();
} else if (dataTypeName.equalsIgnoreCase("DOUBLE")) {
returnTypeName = getDoubleType();
} else if (dataTypeName.equalsIgnoreCase("FLOAT")) {
returnTypeName = getFloatType();
} else if (dataTypeName.equalsIgnoreCase("INT")) {
returnTypeName = getIntType();
} else if (dataTypeName.equalsIgnoreCase("INTEGER")) {
returnTypeName = getIntType();
} else if (dataTypeName.equalsIgnoreCase("LONGBLOB")) {
returnTypeName = getLongBlobType();
} else if (dataTypeName.equalsIgnoreCase("LONGVARBINARY")) {
returnTypeName = getBlobType();
} else if (dataTypeName.equalsIgnoreCase("LONGVARCHAR")) {
returnTypeName = getClobType();
} else if (dataTypeName.equalsIgnoreCase("SMALLINT")) {
returnTypeName = getSmallIntType();
} else if (dataTypeName.equalsIgnoreCase("TEXT")) {
returnTypeName = getClobType();
} else if (dataTypeName.equalsIgnoreCase("TIME") || dataTypeName.equalsIgnoreCase(getTimeType().getDataTypeName())) {
returnTypeName = getTimeType();
} else if (dataTypeName.toUpperCase().contains("TIMESTAMP")) {
returnTypeName = getDateTimeType();
} else if (dataTypeName.equalsIgnoreCase("TINYINT")) {
returnTypeName = getTinyIntType();
} else if (dataTypeName.equalsIgnoreCase("UUID")) {
returnTypeName = getUUIDType();
} else if (dataTypeName.equalsIgnoreCase("VARCHAR")) {
returnTypeName = getVarcharType();
} else if (dataTypeName.equalsIgnoreCase("NVARCHAR")) {
returnTypeName = getNVarcharType();
} else {
return new CustomType(columnTypeString,0,2);
}
You were missing the small icon. I did the same mistake and the above step resolved it.
As per the official documentation: A Notification object must contain the following:
A small icon, set by setSmallIcon()
A title, set by setContentTitle()
Detail text, set by setContentText()
On Android 8.0 (API level 26) and higher, a valid notification channel ID, set by setChannelId() or provided in the NotificationCompat.Builder constructor when creating a channel.
See http://developer.android.com/guide/topics/ui/notifiers/notifications.html
In case someone is using Laravel and is getting this problem. I was getting this as well and the issue was in the order in which I was inserting the ids (i.e., the foreign keys) in the pivot table.
To be concrete, find below an example for a many to many relationship:
wordtokens <-> wordtoken_wordchunk <-> wordchunks
// wordtoken_wordchunk table
Schema::create('wordtoken_wordchunk', function(Blueprint $table) {
$table->integer('wordtoken_id')->unsigned();
$table->integer('wordchunk_id')->unsigned();
$table->foreign('wordtoken_id')->references('id')->on('word_tokens')->onDelete('cascade');
$table->foreign('wordchunk_id')->references('id')->on('wordchunks')->onDelete('cascade');
$table->primary(['wordtoken_id', 'wordchunk_id']);
});
// wordchunks table
Schema::create('wordchunks', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('text');
});
// wordtokens table
Schema::create('word_tokens', function (Blueprint $table) {
$table->increments('id');
$table->string('text');
});
Now my models look like follows:
class WordToken extends Model
{
public function wordchunks() {
return $this->belongsToMany('App\Wordchunk');
}
}
class Wordchunk extends Model
{
public function wordTokens() {
return $this->belongsToMany('App\WordToken', 'wordtoken_wordchunk', 'wordchunk_id', 'wordtoken_id');
}
}
I fixed the problem by exchanging the order of 'wordchunk_id' and 'wordtoken_id' in the Wordchunk model.
For code completion, this is how I persist the models:
private function persistChunks($chunks) {
foreach ($chunks as $chunk) {
$model = new Wordchunk();
$model->text = implode(' ', array_map(function($token) {return $token->text;}, $chunk));
$tokenIds = array_map(function($token) {return $token->id;}, $chunk);
$model->save();
$model->wordTokens()->attach($tokenIds);
}
}
This is nice but doesn't answer the question:
"A VARCHAR should always be used instead of TINYTEXT." Tinytext is useful if you have wide rows - since the data is stored off the record. There is a performance overhead, but it does have a use.
Try this:
str.replace("\"", "\\\""); // (Escape backslashes and embedded double-quotes)
Or, use single-quotes to quote your search and replace strings:
str.replace('"', '\\"'); // (Still need to escape the backslash)
As pointed out by helmus, if the first parameter passed to .replace()
is a string it will only replace the first occurrence. To replace globally, you have to pass a regex with the g
(global) flag:
str.replace(/"/g, "\\\"");
// or
str.replace(/"/g, '\\"');
But why are you even doing this in JavaScript? It's OK to use these escape characters if you have a string literal like:
var str = "Dude, he totally said that \"You Rock!\"";
But this is necessary only in a string literal. That is, if your JavaScript variable is set to a value that a user typed in a form field you don't need to this escaping.
Regarding your question about storing such a string in an SQL database, again you only need to escape the characters if you're embedding a string literal in your SQL statement - and remember that the escape characters that apply in SQL aren't (usually) the same as for JavaScript. You'd do any SQL-related escaping server-side.
You can use .scroll()
to easily scroll elements or window. It has a built-in smooth scroll effect so basically the code couldn't be simpler.
Standard properties:
var options = {
top: 0, // Number of pixels along the Y axis to scroll the window or element
left: 0, // Number of pixels along the X axis to scroll the window or element.
behavior: 'smooth' // ('smooth'|'auto') - animate smoothly, or move in a single jump
}
DOCS: https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll
SEE ALSO: .scrollIntoView()
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
document.getElementById('btn').addEventListener('click',function(){
document.getElementById('container').scroll({top:0,behavior:'smooth'});
});
_x000D_
/*DEMO*/
#container{
width:300px;
max-height:300px;
padding:1rem;
margin-left:auto;
margin-right:auto;
background-color:#222;
color:#ccc;
text-align:justify;
overflow-y:auto;
}
#btn{
width:100%;
margin-top:1rem;
}
_x000D_
<div id="container">
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
<button id="btn">Scroll to top</button>
</div>
_x000D_
The PHP.net recommended way of setting the charset is now this:
Flex layout modes are not (fully) natively supported in IE yet. IE10 implements the "tween" version of the spec which is not fully recent, but still works.
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes
This CSS-Tricks article has some advice on cross-browser use of flexbox (including IE): http://css-tricks.com/using-flexbox/
edit: after a bit more research, IE10 flexbox layout mode implemented current to the March 2012 W3C draft spec: http://www.w3.org/TR/2012/WD-css3-flexbox-20120322/
The most current draft is a year or so more recent: http://dev.w3.org/csswg/css-flexbox/
An old question but deserves an update as now there is a way.
The correct CSS based answer is to use object-fit: cover
, which works like background-size: cover
. Positioning would be taken care of by object-position
attribute, which defaults to centering.
But there is no support for it in any IE / Edge browsers, or Android < 4.4.4. Also, object-position
is not supported by Safari, iOS or OSX. Polyfills do exist, object-fit-images seems to give best support.
For more details on how the property works, see CSS Tricks article on object-fit
for explanation and demo.
You're not actually returning anything from your run_cmd function.
function run_cmd(cmd, args, done) {
var spawn = require("child_process").spawn;
var child = spawn(cmd, args);
var result = { stdout: "" };
child.stdout.on("data", function (data) {
result.stdout += data;
});
child.stdout.on("end", function () {
done();
});
return result;
}
> foo = run_cmd("ls", ["-al"], function () { console.log("done!"); });
{ stdout: '' }
done!
> foo.stdout
'total 28520...'
Works just fine. :)
In case anyone needed the above in swift :
SWIFT 3.0 and above :
this will capitalize your string, make the first letter capital :
viewNoteDateMonth.text = yourString.capitalized
this will uppercase your string, make all the string upper case :
viewNoteDateMonth.text = yourString.uppercased()
You cannot auto increment the char
values. It should be int
or long
(integers or floating points).
Try with this,
CREATE TABLE discussion_topics (
topic_id int(5) NOT NULL AUTO_INCREMENT,
project_id char(36) NOT NULL,
topic_subject VARCHAR(255) NOT NULL,
topic_content TEXT default NULL,
date_created DATETIME NOT NULL,
date_last_post DATETIME NOT NULL,
created_by_user_id char(36) NOT NULL,
last_post_user_id char(36) NOT NULL,
posts_count char(36) default NULL,
PRIMARY KEY (`topic_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
Hope this helps
The server sends the following in its response header to set a cookie field.
Set-Cookie:
name=
value
If there is a cookie set, then the browser sends the following in its request header.
Cookie:
name=
value
See the HTTP Cookie article at Wikipedia for more information.
As Sayse mentioned, exit code 259 (0x103)
has special meaning, in this case the process being debugged is still running.
I saw this a lot with debugging web services, because the thread continues to run after executing each web service call (as it is still listening for further calls).
The worse thing is not having a decent stack trace which you simply cannot generate using an HttpInterceptor
(hope to stand corrected). All you get is a load of zone and rxjs useless bloat, and not the line or class that generated the error.
To do this you will need to generate a stack in an extended HttpClient
, so its not advisable to do this in a production environment.
/**
* Extended HttpClient that generates a stack trace on error when not in a production build.
*/
@Injectable()
export class TraceHttpClient extends HttpClient {
constructor(handler: HttpHandler) {
super(handler);
}
request(...args: [any]): Observable<any> {
const stack = environment.production ? null : Error().stack;
return super.request(...args).pipe(
catchError((err) => {
// tslint:disable-next-line:no-console
if (stack) console.error('HTTP Client error stack\n', stack);
return throwError(err);
})
);
}
}
If you're using jQuery then there are a few different ways to set the disabled attribute.
var $element = $(...);
$element.prop('disabled', true);
$element.attr('disabled', true);
// The following do not require jQuery
$element.get(0).disabled = true;
$element.get(0).setAttribute('disabled', true);
$element[0].disabled = true;
$element[0].setAttribute('disabled', true);
In bash:
$ convert -version
or
$ /usr/local/bin/convert -version
No need to write any PHP file just to check.
I believe there are two answers. One using 'pure' Javascript with IIFE function to hide its auxiliary construction functions. And the other using a NodeJS module to also hide its auxiliary construction functions.
I will show only the example with a NodeJS module.
Class Vector2d.js:
/*
Implement a class of type Vetor2d with three types of constructors.
*/
// If a constructor function is successfully executed,
// must have its value changed to 'true'.let global_wasExecuted = false;
global_wasExecuted = false;
//Tests whether number_value is a numeric type
function isNumber(number_value) {
let hasError = !(typeof number_value === 'number') || !isFinite(number_value);
if (hasError === false){
hasError = isNaN(number_value);
}
return !hasError;
}
// Object with 'x' and 'y' properties associated with its values.
function vector(x,y){
return {'x': x, 'y': y};
}
//constructor in case x and y are 'undefined'
function new_vector_zero(x, y){
if (x === undefined && y === undefined){
global_wasExecuted = true;
return new vector(0,0);
}
}
//constructor in case x and y are numbers
function new_vector_numbers(x, y){
let x_isNumber = isNumber(x);
let y_isNumber = isNumber(y);
if (x_isNumber && y_isNumber){
global_wasExecuted = true;
return new vector(x,y);
}
}
//constructor in case x is an object and y is any
//thing (he is ignored!)
function new_vector_object(x, y){
let x_ehObject = typeof x === 'object';
//ignore y type
if (x_ehObject){
//assigns the object only for clarity of code
let x_object = x;
//tests whether x_object has the properties 'x' and 'y'
if ('x' in x_object && 'y' in x_object){
global_wasExecuted = true;
/*
we only know that x_object has the properties 'x' and 'y',
now we will test if the property values ??are valid,
calling the class constructor again.
*/
return new Vector2d(x_object.x, x_object.y);
}
}
}
//Function that returns an array of constructor functions
function constructors(){
let c = [];
c.push(new_vector_zero);
c.push(new_vector_numbers);
c.push(new_vector_object);
/*
Your imagination is the limit!
Create as many construction functions as you want.
*/
return c;
}
class Vector2d {
constructor(x, y){
//returns an array of constructor functions
let my_constructors = constructors();
global_wasExecuted = false;
//variable for the return of the 'vector' function
let new_vector;
//traverses the array executing its corresponding constructor function
for (let index = 0; index < my_constructors.length; index++) {
//execute a function added by the 'constructors' function
new_vector = my_constructors[index](x,y);
if (global_wasExecuted) {
this.x = new_vector.x;
this.y = new_vector.y;
break;
};
};
}
toString(){
return `(x: ${this.x}, y: ${this.y})`;
}
}
//Only the 'Vector2d' class will be visible externally
module.exports = Vector2d;
The useVector2d.js file uses the Vector2d.js module:
const Vector = require('./Vector2d');
let v1 = new Vector({x: 2, y: 3});
console.log(`v1 = ${v1.toString()}`);
let v2 = new Vector(1, 5.2);
console.log(`v2 = ${v2.toString()}`);
let v3 = new Vector();
console.log(`v3 = ${v3.toString()}`);
Terminal output:
v1 = (x: 2, y: 3)
v2 = (x: 1, y: 5.2)
v3 = (x: 0, y: 0)
With this we avoid dirty code (many if's and switch's spread throughout the code), difficult to maintain and test. Each building function knows which conditions to test. Increasing and / or decreasing your building functions is now simple.
Why can't you initialize when you declare?
Which C compiler are you using? Does it support C99?
If it does support C99, you can declare the variable where you need it and initialize it when you declare it.
The only excuse I can think of for not doing that would be because you need to declare it but do an early exit before using it, so the initializer would be wasted. However, I suspect that any such code is not as cleanly organized as it should be and could be written so it was not a problem.
** Finally!!! Resolved App transport Security **
1. Follow the follow the screen shot. Do it in Targets info Section.
Find the playlist/manifest with the developer tools network tab. There is always one, as that's how it works. It might have a m3u8 extension that you can type into the Filter. (The youtube-dl tool can also find the m3u8 tool automatically some time give it direct link to the webpage where the video is being displayed.)
Give it to the youtube-dl tool (Download) . It can download much more than just YouTube. It'll auto-download each segment then combine everything with FFmpeg then discard the parts. There is a good chance it supports the site you want to download from natively, and you don't even need to do step #1.
If you find a site that is stubborn and you run into 403 errors... Telerik Fiddler to the rescue. It can catch and save anything transmitted (such as the video file) as it acts as a local proxy. Everything you see/hear can be downloaded, unless it's DRM content like Spotify.
Note: in windows, you can use youtube-dl.exe using "Command Prompt" or creating a batch file. i.e
d:\youtube-dl.exe https://www.youtube.com/watch?v=gbdFOwKHil0
Thanks
Any solution which relies on testing before creation can run into a 'race' condition where another process creates the table between you testing that it does not exists and creating it. - Minor point I know.
The exec
family of functions make your process execute a different program, replacing the old program it was running. I.e., if you call
execl("/bin/ls", "ls", NULL);
then the ls
program is executed with the process id, current working dir and user/group (access rights) of the process that called execl
. Afterwards, the original program is not running anymore.
To start a new process, the fork
system call is used. To execute a program without replacing the original, you need to fork
, then exec
.
I had the same issue on a linux machine. I was quite frustrated at first, because I have installed both the JDK and JRE. I am using version 1.6, 1.7 and 1.8 simultaneously, and I have played a lot with the alternatives to have everything set properly.
The problem was quite stupid to solve, yet counter-intuitive. While I was using the correct JDK, I paid attention to the path of the tools jar maven complained about - it was expecting it to be
$JAVA_HOME\..\lib\tools.jar
The $JAVA_HOME
variable pointed directly to my jdk
folder (/usr/local/java
which was also the correct $PATH
entry and alternative sym link). It actually searches for the lib
folder outside the java directory, because:
$JAVA_HOME\..\lib\tools.jar
will resolve to
/usr/local/lib/tools.jar
and that is not a valid location.
To solve this, the $JAVA_HOME
variable should instead point to this location /usr/local/java/jre
(assuming the JDK path is /usr/local/java
) -- there is actually jre
folder inside the JDK installation directory, that comes with each JDK. This new setup will cause maven to look at the JRE directory, that is part of the JDK:
$JAVA_HOME\..\lib\tools
which now resolves to
/usr/local/java/jre/../lib/tools.jar
and finally to
/usr/local/java/lib/tools.jar
which is where the tools.jar
really resides.
So, even of you are indeed using the JDK instead of the JRE, the $JAVA_HOME has to point to the JRE. Remember, the OS alternative should still refer to the JDK.
The problem is that count is intended to count the indexes in an array, not the properties on an object, (unless it's a custom object that implements the Countable interface). Try casting the object, like below, as an array and seeing if that helps.
$total = count((array)$obj);
Simply casting an object as an array won't always work but being a simple stdClass object it should get the job done here.
you have to do like this in your project level gradle file
allprojects {
repositories {
jcenter()
maven { url "http://dl.appnext.com/" }
maven { url "https://maven.google.com" }
}
}
The hyphen is usually a normal character in regular expressions. Only if it’s in a character class and between two other characters does it take a special meaning.
Thus:
[-]
matches a hyphen.[abc-]
matches a
, b
, c
or a hyphen.[-abc]
matches a
, b
, c
or a hyphen.[ab-d]
matches a
, b
, c
or d
(only here the hyphen denotes a character range).Try the following:
<c:set var="count" value="0" scope="page" />
//in your loops
<c:set var="count" value="${count + 1}" scope="page"/>
You need to export the User.name
field so that the json
package can see it. Rename the name
field to Name
.
package main
import (
"fmt"
"encoding/json"
)
type User struct {
Name string
}
func main() {
user := &User{Name: "Frank"}
b, err := json.Marshal(user)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(b))
}
Output:
{"Name":"Frank"}
ok this is an old thread -
but I spent nearly two days and did not get anywhere
Here is what solved my problem
I had USB debugging enabled ( finding developer options itself was a pain - I think the 7 times tap from google is childish and just plain stupid - rant over )
However HTC syn manager , eclipse ADT and windows computer management were all unable to identify my device
My problem was my phone was set to ONLY USB Charge - this was the problem In 'USB Computer connection' >> Choose the option USB Storage Once you do this - PC will install drivers and your device will get detected by Eclipse as well as in 'Computer Management' under ''Android USB devices '
Now I still dont know a way to access ''USB Computer connection' but at that time I did get the option to change and t worked
For those ( like me earlier ) who dont know how to identify if 'Computer Management' shows their device look for 'Android USB devices ' If its present - then your device is being detected by your PC
Hope this helps some others
shankar
string jsonFilePath = @"C:\MyFolder\myFile.json";
string json = File.ReadAllText(jsonFilePath);
Dictionary<string, object> json_Dictionary = (new JavaScriptSerializer()).Deserialize<Dictionary<string, object>>(json);
foreach (var item in json_Dictionary)
{
// parse here
}
You can use a shortcut. Create a .bashrc file in your home directory. In there, you can add the following:
alias sshb="ssh buck@host"
To make the alias available in your terminal, you can either close and open your terminal, or run
source ~/.bashrc
Then you can connect by just typing in:
sshb
I figure you fixed your problem, but I don't see the solution here that helped me, so here it is.
Type in terminal:
echo "" > ~/.ssh/known_hosts
That will empty your known_hosts
file, and you'll have to add every host you used and have connected to, but it solved the problem.
I've always thought that Encryption can be converted both ways, in a way that the end value can bring you to original value and with Hashing you'll not be able to revert from the end result to the original value.
Quickest and cleanest way to change your package name :
Warning : You may want to save some files in android/ and ios/ folder before it gets deleted !
android/
ios/
build/
Let's say you want to rename from com.oldcompany.oldproject
to com.newcompany.newproject
Launch the following code :
flutter create --org com.newcompany --project-name newproject .
PS : To make sure everything is set up correctly, you can search for your package names in your files, by typing the commands grep --color -r com.oldcompany.oldproject *
and grep --color -r com.newcompany.newproject *
This works for SQL Server 2005 - 2012. Look for event id = 26022 in the error log under applications. That will show the port number of sql server as well as what ip addresses are allowed to access.
You can use the CSS3 Linear Gradient property along with your background-image like this:
#landing-wrapper {
display:table;
width:100%;
background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
background-position:center top;
height:350px;
}
Here's a demo:
#landing-wrapper {_x000D_
display: table;_x000D_
width: 100%;_x000D_
background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
background-position: center top;_x000D_
height: 350px;_x000D_
color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
You can use
<li ng-repeat="(name, age) in items">{{name}}: {{age}}</li>
See ngRepeat documentation. Example: http://jsfiddle.net/WRtqV/1/
Watch out for the parentheses. As has been pointed out above, in Python 3, assert
is still a statement, so by analogy with print(..)
, one may extrapolate the same to assert(..)
or raise(..)
but you shouldn't.
This is important because:
assert(2 + 2 == 5, "Houston we've got a problem")
won't work, unlike
assert 2 + 2 == 5, "Houston we've got a problem"
The reason the first one will not work is that bool( (False, "Houston we've got a problem") )
evaluates to True
.
In the statement assert(False)
, these are just redundant parentheses around False
, which evaluate to their contents. But with assert(False,)
the parentheses are now a tuple, and a non-empty tuple evaluates to True
in a boolean context.
In Postman latest version(7++) may be there is no Bearer field in Authorization So go to Header tab
select key as Authorization and in value write JWT
I got this error when loading '|' separated CSV file although there were no '"' characters in my input file. It turned out that I forgot to specify FORMAT:
COPY ... FROM ... WITH (FORMAT CSV, DELIMITER '|').
Edit
A better way to do this is:
Create your own less file as a main less file ( like bootstrap.less ).
Import all bootstrap less files you need. (in this case, you just need to Import all responsive less files but responsive-1200px-min.less
)
If you need to modify anything in original bootstrap less file, you just need to write your own less to overwrite bootstrap's less code. (Just remember to put your less code/file after @import { /* bootstrap's less file */ };
).
Original
I have the same problem. This is how I fixed it.
Find the media query:
@media (max-width:1200px) ...
Remove it. (I mean the whole thing , not just @media (max-width:1200px)
)
Since the default width of Bootstrap is 940px, you don't need to do anything.
If you want to have your own max-width
, just modify the css rule in the media query that matches your desired width.
wininet.dll
returns both standard and non-standard status codes that are listed below.
401 - Unauthorized file
403 - Forbidden file
404 - File Not Found
500 - some inclusion or functions may missed
200 - Completed
12002 - Server timeout
12029,12030, 12031 - dropped connections (either web server or DB server)
12152 - Connection closed by server.
13030 - StatusText properties are unavailable, and a query attempt throws an exception
For the status code "zero" are you trying to do a request on a local webpage running on a webserver or without a webserver?
XMLHttpRequest status = 0 and XMLHttpRequest statusText = unknown can help you if you are not running your script on a webserver.
With Jenkins 1.494, I was able to send a file to a job parameter on Ubuntu Linux 12.10 using curl
with --form
parameters:
curl --form name=myfileparam --form file=@/local/path/to/your/file.xml \
-Fjson='{"parameter": {"name": "myfileparam", "file": "file"}}' \
-Fsubmit=Build \
http://user:password@jenkinsserver/job/jobname/build
On the Jenkins server, I configured a job that accepts a single parameter: a file upload parameter named myfileparam
.
The first line of that curl call constructs a web form with a parameter named myfileparam
(same as in the job); its value will be the contents of a file on the local file system named /local/path/to/your/file.txt
. The @
symbol prefix tells curl to send a local file instead of the given filename.
The second line defines a JSON request that matches the form parameters on line one: a file parameter named myfileparam
.
The third line activates the form's Build button. The forth line is the job URL with the "/build" suffix.
If this call is successful, curl returns 0
. If it is unsuccessful, the error or exception from the service is printed to the console. This answer takes a lot from an old blog post relating to Hudson, which I deconstructed and re-worked for my own needs.
The python libs are obsolete with this function. I've done one that works correctly:
import os
import shutil
def copydirectorykut(src, dst):
os.chdir(dst)
list=os.listdir(src)
nom= src+'.txt'
fitx= open(nom, 'w')
for item in list:
fitx.write("%s\n" % item)
fitx.close()
f = open(nom,'r')
for line in f.readlines():
if "." in line:
shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
else:
if not os.path.exists(dst+'/'+line[:-1]):
os.makedirs(dst+'/'+line[:-1])
copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
f.close()
os.remove(nom)
os.chdir('..')
TL;DR Use Cmd/Ctrl+Shift+P
then Package Control: Install Package
, then Print to HTML
and install it. Use Alt+Shift+P
to print.
My favorite tool for printing from Sublime Text is Print to HTML package. You can "print" a selection or a whole file - via the web browser.
This opens your browser print dialog (Chrome for me) with the selected text neatly in the print dialog window and syntax highlighting intact. There you can choose a printer or export to PDF, and print.
Install the "Print to HTML" package using the package manager.
Ctrl + Shift + P
=> Gives a list of commands.install
"Package Control: Install Package
"print to
"Print to HTML
". Select that, and it is being installed.Alt+Shift+P
background-attachment: fixed;
http://www.w3.org/TR/CSS21/colors.html#background-properties
Just use x["error_msg"]
. If the property doesn't exist, it returns null
.
It seems that your
$(".modal").on('shown.bs.modal') // One way Or
You can do this in a slight different way, like this
$('.btn').click(function(){
// Send the src on click of button to the iframe. Which will make it load.
$(".openifrmahere").find('iframe').attr("src","http://www.hf-dev.info");
$('.modal').modal({show:true});
// Hide the loading message
$(".openifrmahere").find('iframe').load(function() {
$('.loading').hide();
});
})
Check if you did compress the driver or folder in where you put the .mdf file.
If so, plesae goto the driver or folder, change the compress option by
Properties -> Advanced and unticked the “Compress contents to save disk space” checkbox.
After above things, you should be able to start the service again.
The first thing you should do with date variables is confirm that R reads it as a Date. To do this, for the variable (i.e. vector/column) called Date, in the data frame called EPL2011_12, input
class(EPL2011_12$Date)
The output should read [1] "Date". If it doesn't, you should format it as a date by inputting
EPL2011_12$Date <- as.Date(EPL2011_12$Date, "%d-%m-%y")
Note that the hyphens in the date format ("%d-%m-%y") above can also be slashes ("%d/%m/%y"). Confirm that R sees it as a Date. If it doesn't, try a different formatting command
EPL2011_12$Date <- format(EPL2011_12$Date, format="%d/%m/%y")
Once you have it in Date format, you can use the subset
command, or you can use brackets
WhateverYouWant <- EPL2011_12[EPL2011_12$Date > as.Date("2014-12-15"),]
Simply put, you need to rewrite all of your database connections and queries.
You are using mysql_*
functions which are now deprecated and will be removed from PHP in the future. So you need to start using MySQLi or PDO instead, just as the error notice warned you.
A basic example of using PDO (without error handling):
<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$result = $db->exec("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");
$insertId = $db->lastInsertId();
?>
A basic example of using MySQLi (without error handling):
$db = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
$result = $db->query("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");
Here's a handy little PDO tutorial to get you started. There are plenty of others, and ones about the PDO alternative, MySQLi.
Batch uses the less than and greater than brackets as input and output pipes.
>file.ext
Using only one output bracket like above will overwrite all the information in that file.
>>file.ext
Using the double right bracket will add the next line to the file.
(
echo
echo
)<file.ext
This will execute the parameters based on the lines of the file. In this case, we are using two lines that will be typed using "echo". The left bracket touching the right parenthesis bracket means that the information from that file will be piped into those lines.
I have compiled an example-only read/write file. Below is the file broken down into sections to explain what each part does.
@echo off
echo TEST R/W
set SRU=0
SRU can be anything in this example. We're actually setting it to prevent a crash if you press Enter too fast.
set /p SRU=Skip Save? (y):
if %SRU%==y goto read
set input=1
set input2=2
set /p input=INPUT:
set /p input2=INPUT2:
Now, we need to write the variables to a file.
(echo %input%)> settings.cdb
(echo %input2%)>> settings.cdb
pause
I use .cdb as a short form for "Command Database". You can use any extension. The next section is to test the code from scratch. We don't want to use the set variables that were run at the beginning of the file, we actually want them to load FROM the settings.cdb we just wrote.
:read
(
set /p input=
set /p input2=
)<settings.cdb
So, we just piped the first two lines of information that you wrote at the beginning of the file (which you have the option to skip setting the lines to check to make sure it's working) to set the variables of input and input2.
echo %input%
echo %input2%
pause
if %input%==1 goto newecho
pause
exit
:newecho
echo If you can see this, good job!
pause
exit
This displays the information that was set while settings.cdb was piped into the parenthesis. As an extra good-job motivator, pressing enter and setting the default values which we set earlier as "1" will return a good job message. Using the bracket pipes goes both ways, and is much easier than setting the "FOR" stuff. :)
If you just want direct subclasses then .__subclasses__()
works fine. If you want all subclasses, subclasses of subclasses, and so on, you'll need a function to do that for you.
Here's a simple, readable function that recursively finds all subclasses of a given class:
def get_all_subclasses(cls):
all_subclasses = []
for subclass in cls.__subclasses__():
all_subclasses.append(subclass)
all_subclasses.extend(get_all_subclasses(subclass))
return all_subclasses
At last I fixed it simply using:
display: table;
df = df[[col for col in df.columns if not ('Unnamed' in col)]]
Assuming module foo
with method bar
:
import foo
method_to_call = getattr(foo, 'bar')
result = method_to_call()
You could shorten lines 2 and 3 to:
result = getattr(foo, 'bar')()
if that makes more sense for your use case.
You can use getattr
in this fashion on class instance bound methods, module-level methods, class methods... the list goes on.
in laravel-8 default remove namespace prefix so you can set old way in laravel-7 like:
in RouteServiceProvider.php
add this variable
protected $namespace = 'App\Http\Controllers';
and update boot
method
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
});
}
Use this method to convert from NSString
to NSdate
:
-(NSDate *)getDateFromString:(NSString *)pstrDate
{
NSDateFormatter* myFormatter = [[NSDateFormatter alloc] init];
[myFormatter setDateFormat:@"dd/MM/yyyy"];
NSDate* myDate = [myFormatter dateFromString:pstrDate];
return myDate;
}
I have encountered this problem in Eclipse Luna EE. My solution was simply restart eclipse and it magically started loading servlet properly.
If you wish to lowercase all values in an nested array, use the following code:
function nestedLowercase($value) {
if (is_array($value)) {
return array_map('nestedLowercase', $value);
}
return strtolower($value);
}
So:
[ 'A', 'B', ['C-1', 'C-2'], 'D']
would return:
[ 'a', 'b', ['c-1', 'c-2'], 'd']
Tims answer seems to me as misleading. Especially when urllib2 does not return expected code. For example this Error will be fatal (believe or not - it is not uncommon one when downloading urls):
AttributeError: 'URLError' object has no attribute 'code'
Fast, but maybe not the best solution would be code using nested try/except block:
import urllib2
try:
urllib2.urlopen("some url")
except urllib2.HTTPError, err:
try:
if err.code == 404:
# Handle the error
else:
raise
except:
...
More information to the topic of nested try/except blocks Are nested try/except blocks in python a good programming practice?
Method overriding is when a child class redefines the same method as a parent class, with the same parameters. For example, the standard Java class java.util.LinkedHashSet
extends java.util.HashSet
. The method add()
is overridden in LinkedHashSet
. If you have a variable that is of type HashSet
, and you call its add()
method, it will call the appropriate implementation of add()
, based on whether it is a HashSet
or a LinkedHashSet
. This is called polymorphism.
Method overloading is defining several methods in the same class, that accept different numbers and types of parameters. In this case, the actual method called is decided at compile-time, based on the number and types of arguments. For instance, the method System.out.println()
is overloaded, so that you can pass ints as well as Strings, and it will call a different version of the method.
Remove the name
param from the class declaration. The init method is used to pass arguments to a class at creation.
class Person(object):
def __init__(self, name):
self.name = name
me = Person("TheLazyScripter")
print me.name
The easiest way would be to package the Vagrant box and then copy (e.g. scp
or rsync
) it over to the other PC, add it and vagrant up
;-)
For detailed steps, check this out =>
Is there any way to clone a vagrant box that is already installed
Try -
$('#chkdwn2').change(function(){
if($(this).is(':checked'))
$('#dropdown').removeAttr('disabled');
else
$('#dropdown').attr("disabled","disabled");
})
I found the answer here: Is it possible to pass query parameters via Django's {% url %} template tag?
Simply add them to the end:
<a href="{% url myview %}?office=foobar">
For Django 1.5+
<a href="{% url 'myview' %}?office=foobar">
[there is nothing else to improve but I'm getting a stupid error when I fix the code ticks]
I had a hard time finding where it is so here the image depicting it in 2019.
I suppose you want to get the content generated by PHP, if so use:
$Vdata = file_get_contents('http://YOUR_HOST/YOUR/FILE.php');
Otherwise if you want to get the source code of the PHP file, it's the same as a .txt file:
$Vdata = file_get_contents('path/to/YOUR/FILE.php');
You want getActivity()
inside your class. It's better to use
yourclassname.this.getActivity()
Try this. It's helpful for you.
I was looking for a solution where I can use the same model for an insert and update in web api. In my situation is this always a body content. The [Requiered]
attributes must be skipped if it is an update method.
In my solution, you place an attribute [IgnoreRequiredValidations]
above the method. This is as follows:
public class WebServiceController : ApiController
{
[HttpPost]
public IHttpActionResult Insert(SameModel model)
{
...
}
[HttpPut]
[IgnoreRequiredValidations]
public IHttpActionResult Update(SameModel model)
{
...
}
...
What else needs to be done?
An own BodyModelValidator must becreated and added at the startup.
This is in the HttpConfiguration and looks like this: config.Services.Replace(typeof(IBodyModelValidator), new IgnoreRequiredOrDefaultBodyModelValidator());
using Owin;
using your_namespace.Web.Http.Validation;
[assembly: OwinStartup(typeof(your_namespace.Startup))]
namespace your_namespace
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
Configuration(app, new HttpConfiguration());
}
public void Configuration(IAppBuilder app, HttpConfiguration config)
{
config.Services.Replace(typeof(IBodyModelValidator), new IgnoreRequiredOrDefaultBodyModelValidator());
}
...
My own BodyModelValidator is derived from the DefaultBodyModelValidator. And i figure out that i had to override the 'ShallowValidate' methode. In this override i filter the requierd model validators. And now the IgnoreRequiredOrDefaultBodyModelValidator class and the IgnoreRequiredValidations attributte class:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.Http.Controllers;
using System.Web.Http.Metadata;
using System.Web.Http.Validation;
namespace your_namespace.Web.Http.Validation
{
public class IgnoreRequiredOrDefaultBodyModelValidator : DefaultBodyModelValidator
{
private static ConcurrentDictionary<HttpActionBinding, bool> _ignoreRequiredValidationByActionBindingCache;
static IgnoreRequiredOrDefaultBodyModelValidator()
{
_ignoreRequiredValidationByActionBindingCache = new ConcurrentDictionary<HttpActionBinding, bool>();
}
protected override bool ShallowValidate(ModelMetadata metadata, BodyModelValidatorContext validationContext, object container, IEnumerable<ModelValidator> validators)
{
var actionContext = validationContext.ActionContext;
if (RequiredValidationsIsIgnored(actionContext.ActionDescriptor.ActionBinding))
validators = validators.Where(v => !v.IsRequired);
return base.ShallowValidate(metadata, validationContext, container, validators);
}
#region RequiredValidationsIsIgnored
private bool RequiredValidationsIsIgnored(HttpActionBinding actionBinding)
{
bool ignore;
if (!_ignoreRequiredValidationByActionBindingCache.TryGetValue(actionBinding, out ignore))
_ignoreRequiredValidationByActionBindingCache.TryAdd(actionBinding, ignore = RequiredValidationsIsIgnored(actionBinding.ActionDescriptor as ReflectedHttpActionDescriptor));
return ignore;
}
private bool RequiredValidationsIsIgnored(ReflectedHttpActionDescriptor actionDescriptor)
{
if (actionDescriptor == null)
return false;
return actionDescriptor.MethodInfo.GetCustomAttribute<IgnoreRequiredValidationsAttribute>(false) != null;
}
#endregion
}
[AttributeUsage(AttributeTargets.Method, Inherited = true)]
public class IgnoreRequiredValidationsAttribute : Attribute
{
}
}
Sources:
string debug = new StackTrace().ToString()
to find out who is
handeling the model validation.A method taking into consideration
it takes such a multi-line string which may be messy e.g.
test_str = '\nhej ho \n aaa\r\n a\n '
and produces nice one-line string
>>> ' '.join([line.strip() for line in test_str.strip().splitlines()])
'hej ho aaa a'
UPDATE: To fix multiple new-line character producing redundant spaces:
' '.join([line.strip() for line in test_str.strip().splitlines() if line.strip()])
This works for the following too
test_str = '\nhej ho \n aaa\r\n\n\n\n\n a\n '
Use
git apply patchfile
if possible.
patch -p1 < patchfile
has potential side-effect.
git apply
also handles file adds, deletes, and renames if they're described in the git diff
format, which patch
won't do. Finally, git apply
is an "apply all or abort all" model where either everything is applied or nothing is, whereas patch can partially apply patch files, leaving your working directory in a weird state.
For some reason Brice's answer is not working for me. I was able to manipulate it a bit to get it to work. It might just be because I have a newer version of PowerMock. I'm using 1.6.5.
import java.util.Random;
public class CodeWithPrivateMethod {
public void meaningfulPublicApi() {
if (doTheGamble("Whatever", 1 << 3)) {
throw new RuntimeException("boom");
}
}
private boolean doTheGamble(String whatever, int binary) {
Random random = new Random(System.nanoTime());
boolean gamble = random.nextBoolean();
return gamble;
}
}
The test class looks as follows:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.doReturn;
@RunWith(PowerMockRunner.class)
@PrepareForTest(CodeWithPrivateMethod.class)
public class CodeWithPrivateMethodTest {
private CodeWithPrivateMethod classToTest;
@Test(expected = RuntimeException.class)
public void when_gambling_is_true_then_always_explode() throws Exception {
classToTest = PowerMockito.spy(classToTest);
doReturn(true).when(classToTest, "doTheGamble", anyString(), anyInt());
classToTest.meaningfulPublicApi();
}
}
I'm not 100% sure this is the only difference, but it is the main difference. It is also recommended to have bi-directional associations by the Hibernate docs:
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/best-practices.html
Specifically:
Prefer bidirectional associations: Unidirectional associations are more difficult to query. In a large application, almost all associations must be navigable in both directions in queries.
I personally have a slight problem with this blanket recommendation -- it seems to me there are cases where a child doesn't have any practical reason to know about its parent (e.g., why does an order item need to know about the order it is associated with?), but I do see value in it a reasonable portion of the time as well. And since the bi-directionality doesn't really hurt anything, I don't find it too objectionable to adhere to.
In Centos
sudo yum install php-xml
and restart apache
sudo service httpd restart
Here's my bash command line to list multiple certificates in order of their expiration, most recently expiring first.
for pem in /etc/ssl/certs/*.pem; do
printf '%s: %s\n' \
"$(date --date="$(openssl x509 -enddate -noout -in "$pem"|cut -d= -f 2)" --iso-8601)" \
"$pem"
done | sort
Sample output:
2015-12-16: /etc/ssl/certs/Staat_der_Nederlanden_Root_CA.pem
2016-03-22: /etc/ssl/certs/CA_Disig.pem
2016-08-14: /etc/ssl/certs/EBG_Elektronik_Sertifika_Hizmet_S.pem
This is what I think is missing from the answers so far:
If you need one instance of this object per process address space (and you are as confident as you can be that this requirement will not change), you should make it a singleton.
Otherwise, it's not a singleton.
This is a very odd requirement, hardly ever of interest to the user. Processes and address space isolation are an implementation detail. They only impact on the user when they want to stop your application using kill
or Task Manager.
Apart from building a caching system, there aren't that many reasons why you'd be so certain that there should only be on instance of something per process. How about a logging system? Might be better for that to be per-thread or more fine-grained so you can trace the origin of messages more automatically. How about the application's main window? It depends; maybe you'll want all the user's documents to be managed by the same process for some reason, in which case there would be multiple "main windows" in that process.
varvy.com (100/100 Google page speed insight) loads google analitycs code only if user make a scroll of the page:
var fired = false;
window.addEventListener("scroll", function(){
if ((document.documentElement.scrollTop != 0 && fired === false) || (document.body.scrollTop != 0 && fired === false)) {
(function(i,s,o,g,r,a,m{i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXX-X', 'auto');
ga('send', 'pageview');
fired = true;
}
}, true);
Not with an iterator.
For org.json.JSONArray
, you can do:
for (int i = 0; i < arr.length(); i++) {
arr.getJSONObject(i);
}
For javax.json.JsonArray
, you can do:
for (int i = 0; i < arr.size(); i++) {
arr.getJsonObject(i);
}
Yes, if such precision is required use System.nanoTime()
, but be aware that you are then requiring a Java 5+ JVM.
On my XP systems, I see system time reported to at least 100 microseconds 278 nanoseconds using the following code:
private void test() {
System.out.println("currentTimeMillis: "+System.currentTimeMillis());
System.out.println("nanoTime : "+System.nanoTime());
System.out.println();
testNano(false); // to sync with currentTimeMillis() timer tick
for(int xa=0; xa<10; xa++) {
testNano(true);
}
}
private void testNano(boolean shw) {
long strMS=System.currentTimeMillis();
long strNS=System.nanoTime();
long curMS;
while((curMS=System.currentTimeMillis()) == strMS) {
if(shw) { System.out.println("Nano: "+(System.nanoTime()-strNS)); }
}
if(shw) { System.out.println("Nano: "+(System.nanoTime()-strNS)+", Milli: "+(curMS-strMS)); }
}
Easy way to convert base64 image into file and save as some random id or name.
// to create some random id or name for your image name
const imgname = new Date().getTime().toString();
// to declare some path to store your converted image
const path = yourpath.png
// image takes from body which you uploaded
const imgdata = req.body.image;
// to convert base64 format into random filename
const base64Data = imgdata.replace(/^data:([A-Za-z-+/]+);base64,/, '');
fs.writeFile(path, base64Data, 'base64', (err) => {
console.log(err);
});
// assigning converted image into your database
req.body.coverImage = imgname
We can use ng-src
but when ng-src's value
became null
, ''
or undefined
, ng-src
will not work.
So just use ng-if
for this case:
http://jsfiddle.net/Hx7B9/299/
<div ng-app>
<div ng-controller="AppCtrl">
<a href='#'><img ng-src="{{link}}" ng-if="!!link"/></a>
<button ng-click="changeLink()">Change Image</button>
</div>
</div>
SELECT
pg_terminate_backend(pid)
FROM
pg_stat_activity
WHERE
pid <> pg_backend_pid()
-- no need to kill connections to other databases
AND datname = current_database();
-- use current_database by opening right query tool
Connect to the Guest and find out the ip address:
ifconfig
example of result (ip address is 10.0.2.15):
eth0 Link encap:Ethernet HWaddr 08:00:27:AE:36:99
inet addr:10.0.2.15 Bcast:10.0.2.255 Mask:255.255.255.0
Go to Vbox instance window -> Menu -> Network adapters:
Go to host system and try it in browser:
http://127.0.0.1:8000
or your network ip address (find out on the host machine by running: ipconfig).
In this case port forwarding is not needed, the communication goes over the LAN back to the host.
On the host machine - find out your netw ip address:
ipconfig
example of result:
IP Address. . . . . . . . . . . . : 192.168.5.1
On the guest machine you can communicate directly with the host, e.g. check it with ping:
# ping 192.168.5.1
PING 192.168.5.1 (192.168.5.1) 56(84) bytes of data.
64 bytes from 192.168.5.1: icmp_seq=1 ttl=128 time=2.30 ms
...
@Stranger suggested that in some cases it would be necessary to open used port (8000 or whichever is used) in firewall like this (example for ufw firewall, I haven't tested):
sudo ufw allow 8000
In addition to Petr's answer, if you want to bind to a specific interface instead of all the interfaces you can use -b
or --bind
flag.
python -m http.server 8000 --bind 127.0.0.1
The above snippet should do the trick. 8000 is the port number. 80 is used as the standard port for HTTP communications.
Use the below Power shell command to change the execution timeout (Request Timeout)
Please note that I have given this for default web site, before using these please change the site and then try to use this.
Set-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST/Default Web Site' -filter "system.web/httpRuntime" -name "executionTimeout" -value "00:01:40"
Or, You can use the below C# code to do the same thing
using System;
using System.Text;
using Microsoft.Web.Administration;
internal static class Sample {
private static void Main() {
using(ServerManager serverManager = new ServerManager()) {
Configuration config = serverManager.GetWebConfiguration("Default Web Site");
ConfigurationSection httpRuntimeSection = config.GetSection("system.web/httpRuntime");
httpRuntimeSection["executionTimeout"] = TimeSpan.Parse("00:01:40");
serverManager.CommitChanges();
}
}
}
Or, you can use the JavaScript to do this.
var adminManager = new ActiveXObject('Microsoft.ApplicationHost.WritableAdminManager');
adminManager.CommitPath = "MACHINE/WEBROOT/APPHOST/Default Web Site";
var httpRuntimeSection = adminManager.GetAdminSection("system.web/httpRuntime", "MACHINE/WEBROOT/APPHOST/Default Web Site");
httpRuntimeSection.Properties.Item("executionTimeout").Value = "00:01:40";
adminManager.CommitChanges();
Or, you can use the AppCmd commands.
appcmd.exe set config "Default Web Site" -section:system.web/httpRuntime /executionTimeout:"00:01:40"
Select the lines in codesigning that are blank under Any iOS SDK and select the right certificate.
In the Drupal or Wordpress CMS (and likely others), if you are trying to make some custom php code appear not to exist (unless some condition is met), the following works well by making the CMS's 404 handler take over:
<?php
if(condition){
do stuff;
} else {
include('index.php');
}
?>
In MS Windows, the mongoimport command has to be run in a normal Windows command prompt, not from the mongodb command prompt.
You could try the following code. I can't vouch for browser compatibility though, so you'll have to test that.
function testImage(URL) {
var tester=new Image();
tester.onload=imageFound;
tester.onerror=imageNotFound;
tester.src=URL;
}
function imageFound() {
alert('That image is found and loaded');
}
function imageNotFound() {
alert('That image was not found.');
}
testImage("http://foo.com/bar.jpg");
And my sympathies for the jQuery-resistant boss!
From the notebook menu you can save the file directly as a python script. Go to the 'File' option of the menu, then select 'Download as' and there you would see a 'Python (.py)' option.
Another option would be to use nbconvert from the command line:
jupyter nbconvert --to script 'my-notebook.ipynb'
Have a look here.
You can call either string's compareTo method (java.lang.String.compareTo). This feature is well documented on the java documentation site.
Here is a short program that demonstrates it:
class StringCompareExample {
public static void main(String args[]){
String s1 = "Project"; String s2 = "Sunject";
verboseCompare(s1, s2);
verboseCompare(s2, s1);
verboseCompare(s1, s1);
}
public static void verboseCompare(String s1, String s2){
System.out.println("Comparing \"" + s1 + "\" to \"" + s2 + "\"...");
int comparisonResult = s1.compareTo(s2);
System.out.println("The result of the comparison was " + comparisonResult);
System.out.print("This means that \"" + s1 + "\" ");
if(comparisonResult < 0){
System.out.println("lexicographically precedes \"" + s2 + "\".");
}else if(comparisonResult > 0){
System.out.println("lexicographically follows \"" + s2 + "\".");
}else{
System.out.println("equals \"" + s2 + "\".");
}
System.out.println();
}
}
Here is a live demonstration that shows it works: http://ideone.com/Drikp3
There are two ways to fix this:
Execute the following in the MySQL console:
SET GLOBAL log_bin_trust_function_creators = 1;
Add the following to the mysql.ini configuration file:
log_bin_trust_function_creators = 1;
The setting relaxes the checking for non-deterministic functions. Non-deterministic functions are functions that modify data (i.e. have update, insert or delete statement(s)). For more info, see here.
Please note, if binary logging is NOT enabled, this setting does not apply.
Binary Logging of Stored Programs
If binary logging is not enabled, log_bin_trust_function_creators does not apply.
log_bin_trust_function_creators
This variable applies when binary logging is enabled.
The best approach is a better understanding and use of deterministic declarations for stored functions. These declarations are used by MySQL to optimize the replication and it is a good thing to choose them carefully to have a healthy replication.
DETERMINISTIC A routine is considered “deterministic” if it always produces the same result for the same input parameters and NOT DETERMINISTIC otherwise. This is mostly used with string or math processing, but not limited to that.
NOT DETERMINISTIC Opposite of "DETERMINISTIC". "If neither DETERMINISTIC nor NOT DETERMINISTIC is given in the routine definition, the default is NOT DETERMINISTIC. To declare that a function is deterministic, you must specify DETERMINISTIC explicitly.". So it seems that if no statement is made, MySQl will treat the function as "NOT DETERMINISTIC". This statement from manual is in contradiction with other statement from another area of manual which tells that: " When you create a stored function, you must declare either that it is deterministic or that it does not modify data. Otherwise, it may be unsafe for data recovery or replication. By default, for a CREATE FUNCTION statement to be accepted, at least one of DETERMINISTIC, NO SQL, or READS SQL DATA must be specified explicitly. Otherwise an error occurs"
I personally got error in MySQL 5.5 if there is no declaration, so i always put at least one declaration of "DETERMINISTIC", "NOT DETERMINISTIC", "NO SQL" or "READS SQL DATA" regardless other declarations i may have.
READS SQL DATA This explicitly tells to MySQL that the function will ONLY read data from databases, thus, it does not contain instructions that modify data, but it contains SQL instructions that read data (e.q. SELECT).
MODIFIES SQL DATA This indicates that the routine contains statements that may write data (for example, it contain UPDATE, INSERT, DELETE or ALTER instructions).
NO SQL This indicates that the routine contains no SQL statements.
CONTAINS SQL This indicates that the routine contains SQL instructions, but does not contain statements that read or write data. This is the default if none of these characteristics is given explicitly. Examples of such statements are SELECT NOW(), SELECT 10+@b, SET @x = 1 or DO RELEASE_LOCK('abc'), which execute but neither read nor write data.
Note that there are MySQL functions that are not deterministic safe, such as: NOW(), UUID(), etc, which are likely to produce different results on different machines, so a user function that contains such instructions must be declared as NOT DETERMINISTIC. Also, a function that reads data from an unreplicated schema is clearly NONDETERMINISTIC. *
Assessment of the nature of a routine is based on the “honesty” of the creator: MySQL does not check that a routine declared DETERMINISTIC is free of statements that produce nondeterministic results. However, misdeclaring a routine might affect results or affect performance. Declaring a nondeterministic routine as DETERMINISTIC might lead to unexpected results by causing the optimizer to make incorrect execution plan choices. Declaring a deterministic routine as NONDETERMINISTIC might diminish performance by causing available optimizations not to be used.
I had hit the same problem and learnt the following-
Even though database has a default character set of utf-8, it's possible for database columns to have a different character set in MySQL. Modified dB and the problematic column to UTF-8:
mysql> ALTER DATABASE MyDB CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'
mysql> ALTER TABLE database.table MODIFY COLUMN column_name VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;
Now creating new tables with:
> CREATE TABLE My_Table_Name (
twitter_id_str VARCHAR(255) NOT NULL UNIQUE,
twitter_screen_name VARCHAR(512) CHARACTER SET utf8 COLLATE utf8_unicode_ci,
.....
) CHARACTER SET utf8 COLLATE utf8_unicode_ci;
I use it all the time on hackerrank/leetcode
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String lines = br.readLine();
String[] strs = lines.trim().split("\\s+");
for (int i = 0; i < strs.length; i++) {
a[i] = Integer.parseInt(strs[i]);
}
Enter the following code in the opened settings file
{
"editor.formatOnSave": true
}
Save file
There are many way to get application context in Spring application. Those are given bellow:
Via ApplicationContextAware:
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class AppContextProvider implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
Here setApplicationContext(ApplicationContext applicationContext)
method you will get the applicationContext
Via Autowired:
@Autowired
private ApplicationContext applicationContext;
Here @Autowired
keyword will provide the applicationContext.
For more info visit this thread
Thanks :)
!===
will not work because it's a syntax error. The correct way is !==
(not three "equal to" symbols)
There is not a Google Chrome extension comparable to Selenium IDE.
Scirocco is only a partial (and reportedly unreliable) implementation.
There is another plugin, the Bug Buster Test Recorder, but it only works with their service. I don't know it's effectiveness.
Sahi and TestComplete can also record, but neither are free, and are not browser plugins.
iMacros is a plugin that allows record and playback, but is not geared towards testing, and is not compatible with Selenium.
It sounds like there is a demand for a tool like this, and Firefox is becoming unsupported by Selenium. So, while I know Stack Overflow isn't the forum for this, anyone interested in helping make it happen, let me know.
I'd be interested in what the limitations are and why it hasn't been done. Is it just that the official Selenium team doesn't want to support it, or is there a technical limitation?
This should work for you:
$('.SeeMore2').click(function(){
var $this = $(this);
$this.toggleClass('SeeMore2');
if($this.hasClass('SeeMore2')){
$this.text('See More');
} else {
$this.text('See Less');
}
});
For a similar problem, (my problem was to show UTF-8 characters from MySQL on a command prompt),
I solved it like this:
I changed the font of command prompt to Lucida Console. (This step must be irrelevant for your situation. It has to do only with what you see on the screen and not with what is really the character).
I changed the codepage to Windows-1253. You do this on the command prompt by "chcp 1253". It worked for my case where I wanted to see UTF-8.
All of the answers are good but not complete. Use this.
<EditText
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="12dp"
android:layout_marginBottom="12dp"
android:background="@drawable/text_area_background"
android:gravity="start|top"
android:hint="@string/write_your_comments"
android:imeOptions="actionDone"
android:importantForAutofill="no"
android:inputType="textMultiLine"
android:padding="12dp" />
I just leave my solution here.
import csv
import numpy as np
with open(name, newline='') as f:
reader = csv.reader(f, delimiter=",")
# skip header
next(reader)
# convert csv to list and then to np.array
data = np.array(list(reader))[:, 1:] # skip the first column
print(data.shape) # => (N, 2)
# sum each row
s = data.sum(axis=1)
print(s.shape) # => (N,)
I always use 010 Editor to open huge files. It can handle 2 GB easily. I was manipulating files with 50 GB with 010 Editor :-)
It's commercial now, but it has a trial version.
You could use apply() and do something like this
df['que'] = df.apply(lambda x : x['one'] if x['one'] >= x['two'] and x['one'] <= x['three'] else "", axis=1)
or if you prefer not to use a lambda
def que(x):
if x['one'] >= x['two'] and x['one'] <= x['three']:
return x['one']
return ''
df['que'] = df.apply(que, axis=1)
Niyaz is correct, but it's also worth noting that the special + operator can be converted into something more efficient by the Java compiler. Java has a StringBuilder class which represents a non-thread-safe, mutable String. When performing a bunch of String concatenations, the Java compiler silently converts
String a = b + c + d;
into
String a = new StringBuilder(b).append(c).append(d).toString();
which for large strings is significantly more efficient. As far as I know, this does not happen when you use the concat method.
However, the concat method is more efficient when concatenating an empty String onto an existing String. In this case, the JVM does not need to create a new String object and can simply return the existing one. See the concat documentation to confirm this.
So if you're super-concerned about efficiency then you should use the concat method when concatenating possibly-empty Strings, and use + otherwise. However, the performance difference should be negligible and you probably shouldn't ever worry about this.
In my case the problem was introduced when I fixed a static analysis error that the return value of a method was not used.
Old working code in my Application.java was:
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
New code that introduced the problem was:
public static void main(String[] args) {
try (ConfigurableApplicationContext context =
SpringApplication.run(Application.class, args)) {
LOG.trace("context: " + context);
}
}
Obviously, the try with resource block will close the context after starting the application which will result in the application exiting with status 0. This was a case where the resource leak error reported by snarqube static analysis should be ignored.
Try this:
window.location.href = "http://PlaceYourUrl.com";
This will squash second commit into the first one:
A-B-C-... -> AB-C-...
git filter-branch --commit-filter '
if [ "$GIT_COMMIT" = <sha1ofA> ];
then
skip_commit "$@";
else
git commit-tree "$@";
fi
' HEAD
Commit message for AB will be taken from B (although I'd prefer from A).
Has the same effect as Uwe Kleine-König's answer, but works for non-initial A as well.
DATEADD
is the way to go with this
See the W3Schools tutorial: http://www.w3schools.com/sql/func_dateadd.asp
The answers are outdated. You simply have to conda install pip and git. Then you can use pip normally:
Activate your conda environment source activate myenv
conda install git pip
pip install git+git://github.com/scrappy/scrappy@master
span.login-text {
font-size: 22px;
display:table;
margin-left: auto;
margin-right: auto;
}
<span class="login-text">Welcome To .....CMP</span>
For me it worked very well. try this also
check this quick reminder of file path
Here is all you need to know about relative file paths:
Copied from CLR via C# by Jeffrey Richter...
I often hear the question, “Should I design a base type or an interface?” The answer isn’t always clearcut.
Here are some guidelines that might help you:
¦¦ IS-A vs. CAN-DO relationship A type can inherit only one implementation. If the derived type can’t claim an IS-A relationship with the base type, don’t use a base type; use an interface. Interfaces imply a CAN-DO relationship. If the CAN-DO functionality appears to belong with various object types, use an interface. For example, a type can convert instances of itself to another type (IConvertible), a type can serialize an instance of itself (ISerializable), etc. Note that value types must be derived from System.ValueType, and therefore, they cannot be derived from an arbitrary base class. In this case, you must use a CAN-DO relationship and define an interface.
¦¦ Ease of use It’s generally easier for you as a developer to define a new type derived from a base type than to implement all of the methods of an interface. The base type can provide a lot of functionality, so the derived type probably needs only relatively small modifications to its behavior. If you supply an interface, the new type must implement all of the members.
¦¦ Consistent implementation No matter how well an interface contract is documented, it’s very unlikely that everyone will implement the contract 100 percent correctly. In fact, COM suffers from this very problem, which is why some COM objects work correctly only with Microsoft Word or with Windows Internet Explorer. By providing a base type with a good default implementation, you start off using a type that works and is well tested; you can then modify parts that need modification.
¦¦ Versioning If you add a method to the base type, the derived type inherits the new method, you start off using a type that works, and the user’s source code doesn’t even have to be recompiled. Adding a new member to an interface forces the inheritor of the interface to change its source code and recompile.
The best solution is not to use the same element for column and panel:
<div class="row">
<div class="col-md-3">
<div class="panel" id="gameplay-away-team">Away Team</div>
</div>
<div class="col-md-6">
<div class="panel" id="gameplay-baseball-field">Baseball Field</div>
</div>
<div class="col-md-3">
<div class="panel" id="gameplay-home-team">Home Team</div>
</div>
</div>
and some more styles:
#gameplay-baseball-field {
padding-right: 10px;
padding-left: 10px;
}
I was able to have this done via below method
cat ../logs/em2.log.1 |grep -i 192.168.21.15 |awk '{system(`date`); print $1}'
awk has a function called system it enables you to execute any linux bash command within the output of awk.
If you have web.xml then
HTML/JSP
<form action="${pageContext.request.contextPath}/myservlet" method="post">
<input type="submit" name="button1" value="Button 1" />
</form>
web.xml
<servlet>
<display-name>Servlet Name</display-name>
<servlet-name>myservlet</servlet-name>
<servlet-class>package.SomeController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>/myservlet</url-pattern>
</servlet-mapping>
Java SomeController.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Write your code below");
}
Negatives are your friend here:
SELECT Col1
FROM TABLE
WHERE Col1 like '%[^a-Z0-9]%'
Which says that you want any rows where Col1
consists of any number of characters, then one character not in the set a-Z0-9, and then any number of characters.
If you have a case sensitive collation, it's important that you use a range that includes both upper and lower case A
, a
, Z
and z
, which is what I've given (originally I had it the wrong way around. a
comes before A
. Z
comes after z
)
Or, to put it another way, you could have written your original WHERE
as:
Col1 LIKE '[!@#$%]'
But, as you observed, you'd need to know all of the characters to include in the []
.
With Angular 5 and up, you DON'T have to use HttpParams. You can directly send your json object as shown below.
let data = {limit: "2"};
this.httpClient.get<any>(apiUrl, {params: data});
Please note that data values should be string, ie; { params: {limit: "2"}}
Use HttpParams, HttpClient from @angular/common/http
import { HttpParams, HttpClient } from '@angular/common/http';
...
constructor(private httpClient: HttpClient) { ... }
...
let params = new HttpParams();
params = params.append("page", 1);
....
this.httpClient.get<any>(apiUrl, {params: params});
Also, try stringifying your nested object using JSON.stringify()
.
If you add:
<meta http-equiv="content-type" content="text/plain; charset=UTF-8"/>
in the head of the document it will start working as expected:
<script type="text/javascript">
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
</script>
BitConverter
class can be used to convert a byte[]
to string
.
var convertedString = BitConverter.ToString(byteAttay);
Documentation of BitConverter
class can be fount on MSDN
Basically, Python lists are very flexible and can hold completely heterogeneous, arbitrary data, and they can be appended to very efficiently, in amortized constant time. If you need to shrink and grow your list time-efficiently and without hassle, they are the way to go. But they use a lot more space than C arrays, in part because each item in the list requires the construction of an individual Python object, even for data that could be represented with simple C types (e.g. float
or uint64_t
).
The array.array
type, on the other hand, is just a thin wrapper on C arrays. It can hold only homogeneous data (that is to say, all of the same type) and so it uses only sizeof(one object) * length
bytes of memory. Mostly, you should use it when you need to expose a C array to an extension or a system call (for example, ioctl
or fctnl
).
array.array
is also a reasonable way to represent a mutable string in Python 2.x (array('B', bytes)
). However, Python 2.6+ and 3.x offer a mutable byte string as bytearray
.
However, if you want to do math on a homogeneous array of numeric data, then you're much better off using NumPy, which can automatically vectorize operations on complex multi-dimensional arrays.
To make a long story short: array.array
is useful when you need a homogeneous C array of data for reasons other than doing math.
import subprocess
subprocess.check_output('echo "' + YOURTEXT + '" >> hello.txt',shell=True)
Try:
task.AsyncResult(task.request.id).state
this will provide the Celery Task status. If Celery Task is already is under FAILURE state it will throw an Exception:
raised unexpected: KeyError('exc_type',)
paramiko finally worked for me after adding additional line, which is really important one (line 3):
import paramiko
p = paramiko.SSHClient()
p.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # This script doesn't work for me unless this line is added!
p.connect("server", port=22, username="username", password="password")
stdin, stdout, stderr = p.exec_command("your command")
opt = stdout.readlines()
opt = "".join(opt)
print(opt)
Make sure that paramiko package is installed. Original source of the solution: Source
Why involve Notepad?
Sub ReplaceStringInFile()
Dim sBuf As String
Dim sTemp As String
Dim iFileNum As Integer
Dim sFileName As String
' Edit as needed
sFileName = "C:\Temp\test.txt"
iFileNum = FreeFile
Open sFileName For Input As iFileNum
Do Until EOF(iFileNum)
Line Input #iFileNum, sBuf
sTemp = sTemp & sBuf & vbCrLf
Loop
Close iFileNum
sTemp = Replace(sTemp, "THIS", "THAT")
iFileNum = FreeFile
Open sFileName For Output As iFileNum
Print #iFileNum, sTemp
Close iFileNum
End Sub
simple:
today="$(date '+%Y-%m-%d')"
yesterday="$(date -d yesterday '+%Y-%m-%d')"
Inside the input tag you can add autoFocus={true} for anyone using jsx/react.
<input
type="email"
name="email"
onChange={e => setEmail(e.target.value)}
value={email}
placeholder={"Email..."}
autoFocus={true}
/>
On Android the same rules apply as in a normal Java environment. In Java threads are not killed, but the stopping of a thread is done in a cooperative way. The thread is asked to terminate and the thread can then shutdown gracefully.
Often a volatile boolean
field is used which the thread periodically checks and terminates when it is set to the corresponding value.
I would not use a boolean
to check whether the thread should terminate. If you use volatile
as a field modifier, this will work reliable, but if your code becomes more complex, for instead uses other blocking methods inside the while
loop, it might happen, that your code will not terminate at all or at least takes longer as you might want.
Certain blocking library methods support interruption.
Every thread has already a boolean flag interrupted status and you should make use of it. It can be implemented like this:
public void run() {
try {
while(!Thread.currentThread().isInterrupted()) {
// ...
}
} catch (InterruptedException consumed)
/* Allow thread to exit */
}
}
public void cancel() { interrupt(); }
Source code taken from Java Concurrency in Practice. Since the cancel()
method is public you can let another thread invoke this method as you wanted.
There is also a poorly named static method interrupted
which clears the interrupted status of the current thread.
Most (if not all) implementations proposed here have two flaws:
An updated proposition:
def find_first_in_list(objects, **kwargs):
return next((obj for obj in objects if
len(set(obj.keys()).intersection(kwargs.keys())) > 0 and
all([obj[k] == v for k, v in kwargs.items() if k in obj.keys()])),
None)
Maybe not the most pythonic, but at least a bit more failsafe.
Usage:
>>> obj1 = find_first_in_list(list_of_dict, name='Pam', age=7)
>>> obj2 = find_first_in_list(list_of_dict, name='Pam', age=27)
>>> obj3 = find_first_in_list(list_of_dict, name='Pam', address='nowhere')
>>>
>>> print(obj1, obj2, obj3)
{"name": "Pam", "age": 7}, None, {"name": "Pam", "age": 7}
The gist.
I managed to deal with this problem. Below is the link :
https://github.com/nakosung/ng-dynamic-template-example
with the specific file being:
https://github.com/nakosung/ng-dynamic-template-example/blob/master/src/main.coffee
dynamicTemplate
directive hosts dynamic template which is passed within scope and hosted element acts like other native angular elements.
scope.template = '< div ng-controller="SomeUberCtrl">rocks< /div>'
Here`s an elegant solution using Apache Commons Lang 3:
EnumUtils.getEnumList(State.class)
Although it returns a List, you can convert the list easily with list.toArray()
To the delight of font purists everywhere, the iPhone system interface uses Helvetica or a variant thereof.
The original iPhone, iPhone 3G and iPhone 3GS system interface uses Helvetica. As first noted by the always excellent DaringFireball, the iPhone 4 uses a subtly revised font called "Helvetica Neue." DaringFireball also notes that this change is related to the iPhone 4 display rather than the iOS 4 operating system and older iPhone models running iOS 4 still use Helvetica as the system font.
iPod models released prior to the iPhone use either Chicago, Espy Sans, or Myriad and use Helvetica after the release of the iPhone.
From http://www.everyipod.com/iphone-faq/iphone-who-designed-iphone-font-used-iphone-ringtones.html
For iOS9 it has changed to San Fransisco. See http://developer.apple.com/fonts for more info.
This is pretty much as close as you'll get if you want to use the ActionBar
APIs. I'm not sure you can place a colorstrip above the ActionBar
without doing some weird Window
hacking, it's not worth the trouble. As far as changing the MenuItems
goes, you can make those tighter via a style. It would be something like this, but I haven't tested it.
<style name="MyTheme" parent="android:Theme.Holo.Light">
<item name="actionButtonStyle">@style/MyActionButtonStyle</item>
</style>
<style name="MyActionButtonStyle" parent="Widget.ActionButton">
<item name="android:minWidth">28dip</item>
</style>
Here's how to inflate and add the custom layout to your ActionBar
.
// Inflate your custom layout
final ViewGroup actionBarLayout = (ViewGroup) getLayoutInflater().inflate(
R.layout.action_bar,
null);
// Set up your ActionBar
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setCustomView(actionBarLayout);
// You customization
final int actionBarColor = getResources().getColor(R.color.action_bar);
actionBar.setBackgroundDrawable(new ColorDrawable(actionBarColor));
final Button actionBarTitle = (Button) findViewById(R.id.action_bar_title);
actionBarTitle.setText("Index(2)");
final Button actionBarSent = (Button) findViewById(R.id.action_bar_sent);
actionBarSent.setText("Sent");
final Button actionBarStaff = (Button) findViewById(R.id.action_bar_staff);
actionBarStaff.setText("Staff");
final Button actionBarLocations = (Button) findViewById(R.id.action_bar_locations);
actionBarLocations.setText("HIPPA Locations");
Here's the custom layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:enabled="false"
android:orientation="horizontal"
android:paddingEnd="8dip" >
<Button
android:id="@+id/action_bar_title"
style="@style/ActionBarButtonWhite" />
<Button
android:id="@+id/action_bar_sent"
style="@style/ActionBarButtonOffWhite" />
<Button
android:id="@+id/action_bar_staff"
style="@style/ActionBarButtonOffWhite" />
<Button
android:id="@+id/action_bar_locations"
style="@style/ActionBarButtonOffWhite" />
</LinearLayout>
Here's the color strip layout: To use it, just use merge
in whatever layout you inflate in setContentView
.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="@dimen/colorstrip"
android:background="@android:color/holo_blue_dark" />
Here are the Button
styles:
<style name="ActionBarButton">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:background">@null</item>
<item name="android:ellipsize">end</item>
<item name="android:singleLine">true</item>
<item name="android:textSize">@dimen/text_size_small</item>
</style>
<style name="ActionBarButtonWhite" parent="@style/ActionBarButton">
<item name="android:textColor">@color/white</item>
</style>
<style name="ActionBarButtonOffWhite" parent="@style/ActionBarButton">
<item name="android:textColor">@color/off_white</item>
</style>
Here are the colors and dimensions I used:
<color name="action_bar">#ff0d0d0d</color>
<color name="white">#ffffffff</color>
<color name="off_white">#99ffffff</color>
<!-- Text sizes -->
<dimen name="text_size_small">14.0sp</dimen>
<dimen name="text_size_medium">16.0sp</dimen>
<!-- ActionBar color strip -->
<dimen name="colorstrip">5dp</dimen>
If you want to customize it more than this, you may consider not using the ActionBar
at all, but I wouldn't recommend that. You may also consider reading through the Android Design Guidelines to get a better idea on how to design your ActionBar.
If you choose to forgo the ActionBar
and use your own layout instead, you should be sure to add action-able Toasts
when users long press your "MenuItems". This can be easily achieved using this Gist.
select{
filter: progid:DXImageTransform.Microsoft.dropshadow(OffX=-1, OffY=-1,color=#FF0000) progid:DXImageTransform.Microsoft.dropshadow(OffX=1, OffY=1,color=#FF0000);
}
Works for me.
Don't use GitHub as a Maven Repository.
Edit: This option gets a lot of down votes, but no comments as to why. This is the correct option regardless of the technical capabilities to actually host on GitHub. Hosting on GitHub is wrong for all the reasons outlined below and without comments I can't improve the answer to clarify your issues.
Best Option - Collaborate with the Original Project
The best option is to convince the original project to include your changes and stick with the original.
Alternative - Maintain your own Fork
Since you have forked an open source library, and your fork is also open source, you can upload your fork to Maven Central (read Guide to uploading artifacts to the Central Repository) by giving it a new groupId
and maybe a new artifactId
.
Only consider this option if you are willing to maintain this fork until the changes are incorporated into the original project and then you should abandon this one.
Really consider hard whether a fork is the right option. Read the myriad Google results for 'why not to fork'
Reasoning
Bloating your repository with jars increases download size for no benefit
A jar is an output
of your project, it can be regenerated at any time from its inputs
, and your GitHub repo should contain only inputs
.
Don't believe me? Then check Google results for 'dont store binaries in git'.
GitHub's help Working with large files will tell you the same thing. Admittedly jar's aren't large but they are larger than the source code and once a jar has been created by a release they have no reason to be versioned - that is what a new release is for.
Defining multiple repos in your pom.xml slows your build down by Number of Repositories times Number of Artifacts
Stephen Connolly says:
If anyone adds your repo they impact their build performance as they now have another repo to check artifacts against... It's not a big problem if you only have to add one repo... But the problem grows and the next thing you know your maven build is checking 50 repos for every artifact and build time is a dog.
That's right! Maven needs to check every artifact (and its dependencies) defined in your pom.xml against every Repository you have defined, as a newer version might be available in any of those repositories.
Try it out for yourself and you will feel the pain of a slow build.
The best place for artifacts is in Maven Central, as its the central place for jars, and this means your build will only ever check one place.
You can read some more about repositories at Maven's documentation on Introduction to Repositories
The out of memory suggestion doesn't seem like a bad lead.
What is your program doing that it gets this error?
Is it creating a great many windows or controls? Does it create them programatically as opposed to at design time? If so, do you do this in a loop? Is that loop infinite? Are you consuming staggering boatloads of memory in some other way?
What happens when you watch the memory used by your application in task manager? Does it skyrocket to the moon? Or better yet, as suggested above use process monitor to dive into the details.
Dim timeFormat As String = "yyyy-MM-dd HH:mm:ss"
objBL.date = Convert.ToDateTime(txtDate.Value).ToString(timeFormat)
In App.js
import {useHistory } from "react-router-dom";
const TheContext = React.createContext(null);
const App = () => {
const history = useHistory();
<TheContext.Provider value={{ history, user }}>
<Switch>
<Route exact path="/" render={(props) => <Home {...props} />} />
<Route
exact
path="/sign-up"
render={(props) => <SignUp {...props} setUser={setUser} />}
/> ...
Then in a child component :
const Welcome = () => {
const {user, history} = React.useContext(TheContext);
....
None of the above solutions worked for me, I found an article that explained the issue. The security protocols on the system were deprecated and therefore displayed an error message that no match was found for the ProviderPackage.
Here is a the basic steps for upgrading your security protocols:
Run both cmdlets to set .NET Framework strong cryptography registry keys. After that, restart PowerShell and check if the security protocol TLS 1.2 is added. As of last, install the PowerShellGet module.
The first cmdlet is to set strong cryptography on 64 bit .Net Framework (version 4 and above).
[PS] C:\>Set-ItemProperty -Path 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
1
[PS] C:\>Set-ItemProperty -Path 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
The second cmdlet is to set strong cryptography on 32 bit .Net Framework (version 4 and above).
[PS] C:\>Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
1
[PS] C:\>Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
Restart Powershell and check for supported security protocols.
[PS] C:\>[Net.ServicePointManager]::SecurityProtocol
Tls, Tls11, Tls12
1
2
[PS] C:\>[Net.ServicePointManager]::SecurityProtocol
Tls, Tls11, Tls12
Run the command Install-Module PowershellGet -Force and press Y to install NuGet provider, follow with Enter.
[PS] C:\>Install-Module PowershellGet -Force
NuGet provider is required to continue
PowerShellGet requires NuGet provider version '2.8.5.201' or newer to interact with NuGet-based repositories. The NuGet provider must be available in 'C:\Program Files\PackageManagement\ProviderAssemblies' or
'C:\Users\administrator.EXOIP\AppData\Local\PackageManagement\ProviderAssemblies'. You can also install the NuGet provider by running 'Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force'. Do you want PowerShellGet to install
and import the NuGet provider now?
[Y] Yes [N] No [S] Suspend [?] Help (default is "Y"): Y
[PS] C:\>Install-Module PowershellGet -Force
NuGet provider is required to continue
PowerShellGet requires NuGet provider version '2.8.5.201' or newer to interact with NuGet-based repositories. The NuGet provider must be available in 'C:\Program Files\PackageManagement\ProviderAssemblies' or
'C:\Users\administrator.EXOIP\AppData\Local\PackageManagement\ProviderAssemblies'. You can also install the NuGet provider by running 'Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force'. Do you want PowerShellGet to install
and import the NuGet provider now?
[Y] Yes [N] No [S] Suspend [?] Help (default is "Y"): Y
All the answers are pointing to a Lambda expression with an NRE (Null Reference Exception). I have found that it also occurs when using Linq to Entities. I thought it would be helpful to point out that this exception is not limited to just an NRE inside a Lambda expression.
Adding to @marbel's answer (which is a great suggestion!), here's the script that worked for me on Mac OS X El Captain's Terminal, for batch conversion (since that's what the OP asked). I thought it would be trivial to do a for
loop but it wasn't! (had to change the extension by string manipulation and it looks like Mac's bash is a bit different also)
for x in $(ls *.xlsx); do x1=${x%".xlsx"}; in2csv $x > $x1.csv; echo "$x1.csv done."; done
Note:
${x%”.xlsx”}
is bash string manipulation which clips .xlsx
from the end of the string. You need to define the width of the element you are centering, not the parent element.
#header ul {
margin: 0 auto;
width: 90%;
}
Edit: Ok, I've seen the testpage now, and here is how I think you want it:
#header ul {
list-style:none;
margin:0 auto;
width:90%;
}
/* Remove the float: left; property, it interferes with display: inline and
* causes problems. (float: left; makes the element implicitly a block-level
* element. It is still good to use display: inline on it to overcome a bug
* in IE6 and below that doubles horizontal margins for floated elements)
* The styles below is the full style for the list-items.
*/
#header ul li {
color:#CCCCCC;
display:inline;
font-size:20px;
padding-right:20px;
}
I tend to agree that refactoring into a function is usually the best approach for this sort of situation, but for when you really need to break out of nested loops, here's an interesting variant of the exception-raising approach that @S.Lott described. It uses Python's with
statement to make the exception raising look a bit nicer. Define a new context manager (you only have to do this once) with:
from contextlib import contextmanager
@contextmanager
def nested_break():
class NestedBreakException(Exception):
pass
try:
yield NestedBreakException
except NestedBreakException:
pass
Now you can use this context manager as follows:
with nested_break() as mylabel:
while True:
print "current state"
while True:
ok = raw_input("Is this ok? (y/n)")
if ok == "y" or ok == "Y": raise mylabel
if ok == "n" or ok == "N": break
print "more processing"
Advantages: (1) it's slightly cleaner (no explicit try-except block), and (2) you get a custom-built Exception
subclass for each use of nested_break
; no need to declare your own Exception
subclass each time.
Use:
import matplotlib.pyplot as plt
plt.gcf().subplots_adjust(bottom=0.15)
to make room for the label.
Edit:
Since i gave the answer, matplotlib
has added the tight_layout()
function.
So i suggest to use it:
plt.tight_layout()
should make room for the xlabel.
Old post but might help others, Use this way:
OutputStream out = new ByteArrayOutputStream();
...
out.write();
...
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(out.toString().getBytes()));
I like to do the following if running in a script where the function is defined:
POINTER= # used for function return values
my_function() {
# do stuff
POINTER="my_function_return"
}
my_other_function() {
# do stuff
POINTER="my_other_function_return"
}
my_function
RESULT="$POINTER"
my_other_function
RESULT="$POINTER"
I like this, becase I can then include echo statements in my functions if I want
my_function() {
echo "-> my_function()"
# do stuff
POINTER="my_function_return"
echo "<- my_function. $POINTER"
}
I am late for this but i want put some more solution relevant to this.
@GetMapping
public ResponseEntity<List<JSONObject>> getRole() {
return ResponseEntity.ok(service.getRole());
}
There's now also Leaflet, which is built with mobile devices in mind.
There is a Quick Start Guide for leaflet. Besides basic features such as markers, with plugins it also supports routing using an external service.
For a simple map, it is IMHO easier and faster to set up than OpenLayers, yet fully configurable and tweakable for more complex uses.
See ?order
. You just need the last index (or first, in decreasing order), so this should do the trick:
order(matrix[,2],decreasing=T)[1]
A NoClassDefFoundError
is thrown when the JRE can't find a class. In your case, it can't find the class com.google.common.base.Function
, which you most probably did not add to your classpath.
After downloading the following libraries:
and unzipping them and putting all JAR files in a folder called lib
, the test class:
import org.openqa.selenium.firefox.FirefoxDriver;
public class Test {
public static void main(String[] args) {
try{
FirefoxDriver driver = new FirefoxDriver();
driver.get("http:www.yahoo.com");
} catch(Exception e){
e.printStackTrace();
}
}
}
ran without any problems.
You can compile and run the class as follows:
# compile and run on Linux & Mac javac -cp .:lib/* Test.java java -cp .:lib/* Test # compile and run on Windows javac -cp .;lib/* Test.java java -cp .;lib/* Test
From my origin country the currency format is like "3.050,89 €"
parseFloat identifies the dot as the decimal separator, to add 2 values we could put it like these:
parseFloat(element.toString().replace(/\./g,'').replace(',', '.'))
Add C:\Windows\System32\cmd.exe as an external tool. Once run, you can then access it via the normal eclipse console.
http://www.avajava.com/tutorials/lessons/how-do-i-open-a-windows-command-prompt-in-my-console.html
(source: avajava.com)
the simplest option I can suggest is using the schedule library.
In your question, you said "I will need to run a function once every hour" the code to do this is very simple:
import schedule
def thing_you_wanna_do():
...
...
return
schedule.every().hour.do(thing_you_wanna_do)
while True:
schedule.run_pending()
you also asked how to do something at a certain time of the day some examples of how to do this are:
import schedule
def thing_you_wanna_do():
...
...
return
schedule.every().day.at("10:30").do(thing_you_wanna_do)
schedule.every().monday.do(thing_you_wanna_do)
schedule.every().wednesday.at("13:15").do(thing_you_wanna_do)
# If you would like some randomness / variation you could also do something like this
schedule.every(1).to(2).hours.do(thing_you_wanna_do)
while True:
schedule.run_pending()
90% of the code used is the example code of the schedule library. Happy scheduling!
Here is a list what I've found recently searching an answer:
//self name with file extension
echo basename(__FILE__) . '<br>';
//self name without file extension
echo basename(__FILE__, '.php') . '<br>';
//self full url with file extension
echo __FILE__ . '<br>';
//parent file parent folder name
echo basename($_SERVER["REQUEST_URI"]) . '<br>';
//parent file parent folder name with //s
echo $_SERVER["REQUEST_URI"] . '<br>';
// parent file name without file extension
echo basename($_SERVER['PHP_SELF'], ".php") . '<br>';
// parent file name with file extension
echo basename($_SERVER['PHP_SELF']) . '<br>';
// parent file relative url with file etension
echo $_SERVER['PHP_SELF'] . '<br>';
// parent file name without file extension
echo basename($_SERVER["SCRIPT_FILENAME"], '.php') . '<br>';
// parent file name with file extension
echo basename($_SERVER["SCRIPT_FILENAME"]) . '<br>';
// parent file full url with file extension
echo $_SERVER["SCRIPT_FILENAME"] . '<br>';
//self name without file extension
echo pathinfo(__FILE__, PATHINFO_FILENAME) . '<br>';
//self file extension
echo pathinfo(__FILE__, PATHINFO_EXTENSION) . '<br>';
// parent file name with file extension
echo basename($_SERVER['SCRIPT_NAME']);
Don't forget to remove :)
<br>
You can do this:
def deleteContent(pfile):
fn=pfile.name
pfile.close()
return open(fn,'w')
I recently ran into this, because I wanted to inject strings into preformatted JSON. My solution was to create a helper method, like this:
def preformat(msg):
""" allow {{key}} to be used for formatting in text
that already uses curly braces. First switch this into
something else, replace curlies with double curlies, and then
switch back to regular braces
"""
msg = msg.replace('{{', '<<<').replace('}}', '>>>')
msg = msg.replace('{', '{{').replace('}', '}}')
msg = msg.replace('<<<', '{').replace('>>>', '}')
return msg
You can then do something like:
formatted = preformat("""
{
"foo": "{{bar}}"
}""").format(bar="gas")
Gets the job done if performance is not an issue.
I am a beginner in iPhone apps and I still have an issue although I followed the above advices. It looks like POST variables are not received by my server - not sure if it comes from php or objective-c code ...
the objective-c part (coded following Chris' protocol methodo)
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://example.php"]];
// Specify that it will be a POST request
request.HTTPMethod = @"POST";
// This is how we set header fields
[request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSString *stringData = [NSString stringWithFormat:@"user_name=%@&password=%@", self.userNameField.text , self.passwordTextField.text];
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
// Create url connection and fire request
//NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSData *response = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
NSLog(@"Response: %@",[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);
Below the php part :
if (isset($_POST['user_name'],$_POST['password']))
{
// Create connection
$con2=mysqli_connect($servername, $username, $password, $dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
// retrieve POST vars
$username = $_POST['user_name'];
$password = $_POST['password'];
$sql = "INSERT INTO myTable (user_name, password) VALUES ('$username', '$password')";
$retval = mysqli_query( $sql, $con2 );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysqli_close($con2);
}
}
else
{
echo "No data input in php";
}
I have been stuck the last days on this one.
exec(open("./path/to/script.py").read(), globals())
This will execute a script and put all it's global variables in the interpreter's global scope (the normal behavior in most scripting environments).
it should work fine:
var Something = $(this).children("td:nth-child(n)").text();
There are several issues:
getElementsByClassName()
.Example (untested):
<script type="text/javascript">
function hideTd(className){
var elements = document.getElementsByClassName(className);
for(var i = 0, length = elements.length; i < length; i++) {
if( elements[i].textContent == ''){
elements[i].style.display = 'none';
}
}
}
</script>
</head>
<body onload="hideTd('td');">
<table border="1">
<tr>
<td class="td">not empty</td>
</tr>
<tr>
<td class="td"></td>
</tr>
<tr>
<td class="td"></td>
</tr>
</table>
</body>
Note that getElementsByClassName()
is not available up to and including IE8.
Update:
Alternatively you can give the table an ID and use:
var elements = document.getElementById('tableID').getElementsByTagName('td');
to get all td
elements.
To hide the parent row, use the parentNode
property of the element:
elements[i].parentNode.style.display = "none";
functions that implement native code are declared native.
The Java Native Interface (JNI) is a programming framework that enables Java code running in a Java Virtual Machine (JVM) to call, and to be called by, native applications (programs specific to a hardware and operating system platform) and libraries written in other languages such as C, C++ and assembly.
Simpler way (if your only keyword is "code" ) may be:
string ErrorCode = yourString.Split(new string[]{"code"}, StringSplitOptions.None).Last();
i got the same error. it worked with df.fillna(-99999, inplace=True)
before doing any replacement, substitution etc
personally i dont like microsoft......I hate to admit that visual studio is the best IDE i ever use.....Netbeans is gud but drasticaly slow....other free IDEs are useless.. so people try to stick with VS....
Date today = new Date();
today.setHours(0); //same for minutes and seconds
Since the methods are deprecated, you can do this with Calendar
:
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 0); // same for minutes and seconds
And if you need a Date
object in the end, simply call today.getTime()
I was facing the same problem and non of the above solutions helped me. In my Web Api 2
project, I had actually updated my database and had placed a unique constraint
on an SQL table column.
That was actually causing the problem. Simply Checking the the duplicate column values before inserting helped me fix the problem!
Its very simple if you use <MediaElement>
:
<MediaElement Height="113" HorizontalAlignment="Left" Margin="12,12,0,0"
Name="mediaElement1" VerticalAlignment="Top" Width="198" Source="C:\Users\abc.gif"
LoadedBehavior="Play" Stretch="Fill" SpeedRatio="1" IsMuted="False" />
function hasDuplicate($array){
$d = array();
foreach($array as $elements) {
if(!isset($d[$elements])){
$d[$elements] = 1;
}else{
return true;
}
}
return false;
}
The reason you're facing this is due to the difference between composition and aggregation.
In composition, the child object is created when the parent is created and is destroyed when its parent is destroyed. So its lifetime is controlled by its parent. e.g. A blog post and its comments. If a post is deleted, its comments should be deleted. It doesn't make sense to have comments for a post that doesn't exist. Same for orders and order items.
In aggregation, the child object can exist irrespective of its parent. If the parent is destroyed, the child object can still exist, as it may be added to a different parent later. e.g.: the relationship between a playlist and the songs in that playlist. If the playlist is deleted, the songs shouldn't be deleted. They may be added to a different playlist.
The way Entity Framework differentiates aggregation and composition relationships is as follows:
For composition: it expects the child object to a have a composite primary key (ParentID, ChildID). This is by design as the IDs of the children should be within the scope of their parents.
For aggregation: it expects the foreign key property in the child object to be nullable.
So, the reason you're having this issue is because of how you've set your primary key in your child table. It should be composite, but it's not. So, Entity Framework sees this association as aggregation, which means, when you remove or clear the child objects, it's not going to delete the child records. It'll simply remove the association and sets the corresponding foreign key column to NULL (so those child records can later be associated with a different parent). Since your column does not allow NULL, you get the exception you mentioned.
Solutions:
1- If you have a strong reason for not wanting to use a composite key, you need to delete the child objects explicitly. And this can be done simpler than the solutions suggested earlier:
context.Children.RemoveRange(parent.Children);
2- Otherwise, by setting the proper primary key on your child table, your code will look more meaningful:
parent.Children.Clear();
In fact, it is very easy.
composer update
will do all this for you, but it will also update the other packages.
To remove a package without updating the others, specifiy that package in the command, for instance:
composer update monolog/monolog
will remove the monolog/monolog
package.
Nevertheless, there may remain some empty folders or files that cannot be removed automatically, and that have to be removed manually.
All the answers seem correct so I'll go ahead and give a complete answer here.
Firstly, the easiest way to do what you are trying to do is launch a Broadcast in Android when the app is killed manually, and define a custom BroadcastReceiver
to trigger a service restart following that.
Now lets jump into code.
Create your Service in YourService.java
Note the onCreate()
method, where we are starting a foreground service differently for Build versions greater than Android Oreo. This because of the strict notification policies introduced recently where we have to define our own notification channel to display them correctly.
The this.sendBroadcast(broadcastIntent);
in the onDestroy()
method is the statement which asynchronously sends a broadcast with the action name "restartservice"
. We'll be using this later as a trigger to restart our service.
Here we have defined a simple Timer task, which prints a counter value every 1 second in the Log
while incrementing itself every time it prints.
public class YourService extends Service {
public int counter=0;
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
}
@RequiresApi(Build.VERSION_CODES.O)
private void startMyOwnForeground()
{
String NOTIFICATION_CHANNEL_ID = "example.permanence";
String channelName = "Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setContentTitle("App is running in background")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
startTimer();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
stoptimertask();
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("restartservice");
broadcastIntent.setClass(this, Restarter.class);
this.sendBroadcast(broadcastIntent);
}
private Timer timer;
private TimerTask timerTask;
public void startTimer() {
timer = new Timer();
timerTask = new TimerTask() {
public void run() {
Log.i("Count", "========= "+ (counter++));
}
};
timer.schedule(timerTask, 1000, 1000); //
}
public void stoptimertask() {
if (timer != null) {
timer.cancel();
timer = null;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
Create a Broadcast Receiver to respond to your custom defined broadcasts in Restarter.java
The broadcast with the action name "restartservice"
which you just defined in YourService.java
is now supposed to trigger a method which will restart your service. This is done using BroadcastReceiver
in Android.
We override the built-in onRecieve()
method in BroadcastReceiver
to add the statement which will restart the service. The startService()
will not work as intended in and above Android Oreo 8.1, as strict background policies will soon terminate the service after restart once the app is killed. Therefore we use the startForegroundService()
for higher versions and show a continuous notification to keep the service running.
public class Restarter extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("Broadcast Listened", "Service tried to stop");
Toast.makeText(context, "Service restarted", Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context, YourService.class));
} else {
context.startService(new Intent(context, YourService.class));
}
}
}
Define your MainActivity.java
to call the service on app start.
Here we define a separate isMyServiceRunning()
method to check the current status of the background service. If the service is not running, we start it by using startService()
.
Since the app is already running in foreground, we need not launch the service as a foreground service to prevent itself from being terminated.
Note that in onDestroy()
we are dedicatedly calling stopService()
, so that our overridden method gets invoked. If this was not done, then the service would have ended automatically after app is killed without invoking our modified onDestroy()
method in YourService.java
public class MainActivity extends AppCompatActivity {
Intent mServiceIntent;
private YourService mYourService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mYourService = new YourService();
mServiceIntent = new Intent(this, mYourService.getClass());
if (!isMyServiceRunning(mYourService.getClass())) {
startService(mServiceIntent);
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
Log.i ("Service status", "Running");
return true;
}
}
Log.i ("Service status", "Not running");
return false;
}
@Override
protected void onDestroy() {
//stopService(mServiceIntent);
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("restartservice");
broadcastIntent.setClass(this, Restarter.class);
this.sendBroadcast(broadcastIntent);
super.onDestroy();
}
}
Finally register them in your AndroidManifest.xml
All of the above three classes need to be separately registered in AndroidManifest.xml
.
Note that we define an intent-filter
with the action name as "restartservice"
where the Restarter.java
is registered as a receiver
.
This ensures that our custom BroadcastReciever
is called whenever the system encounters a broadcast with the given action name.
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<receiver
android:name="Restarter"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="restartservice" />
</intent-filter>
</receiver>
<activity android:name="MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="YourService"
android:enabled="true" >
</service>
</application>
This should now restart your service again if the app was killed from the task-manager. This service will keep on running in background as long as the user doesn't Force Stop
the app from Application Settings.
UPDATE: Kudos to Dr.jacky for pointing it out. The above mentioned way will only work if the onDestroy()
of the service is called, which might not be the case certain times, which I was unaware of. Thanks.
Did you try this tip?
Or better still, use ipython, and call:
from IPython.Debugger import Tracer; debug_here = Tracer()
then you can just use
debug_here()
whenever you want to set a breakpoint
Despite other answers here, you should not use display:none
to hide the label element.
The accessible way to hide a label visually is to use an 'off-left' or 'clip' rule in your CSS. Using display:none
will prevent people who use screen-readers from having access to the content of the label element. Using display:none hides content from all users, and that includes screen-reader users (who benefit most from label elements).
label[for="foo"] {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
}
The W3C and WAI offer more guidance on this topic, including CSS for the 'clip' technique.
Imports System.Runtime.InteropServices
I got the same issue and this solved it for me. Perhaps this might be a fix for your problem too.
Here is the fix. Follow this link http://www.anindya.com/php-5-4-3-and-php-5-3-13-x64-64-bit-for-windows/
Go to "Fixed curl extensions" and download the extension that matches your PHP version.
Extract and copy "php_curl.dll" to the extension directory of your wamp installation. (i.e. C:\wamp\bin\php\php5.3.13\ext)
Restart Apache
Done!
Refer to: http://blog.nterms.com/2012/07/php-curl-issues-with-wamp-server-on.html
Cheers!
Get your response via a regular http-request, using:
URLConnection con = new URL("http://example.com").openConnection()
;The next step is parsing it. Take a look at this article for a choice of parser.
glOrtho describes a transformation that produces a parallel projection. The current matrix (see glMatrixMode) is multiplied by this matrix and the result replaces the current matrix, as if glMultMatrix were called with the following matrix as its argument:
OpenGL documentation (my bold)
The numbers define the locations of the clipping planes (left, right, bottom, top, near and far).
The "normal" projection is a perspective projection that provides the illusion of depth. Wikipedia defines a parallel projection as:
Parallel projections have lines of projection that are parallel both in reality and in the projection plane.
Parallel projection corresponds to a perspective projection with a hypothetical viewpoint—e.g., one where the camera lies an infinite distance away from the object and has an infinite focal length, or "zoom".
I created a generic solution out of the existing answers which can be reused for any table:
CREATE OR REPLACE FUNCTION create_if_not_exists (table_name text, create_stmt text)
RETURNS text AS
$_$
BEGIN
IF EXISTS (
SELECT *
FROM pg_catalog.pg_tables
WHERE tablename = table_name
) THEN
RETURN 'TABLE ' || '''' || table_name || '''' || ' ALREADY EXISTS';
ELSE
EXECUTE create_stmt;
RETURN 'CREATED';
END IF;
END;
$_$ LANGUAGE plpgsql;
Usage:
select create_if_not_exists('my_table', 'CREATE TABLE my_table (id integer NOT NULL);');
It could be simplified further to take just one parameter if one would extract the table name out of the query parameter. Also I left out the schemas.
In SQL 2005, this is simple: 1. Open SQL Server management studio and copy the sql statement you need into the TSQL , such as exec sp_whatever 2. Query->Results to Grid 3. Highlight the sql statement and run it 4. Highlight the data results (left-click on upper left area of results grid) 5. Now right-click and select Save Results As 6. Select CSV in the Save as type, enter a file name, select a location and click Save.
Easy!
Select A.ARIDNR,A.LIEFNR
from Table A
join Table B
on A.ARIDNR = B.ARIDNR
and A.LIEFNR<> B.LIEFNR
group by A.ARIDNR,A.LIEFNR
You're pretty much correct, but threads share all segments except the stack. Threads have independent call stacks, however the memory in other thread stacks is still accessible and in theory you could hold a pointer to memory in some other thread's local stack frame (though you probably should find a better place to put that memory!).
I recorded a macro with 'Relative References' and this is what I got :
Range("F10").Select
ActiveCell.Offset(0, 3).Range("A1:D11").Select
Heres what I thought : If the range selection is in quotes, VBA really wants a STRING and interprets the cells out of it so tried the following:
Dim MyRange as String
MyRange = "A1:D11"
Range(MyRange).Select
And it worked :) ie.. just create a string using your variables, make sure to dimension it as a STRING variables and Excel will read right off of it ;)
Following tested and found working :
Sub Macro04()
Dim Copyrange As String
Startrow = 1
Lastrow = 11
Let Copyrange = "A" & Startrow & ":" & "D" & Lastrow
Range(Copyrange).Select
End Sub
Please check in your server specification again, if you have changed your port number to something else. And change the port number in your link whatever new port number it is.
Also check whether your server is running properly before you try accessing your localhost.
use this code <script> $('#someid').attr('disabled,'true'); </script>
One important detail to notice is that your data has duplicate index values, so to perform any straightforward comparison we need to turn everything as unique with df.reset_index()
and therefore we can perform selections based on conditions. Once in your case the index is defined, I assume that you would like to keep de index so there are a one-line solution:
[~df2.reset_index().isin(df1.reset_index())].dropna().set_index('Date')
Once the objective from a pythonic perspective is to improve readability, we can break a little bit:
# keep the index name, if it does not have a name it uses the default name
index_name = df.index.name if df.index.name else 'index'
# setting the index to become unique
df1 = df1.reset_index()
df2 = df2.reset_index()
# getting the differences to a Dataframe
df_diff = df2[~df2.isin(df1)].dropna().set_index(index_name)
I also had problem with proximity sensor (I shattered screen in that region on my Nexus 6, Android Marshmallow) and none of proposed solutions / third party apps worked when I tried to disable proximity sensor. What worked for me was to calibrate the sensor using Proximity Sensor Reset/Repair. You have to follow the instruction in app (cover sensor and uncover it) and then restart your phone. Although my sensor is no longer behind the glass, it still showed slightly different results when covered / uncovered and recalibration did the job.
What I tried and didn't work? Proximity Screen Off Lite, Macrodroid and KinScreen.
What would've I tried had it still not worked?[XPOSED] Sensor Disabler, but it requires you to be rooted and have Xposed Framework, so I'm really glad I've found the easier way.
poor man's atomic mass-delete?
maybe you could set them all to EXPIREAT the same second - like a few minutes in the future - and then wait until that time and see them all "self-destruct" at the same time.
but I am not really sure how atomic that would be.
You must be providing the wrong path to the debug.keystore
file.
Follow these steps to get the correct path and complete your command:
And finally, use the path you just copied from Step 3 to construct your command:
For example, in my case, it would be:
C:\Program Files\Java\jre7\bin>keytool -list -v -keystore "C:\Users\Siddharth Lele.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
UPDATED:
If you had already followed the steps mentioned above, the only other solution is to delete the debug.keystore
and let Eclipse recreate it for you.
Step 1: Go to the path where your keystore is stored. In your case, C:\Users\Suresh\.android\debug.keystore
Step 2: Close and restart Eclipse.
Step 3 (Optional): You may need to clean your project before the debug.keystore
is created again.
Source: http://www.coderanch.com/t/440920/Security/KeyTool-genkeypair-exception-Keystore-file
You can refer to this for the part about deleting your debug.keystore
file: "Debug certificate expired" error in Eclipse Android plugins
file_get_contents()
is a simple screwdriver. Great for simple GET requests where the header, HTTP request method, timeout, cookiejar, redirects, and other important things do not matter.
fopen()
with a stream context or cURL with setopt are powerdrills with every bit and option you can think of.
2’s Complements: When we add an extra one with the 1’s complements of a number we will get the 2’s complements. For example: 100101 it’s 1’s complement is 011010 and 2’s complement is 011010+1 = 011011 (By adding one with 1's complement) For more information this article explain it graphically.
When including files in PHP, it acts like the code exists within the file they are being included from. Imagine copy and pasting the code from within each of your included files directly into your index.php
. That is how PHP works with includes.
So, in your example, since you've set a variable called $name
in your front.inc
file, and then included both front.inc
and end.inc
in your index.php
, you will be able to echo
the variable $name
anywhere after the include
of front.inc
within your index.php
. Again, PHP processes your index.php
as if the code from the two files you are including are part of the file.
When you place an echo
within an included file, to a variable that is not defined within itself, you're not going to get a result because it is treated separately then any other included file.
In other words, to do the behavior you're expecting, you will need to define it as a global.
Find the below-mentioned code, it might be helpful for you.
val stringDate = spark.sparkContext.parallelize(Seq("12/16/2019")).toDF("StringDate")
val dateCoversion = stringDate.withColumn("dateColumn", to_date(unix_timestamp($"StringDate", "dd/mm/yyyy").cast("Timestamp")))
dateCoversion.show(false)
+----------+----------+
|StringDate|dateColumn|
+----------+----------+
|12/16/2019|2019-01-12|
+----------+----------+
Be careful if you use fat arrow functions as you will get undefined for this.id Wasted 10 minutes today wondering what the hell was going on
Add a column to your existing data to get rid of the hour:minute:second time stamp on each row:
=DATE(YEAR(A1), MONTH(A1), DAY(A1))
Extend this down the length of your data. Even easier: quit collecting the hh:mm:ss data if you don't need it. Assuming your date/time was in column A, and your value was in column B, you'd put the above formula in column C, and auto-extend it for all your data.
Now, in another column (let's say E), create a series of dates corresponding to each day of the specific month you're interested in. Just type the first date, (for example, 10/7/2016 in E1), and auto-extend. Then, in the cell next to the first date, F1, enter:
=SUMIF(C:C, E1, B:B )
autoextend the formula to cover every date in the month, and you're done. Begin at 1/1/2016, and auto-extend for the whole year if you like.
double minutes = varTime.TotalMinutes;
int minutesRounded = (int)Math.Round(varTime.TotalMinutes);
TimeSpan.TotalMinutes: The total number of minutes represented by this instance.
Numpy is required by pandas (and by virtually all numerical tools for Python). Scipy is not strictly required for pandas but is listed as an "optional dependency". I wouldn't say that pandas is an alternative to Numpy and/or Scipy. Rather, it's an extra tool that provides a more streamlined way of working with numerical and tabular data in Python. You can use pandas data structures but freely draw on Numpy and Scipy functions to manipulate them.
You need to make both your method - printMenu()
and getUserChoice()
static
, as you are directly invoking them from your static main
method, without creating an instance of the class, those methods are defined in. And you cannot invoke a non-static
method without any reference to an instance of the class they are defined in.
Alternatively you can change the method invocation part to:
BookStoreApp2 bookStoreApp = new BookStoreApp2();
bookStoreApp.printMenu();
bookStoreApp.getUserChoice();
Node.JS to install a new version.
Step 1 : NVM Install
npm i -g nvm
Step 2 : NODE Newest version install
nvm install *.*.*(NodeVersion)
Step 3 : Selected Node Version
nvm use *.*.*(NodeVersion)
Finish
You can use the 'attributes' method:
@car.attributes = {:model => 'Sierra', :years => '1990', :looks => 'Sexy'}
Source: http://api.rubyonrails.org/classes/ActiveRecord/Base.html
attributes=(new_attributes, guard_protected_attributes = true) Allows you to set all the attributes at once by passing in a hash with keys matching the attribute names (which again matches the column names).
If guard_protected_attributes is true (the default), then sensitive attributes can be protected from this form of mass-assignment by using the attr_protected macro. Or you can alternatively specify which attributes can be accessed with the attr_accessible macro. Then all the attributes not included in that won’t be allowed to be mass-assigned.
class User < ActiveRecord::Base
attr_protected :is_admin
end
user = User.new
user.attributes = { :username => 'Phusion', :is_admin => true }
user.username # => "Phusion"
user.is_admin? # => false
user.send(:attributes=, { :username => 'Phusion', :is_admin => true }, false)
user.is_admin? # => true
Hosting a nodejs site through apache can be organized with apache proxy module.
It's better to start nodejs server on localhost with default port 1337
Enable proxy with a command:
sudo a2enmod proxy proxy_http
Do not enable proxying with ProxyRequests until you have secured your server. Open proxy servers are dangerous both to your network and to the Internet at large. Setting ProxyRequests to Off does not disable use of the ProxyPass directive.
Configure /etc/apche2/sites-availables with
<VirtualHost *:80>
ServerAdmin [email protected]
ServerName site.com
ServerAlias www.site.com
ProxyRequests off
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
<Location />
ProxyPass http://localhost:1337/
ProxyPassReverse http://localhost:1337/
</Location>
</VirtualHost>
and restart apache2 service.