In my case (im using Firebase Cloud Functions) i opened .eslintrc.json
and changed:
"parserOptions": {
// Required for certain syntax usages
"ecmaVersion": 2017
},
to:
"parserOptions": {
// Required for certain syntax usages
"ecmaVersion": 2020
},
ffmpeg -i <input.mp4> -b:v 2048k -s 1000x600 -fs 2048k -vcodec mpeg4 -acodec copy <output.mp4>
-i input file
-b:v videobitrate of output video in kilobytes (you have to try)
-s dimensions of output video
-fs FILESIZE of output video in kilobytes
-vcodec videocodec (use ffmpeg -codecs
to list all available codecs)
if your input's id is following
<input type='text' id='kg_row1' >
then you can get explode/split the above with the following function of split in jquery
var kg_id = $(this).attr("id");
var getvalues =kg_id.split("_");
var id = getvalues[1];
Here's what I think is a better method:
public int getYearsBetweenDates(Date first, Date second) {
Calendar firstCal = GregorianCalendar.getInstance();
Calendar secondCal = GregorianCalendar.getInstance();
firstCal.setTime(first);
secondCal.setTime(second);
secondCal.add(Calendar.DAY_OF_YEAR, 1 - firstCal.get(Calendar.DAY_OF_YEAR));
return secondCal.get(Calendar.YEAR) - firstCal.get(Calendar.YEAR);
}
EDIT
Apart from a bug which I fixed, this method does not work well with leap years. Here's a complete test suite. I guess you're better off using the accepted answer.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
class YearsBetweenDates {
public static int getYearsBetweenDates(Date first, Date second) {
Calendar firstCal = GregorianCalendar.getInstance();
Calendar secondCal = GregorianCalendar.getInstance();
firstCal.setTime(first);
secondCal.setTime(second);
secondCal.add(Calendar.DAY_OF_YEAR, 1 - firstCal.get(Calendar.DAY_OF_YEAR));
return secondCal.get(Calendar.YEAR) - firstCal.get(Calendar.YEAR);
}
private static class TestCase {
public Calendar date1;
public Calendar date2;
public int expectedYearDiff;
public String comment;
public TestCase(Calendar date1, Calendar date2, int expectedYearDiff, String comment) {
this.date1 = date1;
this.date2 = date2;
this.expectedYearDiff = expectedYearDiff;
this.comment = comment;
}
}
private static TestCase[] tests = {
new TestCase(
new GregorianCalendar(2014, Calendar.JULY, 15),
new GregorianCalendar(2015, Calendar.JULY, 15),
1,
"exactly one year"),
new TestCase(
new GregorianCalendar(2014, Calendar.JULY, 15),
new GregorianCalendar(2017, Calendar.JULY, 14),
2,
"one day less than 3 years"),
new TestCase(
new GregorianCalendar(2015, Calendar.NOVEMBER, 3),
new GregorianCalendar(2017, Calendar.MAY, 3),
1,
"a year and a half"),
new TestCase(
new GregorianCalendar(2016, Calendar.JULY, 15),
new GregorianCalendar(2017, Calendar.JULY, 15),
1,
"leap years do not compare correctly"),
};
public static void main(String[] args) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
for (TestCase t : tests) {
int diff = getYearsBetweenDates(t.date1.getTime(), t.date2.getTime());
String result = diff == t.expectedYearDiff ? "PASS" : "FAIL";
System.out.println(t.comment + ": " +
df.format(t.date1.getTime()) + " -> " +
df.format(t.date2.getTime()) + " = " +
diff + ": " + result);
}
}
}
I believe this is the fastest query that answers your question, because it doesn't use an interpreted $where
clause:
{$nor: [
{name: {$exists: false}},
{name: {$size: 0}},
{name: {$size: 1}}
]}
It means "all documents except those without a name (either non existant or empty array) or with just one name."
Test:
> db.test.save({})
> db.test.save({name: []})
> db.test.save({name: ['George']})
> db.test.save({name: ['George', 'Raymond']})
> db.test.save({name: ['George', 'Raymond', 'Richard']})
> db.test.save({name: ['George', 'Raymond', 'Richard', 'Martin']})
> db.test.find({$nor: [{name: {$exists: false}}, {name: {$size: 0}}, {name: {$size: 1}}]})
{ "_id" : ObjectId("511907e3fb13145a3d2e225b"), "name" : [ "George", "Raymond" ] }
{ "_id" : ObjectId("511907e3fb13145a3d2e225c"), "name" : [ "George", "Raymond", "Richard" ] }
{ "_id" : ObjectId("511907e3fb13145a3d2e225d"), "name" : [ "George", "Raymond", "Richard", "Martin" ] }
>
I'm not sure if returning the address of the thing pointed by the iterator is needed. All you need is the pointer itself. You will see STL's iterator class itself implementing the use of _Ptr for this purpose. So, just do:
return iterator._Ptr;
This error also happens if you're using a self-signed certificate with a keyUsage
missing the value keyCertSign
.
You're not looping over the items. Try this instead:
$.getJSON(url, function(data){
$.each(data.response.venue.tips.groups.items, function (index, value) {
console.log(this.text);
});
});
If you can't change the HTML layout:
.full-width {
width: 100vw;
margin-left: -50vw;
left: 50%;
}
<div class="container">
<div class="row">
<div class="col-xs-12">a</div>
<div class="col-xs-12">b</div>
<div class="col-xs-12 full-width">c</div>
<div class="col-xs-12">d</div>
</div>
</div>
The ul.nav li is more restrictive and so takes precedence, try this:
ul.nav li.selected {
background-color:red;
}
If you are consuming an internal service via AJAX, make sure the url points to https, this cleared up the error for me.
Initial AJAX URL: "http://XXXXXX.com/Core.svc/" + ApiName
Corrected AJAX URL: "https://XXXXXX.com/Core.svc/" + ApiName,
MY PREFERRED METHOD is using fopen,fwrite and fclose [it will cost less CPU]
$f=fopen('myfile.txt','w');
fwrite($f,'new content');
fclose($f);
Warning for those using file_put_contents
It'll affect a lot in performance, for example [on the same class/situation] file_get_contents too: if you have a BIG FILE, it'll read the whole content in one shot and that operation could take a long waiting time
I was just trying to fix same error, I finally fixed it, so I will copy to you part of the code, maybe it helps you.
<input type="text" name="usu" id="usu" value="<?php echo $usu;?>" ></input>
<input type="text" name="pass" id="pass" value="<?php echo $varpass;?>"></input>
those are the inputs I wanted to clean after pressing my button.
And here php code:
$query= "INSERT INTO usuarios (tipo, usuario, password) VALUES ('".$vartipo."', '".$usu."', '".$varpass."')";
if (!mysqli_query($conexion,$query)){
die('Error: ' . mysqli_error($conexion));
}
else{
$usu = '';
$varpass= '';
$result = '<div class="result_ok">El usuario se ha registrado con éxito! <div>';
}
$usu = '';
$varpass= '';
those are the lines that cleans the inputs :D
okay, i know this is way too late. but i had the same requirement. i solved like this
1.First create a xml file (example: border_shadow.xml) in "drawable" folder and copy the below code into it.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<item>
<shape>
<!-- set the shadow color here -->
<stroke
android:width="2dp"
android:color="#7000" />
<!-- setting the thickness of shadow (positive value will give shadow on that side) -->
<padding
android:bottom="2dp"
android:left="2dp"
android:right="-1dp"
android:top="-1dp" />
<corners android:radius="3dp" />
</shape>
</item>
<!-- Background -->
<item>
<shape>
<solid android:color="#fff" />
<corners android:radius="3dp" />
</shape>
</item>
2.now on the layout where you want the shadow(example: LinearLayout) add this in android:background
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="8dip"
android:background="@drawable/border_shadow"
android:orientation="vertical">
and that worked for me.
you can just set the selectedBackgroundView of the cell to be backgroundColor=x.
Now any time you tap on cell his selected mode will change automatically and will couse to the background color to change to x.
it will work if you put it as below:
AA='first line
\nsecond line
\nthird line'
echo $AA
output:
first line
second line
third line
I think you are over complicated things a bit. Do you really need to trigger a click on the input from your button ?
I suggest you just apply a proper style to your input and the ngFileSelect directive will do the rest and call your onFileSelect function whenever a file is submitted :
input.file {
cursor: pointer;
direction: ltr;
font-size: 23px;
margin: 0;
opacity: 0;
position: absolute;
right: 0;
top: 0;
transform: translate(-300px, 0px) scale(4);
}
You have two options:
Option 1: Command line. You can run the following command
node '/Users/complete-path-to-you-project/your-project/node_modules/.bin/jest' '/Users/complete-path-to-you-project/your-project/path-to-your-file-within-the-project/your-file.spec.ts'
This avoids you to install Jest globally. You use the jest used by your project.
Option 2: If you are using Visual Studio Code you have a great plugin to do this: Jest Runner. It allows you not only to run tests file by file, but even specific suites and specs just by a right click on the tests you want to run.
The number one mistake you can make is creating a globally accessible class called with a generic name, like Constants. This simply gets littered with garbage and you lose all ability to figure out what portion of your system uses these constants.
Instead, constants should go into the class which "owns" them. Do you have a constant called TIMEOUT? It should probably go into your Communications() or Connection() class. MAX_BAD_LOGINS_PER_HOUR? Goes into User(). And so on and so forth.
The other possible use is Java .properties files when "constants" can be defined at run-time, but not easily user changeable. You can package these up in your .jars and reference them with the Class resourceLoader.
While value types have default values and can not be null, they also need to be explicitly initialized in order to be used. You can think of these two rules as side by side rules.
Value types can not be null ? the compiler guarantees that. If you ask how, the error message you got is the answer. Once you call their constructors, they got initialized with their default values.
int tmpCnt; // Not accepted
int tmpCnt = new Int(); // Default value applied tmpCnt = 0
I am using nano editor in a Raspberry Pi with Italian OS language and Italian keyboard. Don't know the exact reason, but in this environment the shortcut is:
Ctrl+-
Example: Display different output depending on whether the user is logged in or not.
<?php
if ( is_user_logged_in() ) {
echo 'Welcome, registered user!';
} else {
echo 'Welcome, visitor!';
}
?>
.erb-image-wrapper img{
max-width:100% !important;
height:auto;
display:block;
}
Worked for me.
Thanks for MrMisterMan for his assistance.
The best way is to use closures
, because the window
object gets very, very cluttered with properties.
HTML
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="init.js"></script>
<script type="text/javascript">
MYLIBRARY.init(["firstValue", 2, "thirdValue"]);
</script>
<script src="script.js"></script>
</head>
<body>
<h1>Hello !</h1>
</body>
</html>
init.js (based on this answer)
var MYLIBRARY = MYLIBRARY || (function(){
var _args = {}; // Private
return {
init : function(Args) {
_args = Args;
// Some other initialising
},
helloWorld : function(i) {
return _args[i];
}
};
}());
script.js
// Here you can use the values defined in the HTML content as if it were a global variable
var a = "Hello World " + MYLIBRARY.helloWorld(2);
alert(a);
Here's the plnkr. Hope it help !
personally I favor validating without a callback:
public bool ValidateSchema(string xmlPath, string xsdPath)
{
XmlDocument xml = new XmlDocument();
xml.Load(xmlPath);
xml.Schemas.Add(null, xsdPath);
try
{
xml.Validate(null);
}
catch (XmlSchemaValidationException)
{
return false;
}
return true;
}
(see Timiz0r's post in Synchronous XML Schema Validation? .NET 3.5)
Using array_column to re-index will save time if you need to find multiple times:
$lookup = array_column($arr, NULL, 'id'); // re-index by 'id'
Then you can simply $lookup[$id]
at will.
If you start out with:
let array = [
{name: "malcom", dogType: "four-legged"},
{name: "peabody", dogType: "three-legged"},
{name: "pablo", dogType: "two-legged"}
];
And you want a set of, say, names, you would do:
let namesSet = new Set(array.map(item => item.name));
List<String> whatever_list = df.toJavaRDD().map(new Function<Row, String>() {
public String call(Row row) {
return row.getAs("column_name").toString();
}
}).collect();
logger.info(String.format("list is %s",whatever_list)); //verification
Since no one has given any solution in java(Real Programming Language) Can thank me later
//this is a very basic way of how to order a string alpha-wise, this does not use anything fancy and is great for school use
package string_sorter;
public class String_Sorter {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String word = "jihgfedcba";
for (int endOfString = word.length(); endOfString > 0; endOfString--) {
int largestWord = word.charAt(0);
int location = 0;
for (int index = 0; index < endOfString; index++) {
if (word.charAt(index) > largestWord) {
largestWord = word.charAt(index);
location = index;
}
}
if (location < endOfString - 1) {
String newString = word.substring(0, location) + word.charAt(endOfString - 1) + word.substring(location + 1, endOfString - 1) + word.charAt(location);
word = newString;
}
System.out.println(word);
}
System.out.println(word);
}
}
For second accuracy, yyyy-MM-dd HH:mm:ss should do the trick.
I believe Excel is not very good with fractions of a second (loses them when interacting with COM object IIRC).
Try setting the system default encoding as utf-8
at the start of the script, so that all strings are encoded using that.
Example -
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
The above should set the default encoding as utf-8
.
Except for the first time, each time a word is seen the if statement's test fails. If you are counting a large number of words, many will probably occur multiple times. In a situation where the initialization of a value is only going to occur once and the augmentation of that value will occur many times it is cheaper to use a try statement:
urls_d = {}
for url in list_of_urls:
try:
urls_d[url] += 1
except KeyError:
urls_d[url] = 1
you can read more about this: https://wiki.python.org/moin/PythonSpeed/PerformanceTips
You can now use fetch API/ It returns redirected: *boolean*
You can't use same id for multiple elements in a document. Keep the ids different and name same for the elements.
<input type="text" id="task1" name="task" />
<input type="text" id="task2" name="task" />
<input type="text" id="task3" name="task" />
<input type="text" id="task4" name="task" />
<input type="text" id="task5" name="task" />
var newArray = new Array();
$("input:text[name=task]").each(function(){
newArray.push($(this));
});
simple approach:
List<int>[] a = new List<int>[100];
for (int i = 0; i < a.Length; i++)
{
a[i] = new List<int>();
}
or LINQ
approach
var b = Enumerable.Range(0,100).Select((i)=>new List<int>()).ToArray();
For getting all the info about the cordova package use this command:
npm info cordova
$('#test').click(function() {_x000D_
var startDate = moment("01.01.2019", "DD.MM.YYYY");_x000D_
var endDate = moment("01.02.2019", "DD.MM.YYYY");_x000D_
_x000D_
var result = 'Diff: ' + endDate.diff(startDate, 'days');_x000D_
_x000D_
$('#result').html(result);_x000D_
});
_x000D_
#test {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: #ffb;_x000D_
padding: 10px;_x000D_
border: 2px solid #999;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>_x000D_
_x000D_
<div id='test'>Click Me!!!</div>_x000D_
<div id='result'></div>
_x000D_
For those who tried gkalpak answer and it did not work,
be aware that chrome will add the content script to a needed page only when your extension enabled during chrome launch and also a good idea restart browser after making these changes
What I did was created a validator that did the samething as angular for minLength except I added the trim()
import { Injectable } from '@angular/core';
import { AbstractControl, ValidatorFn, Validators } from '@angular/forms';
@Injectable()
export class ValidatorHelper {
///This is the guts of Angulars minLength, added a trim for the validation
static minLength(minLength: number): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } => {
if (ValidatorHelper.isPresent(Validators.required(control))) {
return null;
}
const v: string = control.value ? control.value : '';
return v.trim().length < minLength ?
{ 'minlength': { 'requiredLength': minLength, 'actualLength': v.trim().length } } :
null;
};
}
static isPresent(obj: any): boolean {
return obj !== undefined && obj !== null;
}
}
I then in my app.component.ts overrode the minLength function provided by angular.
import { Component, OnInit } from '@angular/core';
import { ValidatorHelper } from 'app/common/components/validators/validator-helper';
import { Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
constructor() { }
ngOnInit(): void {
Validators.minLength = ValidatorHelper.minLength;
}
}
Now everywhere angular's minLength built in validator is used, it will use the minLength that you have created in the helper.
Validators.compose([
Validators.minLength(2)
]);
As simple as you can use const adults = family.filter(({ age }) => age > 18 );
const family =[{"name":"Jack", "age": 26},_x000D_
{"name":"Jill", "age": 22},_x000D_
{"name":"James", "age": 5 },_x000D_
{"name":"Jenny", "age": 2 }];_x000D_
_x000D_
const adults = family.filter(({ age }) => age > 18 );_x000D_
_x000D_
console.log(adults)
_x000D_
This is by far the best SQLite library that I've used in Swift: https://github.com/stephencelis/SQLite.swift
Look at the code examples. So much cleaner than the C API:
import SQLite
let db = try Connection("path/to/db.sqlite3")
let users = Table("users")
let id = Expression<Int64>("id")
let name = Expression<String?>("name")
let email = Expression<String>("email")
try db.run(users.create { t in
t.column(id, primaryKey: true)
t.column(name)
t.column(email, unique: true)
})
// CREATE TABLE "users" (
// "id" INTEGER PRIMARY KEY NOT NULL,
// "name" TEXT,
// "email" TEXT NOT NULL UNIQUE
// )
let insert = users.insert(name <- "Alice", email <- "[email protected]")
let rowid = try db.run(insert)
// INSERT INTO "users" ("name", "email") VALUES ('Alice', '[email protected]')
for user in try db.prepare(users) {
print("id: \(user[id]), name: \(user[name]), email: \(user[email])")
// id: 1, name: Optional("Alice"), email: [email protected]
}
// SELECT * FROM "users"
let alice = users.filter(id == rowid)
try db.run(alice.update(email <- email.replace("mac.com", with: "me.com")))
// UPDATE "users" SET "email" = replace("email", 'mac.com', 'me.com')
// WHERE ("id" = 1)
try db.run(alice.delete())
// DELETE FROM "users" WHERE ("id" = 1)
try db.scalar(users.count) // 0
// SELECT count(*) FROM "users"
The documentation also says that "SQLite.swift also works as a lightweight, Swift-friendly wrapper over the C API," and follows with some examples of that.
Open the eclipse.ini
file from your eclipse folder.
It has some of add on configuration . Find the line –launcher.XXMaxPermSize
. Now remove the the default value 256m and save it.
For anyone encountering a similar situation I was able to solve the issue above as follows:
Regenerate your pkcs12 file as follows:
openssl pkcs12 -in oldpkcs.p12 -out keys -passout pass:tmp
openssl pkcs12 -in keys -export -out new.p12 -passin pass:tmp -passout pass:newpasswd
Import the CA certificate from server into a TrustStore ( either your own, or the java keystore in $JAVA_HOME/jre/lib/security/cacerts
, password: changeit
).
Set the following system properties:
System.setProperty("javax.net.ssl.trustStore", "myTrustStore");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
System.setProperty("javax.net.ssl.keyStoreType", "pkcs12");
System.setProperty("javax.net.ssl.keyStore", "new.p12");
System.setProperty("javax.net.ssl.keyStorePassword", "newpasswd");
Test ur url.
Courtesy@ http://forums.sun.com/thread.jspa?threadID=5296333
In simple words: You do abstraction when deciding what to implement. You do encapsulation when hiding something that you have implemented.
You could do something like this:
htmlComponent.ts
htmlVariable: string = "<b>Some html.</b>";
//this is html in TypeScript code that you need to display
htmlComponent.html
<div [innerHtml]="htmlVariable"></div>
//this is how you display html code from TypeScript in your html
There are many suggestions but I found two of them most common.
I first tried export JAVA_OPTS="-Dhttps.protocols=SSLv3,TLSv1,TLSv1.1,TLSv1.2"
on command line before startup of program but it didn't work for me.
Then I added the following code in the startup class constructor and it worked for me.
try {
SSLContext ctx = SSLContext.getInstance("TLSv1.2");
ctx.init(null, null, null);
SSLContext.setDefault(ctx);
} catch (Exception e) {
System.out.println(e.getMessage());
}
Frankly, I don't know in detail why ctx.init(null, null, null);
but all (SSL/TLS) is working fine for me.
There is one more option: System.setProperty("https.protocols", "SSLv3,TLSv1,TLSv1.1,TLSv1.2");
. It will also go in code but I've not tried it.
If possible try this one instant solution:
Intent intent =new Intent(getApplicationBaseContext,second_Act.class);
StartActivity(intent);
JPQL mostly is case-insensitive. One of the things that is case-sensitive is Java entity names. Change your query to:
"SELECT r FROM FooBar r"
Try this:
function PluginUrl() {
//Try to use WP API if possible, introduced in WP 2.6
if (function_exists('plugins_url')) return trailingslashit(plugins_url(basename(dirname(__FILE__))));
//Try to find manually... can't work if wp-content was renamed or is redirected
$path = dirname(__FILE__);
$path = str_replace("\\","/",$path);
$path = trailingslashit(get_bloginfo('wpurl')) . trailingslashit(substr($path,strpos($path,"wp-content/")));
return $path;
}
echo PluginUrl(); will return the current plugin url.
This allows you to just get the image data and set to the img src, which is cool.
var oReq = new XMLHttpRequest();
oReq.open("post", '/somelocation/getmypic', true );
oReq.responseType = "blob";
oReq.onload = function ( oEvent )
{
var blob = oReq.response;
var imgSrc = URL.createObjectURL( blob );
var $img = $( '<img/>', {
"alt": "test image",
"src": imgSrc
} ).appendTo( $( '#bb_theImageContainer' ) );
window.URL.revokeObjectURL( imgSrc );
};
oReq.send( null );
The basic idea is that the data is returned untampered with, it is placed in a blob and then a url is created to that object in memory. See here and here. Note supported browsers.
You can Try this ,
Here you can get the date based on the Client Timezone (Browser).
moment(new Date().getTime()).zone(new Date().toString().match(/([-\+][0-9]+)\s/)[1]).format('YYYY-MM-DD HH:mm:ss')
The regex basically gets you the offset value.
Cheers!!
Non-matched part of the URL is exposed as a request attribute named HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE
:
@RequestMapping("/{id}/**")
public void foo(@PathVariable("id") int id, HttpServletRequest request) {
String restOfTheUrl = (String) request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
...
}
If you have several figures or subplots that you want to modify, it can be helpful to use the matplotlib context manager to change the color, instead of changing each one individually. The context manager allows you to temporarily change the rc parameters only for the immediately following indented code, but does not affect the global rc parameters.
This snippet yields two figures, the first one with modified colors for the axis, ticks and ticklabels, and the second one with the default rc parameters.
import matplotlib.pyplot as plt
with plt.rc_context({'axes.edgecolor':'orange', 'xtick.color':'red', 'ytick.color':'green', 'figure.facecolor':'white'}):
# Temporary rc parameters in effect
fig, (ax1, ax2) = plt.subplots(1,2)
ax1.plot(range(10))
ax2.plot(range(10))
# Back to default rc parameters
fig, ax = plt.subplots()
ax.plot(range(10))
You can type plt.rcParams
to view all available rc parameters, and use list comprehension to search for keywords:
# Search for all parameters containing the word 'color'
[(param, value) for param, value in plt.rcParams.items() if 'color' in param]
Be careful: while the string representations for .NET Guid and (RFC4122) UUID are identical, the storage format is not. .NET trades in little-endian bytes for the first three Guid
parts.
If you are transmitting the bytes (for example, as base64), you can't just use Guid.ToByteArray()
and encode it. You'll need to Array.Reverse
the first three parts (Data1-3).
I do it this way:
var rfc4122bytes = Convert.FromBase64String("aguidthatIgotonthewire==");
Array.Reverse(rfc4122bytes,0,4);
Array.Reverse(rfc4122bytes,4,2);
Array.Reverse(rfc4122bytes,6,2);
var guid = new Guid(rfc4122bytes);
See this answer for the specific .NET implementation details.
Edit: Thanks to Jeff Walker, Code Ranger, for pointing out that the internals are not relevant to the format of the byte array that goes in and out of the byte-array constructor and ToByteArray()
.
Simple way is checking the length is equal zero.
if len(a) == 0:
print("a is empty")
Making a class abstract
sends a message to the readers of your code that you want users of your abstract
class to subclass it. However, this is not what you want then to do: a utility class should not be subclassed.
Therefore, adding a private constructor is a better choice here. You should also make the class final
to disallow subclassing of your utility class.
The functions getElementById
and getElementsByClassName
are very specific, while querySelector
and querySelectorAll
are more elaborate. My guess is that they will actually have a worse performance.
Also, you need to check for the support of each function in the browsers you are targetting. The newer it is, the higher probability of lack of support or the function being "buggy".
A minor but notable advantage of a list over a tuple is that lists tend to be slightly more portable. Standard tools are less likely to support tuples. JSON, for example, does not have a tuple type. YAML does, but its syntax is ugly compared to its list syntax, which is quite nice.
In those cases, you may wish to use a tuple internally then convert to list as part of an export process. Alternately, you might want to use lists everywhere for consistency.
Very Simple to clear editText values.when u click button then only follow 1 line code.
Inside button or anywhere u want.Only use this
editText.setText("");
They are called the ternary operator since they are the only one in Java.
The difference to the if...else construct is, that they return something, and this something can be anything:
int k = a > b ? 7 : 8;
String s = (foobar.isEmpty ()) ? "empty" : foobar.toString ();
It failed because you used ajax="false"
. This fires a full synchronous request which in turn causes a full page reload, causing the oncomplete
to be never fired (note that all other ajax-related attributes like process
, onstart
, onsuccess
, onerror
and update
are also never fired).
That it worked when you removed actionListener
is also impossible. It should have failed the same way. Perhaps you also removed ajax="false"
along it without actually understanding what you were doing. Removing ajax="false"
should indeed achieve the desired requirement.
Also is it possible to execute actionlistener and oncomplete simultaneously?
No. The script can only be fired before or after the action listener. You can use onclick
to fire the script at the moment of the click. You can use onstart
to fire the script at the moment the ajax request is about to be sent. But they will never exactly simultaneously be fired. The sequence is as follows:
onclick
JavaScript code is executedprocess
and current HTML DOM treeonstart
JavaScript code is executedprocess
actionListener
JSF backing bean method is executedaction
JSF backing bean method is executedupdate
and current JSF component treeonsuccess
JavaScript code is executedonerror
JavaScript code is executedupdate
based on ajax response and current HTML DOM treeoncomplete
JavaScript code is executedNote that the update
is performed after actionListener
, so if you were using onclick
or onstart
to show the dialog, then it may still show old content instead of updated content, which is poor for user experience. You'd then better use oncomplete
instead to show the dialog. Also note that you'd better use action
instead of actionListener
when you intend to execute a business action.
#input {
margin:0 0 10px 0;
}
.shape() gives the actual shape of your array in terms of no of elements in it, No of rows/No of Columns. The answer you get is in the form of tuples.
For Example: 1D ARRAY:
d=np.array([1,2,3,4])
print(d)
(1,)
Output: (4,) ie the number4 denotes the no of elements in the 1D Array.
2D Array:
e=np.array([[1,2,3],[4,5,6]])
print(e)
(2,3)
Output: (2,3) ie the number of rows and the number of columns.
The number of elements in the final output will depend on the number of rows in the Array....it goes on increasing gradually.
I wrote a simple ini config library in golang.
goroutine-safe, easy to use
package cfg
import (
"testing"
)
func TestCfg(t *testing.T) {
c := NewCfg("test.ini")
if err := c.Load() ; err != nil {
t.Error(err)
}
c.WriteInt("hello", 42)
c.WriteString("hello1", "World")
v, err := c.ReadInt("hello", 0)
if err != nil || v != 42 {
t.Error(err)
}
v1, err := c.ReadString("hello1", "")
if err != nil || v1 != "World" {
t.Error(err)
}
if err := c.Save(); err != nil {
t.Error(err)
}
}
===================Update=======================
Recently I need an INI parser with section support, and I write a simple package:
github.com/c4pt0r/cfg
u can parse INI like using "flag" package:
package main
import (
"log"
"github.com/c4pt0r/ini"
)
var conf = ini.NewConf("test.ini")
var (
v1 = conf.String("section1", "field1", "v1")
v2 = conf.Int("section1", "field2", 0)
)
func main() {
conf.Parse()
log.Println(*v1, *v2)
}
In Linux, there is different escape sequences for control terminal. For example, there is special escape sequence for erase whole line: \33[2K
and for move cursor to previous line: \33[1A
. So all you need is to print this every time you need to refresh the line. Here is the code which prints Line 1 (second variant)
:
System.out.println("Line 1 (first variant)");
System.out.print("\33[1A\33[2K");
System.out.println("Line 1 (second variant)");
There are codes for cursor navigation, clearing screen and so on.
I think there are some libraries which helps with it (ncurses
?).
I recently had a similar problem and ended up fixing it using a mixture of different solutions.
The first and most simple one was to use two tables, one for the headers and one for the body. This works but the headers and the body columns are not aligned. And, since I wanted to use the auto-size that comes with twitter bootstrap tables I ended up creating a Javascript function that changes the headers when: the body is rendered; the windows is resized; the data in the column changes, etc.
Here is some of the code I used:
<table class="table table-striped table-hover" style="margin-bottom: 0px;">
<thead>
<tr>
<th data-sort="id">Header 1</i></th>
<th data-sort="guide">Header 2</th>
<th data-sort="origin">Header 3</th>
<th data-sort="supplier">Header 4</th>
</tr>
</thead>
</table>
<div class="bodycontainer scrollable">
<table class="table table-hover table-striped table-scrollable">
<tbody id="rows"></tbody>
</table>
</div>
The headers and the body are divided in two separate tables. One of them is inside a DIV with the necessary style to generate the vertical scrollbars. Here is the CSS I used:
.bodycontainer {
//height: 200px
width: 100%;
margin: 0;
}
.table-scrollable {
margin: 0px;
padding: 0px;
}
I commented the height here because I a wanted the table to reach the bottom of the page, whatever the page height might be.
The data-sort attributes I used in the headers are also used in every td. This way I could get the width and the padding of every td and the width of the row. Using the data-sort attributes I set using CSS the padding and width of each header accordingly and of the header row which is always bigger since it doesn´t have a scrollbar. Here is the function using coffeescript:
fixHeaders: =>
for header, i in @headers
tdpadding = parseInt(@$("td[data-sort=#{header}]").css('padding'))
tdwidth = parseInt(@$("td[data-sort=#{header}]").css('width'))
@$("th[data-sort=#{header}]").css('padding', tdpadding)
@$("th[data-sort=#{header}]").css('width', tdwidth)
if (i+1) == @headers.length
trwidth = @$("td[data-sort=#{header}]").parent().css('width')
@$("th[data-sort=#{header}]").parent().parent().parent().css('width', trwidth)
@$('.bodycontainer').css('height', window.innerHeight - ($('html').outerHeight() -@$('.bodycontainer').outerHeight() ) ) unless @collection.length == 0
Here I assume that you have an array of the headers called @headers.
It is not pretty but it works. Hope it helps someone.
You can try as below :
declare @list varchar(MAX), @i int
select @i=0, @list ='4,7,12,22,19,'
while( @i < LEN(@list))
begin
declare @item varchar(MAX)
SELECT @item = SUBSTRING(@list, @i,CHARINDEX(',',@list,@i)-@i)
select @item
--do your stuff here with @item
exec p_MyInnerProcedure @item
set @i = CHARINDEX(',',@list,@i)+1
if(@i = 0) set @i = LEN(@list)
end
There are two pair of modal events, one is "show" and "shown", the other is "hide" and "hidden". As you can see from the name, hide event fires when modal is about the be close, such as clicking on the cross on the top-right corner or close button or so on. While hidden is fired after the modal is actually close. You can test these events your self. For exampel:
$( '#modal' )
.on('hide', function() {
console.log('hide');
})
.on('hidden', function(){
console.log('hidden');
})
.on('show', function() {
console.log('show');
})
.on('shown', function(){
console.log('shown' )
});
And, as for your question, I think you should listen to the 'hide' event of your modal.
I create original class that similar to StringBuidler and can append line by calling method appendLine(String str).
public class StringBuilderPlus {
private StringBuilder sb;
public StringBuilderPlus(){
sb = new StringBuilder();
}
public void append(String str)
{
sb.append(str != null ? str : "");
}
public void appendLine(String str)
{
sb.append(str != null ? str : "").append(System.getProperty("line.separator"));
}
public String toString()
{
return sb.toString();
}
}
Usage:
StringBuilderPlus sb = new StringBuilderPlus();
sb.appendLine("aaaaa");
sb.appendLine("bbbbb");
System.out.println(sb.toString());
Console:
aaaaa
bbbbb
You should use:
URLEncoder.encode("NAME", "UTF-8");
You cannot safely do what you want since the default hashCode() may not return the address, and has been mentioned, multiple objects with the same hashCode are possible. The only way to accomplish what you want, is to actually override the hashCode() method for the objects in question and guarantee that they all provide unique values. Whether this is feasible in your situation is another question.
For the record, I have experienced multiple objects with the same default hashcode in an IBM VM running in a WAS server. We had a defect where objects being put into a remote cache would get overwritten because of this. That was an eye opener for me at that point since I assumed the default hashcode was the objects memory address as well.
Use .AddRange
to append any Enumrable collection to the list.
This solution worked for me if you have a block element (e. g. ). I used the colors to make the solution clearer.
HTML:
<main class="skin_orange">
<p>As you can the the element/box is vertically centered</p>
<div class="bigBox skin_blue">Blue Box</div>
</main>
CSS:
main {
position: relative;
width: 400px;
height: 400px;
}
.skin_orange {
outline: thin dotted red;
background: orange;
}
.bigBox {
width: 150px;
height: 150px;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
.skin_blue {
background-color: blue;
}
String labels[] = { "MH", null, "AP", "KL", "CH", "MP", "GJ", "OR" };
if(Arrays.toString(labels).indexOf("null") > -1) {
System.out.println("Array Element Must not be null");
(or)
throw new Exception("Array Element Must not be null");
}
------------------------------------------------------------------------------------------
For two Dimensional array
String labels2[][] = {{ "MH", null, "AP", "KL", "CH", "MP", "GJ", "OR" },{ "MH", "FG", "AP", "KL", "CH", "MP", "GJ", "OR" };
if(Arrays.deepToString(labels2).indexOf("null") > -1) {
System.out.println("Array Element Must not be null");
(or)
throw new Exception("Array Element Must not be null");
}
------------------------------------------------------------------------------------------
same for Object Array
String ObjectArray[][] = {{ "MH", null, "AP", "KL", "CH", "MP", "GJ", "OR" },{ "MH", "FG", "AP", "KL", "CH", "MP", "GJ", "OR" };
if(Arrays.deepToString(ObjectArray).indexOf("null") > -1) {
System.out.println("Array Element Must not be null");
(or)
throw new Exception("Array Element Must not be null");
}
If you want to find a particular null element, you should use for loop as above said .
Change your subplot settings to:
plt.subplot(1, 2, 1)
...
plt.subplot(1, 2, 2)
The parameters for subplot
are: number of rows, number of columns, and which subplot you're currently on. So 1, 2, 1
means "a 1-row, 2-column figure: go to the first subplot." Then 1, 2, 2
means "a 1-row, 2-column figure: go to the second subplot."
You currently are asking for a 2-row, 1-column (that is, one atop the other) layout. You need to ask for a 1-row, 2-column layout instead. When you do, the result will be:
In order to minimize the overlap of subplots, you might want to kick in a:
plt.tight_layout()
before the show. Yielding:
This is a followup to the font-forge
section of @Kurt Pfeifle's answer, specific to Red Hat (and possibly other Linux distros).
Once you have your TTF file, you can install it on your system by
/usr/share/fonts
(as root)fc-cache -f /usr/share/fonts/
(as root)you might use default parameters in your function and then just pass the entire dataset itself, since the dataset is already a DOMStringMap Object
<div data-uid="aaa" data-name="bbb" data-value="ccc"
onclick="fun(this.dataset)">
<script>
const fun = ({uid:'ddd', name:'eee', value:'fff', other:'default'} = {}) {
//
}
</script>
that way, you can deal with any data-values that got set in the html tag, or use defaults if they weren't set - that kind of thing
maybe not in this situation, but in others, it might be advantageous to put all your preferences in a single data-attribute
<div data-all='{"uid":"aaa","name":"bbb","value":"ccc"}'
onclick="fun(JSON.parse(this.dataset.all))">
there are probably more terse ways of doing that, if you already know certain things about the order of the data
<div data-all="aaa,bbb,ccc" onclick="fun(this.dataset.all.split(','))">
As has been said previously, assertions should be used when your code SHOULD NOT ever reach a point, meaning there is a bug there. Probably the most useful reason I can see to use an assertion is an invariant/pre/postcondition. These are something that must be true at the start or end of each iteration of a loop or a function.
For example, a recursive function (2 seperate functions so 1 handles bad input and the other handles bad code, cause it's hard to distinguish with recursion). This would make it obvious if I forgot to write the if statement, what had gone wrong.
def SumToN(n):
if n <= 0:
raise ValueError, "N must be greater than or equal to 0"
else:
return RecursiveSum(n)
def RecursiveSum(n):
#precondition: n >= 0
assert(n >= 0)
if n == 0:
return 0
return RecursiveSum(n - 1) + n
#postcondition: returned sum of 1 to n
These loop invariants often can be represented with an assertion.
Prefix the variable name with env
:
$env:path
For example, if you want to print the value of environment value "MINISHIFT_USERNAME", then command will be:
$env:MINISHIFT_USERNAME
You can also enumerate all variables via the env
drive:
Get-ChildItem env:
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) ) ;
Boolean isBetween =
( ! today.isBefore( localDate1 ) ) // “not-before” is short for “is-equal-to or later-than”.
&&
today.isBefore( localDate3 ) ;
Or, better, if you add the ThreeTen-Extra library to your project.
LocalDateRange.of(
LocalDate.of( … ) ,
LocalDate.of( … )
).contains(
LocalDate.now()
)
Half-open approach, where beginning is inclusive while ending is exclusive.
By the way, that is a bad choice of format for a text representation of a date or date-time value. Whenever possible, stick with the standard ISO 8601 formats. ISO 8601 formats are unambiguous, understandable across human cultures, and are easy to parse by machine.
For a date-only value, the standard format is YYYY-MM-DD. Note how this format has the benefit of being chronological when sorted alphabetically.
LocalDate
The LocalDate
class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
DateTimeFormatter
As your input strings are non-standard format, we must define a formatting pattern to match.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" );
Use that to parse the input strings.
LocalDate start = LocalDate.parse( "22-02-2010" , f );
LocalDate stop = LocalDate.parse( "25-12-2010" , f );
In date-time work, usually best to define a span of time by the Half-Open approach where the beginning is inclusive while the ending is exclusive. So we want to know if today is the same or later than the start and also before the stop. A briefer way of saying “is the same or later than the start” is “not before the start”.
Boolean intervalContainsToday = ( ! today.isBefore( start ) ) && today.isBefore( stop ) ;
See the Answer by gstackoverflow showing the list of comparison methods you can call.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
UPDATE: This “Joda-Time” section below is left intact as history. The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
Other answers are correct with regard to the bundled java.util.Date and java.util.Calendar classes. But those classes are notoriously troublesome. So here's some example code using the Joda-Time 2.3 library.
If you truly want a date without any time portion and no time zone, then use the LocalDate
class in Joda-Time. That class provides methods of comparison including compareTo
(used with Java Comparators), isBefore
, isAfter
, and isEqual
.
Inputs…
String string1 = "22-02-2010";
String string2 = "07-04-2010";
String string3 = "25-12-2010";
Define a formatter describing the input strings…
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd-MM-yyyy" );
Use formatter to parse the strings into LocalDate objects…
LocalDate localDate1 = formatter.parseLocalDate( string1 );
LocalDate localDate2 = formatter.parseLocalDate( string2 );
LocalDate localDate3 = formatter.parseLocalDate( string3 );
boolean is1After2 = localDate1.isAfter( localDate2 );
boolean is2Before3 = localDate2.isBefore( localDate3 );
Dump to console…
System.out.println( "Dates: " + localDate1 + " " + localDate2 + " " + localDate3 );
System.out.println( "is1After2 " + is1After2 );
System.out.println( "is2Before3 " + is2Before3 );
When run…
Dates: 2010-02-22 2010-04-07 2010-12-25
is1After2 false
is2Before3 true
So see if the second is between the other two (exclusively, meaning not equal to either endpoint)…
boolean is2Between1And3 = ( ( localDate2.isAfter( localDate1 ) ) && ( localDate2.isBefore( localDate3 ) ) );
If you are working with spans of time, I suggest exploring in Joda-Time the classes: Duration, Interval, and Period. Methods such as overlap
and contains
make comparisons easy.
For text representations, look at the ISO 8601 standard’s:
Joda-Time classes can work with strings in both those formats, both as input (parsing) and output (generating strings).
Joda-Time performs comparisons using the Half-Open approach where the beginning of the span is inclusive while the ending is exclusive. This approach is a wise one for handling spans of time. Search StackOverflow for more info.
For anyone interested, I ran into this same issue when using css modules and react css modules.
Most components have an associated css module style, and in this example my Button has its own css file, as does the Promo parent component. But I want to pass some additional styles to Button from Promo
So the style
able Button looks like this:
Button.js
import React, { Component } from 'react'
import CSSModules from 'react-css-modules'
import styles from './Button.css'
class Button extends Component {
render() {
let button = null,
className = ''
if(this.props.className !== undefined){
className = this.props.className
}
button = (
<button className={className} styleName='button'>
{this.props.children}
</button>
)
return (
button
);
}
};
export default CSSModules(Button, styles, {allowMultiple: true} )
In the above Button component the Button.css styles handle the common button styles. In this example just a .button
class
Then in my component where I want to use the Button, and I also want to modify things like the position of the button, I can set extra styles in Promo.css
and pass through as the className
prop. In this example again called .button
class. I could have called it anything e.g. promoButton
.
Of course with css modules this class will be .Promo__button___2MVMD
whereas the button one will be something like .Button__button___3972N
Promo.js
import React, { Component } from 'react';
import CSSModules from 'react-css-modules';
import styles from './Promo.css';
import Button from './Button/Button'
class Promo extends Component {
render() {
return (
<div styleName='promo' >
<h1>Testing the button</h1>
<Button className={styles.button} >
<span>Hello button</span>
</Button>
</div>
</Block>
);
}
};
export default CSSModules(Promo, styles, {allowMultiple: true} );
One possible solution is:
<h:panelGroup rendered="#{bean.row == 10}">
<div class="text-success">
<h:outputText value="#{bean.row}"/>
</div>
</h:panelGroup>
int
can't be null, but Integer
can. You need to be careful when unboxing null Integers since this can cause a lot of confusion and head scratching!
e.g. this:
int a = object.getA(); // getA returns a null Integer
will give you a NullPointerException
, despite object not being null!
To follow up on your question, if you want to indicate the absence of a value, I would investigate java.util.Optional<Integer>
Xcode 8.2, iOS 10
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Ok, thanks for the more specific info, ppl may remove their downvotes now...
What you are proposing is a very common thing to do! You want to run your web application locally without uploading it to your host yet. That's totally fine and that's what your Apache is there for. Your Apache is a web server meaning its main purpose is to serve HTML, PHP, ASP, etc. files. Some like PHP; it first sends to the interpreter and then sends the rendered file to the browser. All in all: it's just serving pages to your browser (the client).
Your web server has a root directory which is wwwroot (IIS) or htdocs (apache, xampp) or something else like public_html, www or html, etc. It depends on your OS and web server.
Now if you type http://localhost
into your browser, your browser will be directed to this webroot and the server will serve any index.html
, index.php
, etc. it can find there (in a customizable order).
If you have a project called "mytutorial" you can enter http://localhost/mytutorial
and the server will show you the index-file of your tutorial, etc. If you look at the absolute path of this tutorial folder then it's just a subfolder of your webroot, which is itself located somewhere on your harddrive, but that doesn't matter for your localhost.
So the relative path is
http://localhost/mytutorial
while the absolute path may be
c:/webservices/apache/www
or
c:/xampp/htdocs
If you're working with Dreamweaver you can simplify the testing process by setting up your local server as a testing server in your project settings. Try it! It's easy. Once it's done, you can just press the browser icon with any of your files and it will open on localhost.
if (new TimeSpan(11,59,0) <= currentTime.TimeOfDay && new TimeSpan(13,01,0) >= currentTime.TimeOfDay)
{
//match found
}
if you really want to parse a string into a TimeSpan, then you can use:
TimeSpan start = TimeSpan.Parse("11:59");
TimeSpan end = TimeSpan.Parse("13:01");
I found one solution for SVG. But it is work only for Webkit, I just want share my workaround with you. In my example is shown how to use SVG element from DOM as background through a filter (background-image: url('#glyph') is not working).
Features needed for this SVG icon render:
.test {_x000D_
/* background-image: url('#glyph');_x000D_
background-size:100% 100%;*/_x000D_
filter: url(#image); _x000D_
height:100px;_x000D_
width:100px;_x000D_
}_x000D_
.test:before {_x000D_
display:block;_x000D_
content:'';_x000D_
color:transparent;_x000D_
}_x000D_
.test2{_x000D_
width:100px;_x000D_
height:100px;_x000D_
}_x000D_
.test2:before {_x000D_
display:block;_x000D_
content:'';_x000D_
color:transparent;_x000D_
filter: url(#image); _x000D_
height:100px;_x000D_
width:100px;_x000D_
}
_x000D_
<svg style="height:0;width:0;" version="1.1" viewbox="0 0 100 100"_x000D_
xmlns="http://www.w3.org/2000/svg"_x000D_
xmlns:xlink="http://www.w3.org/1999/xlink">_x000D_
<defs>_x000D_
<g id="glyph">_x000D_
<path id="heart" d="M100 34.976c0 8.434-3.635 16.019-9.423 21.274h0.048l-31.25 31.25c-3.125 3.125-6.25 6.25-9.375 6.25s-6.25-3.125-9.375-6.25l-31.202-31.25c-5.788-5.255-9.423-12.84-9.423-21.274 0-15.865 12.861-28.726 28.726-28.726 8.434 0 16.019 3.635 21.274 9.423 5.255-5.788 12.84-9.423 21.274-9.423 15.865 0 28.726 12.861 28.726 28.726z" fill="crimson"/>_x000D_
</g>_x000D_
<svg id="resized-glyph" x="0%" y="0%" width="24" height="24" viewBox="0 0 100 100" class="icon shape-codepen">_x000D_
<use xlink:href="#glyph"></use>_x000D_
</svg>_x000D_
<filter id="image">_x000D_
<feImage xlink:href="#resized-glyph" x="0%" y="0%" width="100%" height="100%" result="res"/>_x000D_
<feComposite operator="over" in="res" in2="SourceGraphic"/>_x000D_
</filter>_x000D_
</defs>_x000D_
</svg>_x000D_
<div class="test">_x000D_
</div>_x000D_
<div class="test2">_x000D_
</div>
_x000D_
One more solution, is use url encode
var container = document.querySelector(".container");_x000D_
var svg = document.querySelector("svg");_x000D_
var svgText = (new XMLSerializer()).serializeToString(svg);_x000D_
container.style.backgroundImage = `url(data:image/svg+xml;utf8,${encodeURIComponent(svgText)})`;
_x000D_
.container{_x000D_
height:50px;_x000D_
width:250px;_x000D_
display:block;_x000D_
background-position: center center;_x000D_
background-repeat: no-repeat;_x000D_
background-size: contain;_x000D_
}
_x000D_
<svg height="100" width="500" xmlns="http://www.w3.org/2000/svg">_x000D_
<ellipse cx="240" cy="50" rx="220" ry="30" style="fill:yellow" />_x000D_
</svg>_x000D_
<div class="container"></div>
_x000D_
If you are running AWS image from Bitnami. The username would be bitnami. Cheers!
see my debug and look at the last one:
*
ssh -v -i awsliferaysrta.pem.txt [email protected].***
OpenSSH_6.2p2, OSSLShim 0.9.8r 8 Dec 2011
debug1: Reading configuration data /etc/ssh_config
debug1: /etc/ssh_config line 20: Applying options for *
debug1: Connecting to 54.254.250.*** [54.254.250.***] port 22.
debug1: Connection established.
debug1: identity file awsliferaysrta.pem.txt type -1
debug1: identity file awsliferaysrta.pem.txt-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.2
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.9p1 Debian-5ubuntu1.1
debug1: match: OpenSSH_5.9p1 Debian-5ubuntu1.1 pat OpenSSH_5*
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-md5 none
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Server host key: RSA 05:5c:78:45:c9:39:3a:84:fe:f8:19:5d:31:48:aa:5f
debug1: Host '54.254.250.***' is known and matches the RSA host key.
debug1: Found key in /Users/macbookpro/.ssh/known_hosts:2
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Trying private key: awsliferaysrta.pem.txt
debug1: read PEM private key done: type RSA
debug1: Authentication succeeded (publickey).
Authenticated to 54.254.250.*** ([54.254.250.***]:22).
debug1: channel 0: new [client-session]
debug1: Requesting [email protected]
debug1: Entering interactive session.
debug1: Remote: Port forwarding disabled.
debug1: Remote: Agent forwarding disabled.
debug1: Remote: X11 forwarding disabled.
debug1: Remote: Forced command.
debug1: Sending environment.
debug1: Sending env LANG = en_US.UTF-8
Please login as the user "bitnami" rather than the user "root".
*
For me for any reason :
rm .git/index.lock
Didn't work, so I just went to the .git file and deleted it manually which worked fantastically.
You should be denoting the call by reference in the function definition, not the actual call. Since PHP started showing the deprecation errors in version 5.3, I would say it would be a good idea to rewrite the code.
There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use
&
infoo(&$a);
.
For example, instead of using:
// Wrong way!
myFunc(&$arg); # Deprecated pass-by-reference argument
function myFunc($arg) { }
Use:
// Right way!
myFunc($var); # pass-by-value argument
function myFunc(&$arg) { }
SELECT * FROM table WHERE field1 NOT LIKE '%$x%';
(Make sure you escape $x properly beforehand to avoid SQL injection)
Edit: NOT IN
does something a bit different - your question isn't totally clear so pick which one to use. LIKE 'xxx%'
can use an index. LIKE '%xxx'
or LIKE '%xxx%'
can't.
You may have imported,
project/controllers/base
inside the
project/controllers/routes
You have already imported before. That's not supported.
As noted in a prior answer, although git merge-base
works,
$ git merge-base myfeature develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2
If myfeature
is the current branch, as is common, you can use --fork-point
:
$ git merge-base --fork-point develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2
This argument works only in sufficiently recent versions of git. Unfortunately it doesn't always work, however, and it is not clear why. Please refer to the limitations noted toward the end of this answer.
For full commit info, consider:
$ git log -1 $(git merge-base --fork-point develop)
See InnerFade.
<script type="text/javascript">
$(document).ready(
function() {
$('#portfolio').innerfade({
speed: 'slow',
timeout: 10000,
type: 'sequence',
containerheight: '220px'
});
});
</script>
<ul id="portfolio">
<li>
<a href="http://medienfreunde.com/deutsch/referenzen/kreation/good_guy__bad_guy.html">
<img src="images/ggbg.gif" alt="Good Guy bad Guy" />
</a>
</li>
<li>
<a href="http://medienfreunde.com/deutsch/referenzen/kreation/whizzkids.html">
<img src="images/whizzkids.gif" alt="Whizzkids" />
</a>
</li>
<li>
<a href="http://medienfreunde.com/deutsch/referenzen/printdesign/koenigin_mutter.html">
<img src="images/km.jpg" alt="Königin Mutter" />
</a>
</li>
<li>
<a href="http://medienfreunde.com/deutsch/referenzen/webdesign/rt_reprotechnik_-_hybride_archivierung.html">
<img src="images/rt_arch.jpg" alt="RT Hybride Archivierung" />
</a>
</li>
<li>
<a href="http://medienfreunde.com/deutsch/referenzen/kommunikation/tuev_sued_gruppe.html">
<img src="images/tuev.jpg" alt="TÜV SÜD Gruppe" />
</a>
</li>
</ul>
foreach ($array as $k => $v) {
$tArray[$k] = $v['Weight'];
}
$min_value = min($tArray);
$max_value = max($tArray);
The fragment already has startActivityForResult
, which would call onActivityResult
in the fragment if you use it, instead of getActivity()
...
Just store a regular datetime and ignore everything else. Why spend extra time writing code that loads an int, manipulates it, and converts it into a datetime, when you could just load a datetime?
It makes it clear that the method accepts null values, and that if you override the method, you should also accept null values.
It also serves as a hint for code analyzers like FindBugs. For example, if such a method dereferences its argument without checking for null first, FindBugs will emit a warning.
JavaScript uses the \ (backslash) as an escape characters for:
Note that the \v and \0 escapes are not allowed in JSON strings.
You can't.
The only way to get a list of all event listeners attached to a node is to intercept the listener attachment call.
Says
Append an event listener to the associated list of event listeners with type set to type, listener set to listener, and capture set to capture, unless there already is an event listener in that list with the same type, listener, and capture.
Meaning that an event listener is added to the "list of event listeners". That's all. There is no notion of what this list should be nor how you should access it.
My solution is to use m4. It's supported on most platforms and is included in the binutils package.
First include a macro changequote()
in the file to change the quoting characters to what you prefer (default is `'). The macro is removed when the file is processed.
changequote(`{{', `}}')
include({{other_file}})
On the commandline:
m4 -I./dir_containing_other_file/ input.md > _tmp.md
pandoc -o output.html _tmp.md
Extend your WHERE
condition:
WHERE
(FirstName = ISNULL(@FirstName, FirstName)
OR COALESCE(@FirstName, FirstName, '') = '')
AND (LastName = ISNULL(@LastName, LastName)
OR COALESCE(@LastName, LastName, '') = '')
AND (Title = ISNULL(@Title, Title)
OR COALESCE(@Title, Title, '') = '')
i. e. combine different cases with boolean conditions.
If it still not showing elevation try
android:hardwareAccelerated="true"
this will definitely help you.
There is another way to pristine form that is by sending form into the controller. For example:-
In view:-
<form name="myForm" ng-submit="addUser(myForm)" novalidate>
<input type="text" ng-mode="user.name"/>
<span style="color:red" ng-show="myForm.name.$dirty && myForm.name.$invalid">
<span ng-show="myForm.name.$error.required">Name is required.</span>
</span>
<button ng-disabled="myForm.$invalid">Add User</button>
</form>
In Controller:-
$scope.addUser = function(myForm) {
myForm.$setPristine();
};
cursor.copy_from is the fastest solution I've found for bulk inserts by far. Here's a gist I made containing a class named IteratorFile which allows an iterator yielding strings to be read like a file. We can convert each input record to a string using a generator expression. So the solution would be
args = [(1,2), (3,4), (5,6)]
f = IteratorFile(("{}\t{}".format(x[0], x[1]) for x in args))
cursor.copy_from(f, 'table_name', columns=('a', 'b'))
For this trivial size of args it won't make much of a speed difference, but I see big speedups when dealing with thousands+ of rows. It will also be more memory efficient than building a giant query string. An iterator would only ever hold one input record in memory at a time, where at some point you'll run out of memory in your Python process or in Postgres by building the query string.
Please remove e.preventDefault()
, because event.cancelable
of touchmove is false
.
So you can't call this method.
If you are using T-SQL you could use a temporary table in a stored procedure and update or insert the records of your query accordingly.
As there is no pure byte
type in JavaScript we can represent a byte array as an array of numbers, where each number represents a byte and thus will have an integer value between 0 and 255 inclusive.
Here is a simple function that does convert a JavaScript string into an Array of numbers that contain the UTF-8 encoding of the string:
function toUtf8(str) {
var value = [];
var destIndex = 0;
for (var index = 0; index < str.length; index++) {
var code = str.charCodeAt(index);
if (code <= 0x7F) {
value[destIndex++] = code;
} else if (code <= 0x7FF) {
value[destIndex++] = ((code >> 6 ) & 0x1F) | 0xC0;
value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80;
} else if (code <= 0xFFFF) {
value[destIndex++] = ((code >> 12) & 0x0F) | 0xE0;
value[destIndex++] = ((code >> 6 ) & 0x3F) | 0x80;
value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80;
} else if (code <= 0x1FFFFF) {
value[destIndex++] = ((code >> 18) & 0x07) | 0xF0;
value[destIndex++] = ((code >> 12) & 0x3F) | 0x80;
value[destIndex++] = ((code >> 6 ) & 0x3F) | 0x80;
value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80;
} else if (code <= 0x03FFFFFF) {
value[destIndex++] = ((code >> 24) & 0x03) | 0xF0;
value[destIndex++] = ((code >> 18) & 0x3F) | 0x80;
value[destIndex++] = ((code >> 12) & 0x3F) | 0x80;
value[destIndex++] = ((code >> 6 ) & 0x3F) | 0x80;
value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80;
} else if (code <= 0x7FFFFFFF) {
value[destIndex++] = ((code >> 30) & 0x01) | 0xFC;
value[destIndex++] = ((code >> 24) & 0x3F) | 0x80;
value[destIndex++] = ((code >> 18) & 0x3F) | 0x80;
value[destIndex++] = ((code >> 12) & 0x3F) | 0x80;
value[destIndex++] = ((code >> 6 ) & 0x3F) | 0x80;
value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80;
} else {
throw new Error("Unsupported Unicode character \""
+ str.charAt(index) + "\" with code " + code + " (binary: "
+ toBinary(code) + ") at index " + index
+ ". Cannot represent it as UTF-8 byte sequence.");
}
}
return value;
}
function toBinary(byteValue) {
if (byteValue < 0) {
byteValue = byteValue & 0x00FF;
}
var str = byteValue.toString(2);
var len = str.length;
var prefix = "";
for (var i = len; i < 8; i++) {
prefix += "0";
}
return prefix + str;
}
There are three ways to compile jrxml to jasper.
You can do direct compile via compile button (hammer logo) on iReport designer.
You can use ant to compile as shown in the Ant Compile Sample.
<target name="compile1">
<mkdir dir="./build/reports"/>
<jrc
srcdir="./reports"
destdir="./build/reports"
tempdir="./build/reports"
keepjava="true"
xmlvalidation="true">
<classpath refid="runClasspath"/>
<include name="**/*.jrxml"/>
</jrc>
</target>
Below is the report compile task on my current project.
addition from Daniel Rikowski :
You can also use the JasperCompileManager class to compile from your java code.
JasperCompileManager.compileReportToFile(
"our_jasper_template.jrxml", // the path to the jrxml file to compile
"our_compiled_template.jasper"); // the path and name we want to save the compiled file to
I performed a full-on cop-out and wrote a class which creates a batch file and then calls sftp
via a system
call. Not the nicest (or fastest) way of doing it but it works for what I need and it didn't require any installation of extra libraries or extensions in PHP.
Could be the way to go if you don't want to use the ssh2
extensions
@media only screen and (min-width : 320px) and (max-width : 480px) {/*--- Mobile portrait ---*/}
@media only screen and (min-width : 480px) and (max-width : 595px) {/*--- Mobile landscape ---*/}
@media only screen and (min-width : 595px) and (max-width : 690px) {/*--- Small tablet portrait ---*/}
@media only screen and (min-width : 690px) and (max-width : 800px) {/*--- Tablet portrait ---*/}
@media only screen and (min-width : 800px) and (max-width : 1024px) {/*--- Small tablet landscape ---*/}
@media only screen and (min-width : 1024px) and (max-width : 1224px) {/*--- Tablet landscape --- */}
In my case, it was caused by a missing (0)
in javascript:void(0)
in an anchor.
Ran into this today at work. An admin thought it prudent to hard code Python 2.7 as the PYSPARK_PYTHON
and PYSPARK_DRIVER_PYTHON
in $SPARK_HOME/conf/spark-env.sh
. Needless to say this broke all of our jobs that utilize any other python versions or environments (which is > 90% of our jobs). @PhillipStich points out correctly that you may not always have write permissions for this file, as is our case. While setting the configuration in the spark-submit
call is an option, another alternative (when running in yarn/cluster mode) is to set the SPARK_CONF_DIR
environment variable to point to another configuration script. There you could set your PYSPARK_PYTHON and any other options you may need. A template can be found in the spark-env.sh source code on github.
Weston Ruther built a similar thing using the WebKit proposal for css transitions:
http://weston.ruter.net/projects/jquery-css-transitions/
This implementation might be useful for you.
from datetime import datetime
a = datetime.strptime(f, "%Y-%m-%d")
For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).
This can be caused in many ways:
#include
the header that defines it.#ifndef BLAH_H
) are defective (your #ifndef BLAH_H
doesn't match your #define BALH_H
due to a typo or copy+paste mistake).#define MYHEADER_H
, even if they are in separate directories)new Vector()
should be new Vector<int>()
)NamespaceA::NamespaceB
, AND a <global scope>::NamespaceB
, if you are already within NamespaceA
, it'll look in NamespaceA::NamespaceB
and not bother checking <global scope>::NamespaceB
) unless you explicitly access it.To explicitly access something in the global namespace, prefix it with ::
, as if the global namespace is a namespace with no name (e.g. ::MyType
or ::MyNamespace::MyType
).
Find the table in SQL manager right click it and select design, then right click the little key icon and select remove primary key.
One of the reason I found was why it doesn't find a jar from repository might be because the .pom file for that particular jar might be missing or corrupt. Just correct it and try to load from local repository.
I have had another issue giving me a 504. It's pretty far out but I'll write it up here for googlers and posterity...
I have a client calling an IIS hosted webservice hosted in another domain (Active Directory). There is not full trust between the client domain and the domain where the web services is hosted. One of the many challenges with the selective trust between these two domains is that Kerberos does not work when calling from one to the other.
In my case I was trying to call a service in another domain where I found out that a SPN was registered. Like this : http/myurl.test.local (just an example)
This forces the call to use Kerberos instead of letting it fall back to NTLM and this gave me a 405 back from the calling server.
After removing the spn and allowing the call to fall back to NTLM, it works fine.
As I said ... this is not something you are likely to run into, as most organizations do not venture into having such a selective trusts between two domains ... But it gives a 504 and caused me a few (more) gray hairs.
To anyone come to find timezone of mysql db.
With this query you can get current timezone :
mysql> SELECT @@system_time_zone as tz;
+-------+
| tz |
+-------+
| CET |
+-------+
You can do it with the code you have, you just need to ensure that html
and body
are set to 100% height.
Demo: http://jsfiddle.net/kevinPHPkevin/a7eGN/
html, body {
height:100%;
}
body {
background-color: white;
background-image: url('http://www.canvaz.com/portrait/charcoal-1.jpg');
background-size: auto 100%;
background-repeat: no-repeat;
background-position: left top;
}
You can write the where
clause as:
where (case when (:stateCode = '') then (1)
when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
else 0)
end) = 1;
Alternatively, remove the case
entirely:
where (:stateCode = '') or
((:stateCode != '') and vw.state_cd in (:stateCode));
Or, even better:
where (:stateCode = '') or vw.state_cd in (:stateCode)
i think this might work for you
//<?php
//checks file extension for images only
$allowed = array('gif','png' ,'jpg');
$file = $_FILES['file']['name'];
$ext = pathinfo($file, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) )
{
//?>
<script>
alert('file extension not allowed');
window.location.href='some_link.php?file_type_not_allowed_error';
</script>
//<?php
exit(0);
}
//?>
It looks outdated, but let it be here anyway. The correct way to do it in your case:
elem = wd.find_element_by_css_selector('#my-id')
html = wd.execute_script("return arguments[0].innerHTML;", elem)
or
html = elem.get_attribute('innerHTML')
Both are working for me (selenium-server-standalone-2.35.0).
Based on fireant's excellent answer above, here is the alpha blending but a bit more human legible. You may need to swap 1.0-alpha
and alpha
depending on which direction you're merging (mine is swapped from fireant's answer).
o* == s_img.*
b* == b_img.*
for c in range(0,3):
alpha = s_img[oy:oy+height, ox:ox+width, 3] / 255.0
color = s_img[oy:oy+height, ox:ox+width, c] * (1.0-alpha)
beta = l_img[by:by+height, bx:bx+width, c] * (alpha)
l_img[by:by+height, bx:bx+width, c] = color + beta
The command is date
To customise the output there are a myriad of options available, see date --help
for a list.
For example, date '+%A %W %Y %X'
gives Tuesday 34 2013 08:04:22
which is the name of the day of the week, the week number, the year and the time.
use git stash push -m aNameForYourStash
to save it. Then use git stash list
to learn the index of the stash that you want to apply. Then use git stash pop --index 0
to pop the stash and apply it.
note: I'm using git version 2.21.0.windows.1
Com = commercial application (just like .com, most people register their app as a com app)
First level = always the publishing entity's' name
Second level (optional) = sub-devison, group, or project name
Final level = product name
For example he android launcher (home screen) is Com.Google.android.launcher
I've resolved it by checking the 'UNICODE'checkbox. Click on below Image link:
After struggling with this for hours, I've come up with a solution that feels almost the best.
Chaos' answer of converting values to hexstring doesn't work with every datatype, specifically with datetime columns.
I use PHP's PDO::quote()
, but as it comes with PHP, PDO::quote()
is not supported for MS SQL Server and returns FALSE
. The solution for it to work was to download some Microsoft bundles:
After that you can connect in PHP with PDO using a DSN like the following example:
sqlsrv:Server=192.168.0.25; Database=My_Database;
Using the UID
and PWD
parameters in the DSN didn't worked, so username and password are passed as the second and third parameters on the PDO constructor when creating the connection.
Now you can use PHP's PDO::quote()
. Enjoy.
If you do not specifically need the alt text of an image, then you can just target the class/id of the image.
$('img.propImg').each(function(){
enter code here
}
I know it’s not quite answering the question, though I’d spent ages trying to figure this out and this question gave me the solution :). In my case I needed to hide any image tags with a specific src.
$('img.propImg').each(function(){ //for each loop that gets all the images.
if($(this).attr('src') == "img/{{images}}") { // if the src matches this
$(this).css("display", "none") // hide the image.
}
});
You could create a new array containing that array, so:
<?php
$array = array();
$array['name'] = $oldArray;
?>
To answer, you question you could provide a service that wraps the original Http
object from Angular. Something like described below.
import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
@Injectable()
export class HttpClient {
constructor(private http: Http) {}
createAuthorizationHeader(headers: Headers) {
headers.append('Authorization', 'Basic ' +
btoa('username:password'));
}
get(url) {
let headers = new Headers();
this.createAuthorizationHeader(headers);
return this.http.get(url, {
headers: headers
});
}
post(url, data) {
let headers = new Headers();
this.createAuthorizationHeader(headers);
return this.http.post(url, data, {
headers: headers
});
}
}
And instead of injecting the Http
object you could inject this one (HttpClient
).
import { HttpClient } from './http-client';
export class MyComponent {
// Notice we inject "our" HttpClient here, naming it Http so it's easier
constructor(http: HttpClient) {
this.http = httpClient;
}
handleSomething() {
this.http.post(url, data).subscribe(result => {
// console.log( result );
});
}
}
I also think that something could be done using multi providers for the Http
class by providing your own class extending the Http
one... See this link: http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html.
you can use angular's filter
https://docs.angularjs.org/api/ng/filter/filter
in your controller:
$filter('filter')(myArray, {'id':73})
or in your HTML
{{ myArray | filter : {'id':73} }}
You probably need to chdir to the correct directory before calling the script. This way you can ensure what directory your script is "in" before calling the shell command.
$old_path = getcwd();
chdir('/my/path/');
$output = shell_exec('./script.sh var1 var2');
chdir($old_path);
You need the @Value
annotation.
A common use case is to assign default field values using
"#{systemProperties.myProp}"
style expressions.
public class SimpleMovieLister {
private MovieFinder movieFinder;
private String defaultLocale;
@Autowired
public void configure(MovieFinder movieFinder,
@Value("#{ systemProperties['user.region'] }") String defaultLocale) {
this.movieFinder = movieFinder;
this.defaultLocale = defaultLocale;
}
// ...
}
See: Expression Language > Annotation Configuration
To be more clear: in your scenario, you'd wire two classes, MybeanService
and MyConstructorClass
, something like this:
@Component
public class MyBeanService implements BeanService{
@Autowired
public MybeanService(MyConstructorClass foo){
// do something with foo
}
}
@Component
public class MyConstructorClass{
public MyConstructorClass(@Value("#{some expression here}") String value){
// do something with value
}
}
Update: if you need several different instances of MyConstructorClass
with different values, you should use Qualifier annotations
You want the :checkbox:checked
selector and map
to create an array of the values:
var checkedValues = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
If your checkboxes have a shared class it would be faster to use that instead, eg. $('.mycheckboxes:checked')
, or for a common name $('input[name="Foo"]:checked')
- Update -
If you don't need IE support then you can now make the map()
call more succinct by using an arrow function:
var checkedValues = $('input:checkbox:checked').map((i, el) => el.value).get();
using sklearn library preprocessing class
from sklearn.impute import SimpleImputer
missingvalues = SimpleImputer(missing_values = np.nan, strategy = 'mean', axis = 0)
missingvalues = missingvalues.fit(x[:,1:3])
x[:,1:3] = missingvalues.transform(x[:,1:3])
Note: In the recent version parameter missing_values
value change to np.nan
from NaN
The string
class's Replace
method can also be used to remove multiple characters from a string:
Dim newstring As String
newstring = oldstring.Replace(",", "").Replace(";", "")
To avoid the UnauthorizedAccessException
, I use:
var files = GetFiles(@"C:\", "*.*", SearchOption.AllDirectories);
foreach (var file in files)
{
Console.WriteLine($"{file}");
}
public static IEnumerable<string> GetFiles(string path, string searchPattern, SearchOption searchOption)
{
var foldersToProcess = new List<string>()
{
path
};
while (foldersToProcess.Count > 0)
{
string folder = foldersToProcess[0];
foldersToProcess.RemoveAt(0);
if (searchOption.HasFlag(SearchOption.AllDirectories))
{
//get subfolders
try
{
var subfolders = Directory.GetDirectories(folder);
foldersToProcess.AddRange(subfolders);
}
catch (Exception ex)
{
//log if you're interested
}
}
//get files
var files = new List<string>();
try
{
files = Directory.GetFiles(folder, searchPattern, SearchOption.TopDirectoryOnly).ToList();
}
catch (Exception ex)
{
//log if you're interested
}
foreach (var file in files)
{
yield return file;
}
}
}
Since 2.0 beta :)
import { APP_BASE_HREF } from 'angular2/platform/common';
You should use keyPressed
if you want an immediate effect, and keyReleased
if you want the effect after you release the key. You cannot use keyTyped
because F5 is not a character. keyTyped
is activated only when an character is pressed.
1> Yes... There is pencil icon when we go to Personal==> <app name> ==>Resources
then click on Pencil Icon and drag to left side and Dynos will go down.
2> You can validate using Heroku cli
heroku logs --app {your-appname}
it worked for me.
In C if you implement count line it will never fail. Yes you can get one extra line if there is stray "ENTER KEY" generally at the end of the file.
File might look some thing like this:
"hello 1
"Hello 2
"
Code below
#include <stdio.h>
#include <stdlib.h>
#define FILE_NAME "file1.txt"
int main() {
FILE *fd = NULL;
int cnt, ch;
fd = fopen(FILE_NAME,"r");
if (fd == NULL) {
perror(FILE_NAME);
exit(-1);
}
while(EOF != (ch = fgetc(fd))) {
/*
* int fgetc(FILE *) returns unsigned char cast to int
* Because it has to return EOF or error also.
*/
if (ch == '\n')
++cnt;
}
printf("cnt line in %s is %d\n", FILE_NAME, cnt);
fclose(fd);
return 0;
}
I believe this could be a simpler way:
public int BusinessDaysUntil(DateTime start, DateTime end, params DateTime[] bankHolidays)
{
int tld = (int)((end - start).TotalDays) + 1; //including end day
int not_buss_day = 2 * (tld / 7); //Saturday and Sunday
int rest = tld % 7; //rest.
if (rest > 0)
{
int tmp = (int)start.DayOfWeek - 1 + rest;
if (tmp == 6 || start.DayOfWeek == DayOfWeek.Sunday) not_buss_day++; else if (tmp > 6) not_buss_day += 2;
}
foreach (DateTime bankHoliday in bankHolidays)
{
DateTime bh = bankHoliday.Date;
if (!(bh.DayOfWeek == DayOfWeek.Saturday || bh.DayOfWeek == DayOfWeek.Sunday) && (start <= bh && bh <= end))
{
not_buss_day++;
}
}
return tld - not_buss_day;
}
This is more or less lifted from the Matlab manual; I've only got passing experience...
function my_output = wave ( a, b, n, k, T, f, flag, varargin )
optargin = numel(varargin);
fTrue = inline('0');
if optargin > 0
fTrue = varargin{1};
end
% code ...
end
You have to replace string line
QString line = in.readLine();
into while:
QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
QMessageBox::information(0, "error", file.errorString());
}
QTextStream in(&file);
while(!in.atEnd()) {
QString line = in.readLine();
QStringList fields = line.split(",");
model->appendRow(fields);
}
file.close();
According to maven website, the last version to support Java 6 is 3.2.5, and 3.3 and up use Java 7. My hunch is that you're using Maven 3.3 or higher, and should either upgrade to Java 7 (and set proper source/target attributes in your pom) or downgrade maven.
That library seems to allow validation for single elements. Just associate a click event to your button and try the following:
$("#myform").validate().element("#i1");
Examples here:
Date.prototype.addDays = function(days) {
var dat = new Date(this.valueOf())
dat.setDate(dat.getDate() + days);
return dat;
}
function getDates(startDate, stopDate) {
var dateArray = new Array();
var currentDate = startDate;
while (currentDate <= stopDate) {
dateArray.push(currentDate);
currentDate = currentDate.addDays(1);
}
return dateArray;
}
var dateArray = getDates(new Date(), (new Date().addDays(7)));
for (i = 0; i < dateArray.length; i ++ ) {
// alert (dateArray[i]);
date=('0'+dateArray[i].getDate()).slice(-2);
month=('0' +(dateArray[i].getMonth()+1)).slice(-2);
year=dateArray[i].getFullYear();
alert(date+"-"+month+"-"+year );
}
When moving classes into specific packages like repository, controller, domain just the generic @SpringBootApplication
is not enough.
You will have to specify the base package for component scan
@ComponentScan("base_package")
For JPA
@EnableJpaRepositories(basePackages = "repository")
is also needed, so spring data will know where to look into for repository interfaces.
dict = {'name' : 'Fred', 'age' : 100, 'employed' : True }
# Choose key to print (could be a user input)
x = 'name'
if x in dict.keys():
print(x)
I think you can achieve what you are looking for by combining number 1 with calling a function like in number 3.
You don't want to execute scripts on page load and prefer to call a function later on? Fine, just create a function that returns the value you would have set in a variable:
function getContextPath() {
return "<%=request.getContextPath()%>";
}
It's a function so it wont be executed until you actually call it, but it returns the value directly, without a need to do DOM traversals or tinkering with URLs.
At this point I agree with @BalusC to use EL:
function getContextPath() {
return "${pageContext.request.contextPath}";
}
or depending on the version of JSP fallback to JSTL:
function getContextPath() {
return "<c:out value="${pageContext.request.contextPath}" />";
}
I have faced this similar issue and resolved it by using following steps :
sqlplus "/ as sysdba"
alter user HR identified by password account unlock
password
is the password that I have used. In onCreate
call
requestWindowFeature(Window.FEATURE_NO_TITLE); // for hiding title
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
You can create a trigger which updates NoofUses
column in Coupon
table whenever
couponid
is used in CouponUse
table
query :
CREATE TRIGGER [dbo].[couponcount] ON [dbo].[couponuse]
FOR INSERT
AS
if EXISTS (SELECT 1 FROM Inserted)
BEGIN
UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)
end
For those like me who would rather not embed their UITableViewController
in a UIViewController
try this:
A custom UITableViewController
subclass can append a mask view to the tableView's superview. Add the mask on viewDidAppear, and remove the mask on viewWillDisappear.
private var statusBarMaskView: UIView!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let superview = self.tableView.superview {
self.statusBarMaskView = UIView(frame: CGRect.zero)
superview.insertSubview(self.statusBarMaskView, aboveSubview: self.tableView)
self.statusBarMaskView.backgroundColor = self.tableView.backgroundColor
// using a nice constraint layout library to set the frame
self.statusBarMaskView.pinTop(to: superview)
self.statusBarMaskView.pinLeft(to: superview)
self.statusBarMaskView.pinRight(to: superview)
self.statusBarMaskView.addHeightConstraint(with: 22.0)
////
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.statusBarMaskView.removeFromSuperview()
self.statusBarMaskView = nil
}
for this simply follow below query
select a.Id,a.type,b.Name,b.City from DatabaseName.dbo.TableName a left join DatabaseName.dbo.TableName b on a.Id=b.Id
Where I wrote databasename, you have to define the name of the database. If you are in same database so you don't need to define the database name but if you are in other database you have to mention database name as path or it will show you error. Hope I made your work easy
In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size
like this:
#include <vector>
int main () {
std::vector<int> v;
auto size = v.size();
}
Your third call
int size = v.size();
triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.
int size = static_cast<int>(v.size());
would always compile cleanly and also explicitly states that your conversion from std::vector::size_type
to int
was intended.
Note that if the size of the vector
is greater than the biggest number an int
can represent, size
will contain an implementation defined (de facto garbage) value.
There's a RemoveDuplicates
method that you could use:
Sub DeleteRows()
With ActiveSheet
Set Rng = Range("A1", Range("B1").End(xlDown))
Rng.RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
End With
End Sub
IMHO you could just send the JSON
encoded (ie. encodeURIComponent
) in the URL
, this way you do not violate the HTTP
specs and get your JSON
to the server.
MD5 also benefits from SSE2 usage, check out BarsWF and then tell me that it doesn't. All it takes is a little assembler knowledge and you can craft your own MD5 SSE2 routine(s). For large amounts of throughput however, there is a tradeoff of the speed during hashing as opposed to the time spent rearranging the input data to be compatible with the SIMD instructions used.
Similar to @Aaron Digulla's suggestion except that I would suggest a graphics design tool, select the base color, in your case the background color, then adjust the Hue, Saturation and Value. Using this you can create color swatches very easily. Paint.Net is free and I use it all the time for this and also the pay-for-tools will also do this.
If you want to disable all constraints in the database just run this code:
-- disable all constraints
EXEC sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
To switch them back on, run: (the print is optional of course and it is just listing the tables)
-- enable all constraints
exec sp_MSforeachtable @command1="print '?'", @command2="ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
I find it useful when populating data from one database to another. It is much better approach than dropping constraints. As you mentioned it comes handy when dropping all the data in the database and repopulating it (say in test environment).
If you are deleting all the data you may find this solution to be helpful.
Also sometimes it is handy to disable all triggers as well, you can see the complete solution here.
$(document).ready(function(){
$('#some-id').trigger('click');
});
did the trick.
As alternative you can use insertAdjacentHTML - however I dig into and make some performance tests - (2019.09.13 Friday) MacOs High Sierra 10.13.6 on Chrome 76.0.3809 (64-bit), Safari 12.1.2 (13604.5.6), Firefox 69.0.0 (64-bit) ). The test F is only for reference - it is out of the question scope because we need to insert dynamically html - but in F I do it by 'hand' (in static way) - theoretically (as far I know) this should be the fastest way to insert new html elements.
SUMMARY
innerHTML =
(do not confuse with +=
) is fastest (Safari 48k operations per second, Firefox 43k op/sec, Chrome 23k op/sec) The A is ~31% slower than ideal solution F only chrome but on safari and firefox is faster (!)innerHTML +=...
is slowest on all browsers (Chrome 95 op/sec, Firefox 88 op/sec, Sfari 84 op/sec)More info about why innerHTML =
is much faster than innerHTML +=
is here. You can perform test on your machine/browser HERE
let html = "<div class='box'>Hello <span class='msg'>World</span> !!!</div>"_x000D_
_x000D_
function A() { _x000D_
container.innerHTML = `<div id="A_oiio">A: ${html}</div>`;_x000D_
}_x000D_
_x000D_
function B() { _x000D_
container.innerHTML += `<div id="B_oiio">B: ${html}</div>`;_x000D_
}_x000D_
_x000D_
function C() { _x000D_
container.insertAdjacentHTML('beforeend', `<div id="C_oiio">C: ${html}</div>`);_x000D_
}_x000D_
_x000D_
function D() { _x000D_
$('#container').append(`<div id="D_oiio">D: ${html}</div>`);_x000D_
}_x000D_
_x000D_
function E() {_x000D_
let d = document.createElement("div");_x000D_
d.innerHTML = `E: ${html}`;_x000D_
d.id = 'E_oiio';_x000D_
container.appendChild(d);_x000D_
}_x000D_
_x000D_
function F() { _x000D_
let dm = document.createElement("div");_x000D_
dm.id = "F_oiio";_x000D_
dm.appendChild(document.createTextNode("F: "));_x000D_
_x000D_
let d = document.createElement("div");_x000D_
d.classList.add('box');_x000D_
d.appendChild(document.createTextNode("Hello "));_x000D_
_x000D_
let s = document.createElement("span");_x000D_
s.classList.add('msg');_x000D_
s.appendChild(document.createTextNode("World"));_x000D_
_x000D_
d.appendChild(s);_x000D_
d.appendChild(document.createTextNode(" !!!"));_x000D_
dm.appendChild( d );_x000D_
_x000D_
container.appendChild(dm);_x000D_
}_x000D_
_x000D_
_x000D_
A();_x000D_
B();_x000D_
C();_x000D_
D();_x000D_
E();_x000D_
F();
_x000D_
.warr { color: red } .msg { color: blue } .box {display: inline}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="warr">This snippet only for show code used in test (in jsperf.com) - it not perform test itself. </div>_x000D_
<div id="container"></div>
_x000D_
I'd recommend to keep your controller free from translation logic and translate your strings directly inside your view like this:
<h1>{{ 'TITLE.HELLO_WORLD' | translate }}</h1>
Angular Translate provides the $translate
service which you can use in your Controllers.
An example usage of the $translate
service can be:
.controller('TranslateMe', ['$scope', '$translate', function ($scope, $translate) {
$translate('PAGE.TITLE')
.then(function (translatedValue) {
$scope.pageTitle = translatedValue;
});
});
The translate service also has a method for directly translating strings without the need to handle a promise, using $translate.instant()
:
.controller('TranslateMe', ['$scope', '$translate', function ($scope, $translate) {
$scope.pageTitle = $translate.instant('TITLE.DASHBOARD'); // Assuming TITLE.DASHBOARD is defined
});
The downside with using $translate.instant()
could be that the language file isn't loaded yet if you are loading it async.
This is my preferred way since I don't have to handle promises this way. The output of the filter can be directly set to a scope variable.
.controller('TranslateMe', ['$scope', '$filter', function ($scope, $filter) {
var $translate = $filter('translate');
$scope.pageTitle = $translate('TITLE.DASHBOARD'); // Assuming TITLE.DASHBOARD is defined
});
Since @PascalPrecht is the creator of this awesome library, I'd recommend going with his advise (see his answer below) and use the provided directive which seems to handle translations very intelligent.
The directive takes care of asynchronous execution and is also clever enough to unwatch translation ids on the scope if the translation has no dynamic values.
use this, it realy works:
data.addColumn no of your key, you can add more columns or remove
<?php
$con=mysql_connect("localhost","USername","Password") or die("Failed to connect with database!!!!");
mysql_select_db("Database Name", $con);
// The Chart table contain two fields: Weekly_task and percentage
//this example will display a pie chart.if u need other charts such as Bar chart, u will need to change little bit to make work with bar chart and others charts
$sth = mysql_query("SELECT * FROM chart");
while($r = mysql_fetch_assoc($sth)) {
$arr2=array_keys($r);
$arr1=array_values($r);
}
for($i=0;$i<count($arr1);$i++)
{
$chart_array[$i]=array((string)$arr2[$i],intval($arr1[$i]));
}
echo "<pre>";
$data=json_encode($chart_array);
?>
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable();
data.addColumn("string", "YEAR");
data.addColumn("number", "NO of record");
data.addRows(<?php $data ?>);
]);
var options = {
title: 'My Weekly Plan',
is3D: 'true',
width: 800,
height: 600
};
// Instantiate and draw our chart, passing in some options.
//do not forget to check ur div ID
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
const generateUniqueId = () => 'id_' + Date.now() + String(Math.random()).substr(2);
// if u want to check for collision
const arr = [];
const checkForCollision = () => {
for (let i = 0; i < 10000; i++) {
const el = generateUniqueId();
if (arr.indexOf(el) > -1) {
alert('COLLISION FOUND');
}
arr.push(el);
}
};
If you happen to be using Mono, then you might be interested to know that Mono 2.8 (to be released later this year) will have a performance counter which reports the physical memory size on all the platforms Mono runs on (including Windows). You would retrieve the value of the counter using this code snippet:
using System;
using System.Diagnostics;
class app
{
static void Main ()
{
var pc = new PerformanceCounter ("Mono Memory", "Total Physical Memory");
Console.WriteLine ("Physical RAM (bytes): {0}", pc.RawValue);
}
}
If you are interested in C code which provides the performance counter, it can be found here.
imho: Apache HTTP Client
usage example:
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;
import java.io.*;
public class HttpClientTutorial {
private static String url = "http://www.apache.org/";
public static void main(String[] args) {
// Create an instance of HttpClient.
HttpClient client = new HttpClient();
// Create a method instance.
GetMethod method = new GetMethod(url);
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
// Read the response body.
byte[] responseBody = method.getResponseBody();
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
System.out.println(new String(responseBody));
} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
// Release the connection.
method.releaseConnection();
}
}
}
some highlight features:
None of the solutions above work perfectly.They either loses CSS or have to include/edit external CSS file. I found a perfect solution that will not lose your CSS nor you have to edit/add external CSS.
HTML:
<div id='printarea'>
<p>This is a sample text for printing purpose.</p>
<input type='button' id='btn' value='Print' onclick='printFunc();'>
</div>
<p>Do not print.</p
JQuery:
function printFunc() {
var divToPrint = document.getElementById('printarea');
var htmlToPrint = '' +
'<style type="text/css">' +
'table th, table td {' +
'border:1px solid #000;' +
'padding;0.5em;' +
'}' +
'</style>';
htmlToPrint += divToPrint.outerHTML;
newWin = window.open("");
newWin.document.write("<h3 align='center'>Print Page</h3>");
newWin.document.write(htmlToPrint);
newWin.print();
newWin.close();
}
In the same way just get their other numbers using the other "People" references
People.TYPE_HOME
People.TYPE_MOBILE
People.TYPE_OTHER
People.TYPE_WORK
<form name="myForm" method="post">
<p>Activity</p>
skiing: <input type="checkbox" name="activity" value="skiing" checked="yes" /><br />
skating: <input type="checkbox" name="activity" value="skating" /><br />
running: <input type="checkbox" name="activity" value="running" /><br />
hiking: <input type="checkbox" name="activity" value="hiking" checked="yes" />
</form>
WITHOUT clicking the button you will have to listen to the change event of the input fields
var confirmField = document.getElementById("confirm_password");
var passwordField = document.getElementById("password");
function checkPasswordMatch(){
var status = document.getElementById("password_status");
var submit = document.getElementById("submit");
status.innerHTML = "";
submit.removeAttribute("disabled");
if(confirmField.value === "")
return;
if(passwordField.value === confirmField.value)
return;
status.innerHTML = "Passwords don't match";
submit.setAttribute("disabled", "disabled");
}
passWordField.addEventListener("change", function(event){
checkPasswordMatch();
});
confirmField.addEventListener("change", function(event){
checkPasswordMatch();
});
then add the status element to your html:
<p id="password_status"></p>
and set the submit button id to submit
... id="submit" />
hope this helps you
I try to avoid using the "SELECT * " option and just pull what data I want or need. The code below is what I use, you may cull out or add columns and aliases per your needs.
I also us "IIF" (instant if) to replace binary 0 or 1 with a yes or no. It just makes it easier to read for the non-techie that may want this info.
Here is what I use:
SELECT
name AS 'User'
, PRINCIPAL_ID
, type AS 'User Type'
, type_desc AS 'Login Type'
, CAST(create_date AS DATE) AS 'Date Created'
, default_database_name AS 'Database Name'
, IIF(is_fixed_role LIKE 0, 'No', 'Yes') AS 'Is Active'
FROM master.sys.server_principals
WHERE type LIKE 's' OR type LIKE 'u'
ORDER BY [User], [Database Name];
GO
Hope this helps.
Here is what I did and I'm happy to say that this worked for me. I too wanted a 2x2, 3x3 etc. grid of items to cover the entire screen. Gridlayouts do not adhere to the width of the screen. LinearLayouts kind of work but you cant use nested weights.
The best option for me was to use Fragments I used this tutorial to get started with what I wanted to do.
Here is some code:
Main Activity:
public class GridHolderActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_6);
}
}
activity_main_6 XML (inflates 3 fragments)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment
android:id="@+id/frag1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:name=".TwoHorizontalGridFragment"
tools:layout="@layout/two_horiz" />
<fragment
android:id="@+id/frag2"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:name=".TwoHorizontalGridFragment"
tools:layout="@layout/two_horiz" />
<fragment
android:id="@+id/frag3"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:name=".Grid.TwoHorizontalGridFragment"
tools:layout="@layout/two_horiz" />
Base fragment layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:layout_height="match_parent">
<ImageQueue
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="@+id/img1"
android:layout_weight="1"/>
<ImageQueue
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="@+id/img2"
android:layout_weight="1"/>
</LinearLayout>
Fragment Class (only handles initialization of a custom view) inflates 2 tiles per fragment
public class TwoHorizontalGridFragment extends Fragment {
private View rootView;
private ImageQueue imageQueue1;
private ImageQueue imageQueue2;
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
/**
* Inflate the layout for this fragment
*/
rootView = inflater.inflate(
R.layout.two_horiz, container, false);
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
imageQueue1 = (ImageQueue)rootView.findViewById(R.id.img1);
imageQueue2 = (ImageQueue)rootView.findViewById(R.id.img2);
imageQueue1.updateFiles();
imageQueue2.updateFiles();
}
}
Thats it!
This is a weird work around to using nested weights, essentially. It gives me a perfect 2x3 grid that fills the entire screen of both my 10 inch tablet and my HTC droid DNA. Let me know how it goes for you!
Your connection to redis is failing. Try restarting your redis server, then starting up your client again by running these 3 commands:
sudo service redis-server restart
redis-server
redis-cli
Here is my two cents:
final String CENT_1 = new Random().nextInt(2) == 0 ? "HEADS" : "TAILS";
final static String CENT_2 = new Random().nextInt(2) == 0 ? "HEADS" : "TAILS";
Example:
package test;
public class Test {
final long OBJECT_ID = new Random().nextLong();
final static long CLASSS_ID = new Random().nextLong();
public static void main(String[] args) {
Test[] test = new Test[5];
for (int i = 0; i < test.length; i++){
test[i] = new Test();
System.out.println("Class id: "+test[i].CLASSS_ID);//<- Always the same value
System.out.println("Object id: "+test[i].OBJECT_ID);//<- Always different
}
}
}
The key is that variables and functions can return different values.Therefore final variables can be assigned with different values.
you just need to use word boundary (\b
) instead of ^
and $
:
\bgarp\b
You could also write
-Wl,-rpath=.
To get rid of that pesky space. It's arguably more readable than adding extra commas (it's exactly what gets passed to ld).
You say you're using:
time.asctime(time.localtime(date_in_seconds_from_bash))
where date_in_seconds_from_bash
is presumably the output of date +%s
.
The time.localtime
function, as the name implies, gives you local time.
If you want UTC, use time.gmtime()
rather than time.localtime()
.
As JamesNoonan33's answer says, the output of date +%s
is timezone invariant, so date +%s
is exactly equivalent to date -u %s
. It prints the number of seconds since the "epoch", which is 1970-01-01 00:00:00 UTC
. The output you show in your question is entirely consistent with that:
date -u
Thu Jul 3 07:28:20 UTC 2014
date +%s
1404372514 # 14 seconds after "date -u" command
date -u +%s
1404372515 # 15 seconds after "date -u" command
The last line below is an example for applying two quantifiers: landscape and smallest width(600dp) screen. Update 600dp with the ones you need.
res/layout/main_activity.xml # For handsets
res/layout-land/main_activity.xml # For handsets in landscape
res/layout-sw600dp/main_activity.xml # For 7” tablets
res/layout-sw600dp-land/main_activity.xml # For 7” tablets in landscape
The above applies to dimens as well
res/values/dimens.xml # For handsets
res/values-land/dimens.xml # For handsets in landscape
res/values-sw600dp/dimens.xml # For 7” tablets
res/values-sw600dp-land/dimens.xml # For 7” tablets in landscape
A useful device metrics: https://material.io/tools/devices/
You can't. You can create a new String that has duplicates removed. Why aren't you using StringBuilder (or StringBuffer, presumably)?
You can run through the string and store the unique characters in a char[] array, keeping track of how many unique characters you've seen. Then you can create a new String using the String(char[], int, int)
constructor.
Also, the problem is a little ambiguous—does “duplicates” mean adjacent repetitions? (In other words, what should happen with abcab
?)
==
:In most programming languages, the comparison operator (==) checks, on the one hand, the data type and on the other hand the content of the variable for equality. The standard comparison operator (==) in PHP behaves differently. This tries to convert both variables into the same data type before the comparison and only then checks whether the content of these variables is the same. The following results are obtained:
<?php
var_dump( 1 == 1 ); // true
var_dump( 1 == '1' ); // true
var_dump( 1 == 2 ); // false
var_dump( 1 == '2' ); // false
var_dump( 1 == true ); // true
var_dump( 1 == false ); // false
?>
===
:This operator also checks the datatype of the variable and returns (bool)true only if both variables have the same content and the same datatype. The following would therefore be correct:
<?php
var_dump( 1 === 1 ); // true
var_dump( 1 === '1' ); // false
var_dump( 1 === 2 ); // false
var_dump( 1 === '2' ); // false
var_dump( 1 === true ); // false
var_dump( 1 === false ); // false
?>
Read more in What is the difference between == and === in PHP
This answer applies to this question if
path below can be relative
PYTHONPATH=/path/to/dir python script.py
Sat Jun 25 09:38:51 [initandlisten] listen(): bind() failed errno:98 Address already in use for socket: 0.0.0.0:27017
is self-speaking.
Another instance of mongod is already running and allocating the MongoDB default port which is 27017.
Either kill the other process or use a different port.
If above answer didn't work for you as it didn't work for me on my Xiaomi Mi5.I tried to figure out the Core reason behind it and solve it. In MIUI, in order to change "Install via USB" option, you must be connected to the internet and signed in your Mi account. Due to some reason, requests from out of the China servers are getting rejected, so I connected to one open China VPN and tried again to enable 'Install via USB' and I got success. For detailed solution and VPN details, see this useful Youtube video: https://youtu.be/MeKUJlD-Ke4
In a terminal emulator like konsole or gnome-terminal, you should to set a 256 color setting for vim.
:set t_Co=256
After that you can to change your background.
ArrayList first = new ArrayList ();
ArrayList copy = (ArrayList) first.clone ();
You have to loop over the input array and add rules for each input as described here: Loop Over Rules
Here is a some code for ya:
$input = Request::all();
$rules = [];
foreach($input['name'] as $key => $val)
{
$rules['name.'.$key] = 'required|distinct|min:3';
}
$rules['amount'] = 'required|integer|min:1';
$rules['description'] = 'required|string';
$validator = Validator::make($input, $rules);
//Now check validation:
if ($validator->fails())
{
/* do something */
}
I know this is really old, but if you are copying and pasting anyway, you can just use:
read.csv(readClipboard())
readClipboard() escapes the back-slashes for you. Just remember to make sure the ".csv" is included in your copy, perhaps with this:
read.csv(paste0(readClipboard(),'.csv'))
And if you really want to minimize your typing you can use some functions:
setWD <- function(){
setwd(readClipboard())
}
readCSV <- function(){
return(readr::read_csv(paste0(readClipboard(),'.csv')))
}
#copy directory path
setWD()
#copy file name
df <- readCSV()
When converting datetime to integers one must keep in mind the tens, hundreds and thousands.... like "2018-11-03" must be like 20181103 in int for that you have to 2018*10000 + 100* 11 + 3
Similarly another example, "2018-11-03 10:02:05" must be like 20181103100205 in int
dt = datetime(2018,11,3,10,2,5)
print (dt)
#print (dt.timestamp()) # unix representation ... not useful when converting to int
print (dt.strftime("%Y-%m-%d"))
print (dt.year*10000 + dt.month* 100 + dt.day)
print (int(dt.strftime("%Y%m%d")))
print (dt.strftime("%Y-%m-%d %H:%M:%S"))
print (dt.year*10000000000 + dt.month* 100000000 +dt.day * 1000000 + dt.hour*10000 + dt.minute*100 + dt.second)
print (int(dt.strftime("%Y%m%d%H%M%S")))
To avoid that doing manually use below function
def datetime_to_int(dt):
return int(dt.strftime("%Y%m%d%H%M%S"))