Very, very late to answer this one, but I've just discovered that using a background-image that is encoded as a base64 URI in the CSS, rather than held as a separate image, continues to animate in IE8.
I have the following in a types.ts
file for html input, select, and textarea:
export type InputChangeEventHandler = React.ChangeEventHandler<HTMLInputElement>
export type TextareaChangeEventHandler = React.ChangeEventHandler<HTMLTextAreaElement>
export type SelectChangeEventHandler = React.ChangeEventHandler<HTMLSelectElement>
Then import them:
import { InputChangeEventHandler } from '../types'
Then use them:
const updateName: InputChangeEventHandler = (event) => {
// Do something with `event.currentTarget.value`
}
const updateBio: TextareaChangeEventHandler = (event) => {
// Do something with `event.currentTarget.value`
}
const updateSize: SelectChangeEventHandler = (event) => {
// Do something with `event.currentTarget.value`
}
Then apply the functions on your markup (replacing ...
with other necessary props):
<input onChange={updateName} ... />
<textarea onChange={updateName} ... />
<select onChange={updateSize} ... >
// ...
</select>
Use Keystore Explorer gui - http://keystore-explorer.sourceforge.net/ - allows you to extract the private key from a .jks in various formats.
Without preg_replace()
$str = "This is a Text \n and so on \t Text text.";
$str = str_replace(["\r", "\n", "\t"], " ", $str);
while (strpos($str, " ") !== false)
{
$str = str_replace(" ", " ", $str);
}
echo $str;
Not sure if this is what you're after, but it will loop through the range that you gave it and if it finds an "A" it will remove it from the cell. I'm not sure what oldStr is used for...
Private Sub foo()
Dim myString As String
RowCount = WorksheetFunction.CountA(Range("A:A"))
For i = 2 To RowCount
myString = Trim(Cells(i, 1).Value)
If InStr(myString, "A") > 0 Then
Cells(i, 1).Value = Left(myString, InStr(myString, "A"))
End If
Next
End Sub
Add image in repository from upload file option then in README file
![Alt text]("enter image url of repositoryhere")
I cleared this use. By using this site click Here , follow the steps, the same steps follows upto the ubuntu version 18.04
StringUtils.isBlank()
checks that each character of the string is a whitespace character (or that the string is empty or that it's null). This is totally different than just checking if the string is empty.
From the linked documentation:
Checks if a String is whitespace, empty ("") or null.
StringUtils.isBlank(null) = true StringUtils.isBlank("") = true StringUtils.isBlank(" ") = true StringUtils.isBlank("bob") = false StringUtils.isBlank(" bob ") = false
For comparison StringUtils.isEmpty:
StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("bob") = false
StringUtils.isEmpty(" bob ") = false
Warning: In java.lang.String.isBlank() and java.lang.String.isEmpty() work the same except they don't return true
for null
.
java.lang.String.isBlank()
(since Java 11)
I like Zarembisty's answer. Although, if you want to be more explicit, you can always do:
if len(my_list) == 0:
print "my_list is empty"
Based on your description of what you want to do, the code seems to be correct as it is. ENDIF isn't a valid SQL loop control keyword. Are you sure that the INSERTS are actually pulling data to put into @Classes? In fact, if it was bad it just wouldn't run.
What you might want to try is to put a few PRINT statements in there. Put a PRINT above each of the INSERTS just outputting some silly text to show that that line is executing. If you get both outputs, then your SELECT...INSERT... is suspect. You could also just do the SELECT in place of the PRINT (that is, without the INSERT) and see exactly what data is being pulled.
If you want to drop rows of data frame on the basis of some complicated condition on the column value then writing that in the way shown above can be complicated. I have the following simpler solution which always works. Let us assume that you want to drop the column with 'header' so get that column in a list first.
text_data = df['name'].tolist()
now apply some function on the every element of the list and put that in a panda series:
text_length = pd.Series([func(t) for t in text_data])
in my case I was just trying to get the number of tokens:
text_length = pd.Series([len(t.split()) for t in text_data])
now add one extra column with the above series in the data frame:
df = df.assign(text_length = text_length .values)
now we can apply condition on the new column such as:
df = df[df.text_length > 10]
def pass_filter(df, label, length, pass_type):
text_data = df[label].tolist()
text_length = pd.Series([len(t.split()) for t in text_data])
df = df.assign(text_length = text_length .values)
if pass_type == 'high':
df = df[df.text_length > length]
if pass_type == 'low':
df = df[df.text_length < length]
df = df.drop(columns=['text_length'])
return df
You can use swift.quicktype.io for converting JSON
to either struct
or class
. Even you can mention version of swift to genrate code.
Example JSON:
{
"message": "Hello, World!"
}
Generated code:
import Foundation
typealias Sample = OtherSample
struct OtherSample: Codable {
let message: String
}
// Serialization extensions
extension OtherSample {
static func from(json: String, using encoding: String.Encoding = .utf8) -> OtherSample? {
guard let data = json.data(using: encoding) else { return nil }
return OtherSample.from(data: data)
}
static func from(data: Data) -> OtherSample? {
let decoder = JSONDecoder()
return try? decoder.decode(OtherSample.self, from: data)
}
var jsonData: Data? {
let encoder = JSONEncoder()
return try? encoder.encode(self)
}
var jsonString: String? {
guard let data = self.jsonData else { return nil }
return String(data: data, encoding: .utf8)
}
}
extension OtherSample {
enum CodingKeys: String, CodingKey {
case message
}
}
You can try and add a new run configuration: Run -> Run Configurations ... -> Select "Java Appliction" and click "New".
Alternatively use the shortcut: place the cursor in the class, then press Alt + Shift + X
to open up a context menu, then press J
.
You can use customValidity
$(function(){ var elements = document.getElementsByTagName("input"); for (var i = 0; i < elements.length; i++) { elements[i].oninvalid = function(e) { e.target.setCustomValidity("This can't be left blank!"); }; } });
I think that will work on at least Chrome and FF, I'm not sure about other browsers
As long as you don't need to support versions of Internet Explorer earlier than IE8, you can use display: table-cell
to accomplish this:
HTML:
<div class="outer">
<div class="inner">
<p>Menu or Whatever</p>
</div>
<div class="inner">
<p>Page contents...</p>
</div>
</div>
CSS:
.inner {
display: table-cell;
}
This will force each element with the .inner
class to occupy the full height of its parent element.
Following up on Timores's elegant solution, I have found that the following creates a vertical fill in a vertical LinearLayout and a horizontal fill in a horizontal LinearLayout:
<Space
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
You're sending JSON-formatted data to a server which isn't expecting that format. You already provided the format that the server needs, so you'll need to format it yourself which is pretty simple.
var data = '"title='+title+'" "text='+text+'" "file='+file+'"';
$http.post(uploadUrl, data)
When using sonar-scanner for swift, use sonar.coverage.exclusions in your sonar-project.properties to exclude any file for only code coverage. If you want to exclude files from analysis as well, you can use sonar.exclusions. This has worked for me in swift
sonar.coverage.exclusions=**/*ViewController.swift,**/*Cell.swift,**/*View.swift
I'm using this way:
IIF(EXISTS (SELECT TOP 1 1
FROM Users
WHERE FirstName = 'John'), 1, 0) AS DoesJohnExist
TL;DR: If it works, avoid, or use specifiers like __attribute__
, otherwise _Pragma
.
This is a short version of my blog article Suppressing Warnings in GCC and Clang.
Consider the following Makefile
CPPFLAGS:=-std=c11 -W -Wall -pedantic -Werror
.PHONY: all
all: puts
for building the following puts.c
source code
#include <stdio.h>
int main(int argc, const char *argv[])
{
while (*++argv) puts(*argv);
return 0;
}
It will not compile because argc
is unused, and the settings are hardcore (-W -Wall -pedantic -Werror
).
There are 5 things you could do:
__attribute__
_Pragma
#pragma
The first attempt should be checking if the source code can be improved to get rid of the warning. In this case we don't want to change the algorithm just because of that, as argc
is redundant with !*argv
(NULL
after last element).
__attribute__
#include <stdio.h>
int main(__attribute__((unused)) int argc, const char *argv[])
{
while (*++argv) puts(*argv);
return 0;
}
If you're lucky, the standard provides a specifier for your situation, like _Noreturn
.
__attribute__
is proprietary GCC extension (supported by Clang and some other compilers like armcc
as well) and will not be understood by many other compilers. Put __attribute__((unused))
inside a macro if you want portable code.
_Pragma
operator_Pragma
can be used as an alternative to #pragma
.
#include <stdio.h>
_Pragma("GCC diagnostic push")
_Pragma("GCC diagnostic ignored \"-Wunused-parameter\"")
int main(int argc, const char *argv[])
{
while (*++argv) puts(*argv);
return 0;
}
_Pragma("GCC diagnostic pop")
The main advantage of the _Pragma
operator is that you could put it inside macros, which is not possible with the #pragma
directive.
Downside: It's almost a tactical nuke, as it works line-based instead of declaration-based.
The _Pragma
operator was introduced in C99.
#pragma
directive.We could change the source code to suppress the warning for a region of code, typically an entire function:
#include <stdio.h>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
int main(int argc, const char *argv[])
{
while (*++argc) puts(*argv);
return 0;
}
#pragma GCC diagnostic pop
Downside: It's almost a tactical nuke, as it works line-based instead of declaration-based.
Note that a similar syntax exists in clang.
We could add the following line to the Makefile
to suppress the warning specifically for puts:
CPPFLAGS:=-std=c11 -W -Wall -pedantic -Werror
.PHONY: all
all: puts
puts.o: CPPFLAGS+=-Wno-unused-parameter
This is probably not want you want in your particular case, but it may help other reads who are in similar situations.
You could use
awk '/test_pattern/ {
match($0, /test_pattern/); print substr($0, RSTART - 10, RLENGTH + 20);
}' file
I do this without external libaries:
var yourArray = ['aaa','bbb','ccc'];
var counter = [];
yourArray.forEach(function(name){
conn.collection(name).drop(function(err) {
counter.push(true);
console.log('dropped');
if(counter.length === yourArray.length){
console.log('all dropped');
}
});
});
My issue is :
return __import__('MySQLdb')
ImportError: No module named MySQLdb
and my resolution :
pip install MySQL-python
yum install mysql-devel.x86_64
at the very beginning, i just installed MySQL-python, but the issue still existed. So i think if this issue happened, you should also take mysql-devel into consideration. Hope this helps.
There is Effort which is an in memory entity framework database provider. I've not actually tried it... Haa just spotted this was mentioned in the question!
Alternatively you could switch to EntityFrameworkCore which has an in memory database provider built-in.
https://github.com/tamasflamich/effort
I used a factory to get a context, so i can create the context close to its use. This seems to work locally in visual studio but not on my TeamCity build server, not sure why yet.
return new MyContext(@"Server=(localdb)\mssqllocaldb;Database=EFProviders.InMemory;Trusted_Connection=True;");
html code
<div class="image-container">
<img src=""/>
</div>
css code
img
{
position: relative;
top: 50%;
transform: translateY(-50%);
}
Below code might help to check if form got more than 1 date field:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Datepicker - Display month & year menus</title>
<link rel="stylesheet" href="jquery-ui.css" />
<script src="jquery-1.8.3.js"></script>
<script src="jquery-ui.js"></script>
<link rel="stylesheet" href="style.css" />
<script>
function pickDate(DateObject){
// alert(DateObject.name)
$(function() {
$("#"+DateObject.name).datepicker({ dateFormat: "dd/mm/yy" }).val()
});
}
/*
$(function() {
$( "#datepicker" ).datepicker({
changeMonth: true,
changeYear: true
});
});
*/
</script>
</head>
<body>
<p>From Date: <input type="text" name="FromDate" id="FromDate" size="9" onfocus="pickDate(this)"/></p>
<p>To Date: <input type="text" name="ToDate" id="ToDate" size="9" onfocus="pickDate(this)" /></p>
</body>
</html>
The simplest way to check the existence of the column in mongo compass is :
{ 'column_name': { $exists: true } }
Use document.location.reload(true)
it will not load page from cache.
We can implement the basic authorization without needing any module
//1.
var http = require('http');
//2.
var credentials = {
userName: "vikas kohli",
password: "vikas123"
};
var realm = 'Basic Authentication';
//3.
function authenticationStatus(resp) {
resp.writeHead(401, { 'WWW-Authenticate': 'Basic realm="' + realm + '"' });
resp.end('Authorization is needed');
};
//4.
var server = http.createServer(function (request, response) {
var authentication, loginInfo;
//5.
if (!request.headers.authorization) {
authenticationStatus (response);
return;
}
//6.
authentication = request.headers.authorization.replace(/^Basic/, '');
//7.
authentication = (new Buffer(authentication, 'base64')).toString('utf8');
//8.
loginInfo = authentication.split(':');
//9.
if (loginInfo[0] === credentials.userName && loginInfo[1] === credentials.password) {
response.end('Great You are Authenticated...');
// now you call url by commenting the above line and pass the next() function
}else{
authenticationStatus (response);
}
});
server.listen(5050);
Source:- http://www.dotnetcurry.com/nodejs/1231/basic-authentication-using-nodejs
The error is exactly what it says it is; you're trying to take sumall[0]
when sumall
is an int and that doesn't make any sense. What do you believe sumall
should be?
// "Main" is name of .storybord file "
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
// "MiniGameView" is the ID given to the ViewController in the interfacebuilder
// MiniGameViewController is the CLASS name of the ViewController.swift file acosiated to the ViewController
var setViewController = mainStoryboard.instantiateViewControllerWithIdentifier("MiniGameView") as MiniGameViewController
var rootViewController = self.window!.rootViewController
rootViewController?.presentViewController(setViewController, animated: false, completion: nil)
This worked fine for me when i put it in AppDelegate
Sending raw POST requests can be sometimes more convenient. Below you can see post.js original example from PhantomJS
// Example using HTTP POST operation
var page = require('webpage').create(),
server = 'http://posttestserver.com/post.php?dump',
data = 'universe=expanding&answer=42';
page.open(server, 'post', data, function (status) {
if (status !== 'success') {
console.log('Unable to post!');
} else {
console.log(page.content);
}
phantom.exit();
});
... or MyEnum.values() ? Or am I missing something?
In my case where I had the problem I was referring to a module when I tried extending the class.
import logging
class UserdefinedLogging(logging):
If you look at the Documentation Info, you'll see "logging" displayed as module.
In this specific case I had to simply inherit the logging module to create an extra class for the logging.
While I strongly disagree with the idea of running a laravel app on shared hosting (a bad idea all around), this package would likely solve your problem. It is a package that allows you to run some artisan commands from the web. It's far from perfect, but can work for some usecases.
Two of the most widely used parsers are Expat and libxml.
If you are okay with using C++, there's Xerces-C++ too.
There is probably no need to use the ldpi
, mdpi
or hdpi
qualifiers in this case.
When you define a dimension in a resource file you include the measurement unit. If you use sp units they are scaled according to the screen density so text at 15sp should appear roughly the same size on screens of differing density.
(The real screen density of the device isn't going to exactly match as Android generalises screen density into 120, 160, 240, 320, 480 and 640 dpi
groups.)
When calling getResources().getDimension(R.dimen.textsize)
it will return the size in pixels. If using sp it will scaled by the screen density,
Calling setText(float)
sets the size in sp units
. This is where the issue is,
i.e you have pixels measurements on one hand and sp unit
on the other to fix do this:
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
getResources().getDimension(R.dimen.textsize));
Note you can also use
getResources().getDimensionPixelSize(R.dimen.textSize);
instead of getDimension()
and it will round and convert to an non fractional value.
On a linux server you can just use this commands to reconfigure Tomcat to listen on port 80:
sed -i 's|port="8080"|port="80"|g' /etc/tomcat?/server.xml
sed -i 's|#AUTHBIND=no|AUTHBIND=yes|g' /etc/default/tomcat?
service tomcat8 restart
The div take the height of its parent, but since it has no content (expecpt for your divs) it will only be as height as its content.
You need to set the height of the body and html:
HTML:
<div class="block12">
<div class="block1">1</div>
<div class="block2">2</div>
</div>
<div class="block3">3</div>
CSS:
body, html {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.block12 {
width: 100%;
height: 50%;
background: yellow;
overflow: auto;
}
.block1, .block2 {
width: 50%;
height: 100%;
display: inline-block;
margin-right: -4px;
background: lightgreen;
}
.block2 { background: lightgray }
.block3 {
width: 100%;
height: 50%;
background: lightblue;
}
And a JSFiddle
A cookie is a bit of data stored by the browser and sent to the server with every request.
A session is a collection of data stored on the server and associated with a given user (usually via a cookie containing an id code)
Add the css for .card
.card {
margin: 0 auto; /* Added */
float: none; /* Added */
margin-bottom: 10px; /* Added */
}
here is the pen
UPDATE:
You can use the class .mx-auto
available in bootstrap 4 to center cards.
Don't Create 9-patch images for launcher icons . You have to make separate image for each one.
LDPI - 36 x 36
MDPI - 48 x 48
HDPI - 72 x 72
XHDPI - 96 x 96
XXHDPI - 144 x 144
XXXHDPI - 192 x 192.
WEB - 512 x 512 (Require when upload application on Google Play)
Note: WEB(512 x 512) image is used when you upload your android application on Market.
|| Android App Icon Size ||
All Devices
hdpi=281*164
mdpi=188*110
xhdpi=375*219
xxhdpi=563*329
xxxhdpi=750*438
48 × 48 (mdpi)
72 × 72 (hdpi)
96 × 96 (xhdpi)
144 × 144 (xxhdpi)
192 × 192 (xxxhdpi)
512 × 512 (Google Play store)
This question already has many answers, but in some cases you can settle for something simpler than all of them. If the string you're looking for is known (hardcoded), you can use regular expressions without any quoting etc.
Check if a string starts with 'ABC':
preg_match('/^ABC/', $myString); // "^" here means beginning of string
ends with 'ABC':
preg_match('/ABC$/', $myString); // "$" here means end of string
In my simple case, I wanted to check if a string ends with slash:
preg_match('#/$#', $myPath); // Use "#" as delimiter instead of escaping slash
The advantage: since it's very short and simple, you don't have to define a function (such as endsWith()
) as shown above.
But again -- this is not a solution for every case, just this very specific one.
You should be able to use the variable name directly
ansible_ssh_host
Or you can go through hostvars without having to specify the host literally
by using the magic variable inventory_hostname
hostvars[inventory_hostname].ansible_ssh_host
Note before you read the rest: The shell script shown here is certainly not safe to use and well tested. Use at your own risk!
I wrote a bash script to accomplish that task. Suppose your library is lib1 and the one you need to include some symbols from is lib2. The script now runs in a loop, where it first checks which undefined symbols from lib1 can be found in lib2. It then extracts the corresponding object files from lib2 with ar
, renames them a bit, and puts them into lib1. Now there may be more missing symbols, because the stuff you included from lib2 needs other stuff from lib2, which we haven't included yet, so the loop needs to run again. If after some passes of the loop there are no changes anymore, i.e. no object files from lib2 added to lib1, the loop can stop.
Note, that the included symbols are still reported as undefined by nm
, so I'm keeping track of the object files, that were added to lib1, themselves, in order to determine whether the loop can be stopped.
#! /bin/bash
lib1="$1"
lib2="$2"
if [ ! -e $lib1.backup ]; then
echo backing up
cp $lib1 $lib1.backup
fi
remove_later=""
new_tmp_file() {
file=$(mktemp)
remove_later="$remove_later $file"
eval $1=$file
}
remove_tmp_files() {
rm $remove_later
}
trap remove_tmp_files EXIT
find_symbols() {
nm $1 $2 | cut -c20- | sort | uniq
}
new_tmp_file lib2symbols
new_tmp_file currsymbols
nm $lib2 -s --defined-only > $lib2symbols
prefix="xyz_import_"
pass=0
while true; do
((pass++))
echo "Starting pass #$pass"
curr=$lib1
find_symbols $curr "--undefined-only" > $currsymbols
changed=0
for sym in $(cat $currsymbols); do
for obj in $(egrep "^$sym in .*\.o" $lib2symbols | cut -d" " -f3); do
echo " Found $sym in $obj."
if [ -e "$prefix$obj" ]; then continue; fi
echo " -> Adding $obj to $lib1"
ar x $lib2 $obj
mv $obj "$prefix$obj"
ar -r -s $lib1 "$prefix$obj"
remove_later="$remove_later $prefix$obj"
((changed=changed+1))
done
done
echo "Found $changed changes in pass #$pass"
if [[ $changed == 0 ]]; then break; fi
done
I named that script libcomp
, so you can call it then e.g. with
./libcomp libmylib.a libwhatever.a
where libwhatever is where you want to include symbols from. However, I think it's safest to copy everything into a separate directory first. I wouldn't trust my script so much (however, it worked for me; I could include libgsl.a into my numerics library with that and leave out that -lgsl compiler switch).
A callback URL will be invoked by the API method you're calling after it's done. So if you call
POST /api.example.com/foo?callbackURL=http://my.server.com/bar
Then when /foo
is finished, it sends a request to http://my.server.com/bar
. The contents and method of that request are going to vary - check the documentation for the API you're accessing.
The accepted answer (its image) is wrong, at least now in QT5. Instead you should assign a layout to the root object/widget (pointing to the aforementioned image, it should be the MainWindow
instead of centralWidget
). Also note that you must have at least one QObject
created beneath it for this to work. Do this and your ui will become responsive to window resizing.
This is a stab in the dark, but maybe do you need to wrap your JSON arguments; like say something like this:
data: "{'Ids':[{'Id1':'2'},{'Id2':'2'}]}"
Make sure your JSON is properly formed?
Java 9 offers a Matcher.replaceAll()
that accepts a replacement function:
resultString = regexMatcher.replaceAll(
m -> String.valueOf(Integer.parseInt(m.group()) * 3));
I have a solution. in my JS I have two functions. First to get Cookies (ie. csrftoken):
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
Second one is my ajax function. in this case it's for login and in fact doesn't return any thing, just pass values to set a session:
function LoginAjax() {
//get scrftoken:
const csrftoken = getCookie('csrftoken');
var req = new XMLHttpRequest();
var userName = document.getElementById("Login-Username");
var password = document.getElementById("Login-Password");
req.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
//read response loggedIn JSON show me if user logged in or not
var respond = JSON.parse(this.responseText);
alert(respond.loggedIn);
}
}
req.open("POST", "login", true);
//following header set scrftoken to resolve problem
req.setRequestHeader('X-CSRFToken', csrftoken);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send("UserName=" + userName.value + "&Password=" + password.value);
}
I had the same problem, mine was a little different though I did not have a package name. My problem was the Class Path for example:
C:\Java Example>java -cp . HelloWorld
The -cp
option for Java and from what I can tell from my experience (not much) but I encountered the error about 20 times trying different methods and until I declared the class Path I was receiving the same error. Vishrant was correct in stating that . represents current directory.
If you need more information about the java options enter java -?
or java -help
I think the options are not optional.
I just did some more research I found a website that goes into detail about CLASSPATH
. The CLASSPATH
must be set as an environment variable; to the current directory <.>. You can set it from the command line in windows:
// Set CLASSPATH to the current directory '.'
prompt> set CLASSPATH=.
When you add a new environment setting you need to reboot before enabling the variable. But from the command prompt you can set it. It also can be set like I mentioned at the beginning. For more info, and if your using a different OS, check: Environment Variables.
scanf("%s",str)
scans only until it finds a whitespace character. With the input "A 1"
, it will scan only the first character, hence s2
points at the garbage that happened to be in str
, since that array wasn't initialised.
According to the documentation (emphasis mine):
Parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".
I didn't think this was possible: I had to delete flutter folder and reinstall it from scratch!
Updated 10-second countdown using Hooks (a new feature proposal that lets you use state and other React features without writing a class. They’re currently in React v16.7.0-alpha).
import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
const Clock = () => {
const [currentCount, setCount] = useState(10);
const timer = () => setCount(currentCount - 1);
useEffect(
() => {
if (currentCount <= 0) {
return;
}
const id = setInterval(timer, 1000);
return () => clearInterval(id);
},
[currentCount]
);
return <div>{currentCount}</div>;
};
const App = () => <Clock />;
ReactDOM.render(<App />, document.getElementById('root'));
The rouine is pretty good, however it causes my app to hang, so I needed to add the case:
<xsl:when test="$text = '' or $replace = ''or not($replace)" >
<xsl:value-of select="$text" />
<!-- Prevent thsi routine from hanging -->
</xsl:when>
before the function gets called recursively.
I got the answer from here: When test hanging in an infinite loop
Thank you!
alternative to stdbuf is awk '{print} END {fflush()}'
I wish there were a bash builtin to do this.
Normally it shouldn't be necessary, but with older versions there might be bash synchronization bugs on file descriptors.
This way works well for me:
Add onSubmit
attribute in your form
, don't forget to include return
in the value.
<form id='frm-contact' method='POST' action='' onSubmit="return contact()">
Define the function.
function contact(params) {
$.ajax({
url: 'sendmail.php',
type: "POST",
dataType: "json",
timeout: 5000,
data: { params:params },
success: function (data, textStatus, jqXHR) {
// callback
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR.responseText);
}
});
return false;
}
The sumplest solution is:
From the project dir:
sudo chmod 777 -R .git/objects
Should be
private ArrayList<String[]> action = new ArrayList<String[]>();
action.add(new String[2]);
...
You can't specify the size of the array within the generic parameter, only add arrays of specific size to the list later. This also means that the compiler can't guarantee that all sub-arrays be of the same size, it must be ensured by you.
A better solution might be to encapsulate this within a class, where you can ensure the uniform size of the arrays as a type invariant.
It sometimes happen even when we stop running processes in IDE with help of Red button , we continue to get same error.
It was resolved with following steps,
Check what processes are running at available ports
netstat -ao |find /i "listening"
We get following
TCP 0.0.0.0:7981 machinename:0 LISTENING 2428
TCP 0.0.0.0:7982 machinename:0 LISTENING 2428
TCP 0.0.0.0:8080 machinename:0 LISTENING 12704
TCP 0.0.0.0:8500 machinename:0 LISTENING 2428
i.e. Port Numbers and what Process Id they are listening to
Stop process running at your port number(In this case it is 8080 & Process Id is 12704)
Taskkill /F /IM 12704
(Note: Mention correct Process Id)
For more information follow these links Link1 and Link2.
My Issue was resolved with this, Hope this helps !
string result = myList.FirstOrDefault(x => x == myString)
if(result != null)
{
//found
}
Here's what I ended up doing:
Obj.writeToStream(toWrite, os);
try {
String out = new String(os.toByteArray(), "UTF-8");
assertTrue(out.contains("testString"));
} catch (UnsupportedEncondingException e) {
fail("Caught exception: " + e.getMessage());
}
Where os is a ByteArrayOutputStream
.
Simply type conda update pandas
in your preferred shell (on Windows, use cmd; if Anaconda is not added to your PATH use the Anaconda prompt). You can of course use Eclipse together with Anaconda, but you need to specify the Python-Path (the one in the Anaconda-Directory).
See this document for a detailed instruction.
You can save the JavaScript into local files:
Into the first file, player_api
put this code:
if(!window.YT)var YT={loading:0,loaded:0};if(!window.YTConfig)var YTConfig={host:"https://www.youtube.com"};YT.loading||(YT.loading=1,function(){var o=[];YT.ready=function(n){YT.loaded?n():o.push(n)},window.onYTReady=function(){YT.loaded=1;for(var n=0;n<o.length;n++)try{o[n]()}catch(i){}},YT.setConfig=function(o){for(var n in o)o.hasOwnProperty(n)&&(YTConfig[n]=o[n])}}());
Into the second file, find the code: this.a.contentWindow.postMessage(a,b[c]);
and replace it with:
if(this._skiped){
this.a.contentWindow.postMessage(a,b[c]);
}
this._skiped = true;
Of course, you can concatenate into one file - will be more efficient. This is not a perfect solution, but it's works!
My Source : yt_api-concat
If you don't mind a Perl one-liner:
$ perl -CS -E 'say "\x{2620}"'
?
-CS
enables UTF-8 decoding on input and UTF-8 encoding on output. -E
evaluates the next argument as Perl, with modern features like say
enabled. If you don't want a newline at the end, use print
instead of say
.
If you want a true O(n)
algorithm, as opposed to O(kn)
or something like that, then you should use quickselect (it's basically quicksort where you throw out the partition that you're not interested in). My prof has a great writeup, with the runtime analysis: (reference)
The QuickSelect algorithm quickly finds the k-th smallest element of an unsorted array of n
elements. It is a RandomizedAlgorithm, so we compute the worst-case expected running time.
Here is the algorithm.
QuickSelect(A, k)
let r be chosen uniformly at random in the range 1 to length(A)
let pivot = A[r]
let A1, A2 be new arrays
# split into a pile A1 of small elements and A2 of big elements
for i = 1 to n
if A[i] < pivot then
append A[i] to A1
else if A[i] > pivot then
append A[i] to A2
else
# do nothing
end for
if k <= length(A1):
# it's in the pile of small elements
return QuickSelect(A1, k)
else if k > length(A) - length(A2)
# it's in the pile of big elements
return QuickSelect(A2, k - (length(A) - length(A2))
else
# it's equal to the pivot
return pivot
What is the running time of this algorithm? If the adversary flips coins for us, we may find that the pivot is always the largest element and k
is always 1, giving a running time of
T(n) = Theta(n) + T(n-1) = Theta(n2)
But if the choices are indeed random, the expected running time is given by
T(n) <= Theta(n) + (1/n) ?i=1 to nT(max(i, n-i-1))
where we are making the not entirely reasonable assumption that the recursion always lands in the larger of A1
or A2
.
Let's guess that T(n) <= an
for some a
. Then we get
T(n)
<= cn + (1/n) ?i=1 to nT(max(i-1, n-i))
= cn + (1/n) ?i=1 to floor(n/2) T(n-i) + (1/n) ?i=floor(n/2)+1 to n T(i)
<= cn + 2 (1/n) ?i=floor(n/2) to n T(i)
<= cn + 2 (1/n) ?i=floor(n/2) to n ai
and now somehow we have to get the horrendous sum on the right of the plus sign to absorb the cn
on the left. If we just bound it as 2(1/n) ?i=n/2 to n an
, we get roughly 2(1/n)(n/2)an = an
. But this is too big - there's no room to squeeze in an extra cn
. So let's expand the sum using the arithmetic series formula:
?i=floor(n/2) to n i
= ?i=1 to n i - ?i=1 to floor(n/2) i
= n(n+1)/2 - floor(n/2)(floor(n/2)+1)/2
<= n2/2 - (n/4)2/2
= (15/32)n2
where we take advantage of n being "sufficiently large" to replace the ugly floor(n/2)
factors with the much cleaner (and smaller) n/4
. Now we can continue with
cn + 2 (1/n) ?i=floor(n/2) to n ai,
<= cn + (2a/n) (15/32) n2
= n (c + (15/16)a)
<= an
provided a > 16c
.
This gives T(n) = O(n)
. It's clearly Omega(n)
, so we get T(n) = Theta(n)
.
FLAG_ACTIVITY_NO_HISTORY when starting the activity you wish to finish after the user goes to another one.
http://developer.android.com/reference/android/content/Intent.html#FLAG%5FACTIVITY%5FNO%5FHISTORY
The poster's second comment from September 21st is spot on. For those who may be coming to this thread later with the same problem as the poster, here is a brief explanation. The other answers are good to keep in mind, but do not address the common issue encountered by this code.
In Swift, declarations made with the let
keyword are constants. Of course if you were going to add items to an array, the array can't be declared as a constant, but a segmented control should be fine, right?! Not if you reference the completed segmented control in its declaration.
Referencing the object (in this case a UISegmentedControl
, but this also happens with UIButton
) in its declaration when you say .addTarget
and let the target be self
, things crash. Why? Because self
is in the midst of being defined. But we do want to define behaviour as part of the object... Declare it lazily as a variable with var
. The lazy
fools the compiler into thinking that self
is well defined - it silences your compiler from caring at the time of declaration. Lazily declared variables don't get set until they are first called. So in this situation, lazy
lets you use the notion of self
without issue while you set up the object, and then when your object gets a .touchUpInside
or .valueChanged
or whatever your 3rd argument is in your .addTarget()
, THEN it calls on the notion of self
, which at that point is fully established and totally prepared to be a valid target. So it lets you be lazy in declaring your variable. In cases like these, I think they could give us a keyword like necessary
, but it is generally seen as a lazy, sloppy practice and you don't want to use it all over your code, though it may have its place in this sort of situation. What it
There is no lazy let
in Swift (no lazy
for constants).
Here is the Apple documentation on lazy.
Here is the Apple on variables and constants. There is a little more in their Language Reference under Declarations.
import java.util.HashMap;
import java.util.Scanner;
public class HashMapDemo {
public static void main(String[] args) {
//Create HashMap object to Store Element as Key and Value
HashMap<Character,Integer> hm= new HashMap<Character,Integer>();
//Enter Your String From Console
System.out.println("Enter an String:");
//Create Scanner Class Object From Retrive the element from console to our java application
Scanner sc = new Scanner(System.in);
//Store Data in an string format
String s1=sc.nextLine();
//find the length of an string and check that hashmap object contain the character or not by using
//containskey() if that map object contain element only one than count that value as one or if it contain more than one than increment value
for(int i=0;i<s1.length();i++){
if(!hm.containsKey(s1.charAt(i))){
hm.put(s1.charAt(i),(Integer)1);
}//if
else{
hm.put(s1.charAt(i),hm.get(s1.charAt(i))+1);
}//else
}//for
System.out.println("The Charecters are:"+hm);
}//main
}//HashMapDemo
Here's how I solved the problem today after hours of trying all of these different solutions - (for anyone looking for another way still).
Open 2 instances of cmd at your quickstart dir:
window #1:
npm run build:watch
then...
window #2:
npm run serve
It will then open in the browser and work as expected
window.location
sets the URL of your current window. To open a new window, you need to use window.open
. This should work:
function ToKey(){
var key = document.tokey.key.value.toLowerCase();
if (key == "smk") {
window.open('http://www.smkproduction.eu5.org', '_blank');
} else {
alert("Kodi nuk është valid!");
}
}
Use:
if (containerObject.has("video")) {
//get value of video
}
Use following layerlist
:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" android:padding="10dp">
<corners
android:bottomRightRadius="5dp"
android:bottomLeftRadius="5dp"
android:topLeftRadius="5dp"
android:topRightRadius="5dp"/>
</shape>
</item>
<item android:drawable="@drawable/image_name_here" />
</layer-list>
You can use iter to process lines as soon as the command outputs them: lines = iter(fd.readline, "")
. Here's a full example showing a typical use case (thanks to @jfs for helping out):
from __future__ import print_function # Only Python 2.x
import subprocess
def execute(cmd):
popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)
for stdout_line in iter(popen.stdout.readline, ""):
yield stdout_line
popen.stdout.close()
return_code = popen.wait()
if return_code:
raise subprocess.CalledProcessError(return_code, cmd)
# Example
for path in execute(["locate", "a"]):
print(path, end="")
If you want to remove EVERYTHING :
textarea {
border: none;
background-color: transparent;
resize: none;
outline: none;
}
RJSONIO from Omegahat is another package which provides facilities for reading and writing data in JSON format.
rjson does not use S4/S3 methods and so is not readily extensible, but still useful. Unfortunately, it does not used vectorized operations and so is too slow for non-trivial data. Similarly, for reading JSON data into R, it is somewhat slow and so does not scale to large data, should this be an issue.
Update (new Package 2013-12-03):
jsonlite: This package is a fork of the RJSONIO
package. It builds on the parser from RJSONIO
but implements a different mapping between R objects and JSON strings. The C code in this package is mostly from the RJSONIO
Package, the R code has been rewritten from scratch. In addition to drop-in replacements for fromJSON
and toJSON
, the package has functions to serialize objects. Furthermore, the package contains a lot of unit tests to make sure that all edge cases are encoded and decoded consistently for use with dynamic data in systems and applications.
Example - sending some data encoded as JSON as a POST data:
import json
import urllib2
data = json.dumps([1, 2, 3])
f = urllib2.urlopen(url, data)
response = f.read()
f.close()
To remove the hash, you may try using this function
function remove_hash_from_url()
{
var uri = window.location.toString();
if (uri.indexOf("#") > 0) {
var clean_uri = uri.substring(0, uri.indexOf("#"));
window.history.replaceState({}, document.title, clean_uri);
}
}
Experienced this on ubuntu 16.04 running PHP 7.1.14. To resolve,first put this in a script and execute. It will return true if curl is installed and enabled,otherwise, it will return false.
<?php
var_dump(extension_loaded('curl'));
?>
If it returns false, run
sudo apt-get install php7.1-curl
And finally,
sudo service apache2 restart
After the restart, the script will return true and hopefully, your error should be resolved.
mysql Export the query results command line:
mysql -h120.26.133.63 -umiyadb -proot123 miya -e "select * from user where id=1" > mydumpfile.txt
First, add new VB code file in your project.
or press Ctrl+Shift+A
COPY & PASTE following code into this file and give it a suitable name. (i.e. KeyValidation.vb)
Imports System.Text.RegularExpressions
Module Module1
Public Enum ValidationType
Only_Numbers = 1
Only_Characters = 2
Not_Null = 3
Only_Email = 4
Phone_Number = 5
End Enum
Public Sub AssignValidation(ByRef CTRL As Windows.Forms.TextBox, ByVal Validation_Type As ValidationType)
Dim txt As Windows.Forms.TextBox = CTRL
Select Case Validation_Type
Case ValidationType.Only_Numbers
AddHandler txt.KeyPress, AddressOf number_Leave
Case ValidationType.Only_Characters
AddHandler txt.KeyPress, AddressOf OCHAR_Leave
Case ValidationType.Not_Null
AddHandler txt.Leave, AddressOf NotNull_Leave
Case ValidationType.Only_Email
AddHandler txt.Leave, AddressOf Email_Leave
Case ValidationType.Phone_Number
AddHandler txt.KeyPress, AddressOf Phonenumber_Leave
End Select
End Sub
Public Sub number_Leave(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
Dim numbers As Windows.Forms.TextBox = sender
If InStr("1234567890.", e.KeyChar) = 0 And Asc(e.KeyChar) <> 8 Or (e.KeyChar = "." And InStr(numbers.Text, ".") > 0) Then
e.KeyChar = Chr(0)
e.Handled = True
End If
End Sub
Public Sub Phonenumber_Leave(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
Dim numbers As Windows.Forms.TextBox = sender
If InStr("1234567890.()-+ ", e.KeyChar) = 0 And Asc(e.KeyChar) <> 8 Or (e.KeyChar = "." And InStr(numbers.Text, ".") > 0) Then
e.KeyChar = Chr(0)
e.Handled = True
End If
End Sub
Public Sub OCHAR_Leave(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
If InStr("1234567890!@#$%^&*()_+=-", e.KeyChar) > 0 Then
e.KeyChar = Chr(0)
e.Handled = True
End If
End Sub
Public Sub NotNull_Leave(ByVal sender As Object, ByVal e As System.EventArgs)
Dim No As Windows.Forms.TextBox = sender
If No.Text.Trim = "" Then
MsgBox("This field Must be filled!")
No.Focus()
End If
End Sub
Public Sub Email_Leave(ByVal sender As Object, ByVal e As System.EventArgs)
Dim Email As Windows.Forms.TextBox = sender
If Email.Text <> "" Then
Dim rex As Match = Regex.Match(Trim(Email.Text), "^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,3})$", RegexOptions.IgnoreCase)
If rex.Success = False Then
MessageBox.Show("Please Enter a valid Email Address", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
Email.BackColor = Color.Red
Email.Focus()
Exit Sub
Else
Email.BackColor = Color.White
End If
End If
End Sub
End Module
Now use following code to Form Load Event like below.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
AssignValidation(Me.TextBox1, ValidationType.Only_Digits)
AssignValidation(Me.TextBox2, ValidationType.Only_Characters)
AssignValidation(Me.TextBox3, ValidationType.No_Blank)
AssignValidation(Me.TextBox4, ValidationType.Only_Email)
End Sub
Done..!
Just came acreoss this, and since I had the same issue, I'd just post the results I came up with
when parsing, you could update the offset (ie I am parsing a data (1.1.2014) and I only want the date, 1st Jan 2014. On GMT+1 I'd get 31.12.2013. So I offset the value first.
moment(moment.utc('1.1.2014').format());
Well, came in handy for me to support across timezones
B
Try something like:
from tkinter import Tk, Button, Frame, Entry, END
class ABC(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
root = Tk()
app = ABC(master=root)
app.master.title("Simple Prog")
app.mainloop()
root.destroy()
Now you should have a frame with a title, then afterwards you can add windows for different widgets if you like.
Apart from the fantastic answers that were already provided, if it is just a matter of printing out the data you may consider using awk
:
awk -F";" '{for (i=1;i<=NF;i++) printf("> [%s]\n", $i)}' <<< "$IN"
This sets the field separator to ;
, so that it can loop through the fields with a for
loop and print accordingly.
$ IN="[email protected];[email protected]"
$ awk -F";" '{for (i=1;i<=NF;i++) printf("> [%s]\n", $i)}' <<< "$IN"
> [[email protected]]
> [[email protected]]
With another input:
$ awk -F";" '{for (i=1;i<=NF;i++) printf("> [%s]\n", $i)}' <<< "a;b;c d;e_;f"
> [a]
> [b]
> [c d]
> [e_]
> [f]
Diagnostics:
You can see which java version Maven uses by running "mvn --version"
Solution for Debian:
The mvn script sets the JAVA_HOME env variable internally by looking for javac (which javac). Therefore, if you have multiple java versions installed concurrently, e.g. JDK 6 and JDK 7 and use the Debian Alternatives system to choose between them, even though you changed the alternative for "java" to JDK 7, mvn will still use JDK 6. You have to change the alternative for "javac", too. E.g.:
# update-alternatives --set javac /usr/lib/jvm/java-7-openjdk-amd64/bin/javac
EDIT:
Actually, an even better solution is to use update-java-alternatives (e.g.)
# update-java-alternatives -s java-1.7.0-openjdk-amd64
as detailed in https://wiki.debian.org/JavaPackage, because this will change all the alternatives to various Java tools (there's a dozen or so).
What you put directly under src/main/java
is in the default package, at the root of the classpath. It's the same for resources put under src/main/resources
: they end up at the root of the classpath.
So the path of the resource is app-context.xml
, not main/resources/app-context.xml
.
I had set:
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender log4j.appender.R.DatePattern='.'yyyy-MM-dd # Archive log files (Keep one year of daily files) log4j.appender.R.MaxBackupIndex=367
Like others before me, the DEBUG option showed me the error:
log4j:WARN No such property [maxBackupIndex] in org.apache.log4j.DailyRollingFileAppender.
Here is an idea I have not tried yet, suppose I set the DatePattern such that the files overwrite each other after the required time period. To retain a year's worth I could try setting:
log4j.appender.R.DatePattern='.'MM-dd
Would it work or would it cause an error ? Like that it will take a year to find out, I could try:
log4j.appender.R.DatePattern='.'dd
but it will still take a month to find out.
You could use CONCAT, and the numeric argument of it is converted to its equivalent binary string form.
select t2.*
from t1 join t2
on t2.url=CONCAT('site.com/path/%', t1.id, '%/more') where t1.id > 9000
Deleting a null pointer has no effect. It's not good coding style necessarily because it's not needed, but it's not bad either.
If you are searching for good coding practices consider using smart pointers instead so then you don't need to delete
at all.
TLS/SSL (The S in HTTPS) guarantees that there are no eavesdroppers between you and the server you are contacting, i.e. no proxies. Normally, you use CONNECT
to open up a TCP connection through the proxy. In this case, the proxy will not be able to cache, read, or modify any requests/responses, and therefore be rather useless.
If you want the proxy to be able to read information, you can take the following approach:
An example is Squid's SSL bump. Similarly, burp can be configured to do this. This has also been used in a less-benign context by an Egyptian ISP.
Note that modern websites and browsers can employ HPKP or built-in certificate pins which defeat this approach.
There is no installation per se.
You download jQuery and include it in your html files like this:
<script src="jquery.js" type="text/javascript"></script>
Of course, modify the filename so that it's the same as the downloaded script file.
Done!
NSString *deviceType = [UIDevice currentDevice].model;
It's very simple to define a function inside razor.
@functions {
public static HtmlString OrderedList(IEnumerable<string> items)
{ }
}
So you can call a the function anywhere. Like
@Functions.OrderedList(new[] { "Blue", "Red", "Green" })
However, this same work can be done through helper
too. As an example
@helper OrderedList(IEnumerable<string> items){
<ol>
@foreach(var item in items){
<li>@item</li>
}
</ol>
}
So what is the difference?? According to this previous post both @helpers and @functions do share one thing in common - they make code reuse a possibility within Web Pages. They also share another thing in common - they look the same at first glance, which is what might cause a bit of confusion about their roles. However, they are not the same. In essence, a helper is a reusable snippet of Razor sytnax exposed as a method, and is intended for rendering HTML to the browser, whereas a function is static utility method that can be called from anywhere within your Web Pages application. The return type for a helper is always HelperResult, whereas the return type for a function is whatever you want it to be.
When you use float without width, there remains some space in that row. To block this space you can use clear:both;
in next element.
if string is a variable, use the .repr method on it:
>>> s = '\tgherkin\n'
>>> s
'\tgherkin\n'
>>> print(s)
gherkin
>>> print(s.__repr__())
'\tgherkin\n'
If someone uses AndroidStudio make sure that the assets folder is placed in
app/src/main/assets
directory.
SELECT datetime('now', 'localtime');
Try this code:
Drawable thumb = ContextCompat.getDrawable(getActivity(), R.mipmap.cir_32);
mSeekBar.setThumb(thumb);
A tree in Python is quite simple. Make a class that has data and a list of children. Each child is an instance of the same class. This is a general n-nary tree.
class Node(object):
def __init__(self, data):
self.data = data
self.children = []
def add_child(self, obj):
self.children.append(obj)
Then interact:
>>> n = Node(5)
>>> p = Node(6)
>>> q = Node(7)
>>> n.add_child(p)
>>> n.add_child(q)
>>> n.children
[<__main__.Node object at 0x02877FF0>, <__main__.Node object at 0x02877F90>]
>>> for c in n.children:
... print c.data
...
6
7
>>>
This is a very basic skeleton, not abstracted or anything. The actual code will depend on your specific needs - I'm just trying to show that this is very simple in Python.
I used SCSS, and the fully responsive modal:
.modal-dialog.large {
@media (min-width: $screen-sm-min) { width:500px; }
@media (min-width: $screen-md-min) { width:700px; }
@media (min-width: $screen-lg-min) { width:850px; }
}
You shouldn't edit it, you should completely scrap it.
Any attempt to make execution stop for a certain amount of time will lock up the browser and switch it to a Not Responding state. The only thing you can do is use setTimeout
correctly.
try:
a # does a exist in the current namespace
except NameError:
a = 10 # nope
I started by using the answers here, but modified it to use YouTube's new iframe
embedding...
$('a.more').on('click', function(event) {
event.preventDefault();
$.fancybox({
'type' : 'iframe',
// hide the related video suggestions and autoplay the video
'href' : this.href.replace(new RegExp('watch\\?v=', 'i'), 'embed/') + '?rel=0&autoplay=1',
'overlayShow' : true,
'centerOnScroll' : true,
'speedIn' : 100,
'speedOut' : 50,
'width' : 640,
'height' : 480
});
});
To disable auto activation of conda base environment in terminal:
conda config --set auto_activate_base false
To activate conda base environment:
conda activate
This is for others who may encounter the following requirements:
If you're like me (using WPF with .NET 4.5) and found that the solutions involving style triggers simply didn't work, here's my solution:
Replace the ControlTemplate of the ListViewItem in a style:
<ListView ItemsSource="{Binding MyStrings}" ItemTemplate="{StaticResource dtStrings}">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListViewItem">
<ContentPresenter/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListView.ItemContainerStyle>
</ListView>
..And the DataTemplate:
<DataTemplate x:Key="dtStrings">
<Border Background="LightCoral" Width="80" Height="24" Margin="1">
<Grid >
<Border Grid.ColumnSpan="2" Background="#88FF0000" Visibility="{Binding RelativeSource={RelativeSource AncestorType=ListViewItem}, Path=IsMouseOver, Converter={StaticResource conBoolToVisibilityTrueIsVisibleFalseIsCollapsed}}"/>
<Rectangle Grid.Column="0" Fill="Lime" Width="10" HorizontalAlignment="Left" Visibility="{Binding RelativeSource={RelativeSource AncestorType=ListViewItem}, Path=IsSelected, Converter={StaticResource conBoolToVisibilityTrueIsVisibleFalseIsCollapsed}}" />
<TextBlock Grid.Column="1" Text="{Binding}" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White" />
</Grid>
</Border>
</DataTemplate>
Results in this at runtime (item 'B' is selected, item 'D' has mouse over):
try:
[checked]="item.checked"
check out: How to Deal with Different Form Controls in Angular
Just add the following rules to the parent element:
display: flex;
justify-content: center; /* align horizontal */
align-items: center; /* align vertical */
Here's a sample demo (Resize window to see the image align)
Browser support for Flexbox nowadays is quite good.
For cross-browser compatibility for display: flex
and align-items
, you can add the older flexbox syntax as well:
display: -webkit-box;
display: -webkit-flex;
display: -moz-box;
display: -ms-flexbox;
display: flex;
-webkit-flex-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
1) Download the JDBC Driver here.
2) unzip the file and go to sqljdbc_version\fra\auth\x86 or \x64
3) copy the sqljdbc_auth.dll to C:\Program Files\Java\jre_Version\bin
4) Finally restart eclipse
Here's the more concise and easy to read solution based on offset width difference:
function getScrollbarWidth(): number {
// Creating invisible container
const outer = document.createElement('div');
outer.style.visibility = 'hidden';
outer.style.overflow = 'scroll'; // forcing scrollbar to appear
outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps
document.body.appendChild(outer);
// Creating inner element and placing it in the container
const inner = document.createElement('div');
outer.appendChild(inner);
// Calculating difference between container's full width and the child width
const scrollbarWidth = (outer.offsetWidth - inner.offsetWidth);
// Removing temporary elements from the DOM
outer.parentNode.removeChild(outer);
return scrollbarWidth;
}
See the JSFiddle.
Imagine you've thread A and thread B. They are both synchronised
on the same object and inside this block there's a global variable they are both updating;
static boolean commonVar = false;
Object lock = new Object;
...
void threadAMethod(){
...
while(commonVar == false){
synchornized(lock){
...
commonVar = true
}
}
}
void threadBMethod(){
...
while(commonVar == true){
synchornized(lock){
...
commonVar = false
}
}
}
So, when thread A enters in the while
loop and holds the lock, it does what it has to do and set the commonVar
to true
. Then thread B comes in, enters in the while
loop and since commonVar
is true
now, it is be able to hold the lock. It does so, executes the synchronised
block, and sets commonVar
back to false
. Now, thread A again gets it's new CPU window, it was about to quit the while
loop but thread B has just set it back to false
, so the cycle repeats over again. Threads do something (so they're not blocked in the traditional sense) but for pretty much nothing.
It maybe also nice to mention that livelock does not necessarily have to appear here. I'm assuming that the scheduler favours the other thread once the synchronised
block finish executing. Most of the time, I think it's a hard-to-hit expectation and depends on many things happening under the hood.
If you want to know the number of visitors (as is titled in the question) and not the number of pageviews, then you'll need to create a custom report.
Google Analytics has changed the terminology they use within the reports. Now, visits is named "sessions" and unique visitors is named "users."
User - A unique person who has visited your website. Users may visit your website multiple times, and they will only be counted once.
Session - The number of different times that a visitor came to your site.
Pageviews - The total number of pages that a user has accessed.
0 */2 * * *
The answer is from https://crontab.guru/every-2-hours. It is interesting.
Yes, image alt text can be styled using any style property you use for regular text, such as font-size, font-weight, line-height, color, background-color,etc. The line-height (of text) or vertical-align (if display:table-cell used) could also be used to vertically align alt text within an image element or image wrapping container, i.e. div.
To prevent accessibility issues regarding contrast, and inheriting the browser's default black font color when you've set a dark blue background-color, always set both the color of your font and its background-color at the same time.
for some more useful info, visit Alternate text for background images or The Ultimate Guide to Styled ALT Text in Email
Using the Interop you get a range of cells and call the .Merge()
method on that range.
eWSheet.Range[eWSheet.Cells[1, 1], eWSheet.Cells[4, 1]].Merge();
I create a file dif.go
that contains your code:
package dif
import (
"time"
)
var StartTime = time.Now()
Outside the folder I create my main.go
, it is ok!
package main
import (
dif "./dif"
"fmt"
)
func main() {
fmt.Println(dif.StartTime)
}
Outputs:
2016-01-27 21:56:47.729019925 +0800 CST
Files directory structure:
folder
main.go
dif
dif.go
It works!
Objective-C is not Java. In Objective-C exceptions are what they are called. Exceptions! Don’t use them for error handling. It’s not their proposal. Just check the length of the string before using characterAtIndex and everything is fine....
you can simply use this
startActivity(new Intent(this, Splash.class));
moveTaskToBack(true);
The startActivity(new Intent(this, Splash.class));
is the first class that will be lauched when the application starts
moveTaskToBack(true);
will minimize your application
I will provide really simple solution to the problem.
Suppose we have two inputs username
and password
,but we want our handle to be easy and generic ,so we can reuse it and don't write boilerplate code.
I.Our form:
<form>
<input type="text" name = "username" onChange={this.onChange} value={this.state.username}/>
<input type="text" name = "password" onChange={this.onChange} value={this.state.password}/>
<br></br>
<button type="submit">Submit</button>
</form>
II.Our constructor ,which we want to save our username
and password
,so we can access them easily:
constructor(props) {
super(props);
this.state = {
username: '',
password: ''
};
this.onSubmit = this.onSubmit.bind(this);
this.onChange = this.onChange.bind(this);
}
III.The interesting and "generic" handle with only one onChange
event is based on this:
onChange(event) {
let inputName = event.target.name;
let value = event.target.value;
this.setState({[inputName]:value});
event.preventDefault();
}
Let me explain:
1.When a change is detected the onChange(event)
is called
2.Then we get the name parameter of the field and its value:
let inputName = event.target.name; ex: username
let value = event.target.value; ex: itsgosho
3.Based on the name parameter we get our value from the state in the constructor and update it with the value:
this.state['username'] = 'itsgosho'
4.The key to note here is that the name of the field must match with our parameter in the state
Hope I helped someone somehow :)
Eclipse Toolbar > Windows > Preferences > General (Right side) > Editors (Right side) > Text Editors (Right side) > Annotations (Right side)
For Occurrences and Write Occurrences, make sure you DO have the 'Text as highlighted' option checked for all of them. See screenshot below:
After Python 3.4, you can also use pathlib
's class Path
to move file.
from pathlib import Path
Path("path/to/current/file.foo").rename("path/to/new/destination/for/file.foo")
https://docs.python.org/3.4/library/pathlib.html#pathlib.Path.rename
In jQuery, you can do alert($("#theid").css("width"))
.
-- if you haven't taken a look at jQuery, I highly recommend it; it makes many simple javascript tasks effortless.
for the record, this post is 5 years old. The web has developed, moved on, etc. There are ways to do this with Plain Old Javascript, which is better.
I was having a problem building notifications (only developing for Android 4.0+). This link showed me exactly what I was doing wrong and says the following:
Required notification contents
A Notification object must contain the following:
A small icon, set by setSmallIcon()
A title, set by setContentTitle()
Detail text, set by setContentText()
Basically I was missing one of these. Just as a basis for troubleshooting with this, make sure you have all of these at the very least. Hopefully this will save someone else a headache.
Just after your Page_Load add this:
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
}
Note that I don't do anything in the function.
EDIT: Tim answered the same thing. :) You can also find the answer Here
If you want to specifically use java ArrayList then you can do something like this:
fun initList(){
val list: ArrayList<String> = ArrayList()
list.add("text")
println(list)
}
Otherwise @guenhter answer is the one you are looking for.
A library and demo with the complete source code for scrolling toolbars or any type of header can be downloaded here:
https://github.com/JohannBlake/JBHeaderScroll
Headers can be Toolbars, LinearLayouts, RelativeLayouts, or whatever type of view you use to create a header.
The scrollable area can be any type of scroll content including ListView, ScrollView, WebView, RecyclerView, RelativeLayout, LinearLayout or whatever you want.
There's even support for nested headers.
It is indeed a complex undertaking to synchronize headers (toolbars) and scrollable content the way it's done in Google Newsstand.
This library doesn't require implementing any kind of onScrollListener.
The solutions listed above by others are only half baked solutions that don't take into consideration that the top edge of the scrollable content area beneath the toolbar has to initially be aligned to the bottom edge of the toolbar and then during scrolling the content area needs to be repositioned and possibly resized. The JBHeaderScroll handles all these issues.
The python code you write is compiled into python bytecode, which creates file with extension .pyc. If compiles, again question is, why not compiled language.
Note that this isn't compilation in the traditional sense of the word. Typically, we’d say that compilation is taking a high-level language and converting it to machine code. But it is a compilation of sorts. Compiled in to intermediate code not into machine code (Hope you got it Now).
Back to the execution process, your bytecode, present in pyc file, created in compilation step, is then executed by appropriate virtual machines, in our case, the CPython VM The time-stamp (called as magic number) is used to validate whether .py file is changed or not, depending on that new pyc file is created. If pyc is of current code then it simply skips compilation step.
Seeing that it appears you are running using the SQL syntax, try with the correct wild card.
SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4;
string firstdayofyear = new DateTime(DateTime.Now.Year, 1, 1).ToString("MM-dd-yyyy");
string lastdayofyear = new DateTime(DateTime.Now.Year, 12, 31).ToString("MM-dd-yyyy");
string firstdayofmonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("MM-dd-yyyy");
string lastdayofmonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1).ToString("MM-dd-yyyy");
How about:
writing-mode:tb-rl
Where top->bottom, right->left?
We will need vertical rule for this.
Dim fileEntries As String() = Directory.GetFiles("YourPath", "*.txt")
' Process the list of .txt files found in the directory. '
Dim fileName As String
For Each fileName In fileEntries
If (System.IO.File.Exists(fileName)) Then
'Read File and Print Result if its true
ReadFile(fileName)
End If
TransfereFile(fileName, 1)
Next
If you are on Rails 4 and you get this error, it could happen if you are using enum
on the model if you've defined with symbols like this:
class User
enum preferred_phone: [:home_phone, :mobile_phone, :work_phone]
end
The form will pass say a radio selector as a string param. That's what happened in my case. The simple fix is to change enum
to strings instead of symbols
enum preferred_phone: %w[home_phone mobile_phone work_phone]
# or more verbose
enum preferred_phone: ['home_phone', 'mobile_phone', 'work_phone']
The format string attack on printf you mentioned isn't specific to the "%x" formatting - in any case where printf has more formatting parameters than passed variables, it will read values from the stack that do not belong to it. You will get the same issue with %d for example. %x is useful when you want to see those values as hex.
As explained in previous answers, %08x will produce a 8 digits hex number, padded by preceding zeros.
Using the formatting in your code example in printf, with no additional parameters:
printf ("%08x %08x %08x %08x");
Will fetch 4 parameters from the stack and display them as 8-digits padded hex numbers.
Try this:
<a onclick='$("#notification").fadeOut(300, function() { $(this).remove(); });' class="notificationClose "><img src="close.png"/></a>
I think your double quotes around the onclick
were making it not work. :)
EDIT: As pointed out below, inline javascript is evil and you should probably take this out of the onclick
and move it to jQuery's click()
event handler. That is how the cool kids are doing it nowadays.
Or using regular expressions
"rmlike" <- function(...) {
names <- sapply(
match.call(expand.dots = FALSE)$..., as.character)
names = paste(names,collapse="|")
Vars <- ls(1)
r <- Vars[grep(paste("^(",names,").*",sep=""),Vars)]
rm(list=r,pos=1)
}
rmlike(temp)
I like this approach because it is simple and clean:
String getCompaniesIdAndName = " select "
+ " c.id as id, "
+ " c.name as name "
+ " from Company c ";
@Query(value = getCompaniesWithoutAccount)
Set<CompanyIdAndName> findAllIdAndName();
public static interface CompanyIdAndName extends DTO {
Integer getId();
String getName();
}
You can use display: table-cell
property as in the following code:
div {
height: 100%;
display: table-cell;
vertical-align: middle;
}
The source for this answer is the comment to the answer at: Will docker container auto sync time with the host machine?
After looking at the answer, I realized that there is no way a clock drift will occur on the docker container. Docker uses the same clock as the host and the docker cannot change it. It means that doing an ntpdate
inside the docker does not work.
The correct thing to do is to update the host time using ntpdate
As far as syncing timezones is concerned, -v /etc/localtime:/etc/localtime:ro
works.
Here is a useful git alias
that works for me.
git config --global alias.tree '! git ls-tree --full-name --name-only -t -r HEAD | sed -e "s/[^-][^\/]*\// |/g" -e "s/|\([^ ]\)/|-- \1/"'
Here is the output of git tree
jonavon@XPS13:~/projects/roman-numerals$ git tree
.gitignore
pom.xml
src
|-- main
| |-- java
| | |-- com
| | | |-- foxguardsolutions
| | | | |-- jonavon
| | | | | |-- AbstractFile.java
| | | | | |-- roman
| | | | | | |-- Main.java
| | | | | | |-- Numeral.java
| | | | | | |-- RomanNumberInputFile.java
| | | | | | |-- RomanNumeralToDecimalEvaluator.java
|-- test
| |-- java
| | |-- com
| | | |-- foxguardsolutions
| | | | |-- jonavon
| | | | | |-- roman
| | | | | | |-- InterpretSteps.java
| | | | | | |-- RunCukesTest.java
| |-- resources
| | |-- com
| | | |-- foxguardsolutions
| | | | |-- jonavon
| | | | | |-- roman
| | | | | | |-- Interpret.feature
| | |-- sample-input.txt
The comparable tree
command
jonavon@XPS13:~/projects/roman-numerals$ tree -n
.
+-- pom.xml
+-- src
¦ +-- main
¦ ¦ +-- java
¦ ¦ +-- com
¦ ¦ +-- foxguardsolutions
¦ ¦ +-- jonavon
¦ ¦ +-- AbstractFile.java
¦ ¦ +-- roman
¦ ¦ +-- Main.java
¦ ¦ +-- Numeral.java
¦ ¦ +-- RomanNumberInputFile.java
¦ ¦ +-- RomanNumeralToDecimalEvaluator.java
¦ +-- test
¦ +-- java
¦ ¦ +-- com
¦ ¦ +-- foxguardsolutions
¦ ¦ +-- jonavon
¦ ¦ +-- roman
¦ ¦ +-- InterpretSteps.java
¦ ¦ +-- RunCukesTest.java
¦ +-- resources
¦ +-- com
¦ ¦ +-- foxguardsolutions
¦ ¦ +-- jonavon
¦ ¦ +-- roman
¦ ¦ +-- Interpret.feature
¦ +-- sample-input.txt
+-- target
+-- classes
¦ +-- com
¦ +-- foxguardsolutions
¦ +-- jonavon
¦ +-- AbstractFile.class
¦ +-- roman
¦ +-- Main.class
¦ +-- Numeral.class
¦ +-- RomanNumberInputFile.class
¦ +-- RomanNumeralToDecimalEvaluator.class
+-- generated-sources
¦ +-- annotations
+-- maven-status
+-- maven-compiler-plugin
+-- compile
+-- default-compile
+-- createdFiles.lst
+-- inputFiles.lst
30 directories, 17 files
Clearly tree has better output, but I would like it to use my .gitignore file. So that my compiled content doesn't show
To complement Jon Lin's answer, here is a no-trailing-slash technique that also works if the website is located in a directory (like example.org/blog/):
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=301,L]
For the sake of completeness, here is an alternative emphasizing that REQUEST_URI
starts with a slash (at least in .htaccess
files):
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /(.*)/$
RewriteRule ^ /%1 [R=301,L] <-- added slash here too, don't forget it
Just don't use %{REQUEST_URI} (.*)/$
. Because in the root directory REQUEST_URI
equals /
, the leading slash, and it would be misinterpreted as a trailing slash.
If you are interested in more reading:
(update: this technique is now implemented in Laravel 5.5)
./gradlew
Your directory with gradlew is not included in the PATH, so you must specify path to the gradlew. .
means "current directory".
Yes, you can do this quite easily. Click on your project in the project explorer or Navigator, go to the Search menu at the top, click File..., input your search string, and make sure that 'Selected Resources' or 'Enclosing Projects' is selected, then hit search. The alternative way to open the window is with Ctrl-H. This may depend on your keyboard accelerator configuration.
More details: http://www.ehow.com/how_4742705_file-eclipse.html and http://www.avajava.com/tutorials/lessons/how-do-i-do-a-find-and-replace-in-multiple-files-in-eclipse.html
(source: avajava.com)
You can also use this approach in case you want to pass some http parameters and send a json request:
(note: I have added in some extra code just incase it helps any other future readers)
public void postJsonWithHttpParams() throws URISyntaxException, UnsupportedEncodingException, IOException {
//add the http parameters you wish to pass
List<NameValuePair> postParameters = new ArrayList<>();
postParameters.add(new BasicNameValuePair("param1", "param1_value"));
postParameters.add(new BasicNameValuePair("param2", "param2_value"));
//Build the server URI together with the parameters you wish to pass
URIBuilder uriBuilder = new URIBuilder("http://google.ug");
uriBuilder.addParameters(postParameters);
HttpPost postRequest = new HttpPost(uriBuilder.build());
postRequest.setHeader("Content-Type", "application/json");
//this is your JSON string you are sending as a request
String yourJsonString = "{\"str1\":\"a value\",\"str2\":\"another value\"} ";
//pass the json string request in the entity
HttpEntity entity = new ByteArrayEntity(yourJsonString.getBytes("UTF-8"));
postRequest.setEntity(entity);
//create a socketfactory in order to use an http connection manager
PlainConnectionSocketFactory plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory();
Registry<ConnectionSocketFactory> connSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", plainSocketFactory)
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(connSocketFactoryRegistry);
connManager.setMaxTotal(20);
connManager.setDefaultMaxPerRoute(20);
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(HttpClientPool.connTimeout)
.setConnectTimeout(HttpClientPool.connTimeout)
.setConnectionRequestTimeout(HttpClientPool.readTimeout)
.build();
// Build the http client.
CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(connManager)
.setDefaultRequestConfig(defaultRequestConfig)
.build();
CloseableHttpResponse response = httpclient.execute(postRequest);
//Read the response
String responseString = "";
int statusCode = response.getStatusLine().getStatusCode();
String message = response.getStatusLine().getReasonPhrase();
HttpEntity responseHttpEntity = response.getEntity();
InputStream content = responseHttpEntity.getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = buffer.readLine()) != null) {
responseString += line;
}
//release all resources held by the responseHttpEntity
EntityUtils.consume(responseHttpEntity);
//close the stream
response.close();
// Close the connection manager.
connManager.close();
}
Try reading the InputStream
of the runtime:
Runtime rt = Runtime.getRuntime();
String[] commands = {"system.exe", "-send", argument};
Process proc = rt.exec(commands);
BufferedReader br = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
String line;
while ((line = br.readLine()) != null)
System.out.println(line);
You might also need to read the error stream (proc.getErrorStream()
) if the process is printing error output. You can redirect the error stream to the input stream if you use ProcessBuilder
.
I am using OSX -v 10.10.4. The solution above is a quick & easy.
Happening OSX does not have the connection library by default.
First you should install the connector:
brew install mysql-connector-c
Then install with pip mysql
pip install mysql-python
The OP did not ask for cleanup for all remotes, rather for all branches of default remote.
So git fetch --prune
is what should be used.
Setting git config remote.origin.prune true
makes --prune
automatic. In that case just git fetch
will also prune stale remote branches from the local copy. See also Automatic prune with Git fetch or pull.
Note that this does not clean local branches that are no longer tracking a remote branch. See How to prune local tracking branches that do not exist on remote anymore for that.
If you're looking for a good alias to do this plus not blow up cd
if you aren't in a git dir:
alias ..g='git rev-parse && cd "$(git rev-parse --show-cdup)"'
This is an answer to the comment posted by erikkallen:
You don't need a temp table. If you only have a few rows, (SELECT 1 FROM dual UNION SELECT 2 FROM dual) will do. Why would your example give ORA-0001? Wouldn't merge take the update lock on the index key and not continue until Sess1 has either committed or rolled back? – erikkallen
Well, try it yourself and tell me whether you get the same error or not:
SESS1:
create table t1 (pk int primary key, i int);
create table t11 (pk int primary key, i int);
insert into t1 values(1, 1);
insert into t11 values(2, 21);
insert into t11 values(3, 31);
commit;
SESS2: insert into t1 values(2, 2);
SESS1:
MERGE INTO t1 d
USING t11 s ON (d.pk = s.pk)
WHEN NOT MATCHED THEN INSERT (d.pk, d.i) VALUES (s.pk, s.i);
SESS2: commit;
SESS1: ORA-00001
Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin
not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors
at your server side.
You can fetch request using mode: 'cors'
. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.
So in both condition you need to configure cors
in your server or you need to use custom proxy server.
Like others already wrote, in short:
shared project
reuse on the code (file) level, allowing for folder structure and resources as well
pcl
reuse on the assembly level
What was mostly missing from answers here for me is the info on reduced functionality available in a PCL: as an example you have limited file operations (I was missing a lot of File.IO fuctionality in a Xamarin cross-platform project).
In more detail
shared project:
+ Can use #if when targeting multiple platforms (e. g. Xamarin iOS, Android, WinPhone)
+ All framework functionality available for each target project (though has to be conditionally compiled)
o Integrates at compile time
- Slightly larger size of resulting assemblies
- Needs Visual Studio 2013 Update 2 or higher
pcl:
+ generates a shared assembly
+ usable with older versions of Visual Studio (pre-2013 Update 2)
o dynamically linked
- lmited functionality (subset of all projects it is being referenced by)
If you have the choice, I would recommend going for shared project, it is generally more flexible and more powerful. If you know your requirements in advance and a PCL can fulfill them, you might go that route as well. PCL also enforces clearer separation by not allowing you to write platform-specific code (which might not be a good choice to be put into a shared assembly in the first place).
Main focus of both is when you target multiple platforms, else you would normally use just an ordinary library/dll project.
In addition to above differences following are few more:
RV separates view creation and binding of data to view. In LV, you need to check if convertView is null or not for creating view, before binding data to it. So, in case of RV, view will be created only when it is needed but in case of LV, one can miss the check for convertview and will create view everytime.
Switching between Grid and List is more easy now with LayoutManager.
No need to notify and update all items, even if only single item is changed.
One had to implement view caching in case of LV. It is provided in RV by default. (There is difference between view caching n recycling.)
Very easy item animations in case of RV.
Have you checked your hidden input field where the token is generated?
If it is null then your token is not returned by csrf_token function.You have to write your route that renders the form inside the middleware group provide by laravel as follows:
Route::group(['middleware' => 'web'], function () {
Route::get('/', function () {
return view('welcome');
});
Here root route contains my sign up page which requires csrf token. This token is managed by laravel 5.2.7 inside 'web' middleware in kernel.php.
Do not forget to insert {!! csrf_field() !!} inside the form..
Yes, SQL Server 2012 supports multiple inserts - that feature was introduced in SQL Server 2008.
That makes me wonder if you have Management Studio 2012, but you're really connected to a SQL Server 2005 instance ...
What version of the SQL Server engine do you get from SELECT @@VERSION
??
A quick solution:
First, exclude the package: Right click on the source package >> Build Path >> Exclude
Then include it back: Right click on the source package >> Build Path >> Include
Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.
UPD 19.03.2019 Here is a version for browser on GitHub.
You might not be able to change npm registry using .bat
file as Gntem pointed out.
But I understand that you need the ability to automate changing registries.
You can do so by having your .npmrc
configs in separate files (say npmrc_jfrog & npmrc_default) and have your .bat
files do the copying task.
For example (in Windows):
Your default_registry.bat
will have
xcopy /y npmrc_default .npmrc
and your jfrog_registry.bat
will have
xcopy /y npmrc_jfrog .npmrc
Note: /y
suppresses prompting to confirm that you want to overwrite an existing destination file.
This will make sure that all the config properties (registry, proxy, apiKeys, etc.) get copied over to .npmrc
.
You can read more about xcopy here.
/* I have done it this way, and also tested it */
Step 1 = Register custom cell class (in case of prototype cell in table) or nib (in case of custom nib for custom cell) for table like this in viewDidLoad method:
[self.yourTableView registerClass:[CustomTableViewCell class] forCellReuseIdentifier:@"CustomCell"];
OR
[self.yourTableView registerNib:[UINib nibWithNibName:@"CustomTableViewCell" bundle:nil] forCellReuseIdentifier:@"CustomCell"];
Step 2 = Use UITableView's "dequeueReusableCellWithIdentifier: forIndexPath:" method like this (for this, you must register class or nib) :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CustomTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell" forIndexPath:indexPath];
cell.imageViewCustom.image = nil; // [UIImage imageNamed:@"default.png"];
cell.textLabelCustom.text = @"Hello";
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// retrive image on global queue
UIImage * img = [UIImage imageWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:kImgLink]]];
dispatch_async(dispatch_get_main_queue(), ^{
CustomTableViewCell * cell = (CustomTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
// assign cell image on main thread
cell.imageViewCustom.image = img;
});
});
return cell;
}
Try changing it to.
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "text/plain";
Response.Flush();
Response.TransmitFile(file.FullName);
Response.End();
For general check if there was a POST
action use:
if (!empty($_POST))
EDIT: As stated in the comments, this method won't work for in some cases (e.g. with check boxes and button without a name). You really should use:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
If MySQLdb's now distributed in a way that requires setuptools
, your choices are either to download the latter (e.g. from here) or refactor MySQLdb's setup.py to bypass setuptools
(maybe just importing setup
and Extension
from plain distutils
instead might work, but you may also need to edit some of the setup_*.py
files in the same directory).
Depending on how your site's Python installation is configured, installing extensions for your own individual use without requiring sysadm rights may be hard, but it's never truly impossible if you have shell access. You'll need to tweak your Python's sys.path to start with a directory of your own that's your personal equivalent of the system-wide site pacages directory, e.g. by setting PYTHONPATH
persistently in your own environment, and then manually place in said personal directory what normal installs would normally place in site-packages (and/or subdirectories thereof).
Your arguments are in the wrong order. Try git commit -m 'my notes' path/to/my/file.ext
, or if you want to be more explicit, git commit -m 'my notes' -- path/to/my/file.ext
.
Incidentally, git v1.5.2.1 is 4.5 years old. You may want to update to a newer version (1.7.8.3 is the current release).
readline is for string.. just use read
Mostly we write below statement select * from table where length(ltrim(rtrim(field)))=10;
ORA-06512 is part of the error stack. It gives us the line number where the exception occurred, but not the cause of the exception. That is usually indicated in the rest of the stack (which you have still not posted).
In a comment you said
"still, the error comes when pNum is not between 12 and 14; when pNum is between 12 and 14 it does not fail"
Well, your code does this:
IF ((pNum < 12) OR (pNum > 14)) THEN
RAISE vSOME_EX;
That is, it raises an exception when pNum is not between 12 and 14. So does the rest of the error stack include this line?
ORA-06510: PL/SQL: unhandled user-defined exception
If so, all you need to do is add an exception block to handle the error. Perhaps:
PROCEDURE PX(pNum INT,pIdM INT,pCv VARCHAR2,pSup FLOAT)
AS
vSOME_EX EXCEPTION;
BEGIN
IF ((pNum < 12) OR (pNum > 14)) THEN
RAISE vSOME_EX;
ELSE
EXECUTE IMMEDIATE 'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('||pCv||', '||pSup||', '||pIdM||')';
END IF;
exception
when vsome_ex then
raise_application_error(-20000
, 'This is not a valid table: M'||pNum||'GR');
END PX;
The documentation covers handling PL/SQL exceptions in depth.
URL url = new File("src/main/java/ua/adeptius/goit/sample.fxml").toURI().toURL();
Parent root = FXMLLoader.load(url);
That is helped for me because
getClass.getResource("path")
always returns me null;
In the layout (app/design/frontend/your_theme/layout/default.xml):
<default>
<cms_page> <!-- need to be redefined for your needs -->
<reference name="content">
<block type="cms/block" name="cms_newest_product" as="cms_newest_product">
<action method="setBlockId"><block_id>newest_product</block_id></action>
</block>
</reference>
</cms_page>
</default>
In your phtml template:
<?php echo $this->getChildHtml('newest_product'); ?>
Don't forget about cache cleaning.
I think it help.
C# Xamarin version
const string FIRST_RUN = "hasRunBefore";
var userDefaults = NSUserDefaults.StandardUserDefaults;
if (!userDefaults.BoolForKey(FIRST_RUN))
{
//TODO: remove keychain items
userDefaults.SetBool(true, FIRST_RUN);
userDefaults.Synchronize();
}
... and to clear records from the keychain (TODO comment above)
var securityRecords = new[] { SecKind.GenericPassword,
SecKind.Certificate,
SecKind.Identity,
SecKind.InternetPassword,
SecKind.Key
};
foreach (var recordKind in securityRecords)
{
SecRecord query = new SecRecord(recordKind);
SecKeyChain.Remove(query);
}
Reason can be Middleware
if you forget to put following code to the end of handle
function
return $next($request);
or you can simply have
$('.date-pick').datePicker().val(new Date()).trigger('change')
Here is a full example which reads the contents of the given web page.
The web page is read from an HTML form. We use standard InputStream
classes, but it could be done more easily with JSoup library.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.6</version>
</dependency>
These are the Maven dependencies. We use Apache Commons library to validate URL strings.
package com.zetcode.web;
import com.zetcode.service.WebPageReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "ReadWebPage", urlPatterns = {"/ReadWebPage"})
public class ReadWebpage extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain;charset=UTF-8");
String page = request.getParameter("webpage");
String content = new WebPageReader().setWebPageName(page).getWebPageContent();
ServletOutputStream os = response.getOutputStream();
os.write(content.getBytes(StandardCharsets.UTF_8));
}
}
The ReadWebPage
servlet reads the contents of the given web page and sends it back to the client in plain text format. The task of reading the page is delegated to WebPageReader
.
package com.zetcode.service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.apache.commons.validator.routines.UrlValidator;
public class WebPageReader {
private String webpage;
private String content;
public WebPageReader setWebPageName(String name) {
webpage = name;
return this;
}
public String getWebPageContent() {
try {
boolean valid = validateUrl(webpage);
if (!valid) {
content = "Invalid URL; use http(s)://www.example.com format";
return content;
}
URL url = new URL(webpage);
try (InputStream is = url.openStream();
BufferedReader br = new BufferedReader(
new InputStreamReader(is, StandardCharsets.UTF_8))) {
content = br.lines().collect(
Collectors.joining(System.lineSeparator()));
}
} catch (IOException ex) {
content = String.format("Cannot read webpage %s", ex);
Logger.getLogger(WebPageReader.class.getName()).log(Level.SEVERE, null, ex);
}
return content;
}
private boolean validateUrl(String webpage) {
UrlValidator urlValidator = new UrlValidator();
return urlValidator.isValid(webpage);
}
}
WebPageReader
validates the URL and reads the contents of the web page.
It returns a string containing the HTML code of the page.
<!DOCTYPE html>
<html>
<head>
<title>Home page</title>
<meta charset="UTF-8">
</head>
<body>
<form action="ReadWebPage">
<label for="page">Enter a web page name:</label>
<input type="text" id="page" name="webpage">
<button type="submit">Submit</button>
</form>
</body>
</html>
Finally, this is the home page containing the HTML form. This is taken from my tutorial about this topic.
For Data access you can use OData. Here is a demo where Scott Hanselman creates an OData front end to StackOverflow database in 30 minutes, with XML and JSON access: Creating an OData API for StackOverflow including XML and JSON in 30 minutes.
For administrative access, like phpMyAdmin package, there is no well established one. You may give a try to IIS Database Manager.
if you know at least one <style>
tag exist in page , use this function :
CSS=function(i){document.getElementsByTagName('style')[0].innerHTML+=i};
usage :
CSS("div{background:#00F}");
The WHERE
clause is misplaced, it has to follow the table references and JOIN operations.
Something like this:
FROM tartikel p1
JOIN tartikelpict p2
ON p1.kArtikel = p2.kArtikel
AND p2.nNr = 1
WHERE p1.dErstellt >= DATE(NOW()) - INTERVAL 7 DAY
ORDER BY p1.kArtikel DESC
EDIT (three plus years later)
The above essentially answers the question "I tried to add a WHERE clause to my query and now the query is returning an error, how do I fix it?"
As to a question about writing a condition that checks a date range of "last 7 days"...
That really depends on interpreting the specification, what the datatype of the column in the table is (DATE or DATETIME) and what data is available... what should be returned.
To summarize: the general approach is to identify a "start" for the date/datetime range, and "end" of that range, and reference those in a query. Let's consider something easier... all rows for "yesterday".
If our column is DATE type. Before we incorporate an expression into a query, we can test it in a simple SELECT
SELECT DATE(NOW()) + INTERVAL -1 DAY
and verify the result returned is what we expect. Then we can use that same expression in a WHERE clause, comparing it to a DATE column like this:
WHERE datecol = DATE(NOW()) + INTERVAL -1 DAY
For a DATETIME or TIMESTAMP column, we can use >=
and <
inequality comparisons to specify a range
WHERE datetimecol >= DATE(NOW()) + INTERVAL -1 DAY
AND datetimecol < DATE(NOW()) + INTERVAL 0 DAY
For "last 7 days" we need to know if that mean from this point right now, back 7 days ... e.g. the last 7*24 hours , including the time component in the comparison, ...
WHERE datetimecol >= NOW() + INTERVAL -7 DAY
AND datetimecol < NOW() + INTERVAL 0 DAY
the last seven complete days, not including today
WHERE datetimecol >= DATE(NOW()) + INTERVAL -7 DAY
AND datetimecol < DATE(NOW()) + INTERVAL 0 DAY
or past six complete days plus so far today ...
WHERE datetimecol >= DATE(NOW()) + INTERVAL -6 DAY
AND datetimecol < NOW() + INTERVAL 0 DAY
I recommend testing the expressions on the right side in a SELECT statement, we can use a user-defined variable in place of NOW() for testing, not being tied to what NOW() returns so we can test borders, across week/month/year boundaries, and so on.
SET @clock = '2017-11-17 11:47:47' ;
SELECT DATE(@clock)
, DATE(@clock) + INTERVAL -7 DAY
, @clock + INTERVAL -6 DAY
Once we have expressions that return values that work for "start" and "end" for our particular use case, what we mean by "last 7 days", we can use those expressions in range comparisons in the WHERE clause.
(Some developers prefer to use the DATE_ADD
and DATE_SUB
functions in place of the + INTERVAL val DAY/HOUR/MINUTE/MONTH/YEAR
syntax.
And MySQL provides some convenient functions for working with DATE, DATETIME and TIMESTAMP datatypes... DATE, LAST_DAY,
Some developers prefer to calculate the start and end in other code, and supply string literals in the SQL query, such that the query submitted to the database is
WHERE datetimecol >= '2017-11-10 00:00'
AND datetimecol < '2017-11-17 00:00'
And that approach works too. (My preference would be to explicitly cast those string literals into DATETIME, either with CAST, CONVERT or just the + INTERVAL trick...
WHERE datetimecol >= '2017-11-10 00:00' + INTERVAL 0 SECOND
AND datetimecol < '2017-11-17 00:00' + INTERVAL 0 SECOND
The above all assumes we are storing "dates" in appropriate DATE, DATETIME and/or TIMESTAMP datatypes, and not storing them as strings in variety of formats e.g. 'dd/mm/yyyy'
, m/d/yyyy
, julian dates, or in sporadically non-canonical formats, or as a number of seconds since the beginning of the epoch, this answer would need to be much longer.
Try this:
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");
Or alternatively if you have the XML in a string use the LoadXml
method.
Once you have it loaded, you can use SelectNodes
and SelectSingleNode
to query specific values, for example:
XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"
Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:
<Data>
<Employee>
<Name>Test</Name>
<ID>123</ID>
</Employee>
<Company>
<Name>ABC</Name>
<Email>[email protected]</Email>
</Company>
</Data>
Well, this solution might sound very silly, but can save you in certain conditions.
A friend of mine just ran into accidentally committing very some huge files (four auto-generated files ranging between 3GB to 5GB each) and then made some additional code commits on top of that before realizing the problem that git push
wasn't working any longer!
The files had been listed in .gitignore
but after renaming the container folder, they got exposed and committed! And now there were a few more commits of the code on top of that, but push
was running forever (trying to upload GB of data!) and finally would fail due to Github's file size limits.
The problem with interactive rebase or anything similar was that they would deal with poking around these huge files and would take forever to do anything. Nevertheless, after spending almost an hour in the CLI, we weren't sure if the files (and deltas) are actually removed from the history or simply not included in the current commits. The push wasn't working either and my friend was really stuck.
So, the solution I came up with was:
~/Project-old
.~/Project
). cp -r
the files from ~/Project-old
folder to ~/Project
. mv
ed, and included in .gitignore
properly. .git
folder in the recently-cloned ~/Project
by the old one. That's where the logs of the problematic history lives!push
'ed.The biggest problem with this solution is, it deals with manual copying some files, and also it merges all the recent commits into one (obviously with a new commit-hash.) B
The big benefits are that, it is very clear in every step, it works great for huge files (as well as sensitive ones), and it doesn't leave any trace in history behind!
You are mixing the 2 different CASE
syntaxes inappropriately.
Use this style (Searched)
CASE
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Or this style (Simple)
CASE u.nnmu
WHEN '0' THEN mu.naziv_mesta
WHEN '1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Not This (Simple but with boolean search predicates)
CASE u.nnmu
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
In MySQL this will end up testing whether u.nnmu
is equal to the value of the boolean expression u.nnmu ='0'
itself. Regardless of whether u.nnmu
is 1
or 0
the result of the case expression itself will be 1
For example if nmu = '0'
then (nnmu ='0'
) evaluates as true
(1) and (nnmu ='1'
) evaluates as false
(0). Substituting these into the case expression gives
SELECT CASE '0'
WHEN 1 THEN '0'
WHEN 0 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
if nmu = '1'
then (nnmu ='0'
) evaluates as false
(0) and (nnmu ='1'
) evaluates as true
(1). Substituting these into the case expression gives
SELECT CASE '1'
WHEN 0 THEN '0'
WHEN 1 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
Try
let str ="554,20";_x000D_
let float = +str.replace(',','.');_x000D_
let int = str.split(',').map(x=>+x);_x000D_
_x000D_
console.log({float,int});
_x000D_
final
means that the value cannot be changed after initialization, that's what makes it a constant. static
means that instead of having space allocated for the field in each object, only one instance is created for the class.
So, static final
means only one instance of the variable no matter how many objects are created and the value of that variable can never change.
Although probably not exactly what your looking for and you probably don't care at this point since the question was asked 5 years ago, one method is to use "forward".
Go to your inbox or wherever your messages are and select the 2+ messages you want to send than simply click forward... all messages get combined into 1.
You can use Future.delayed
to run your code after some time. e.g.:
Future.delayed(const Duration(milliseconds: 500), () {
// Here you can write your code
setState(() {
// Here you can write your code for open new view
});
});
In setState function, you can write a code which is related to app UI e.g. refresh screen data, change label text, etc.
I'm not sure what you are doing wrong here, when I build a form using form classes Symfony takes care of selecting the correct option in the list. Here's an example of one of my forms that works.
In the controller for the edit action:
$entity = $em->getRepository('FooBarBundle:CampaignEntity')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find CampaignEntity entity.');
}
$editForm = $this->createForm(new CampaignEntityType(), $entity);
$deleteForm = $this->createDeleteForm($id);
return $this->render('FooBarBundle:CampaignEntity:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
The campaign entity type class (src: Foo\BarBundle\Form\CampaignEntityType.php):
namespace Foo\BarBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Doctrine\ORM\EntityRepository;
class CampaignEntityType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('store', 'entity', array('class'=>'FooBarBundle:Store', 'property'=>'name', 'em'=>'my_non_default_em','required' => true, 'query_builder' => function(EntityRepository $er) {return $er->createQueryBuilder('s')->orderBy('s.name', 'ASC');}))
->add('reward');
}
public function getName()
{
return 'foo_barbundle_campaignentitytype';
}
}
Using break-inside should work:
@media print {
div {
break-inside: avoid;
}
}
It works on all major browsers:
Using page-break-inside: avoid;
instead should work too, but has been exactly deprecated by break-inside: avoid
.
Run the installer from command line with argument /CustomInstallPath
InstallationDirectory
See more command-line parameters and other installation information.
Note: this won't change location of all files, but only of those which can be (by design) installed onto different location. Be warned that there is many shared components which will be installed into shared repositories on drive C:
without any possibility to change their path (unless you do some hacking using mklink /j
(directory junction, i.e."hard link for folder"), but it is questionable whether it is worth it, because any Visual Studio updates will break those hard links. This is confirmed by people who tried that, although on Visual Studio 2012.)
Update: per recent comment, uninstallation of Visual Studio might be required before the above applies. Uninstallation command is like this: vs_community_ENU.exe /uninstall /force
I found that this works and seems more readable:
switch($someString)
{
{ @("y", "yes") -contains $_ } { "You entered Yes." }
default { "You entered No." }
}
The "-contains" operator performs a non-case sensitive search, so you don't need to use "ToLower()". If you do want it to be case sensitive, you can use "-ccontains" instead.
Here's an alternate
req.hostname
Read about it in the Express Docs.
You used data-datepicker="datepicker"
It must be date-provide="datepicker"
Also, you included 2 bootstrap stylesheets bootstrap.css
and bootstrap.min.css
I also prefer to use bootstrap-datepicker3.min.css
than datepicker.less
Full Html:
<html>
<head>
<title>DatePicker Demo</title>
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="css/bootstrap-datepicker3.min.css">
<script src="js/jquery-1.7.1.js"></script>
<script src="js/bootstrap-datepicker.js"></script>
</head>
<body>
<form>
<div class="input">
<input data-provide="datepicker" class="small" type="text" value="01/05/2011">
</div>
</form>
</body>
</html>
Have you tried to access your page by typing "http://localhost:8012" (after restarting the apache)?
No one has mentioned the obvious:
var myCallback = function() { console.log("name or age changed"); };
$scope.$watch("name", myCallback);
$scope.$watch("age", myCallback);
This might mean a little less polling. If you watch both name + age
(for this) and name
(elsewhere) then I assume Angular will effectively look at name
twice to see if it's dirty.
It's arguably more readable to use the callback by name instead of inlining it. Especially if you can give it a better name than in my example.
And you can watch the values in different ways if you need to:
$scope.$watch("buyers", myCallback, true);
$scope.$watchCollection("sellers", myCallback);
$watchGroup
is nice if you can use it, but as far as I can tell, it doesn't let you watch the group members as a collection or with object equality.
If you need the old and new values of both expressions inside one and the same callback function call, then perhaps some of the other proposed solutions are more convenient.
in 1.x there used to be things DataTables couldn't do which DataSets could (don't remember exactly what). All that was changed in 2.x. My guess is that's why a lot of examples still use DataSets. DataTables should be quicker as they are more lightweight. If you're only pulling a single resultset, its your best choice between the two.
It is possible using ConfigTransform
build target available as a Nuget package - https://www.nuget.org/packages/CodeAssassin.ConfigTransform/
All "web.*.config" transform files will be transformed and output as a series of "web.*.config.transformed" files in the build output directory regardless of the chosen build configuration.
The same applies to "app.*.config" transform files in non-web projects.
and then adding the following target to your *.csproj
.
<Target Name="TransformActiveConfiguration" Condition="Exists('$(ProjectDir)/Web.$(Configuration).config')" BeforeTargets="Compile" >
<TransformXml Source="$(ProjectDir)/Web.Config" Transform="$(ProjectDir)/Web.$(Configuration).config" Destination="$(TargetDir)/Web.config" />
</Target>
Posting an answer as this is the first Stackoverflow post that appears in Google on the subject.
screen -S your_session_name
Ctrl+a, : sessionname YOUR_SESSION_NAME Enter
You must be inside the session
For more generic advice on debugging this kind of problem MDN have a good article TypeError: "x" is not a function:
It was attempted to call a value like a function, but the value is not actually a function. Some code expects you to provide a function, but that didn't happen.
Maybe there is a typo in the function name? Maybe the object you are calling the method on does not have this function? For example, JavaScript objects have no map function, but JavaScript Array object do.
Basically the object (all functions in js are also objects) does not exist where you think it does. This could be for numerous reasons including(not an extensive list):
var x = function(){_x000D_
var y = function() {_x000D_
alert('fired y');_x000D_
}_x000D_
};_x000D_
_x000D_
//the global scope can't access y because it is closed over in x and not exposed_x000D_
//y is not a function err triggered_x000D_
x.y();
_x000D_
var x = function(){_x000D_
var y = function() {_x000D_
alert('fired y');_x000D_
}_x000D_
};_x000D_
_x000D_
//z is not a function error (as above) triggered_x000D_
x.z();
_x000D_
You are on the right track. Since you said you can't modify the global settings, then the next best thing is to apply the JsonConverter
attribute on an as-needed basis, as you suggested. It turns out Json.Net already has a built-in IsoDateTimeConverter
that lets you specify the date format. Unfortunately, you can't set the format via the JsonConverter
attribute, since the attribute's sole argument is a type. However, there is a simple solution: subclass the IsoDateTimeConverter
, then specify the date format in the constructor of the subclass. Apply the JsonConverter
attribute where needed, specifying your custom converter, and you're ready to go. Here is the entirety of the code needed:
class CustomDateTimeConverter : IsoDateTimeConverter
{
public CustomDateTimeConverter()
{
base.DateTimeFormat = "yyyy-MM-dd";
}
}
If you don't mind having the time in there also, you don't even need to subclass the IsoDateTimeConverter. Its default date format is yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK
(as seen in the source code).
I will suggest creating a setup project for the reasons while deploying this seems the best convinience , no headaches of copying files manually. Follow the Windows service setup creation tutorial and you know how to create it. And this instance is for vb.net but it is the same for any type.
This answer was made pre-JPA2 implementations, if you're using JPA2, see the ElementCollection answer above:
Lists of objects inside a model object are generally considered "OneToMany" relationships with another object. However, a String is not (by itself) an allowable client of a One-to-Many relationship, as it doesn't have an ID.
So, you should convert your list of Strings to a list of Argument-class JPA objects containing an ID and a String. You could potentially use the String as the ID, which would save a little space in your table both from removing the ID field and by consolidating rows where the Strings are equal, but you would lose the ability to order the arguments back into their original order (as you didn't store any ordering information).
Alternatively, you could convert your list to @Transient and add another field (argStorage) to your class that is either a VARCHAR() or a CLOB. You'll then need to add 3 functions: 2 of them are the same and should convert your list of Strings into a single String (in argStorage) delimited in a fashion that you can easily separate them. Annotate these two functions (that each do the same thing) with @PrePersist and @PreUpdate. Finally, add the third function that splits the argStorage into the list of Strings again and annotate it @PostLoad. This will keep your CLOB updated with the strings whenever you go to store the Command, and keep the argStorage field updated before you store it to the DB.
I still suggest doing the first case. It's good practice for real relationships later.