I got similar error after deleting a subproject, removed
"*compile project(path: ':MySubProject', configuration: 'android-endpoints')*"
in build.gradle
(dependencies) under Gradle Scripts
If you are using MVC, you put this in the web.config file in the Root directory of the web application, not the web.config in the Views directory. It also needs to be IN the system.web node, not under like George2 stated in his question: "I wrote under system.web section in the web.config"
The timeout parameter value represents minutes.
There are other attributes that can be set in the sessionState element. You can find information here: docs.microsoft.com sessionState
<configuration>
<system.web>
<sessionState timeout="20"></sessionState>
</system.web>
</configuration>
You can then catch the begining of a new session in the Global.asax file by adding the following method:
void Session_Start(object sender, EventArgs e)
{
if (Session.IsNewSession)
{
//do things that need to happen
//when a new session starts.
}
}
From API 19 onwards you can make use of the Telephony Class for that; Since hardcored values won't retrieve messages in every devices because the content provider Uri changes from devices and manufacturers.
public void getAllSms(Context context) {
ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(Telephony.Sms.CONTENT_URI, null, null, null, null);
int totalSMS = 0;
if (c != null) {
totalSMS = c.getCount();
if (c.moveToFirst()) {
for (int j = 0; j < totalSMS; j++) {
String smsDate = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.DATE));
String number = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.ADDRESS));
String body = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.BODY));
Date dateFormat= new Date(Long.valueOf(smsDate));
String type;
switch (Integer.parseInt(c.getString(c.getColumnIndexOrThrow(Telephony.Sms.TYPE)))) {
case Telephony.Sms.MESSAGE_TYPE_INBOX:
type = "inbox";
break;
case Telephony.Sms.MESSAGE_TYPE_SENT:
type = "sent";
break;
case Telephony.Sms.MESSAGE_TYPE_OUTBOX:
type = "outbox";
break;
default:
break;
}
c.moveToNext();
}
}
c.close();
} else {
Toast.makeText(this, "No message to show!", Toast.LENGTH_SHORT).show();
}
}
GitLab by default marks master
branch as protected
(See part Protecting your code
in https://about.gitlab.com/2014/11/26/keeping-your-code-protected/ why). If so in your case, then this can help:
Open your project > Settings > Repository and go to "Protected branches", find "master" branch into the list and click "Unprotect" and try again.
via https://gitlab.com/gitlab-com/support-forum/issues/40
For version 8.11 and above how-to here: https://docs.gitlab.com/ee/user/project/protected_branches.html#restricting-push-and-merge-access-to-certain-users
Starting from C# 2.0, you can use the nullable generic type Nullable, and in C# there is a shorthand notation the type followed by ?
e.g.
private void Example(int? arg1, int? arg2)
{
if(arg1 == null)
{
//do something
}
if(arg2 == null)
{
//do something else
}
}
In your example I'd go for the following pattern:
'([^\n]+)$
use multiline and global options to match all occurences.
To include the linefeed in the match you could use:
'[^\n]+\n
But this might miss the last line if it has no linefeed.
For a single line, if you don't need to match the linefeed I'd prefer to use:
'[^$]+$
In my particular case I was rendering a Rails partial without render layout: false
which was re-rendering the entire layout, including all of the scripts in the <head>
tag. Adding render layout: false
to the controller action fixed the problem.
If you are familiar with LaTex you might want to consider pylatex
One of the advantages of pylatex is that it is easy to control the image quality. The images in your pdf will be of the same quality as the original images. When using reportlab, I experienced that the images were automatically compressed, and the image quality reduced.
The disadvantage of pylatex is that, since it is based on LaTex, it can be hard to place images exactly where you want on the page. However, I have found that using the position argument in the Figure class, and sometimes Subfigure, gives good enough results.
Example code for creating a pdf with a single image:
from pylatex import Document, Figure
doc = Document(documentclass="article")
with doc.create(Figure(position='p')) as fig:
fig.add_image('Lenna.png')
doc.generate_pdf('test', compiler='latexmk', compiler_args=["-pdf", "-pdflatex=pdflatex"], clean_tex=True)
In addition to installing pylatex (pip install pylatex), you need to install LaTex. For Ubuntu and other Debian systems you can run sudo apt-get install texlive-full
. If you are using Windows I would recommend MixTex
This can be done by using intents too:
final Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(
"http://maps.google.com/maps?" +
"saddr="+YOUR_START_LONGITUDE+","+YOUR_START_LATITUDE+"&daddr="YOUR_END_LONGITUDE+","+YOUR_END_LATITUDE));
intent.setClassName(
"com.google.android.apps.maps",
"com.google.android.maps.MapsActivity");
startActivity(intent);
alphabets-> caps & small
digits-> 0-9
special chars-> ':', '-', '_', '.'
the format should be either starting from '.' or an alphabet, followed by either of the special chars of more alphabets or numbers. the value of the id field must not end at an '_'.
Also, spaces are not allowed, if provided, they are treated as different values, which is not valid in case of the id attributes.
The other main difference is that table variables don't have column statistics, where as temp tables do. This means that the query optimiser doesn't know how many rows are in the table variable (it guesses 1), which can lead to highly non-optimal plans been generated if the table variable actually has a large number of rows.
Here is a method for converting from a GregorianCalendar to XMLGregorianCalendar; I'll leave the part of converting from a java.util.Date to GregorianCalendar as an exercise for you:
import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
public class DateTest {
public static void main(final String[] args) throws Exception {
GregorianCalendar gcal = new GregorianCalendar();
XMLGregorianCalendar xgcal = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(gcal);
System.out.println(xgcal);
}
}
EDIT: Slooow :-)
Report Manager has been around for quite a few years. It's written in Delphi (at least it was originally) and has components that can be used in Delphi, but is usable via ActiveX or dll from just about any language. Now has a native .NET library too. Has a nifty report-serving webserver you can set up too. The designer gui looks and feels a little rough around the edges but it works. http://reportman.sourceforge.net/
Just weighing in here with a nice solution I have been using. This is similar to Lucky Soni's solution above in that it supports aggregation, but doesn't require hard coding of the field names.
cursor = db.<collection_name>.<my_query_with_aggregation>;
headerPrinted = false;
while (cursor.hasNext()) {
item = cursor.next();
if (!headerPrinted) {
print(Object.keys(item).join(','));
headerPrinted = true;
}
line = Object
.keys(item)
.map(function(prop) {
return '"' + item[prop] + '"';
})
.join(',');
print(line);
}
Save this as a .js
file, in this case we'll call it example.js
and run it with the mongo command line like so:
mongo <database_name> example.js --quiet > example.csv
You can call UserPrincipal.FindByIdentity
inside System.DirectoryServices.AccountManagement
:
using System.DirectoryServices.AccountManagement;
using (var pc = new PrincipalContext(ContextType.Domain, "MyDomainName"))
{
var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, "MyDomainName\\" + userName);
}
The best way to retrieve your public folder path from your Laravel config is the function:
$myPublicFolder = public_path();
$savePath = $mypublicPath."enter_path_to_save";
$path = $savePath."filename.ext";
return File::put($path , $data);
There is no need to have all the variables, but this is just for a demonstrative purpose.
Hope this helps, GRnGC
Use MomentJS.
function getXDaysBeforeDate(referenceDate, x) {_x000D_
return moment(referenceDate).subtract(x , 'day').format('MMMM Do YYYY, h:mm:ss a');_x000D_
}_x000D_
_x000D_
var yourDate = new Date(); // let's say today_x000D_
var valueOfX = 7; // let's say 7 days before_x000D_
_x000D_
console.log(getXDaysBeforeDate(yourDate, valueOfX));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
_x000D_
Unfortunately, vars files do not have include statements.
You can either put all the vars into the definitions
dictionary, or add the variables as another dictionary in the same file.
If you don't want to have them in the same file, you can include them at the playbook level by adding the vars file at the start of the play:
---
- hosts: myhosts
vars_files:
- default_step.yml
or in a task:
---
- hosts: myhosts
tasks:
- name: include default step variables
include_vars: default_step.yml
You can simply use the jQuery Validate plugin as follows.
jQuery:
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true,
email: true
},
field2: {
required: true,
minlength: 5
}
}
});
});
HTML:
<form id="myform">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" />
</form>
DEMO: http://jsfiddle.net/xs5vrrso/
Options: http://jqueryvalidation.org/validate
Methods: http://jqueryvalidation.org/category/plugin/
Standard Rules: http://jqueryvalidation.org/category/methods/
Optional Rules available with the additional-methods.js
file:
maxWords
minWords
rangeWords
letterswithbasicpunc
alphanumeric
lettersonly
nowhitespace
ziprange
zipcodeUS
integer
vinUS
dateITA
dateNL
time
time12h
phoneUS
phoneUK
mobileUK
phonesUK
postcodeUK
strippedminlength
email2 (optional TLD)
url2 (optional TLD)
creditcardtypes
ipv4
ipv6
pattern
require_from_group
skip_or_fill_minimum
accept
extension
Also you can set option:
{plotOptions: {column: {colorByPoint: true}}}
for more information read docs
Maybe remove the semi-colon after set because now the where statement doesn't belong to the update statement. Also the idRequest
could be a problem, better write BookingRequest.idRequest
echo Hello, > file.txt
echo. >>file.txt
echo world >>file.txt
and you can always run:
wordpad file.txt
on any version of Windows.
On Windows 2000 and above you can do:
( echo Hello, & echo. & echo world ) > file.txt
Another way of showing a message for a small amount of text is to create file.vbs containing:
Msgbox "Hello," & vbCrLf & vbCrLf & "world", 0, "Message"
Call it with
cscript /nologo file.vbs
Or use wscript
if you don't need it to wait until they click OK.
The problem with the message you're writing is that the vertical bar (|
) is the "pipe" operator. You'll need to escape it by using ^|
instead of |
.
P.S. it's spelled Pwned.
Use:
public void onClick(View v) {
switch(v.getId()){
case R.id.Button_MyCards: /** Start a new Activity MyCards.java */
Intent intent = new Intent(this, MyCards.class);
this.startActivity(intent);
break;
case R.id.Button_Exit: /** AlerDialog when click on Exit */
MyAlertDialog();
break;
}
}
Note that this will not work in Android library projects (due to http://tools.android.com/tips/non-constant-fields) where you will need to use something like:
int id = view.getId();
if (id == R.id.Button_MyCards) {
action1();
} else if (id == R.id.Button_Exit) {
action2();
}
Find all products that has been ordered 1 or more times... (kind of duplicate records)
SELECT DISTINCT * from [order_items] where productid in
(SELECT productid
FROM [order_items]
group by productid
having COUNT(*)>0)
order by productid
To select the last inserted of those...
SELECT DISTINCT productid, MAX(id) OVER (PARTITION BY productid) AS LastRowId from [order_items] where productid in
(SELECT productid
FROM [order_items]
group by productid
having COUNT(*)>0)
order by productid
Try using this tool,which is just a simple js script https://github.com/shashwatsahai/CSSExtractor/ This tool helps in getting the CSS from a specific page listing all sources for active styles and save it to a JSON with source as key and rules as value. It loads all the CSS from the href links and tells all the styles applied from them You can modify the code to save all css into a .css file. Thereby combining all your css.
If scope resolution :: had to be used outside the class then the respective function or variable should be declared as static
class Foo {
//Static variable
public static $static_var = 'static variable';
//Static function
static function staticValue() { return 'static function'; }
//function
function Value() { return 'Object'; }
}
echo Foo::$static_var . "<br/>"; echo Foo::staticValue(). "<br/>"; $foo = new Foo(); echo $foo->Value();
For MySQL:
SELECT contract, activity
FROM table
GROUP BY contract
HAVING COUNT(DISTINCT activity) = 1
The :last-child
selector should do it, but it's not supported in any version of IE.
I'm afraid you have no choice but to use a class.
The Problem is with your code formatting,
inorder to use strtotime()
You should replace '06/Oct/2011:19:00:02'
with 06/10/2011 19:00:02
and date('d/M/Y:H:i:s', $date);
with date('d/M/Y H:i:s', $date);
. Note the spaces in between.
So the final code looks like this
$s = '06/10/2011 19:00:02';
$date = strtotime($s);
echo date('d/M/Y H:i:s', $date);
Another alternative is to set the root_path
which fixes the problem both for templates and static folders.
root_path = Path(sys.executable).parent if getattr(sys, 'frozen', False) else Path(__file__).parent
app = Flask(__name__.split('.')[0], root_path=root_path)
If you render templates directly via Jinja2
, then you write:
ENV = jinja2.Environment(loader=jinja2.FileSystemLoader(str(root_path / 'templates')))
template = ENV.get_template(your_template_name)
This link contains relevant information on detecting versions of Internet Explorer:
http://tanalin.com/en/articles/ie-version-js/
Example:
if (document.all && !document.addEventListener) {
alert('IE8 or older.');
}
On windows I used the following command
:wq
and it aborts the previous commit because of the empty commit message
The easiest way to do it, at least for me, is:
Conditional format-> Add new rule->Set your own formula:
=ISNA(MATCH(A2;$B:$B;0))
Where A2 is the first element in column A to be compared and B is the column where A's element will be searched.
Once you have set the formula and picked the format, apply this rule to all elements in the column.
Hope this helps
Typically this happens when you are trying to load a non-html resource (e.g the jquery library script file as type text/javascript) and the server, instead of returning the expected JS resource, returns HTML instead - typically a 404 page.
The browser then attempts to parse the resource as JS, but since what was actually returned was an HTML page, the parsing fails with a syntax error, and since an HTML page will typically start with a < character, this is the character that is highlighted in the syntax error exception.
The existence of that piece of metadata is entirely dependent on the application that wrote the file. It's very common to load up JPG files with metadata (EXIF tags) about the file, such as a timestamp or camera information or geolocation. ID3 tags in MP3 files are also very common. But it's a lot less common to see this kind of metadata in video files.
If you just need a tool to read this data from files manually, GSpot might do the trick: http://www.videohelp.com/tools/Gspot
If you want to read this in code then I imagine each container format is going to have its own standards and each one will take a bit of research and implementation to support.
You can do it in a single line by using regex:
if (myList.toString().matches(".*\\bA\\b.*"))
This code should perform quite well.
BTW, you could build the regex from a variable, like this:
.matches("\\[.*\\b" + word + "\\b.*]")
I added [
and ]
to each end to prevent a false positive match when the search term contains an open/close square bracket at the start/end.
This is lighter weight than xrange
(and the while loop) since it doesn't even need to create the int
objects. It also works equally well in Python2 and Python3
from itertools import repeat
for i in repeat(None, 10):
do_sth()
All I needed was this :
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat sdfLocal = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
try {
String d = sdf.format(new Date());
System.out.println(d);
System.out.println(sdfLocal.parse(d));
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
Output : slightly dubious, but I want only the date to be consistent
2013.08.08 11:01:08
Thu Aug 08 11:01:08 GMT+08:00 2013
Date
is Comparable
& Equatable
(as of Swift 3)This answer complements @Ankit Thakur's answer.
Since Swift 3 the Date
struct (based on the underlying NSDate
class) adopts the Comparable
and Equatable
protocols.
Comparable
requires that Date
implement the operators: <
, <=
, >
, >=
.Equatable
requires that Date
implement the ==
operator.Equatable
allows Date
to use the default implementation of the !=
operator (which is the inverse of the Equatable
==
operator implementation).The following sample code exercises these comparison operators and confirms which comparisons are true with print
statements.
import Foundation
func describeComparison(date1: Date, date2: Date) -> String {
var descriptionArray: [String] = []
if date1 < date2 {
descriptionArray.append("date1 < date2")
}
if date1 <= date2 {
descriptionArray.append("date1 <= date2")
}
if date1 > date2 {
descriptionArray.append("date1 > date2")
}
if date1 >= date2 {
descriptionArray.append("date1 >= date2")
}
if date1 == date2 {
descriptionArray.append("date1 == date2")
}
if date1 != date2 {
descriptionArray.append("date1 != date2")
}
return descriptionArray.joined(separator: ", ")
}
let now = Date()
describeComparison(date1: now, date2: now.addingTimeInterval(1))
// date1 < date2, date1 <= date2, date1 != date2
describeComparison(date1: now, date2: now.addingTimeInterval(-1))
// date1 > date2, date1 >= date2, date1 != date2
describeComparison(date1: now, date2: now)
// date1 <= date2, date1 >= date2, date1 == date2
Since you're using requests
, you should use the response's json
method.
import requests
response = requests.get(...)
data = response.json()
Google chrome has a problem if you set and unset cookie improper way. This is php code. Thought this will give you idea.
Set cookie
setcookie('userLoggedIn', 1, 0, PATH);
Wrong way and will not work (notice PATH is missing)
setcookie('userLoggedIn', 0, time()-3600);
Correct way fixes issue on google chrome
setcookie('userLoggedIn', 0, time()-3600, PATH);
Or you can use what JQuery alreay made for you:
http://jqueryui.com/datepicker/#icon-trigger
It's what you are trying to achieve isn't it?
You can do this directly with tar and even better:
tar -N '2014-02-01 18:00:00' -jcvf archive.tar.bz2 files
This instructs tar to compress files newer than 1st of January 2014, 18:00:00.
Find the ref spec of the commit you want to be the head of your branch on Github and use the following command:
git push origin +[ref]:[branchName]
In your case, if you just want to go back one commit, find the beginning of the ref for that commit, say for example it is 7f6d03, and the name of the branch you want to change, say for example it is master, and do the following:
git push origin +7f6d03:master
The plus character is interpreted as --force
, which will be necessary since you are rewriting history.
Note that any time you --force
a commit you could potentially rewrite other peoples' history who merge your branch. However, if you catch the problem quickly (before anyone else merges your branch), you won't have any issues.
Passphrases can be added to an existing key or changed without regenerating the key pair:
Note This will work if keys doesn't had a passphrase, otherwise you'll get this: Enter old passphrase:
then Bad passphrase
$ ssh-keygen -p
Enter file in which the key is (/Users/tekkub/.ssh/id_rsa):
Key has comment '/Users/tekkub/.ssh/id_rsa'
Enter new passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved with the new passphrase.
If your key had passphrase
then, There's no way to recover the passphrase for a pair of SSH keys. In that case you have to create a new pair of SSH keys.
It means '\0' is a NULL
character in C, don't know about Objective-C
but its probably the same.
It's working for me in TypeScript
and JavaScript
:
let lst = [_x000D_
{ description:'Senior', price: 10},_x000D_
{ description:'Adult', price: 20},_x000D_
{ description:'Child', price: 30}_x000D_
];_x000D_
let sum = lst.map(o => o.price).reduce((a, c) => { return a + c });_x000D_
console.log(sum);
_x000D_
I hope is useful.
There are none (at least in the standard Java library). Character sets vary from platform to platform so there isn't a standard list of them in Java.
There are some 3rd party libraries which contain these constants though. One of these is Guava (Google core libraries): http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Charsets.html
No need to use a macro. Supposing your first string is in A1.
=RIGHT(A1, 4)
Drag this down and you will get your four last characters.
Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()
=RIGHT(TRIMSPACES(A1), 4)
Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:
=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))
@RichieHindle solution is now deprecated as of Visual Studio 2012. As the VS studio prompt now states:
VC++ Directories are now available as a user property sheet that is added by default to all projects.
To set an include path you now must right-click a project and go to:
Properties/VC++ Directories/General/Include Directories
Try This
Write code in your service
import {Observable, of} from 'rxjs';
import json file
import Product from "./database/product.json";
getProduct(): Observable<any> {
return of(Product).pipe(delay(1000));
}
In component
get_products(){
this.sharedService.getProduct().subscribe(res=>{
console.log(res);
})
}
You could use -sed- and -grep- to replace or write to the xml header of each file specifying your desired sheet name, e.g., sheetname1, between any occurrence of the tags:
<Sheetnames>?sheetname1?</Sheetnames>
I had a similar problem, I wanted to change the format, but I also wanted the flexibility of being able to change the format in the blade template engine too.
I, therefore, set my model up as the following:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
\Carbon\Carbon::setToStringFormat('d-m-Y');
class User extends Model
{
protected $dates = [
'from_date',
];
}
The setToStringFormat
will set all the dates to use this format for this model.
The advantage of this for me is that I could have the format that I wanted without the mutator, because with the mutator, the attribute is returned as a string meaning that in the blade template I would have to write something like this if I wanted to change the format in the template:
{{ date('Y', strtotime($user->from_date)) }}
Which isn't very clean.
Instead, the attribute is still returned as a Carbon instance, however it is first returned in the desired format.
That means that in the template I could write the following, cleaner, code:
{{ $user->from_date->format('Y') }}
In addition to being able to reformat the Carbon instance, I can also call various Carbon methods on the attribute in the template.
There is probably an oversight to this approach; I'm going to wager it is not a good idea to specify the string format at the top of the model in case it affects other scripts. From what I have seen so far, that has not happened. It has only changed the default Carbon for that model only.
In this instance, it might be a good set the Carbon format back to what it was originally at the bottom of the model script. This is a bodged idea, but it would work for each model to have its own format.
Contrary, if you are having the same format for each model then in your AppServiceProvider instead. That would just keep the code neater and easier to maintain.
insert into run(id,name,dob)values(&id,'&name',[what should I write here?]);
insert into run(id,name,dob)values(&id,'&name',TO_DATE('&dob','YYYY-MM-DD'));
Check this out: http://wil-linssen.com/entry/extending-the-jquery-sortable-with-ajax-mysql/ I'm using this and I'm happy with the solution.
Right here you can find a demo: http://demo.wil-linssen.com/jquery-sortable-ajax/
Enjoy!
I've found that using OnTime
can be painful, particularly when:
This article by Chip Pearson was very illuminating. I prefer to use the Windows Timer now, instead of OnTime
.
Alternatively
with Pool() as pool:
pool.map(fits.open, [name + '.fits' for name in datainput])
Simply include permissions integer in octal (works for both python 2 and python3):
os.chmod(path, 0o444)
Try this:
import cv2
import cv
color_img = cv2.cvtColor(gray_img, cv.CV_GRAY2RGB)
I discovered, while using opencv, that some of the constants are defined in the cv2 module, and other in the cv module.
Sure. I suppose that you have already installed TensorFlow for GPU.
You need to add the following block after importing keras. I am working on a machine which have 56 core cpu, and a gpu.
import keras
import tensorflow as tf
config = tf.ConfigProto( device_count = {'GPU': 1 , 'CPU': 56} )
sess = tf.Session(config=config)
keras.backend.set_session(sess)
Of course, this usage enforces my machines maximum limits. You can decrease cpu and gpu consumption values.
Without installing any additional library, it is compatible with every single terminal i know.
Class approach:
First do import config as cfg
.
clipped
is dataframe.
#### HEADER: ####
print('{0:<23} {1:>24} {2:>26} {3:>26} {4:>11} {5:>11}'.format('Road name','Classification','Function','Form of road','Length','Distance') )
#### Now row by row: ####
for index, row in clipped.iterrows():
rdName = self.colorize(row['name1'],cfg.Green)
rdClass = self.colorize(row['roadClassification'],cfg.LightYellow)
rdFunction = self.colorize(row['roadFunction'],cfg.Yellow)
rdForm = self.colorize(row['formOfWay'],cfg.LightBlue)
rdLength = self.colorize(row['length'],cfg.White)
rdDistance = self.colorize(row['distance'],cfg.LightCyan)
print('{0:<30} {1:>35} {2:>35} {3:>35} {4:>20} {5:>20}'.format(rdName,rdClass,rdFunction,rdForm,rdLength,rdDistance) )
Meaning of {0:<30} {1:>35} {2:>35} {3:>35} {4:>20} {5:>20}
:
0, 1, 2, 3, 4, 5
-> columns, there are 6 in total in this case
30, 35, 20
-> width of column (note that you'll have to add length of \033[96m
- this for Python is a string as well), just experiment :)
>, <
-> justify: right, left (there is =
for filling with zeros as well)
What is in config.py:
#colors
ResetAll = "\033[0m"
Bold = "\033[1m"
Dim = "\033[2m"
Underlined = "\033[4m"
Blink = "\033[5m"
Reverse = "\033[7m"
Hidden = "\033[8m"
ResetBold = "\033[21m"
ResetDim = "\033[22m"
ResetUnderlined = "\033[24m"
ResetBlink = "\033[25m"
ResetReverse = "\033[27m"
ResetHidden = "\033[28m"
Default = "\033[39m"
Black = "\033[30m"
Red = "\033[31m"
Green = "\033[32m"
Yellow = "\033[33m"
Blue = "\033[34m"
Magenta = "\033[35m"
Cyan = "\033[36m"
LightGray = "\033[37m"
DarkGray = "\033[90m"
LightRed = "\033[91m"
LightGreen = "\033[92m"
LightYellow = "\033[93m"
LightBlue = "\033[94m"
LightMagenta = "\033[95m"
LightCyan = "\033[96m"
White = "\033[97m"
First thing first. set the column in which you are working in by clicking on format cells->number-> date and then format e.g Jan-16 representing Jan, 1, 2016. and then apply either of the formulas above.
With Bootstrap 4, you can do it much more easily: http://v4-alpha.getbootstrap.com/layout/flexbox-grid/#vertical-alignment
Just right click on the ConstrainLayout and select the "convert view" and then "RelativeLayout":
Using Promise
and checking if the body
object is a valid JSON. If not a Promise reject
will be returned.
var DoPost = function(url, body) {
try {
body = JSON.stringify(body);
} catch (error) {
return reject(error);
}
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: url,
data: body,
contentType: "application/json",
dataType: 'json'
})
.done(function(data) {
return resolve(data);
})
.fail(function(error) {
console.error(error);
return reject(error);
})
.always(function() {
// called after done or fail
});
});
}
As John Weldon said all members must be static in a static class. Try
public static class employee
{
static NameValueCollection appSetting = ConfigurationManager.AppSettings;
}
You can try using an output parameter. http://msdn.microsoft.com/en-us/library/ms378108.aspx
Try Case
SELECT stock.name,
CASE
WHEN stock.quantity <20 THEN 'Buy urgent'
ELSE 'There is enough'
END
FROM stock
I've just come across this, and thought I'd add my thoughts. As others have suggested, I'd recommend manually adding IDs, but if you really want something close to what you've described, you could use this:
var objectId = (function () {
var allObjects = [];
var f = function(obj) {
if (allObjects.indexOf(obj) === -1) {
allObjects.push(obj);
}
return allObjects.indexOf(obj);
}
f.clear = function() {
allObjects = [];
};
return f;
})();
You can get any object's ID by calling objectId(obj)
. Then if you want the id to be a property of the object, you can either extend the prototype:
Object.prototype.id = function () {
return objectId(this);
}
or you can manually add an ID to each object by adding a similar function as a method.
The major caveat is that this will prevent the garbage collector from destroying objects when they drop out of scope... they will never drop out of the scope of the allObjects
array, so you might find memory leaks are an issue. If your set on using this method, you should do so for debugging purpose only. When needed, you can do objectId.clear()
to clear the allObjects
and let the GC do its job (but from that point the object ids will all be reset).
You can't select a sheet in a non-active workbook.
You must first activate the workbook, then you can select the sheet.
workbooks("A").activate
workbooks("A").worksheets("B").select
When you use Activate it automatically activates the workbook.
Note you can select >1 sheet in a workbook:
activeworkbook.sheets(array("sheet1","sheet3")).select
but only one sheet can be Active, and if you activate a sheet which is not part of a multi-sheet selection then those other sheets will become un-selected.
Quick work around
Simply enclose the list within a new list, as done for col2 in the data frame below. The reason it works is that python takes the outer list (of lists) and converts it into a column as if it were containing normal scalar items, which is lists in our case and not normal scalars.
mydict={'col1':[1,2,3],'col2':[[1, 4], [2, 5], [3, 6]]}
data=pd.DataFrame(mydict)
data
col1 col2
0 1 [1, 4]
1 2 [2, 5]
2 3 [3, 6]
DateTimePicker1.value = Format(Date.Now)
Click on Statistics icon to display and then run the query to get the timings and to know how efficient your query is
Your app will crash if you call Context.startForegroundService(...)
and then call Context.stopService(...)
before Service.startForeground(...)
is called.
I have a clear repro here ForegroundServiceAPI26
I have opened a bug on this at : Google issue tracker
Several bugs on this have been opened and closed Won't Fix.
Hopefully mine with clear repro steps will make the cut.
Information provided by google team
Google issue tracker Comment 36
This is not a framework bug; it's intentional. If the app starts a service instance with startForegroundService()
, it must transition that service instance to the foreground state and show the notification. If the service instance is stopped before startForeground()
is called on it, that promise is unfulfilled: this is a bug in the app.
Re #31, publishing a Service that other apps can start directly is fundamentally unsafe. You can mitigate that a bit by treating all start actions of that service as requiring startForeground()
, though obviously that may not be what you had in mind.
Google issue tracker Comment 56
There are a couple of different scenarios that lead to the same outcome here.
The outright semantic issue, that it's simply an error to kick something off with startForegroundService()
but neglect to actually transition it to foreground via startForeground()
, is just that: a semantic issue. That's treated as an app bug, intentionally. Stopping the service before transitioning it to foreground is an app error. That was the crux of the OP, and is why this issue has been marked "working as intended."
However, there are also questions about spurious detection of this problem. That's is being treated as a genuine problem, though it's being tracked separately from this particular bug tracker issue. We aren't deaf to the complaint.
In my case, one of the exported child module was not returning a proper react component.
const Component = <div> Content </div>;
instead of
const Component = () => <div>Content</div>;
The error shown was for the parent, hence couldn't figure out.
To fix this issue, do these steps:
Set as StartUp Project
from the menu If it did not work, be sure that you have set your start page. If your project is C# Windows Application or C# Console Application, try this:
Properties
Output Type
drop boxAll your exercise conditionals are separate and the else is only tied to the last if statement. Use else if
to bind them all together in the way I believe you intend.
Suppose you have COMPANY and EMPLOYEE. COMPANY has many EMPLOYEES (i.e. EMPLOYEE has a field COMPANY_ID).
In some O/R configurations, when you have a mapped Company object and go to access its Employee objects, the O/R tool will do one select for every employee, wheras if you were just doing things in straight SQL, you could select * from employees where company_id = XX
. Thus N (# of employees) plus 1 (company)
This is how the initial versions of EJB Entity Beans worked. I believe things like Hibernate have done away with this, but I'm not too sure. Most tools usually include info as to their strategy for mapping.
in Unix:
new com.sun.security.auth.module.UnixSystem().getUsername()
in Windows:
new com.sun.security.auth.module.NTSystem().getName()
in Solaris:
new com.sun.security.auth.module.SolarisSystem().getUsername()
You can use the border-radius attribute to give it a border-radius equivalent to the element's border-radius. For example:
<div style="border-radius 10px; -moz-border-radius 10px; -webkit-border-radius 10px; width: 20px; height: 20px; background: red; border: solid black 1px;"> </div>
(The reason for using the -moz and -webkit extensions is to support pre-CSS3-final versions of Gecko and Webkit.)
There are more examples on this page. As far as inserting text, you can do it but you have to be mindful of the positioning, as most browsers' box padding model still uses the outer square.
Learn more about how to navigate through the parse tree in BeautifulSoup
. Parse tree has got tags
and NavigableStrings
(as THIS IS A TEXT). An example
from BeautifulSoup import BeautifulSoup
doc = ['<html><head><title>Page title</title></head>',
'<body><p id="firstpara" align="center">This is paragraph <b>one</b>.',
'<p id="secondpara" align="blah">This is paragraph <b>two</b>.',
'</html>']
soup = BeautifulSoup(''.join(doc))
print soup.prettify()
# <html>
# <head>
# <title>
# Page title
# </title>
# </head>
# <body>
# <p id="firstpara" align="center">
# This is paragraph
# <b>
# one
# </b>
# .
# </p>
# <p id="secondpara" align="blah">
# This is paragraph
# <b>
# two
# </b>
# .
# </p>
# </body>
# </html>
To move down the parse tree you have contents
and string
.
contents is an ordered list of the Tag and NavigableString objects contained within a page element
if a tag has only one child node, and that child node is a string, the child node is made available as tag.string, as well as tag.contents[0]
For the above, that is to say you can get
soup.b.string
# u'one'
soup.b.contents[0]
# u'one'
For several children nodes, you can have for instance
pTag = soup.p
pTag.contents
# [u'This is paragraph ', <b>one</b>, u'.']
so here you may play with contents
and get contents at the index you want.
You also can iterate over a Tag, this is a shortcut. For instance,
for i in soup.body:
print i
# <p id="firstpara" align="center">This is paragraph <b>one</b>.</p>
# <p id="secondpara" align="blah">This is paragraph <b>two</b>.</p>
Yes to the first question and no to the second question; it's a virtual machine. Your problems are probably related to unspecified changes in library implementation between versions. Although it could be, say, a race condition.
There are some hoops the VM has to go through. Notably references are treated in class files as if they took the same space as int
s on the stack. double
and long
take up two reference slots. For instance fields, there's some rearrangement the VM usually goes through anyway. This is all done (relatively) transparently.
Also some 64-bit JVMs use "compressed oops". Because data is aligned to around every 8 or 16 bytes, three or four bits of the address are useless (although a "mark" bit may be stolen for some algorithms). This allows 32-bit address data (therefore using half as much bandwidth, and therefore faster) to use heap sizes of 35- or 36-bits on a 64-bit platform.
Well, it's not a single statement, but it's about as close as you can get with oracle:
BEGIN
FOR R IN (SELECT owner, table_name FROM all_tables WHERE owner='TheOwner') LOOP
EXECUTE IMMEDIATE 'grant select on '||R.owner||'.'||R.table_name||' to TheUser';
END LOOP;
END;
I think it will help you
string filename = String.Format("Results_{0}_{1}.xls", DateTime.Today.Month.ToString(), DateTime.Today.Year.ToString());
if (!string.IsNullOrEmpty(GRIDVIEWNAME.Page.Title))
filename = GRIDVIEWNAME.Page.Title + ".xls";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.Charset = "";
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm();
GRIDVIEWNAME.Parent.Controls.Add(form);
form.Controls.Add(GRIDVIEWNAME);
form.RenderControl(htmlWriter);
HttpContext.Current.Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
HttpContext.Current.Response.Write(stringWriter.ToString());
HttpContext.Current.Response.End();
Span is an inline element. It has no width or height.
You could turn it into a block-level element, then it will accept your dimension directives.
span.product__specfield_8_arrow
{
display: inline-block; /* or block */
}
In the format for if
if (this OR that)
this
and that
are expression not values. title == "aaaaa"
is a valid expression. Also OR
is not a valid construct in C#, you have to use ||
.
Perform a click on the link to the tab anchor whenever the page is ready i.e.
$('a[href="' + window.location.hash + '"]').trigger('click');
Or in vanilla JavaScript
document.querySelector('a[href="' + window.location.hash + '"]').click();
Make a class that will fit table cell width to content
.table td.fit,
.table th.fit {
white-space: nowrap;
width: 1%;
}
As of the current JRE implementation, Function.identity()
will always return the same instance while each occurrence of identifier -> identifier
will not only create its own instance but even have a distinct implementation class. For more details, see here.
The reason is that the compiler generates a synthetic method holding the trivial body of that lambda expression (in the case of x->x
, equivalent to return identifier;
) and tell the runtime to create an implementation of the functional interface calling this method. So the runtime sees only different target methods and the current implementation does not analyze the methods to find out whether certain methods are equivalent.
So using Function.identity()
instead of x -> x
might save some memory but that shouldn’t drive your decision if you really think that x -> x
is more readable than Function.identity()
.
You may also consider that when compiling with debug information enabled, the synthetic method will have a line debug attribute pointing to the source code line(s) holding the lambda expression, therefore you have a chance of finding the source of a particular Function
instance while debugging. In contrast, when encountering the instance returned by Function.identity()
during debugging an operation, you won’t know who has called that method and passed the instance to the operation.
No to compare anything, you can simply check that by this...,.
if(document.getElementById("url")){ alert('exit');}
if($("#url")){alert('exist');}
you can also use the html() function as well like
if($("#url).html()){alert('exist');}
In case you want to install mysql or percona unattended (like in my case ansible), you can use following script:
# first part opens mysql log
# second part greps lines with temporary password
# third part picks last line (most recent one)
# last part removes all the line except the password
# the result goes into password variable
password=$(cat /var/log/mysqld.log | grep "A temporary password is generated for" | tail -1 | sed -n 's/.*root@localhost: //p')
# setting new password, you can use $1 and run this script as a file and pass the argument through the script
newPassword="wh@teverYouLikE"
# resetting temporary password
mysql -uroot -p$password -Bse "ALTER USER 'root'@'localhost' IDENTIFIED BY '$newPassword';"
Here is a simple way to get substring in Swift
import UIKit
var str = "Hello, playground"
var res = NSString(string: str)
print(res.substring(from: 4))
print(res.substring(to: 10))
Directory Services/LDAP lookups can be used to serve this purpose. It involves some changes at infrastructure level, but most production environments have such provision
You need to pass the values of the dict into the Bike
constructor before using like that. Or, see the namedtuple
-- seems more in line with what you're trying to do.
There is no universal command line that would fit to all cases (sometimes you need to blur and sharpen image). But you can give a try to TEXTCLEANER from Fred's ImageMagick Scripts.
If you are not fan of command line, maybe you can try to use opensource scantailor.sourceforge.net or commercial bookrestorer.
A span tag is only as wide as its contents, so there is no 'center' of a span tag. There is no extra space on either side of the content.
A div tag, however, is as wide as its containing element, so the content of that div can be centered using any extra space that the content doesn't take up.
So if your div is 100px width and your content only takes 50px, the browser will divide the remaining 50px by 2 and pad 25px on each side of your content to center it.
import * as mongoose from 'mongoose'
Message queues are asynchronous and can retry a number of times if delivery fails. Use a message queue if the requester doesn't need to wait for a response.
The phrase "web services" make me think of synchronous calls to a distributed component over HTTP. Use web services if the requester needs a response back.
for objects/modules, you can also
'var' in dir(obj)
For example,
>>> class Something(object):
... pass
...
>>> c = Something()
>>> c.a = 1
>>> 'a' in dir(c)
True
>>> 'b' in dir(c)
False
Here's a nice way (not mine, the original reference is here: http://sujitpal.blogspot.com/2007/03/accessing-spring-beans-from-legacy-code.html
I've used this approach and it works fine. Basically it's a simple bean that holds a (static) reference to the application context. By referencing it in the spring config it's initialized.
Take a look at the original ref, it's very clear.
All the other solutions, including the top-voted one with vh
are sub-optimal when compared to the flex model solution.
With the advent of the CSS flex model, solving the 100% height problem becomes very, very easy: use height: 100%; display: flex
on the parent, and flex: 1
on the child elements. They'll automatically take up all the available space in their container.
Note how simple the markup and the CSS are. No table hacks or anything.
The flex model is supported by all major browsers as well as IE11+.
html, body {_x000D_
height: 100%;_x000D_
}_x000D_
body {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.left, .right {_x000D_
flex: 1;_x000D_
}_x000D_
_x000D_
.left {_x000D_
background: orange;_x000D_
}_x000D_
_x000D_
.right {_x000D_
background: cyan;_x000D_
}
_x000D_
<div class="left">left</div>_x000D_
<div class="right">right</div>
_x000D_
Learn more about the flex model here.
Here is C# version of Reverse for linklist.
public void Reverse()
{
Node currentNode, nextNode=null, prevNode=null;
currentNode = head;
while(currentNode!=null)
{
nextNode = currentNode.next;
currentNode.next = prevNode;
prevNode = currentNode;
currentNode = nextNode;
}
head = prevNode;
}
document.addEventListener('dblclick', (event) => {
event.preventDefault()
}, { passive: false });
use c methods
FILE *fp =fopen("filename","mode");
fclose(fp);
mode means a for appending r for reading ,w for writing
/ / using ofstream constructors.
#include <iostream>
#include <fstream>
std::string input="some text to write"
std::ofstream outfile ("test.txt");
outfile <<input << std::endl;
outfile.close();
You could also solve this problem in following way:
$totalView = View::select(DB::raw('Date(read_at) as date'), DB::raw('count(*) as Views'))
->groupBy(DB::raw('Date(read_at)'))
->orderBy(DB::raw('Date(read_at)'))
->get();
I also had a similar requirement where I need to import .png images. I have stored these images in public folder. So the following approach worked for me.
<img src={process.env.PUBLIC_URL + './Images/image1.png'} alt="Image1"></img>
In addition to the above I have tried using require as well and it also worked for me. I have included the images inside the Images folder in src directory.
<img src={require('./Images/image1.png')} alt="Image1"/>
$("#select_id").find("option:selected").text();
It is helpful if your control is on Server side. In .NET it looks like:
$('#<%= dropdownID.ClientID %>').find("option:selected").text();
Replace var appDelegate : AppDelegate?
with
let appDelegate = UIApplication.sharedApplication().delegate
as hinted on the second commented line in viewDidLoad()
.
The keyword "optional" refers exactly to the use of ?
, see this for more details.
IF
is a PL/SQL construct. If you are executing a query, you are using SQL not PL/SQL.
In SQL, you can use a CASE
statement in the query itself
SELECT DISTINCT a.item,
(CASE WHEN b.salesman = 'VIKKIE'
THEN 'ICKY'
ELSE b.salesman
END),
NVL(a.manufacturer,'Not Set') Manufacturer
FROM inv_items a,
arv_sales b
WHERE a.co = '100'
AND a.co = b.co
AND A.ITEM_KEY = b.item_key
AND a.item LIKE 'BX%'
AND b.salesman in ('01','15')
AND trans_date BETWEEN to_date('010113','mmddrr')
and to_date('011713','mmddrr')
ORDER BY a.item
Since you aren't doing any aggregation, you don't want a GROUP BY
in your query. Are you really sure that you need the DISTINCT
? People often throw that in haphazardly or add it when they are missing a join condition rather than considering whether it is really necessary to do the extra work to identify and remove duplicates.
Take a look at the System.Net.WebClient
class, it can be used to issue requests and handle their responses, as well as to download files:
http://www.hanselman.com/blog/HTTPPOSTsAndHTTPGETsWithWebClientAndCAndFakingAPostBack.aspx
http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.90).aspx
Runnable
is often used to provide the code that a thread should run, but Runnable
itself has nothing to do with threads. It's just an object with a run()
method.
In Android, the Handler
class can be used to ask the framework to run some code later on the same thread, rather than on a different one. Runnable
is used to provide the code that should run later.
Put non-breaking spaces in your text instead of normal spaces. On Ubuntu I do this with (Compose Key)-space-space.
import ast
answer = subprocess.check_output(PYTHON_ + command, shell=True).strip()
print(ast.literal_eval(answer.decode(UTF_)))
Works for me
I didn't want to have to have the YouTube app present on the device so I used this tutorial:
http://www.viralandroid.com/2015/09/how-to-embed-youtube-video-in-android-webview.html
...to produce this code in my app:
WebView mWebView;
@Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.video_webview);
mWebView=(WebView)findViewById(R.id.videoview);
//build your own src link with your video ID
String videoStr = "<html><body>Promo video<br><iframe width=\"420\" height=\"315\" src=\"https://www.youtube.com/embed/47yJ2XCRLZs\" frameborder=\"0\" allowfullscreen></iframe></body></html>";
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
WebSettings ws = mWebView.getSettings();
ws.setJavaScriptEnabled(true);
mWebView.loadData(videoStr, "text/html", "utf-8");
}
//video_webview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:background="#000000"
android:id="@+id/bmp_programme_ll"
android:orientation="vertical" >
<WebView
android:id="@+id/videoview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
This worked just how I wanted it. It doesn't autoplay but the video streams within my app. Worth noting that some restricted videos won't play when embedded.
There isn't any EditorFor
override that lets you pass in an anonymous object whose properties would somehow get added as attributes on some tag, especially for the built-in editor templates. You would need to write your own custom editor template and pass the value you want as additional viewdata.
No. Order is not guaranteed in JSON and most other key-value data structures, so therefore the last item could sometimes be carrot
and at other times be banana
and so on. If you need to rely on ordering, your best bet is to go with arrays. The power of key-value data structures lies in accessing values by their keys
, not in being able to get the nth
item of the object.
xcopy "%userprofile%\Desktop\?????????" "D:\Backup\" /s/h/e/k/f/c
should work, assuming that your language setting allows Cyrillic (or you use Unicode fonts in the console).
For reference about the arguments: http://ss64.com/nt/xcopy.html
The solution is pretty straightforward. Suppose you want to use the "autumn" colormap scheme. The standard version:
cmap = matplotlib.cm.autumn
To reverse the colormap color spectrum, use get_cmap() function and append '_r' to the colormap title like this:
cmap_reversed = matplotlib.cm.get_cmap('autumn_r')
you can do some thing like this:
a {
color: #0060B6;
text-decoration: none;
}
a:hover
{
color:#00A0C6;
text-decoration:none;
cursor:pointer;
}
if text-decoration doesn't work then include text-decoration: none !important;
my problem was the newVersion in this code in web.config was not correct
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.1.0" />
you can see the version of Newtonsoft.Json package in nuget package manager and use it.
Try this, this should also get rid of those empty lines also:
SELECT prereq FROM test WHERE prereq IS NOT NULL;
Why not just run this: No need for special permissions
SELECT
name,
object_id,
create_date,
modify_date
FROM
sys.tables
WHERE
name like '%yourTablePattern%'
ORDER BY
modify_date
More simplified:
resultList.Remove(resultList.Single(x => x.Id == 2));
there is no needing to create a new var object.
// On the state
constructor() {
this.state = {
email: ''
}
}
// Input view ( always check if property is available in state {this.state.email ? this.state.email : ''}
<Input
value={this.state.email ? this.state.email : ''}
onChange={event => this.setState({ email: event.target.value)}
type="text"
name="emailAddress"
placeholder="[email protected]" />
Optimistic Locking is a strategy where you read a record, take note of a version number (other methods to do this involve dates, timestamps or checksums/hashes) and check that the version hasn't changed before you write the record back. When you write the record back you filter the update on the version to make sure it's atomic. (i.e. hasn't been updated between when you check the version and write the record to the disk) and update the version in one hit.
If the record is dirty (i.e. different version to yours) you abort the transaction and the user can re-start it.
This strategy is most applicable to high-volume systems and three-tier architectures where you do not necessarily maintain a connection to the database for your session. In this situation the client cannot actually maintain database locks as the connections are taken from a pool and you may not be using the same connection from one access to the next.
Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking but requires you to be careful with your application design to avoid Deadlocks. To use pessimistic locking you need either a direct connection to the database (as would typically be the case in a two tier client server application) or an externally available transaction ID that can be used independently of the connection.
In the latter case you open the transaction with the TxID and then reconnect using that ID. The DBMS maintains the locks and allows you to pick the session back up through the TxID. This is how distributed transactions using two-phase commit protocols (such as XA or COM+ Transactions) work.
By default browser always plays animated gifs, and you can't change that behaviour. If gif image does not animate there can be 2 ways to look: something wrong with the browser, something wrong with the image. Then to exclude the first variant just check trusted image in your browser (run snippet below, this gif definitely animated and works in all browsers).
Your code looks OK.
Can you check if this snippet is animated for you?
If YES, then something is bad with your gif, if NO something is wrong with your browser.
<img src="http://i.stack.imgur.com/SBv4T.gif" alt="this slowpoke moves" width=250/>
_x000D_
Add this line to Toolbar
. 100% working
android:theme="@style/Theme.AppCompat.Light.DarkActionBar"
<form method='post' id='userform' action='thisform.php'> <tr>
<td>Trouble Type</td>
<td>
<input type='checkbox' name='checkboxvar[]' value='Option One'>1<br>
<input type='checkbox' name='checkboxvar[]' value='Option Two'>2<br>
<input type='checkbox' name='checkboxvar[]' value='Option Three'>3
</td> </tr> </table> <input type='submit' class='buttons'> </form>
<?php
if (isset($_POST['checkboxvar']))
{
print_r($_POST['checkboxvar']);
}
?>
You pass the form name as an array and then you can access all checked boxes using the var itself which would then be an array.
To echo checked options into your email you would then do this:
echo implode(',', $_POST['checkboxvar']); // change the comma to whatever separator you want
Please keep in mind you should always sanitize your input as needed.
For the record, official docs on this exist: http://php.net/manual/en/faq.html.php#faq.html.arrays
Your comparator is not transitive.
Let A
be the parent of B
, and B
be the parent of C
. Since A > B
and B > C
, then it must be the case that A > C
. However, if your comparator is invoked on A
and C
, it would return zero, meaning A == C
. This violates the contract and hence throws the exception.
It's rather nice of the library to detect this and let you know, rather than behave erratically.
One way to satisfy the transitivity requirement in compareParents()
is to traverse the getParent()
chain instead of only looking at the immediate ancestor.
First of all don't make the mock static. Make it a private field. Just put your setUp class in the @Before
not @BeforeClass
. It might be run a bunch, but it's cheap.
Secondly, the way you have it right now is the correct way to get a mock to return something different depending on the test.
You can only change the language on the whole server, not individual databases. However if you need to support the UK you can run the following command before all inputs and outputs:
set language 'british english'
Or if you are having issues entering datatimes from your application you might want to consider a universal input type such as
1-Dec-2008
maybe you can use jqmodal,it's lightweight and easy to use. you can show the modal box by calling
$('.box').jqmShow()
It may be added at that '&' can be used to add additional conditions e.g.
df = df[(df.EPS > 2.0) & (df.EPS <4.0)]
Notice that when evaluating the statements, pandas needs parenthesis.
I found this in the PHP manual comments:
/**
* function xml2array
*
* This function is part of the PHP manual.
*
* The PHP manual text and comments are covered by the Creative Commons
* Attribution 3.0 License, copyright (c) the PHP Documentation Group
*
* @author k dot antczak at livedata dot pl
* @date 2011-04-22 06:08 UTC
* @link http://www.php.net/manual/en/ref.simplexml.php#103617
* @license http://www.php.net/license/index.php#doc-lic
* @license http://creativecommons.org/licenses/by/3.0/
* @license CC-BY-3.0 <http://spdx.org/licenses/CC-BY-3.0>
*/
function xml2array ( $xmlObject, $out = array () )
{
foreach ( (array) $xmlObject as $index => $node )
$out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;
return $out;
}
It could help you. However, if you convert XML to an array you will loose all attributes that might be present, so you cannot go back to XML and get the same XML.
One reason you might want to host on an external server is to work around the browser limitations of concurent connections to particular server.
However, given that the jQuery file you are using will likely not change very often, the browser cache will kick in and make that point moot for the most part.
Second reason to host it on external server is to lower the traffic to your own server.
However, given the size of jQuery, chances are it will be a small part of your traffic. You should probably try to optimize your actual content.
Please put the pages in localhost and try
You can use the path
module to join the path of the directory in which helper1.js
lives to the relative path of foobar.json
. This will give you the absolute path to foobar.json
.
var fs = require('fs');
var path = require('path');
var jsonPath = path.join(__dirname, '..', 'config', 'dev', 'foobar.json');
var jsonString = fs.readFileSync(jsonPath, 'utf8');
This should work on Linux, OSX, and Windows assuming a UTF8 encoding.
Did you already check your proxys here?
git config --global --list
or
git config --local --list
Follow these steps :
Thats All.
Here is an example that sorts by the header. This table is dynamic and changes with the JSON size.
I was able to build a dynamic table off of some other people's examples and documentation. http://jsfiddle.net/lastlink/v7pszemn/1/
<tr>
<th class="{{header}}" ng-repeat="(header, value) in items[0]" ng-click="changeSorting(header)">
{{header}}
<i ng-class="selectedCls2(header)"></i>
</tr>
<tbody>
<tr ng-repeat="row in pagedItems[currentPage] | orderBy:sort.sortingOrder:sort.reverse">
<td ng-repeat="cell in row">
{{cell}}
</td>
</tr>
Although the columns are out of order, on my .NET project they are in order.
Different W3C specifications define different sets of "Node" types.
Thus, the DOM spec defines the following types of nodes:
Document
-- Element
(maximum of
one), ProcessingInstruction
,
Comment
, DocumentType
DocumentFragment
-- Element
, ProcessingInstruction
,
Comment
, Text
, CDATASection
, EntityReference
DocumentType
--
no children
EntityReference
-- Element
, ProcessingInstruction
,
Comment
, Text
, CDATASection
, EntityReference
Element
-- Element
, Text
, Comment
, ProcessingInstruction
,
CDATASection
, EntityReference
Attr
-- Text
, EntityReference
ProcessingInstruction
-- no children
Comment
-- no
children
Text
-- no
children
CDATASection
--
no children
Entity
-- Element
, ProcessingInstruction
,
Comment
, Text
, CDATASection
, EntityReference
Notation
-- no
children The XML Infoset (used by XPath) has a smaller set of nodes:
XPath has the following Node types:
The answer to your question "What is the difference between an element and a node" is:
An element is a type of node. Many other types of nodes exist and serve different purposes.
Using Vue 1.x, use the special variable $index
like so:
<li v-for="catalog in catalogs">this index : {{$index + 1}}</li>
alternatively, you can specify an alias as a first argument for v-for
directive like so:
<li v-for="(itemObjKey, catalog) in catalogs">
this index : {{itemObjKey + 1}}
</li>
See : Vue 1.x guide
Using Vue 2.x, v-for
provides a second optional argument referencing the index of the current item, you can add 1 to it in your mustache template as seen before:
<li v-for="(catalog, itemObjKey) in catalogs">
this index : {{itemObjKey + 1}}
</li>
See: Vue 2.x guide
Eliminating the parentheses in the v-for
syntax also works fine hence:
<li v-for="catalog, itemObjKey in catalogs">
this index : {{itemObjKey + 1}}
</li>
Hope that helps.
Use the following block of query to update Table1 with Table2 based on ID:
UPDATE Sales_Import, RetrieveAccountNumber
SET Sales_Import.AccountNumber = RetrieveAccountNumber.AccountNumber
where Sales_Import.LeadID = RetrieveAccountNumber.LeadID;
This is the easiest way to tackle this problem.
Using resources at http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy will solve the problem. However, you should be careful about versions compatibility. After trying for several times, finally I decided to uninstall python and then installed a fresh version of python along with numpy and then installed scipy and this resolved my problem.
Microsoft provides a walkthrough for creating a Windows Explorer style interface in C#.
There are also several examples on Code Project and other sites. Immediate examples are Explorer Tree, My Explorer, File Browser and Advanced File Explorer but there are others. Explorer Tree seems to look the best from the brief glance I took.
I used the search term windows explorer tree view C#
in Google to find these links.
This comes down to browser image support; it looks like the only mainstream browser that supports tiff is Safari:
http://en.wikipedia.org/wiki/Comparison_of_web_browsers#Image_format_support
Where are you getting the tiff images from? Is it possible for them to be generated in a different format?
If you have a static set of images then I'd recommend using something like PaintShop Pro to batch convert them, changing the format.
If this isn't an option then there might be some mileage in looking for a pre-written Java applet (or another browser plugin) that can display the images in the browser.
The smarter_csv
gem was specifically created for this use-case: to read data from CSV file and quickly create database entries.
require 'smarter_csv'
options = {}
SmarterCSV.process('input_file.csv', options) do |chunk|
chunk.each do |data_hash|
Moulding.create!( data_hash )
end
end
You can use the option chunk_size
to read N csv-rows at a time, and then use Resque in the inner loop to generate jobs which will create the new records, rather than creating them right away - this way you can spread the load of generating entries to multiple workers.
See also: https://github.com/tilo/smarter_csv
I had the same issue. After changing a semicolon in the php.ini file I solved my problem. Let's see how can you solve it?
First, open php.ini file. xampp/php/php.ini
Search extension=imap
remove semicolon before extension and save this file.
Code before remove semicolon ;extension=imap
Code after remove semicolon extension=imap
Finally, open the XAMPP Control panel and restart Apache.
Interestingly putting <httpCookies httpOnlyCookies="false"/>
doesn't seem to disable httpOnlyCookies
in ASP.NET 2.0. Check this article about SessionID and Login Problems With ASP .NET 2.0.
Looks like Microsoft took the decision to not allow you to disable it from the web.config. Check this post on forums.asp.net
Since Java 1.6, there is ArrayDeque
, which implements Queue
and seems to be faster and more memory efficient than a LinkedList
and doesn't have the thread synchronization overhead of the ArrayBlockingQueue
: from the API docs: "This class is likely to be faster than Stack when used as a stack, and faster than LinkedList when used as a queue."
final Queue<Object> q = new ArrayDeque<Object>();
q.add(new Object()); //insert element
q.poll(); //remove element
Instead of using the new pragmas, you can also use __attribute__((optimize("O0")))
for your needs. This has the advantage of just applying to a single function and not all functions defined in the same file.
Usage example:
void __attribute__((optimize("O0"))) foo(unsigned char data) {
// unmodifiable compiler code
}
Use $() to assign the output of cat
to your variable like this:
VAR=$(cat <<'END_HEREDOC'
abc'asdf"
$(dont-execute-this)
foo"bar"''
END_HEREDOC
)
# this will echo variable with new lines intact
echo "$VAR"
# this will echo variable without new lines (changed to space character)
echo $VAR
Making sure to delimit starting END_HEREDOC with single-quotes.
Note that ending heredoc delimiter END_HEREDOC
must be alone on the line (hence ending parenthesis is on the next line).
Thanks to @ephemient
for the answer.
[Updated to adapt to modern pandas
, which has isnull
as a method of DataFrame
s..]
You can use isnull
and any
to build a boolean Series and use that to index into your frame:
>>> df = pd.DataFrame([range(3), [0, np.NaN, 0], [0, 0, np.NaN], range(3), range(3)])
>>> df.isnull()
0 1 2
0 False False False
1 False True False
2 False False True
3 False False False
4 False False False
>>> df.isnull().any(axis=1)
0 False
1 True
2 True
3 False
4 False
dtype: bool
>>> df[df.isnull().any(axis=1)]
0 1 2
1 0 NaN 0
2 0 0 NaN
[For older pandas
:]
You could use the function isnull
instead of the method:
In [56]: df = pd.DataFrame([range(3), [0, np.NaN, 0], [0, 0, np.NaN], range(3), range(3)])
In [57]: df
Out[57]:
0 1 2
0 0 1 2
1 0 NaN 0
2 0 0 NaN
3 0 1 2
4 0 1 2
In [58]: pd.isnull(df)
Out[58]:
0 1 2
0 False False False
1 False True False
2 False False True
3 False False False
4 False False False
In [59]: pd.isnull(df).any(axis=1)
Out[59]:
0 False
1 True
2 True
3 False
4 False
leading to the rather compact:
In [60]: df[pd.isnull(df).any(axis=1)]
Out[60]:
0 1 2
1 0 NaN 0
2 0 0 NaN
In general, you can the characters of a string from i
until j
with string[i:j]
.
string[:2]
is shorthand for string[0:2]
. This works for arrays as well.
Learn about python's slice notation at the official tutorial
The ALL_DIRECTORIES
data dictionary view will have information about all the directories that you have access to. That includes the operating system path
SELECT owner, directory_name, directory_path
FROM all_directories
There's a hack I've used since the Invoke-Expression works fine for me.
You could set the current location to the path with spaces, invoke the expression, get back to your previous location and continue:
$currLocation = Get-Location
Set-Location = "C:\Windows Services\"
Invoke-Expression ".\MyService.exe"
Set-Location $currLocation
This will only work if the exe doesn't have any spaces in its name.
Hope this helps
It is better to add new Maven repository (preferably using your own artifactory) to your project instead of installing it to your local repository.
Maven syntax:
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
...
<repositories>
<repository>
<id>codelds</id>
<url>https://code.lds.org/nexus/content/groups/main-repo</url>
</repository>
</repositories>
Grails example:
mavenRepo "https://code.lds.org/nexus/content/groups/main-repo"
build 'com.oracle:ojdbc6:11.2.0.3'
The PHP way of doing this is simple:
$out = strlen($in) > 50 ? substr($in,0,50)."..." : $in;
But you can achieve a much nicer effect with this CSS:
.ellipsis {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
Now, assuming the element has a fixed width, the browser will automatically break off and add the ...
for you.
This answer is late, but hopefully it helps others.
I have had the same experience of not being able to connect. Rebooting phone and PC does not help. I found the fix at: http://developer.android.com/tools/help/adb.html at the bottom of the page.
Basically you follow these steps:
adb usb
adb tcpip 5555
adb connect xxx.xxx.xxx.xxx
Where xxx.xxx.xxx.xxx is your phone's IP address.
I had the same error. I was digging all day long, don't know but I think I tried ~25 solutions on this problem. None worked until at 2AM I found out that I was missing this line at apps manifest xml:
<meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
That line was inside <application>
tag. I really hope this helps for someone.
GL.
Take a look at the autocomplete plugin. I know that it allows you to specify a delay or a minimum number of characters. Even if you don't end up using the plugin, looking through the code will give you some ideas on how to implement it yourself.
How to edit one specific row/tuple in Server Management Studio 2008/2012/2014/2016
Step 1: Right button mouse > Select "Edit Top 200 Rows"
Step 2: Navigate to Query Designer > Pane > SQL (Shortcut: Ctrl+3)
Step 3: Modify the query
Step 4: Right button mouse > Select "Execute SQL" (Shortcut: Ctrl+R)
Absolute path routing
There are 2 methods for navigation, .navigate()
and .navigateByUrl()
You can use the method .navigateByUrl()
for absolute path routing:
import {Router} from '@angular/router';
constructor(private router: Router) {}
navigateToLogin() {
this.router.navigateByUrl('/login');
}
You put the absolute path to the URL of the component you want to navigate to.
Note: Always specify the complete absolute path when calling router's navigateByUrl
method. Absolute paths must start with a leading /
// Absolute route - Goes up to root level
this.router.navigate(['/root/child/child']);
// Absolute route - Goes up to root level with route params
this.router.navigate(['/root/child', crisis.id]);
Relative path routing
If you want to use relative path routing, use the .navigate()
method.
NOTE: It's a little unintuitive how the routing works, particularly parent, sibling, and child routes:
// Parent route - Goes up one level
// (notice the how it seems like you're going up 2 levels)
this.router.navigate(['../../parent'], { relativeTo: this.route });
// Sibling route - Stays at the current level and moves laterally,
// (looks like up to parent then down to sibling)
this.router.navigate(['../sibling'], { relativeTo: this.route });
// Child route - Moves down one level
this.router.navigate(['./child'], { relativeTo: this.route });
// Moves laterally, and also add route parameters
// if you are at the root and crisis.id = 15, will result in '/sibling/15'
this.router.navigate(['../sibling', crisis.id], { relativeTo: this.route });
// Moves laterally, and also add multiple route parameters
// will result in '/sibling;id=15;foo=foo'.
// Note: this does not produce query string URL notation with ? and & ... instead it
// produces a matrix URL notation, an alternative way to pass parameters in a URL.
this.router.navigate(['../sibling', { id: crisis.id, foo: 'foo' }], { relativeTo: this.route });
Or if you just need to navigate within the current route path, but to a different route parameter:
// If crisis.id has a value of '15'
// This will take you from `/hero` to `/hero/15`
this.router.navigate([crisis.id], { relativeTo: this.route });
Link parameters array
A link parameters array holds the following ingredients for router navigation:
['/hero']
['/hero', hero.id]
or ['/hero', { id: hero.id, foo: baa }]
Directory-like syntax
The router supports directory-like syntax in a link parameters list to help guide route name lookup:
./
or no leading slash is relative to the current level.
../
to go up one level in the route path.
You can combine relative navigation syntax with an ancestor path. If you must navigate to a sibling route, you could use the ../<sibling>
convention to go up one level, then over and down the sibling route path.
Important notes about relative nagivation
To navigate a relative path with the Router.navigate
method, you must supply the ActivatedRoute
to give the router knowledge of where you are in the current route tree.
After the link parameters array, add an object with a relativeTo
property set to the ActivatedRoute
. The router then calculates the target URL based on the active route's location.
From official Angular Router Documentation
JSch library is the powerful library that can be used to read file from SFTP server. Below is the tested code to read file from SFTP location line by line
JSch jsch = new JSch();
Session session = null;
try {
session = jsch.getSession("user", "127.0.0.1", 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword("password");
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
InputStream stream = sftpChannel.get("/usr/home/testfile.txt");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException io) {
System.out.println("Exception occurred during reading file from SFTP server due to " + io.getMessage());
io.getMessage();
} catch (Exception e) {
System.out.println("Exception occurred during reading file from SFTP server due to " + e.getMessage());
e.getMessage();
}
sftpChannel.exit();
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
}
Please refer the blog for whole program.
SELECT d1.Short_Code
FROM domain1 d1
LEFT JOIN domain2 d2
ON d1.Short_Code = d2.Short_Code
WHERE d2.Short_Code IS NULL
It's simple to convert the Unix timestamp into the desired format. Lets suppose _ts is the Unix timestamp in long
let date = NSDate(timeIntervalSince1970: _ts)
let dayTimePeriodFormatter = NSDateFormatter()
dayTimePeriodFormatter.dateFormat = "MMM dd YYYY hh:mm a"
let dateString = dayTimePeriodFormatter.stringFromDate(date)
print( " _ts value is \(_ts)")
print( " _ts value is \(dateString)")
All you need to do is this: click on (window) on the dropdown manue on top of your screen. click on (Editor). click on (zoom in) as many times as you need to.
Just a note, if you ever see this:
a = x ? : y;
It's a GNU extension to the standard (see https://gcc.gnu.org/onlinedocs/gcc/Conditionals.html#Conditionals).
It is the same as
a = x ? x : y;
The only way to prevent all after_save callbacks is to have the first one return false.
Perhaps you could try something like (untested):
class MyModel < ActiveRecord::Base
attr_accessor :skip_after_save
def after_save
return false if @skip_after_save
... blah blah ...
end
end
...
m = MyModel.new # ... etc etc
m.skip_after_save = true
m.save
It basically means that the object implements the __getitem__()
method. In other words, it describes objects that are "containers", meaning they contain other objects. This includes strings, lists, tuples, and dictionaries.
The following example the fastest (not parallelized) way list files and sub-folders in a directory tree handling exceptions. It would be faster to use Directory.EnumerateDirectories using SearchOption.AllDirectories to enumerate all directories, but this method will fail if hits a UnauthorizedAccessException or PathTooLongException.
Uses the generic Stack collection type, which is a last in first out (LIFO) stack and does not use recursion. From https://msdn.microsoft.com/en-us/library/bb513869.aspx, allows you to enumerate all sub-directories and files and deal effectively with those exceptions.
public class StackBasedIteration
{
static void Main(string[] args)
{
// Specify the starting folder on the command line, or in
// Visual Studio in the Project > Properties > Debug pane.
TraverseTree(args[0]);
Console.WriteLine("Press any key");
Console.ReadKey();
}
public static void TraverseTree(string root)
{
// Data structure to hold names of subfolders to be
// examined for files.
Stack<string> dirs = new Stack<string>(20);
if (!System.IO.Directory.Exists(root))
{
throw new ArgumentException();
}
dirs.Push(root);
while (dirs.Count > 0)
{
string currentDir = dirs.Pop();
string[] subDirs;
try
{
subDirs = System.IO.Directory.EnumerateDirectories(currentDir); //TopDirectoryOnly
}
// An UnauthorizedAccessException exception will be thrown if we do not have
// discovery permission on a folder or file. It may or may not be acceptable
// to ignore the exception and continue enumerating the remaining files and
// folders. It is also possible (but unlikely) that a DirectoryNotFound exception
// will be raised. This will happen if currentDir has been deleted by
// another application or thread after our call to Directory.Exists. The
// choice of which exceptions to catch depends entirely on the specific task
// you are intending to perform and also on how much you know with certainty
// about the systems on which this code will run.
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e.Message);
continue;
}
catch (System.IO.DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
continue;
}
string[] files = null;
try
{
files = System.IO.Directory.EnumerateFiles(currentDir);
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e.Message);
continue;
}
catch (System.IO.DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
continue;
}
// Perform the required action on each file here.
// Modify this block to perform your required task.
foreach (string file in files)
{
try
{
// Perform whatever action is required in your scenario.
System.IO.FileInfo fi = new System.IO.FileInfo(file);
Console.WriteLine("{0}: {1}, {2}", fi.Name, fi.Length, fi.CreationTime);
}
catch (System.IO.FileNotFoundException e)
{
// If file was deleted by a separate application
// or thread since the call to TraverseTree()
// then just continue.
Console.WriteLine(e.Message);
continue;
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e.Message);
continue;
}
}
// Push the subdirectories onto the stack for traversal.
// This could also be done before handing the files.
foreach (string str in subDirs)
dirs.Push(str);
}
}
}
For those who get this error in an ASP.NET MVC 3 project, within Visual Studio itself:
In an ASP.NET MVC 3 app I'm working on, I tried adding a reference to Microsoft.SqlServer.BatchParser to a project to resolve a problem where it was missing on a deployment server. (Our app uses SMO; the correct fix was to install SQL Server Native Client and a couple other things on the deployment server.)
Even after I removed the reference to BatchParser, I kept getting the "An attempt was made..." error, referencing the BatchParser DLL, on every ASP.NET MVC 3 page I opened, and that error was followed by dozens of page parsing errors.
If this happens to you, do a file search and see if the DLL is still in one of your project's \bin folders. Even if you do a rebuild, Visual Studio doesn't necessarily clear out everything in all your \bin folders. When I deleted the DLL from the bin and built again, the error went away.
Here is another choice: Chaosreader
So I need to debug an application which posts xml to a 3rd party application. I found a brilliant little perl script which does all the hard work – you just chuck it a tcpdump output file, and it does all the manipulation and outputs everything you need...
The script is called chaosreader0.94. See http://www.darknet.org.uk/2007/11/chaosreader-trace-tcpudp-sessions-from-tcpdump/
It worked like a treat, I did the following:
tcpdump host www.blah.com -s 9000 -w outputfile; perl chaosreader0.94 outputfile
JSON in any HTML tag except <script>
tag would be a mere text. Thus it's like you add a story to your HTML page.
However, about formatting, that's another matter. I guess you should change the title of your question.
A better way to normalize your image is to take each value and divide by the largest value experienced by the data type. This ensures that images that have a small dynamic range in your image remain small and they're not inadvertently normalized so that they become gray. For example, if your image had a dynamic range of [0-2]
, the code right now would scale that to have intensities of [0, 128, 255]
. You want these to remain small after converting to np.uint8
.
Therefore, divide every value by the largest value possible by the image type, not the actual image itself. You would then scale this by 255 to produced the normalized result. Use numpy.iinfo
and provide it the type (dtype
) of the image and you will obtain a structure of information for that type. You would then access the max
field from this structure to determine the maximum value.
So with the above, do the following modifications to your code:
import numpy as np
import cv2
[...]
info = np.iinfo(data.dtype) # Get the information of the incoming image type
data = data.astype(np.float64) / info.max # normalize the data to 0 - 1
data = 255 * data # Now scale by 255
img = data.astype(np.uint8)
cv2.imshow("Window", img)
Note that I've additionally converted the image into np.float64
in case the incoming data type is not so and to maintain floating-point precision when doing the division.
In Swift 4:
Swift 4
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Your title"
}
I hope it helps, regards!
if exist yourfilename (
echo Yes
) else (
echo No
)
Replace yourfilename with the name of your file.
if exist yourfoldername\ (
echo Yes
) else (
echo No
)
Replace yourfoldername with the name of your folder.
A trailing backslash (\
) seems to be enough to distinguish between directories and ordinary files.
You need to run your script after the element exists. Move the <input type="hidden" name="checkyear" id="checkyear" value="">
to the beginning.
Use -
new Select(driver.findElement(By.id("gender"))).selectByVisibleText("Germany");
Of course, you need to import org.openqa.selenium.support.ui.Select;
Normally the ON clause comes from the mapping's join columns, but the JPA 2.1 draft allows for additional conditions in a new ON clause.
See,
http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/JPQL#ON
import * as Rx from 'rxjs/Rx';
We should add the above import to make the blow code to work
Let obs = Rx.Observable
.interval(1000).take(3);
obs.subscribe(value => console.log('Subscriber: ' + value));
const d = new Date();
const day = `0${d.getDate()}`.slice(-2);
So a function could be created like :
AddZero(val){
// adding 0 if the value is a single digit
return `0${val}`.slice(-2);
}
Your new code :
var MyDate = new Date();
var MyDateString = new Date();
MyDate.setDate(MyDate.getDate()+10);
MyDateString = AddZero(MyDate.getDate()) + '/' + AddZero(MyDate.getMonth() + 1) + '/' + MyDate.getFullYear();
Use position: fixed
instead of position: absolute
.
See here.
In addition to the above I personally recommend
onKeyUp():
Programatically Speaking keydown will fire when the user depresses a key initially but It will repeat while the user keeps the key depressed.*
This remains true for all development platforms.
Google development suggested that if you are intercepting the BACK button in a view you should track the KeyEvent with starttracking on keydown then invoke with keyup.
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
event.startTracking();
return true;
}
return super.onKeyDown(keyCode, event);
}
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
&& !event.isCanceled()) {
// *** Your Code ***
return true;
}
return super.onKeyUp(keyCode, event);
}
This solution seems easy to follow:
public static bool isValidURL(string url) {
WebRequest webRequest = WebRequest.Create(url);
WebResponse webResponse;
try
{
webResponse = webRequest.GetResponse();
}
catch //If exception thrown then couldn't get response from address
{
return false ;
}
return true ;
}
For anyone having issues in IE:
Please upvote the answer here by Yetti: saving canvas locally in IE
dataURItoBlob = function(dataURI) {
var binary = atob(dataURI.split(',')[1]);
var array = [];
for(var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {type: 'image/png'});
}
var blob = dataURItoBlob(uri);
window.navigator.msSaveOrOpenBlob(blob, "my-image.png");
This will get you the PID of a process by name:
pidof name
Which you can then plug back in to ps for more detail:
ps -p $(pidof name)
This can also happen when calling dismiss()
on a dialog fragment after the screen has been locked\blanked and the Activity + dialog's instance state has been saved. To get around this call:
dismissAllowingStateLoss()
Literally every single time I'm dismissing a dialog i don't care about it's state anymore anyway, so this is ok to do - you're not actually losing any state.
The @import syntax is supported in vscode-markdown-preview-enhanced
https://github.com/shd101wyy/vscode-markdown-preview-enhanced
which probably means its part of the the underlying tool mume
https://github.com/shd101wyy/mume
and other tools built on mume
Basically you can use Directory.Getfiles(Path) to get a list of all the files. After that you loop through the list and call GetLastAccessTim() as Keith suggested.
This is commonly reported as an error due to using the wrong version of SSMS(Sql Server Management Studio). Use the version designed for your database version. You can use the command select @@version
to check which version of sql server you are actually using. This version is reported in a way that is easier to interpret than that shown in the Help About in SSMS.
Using a newer version of SSMS than your database is generally error-free, i.e. backward compatible.
I had the the same problem and I solved it that way:
File currentJavaJarFile = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath());
String currentJavaJarFilePath = currentJavaJarFile.getAbsolutePath();
String currentRootDirectoryPath = currentJavaJarFilePath.replace(currentJavaJarFile.getName(), "");
I hope I was of help to you.
A quick Google search reveals this script
// create function, it expects 2 values.
function insertAfter(newElement,targetElement) {
// target is what you want it to go after. Look for this elements parent.
var parent = targetElement.parentNode;
// if the parents lastchild is the targetElement...
if (parent.lastChild == targetElement) {
// add the newElement after the target element.
parent.appendChild(newElement);
} else {
// else the target has siblings, insert the new element between the target and it's next sibling.
parent.insertBefore(newElement, targetElement.nextSibling);
}
}
I am a happy boost user and would certainly use Andreas' solution. But if you didn't have access to the boost libs you can use the stream library:
ifstream file(argv[1]);
if (!file)
{
// Can't open file
}
It's not quite as nice as boost::filesystem::exists since the file will actually be opened...but then that's usually the next thing you want to do anyway.
Alternatively, if the method on Child is truly static (not a product of current props, state) you can define it on statics
and then access it as you would a static class method. For example:
var Child = React.createClass({
statics: {
someMethod: function() {
return 'bar';
}
},
// ...
});
console.log(Child.someMethod()) // bar
Response is dynamically generated data, according to the query parameters passed in the URL.
Example:
{ "Name": "Foo", "Id": 1234, "Rank": 7 }
Content-Type: application/json
JSON with padding. Response is JSON data, with a function call wrapped around it.
Example:
functionCall({"Name": "Foo", "Id": 1234, "Rank": 7});
Content-Type: application/javascript
You do not have to install something.
parseInt(req.params.year, 10);
should work properly.
console.log(typeof parseInt(req.params.year)); // returns 'number'
What is your output, if you use parseInt? is it still a string?