These instructions are for XCode 6.4 (since I couldn't find the update for the recent versions even this was a bit outdated)
a) Part on the developers' website:
Sign in into: https://developer.apple.com/
Member Center
Certificates, Identifiers & Profiles
Certificates>All
Click "+" to add, and then follow the instructions. You will need to open "Keychain Access.app", there under "Keychain Access" menu > "Certificate Assistant>", choose "Request a Certificate From a Certificate Authority" etc.
b) XCode part:
After all, you need to go to XCode, and open XCode>Preferences..., choose your Apple ID > View Details... > click that rounded arrow to update as well as "+" to check for iOS Distribution or iOS Developer Signing Identities.
Use generators?
def fib():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fibs = fib() #seems to be the only way to get the following line to work is to
#assign the infinite generator to a variable
f = [fibs.next() for x in xrange(1001)]
for num in f:
print num
above fib() function adapted from: http://intermediatepythonista.com/python-generators
For anybody else having issues with storyboard crashes after copying your project, head over to Main.storyboard under Identity Inspector.
Next, check that your current module is the correct renamed module and not the old one.
I had the same issue and my issue was the device not having the right date and time. Once I fixed that the certificate is being trusted.
Look here for c#
https://msdn.microsoft.com/en-us/library/system.io.streamreader.currentencoding%28v=vs.110%29.aspx
string path = @"path\to\your\file.ext";
using (StreamReader sr = new StreamReader(path, true))
{
while (sr.Peek() >= 0)
{
Console.Write((char)sr.Read());
}
//Test for the encoding after reading, or at least
//after the first read.
Console.WriteLine("The encoding used was {0}.", sr.CurrentEncoding);
Console.ReadLine();
Console.WriteLine();
}
$client = new \GuzzleHttp\Client();
$body['grant_type'] = "client_credentials";
$body['client_id'] = $this->client_id;
$body['client_secret'] = $this->client_secret;
$res = $client->post($url, [ 'body' => json_encode($body) ]);
$code = $res->getStatusCode();
$result = $res->json();
With Java 8 you may try this :
public Map<String, Object> toKeyValuePairs(Object instance) {
return Arrays.stream(Bean.class.getDeclaredMethods())
.collect(Collectors.toMap(
Method::getName,
m -> {
try {
Object result = m.invoke(instance);
return result != null ? result : "";
} catch (Exception e) {
return "";
}
}));
}
Problem was apparently not the SQL server, but the NAV system that updates the field. There is a compression property that can be used on BLOB fields in NAV, that is not a part of SQL Server. So the custom compression made the data unreadable, though the conversion worked.
The solution was to turn off compression through the Object Designer, Table Designer, Properties for the field (Shift+F4 on the field row).
After that the extraction of data can be made with e.g.: select convert(varchar(max), cast(BLOBFIELD as binary)) from Table
Thanks for all answers that were correct in many ways!
Two things.
Remove the parenthesis in setTimeout(startTimer(),startInterval);
. Keeping the parentheses invokes the function immediately.
Your startTimer function will overwrite the page content with your use of document.write
(without the above fix), and wipes out the script and HTML in the process.
Piece of cake.
Use 960Grids Go to the automatic layout builder and make a two column, fluid design. Build a left column to the width of grids that works....this is the only challenge using grids and it's very easy once you read a tutorial. In a nutshell, each column in a grid is a certain width, and you set the amount of columns you want to use. To get a column that's exactly a certain width, you have to adjust your math so that your column width is exact. Not too tough.
No chance of wrapping because others have already fought that battle for you. Compatibility back as far as you likely will ever need to go. Quick and easy....Now, download, customize and deploy.
Voila. Grids FTW.
def merge_with(f, xs, ys):
xs = a_copy_of(xs) # dict(xs), maybe generalizable?
for (y, v) in ys.iteritems():
xs[y] = v if y not in xs else f(xs[x], v)
merge_with((lambda x, y: x + y), A, B)
You could easily generalize this:
def merge_dicts(f, *dicts):
result = {}
for d in dicts:
for (k, v) in d.iteritems():
result[k] = v if k not in result else f(result[k], v)
Then it can take any number of dicts.
In my case, it was because I was only catching specific types of exceptions:
try
{
get-item -Force -LiteralPath $Path -ErrorAction Stop
#if file exists
if ($Path -like '\\*') {$fileType = 'n'} #Network
elseif ($Path -like '?:\*') {$fileType = 'l'} #Local
else {$fileType = 'u'} #Unknown File Type
}
catch [System.UnauthorizedAccessException] {$fileType = 'i'} #Inaccessible
catch [System.Management.Automation.ItemNotFoundException]{$fileType = 'x'} #Doesn't Exist
Added these to handle additional the exception causing the terminating error, as well as unexpected exceptions
catch [System.Management.Automation.DriveNotFoundException]{$fileType = 'x'} #Doesn't Exist
catch {$fileType='u'} #Unknown
Here's a runnable snippet to help you generate mailto: links with optional subject and body.
function generate() {_x000D_
var email = $('#email').val();_x000D_
var subject = $('#subject').val();_x000D_
var body = $('#body').val();_x000D_
_x000D_
var mailto = 'mailto:' + email;_x000D_
var params = {};_x000D_
if (subject) {_x000D_
params.subject = subject;_x000D_
}_x000D_
if (body) {_x000D_
params.body = body;_x000D_
}_x000D_
if (params) {_x000D_
mailto += '?' + $.param(params);_x000D_
}_x000D_
_x000D_
var $output = $('#output');_x000D_
$output.val(mailto);_x000D_
$output.focus();_x000D_
$output.select();_x000D_
document.execCommand('copy');_x000D_
}_x000D_
_x000D_
$(document).ready(function() {_x000D_
$('#generate').on('click', generate);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" id="email" placeholder="email address" /><br/>_x000D_
<input type="text" id="subject" placeholder="Subject" /><br/>_x000D_
<textarea id="body" placeholder="Body"></textarea><br/>_x000D_
<button type="button" id="generate">Generate & copy to clipboard</button><br/>_x000D_
<textarea id="output">Output</textarea>
_x000D_
I was getting this env: node: No such file or directory
error when running the job through Jenkins.
What I did to fix it - added export PATH="$PATH:"/usr/local/bin/
at the beginning of the script that Jenkins job executes.
Edit: Watch out for attr() Its related to calc() in css. You may be able to achieve it in future.
Unfortunately for now there isn't a css only solution. This is what I suggest you do. To your element give a title attribute. And use text-overflow ellipsis to prevent breakage of the design and let user know more text is there.
<div style="width: 200px; height: 1em; text-overflow: ellipsis;" title="Some sample dynamic amount of text here">
Some sample dynamic amount of text here
</div>
.
.
.
Alternatively, If you just want to reduce size based on the viewport. CSS3 supports new dimensions that are relative to view port.
body {
font-size: 3.2vw;
}
Use the following instead:
boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );
This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.
Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.
The easiest way to match both
^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$
and
^[0-9]{3}-[0-9]{3}-[0-9]{4}$
is to use alternation ((...|...)
): specify them as two mostly-separate options:
^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$
By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234
, not (123)123-1234
. So you might want to write:
^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$
(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)
When using SASS
I use the following 2 @media queries
to target IE 6-10 & EDGE.
@media screen\9
@import ie_styles
@media screen\0
@import ie_styles
http://keithclark.co.uk/articles/moving-ie-specific-css-into-media-blocks/
Edit
I also target later versions of EDGE using @support queries
(add as many as you need)
@supports (-ms-ime-align:auto)
@import ie_styles
@supports (-ms-accelerator:auto)
@import ie_styles
https://jeffclayton.wordpress.com/2015/04/07/css-hacks-for-windows-10-and-spartan-browser-preview/
Chrome has disabled it. https://bugs.chromium.org/p/chromium/issues/detail?id=159336 Even the jQuery play() is blocked. They want user to initiate it so bandwidth can be saved.
'Create a class to hold the pair...
Public Class ColumnValue
Public ColumnName As String
Public ColumnValue As New Object
End Class
'Build the pair...
For Each row In [YourDataTable].Rows
For Each item As DataColumn In row.Table.Columns
Dim rowValue As New ColumnValue
rowValue.ColumnName = item.Caption
rowValue.ColumnValue = row.item(item.Ordinal)
RowValues.Add(rowValue)
rowValue = Nothing
Next
' Now you can grab the value by the column name...
Dim results = (From p In RowValues Where p.ColumnName = "MyColumn" Select p.ColumnValue).FirstOrDefault
Next
For mass-delete by query you may use special delete by query API:
$ curl -XDELETE 'http://localhost:9200/twitter/tweet/_query' -d '{
"query" : {
"term" : { "user" : "kimchy" }
}
}
Who interesting it has long history.
I don't have a reference for it handy, but script tags are processed in order, and so if you put your $(document).ready(function1)
in a script tag after the script tags that define function1, etc., you should be good to go.
<script type='text/javascript' src='...'></script>
<script type='text/javascript' src='...'></script>
<script type='text/javascript'>
$(document).ready(function1);
</script>
Of course, another approach would be to ensure that you're using only one script tag, in total, by combining files as part of your build process. (Unless you're loading the other ones from a CDN somewhere.) That will also help improve the perceived speed of your page.
EDIT: Just realized that I didn't actually answer your question: I don't think there's a cross-browser event that's fired, no. There is if you work hard enough, see below. You can test for symbols and use setTimeout to reschedule:
<script type='text/javascript'>
function fireWhenReady() {
if (typeof function1 != 'undefined') {
function1();
}
else {
setTimeout(fireWhenReady, 100);
}
}
$(document).ready(fireWhenReady);
</script>
...but you shouldn't have to do that if you get your script tag order correct.
Update: You can get load notifications for script
elements you add to the page dynamically if you like. To get broad browser support, you have to do two different things, but as a combined technique this works:
function loadScript(path, callback) {
var done = false;
var scr = document.createElement('script');
scr.onload = handleLoad;
scr.onreadystatechange = handleReadyStateChange;
scr.onerror = handleError;
scr.src = path;
document.body.appendChild(scr);
function handleLoad() {
if (!done) {
done = true;
callback(path, "ok");
}
}
function handleReadyStateChange() {
var state;
if (!done) {
state = scr.readyState;
if (state === "complete") {
handleLoad();
}
}
}
function handleError() {
if (!done) {
done = true;
callback(path, "error");
}
}
}
In my experience, error notification (onerror
) is not 100% cross-browser reliable. Also note that some browsers will do both mechanisms, hence the done
variable to avoid duplicate notifications.
The code you provided would print the number of tabs, not the number of spaces. The below function should count the number of whitespace characters in a given string.
int countSpaces(String string) {
int spaces = 0;
for(int i = 0; i < string.length(); i++) {
spaces += (Character.isWhitespace(string.charAt(i))) ? 1 : 0;
}
return spaces;
}
sudo launchctl list | grep -i mysql
If the result shows anything like: "xxx.xxx.mysqlxxx"
sudo launchctl remove xxx.xxx.mysqlxxx
Example:
sudo launchctl remove org.macports.mysql56-server
sudo launchctl unload -wF /Library/LaunchDaemons/xxx.xxx.mysqlxxx.plist
Example:
sudo launchctl unload -wF /Library/LaunchDaemons/org.macports.mysql56-server.plist
Note: In some cases if you tried "a)" first, you need to reboot again before try b).
This will make the scroll bars always display when there is content within windows that must be scrolled to access, it applies to all windows and all apps on the Mac:
Launch System Preferences from the ? Apple menu Click on the “General” settings panel Look for ‘Show scroll bars’ and select the radiobox next to “Always” Close out of System Preferences when finished
Adding on to what Hubro said, apparently get_highest_row()
has been deprecated. Using the max_row
and max_column
properties returns the row and column count. For example:
wb = load_workbook(path, use_iterators=True)
sheet = wb.worksheets[0]
row_count = sheet.max_row
column_count = sheet.max_column
SELECT
Store_Name,
CASE Store_Name
WHEN 'Los Angeles' THEN Sales * 2
WHEN 'San Diego' THEN Sales * 1.5
ELSE Sales
END AS "New Sales",
Txn_Date
FROM Store_Information;
Try out this will solve ur problem ....
EditText etxt = (EditText)findviewbyid(R.id.etxt);
String str_value = etxt.getText().toString();
You are trying to run bash
, an interactive shell that requires a tty in order to operate. It doesn't really make sense to run this in "detached" mode with -d
, but you can do this by adding -it
to the command line, which ensures that the container has a valid tty associated with it and that stdin
remains connected:
docker run -it -d -p 52022:22 basickarl/docker-git-test
You would more commonly run some sort of long-lived non-interactive process (like sshd
, or a web server, or a database server, or a process manager like systemd
or supervisor
) when starting detached containers.
If you are trying to run a service like sshd
, you cannot simply run service ssh start
. This will -- depending on the distribution you're running inside your container -- do one of two things:
It will try to contact a process manager like systemd
or upstart
to start the service. Because there is no service manager running, this will fail.
It will actually start sshd
, but it will be started in the background. This means that (a) the service sshd start
command exits, which means that (b) Docker considers your container to have failed, so it cleans everything up.
If you want to run just ssh in a container, consider an example like this.
If you want to run sshd
and other processes inside the container, you will need to investigate some sort of process supervisor.
This is the way I am copying my arrays in Php:
function equal_array($arr){
$ArrayObject = new ArrayObject($arr);
return $ArrayObject->getArrayCopy();
}
$test = array("aa","bb",3);
$test2 = equal_array($test);
print_r($test2);
This outputs:
Array
(
[0] => aa
[1] => bb
[2] => 3
)
Encapsulation is what it sounds like, a way of putting a box around something to protect its contents. Abstraction is extracting the functional properties of something such that you can perform operations using only what you've extracted without knowledge of the inner workings.
When we say that two substances are liquids we are using "liquid" as an abstraction over the properties of those substances we're choosing to discuss. That abstraction tells us the things we can do with the substances given our previous experience with liquids.
Abstraction also doesn't really have anything to do with heirarchies. You can have another abstraction like "metals" that extracts properties of substances in a different way.
Abstractions forget details, so if you're using a particular abstraction you shouldn't ask about properties of the underlying substance that aren't granted by the abstraction. Like if you take milk and water and mix them together, you have a hard time then asking how much milk you have.
A Functor is an abstraction over something that has some notion of map, that is, you can run a function on its inner contents that transforms the inner bit into anything else. The outer something stays the same kind of thing.
Where this gets useful is that if you have a function that works on Lists and you realise you're only depending on the map interface, you can instead depend on Functor and then your function can work with streams, promises, maybes, tuples, and anything else that shares that abstraction.
Functional languages like Haskell have some really great powers of abstraction that make extreme code reuse practical.
Wikipedia's Switch statement entry is pretty big and actually pretty good. Interesting points:
For a strange and interesting optimization using a C switch see Duff's Device.
In case if < TEXT VIEW > is placed in LinearLayout, set the Layout_weight proprty of < and > to 0 and 1 for TextView.
In case of RelativeLayout align < and > to left and right and set "Layout to left of" and "Layout to right of" property of TextView to ids of < and >
so long as your html content doesn't need to contain a CDATA
element, you can contain the HTML in a CDATA
element, otherwise you'll have to escape the XML entities.
<element><![CDATA[<p>your html here</p>]]></element>
VS
<element><p>your html here</p></element>
INSERT INTO exampleTbl VALUES('he doesn''t work for me')
If you're adding a record through ASP.NET, you can use the SqlParameter object to pass in values so you don't have to worry about the apostrophe's that users enter in.
But the spring documentation says they are same.
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-introduction
In the first line "IoC is also known as dependency injection (DI)".
Workstation has some features that Player lacks, such as teams (groups of VMs connected by private LAN segments) and multi-level snapshot trees. It's aimed at power users and developers; they even have some hooks for using a debugger on the host to debug code in the VM (including kernel-level stuff). The core technology is the same, though.
Use the category below and then apply border from Quartz into your image:
[yourimage.layer setBorderColor:[[UIColor whiteColor] CGColor]];
[yourimage.layer setBorderWidth:2];
The category: UIImage+AutoScaleResize.h
#import <Foundation/Foundation.h>
@interface UIImage (AutoScaleResize)
- (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize;
@end
UIImage+AutoScaleResize.m
#import "UIImage+AutoScaleResize.h"
@implementation UIImage (AutoScaleResize)
- (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize
{
UIImage *sourceImage = self;
UIImage *newImage = nil;
CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;
CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;
CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
if (CGSizeEqualToSize(imageSize, targetSize) == NO)
{
CGFloat widthFactor = targetWidth / width;
CGFloat heightFactor = targetHeight / height;
if (widthFactor > heightFactor)
{
scaleFactor = widthFactor; // scale to fit height
}
else
{
scaleFactor = heightFactor; // scale to fit width
}
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;
// center the image
if (widthFactor > heightFactor)
{
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
}
else
{
if (widthFactor < heightFactor)
{
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
}
}
}
UIGraphicsBeginImageContext(targetSize); // this will crop
CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width = scaledWidth;
thumbnailRect.size.height = scaledHeight;
[sourceImage drawInRect:thumbnailRect];
newImage = UIGraphicsGetImageFromCurrentImageContext();
if(newImage == nil)
{
NSLog(@"could not scale image");
}
//pop the context to get back to the default
UIGraphicsEndImageContext();
return newImage;
}
@end
To get the output of ls
, use stdout=subprocess.PIPE
.
>>> proc = subprocess.Popen('ls', stdout=subprocess.PIPE)
>>> output = proc.stdout.read()
>>> print output
bar
baz
foo
The command cdrecord --help
outputs to stderr, so you need to pipe that indstead. You should also break up the command into a list of tokens as I've done below, or the alternative is to pass the shell=True
argument but this fires up a fully-blown shell which can be dangerous if you don't control the contents of the command string.
>>> proc = subprocess.Popen(['cdrecord', '--help'], stderr=subprocess.PIPE)
>>> output = proc.stderr.read()
>>> print output
Usage: wodim [options] track1...trackn
Options:
-version print version information and exit
dev=target SCSI target to use as CD/DVD-Recorder
gracetime=# set the grace time before starting to write to #.
...
If you have a command that outputs to both stdout and stderr and you want to merge them, you can do that by piping stderr to stdout and then catching stdout.
subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
As mentioned by Chris Morgan, you should be using proc.communicate()
instead of proc.read()
.
>>> proc = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> out, err = proc.communicate()
>>> print 'stdout:', out
stdout:
>>> print 'stderr:', err
stderr:Usage: wodim [options] track1...trackn
Options:
-version print version information and exit
dev=target SCSI target to use as CD/DVD-Recorder
gracetime=# set the grace time before starting to write to #.
...
Checkout this wiki, specifically the section Restrictions on valid host names
Hostnames are composed of series of labels concatenated with dots, as are all domain names. For example, "en.wikipedia.org" is a hostname. Each label must be between 1 and 63 characters long, and the entire hostname (including the delimiting dots but not a trailing dot) has a maximum of 253 ASCII characters.
The Internet standards (Requests for Comments) for protocols mandate that component hostname labels may contain only the ASCII letters 'a' through 'z' (in a case-insensitive manner), the digits '0' through '9', and the hyphen ('-'). The original specification of hostnames in RFC 952, mandated that labels could not start with a digit or with a hyphen, and must not end with a hyphen. However, a subsequent specification (RFC 1123) permitted hostname labels to start with digits. No other symbols, punctuation characters, or white space are permitted.
Why do you use new Date instead of a static UTC string?
function clearListCookies(){
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++){
var spcook = cookies[i].split("=");
document.cookie = spcook[0] + "=;expires=Thu, 21 Sep 1979 00:00:01 UTC;";
}
}
This is known as a fork bomb. It keeps splitting itself until there is no option but to restart the system. http://en.wikipedia.org/wiki/Fork_bomb
Django 1.11 delete all objects from a database table -
Entry.objects.all().delete() ## Entry being Model Name.
Refer the Official Django documentation here as quoted below - https://docs.djangoproject.com/en/1.11/topics/db/queries/#deleting-objects
Note that delete() is the only QuerySet method that is not exposed on a Manager itself. This is a safety mechanism to prevent you from accidentally requesting Entry.objects.delete(), and deleting all the entries. If you do want to delete all the objects, then you have to explicitly request a complete query set:
I myself tried the code snippet seen below within my somefilename.py
# for deleting model objects
from django.db import connection
def del_model_4(self):
with connection.schema_editor() as schema_editor:
schema_editor.delete_model(model_4)
and within my views.py
i have a view that simply renders a html page ...
def data_del_4(request):
obj = calc_2() ##
obj.del_model_4()
return render(request, 'dc_dash/data_del_4.html') ##
it ended deleting all entries from - model == model_4 , but now i get to see a Error screen within Admin console when i try to asceratin that all objects of model_4 have been deleted ...
ProgrammingError at /admin/dc_dash/model_4/
relation "dc_dash_model_4" does not exist
LINE 1: SELECT COUNT(*) AS "__count" FROM "dc_dash_model_4"
Do consider that - if we do not go to the ADMIN Console and try and see objects of the model - which have been already deleted - the Django app works just as intended.
You have some syntax issues with your script. Here is a fixed version:
#!/bin/bash
if [ "$seconds" -eq 0 ]; then
timezone_string="Z"
elif [ "$seconds" -gt 0 ]; then
timezone_string=$(printf "%02d:%02d" $((seconds/3600)) $(((seconds / 60) % 60)))
else
echo "Unknown parameter"
fi
There is a typo in your SQL. Fixed version is below:
SELECT GETVARIABLE('SYSIBM.VERSION') FROM SYSIBM.SYSDUMMY1;
I ran this on the IBM Mainframe under Z/OS in QMF and got the following results. We are currently running DB2 Version 8 and upgrading to Ver 10.
DSN08015 -- Format seems to be DSNVVMMM
-- PPP IS PRODUCT STRING 'DSN'
-- VV IS VERSION NUMBER E.G. 08
-- MMM IS MAINTENANCE LEVEL E.G. 015
What you're trying to do is to monitor the property of attribute in directive. You can watch the property of attribute changes using $observe() as follows:
angular.module('myApp').directive('conversation', function() {
return {
restrict: 'E',
replace: true,
compile: function(tElement, attr) {
attr.$observe('typeId', function(data) {
console.log("Updated data ", data);
}, true);
}
};
});
Keep in mind that I used the 'compile' function in the directive here because you haven't mentioned if you have any models and whether this is performance sensitive.
If you have models, you need to change the 'compile' function to 'link' or use 'controller' and to monitor the property of a model changes, you should use $watch(), and take of the angular {{}} brackets from the property, example:
<conversation style="height:300px" type="convo" type-id="some_prop"></conversation>
And in the directive:
angular.module('myApp').directive('conversation', function() {
return {
scope: {
typeId: '=',
},
link: function(scope, elm, attr) {
scope.$watch('typeId', function(newValue, oldValue) {
if (newValue !== oldValue) {
// You actions here
console.log("I got the new value! ", newValue);
}
}, true);
}
};
});
<script type="text/javascript" src="http://twitter.github.com/bootstrap/assets/js/bootstrap-dropdown.js"></script>
You may need to upgrade your mongo shell. I had version 2.4.9 of the mongo shell locally, and I got this error trying to connect to a mongo 3 database. Upgrading the shell version to 3 solved the problem.
You need to iterate through all the enum values in Animal and return the value that matches the description you need.
The response headers in case of cors remain hidden. You need to add in response headers to direct the Angular to expose headers to javascript.
// From server response headers :
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With,
Content-Type, Accept, Authorization, X-Custom-header");
header("Access-Control-Expose-Headers: X-Custom-header");
header("X-Custom-header: $some data");
var data = res.headers.get('X-Custom-header');
Try initializing your variables and use them in your connection object:
$username ="root";
$password = "password";
$host = "localhost";
$table = "shop";
$conn = new mysqli("$host", "$username", "$password", "$table");
While it's true that json
is a built-in module, I also found that on an Ubuntu system with python-minimal
installed, you DO have python
but you can't do import json
. And then I understand that you would try to install the module using pip!
If you have python-minimal
you'll get a version of python with less modules than when you'd typically compile python yourself, and one of the modules you'll be missing is the json
module. The solution is to install an additional package, called libpython2.7-stdlib
, to install all 'default' python libraries.
sudo apt install libpython2.7-stdlib
And then you can do import json
in python and it would work!
for each project in your solution make sure that
Properties > Config. Properties > General > Platform Toolset
is one for all of them, v100 for visual studio 2010, v110 for visual studio 2012
you also may be working on v100 from visual studio 2012
Create xml file like edit_text_design.xml and save it to your drawable folder
i have given the Color codes According to my Choice, Please Change Color Codes As per your Choice !
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape>
<solid android:color="#c2c2c2" />
</shape>
</item>
<!-- main color -->
<item
android:bottom="1.5dp"
android:left="1.5dp"
android:right="1.5dp">
<shape>
<solid android:color="#000" />
</shape>
</item>
<!-- draw another block to cut-off the left and right bars -->
<item android:bottom="5.0dp">
<shape>
<solid android:color="#000" />
</shape>
</item>
</layer-list>
your Edit Text Should contain it as Background :
add android:background="@drawable/edit_text_design" to all of your EditText's
and your above EditText should now look like this:
<EditText
android:id="@+id/name_edit_text"
android:background="@drawable/edit_text_design"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/profile_image_view_layout"
android:layout_centerHorizontal="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="20dp"
android:ems="15"
android:hint="@string/name_field"
android:inputType="text" />
Use DBNull.Value.Equals on the object without converting it to a string.
Here's an example:
if (! DBNull.Value.Equals(row[fieldName]))
{
//not null
}
else
{
//null
}
The function you're looking for is 'Insert'. It takes as its parameters the index you want to insert at, and an array of values to use for the new row values. Typical usage might include:
myDataGridView.Rows.Insert(4,new object[]{value1,value2,value3});
or something to that effect.
The code below will do the trick.
$('input[type=radio]').click(function() {_x000D_
if($(this).hasClass("checked")){_x000D_
this.checked = false;_x000D_
$(this).removeClass("checked")_x000D_
}else{_x000D_
$(this).addClass("checked")_x000D_
}_x000D_
});
_x000D_
It will kill not only all plot windows, but all processes that are called python3, except the current script you run. It works for python3. So, if you are running any other python3 script it will be terminated. As I only run one script at once, it does the job for me.
import os
import subprocess
subprocess.call(["bash","-c",'pyIDs=($(pgrep python3));for x in "${pyIDs[@]}"; do if [ "$x" -ne '+str(os.getpid())+' ];then kill -9 "$x"; fi done'])
To get all the elements starting with "jander" you should use:
$("[id^=jander]")
To get those that end with "jander"
$("[id$=jander]")
See also the JQuery documentation
The answer of George Bailey works fine. I would just add the following flags and use sudo if needed:
sudo rm -rf bin/node bin/node-waf include/node lib/node lib/pkgconfig/nodejs.pc share/man/man1/node
Try this one:
find . -type f -printf "%T@ %p\n" | sort -nr | cut -d\ -f2-
pip
/ conda
After extensively documenting a similar problem with Git (How can I make git accept a self signed certificate?), here we are again behind a corporate firewall with a proxy giving us a MitM "attack" that we should trust and:
NEVER disable all SSL verification!
This creates a bad security culture. Don't be that person.
pip config set global.cert path/to/ca-bundle.crt
pip config list
conda config --set ssl_verify path/to/ca-bundle.crt
conda config --show ssl_verify
# Bonus while we are here...
git config --global http.sslVerify true
git config --global http.sslCAInfo path/to/ca-bundle.crt
But where do we get ca-bundle.crt
?
cURL publishes an extract of the Certificate Authorities bundled with Mozilla Firefox
https://curl.haxx.se/docs/caextract.html
I recommend you open up this cacert.pem
file in a text editor as we will need to add our self-signed CA to this file.
Certificates are a document complying with X.509 but they can be encoded to disk a few ways. The below article is a good read but the short version is that we are dealing with the base64 encoding which is often called PEM in the file extensions. You will see it has the format:
----BEGIN CERTIFICATE----
....
base64 encoded binary data
....
----END CERTIFICATE----
Below are a few options on how to get our self signed certificate:
echo quit | openssl s_client -showcerts -servername "curl.haxx.se" -connect curl.haxx.se:443 > cacert.pem
Thanks to this answer and the linked blog, it shows steps (on Windows) how to view the certificate and then copy to file using the base64 PEM encoding option.
Copy the contents of this exported file and paste it at the end of your cacerts.pem
file.
For consistency rename this file cacerts.pem
--> ca-bundle.crt
and place it somewhere easy like:
# Windows
%USERPROFILE%\certs\ca-bundle.crt
# or *nix
$HOME/certs/cabundle.crt
Thanks to all the brilliant answers in:
How to get response SSL certificate from requests in python?
I have put together the following to attempt to take it a step further.
https://github.com/neozenith/get-ca-py
Set the configuration in pip and conda so that it knows where this CA store resides with our extra self-signed CA.
pip config set global.cert %USERPROFILE%\certs\ca-bundle.crt
conda config --set ssl_verify %USERPROFILE%\certs\ca-bundle.crt
OR
pip config set global.cert $HOME/certs/ca-bundle.crt
conda config --set ssl_verify $HOME/certs/ca-bundle.crt
THEN
pip config list
conda config --show ssl_verify
# Hot tip: use -v to show where your pip config file is...
pip config list -v
# Example output for macOS and homebrew installed python
For variant 'global', will try loading '/Library/Application Support/pip/pip.conf'
For variant 'user', will try loading '/Users/jpeak/.pip/pip.conf'
For variant 'user', will try loading '/Users/jpeak/.config/pip/pip.conf'
For variant 'site', will try loading '/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/pip.conf'
The accepted answer does not work in Jupyter (at least when using some libraries).
The Javascript solutions here only hide warnings that are already showing but not warnings that would be shown in the future.
To hide/unhide warnings in Jupyter and JupyterLab I wrote the following script that essentially toggles css to hide/unhide warnings.
%%javascript
(function(on) {
const e=$( "<a>Setup failed</a>" );
const ns="js_jupyter_suppress_warnings";
var cssrules=$("#"+ns);
if(!cssrules.length) cssrules = $("<style id='"+ns+"' type='text/css'>div.output_stderr { } </style>").appendTo("head");
e.click(function() {
var s='Showing';
cssrules.empty()
if(on) {
s='Hiding';
cssrules.append("div.output_stderr, div[data-mime-type*='.stderr'] { display:none; }");
}
e.text(s+' warnings (click to toggle)');
on=!on;
}).click();
$(element).append(e);
})(true);
I faced the same issue and I resolved it by using: max-width: fit-content;
Ideally your .gitignore
should prevent the untracked ( and ignored )files from being shown in status, added using git add
etc. So I would ask you to correct your .gitignore
You can do git add -u
so that it will stage the modified and deleted files.
You can also do git commit -a
to commit only the modified and deleted files.
Note that if you have Git of version before 2.0 and used git add .
, then you would need to use git add -u .
(See "Difference of “git add -A
” and “git add .
”").
I am going to answer my own question.
I added the following lines of code to my Makefile and it fixed the "clock skew" problem:
clean:
find . -type f | xargs touch
rm -rf $(OBJS)
Click on "Connect as" and select "specific user", then type in the credentials of your user (I used the admin of the server).
Because you are talking about your replacement being anything, and also replacing in the middle of an element's children, it becomes more tricky than just inserting a singular element, or directly removing and appending:
function replaceTargetWith( targetID, html ){
/// find our target
var i, tmp, elm, last, target = document.getElementById(targetID);
/// create a temporary div or tr (to support tds)
tmp = document.createElement(html.indexOf('<td')!=-1?'tr':'div'));
/// fill that div with our html, this generates our children
tmp.innerHTML = html;
/// step through the temporary div's children and insertBefore our target
i = tmp.childNodes.length;
/// the insertBefore method was more complicated than I first thought so I
/// have improved it. Have to be careful when dealing with child lists as
/// they are counted as live lists and so will update as and when you make
/// changes. This is why it is best to work backwards when moving children
/// around, and why I'm assigning the elements I'm working with to `elm`
/// and `last`
last = target;
while(i--){
target.parentNode.insertBefore((elm = tmp.childNodes[i]), last);
last = elm;
}
/// remove the target.
target.parentNode.removeChild(target);
}
example usage:
replaceTargetWith( 'idTABLE', 'I <b>can</b> be <div>anything</div>' );
demo:
By using the .innerHTML
of our temporary div this will generate the TextNodes
and Elements
we need to insert without any hard work. But rather than insert the temporary div itself -- this would give us mark up that we don't want -- we can just scan and insert it's children.
...either that or look to using jQuery and it's replaceWith
method.
jQuery('#idTABLE').replaceWith('<blink>Why this tag??</blink>');
As a response to EL 2002's comment above:
It not always possible. For example, when
createElement('div')
and set its innerHTML as<td>123</td>
, this div becomes<div>123</div>
(js throws away inappropriate td tag)
The above problem obviously negates my solution as well - I have updated my code above accordingly (at least for the td
issue). However for certain HTML this will occur no matter what you do. All user agents interpret HTML via their own parsing rules, but nearly all of them will attempt to auto-correct bad HTML. The only way to achieve exactly what you are talking about (in some of your examples) is to take the HTML out of the DOM entirely, and manipulate it as a string. This will be the only way to achieve a markup string with the following (jQuery will not get around this issue either):
<table><tr>123 text<td>END</td></tr></table>
If you then take this string an inject it into the DOM, depending on the browser you will get the following:
123 text<table><tr><td>END</td></tr></table>
<table><tr><td>END</td></tr></table>
The only question that remains is why you would want to achieve broken HTML in the first place? :)
Eventually found the FontForge Windows installer package and opened the PDF through the installed program. Worked a treat, so happy.
Once you've upgraded to PowerShell version 5 you can get the startup type.
To check the version of PowerShell you're running, use $PSVersionTable
.
The examples below are for the Windows Firewall Service:
For the local system
Get-Service | Select-Object -Property Name,Status,StartType | where-object {$_.Name -eq "MpsSvc"} | Format-Table -auto
For one remote system
Get-Service -ComputerName HOSTNAME_OF_SYSTEM | Select-Object -Property MachineName,Name,Status,StartType | where-object {$_.Name -eq "MpsSvc"} | Format-Table -auto
For multiple systems (must create the systems.txt)
Get-Service -ComputerName (Get-content c:\systems.txt) | Select-Object -Property MachineName,Name,Status,StartType | where-object {$_.Name -eq "MpsSvc"} | Format-Table -auto
Check this SharpDOM . This is a c# 4.0 internal dsl for generating html and also asp.net mvc view engine.
The 487 Response indicates that the previous request was terminated by user/application action. The most common occurrence is when the CANCEL happens as explained above. But it is also not limited to CANCEL. There are other cases where such responses can be relevant. So it depends on where you are seeing this behavior and whether its a user or application action that caused it.
15.1.2 UAS Behavior==> BYE Handling in RFC 3261
The UAS MUST still respond to any pending requests received for that dialog. It is RECOMMENDED that a 487 (Request Terminated) response be generated to those pending requests.
In my case, the service failed to start because I didn't set Platform='x64'
in the wix file.
I saw these errors in Event Viewer:
Service cannot be started.
System.BadImageFormatException: Could not load file or assembly 'SOME_LIBRARY_FILE, Version=5.0.0.0, Culture=neutral, PublicKeyToken=33345856ad364e35' or one of its dependencies.
I tried checking the bitness of all service related files using CorFlags.exe
. When I changed my installer to be 64 bit
, everything started working fine.
I had the same issue, for me this fixed the issue:
right click on the project ->maven -> update project
There are many ways of doing this (and I encourage you to look them up as they will be more efficient generally) but the simplest way of doing this is to use a non-set operation to define the value of the third column:
SELECT
t1.previous
,t1.present
,(t1.present - t1.previous) as difference
FROM #TEMP1 t1
Note, this style of selection is considered bad practice because it requires the query plan to reselect the value of the first two columns to logically determine the third (a violation of set theory that SQL is based on). Though it is more complicated, if you plan on using this to evaluate more than the values you listed in your example, I would investigate using an APPLY clause. http://technet.microsoft.com/en-us/library/ms175156(v=sql.105).aspx
Simpler way (if your only keyword is "code" ) may be:
string ErrorCode = yourString.Split(new string[]{"code"}, StringSplitOptions.None).Last();
db:create
- Creates the database for the current RAILS_ENV environment. If RAILS_ENV is not specified it defaults to the development and test databases.
db:create:all
- Creates the database for all environments.
db:drop
- Drops the database for the current RAILS_ENV environment. If RAILS_ENV is not specified it defaults to the development and test databases.
db:drop:all
- Drops the database for all environments.
db:migrate
- Runs migrations for the current environment that have not run yet. By default it will run migrations only in the development environment.
db:migrate:redo
- Runs db:migrate:down and db:migrate:up or db:migrate:rollback and db:migrate:up depending on the specified migration.
db:migrate:up
- Runs the up for the given migration VERSION.
db:migrate:down
- Runs the down for the given migration VERSION.
db:migrate:status
- Displays the current migration status.
db:migrate:rollback
- Rolls back the last migration.
db:version
- Prints the current schema version.
db:forward
- Pushes the schema to the next version.
db:seed
- Runs the db/seeds.rb file.
db:schema:load
Recreates the database from the schema.rb file. Deletes existing data.
db:schema:dump
Dumps the current environment’s schema to db/schema.rb.
db:structure:load
- Recreates the database from the structure.sql file.
db:structure:dump
- Dumps the current environment’s schema to db/structure.sql.
(You can specify another file with SCHEMA=db/my_structure.sql
)
db:setup
Runs db:create, db:schema:load and db:seed.
db:reset
Runs db:drop and db:setup.
db:migrate:reset
- Runs db:drop, db:create and db:migrate.
db:test:prepare
- Check for pending migrations and load the test schema. (If you run rake without any arguments it will do this by default.)
db:test:clone
- Recreate the test database from the current environment’s database schema.
db:test:clone_structure
- Similar to db:test:clone, but it will ensure that your test database has the same structure, including charsets and collations, as your current environment’s database.
db:environment:set
- Set the current RAILS_ENV environment in the ar_internal_metadata table. (Used as part of the protected environment check.)
db:check_protected_environments
- Checks if a destructive action can be performed in the current RAILS_ENV environment. Used internally when running a destructive action such as db:drop or db:schema:load.
Modulus, in modular arithmetic as you're referring, is the value left over or remaining value after arithmetic division. This is commonly known as remainder. % is formally the remainder operator in C / C++. Example:
7 % 3 = 1 // dividend % divisor = remainder
What's left for discussion is how to treat negative inputs to this % operation. Modern C and C++ produce a signed remainder value for this operation where the sign of the result always matches the dividend input without regard to the sign of the divisor input.
It defines an XML Namespace.
In your example, the Namespace Prefix is "android" and the Namespace URI is "http://schemas.android.com/apk/res/android"
In the document, you see elements like: <android:foo />
Think of the namespace prefix as a variable with a short name alias for the full namespace URI. It is the equivalent of writing <http://schemas.android.com/apk/res/android:foo />
with regards to what it "means" when an XML parser reads the document.
NOTE: You cannot actually use the full namespace URI in place of the namespace prefix in an XML instance document.
Check out this tutorial on namespaces: http://www.sitepoint.com/xml-namespaces-explained/
you could use setBackgroundResource()
instead i.e. relativeLayout.setBackgroundResource(R.drawable.back);
this works for me.
Well, your code is not reproducible so we will never know for sure, but this is what help('break')
says:
break breaks out of a for, while or repeat loop; control is transferred to the first statement outside the inner-most loop.
So yes, break
only breaks the current loop. You can also see it in action with e.g.:
for (i in 1:10)
{
for (j in 1:10)
{
for (k in 1:10)
{
cat(i," ",j," ",k,"\n")
if (k ==5) break
}
}
}
Most phone cameras are landscape, meaning if you take the photo in portrait, the resulting photos will be rotated 90 degrees. In this case, the camera software should populate the Exif data with the orientation that the photo should be viewed in.
Note that the below solution depends on the camera software/device manufacturer populating the Exif data, so it will work in most cases, but it is not a 100% reliable solution.
ExifInterface ei = new ExifInterface(photoPath);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
Bitmap rotatedBitmap = null;
switch(orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotatedBitmap = rotateImage(bitmap, 90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotatedBitmap = rotateImage(bitmap, 180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotatedBitmap = rotateImage(bitmap, 270);
break;
case ExifInterface.ORIENTATION_NORMAL:
default:
rotatedBitmap = bitmap;
}
Here is the rotateImage
method:
public static Bitmap rotateImage(Bitmap source, float angle) {
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(),
matrix, true);
}
You can use primefaces
library
<p:spacer width="10" />
First, I add the references to my Model, then I use them in my code. There are two references you should add:
using System.ServiceModel;
using System.Runtime.Serialization;
then, this problem was solved in my program. I hope this answer can help you. Thanks.
I'm not aware of anything like a single table that lets you compare all of them in at one glance (I'm not sure such a table would even be feasible).
Of course the ISO standard document enumerates the complexity requirements in detail, sometimes in various rather readable tables, other times in less readable bullet points for each specific method.
Also the STL library reference at http://www.cplusplus.com/reference/stl/ provides the complexity requirements where appropriate.
You can combine multiple conditions to avoid the situation:
CASE WHEN condition1 = true AND condition2 = true THEN calculation1
WHEN condition1 = true AND condition2 = false
ELSE 'what so ever' END,
In MongoDB To insert Json array data from file(from particular location from a system / pc) using mongo shell command. While executing below command, command should be in single line.
var file = cat('I:/data/db/card_type_authorization.json'); var o = JSON.parse(file); db.CARD_TYPE_AUTHORIZATION.insert(o);
JSON File: card_type_authorization.json
[{
"code": "visa",
"position": 1,
"description": "Visa",
"isVertualCard": false,
"comments": ""
},{
"code": "mastercard",
"position": 2,
"description": "Mastercard",
"isVertualCard": false,
"comments": ""
}]
You need to use the SQL Server dynamic SQL:
DECLARE @table NVARCHAR(128),
@sql NVARCHAR(MAX);
SET @table = N'tableName';
SET @sql = N'SELECT * FROM ' + @table;
Use EXEC to execute any SQL:
EXEC (@sql)
Use EXEC sp_executesql to execute any SQL:
EXEC sp_executesql @sql;
Use EXECUTE sp_executesql to execute any SQL:
EXECUTE sp_executesql @sql
Just create a new MFC C++ app. It's built in, pretty easy, and thousands of examples exist in the world...
Plus, you can design your dialog box right in Visual Studio, give them variable names, and 90% of the code is generated for you.
I too needed a rounded ImageView, I used the below code, you can modify it accordingly:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
public class RoundedImageView extends ImageView {
public RoundedImageView(Context context) {
super(context);
}
public RoundedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
if (getWidth() == 0 || getHeight() == 0) {
return;
}
Bitmap b = ((BitmapDrawable) drawable).getBitmap();
Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
int w = getWidth();
@SuppressWarnings("unused")
int h = getHeight();
Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
canvas.drawBitmap(roundBitmap, 0, 0, null);
}
public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
Bitmap sbmp;
if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
float factor = smallest / radius;
sbmp = Bitmap.createScaledBitmap(bmp,
(int) (bmp.getWidth() / factor),
(int) (bmp.getHeight() / factor), false);
} else {
sbmp = bmp;
}
Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final String color = "#BAB399";
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, radius, radius);
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor(color));
canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
radius / 2 + 0.1f, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(sbmp, rect, rect, paint);
return output;
}
}
You don't need the date
validator. It doesn't support dd/mm/yyyy format, and that's why you are getting "Please enter a valid date" message for input like 13/01/2014. You already have the dateITA
validator, which uses dd/mm/yyyy format as you need.
Just like the date
validator, your code for dateGreaterThan
and dateLessThan
calls new Date
for input string and has the same issue parsing dates. You can use a function like this to parse the date:
function parseDMY(value) {
var date = value.split("/");
var d = parseInt(date[0], 10),
m = parseInt(date[1], 10),
y = parseInt(date[2], 10);
return new Date(y, m - 1, d);
}
If I am not mistaken, it will be onunload event.
"Occurs when the application is about to be unloaded." - MSDN
If you're running your React Native app through Expo, upgrading React Native is liable to cause this error (as noted at https://github.com/expo/expo/issues/923).
If that's your scenario, your options are:
package.json
) to a version that is compatible with your React Native version (if one exists, which may not be the case - judging by the linked issue, I figure that Expo support trails React Native releases).You don't need an IIF() at all here. The comparisons return true or false anyway.
Also, since this row visibility is on a group row, make sure you use the same aggregate function on the fields as you use in the fields in the row. So if your group row shows sums, then you'd put this in the Hidden property.
=Sum(Fields!OpeningStock.Value) = 0 And
Sum(Fields!GrossDispatched.Value) = 0 And
Sum(Fields!TransferOutToMW.Value) = 0 And
Sum(Fields!TransferOutToDW.Value) = 0 And
Sum(Fields!TransferOutToOW.Value) = 0 And
Sum(Fields!NetDispatched.Value) = 0 And
Sum(Fields!QtySold.Value) = 0 And
Sum(Fields!StockAdjustment.Value) = 0 And
Sum(Fields!ClosingStock.Value) = 0
But with the above version, if one record has value 1 and one has value -1 and all others are zero then sum is also zero and the row could be hidden. If that's not what you want you could write a more complex expression:
=Sum(
IIF(
Fields!OpeningStock.Value=0 AND
Fields!GrossDispatched.Value=0 AND
Fields!TransferOutToMW.Value=0 AND
Fields!TransferOutToDW.Value=0 AND
Fields!TransferOutToOW.Value=0 AND
Fields!NetDispatched.Value=0 AND
Fields!QtySold.Value=0 AND
Fields!StockAdjustment.Value=0 AND
Fields!ClosingStock.Value=0,
0,
1
)
) = 0
This is essentially a fancy way of counting the number of rows in which any field is not zero. If every field is zero for every row in the group then the expression returns true and the row is hidden.
You could also use function exposed by the axes object of the scatter plot
scatter = plt.scatter(x, y)
ax = scatter.axes
ax.invert_xaxis()
ax.invert_yaxis()
<div id="image">Example to have Background Image</div>
We need to Add the below content in Style tag:
.image {
background-image: url('C:\Users\ajai\Desktop\10.jpg');
}
I actually have this working now in a branch in my Zend_Mobile tree: https://github.com/mwillbanks/Zend_Mobile/tree/feature/gcm
This will be released with ZF 1.12, however, it should give you some great examples on how to do this.
Here is a quick demo on how it would work....
<?php
require_once 'Zend/Mobile/Push/Gcm.php';
require_once 'Zend/Mobile/Push/Message/Gcm.php';
$message = new Zend_Mobile_Push_Message_Gcm();
$message->setId(time());
$message->addToken('ABCDEF0123456789');
$message->setData(array(
'foo' => 'bar',
'bar' => 'foo',
));
$gcm = new Zend_Mobile_Push_Gcm();
$gcm->setApiKey('MYAPIKEY');
$response = false;
try {
$response = $gcm->send($message);
} catch (Zend_Mobile_Push_Exception $e) {
// all other exceptions only require action to be sent or implementation of exponential backoff.
die($e->getMessage());
}
// handle all errors and registration_id's
foreach ($response->getResults() as $k => $v) {
if ($v['registration_id']) {
printf("%s has a new registration id of: %s\r\n", $k, $v['registration_id']);
}
if ($v['error']) {
printf("%s had an error of: %s\r\n", $k, $v['error']);
}
if ($v['message_id']) {
printf("%s was successfully sent the message, message id is: %s", $k, $v['message_id']);
}
}
File -> Export -> Web -> WAR file
OR in Kepler follow as shown below :
As has already been mentioned, you’d want to do a foreach with the key, and unset using the key – but note that mutating an array during iteration is in general a bad idea, though I’m not sure on PHP’s rules on this offhand.
You can use lamba function:
index = df.index[lambda x : for x in df.index() ]
print(index)
This works in IE9 (Compatibility View and Normal Mode), Firefox 17, and Chrome 23:
<table>
<tr>
<td style="background-image:url(untitled.png); background-position:right 0px; background-repeat:no-repeat;">
Hello World
</td>
</tr>
</table>
You can create a SUPERUSER
or promote USER
, so for your case
$ sudo -u postgres psql -c "ALTER USER myuser WITH SUPERUSER;"
or rollback
$ sudo -u postgres psql -c "ALTER USER myuser WITH NOSUPERUSER;"
To prevent a command from logging when you set password, insert a whitespace in front of it, but check that your system supports this option.
$ sudo -u postgres psql -c "CREATE USER my_user WITH PASSWORD 'my_pass';"
$ sudo -u postgres psql -c "CREATE USER my_user WITH SUPERUSER PASSWORD 'my_pass';"
Here is the code for the short version of if-then-else statement:
( [ $a -eq 1 ] || [ $b -eq 2 ] ) && echo "ok" || echo "nok"
Pay attention to the following:
||
and &&
operands inside if condition (i.e. between round parentheses) are logical operands (or/and)
||
and &&
operands outside if condition mean then/else
Practically the statement says:
if (a=1 or b=2) then "ok" else "nok"
You must set the height of the container explicitly
#container {
height:100%;
width:100%;
position:absolute;
}
Unlike in C# where you have the Array.IndexOf method, and JavaScript where you have the indexOf method, Java's API (the Array
and Arrays
classes in particular) have no such method.
This method indexOf (together with its complement lastIndexOf) is defined in the java.util.List interface. Note that indexOf and lastIndexOf are not overloaded and only take an Object as a parameter.
If your array is sorted, you are in luck because the Arrays class defines a series of overloads of the binarySearch method that will find the index of the element you are looking for with best possible performance (O(log n) instead of O(n), the latter being what you can expect from a sequential search done by indexOf). There are four considerations:
The array must be sorted either in natural order or in the order of a Comparator that you provide as an argument, or at the very least all elements that are "less than" the key must come before that element in the array and all elements that are "greater than" the key must come after that element in the array;
The test you normally do with indexOf to determine if a key is in the array (verify if the return value is not -1) does not hold with binarySearch. You need to verify that the return value is not less than zero since the value returned will indicate the key is not present but the index at which it would be expected if it did exist;
If your array contains multiple elements that are equal to the key, what you get from binarySearch is undefined; this is different from indexOf that will return the first occurrence and lastIndexOf that will return the last occurrence.
An array of booleans might appear to be sorted if it first contains all falses and then all trues, but this doesn't count. There is no override of the binarySearch method that accepts an array of booleans and you'll have to do something clever there if you want O(log n) performance when detecting where the first true appears in an array, for instance using an array of Booleans and the constants Boolean.FALSE and Boolean.TRUE.
If your array is not sorted and not primitive type, you can use List's indexOf and lastIndexOf methods by invoking the asList method of java.util.Arrays. This method will return an AbstractList interface wrapper around your array. It involves minimal overhead since it does not create a copy of the array. As mentioned, this method is not overloaded so this will only work on arrays of reference types.
If your array is not sorted and the type of the array is primitive, you are out of luck with the Java API. Write your own for loop, or your own static utility method, which will certainly have performance advantages over the asList approach that involves some overhead of an object instantiation. In case you're concerned that writing a brute force for loop that iterates over all of the elements of the array is not an elegant solution, accept that that is exactly what the Java API is doing when you call indexOf. You can make something like this:
public static int indexOfIntArray(int[] array, int key) {
int returnvalue = -1;
for (int i = 0; i < array.length; ++i) {
if (key == array[i]) {
returnvalue = i;
break;
}
}
return returnvalue;
}
If you want to avoid writing your own method here, consider using one from a development framework like Guava. There you can find an implementation of indexOf and lastIndexOf.
If you want the position relative to the document then:
$("#myTable").offset().top;
but often you will want the position relative to the closest positioned parent:
$("#myTable").position().top;
(Updated to include @Socowi's execellent speed improvement)
With any $SHELL
that supports it (dash/zsh/bash...):
find . -name "*.txt" -exec $SHELL -c '
for i in "$@" ; do
echo "$i"
done
' {} +
Done.
Original answer (shorter, but slower):
find . -name "*.txt" -exec $SHELL -c '
echo "$0"
' {} \;
For people looking at this today, I would recommend the Seaborn heatmap()
as documented here.
The example above would be done as follows:
import numpy as np
from pandas import DataFrame
import seaborn as sns
%matplotlib inline
Index= ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
Cols = ['A', 'B', 'C', 'D']
df = DataFrame(abs(np.random.randn(5, 4)), index=Index, columns=Cols)
sns.heatmap(df, annot=True)
Where %matplotlib
is an IPython magic function for those unfamiliar.
Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:
*** Phones:
*** Tablets:
Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.
window.location.href = window.location.href
adb shell am broadcast -a android.intent.action.xxx
Mention xxx as the action that you mentioned in the manifest file.
To pass info to a fragment , you setArguments when you create it, and you can retrieve this argument later on the method onCreate or onCreateView of your fragment.
On the newInstance function of your fragment you add the arguments you wanna send to it:
/**
* Create a new instance of DetailsFragment, initialized to
* show the text at 'index'.
*/
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
Then inside the fragment on the method onCreate
or onCreateView
you can retrieve the arguments like this:
Bundle args = getArguments();
int index = args.getInt("index", 0);
If you want now communicate from your fragment with your activity (sending or not data), you need to use interfaces. The way you can do this is explained really good in the documentation tutorial of communication between fragments. Because all fragments communicate between each other through the activity, in this tutorial you can see how you can send data from the actual fragment to his activity container to use this data on the activity or send it to another fragment that your activity contains.
Documentation tutorial:
http://developer.android.com/training/basics/fragments/communicating.html
It depends on the property type that you are parsing.
If the json property is a number (e.g. 5) you can cast to Long directly, so you could do:
(long) jsonObj.get("id") // with id = 5, cast `5` to long
After getting the long,you could cast again to int, resulting in:
(int) (long) jsonObj.get("id")
If the json property is a number with quotes (e.g. "5"), is is considered a string, and you need to do something similar to Integer.parseInt() or Long.parseLong();
Integer.parseInt(jsonObj.get("id")) // with id = "5", convert "5" to Long
The only issue is, if you sometimes receive id's a string or as a number (you cant predict your client's format or it does it interchangeably), you might get an exception, especially if you use parseInt/Long on a null json object.
If not using Java Generics, the best way to deal with these runtime exceptions that I use is:
if(jsonObj.get("id") == null) {
// do something here
}
int id;
try{
id = Integer.parseInt(jsonObj.get("id").toString());
} catch(NumberFormatException e) {
// handle here
}
You could also remove that first if and add the exception to the catch. Hope this helps.
Notice (aside from the encoding issue) that some of the more complicated code linked goes to the trouble of getting the "active" portion of the ByteBuffer in question (for example by using position and limit), rather than simply encoding all of the bytes in the entire backing array (as many of the examples in these answers do).
PHP:
<?php
$a = array(array(1,2,3,4),array(5,6,7,8),array(9,0,1,2),array(3,4,5,6));
$b = array(); //result
while(count($a)>0)
{
$b[count($a[0])-1][] = array_shift($a[0]);
if (count($a[0])==0)
{
array_shift($a);
}
}
From PHP5.6, Array transposition can be performed with a sleak array_map()
call. In other words, columns are converted to rows.
Code: (Demo)
$array = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 0, 1, 2],
[3, 4, 5, 6]
];
$transposed = array_map(null, ...$array);
$transposed:
[
[1, 5, 9, 3],
[2, 6, 0, 4],
[3, 7, 1, 5],
[4, 8, 2, 6]
]
Here are the basic instructions:-
%CATALINA_HOME%/conf/server.xml
).<Connector
.protocol="HTTP/1.1"
.connectionTimeout
value is set on the connector, it may need to be increased - e.g. from 20000 milliseconds (= 20 seconds) to 120000 milliseconds (= 2 minutes). If no connectionTimeout
property value is set on the connector, the default is 60 seconds - if this is insufficient, the property may need to be added.Using ElementTree
:
import xml.etree.ElementTree
# Open original file
et = xml.etree.ElementTree.parse('file.xml')
# Append new tag: <a x='1' y='abc'>body text</a>
new_tag = xml.etree.ElementTree.SubElement(et.getroot(), 'a')
new_tag.text = 'body text'
new_tag.attrib['x'] = '1' # must be str; cannot be an int
new_tag.attrib['y'] = 'abc'
# Write back to file
#et.write('file.xml')
et.write('file_new.xml')
note: output written to file_new.xml
for you to experiment, writing back to file.xml
will replace the old content.
IMPORTANT: the ElementTree library stores attributes in a dict, as such, the order in which these attributes are listed in the xml text will NOT be preserved. Instead, they will be output in alphabetical order. (also, comments are removed. I'm finding this rather annoying)
ie: the xml input text <b y='xxx' x='2'>some body</b>
will be output as <b x='2' y='xxx'>some body</b>
(after alphabetising the order parameters are defined)
This means when committing the original, and changed files to a revision control system (such as SVN, CSV, ClearCase, etc), a diff between the 2 files may not look pretty.
using namespace std;
// c++03
string s = "(555) 555-5555";
s.erase(remove_if(s.begin(), s.end(), not1(ptr_fun(::isdigit))), s.end());
// c++11
s.erase(remove_if(s.begin(), s.end(), ptr_fun(::ispunct)), s.end());
Note: It's posible you need write ptr_fun<int, int>
rather than simple ptr_fun
These solutions often have issues with the header columns aligning with the body columns, and may not work properly when resizing. I know you didn't want to use an additional library, but if you happen to be using jQuery, this one is really small. It supports fixed header, footer, column spanning (colspan), horizontal scrolling, resizing, and an optional number of rows to display before scrolling starts.
jQuery.scrollTableBody (GitHub)
As long as you have a table with proper <thead>
, <tbody>
, and (optional) <tfoot>
, all you need to do is this:
$('table').scrollTableBody();
You can create your own simple unsafe html binding, of course if you use user input it could be a security risk.
App.directive('simpleHtml', function() {
return function(scope, element, attr) {
scope.$watch(attr.simpleHtml, function (value) {
element.html(scope.$eval(attr.simpleHtml));
})
};
})
<input type="radio" name="gender" value="male"<%=rs.getString(6).equals("male") ? "checked='checked'": "" %>: "checked='checked'" %> >Male
<%=rs.getString(6).equals("male") ? "checked='checked'": "" %>
The new cv2
interface for Python integrates numpy arrays into the OpenCV framework, which makes operations much simpler as they are represented with simple multidimensional arrays. For example, your question would be answered with:
import cv2 # Not actually necessary if you just want to create an image.
import numpy as np
blank_image = np.zeros((height,width,3), np.uint8)
This initialises an RGB-image that is just black. Now, for example, if you wanted to set the left half of the image to blue and the right half to green , you could do so easily:
blank_image[:,0:width//2] = (255,0,0) # (B, G, R)
blank_image[:,width//2:width] = (0,255,0)
If you want to save yourself a lot of trouble in future, as well as having to ask questions such as this one, I would strongly recommend using the cv2
interface rather than the older cv
one. I made the change recently and have never looked back. You can read more about cv2
at the OpenCV Change Logs.
See the following snippet, is this what you want?
body {
background: silver;
padding: 0 10px;
}
#content:after {
height: 10px;
display: block;
width: 100px;
background: #808080;
border-right: 1px white;
content: '';
}
#footer:before {
display: block;
content: '';
background: silver;
height: 10px;
margin-top: -20px;
margin-left: 101px;
}
#content {
background: white;
}
#footer {
padding-top: 10px;
background: #404040;
}
p {
padding: 100px;
text-align: center;
}
#footer p {
color: white;
}
_x000D_
<body>
<div id="content"><p>#content</p></div>
<div id="footer"><p>#footer</p></div>
</body>
_x000D_
I was having issue with connecting to MS SQL 2005 using Windows Authentication. I was able to solve the issue with help from this and other forums. Here is what I did:
My environment: Windows XP clinet hosting Apache Tomcat 6 with MS SQL 2005 backend on Windows 2003
You can use a vector. Instead of worry about different screen sizes you only need to create an .svg file and import it to your project using Vector Asset Studio.
Currently AFAIK there is no easy way to do this as this information should be stored by index which private registry doesn't have. But depending on how you started registry you have 2 options:
docker diff <id_of_registry_container>
with this you should get info about changes in container fs. All pushed images should be somewhere in /tmp/registry/repositories/If you used "centos" as name it should be in /tmp/registry/repositories/library/centos. This folder will contain text files which describes image structure. Actual data is in /tmp/registry/images/.
Probably something like:
ArrayList<DataPoint> myList = new ArrayList<DataPoint>();
//Fill up myList with your Data Points
//Traversal
for(DataPoint myPoint : myList) {
if(myPoint.getName() != null && myPoint.getName().equals("Michael Hoffmann")) {
//Process data do whatever you want
System.out.println("Found it!");
}
}
Here is the complete step-by-step method that worked for me in order to update the LINQ to SQL dbml and associated files to include a new column that I added to one of the database tables.
You need to make the changes to your design surface as suggested by other above; however, you need to do some extra steps. These are the complete steps:
Drag your updated table from Server Explorer onto the design surface
Copy the new column from this "new" table to the "old" table (see M463 answer for details on this step)
Delete the "new" table that you just dragged over
Click and highlight the stored procedure, then delete it
Drag the new stored procedure and drop into place.
Delete the .designer.vb file in the code-behind of the .dbml (if you do not delete this, your code-behind containing the schema will not update even if you rebuild and the new table field will not be included)
Clean and Rebuild the solution (this will rebuild the .designer.vb file to include all the new changes!).
The six library helps with writing code that is compatible with both python 2.5+ and python 3. It has an iteritems method that will work in both python 2 and 3. Example:
import six
d = dict( foo=1, bar=2 )
for k, v in six.iteritems(d):
print(k, v)
You can also like this:
$ nvm alias default lts/fermium
GoalSeek will throw an "Invalid Reference" error if the GoalSeek cell contains a value rather than a formula or if the ChangingCell contains a formula instead of a value or nothing.
The GoalSeek cell must contain a formula that refers directly or indirectly to the ChangingCell; if the formula doesn't refer to the ChangingCell in some way, GoalSeek either may not converge to an answer or may produce a nonsensical answer.
I tested your code with a different GoalSeek formula than yours (I wasn't quite clear whether some of the terms referred to cells or values).
For the test, I set:
the GoalSeek cell H18 = (G18^3)+(3*G18^2)+6
the Goal cell H32 = 11
the ChangingCell G18 = 0
The code was:
Sub GSeek()
With Worksheets("Sheet1")
.Range("H18").GoalSeek _
Goal:=.Range("H32").Value, _
ChangingCell:=.Range("G18")
End With
End Sub
And the code produced the (correct) answer of 1.1038, the value of G18 at which the formula in H18 produces the value of 11, the goal I was seeking.
Regarding the answer from Michael Wyraz, where you use alt*DeploymentRepository
in your settings.xml
or command on the line, be careful if you are using version 3.0.0-M1 of the maven-deploy-plugin (which is the latest version at the time of writing), there is a bug in this version that could cause a server authentication issue.
A workaround is as follows. In the value:
releases::default::https://YOUR_NEXUS_URL/releases
you need to remove the default
section, making it:
releases::https://YOUR_NEXUS_URL/releases
The prior version 2.8.2 does not have this bug.
Add these helper classes to the stylesheet.less (you can use http://less2css.org/ to compile them to CSS )
.row.gutter-0 {
margin-left: 0;
margin-right: 0;
[class*="col-"] {
padding-left: 0;
padding-right: 0;
}
}
.row.gutter-10 {
margin-left: -5px;
margin-right: -5px;
[class*="col-"] {
padding-left: 5px;
padding-right: 5px;
}
}
.row.gutter-20 {
margin-left: -10px;
margin-right: -10px;
[class*="col-"] {
padding-left: 10px;
padding-right: 10px;
}
}
And here’s how you can use it in your HTML:
<div class="row gutter-0">
<div class="col-sm-3 col-md-3 col-lg-3">
</div>
<div class="col-sm-3 col-md-3 col-lg-3">
</div>
<div class="col-sm-3 col-md-3 col-lg-3">
</div>
<div class="col-sm-3 col-md-3 col-lg-3">
</div>
</div>
<div class="row gutter-10">
<div class="col-sm-3 col-md-3 col-lg-3">
</div>
<div class="col-sm-3 col-md-3 col-lg-3">
</div>
<div class="col-sm-3 col-md-3 col-lg-3">
</div>
<div class="col-sm-3 col-md-3 col-lg-3">
</div>
</div>
<div class="row gutter-20">
<div class="col-sm-3 col-md-3 col-lg-3">
</div>
<div class="col-sm-3 col-md-3 col-lg-3">
</div>
<div class="col-sm-3 col-md-3 col-lg-3">
</div>
<div class="col-sm-3 col-md-3 col-lg-3">
</div>
</div>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$table_name = "employee";
$backup_file = "/tmp/employee.sql";
$sql = "SELECT * INTO OUTFILE '$backup_file' FROM $table_name";
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not take data backup: ' . mysql_error());
}
echo "Backedup data successfully\n";
mysql_close($conn);
?>
Here is how you set the date and time:
update user set expiry_date=TO_DATE('31/DEC/2017 12:59:59', 'dd/mm/yyyy hh24:mi:ss') where id=123;
Just for completeness, let's not forget the Simplest Thing That Could Possibly Work:
for i in list:
if i.n == 5:
# do something with it
print "YAY! Found one!"
Change . to / as the path separator and use getResourceAsStream
:
reader = new BufferedReader(new InputStreamReader(
getClass().getClassLoader().getResourceAsStream(
"com/company/app/dao/sql/SqlQueryFile.sql")));
or
reader = new BufferedReader(new InputStreamReader(
getClass().getResourceAsStream(
"/com/company/app/dao/sql/SqlQueryFile.sql")));
Note the leading slash when using Class.getResourceAsStream()
vs ClassLoader.getResourceAsStream
.
getSystemResourceAsStream
uses the system classloader which isn't what you want.
I suspect that using slashes instead of dots would work for ClassPathResource
too.
Try in Swift, don't update the tintColor
if you have some design for your UIBarButtonItem like font size in AppDelegate, it will totally change the appearance of your button when showing up.
In case of a text button, changing title can let your button 'disappear'.
if WANT_TO_SHOW {
myBarButtonItem.enabled = true
myBarButtonItem.title = "BUTTON_NAME"
}else{
myBarButtonItem.enabled = false
myBarButtonItem.title = ""
}
Add my 5 cents) My question model
{
name: "what_is_it",
options:[
{
label: 'Option name',
value: '1'
},
{
label: 'Option name 2',
value: '2'
}
]
}
template.html
<div class="question" formGroupName="{{ question.name }}">
<div *ngFor="let opt of question.options; index as i" class="question__answer" >
<input
type="checkbox" id="{{question.name}}_{{i}}"
[name]="question.name" class="hidden question__input"
[value]="opt.value"
[formControlName]="opt.label"
>
<label for="{{question.name}}_{{i}}" class="question__label question__label_checkbox">
{{opt.label}}
</label>
</div>
component.ts
onSubmit() {
let formModel = {};
for (let key in this.form.value) {
if (typeof this.form.value[key] !== 'object') {
formModel[key] = this.form.value[key]
} else { //if formgroup item
formModel[key] = '';
for (let k in this.form.value[key]) {
if (this.form.value[key][k])
formModel[key] = formModel[key] + k + ';'; //create string with ';' separators like 'a;b;c'
}
}
}
console.log(formModel)
}
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"sms:number"]]
This would be the best and short way to do it.
Because this thread is the first thing that pops up when searching for the error mentioned I would like to add another possible cause for this error: you may have mod_evasive
active and the client seeing this error simply has crossed the limits configured in your mod_evasive.conf
This is especially a cause worth investigating if you are suddenly getting this error for a client that had no problems before and nothing else has changed.
(if mod_evasive
is the cause then the error will go away by itself if the client just temporarily stops trying to access the site; however it may be a sign that you have configured too tight limits)
move you mouse over the "Hello, playground" on the right side bar, you will see an eye icon and a small circle icon next it. Just click on the circle one to show the detail page and console output!
Pure Python2 w/o dep:
def relpath(cwd, path):
"""Create a relative path for path from cwd, if possible"""
if sys.platform == "win32":
cwd = cwd.lower()
path = path.lower()
_cwd = os.path.abspath(cwd).split(os.path.sep)
_path = os.path.abspath(path).split(os.path.sep)
eq_until_pos = None
for i in xrange(min(len(_cwd), len(_path))):
if _cwd[i] == _path[i]:
eq_until_pos = i
else:
break
if eq_until_pos is None:
return path
newpath = [".." for i in xrange(len(_cwd[eq_until_pos+1:]))]
newpath.extend(_path[eq_until_pos+1:])
return os.path.join(*newpath) if newpath else "."
Based on the work of Bas Brekelmans above, I have also created two derivations -> "input" dialogs that allow you to receive from the user both a text value and a boolean (TextBox and CheckBox):
public static class PromptForTextAndBoolean
{
public static string ShowDialog(string caption, string text, string boolStr)
{
Form prompt = new Form();
prompt.Width = 280;
prompt.Height = 160;
prompt.Text = caption;
Label textLabel = new Label() { Left = 16, Top = 20, Width = 240, Text = text };
TextBox textBox = new TextBox() { Left = 16, Top = 40, Width = 240, TabIndex = 0, TabStop = true };
CheckBox ckbx = new CheckBox() { Left = 16, Top = 60, Width = 240, Text = boolStr };
Button confirmation = new Button() { Text = "Okay!", Left = 16, Width = 80, Top = 88, TabIndex = 1, TabStop = true };
confirmation.Click += (sender, e) => { prompt.Close(); };
prompt.Controls.Add(textLabel);
prompt.Controls.Add(textBox);
prompt.Controls.Add(ckbx);
prompt.Controls.Add(confirmation);
prompt.AcceptButton = confirmation;
prompt.StartPosition = FormStartPosition.CenterScreen;
prompt.ShowDialog();
return string.Format("{0};{1}", textBox.Text, ckbx.Checked.ToString());
}
}
...and text along with a selection of one of multiple options (TextBox and ComboBox):
public static class PromptForTextAndSelection
{
public static string ShowDialog(string caption, string text, string selStr)
{
Form prompt = new Form();
prompt.Width = 280;
prompt.Height = 160;
prompt.Text = caption;
Label textLabel = new Label() { Left = 16, Top = 20, Width = 240, Text = text };
TextBox textBox = new TextBox() { Left = 16, Top = 40, Width = 240, TabIndex = 0, TabStop = true };
Label selLabel = new Label() { Left = 16, Top = 66, Width = 88, Text = selStr };
ComboBox cmbx = new ComboBox() { Left = 112, Top = 64, Width = 144 };
cmbx.Items.Add("Dark Grey");
cmbx.Items.Add("Orange");
cmbx.Items.Add("None");
Button confirmation = new Button() { Text = "In Ordnung!", Left = 16, Width = 80, Top = 88, TabIndex = 1, TabStop = true };
confirmation.Click += (sender, e) => { prompt.Close(); };
prompt.Controls.Add(textLabel);
prompt.Controls.Add(textBox);
prompt.Controls.Add(selLabel);
prompt.Controls.Add(cmbx);
prompt.Controls.Add(confirmation);
prompt.AcceptButton = confirmation;
prompt.StartPosition = FormStartPosition.CenterScreen;
prompt.ShowDialog();
return string.Format("{0};{1}", textBox.Text, cmbx.SelectedItem.ToString());
}
}
Both require the same usings:
using System;
using System.Windows.Forms;
Call them like so:
Call them like so:
PromptForTextAndBoolean.ShowDialog("Jazz", "What text should accompany the checkbox?", "Allow Scat Singing");
PromptForTextAndSelection.ShowDialog("Rock", "What should the name of the band be?", "Beret color to wear");
If you dont want to query for it just create an entity, and then delete it.
Customer customer = new Customer() { Id = 1 } ;
context.AttachTo("Customers", customer);
context.DeleteObject(customer);
context.Savechanges();
If you want to read CSV file with some lines, so this the solution.
while IFS=, read -ra line
do
test $i -eq 1 && ((i=i+1)) && continue
for col_val in ${line[@]}
do
echo -n "$col_val|"
done
echo
done < "$csvFile"
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script>
$(function() {
var people = [];
$.getJSON('people.json', function(data) {
$.each(data.person, function(i, f) {
var tblRow = "<tr>" + "<td>" + f.firstName + "</td>" +
"<td>" + f.lastName + "</td>" + "<td>" + f.job + "</td>" + "<td>" + f.roll + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
});
});
});
</script>
</head>
<body>
<div class="wrapper">
<div class="profile">
<table id= "userdata" border="2">
<thead>
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
<th>City</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</body>
</html>
My JSON
file:
{
"person": [
{
"firstName": "Clark",
"lastName": "Kent",
"job": "Reporter",
"roll": 20
},
{
"firstName": "Bruce",
"lastName": "Wayne",
"job": "Playboy",
"roll": 30
},
{
"firstName": "Peter",
"lastName": "Parker",
"job": "Photographer",
"roll": 40
}
]
}
I succeeded in integrating a JSON
file to HTML
table after working a day on it!!!
Referring to Spring Boot application as a Service as well, I would go for the systemd
version, since it's the easiest, least verbose, and best integrated into modern distros (and even the not-so-modern ones like CentOS 7.x).
I had this issue when trying to concatenate getdate()
into a string that I was inserting into an nvarchar field.
I did some casting to get around it:
INSERT INTO [SYSTEM_TABLE] ([SYSTEM_PROP_TAG],[SYSTEM_PROP_VAL]) VALUES
(
'EMAIL_HEADER',
'<h2>111 Any St.<br />Anywhere, ST 11111</h2><br />' +
CAST(CAST(getdate() AS datetime2) AS nvarchar) +
'<br /><br /><br />'
)
That's a sanitized example. The key portion of that is:
...' + CAST(CAST(getdate() AS datetime2) AS nvarchar) + '...
Casted the date as datetime2
, then as nvarchar
to concatenate it.
As explained here by Filip - http://www.filipekberg.se/2011/10/02/adding-properties-and-methods-to-an-expandoobject-dynamicly/
You can add a method too at runtime.
x.Add("Shout", new Action(() => { Console.WriteLine("Hellooo!!!"); }));
x.Shout();
This is how I achieved this. In Sileria answer he/she did the following:
ViewGroup.LayoutParams params = layout.getLayoutParams();
params.height = customHeight;
layout.requestLayout();
This is correct, but it expects us to give the height in pixels
, but I wanted to give the dp
I want the height to be so I added:
public int convertDpToPixelInt(float dp, Context context) {
return (int) (dp * (((float) context.getResources().getDisplayMetrics().densityDpi) / 160.0f));
}
So it will look like this:
ViewGroup.LayoutParams params = layout.getLayoutParams();
params.height = convertDpToPixelInt(50, getContext());
layout.requestLayout();
In my case it was because of function inside another function! once I moved out the function, error was gone , and everything worked as expected.
This answer explains why you shouldn't use function inside function.
This might help somebody.
Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.
git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67
Then, abort the rebase again.
You can use pathlib
. Unfortunately this is only available in the stdlib for Python 3.4. If you have an older version you'll have to install a copy from PyPI here. This should be easy to do using pip
.
from pathlib import Path
p = Path(__file__).parents[1]
print(p)
# /absolute/path/to/two/levels/up
This uses the parents
sequence which provides access to the parent directories and chooses the 2nd one up.
Note that p
in this case will be some form of Path
object, with their own methods. If you need the paths as string then you can call str
on them.
If macOS GUI applications are your bread and butter, SubEthaEdit is the text editor I usually go to for encoding-wrangling — its "conversion preview" allows you to see all invalid characters in the output encoding, and fix/remove them.
And it's open-source now, so yay for them .
HttpHandler Example,
HTTP Handler in ASP.NET 2.0
A handler is responsible for fulfilling requests from a browser. Requests that a browser manages are either handled by file extension or by calling the handler directly.The low level Request and Response API to service incoming Http requests are Http Handlers in Asp.Net. All handlers implement the IHttpHandler interface, which is located in the System.Web namespace. Handlers are somewhat analogous to Internet Server Application Programming Interface (ISAPI) extensions.
You implement the IHttpHandler interface to create a synchronous handler and the IHttpAsyncHandler interface to create an asynchronous handler. The interfaces require you to implement the ProcessRequest method and the IsReusable property. The ProcessRequest method handles the actual processing for requests made, while the Boolean IsReusable property specifies whether your handler can be pooled for reuse to increase performance or whether a new handler is required for each request.
The .ashx file extension is reserved for custom handlers. If you create a custom handler with a file name extension of .ashx, it will automatically be registered within IIS and ASP.NET. If you choose to use an alternate file extension, you will have to register the extension within IIS and ASP.NET. The advantage of using an extension other than .ashx is that you can assign multiple file extensions to one handler.
Configuring HTTP Handlers
The configuration section handler is responsible for mapping incoming URLs to the IHttpHandler or IHttpHandlerFactory class. It can be declared at the computer, site, or application level. Subdirectories inherit these settings. Administrators use the tag directive to configure the section. directives are interpreted and processed in a top-down sequential order. Use the following syntax for the section handler:
Creating HTTP Handlers
To create an HTTP handler, you must implement the IHttpHandler interface. The IHttpHandler interface has one method and one property with the following signatures: void ProcessRequest(HttpContext); bool IsReusable {get;}
your manifest application name should contain application class name. Like
<application
android:name="your package name.MyApplication"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:largeHeap="true"
android:theme="@style/AppTheme">
We can import single table using CMD as below:
D:\wamp\bin\mysql\mysql5.5.24\bin>mysql -h hostname -u username -p passowrd databasename < filepath
Even though the ID selector is the simplest, you can also use the name selector as below:
$('[name='submitted[first_name]']').removeAttr('required');
For more see: https://api.jquery.com/attribute-equals-selector/
You could opt for a pure CSS solution:
#hfont1 {
transition: color 1s ease-in-out;
-moz-transition: color 1s ease-in-out; /* FF 4 */
-webkit-transition: color 1s ease-in-out; /* Safari & Chrome */
-o-transition: color 1s ease-in-out; /* Opera */
}
When you populate your fields, you can check for the value:
<input type="radio" name="sex" value="Male" <?php echo ($sex=='Male')?'checked':'' ?>size="17">Male
<input type="radio" name="sex" value="Female" <?php echo ($sex=='Female')?'checked':'' ?> size="17">Female
Assuming that the value you return from your database is in the variable $sex
The checked property will preselect the value that match
Sybase has the same case syntax as SQL Server:
Supports conditional SQL expressions; can be used anywhere a value expression can be used.
case
when search_condition then expression
[when search_condition then expression]...
[else expression]
end
case expression
when expression then expression
[when expression then expression]...
[else expression]
end
begins the case expression.
precedes the search condition or the expression to be compared.
is used to set conditions for the results that are selected. Search conditions for case expressions are similar to the search conditions in a where clause. Search conditions are detailed in the Transact-SQL User’s Guide.
precedes the expression that specifies a result value of case.
is a column name, a constant, a function, a subquery, or any combination of column names, constants, and functions connected by arithmetic or bitwise operators. For more information about expressions, see “Expressions” in.
select disaster,
case
when disaster = "earthquake"
then "stand in doorway"
when disaster = "nuclear apocalypse"
then "hide in basement"
when monster = "zombie apocalypse"
then "hide with Chuck Norris"
else
then "ask mom"
end
from endoftheworld
Lambda can be any function. So if you had a function
def compare_person(a):
return a.age
You could sort a list of Person (each of which having an age attribute) like this:
sorted(personArray, key=compare_person)
This way, the list would be sorted by age in ascending order.
The parameter is called lambda because python has a nifty lambda keywords for defining such functions on the fly. Instead of defining a function compare_person and passing that to sorted, you can also write:
sorted(personArray, key=lambda a: a.age)
which does the same thing.
Dividing two integers will result in an integer (whole number) result.
You need to cast one number as a float, or add a decimal to one of the numbers, like a/350.0.
Compact form for short commands (no 'echo'):
IF "%ID%"=="0" ( ... & ... & ... ) ELSE ^
IF "%ID%"=="1" ( ... ) ELSE ^
IF "%ID%"=="2" ( ... ) ELSE ^
REM default case...
After ^
must be an immediate line end, no spaces.
Here are some differences between the two languages:
this
scope for non-static methods, and implicit class scope; JavaScript has implicit global scope.Here are some features that I think are particular strengths of JavaScript:
You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.
When using storageClass
Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.
storageClass
-line from the PersistentVolumeClaimAt creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.
The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.
The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound
"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.
A PersistentVolume without StorageClass is considered to be static.
"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.
In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:
apiVersion: v1
kind: PersistentVolume
metadata:
name: ckan-pv-home
labels:
type: local
spec:
capacity:
storage: 100Mi
hostPath:
path: "/mnt/data/ckan"
The PersistentVolumeSpec allows us to define multiple attributes.
I chose a hostPath
volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.
There are three options:
results = Model.objects.exclude(a=True).filter(x=5)
Use Q()
objects and the ~
operator
from django.db.models import Q
object_list = QuerySet.filter(~Q(a=True), x=5)
Register a custom lookup function
from django.db.models import Lookup
from django.db.models import Field
@Field.register_lookup
class NotEqual(Lookup):
lookup_name = 'ne'
def as_sql(self, compiler, connection):
lhs, lhs_params = self.process_lhs(compiler, connection)
rhs, rhs_params = self.process_rhs(compiler, connection)
params = lhs_params + rhs_params
return '%s <> %s' % (lhs, rhs), params
Which can the be used as usual:
results = Model.objects.exclude(a=True, x__ne=5)
A default value of 0 for arrays of integral types is guaranteed by the language spec:
Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10) [...] For type
int
, the default value is zero, that is,0
.
If you want to initialize an one-dimensional array to a different value, you can use java.util.Arrays.fill() (which will of course use a loop internally).
The following will return '0' if the string consists entirely of zeros:
CASE WHEN SUBSTRING(str_col, PATINDEX('%[^0]%', str_col+'.'), LEN(str_col)) = '' THEN '0' ELSE SUBSTRING(str_col, PATINDEX('%[^0]%', str_col+'.'), LEN(str_col)) END AS str_col
The files in your working copy might look exactly the same after, but they are still very different actions -- the repository is in a completely different state, and you will have different options available to you after reverting than "updating" to an old revision.
Briefly, "update to" only affects your working copy, but "reverse merge and commit" will affect the repository.
If you "update" to an old revision, then the repository has not changed: in your example, the HEAD revision is still 100. You don't have to commit anything, since you are just messing around with your working copy. If you make modifications to your working copy and try to commit, you will be told that your working copy is out-of-date, and you will need to update before you can commit. If someone else working on the same repository performs an "update", or if you check out a second working copy, it will be r100.
However, if you "reverse merge" to an old revision, then your working copy is still based on the HEAD (assuming you are up-to-date) -- but you are creating a new revision to supersede the unwanted changes. You have to commit these changes, since you are changing the repository. Once done, any updates or new working copies based on the HEAD will show r101, with the contents you just committed.
Try this
$date = Carbon::parse(date_format($youttimestring,'d/m/Y H:i:s'));
echo $date;
You need to include the protocol scheme:
'http://192.168.1.61:8080/api/call'
Without the http://
part, requests
has no idea how to connect to the remote server.
Note that the protocol scheme must be all lowercase; if your URL starts with HTTP://
for example, it won’t find the http://
connection adapter either.
You wont be able to access a local resource from your aspx page (web server). Have you tried a relative path from your aspx page to your css file like so...
<link rel="stylesheet" media="all" href="/CSS/Style.css" type="text/css" />
The above assumes that you have a folder called CSS
in the root of your website like this:
http://www.website.com/CSS/Style.css
Similar to what has already been said:
public String multStuff(String first, String toAdd, int amount) {
String append = "";
for (int i = 1; i <= amount; i++) {
append += toAdd;
}
return first + append;
}
Input multStuff("123", "0", 3);
Output "123000"
If you want movie details api you can consider
OMDB API which is Open movies Database Returns IBDB Rating, IMDB Votes and you can include Rotten Tomato rating too.
Or else You can use
My Api Films which allows you to search with IMDB ID and returns detailed information but it has request limits.
This should work...tested on a mac...
#include <stdio.h>
#include <sys/time.h>
int main() {
struct timeval tv;
struct timezone tz;
struct tm *tm;
gettimeofday(&tv,&tz);
tm=localtime(&tv.tv_sec);
printf("StartTime: %d:%02d:%02d %d \n", tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec);
}
Yeah...run it twice and subtract...
You could use a div
with a background image instead and this CSS3 property:
background-size: contain
You can check out an example on:
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Scaling_background_images#contain
To quote Mozilla:
The contain value specifies that regardless of the size of the containing box, the background image should be scaled so that each side is as large as possible while not exceeding the length of the corresponding side of the container.
However, keep in mind that your image will be upscaled if the div
is larger than your original image.
This is really a square peg, round hole question.
If relational databases and SQL are the only hammer you have or are willing to use, then the answers that have been posted thus far are adequate. However, why not use a tool designed to handle hierarchical data? Graph database are ideal for complex hierarchical data.
The inefficiencies of the relational model along with the complexities of any code/query solution to map a graph/hierarchical model onto a relational model is just not worth the effort when compared to the ease with which a graph database solution can solve the same problem.
Consider a Bill of Materials as a common hierarchical data structure.
class Component extends Vertex {
long assetId;
long partNumber;
long material;
long amount;
};
class PartOf extends Edge {
};
class AdjacentTo extends Edge {
};
Shortest path between two sub-assemblies: Simple graph traversal algorithm. Acceptable paths can be qualified based on criteria.
Similarity: What is the degree of similarity between two assemblies? Perform a traversal on both sub-trees computing the intersection and union of the two sub-trees. The percent similar is the intersection divided by the union.
Transitive Closure: Walk the sub-tree and sum up the field(s) of interest, e.g. "How much aluminum is in a sub-assembly?"
Yes, you can solve the problem with SQL and a relational database. However, there are much better approaches if you are willing to use the right tool for the job.
For quick readers:
Don’t ever use the types Number, String, Boolean, Symbol, or Object These types refer to non-primitive boxed objects that are almost never used appropriately in JavaScript code.
source: https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html
It works in Chrome 19.0.1084.41 beta!
So at some point in the future, keyframes could really be... frames!
You are living in the future ;)
It is all about the namespace
declaration. According to http://php.net/manual/en/language.namespaces.definition.php all namespace
declaration must be put on the very top of the file after the <?php
opening php tag. This means that before writing any code on the file, if that file needs to be contained in a namespace
then you must first declare the namespace
before writing any code. Like this:
<?php
namespace App\Suport\Facades;
class AuthUser {
// methods and more codes
}
BUT the declare
keyword can be put before the namespace
declaration so this is still valid:
<?php
declare(maxTries = 3);
namespace App\Suport\Facades;
class AuthUser {
// methods and more codes
}
all other stuff must be put AFTER the namespace
keyword. For more info, read the http://php.net/manual/en/language.namespaces.definition.php.
As Pablo said, you need to use find
instead of grep
, but there's no need to pipe find
to grep
. find
has that functionality built in:
find . -regex 'f[[:alnum:]]\.frm'
find
is a very powerful program for searching for files by name and supports searching by file type, depth limiting, combining different search terms with boolean operations, and executing arbitrary commands on found files. See the find man page for more information.
You are testing if the values of the variables error
and Already
are present in RepoOutput[RepoName.index(repo)]
. If these variables don't exist then an undefined object is used.
Both of your if
and elif
tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].
I think you wanted to test if certain strings are in the value instead:
{% if "error" in RepoOutput[RepoName.index(repo)] %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
<td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>
Other corrections I made:
{% elif ... %}
instead of {$ elif ... %}
.</tr>
tag out of the if
conditional structure, it needs to be there always.id
attributeNote that most likely you want to use a class
attribute instead here, not an id
, the latter must have a value that must be unique across your HTML document.
Personally, I'd set the class value here and reduce the duplication a little:
{% if "Already" in RepoOutput[RepoName.index(repo)] %}
{% set row_class = "good" %}
{% else %}
{% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>
You're passing the same model to the partial view as is being passed to the main view, and they are different types. The model is a DbSet
of Note
s, where you need to pass in a single Note
.
You can do this by adding a parameter, which I'm guessing as it's the create form would be a new Note
@Html.Partial("_CreateNote", new QuickNotes.Models.Note())
try this one
String fileSuffix = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
The argument passed to the callback is one of the elements of the array. The elements of your array are objects of the form {description: ..., id: ...}
.
var delete_id = _.result(_.find(savedViews, function(obj) {
return obj.description === view;
}), 'id');
Yet another alternative from the docs you linked to (lodash v3):
_.find(savedViews, 'description', view);
Lodash v4:
_.find(savedViews, ['description', view]);
This answer is over six years old. While the concepts and application of JSONP haven't changed (i.e. the details of the answer are still valid), you should look to use CORS where possible (i.e. your server or API supports it, and the browser support is adequate), as JSONP has inherent security risks.
JSONP (JSON with Padding) is a method commonly used to bypass the cross-domain policies in web browsers. (You are not allowed to make AJAX requests to a web page perceived to be on a different server by the browser.)
JSON and JSONP behave differently on the client and the server. JSONP requests are not dispatched using the XMLHTTPRequest
and the associated browser methods. Instead a <script>
tag is created, whose source is set to the target URL. This script tag is then added to the DOM (normally inside the <head>
element).
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// success
};
};
xhr.open("GET", "somewhere.php", true);
xhr.send();
var tag = document.createElement("script");
tag.src = 'somewhere_else.php?callback=foo';
document.getElementsByTagName("head")[0].appendChild(tag);
The difference between a JSON response and a JSONP response is that the JSONP response object is passed as an argument to a callback function.
{ "bar": "baz" }
foo( { "bar": "baz" } );
This is why you see JSONP requests containing the callback
parameter, so that the server knows the name of the function to wrap the response.
This function must exist in the global scope at the time the <script>
tag is evaluated by the browser (once the request has completed).
Another difference to be aware of between the handling of a JSON response and a JSONP response is that any parse errors in a JSON response could be caught by wrapping the attempt to evaluate the responseText in a try/catch statement. Because of the nature of a JSONP response, parse errors in the response will cause an uncatchable JavaScript parse error.
Both formats can implement timeout errors by setting a timeout before initiating the request and clearing the timeout in the response handler.
The usefulness of using jQuery to make JSONP requests, is that jQuery does all of the work for you in the background.
By default jQuery requires you to include &callback=?
in the URL of your AJAX request. jQuery will take the success
function you specify, assign it a unique name, and publish it in the global scope. It will then replace the question mark ?
in &callback=?
with the name it has assigned.
The following assumes a response object { "bar" : "baz" }
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("output").innerHTML = eval('(' + this.responseText + ')').bar;
};
};
xhr.open("GET", "somewhere.php", true);
xhr.send();
function foo(response) {
document.getElementById("output").innerHTML = response.bar;
};
var tag = document.createElement("script");
tag.src = 'somewhere_else.php?callback=foo';
document.getElementsByTagName("head")[0].appendChild(tag);
The split method of a string is what you need. In fact the tokenizer class in Java is deprecated in favor of Java's string split method.
Perhaps create a shared Fruit
interface that provides isDecayed. fruits
is now of type Fruit[]
so the type can be explicit. Like this:
interface Fruit {
isDecayed: boolean;
}
interface Apple extends Fruit {
color: string;
}
interface Pear extends Fruit {
weight: number;
}
interface FruitBasket {
apples: Apple[];
pears: Pear[];
}
const fruitBasket: FruitBasket = { apples: [], pears: [] };
const key: keyof FruitBasket = Math.random() > 0.5 ? 'apples': 'pears';
const fruits: Fruit[] = fruitBasket[key];
const freshFruits = fruits.filter((fruit) => !fruit.isDecayed);
You need to use LogLevel rewrite:trace3
to your httpd.conf
in newer version
http://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#logging
I can't pass up this opportunity to plug Josh Bloch's book Effective Java (2nd Edition). Chapter 11 is an indispensible resource on Java serialization.
Per Josh, the automatically-generated UID is generated based on a class name, implemented interfaces, and all public and protected members. Changing any of these in any way will change the serialVersionUID
. So you don't need to mess with them only if you are certain that no more than one version of the class will ever be serialized (either across processes or retrieved from storage at a later time).
If you ignore them for now, and find later that you need to change the class in some way but maintain compatibility w/ old version of the class, you can use the JDK tool serialver to generate the serialVersionUID
on the old class, and explicitly set that on the new class. (Depending on your changes you may need to also implement custom serialization by adding writeObject
and readObject
methods - see Serializable
javadoc or aforementioned chapter 11.)
in VB.net
My.Application.Info.DirectoryPath
works for me (Application Type: Class Library). Not sure about C#... Returns the path w/o Filename as string
SELECT t1.a, t2.b
FROM t1
JOIN t2 ON t1.a LIKE '%'+t2.b +'%'
because the last answer not work
Use pointers as your function parameters. Then use them to return multiple value.
The then()
method returns a Promise. It takes two arguments, both are callback functions for the success and failure cases of the Promise. the promise object itself doesn't give you the resolved data directly, the interface of this object only provides the data via callbacks supplied. So, you have to do this like this:
getFeed().then(function(data) { vm.feed = data;});
The then()
function returns the promise with a resolved value of the previous then()
callback, allowing you the pass the value to subsequent callbacks:
promiseB = promiseA.then(function(result) {
return result + 1;
});
// promiseB will be resolved immediately after promiseA is resolved
// and its value will be the result of promiseA incremented by 1
I once also faced such an issue where i needed to save data which was used by different collaborators and i ended up storing the time in unix timestamp form which represents the number of seconds since january 1970 which is an integer format.
Example todays date and time in tanzania is Friday, September 13, 2019 9:44:01 PM
which when store in unix timestamp would be 1568400241
Now when reading the data simply use something like php or any other language and extract the date from the unix timestamp. An example with php will be
echo date('m/d/Y', 1568400241);
This makes it easier even to store data with other collaborators in different locations. They can simply convert the date to unix timestamp with their own gmt offset and store it in a integer format and when outputting this simply convert with a
-Ldir
Add directory dir to the list of directories to be searched for -l.