Simply do this
var key = "keyOne";
var obj = {};
obj[key] = someValue;
exec does not execute a command in your shell
try
Process p = Runtime.getRuntime().exec(new String[]{"csh","-c","cat /home/narek/pk.txt"});
instead.
EDIT:: I don't have csh on my system so I used bash instead. The following worked for me
Process p = Runtime.getRuntime().exec(new String[]{"bash","-c","ls /home/XXX"});
Just change MAIL_ENCRYPTION=null to MAIL_ENCRYPTION=tls
And run this command "php artisan config:cache"
That is the standard way to swap two variables, yes.
Because the operating system may not do so. The flush operation forces the file data into the file cache in RAM, and from there it's the OS's job to actually send it to the disk.
I got confused by the answer to this question, so I created a test case in MySQL, hope this helps
-- Schema
CREATE TABLE T1 (
`ID` int not null auto_increment,
`Label` varchar(50),
primary key (`ID`)
);
CREATE TABLE T2 (
`ID` int not null auto_increment,
`Label` varchar(50),
primary key (`ID`)
);
CREATE TABLE TT (
`IDT1` int not null,
`IDT2` int not null,
primary key (`IDT1`,`IDT2`)
);
ALTER TABLE `TT`
ADD CONSTRAINT `fk_tt_t1` FOREIGN KEY (`IDT1`) REFERENCES `T1`(`ID`) ON DELETE CASCADE,
ADD CONSTRAINT `fk_tt_t2` FOREIGN KEY (`IDT2`) REFERENCES `T2`(`ID`) ON DELETE CASCADE;
-- Data
INSERT INTO `T1` (`Label`) VALUES ('T1V1'),('T1V2'),('T1V3'),('T1V4');
INSERT INTO `T2` (`Label`) VALUES ('T2V1'),('T2V2'),('T2V3'),('T2V4');
INSERT INTO `TT` (`IDT1`,`IDT2`) VALUES
(1,1),(1,2),(1,3),(1,4),
(2,1),(2,2),(2,3),(2,4),
(3,1),(3,2),(3,3),(3,4),
(4,1),(4,2),(4,3),(4,4);
-- Delete
DELETE FROM `T2` WHERE `ID`=4; -- Delete one field, all the associated fields on tt, will be deleted, no change in T1
TRUNCATE `T2`; -- Can't truncate a table with a referenced field
DELETE FROM `T2`; -- This will do the job, delete all fields from T2, and all associations from TT, no change in T1
To change your application to a different built-in theme, just add this line under application tag in your app's manifest.xml
file.
Example:
<application
android:theme="@android:style/Theme.Holo"/>
<application
android:theme="@android:style/Theme.Holo.Light"/>
<application
android:theme="@android:style/Theme.Black"/>
<application
android:theme="@android:style/Theme.DeviceDefault"/>
If you set style to DeviceDefault it will require min SDK version 14, but if you won't add a style, it will set to the device default anyway.
<uses-sdk
android:minSdkVersion="14"/>
Sets remove duplicate items. In order to do that, the item can't change while in the set. Lists can change after being created, and are termed 'mutable'. You cannot put mutable things in a set.
Lists have an unmutable equivalent, called a 'tuple'. This is how you would write a piece of code that took a list of lists, removed duplicate lists, then sorted it in reverse.
result = sorted(set(map(tuple, my_list)), reverse=True)
Additional note: If a tuple contains a list, the tuple is still considered mutable.
Some examples:
>>> hash( tuple() )
3527539
>>> hash( dict() )
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
hash( dict() )
TypeError: unhashable type: 'dict'
>>> hash( list() )
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
hash( list() )
TypeError: unhashable type: 'list'
I have Xcode 10.1 and I can not run my application on my device with 12.2 iOS version.
The easiest solution for me was:
If this trick does not working, you have to get the versions from the new Xcode version.
But you can try, saves a lot of time. Good luck!
EDIT: Or you can download your needed device support from here: https://github.com/iGhibli/iOS-DeviceSupport/tree/master/DeviceSupport
Something like this:
if($('#postageyes').is(':checked')) {
// do stuff
}
May be answer would depend on what problem you have with using iterator? may be use
i = 100
while i:
print i
i-=1
or
def loop(N, doSomething):
if not N:
return
print doSomething(N)
loop(N-1, doSomething)
loop(100, lambda a:a)
but frankly i see no point in using such approaches
See this fiddle for a preview and check the documentation for jquerys toggle and animate methods.
$('#toggle').toggle(function(){
$('#A').animate({width:0});
$('#B').animate({left:0});
},function(){
$('#A').animate({width:200});
$('#B').animate({left:200});
});
Basically you animate on the properties that sets the layout.
A more advanced version:
$('#toggle').toggle(function(){
$('#A').stop(true).animate({width:0});
$('#B').stop(true).animate({left:0});
},function(){
$('#A').stop(true).animate({width:200});
$('#B').stop(true).animate({left:200});
})
This stops the previous animation, clears animation queue and begins the new animation.
Checkout this, This is from PHP MANUAL, This may help you.
If you're using PHP_CLI SAPI and getting error "Maximum execution time of N seconds exceeded" where N is an integer value, try to call set_time_limit(0) every M seconds or every iteration. For example:
<?php
require_once('db.php');
$stmt = $db->query($sql);
while ($row = $stmt->fetchRow()) {
set_time_limit(0);
// your code here
}
?>
I just experienced this. I had read the suggestions on this page, as well as the SQL Authority suggestions (which is the same thing) and none of the above worked.
In the end, I removed the account and recreated (with the same username/password). Just like that, all the issues went away.
Sadly, this means I don't know what went wrong so I can't share any thing else.
Your call_python_file.php should look like this:
<?php
$item='Everything is awesome!!';
$tmp = exec("py.py $item");
echo $tmp;
?>
This executes the python script and outputs the result to the browser. While in your python script the (sys.argv[1:]) variable will bring in all your arguments. To display the argv as a string for wherever your php is pulling from so if you want to do a text area:
import sys
list1 = ' '.join(sys.argv[1:])
def main():
print list1
if __name__ == '__main__':
main()
In my EPiServer solution on several controllers there was a ContentOutputCache attribute on the Index action which accepted HttpGet. Each view for those actions contained a form which was posting to a HttpPost action to the same controller or to a different one. As soon as I removed that attribute from all of those Index actions problem was gone.
You can add leading zeroes to a variable (value up to 99) like this in batch:
IF 1%Var% LSS 100 SET Var=0%Var%
So you'd need to parse your date and time components out into separate variables, treat them all like this, then concatenate them back together to create the file name.
However, your underlying method for parsing date and time is dependent on system locale settings. If you're happy for your code not to be portable to other machines, that's probably fine, but if you expect it to work in different international contexts then you'll need a different approach, for example by reading out the registry settings:
HKEY_CURRENT_USER\Control Panel\International\iDate
HKEY_CURRENT_USER\Control Panel\International\iTime
HKEY_CURRENT_USER\Control Panel\International\iTLZero
(That last one controls whether there is a leading zero on times, but not dates as far as I know).
Strictly, method a
is the least resource intensive:
a) select DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)
Proven less CPU intensive for the same total duration a million rows by someone with way too much time on their hands: Most efficient way in SQL Server to get a date from date+time?
I saw a similar test elsewhere with similar results too.
I prefer the DATEADD/DATEDIFF because:
Edit, Oct 2011
For SQL Server 2008+, you can CAST to date
i.e. CAST(getdate() AS date)
. Or just use date
datatype so no time
to remove.
Edit, Jan 2012
A worked example of how flexible this is: Need to calculate by rounded time or date figure in sql server
Edit, May 2012
Do not use this in WHERE clauses and the like without thinking: adding a function or CAST to a column invalidates index usage. See number 2 here Common SQL Programming Mistakes
Now, this does have an example of later SQL Server optimiser versions managing CAST to date correctly, but generally it will be a bad idea ...
Edit, Sep 2018, for datetime2
DECLARE @datetime2value datetime2 = '02180912 11:45' --this is deliberately within datetime2, year 0218
DECLARE @datetime2epoch datetime2 = '19000101'
select DATEADD(dd, DATEDIFF(dd, @datetime2epoch, @datetime2value), @datetime2epoch)
I had the same problem, and finally I found that I forgot to add the selenium-server-standalone-version.jar. I had only added the client jar, selenium-java-version.jar.
Use unset
to delete the key Street
:
<?php
$arr1 = array("Name" => "Johm", "Street" => "Waall", "Country" => "India");
unset($arr1["Street"]);
?>
RESULT:
array("Name" => "Johm","Country" => "India")`
This will not re-index the array after deleting the value, so use array_splice();
NSURL.h provided - (BOOL)checkResourceIsReachableAndReturnError:(NSError **)error
to do so
NSURL *fileURL = [NSURL fileURLWithPath:NSHomeDirectory()];
NSError * __autoreleasing error = nil;
if ([fileURL checkResourceIsReachableAndReturnError:&error]) {
NSLog(@"%@ exists", fileURL);
} else {
NSLog(@"%@ existence checking error: %@", fileURL, error);
}
Or using Swift
if let url = URL(fileURLWithPath: NSHomeDirectory()) {
do {
let result = try url.checkResourceIsReachable()
} catch {
print(error)
}
}
You can use bellow code example for date string like mdate and Now() like toDay, you can also calculate deference between both date like Aging
Public Sub test(mdate As String)
Dim toDay As String
mdate = Round(CDbl(CDate(mdate)), 0)
toDay = Round(CDbl(Now()), 0)
Dim Aging as String
Aging = toDay - mdate
MsgBox ("So aging is -" & Aging & vbCr & "from the date - " & _
Format(mdate, "dd-mm-yyyy")) & " to " & Format(toDay, "dd-mm-yyyy"))
End Sub
NB: Used CDate
for convert Date String to Valid Date
I am using this in Office 2007 :)
I can't get that constructor to work either. This however seems to work:
# $temp = Get-ResourceFiles
$resourceFiles = New-Object System.Collections.ArrayList($null)
$resourceFiles.AddRange($temp)
You can also pass an integer in the constructor to set an initial capacity.
What do you mean when you say you want to enumerate the files? Why can't you just filter the wanted values into a fresh array?
Edit:
It seems that you can use the array constructor like this:
$resourceFiles = New-Object System.Collections.ArrayList(,$someArray)
Note the comma. I believe what is happening is that when you call a .NET method, you always pass parameters as an array. PowerShell unpacks that array and passes it to the method as separate parameters. In this case, we don't want PowerShell to unpack the array; we want to pass the array as a single unit. Now, the comma operator creates arrays. So PowerShell unpacks the array, then we create the array again with the comma operator. I think that is what is going on.
JTextField
allows us to getText()
and setText()
these are used to get and set the contents of the text field, for example.
text = texfield.getText();
hope this helps
how about trying this?
void CheckKey(void) {
int key;
if (kbhit()) {
key=getch();
if (key == 224) {
do {
key=getch();
} while(key==224);
switch (key) {
case 72:
printf("up");
break;
case 75:
printf("left");
break;
case 77:
printf("right");
break;
case 80:
printf("down");
break;
}
}
printf("%d\n",key);
}
int main() {
while (1) {
if (kbhit()) {
CheckKey();
}
}
}
(if you can't understand why there is 224, then try running this code: )
#include <stdio.h>
#include <conio.h>
int main() {
while (1) {
if (kbhit()) {
printf("%d\n",getch());
}
}
}
but I don't know why it's 224. can you write down a comment if you know why?
I also had the same error. In my case reason was I have created a update trigger on a table and under that trigger I am again updating the same table. And when I have removed the update statement from the trigger my problem has been resolved.
SELECT COUNT(*), table1.category_id, table2.category_name
FROM table1
INNER JOIN table2 ON table1.category_id=table2.category_id
WHERE table1.colour <> 'red'
GROUP BY table1.category_id, table2.category_name
Try to disable ModSecurity from your cPanel. Log into your cPanel. Find the category "Security". There you can find ModSecurity link.Click on it and disable it for the domain you are facing the 403 error.
Some 403 errors can be solved by this method too. Go to the wordpress dashboard, settings>permalink and just click save.
Hope this helped. :)
When you source, you're loading the activate script into your active shell.
When you do it in a script, you load it into that shell which exits when your script finishes and you're back to your original, unactivated shell.
Your best option would be to do it in a function
activate () {
. ../.env/bin/activate
}
or an alias
alias activate=". ../.env/bin/activate"
Hope this helps.
AHHH!!! This looks so wrong it hurts my head. Try something more like this...
<?php
include('db.php');
$result = mysql_query('SELECT `id`, `name`, `description`, `icon` FROM `staff` ORDER BY `id` DESC LIMIT 20') or die(mysql_error());
$rows = array();
while($row = mysql_fetch_assoc($result)){
$rows[] = $row;
}
echo json_encode($rows);
?>
mysql_num_rows
you should use <
not <=
. You should also cache this value (save it to a variable) instead of having it re-count every loop. Who knows what it's doing under the hood... (might be efficient, I'm not really sure)mysql_fetch_array
returns the values both by key
and by int
. You not using the indices, so don't fetch em.If this really is a problem with json_encode
, then might I suggest replacing the body of the loop with something like
$rows[] = array_map('htmlentities',$row);
Perhpas there are some special chars in there that are mucking things up...
Use this query:
SELECT User FROM mysql.user;
Which will output a table like this:
+-------+
| User |
+-------+
| root |
+-------+
| user2 |
+-------+
As Matthew Scharley points out in the comments on this answer, you can group by the User
column if you'd only like to see unique usernames.
This script outputs the number of unique values in each column of a given file. It assumes that first line of given file is header line. There is no need for defining number of fields. Simply save the script in a bash file (.sh) and provide the tab delimited file as a parameter to this script.
Code
#!/bin/bash
awk '
(NR==1){
for(fi=1; fi<=NF; fi++)
fname[fi]=$fi;
}
(NR!=1){
for(fi=1; fi<=NF; fi++)
arr[fname[fi]][$fi]++;
}
END{
for(fi=1; fi<=NF; fi++){
out=fname[fi];
for (item in arr[fname[fi]])
out=out"\t"item"_"arr[fname[fi]][item];
print(out);
}
}
' $1
Execution Example:
bash> ./script.sh <path to tab-delimited file>
Output Example
isRef A_15 C_42 G_24 T_18
isCar YEA_10 NO_40 NA_50
isTv FALSE_33 TRUE_66
Base href example
Say a typical page with links:
<a href=home>home</a> <a href=faq>faq</a> <a href=etc>etc</a>
.and links to a diff folder:
..<a href=../p2/home>Portal2home</a> <a href=../p2/faq>p2faq</a> <a href=../p2/etc>p2etc</a>..
With base href, we can avoid repeating the base folder:
<base href=../p2/>
<a href=home>Portal2-Home</a> <a href=faq>P2FAQ</a> <a href=contact>P2Contact</a>
So that's a win.. yet pages too-often contain urls to diff bases And the current web supports only one base href per page, so the win is quickly lost as bases that aint base∙hrefed repeats, eg:
<a href=../p1/home>home</a> <a href=../p1/faq>faq</a> <a href=../p1/etc>etc</a>
<!--.. <../p1/> basepath is repeated -->
<base href=../p2>
<a href=home>Portal2-Home</a> <a href=faq>P2FAQ</a> <a href=contact>P2Contact</a>
(Base target might be useful.) Base href is useless as:
Related
The best practice and Best OneLiner:
df.to_csv(newformat,header=1)
Notice the header value:
Header refer to the Row number(s) to use as the column names. Make no mistake, the row number is not the df but from the excel file(0 is the first row, 1 is the second and so on).
This way, you will get the column name you want and won't have to write additional codes or create new df.
Good thing is, it drops the replaced row.
try: typeof(predQuery[preId])=='undefined'
or more generally: typeof(yourArray[yourIndex])=='undefined'
You're comparing "undefined" to undefined, which returns false =)
shoud be @drawable/image where image could have any extension like: image.png, image.xml, image.gif. Android will automatically create a reference in R class with its name, so you cannot have in any drawable folder image.png and image.gif.
Your makefile should ideally be named makefile
, not make
. Note that you can call your makefile anything you like, but as you found, you then need the -f
option with make
to specify the name of the makefile. Using the default name of makefile
just makes life easier.
$("#element").validate().valid()
While you cannot record tests using the Selenium IDE in Chrome (or any other browser other than FF), you can run them (from the IDE) in Chrome, IE and other browsers using the Webdriver playback feature of Selenium 2 IDE. Tests will need to be recorded and launched from FF - Chrome will launch before the first step of the test is executed. Instructions for setup and test execution are here and here. You will need to install Selenium 2 IDE (if you haven't already done so) and the Chrome Webdriver Server executable - both are available for download on the Selenium HQ website.
NOTE: If the above meets your needs, you may also want to consider just converting all your tests to Selenium Webdriver (which means they would be all code and no longer run from the Selenium IDE). This would be a better solution from the perspective of test maintenance and simplicity of execution. The Selenium documentation (on the Selenium website) has more information on the process to convert Selenium IDE tests to Webdriver.
Depending on what you're doing in the loop, the fact that the %in%
operator returns a vector might be an issue; consider a simple example:
c1 <- c("one","two","three","more","more")
c2 <- c("seven","five","three")
if(c1%in%c2) {
print("hello")
}
then the following warning is issued:
Warning message:
In if (c1 %in% c2) { :
the condition has length > 1 and only the first element will be used
if something in your if statement is dependent on a specific number of elements, and they don't match, then it is possible to obtain the error you see
If by configure release/build, you mean you only need one config per makefile, then it is simply a matter and decoupling CC and CFLAGS:
CFLAGS=-DDEBUG
#CFLAGS=-O2 -DNDEBUG
CC=g++ -g3 -gdwarf2 $(CFLAGS)
Depending on whether you can use gnu makefile, you can use conditional to make this a bit fancier, and control it from the command line:
DEBUG ?= 1
ifeq ($(DEBUG), 1)
CFLAGS =-DDEBUG
else
CFLAGS=-DNDEBUG
endif
.o: .c
$(CC) -c $< -o $@ $(CFLAGS)
and then use:
make DEBUG=0
make DEBUG=1
If you need to control both configurations at the same time, I think it is better to have build directories, and one build directory / config.
Hint: break up the 32-bit integer to 4 8-bit integers, and print them out.
Something along the lines of this (not compiled, YMMV):
int i = 0xDEADBEEF; // some 32-bit integer
printf("%i.%i.%i.%i",
(i >> 24) & 0xFF,
(i >> 16) & 0xFF,
(i >> 8) & 0xFF,
i & 0xFF);
C++ sorting using sort function
#include <bits/stdc++.h>
using namespace std;
vector <int> v[100];
int main()
{
sort(v.begin(), v.end());
}
In my case for avoiding that problem:
Be sure that you are dealing with Xcode 7, NOT lower versions. In lower version this flag does not exist.
Setup: Project>Build Settings>All>Build Options>Enable Bitcode = NO
When I'm in my work place with terminal only, I use:
git log --oneline --graph --color --all --decorate
When the OS support GUI, I use:
gitk --all
When I'm in my home Windows PC, I use my own GitVersionTree
The .spec.ts files are for unit tests for individual components.
You can run Karma task runner through ng test
. In order to see code coverage of unit test cases for particular components run ng test --code-coverage
You should be able to access the local database by using the name localhost
. There is also a way to determine the hostname of the computer you're running on, but it doesn't sound like you need that. As for the username, you can either (1) give permissions to the account that PHP runs under to access the database without a password, or (2) store the username and password that you need to connect with (hard-coded or stored in a config file), and pass those as arguments to mysql_connect
. See http://php.net/manual/en/function.mysql-connect.php.
The documentation is not very clear about AngularJS routing. It talks about Hashbang and HTML5 mode. In fact, AngularJS routing operates in three modes:
For each mode there is a a respective LocationUrl class (LocationHashbangUrl, LocationUrl and LocationHashbangInHTML5Url).
In order to simulate URL rewriting you must actually set html5mode to true and decorate the $sniffer class as follows:
$provide.decorator('$sniffer', function($delegate) {
$delegate.history = false;
return $delegate;
});
I will now explain this in more detail:
Configuration:
$routeProvider
.when('/path', {
templateUrl: 'path.html',
});
$locationProvider
.html5Mode(false)
.hashPrefix('!');
This is the case when you need to use URLs with hashes in your HTML files such as in
<a href="index.html#!/path">link</a>
In the Browser you must use the following Link: http://www.example.com/base/index.html#!/base/path
As you can see in pure Hashbang mode all links in the HTML files must begin with the base such as "index.html#!".
Configuration:
$routeProvider
.when('/path', {
templateUrl: 'path.html',
});
$locationProvider
.html5Mode(true);
You should set the base in HTML-file
<html>
<head>
<base href="/">
</head>
</html>
In this mode you can use links without the # in HTML files
<a href="/path">link</a>
Link in Browser:
http://www.example.com/base/path
This mode is activated when we actually use HTML5 mode but in an incompatible browser. We can simulate this mode in a compatible browser by decorating the $sniffer service and setting history to false.
Configuration:
$provide.decorator('$sniffer', function($delegate) {
$delegate.history = false;
return $delegate;
});
$routeProvider
.when('/path', {
templateUrl: 'path.html',
});
$locationProvider
.html5Mode(true)
.hashPrefix('!');
Set the base in HTML-file:
<html>
<head>
<base href="/">
</head>
</html>
In this case the links can also be written without the hash in the HTML file
<a href="/path">link</a>
Link in Browser:
http://www.example.com/index.html#!/base/path
There isn't anything native to java that lets you do this like async/await keywords, but what you can do if you really want to is use a CountDownLatch. You could then imitate async/await by passing this around (at least in Java7). This is a common practice in Android unit testing where we have to make an async call (usually a runnable posted by a handler), and then await for the result (count down).
Using this however inside your application as opposed to your test is NOT what I am recommending. That would be extremely shoddy as CountDownLatch depends on you effectively counting down the right number of times and in the right places.
Your images are not centered because your list items are not centered; only their text is centered. You can achieve the positioning you want by either centering the entire list or centering the images within the list.
A revised version of your code can be found at the bottom. In my revision I center both the list and the images within it.
The truth is you cannot center an element that has a position set to absolute.
Note: These instructions will work with any DOM block element, not just img.
Surround your image with a div or other tag (in your case a li).
<div class="absolute-div">
<img alt="my-image" src="#">
</div>
Note: The names given to these elements are not special.
Alter your css or scss to give the div absolute positioning and your image centered.
.absolute-div {
position: absolute;
width: 100%;
// Range to be centered over.
// If this element's parent is the body then 100% = the window's width
// Note: You can apply additional top/bottom and left/right attributes
// i.e. - top: 200px; left: 200px;
// Test for desired positioning.
}
.absolute-div img {
width: 500px;
// Note: Setting a width is crucial for margin: auto to work.
margin: 0 auto;
}
Try this out:
body_x000D_
{_x000D_
text-align : center;_x000D_
}_x000D_
_x000D_
#slideshow_x000D_
{_x000D_
list-style : none;_x000D_
width : 800px;_x000D_
// alter to taste_x000D_
_x000D_
margin : 50px auto 0;_x000D_
}_x000D_
_x000D_
#slideshow li_x000D_
{_x000D_
position : absolute;_x000D_
}_x000D_
_x000D_
#slideshow img_x000D_
{_x000D_
border : 1px solid #CCC;_x000D_
padding : 4px;_x000D_
height : 500px;_x000D_
width : auto;_x000D_
// This sets the width relative to your set height._x000D_
_x000D_
// Setting a width is required for the margin auto attribute below. _x000D_
_x000D_
margin : 0 auto;_x000D_
}
_x000D_
<ul id="slideshow">_x000D_
<li><img src="http://lorempixel.com/500/500/nature/" alt="Dummy 1" /></li>_x000D_
<li><img src="http://lorempixel.com/500/500/nature/" alt="Dummy 2" /></li>_x000D_
</ul>
_x000D_
I hope this was helpful. Good luck!
With Java 8 you can use stream
and collect
to copy the items:
Set<Item> newSet = oldSet.stream().collect(Collectors.toSet());
Or you can collect to an ImmutableSet
(if you know that the set should not change):
Set<Item> newSet = oldSet.stream().collect(ImmutableSet.toImmutableSet());
A regular for each will do:
foreach (var item in collection)
{
// do your stuff
}
What does your text file look like?? Each line a record?
You'll have to check out the BULK INSERT statement - that should look something like:
BULK INSERT dbo.YourTableName
FROM 'D:\directory\YourFileName.csv'
WITH
(
CODEPAGE = '1252',
FIELDTERMINATOR = ';',
CHECK_CONSTRAINTS
)
Here, in my case, I'm importing a CSV file - but you should be able to import a text file just as well.
From the MSDN docs - here's a sample that hopefully works for a text file with one field per row:
BULK INSERT dbo.temp
FROM 'c:\temp\file.txt'
WITH
(
ROWTERMINATOR ='\n'
)
Seems to work just fine in my test environment :-)
You can use the call
command...
Type: call /?
Usage: call [drive:][path]filename [batch-parameters]
For example call "Example File/Input File/My Program.bat"
[This is also capable with calling files that have a .exe, .cmd, .txt, etc.
NOTE: THIS COMMAND DOES NOT ALWAYS WORK!!!
Not all computers are capable to run this command, but if it does work than it is very useful, and you won't have to open a brand new window...
import pandas as pd
print(pd.json_normalize(your_json))
This will Normalize semi-structured JSON data into a flat table
Output
FirstName LastName MiddleName password username
John Mark Lewis 2910 johnlewis2
The easy way is to define a non-ASCII character... as a character that is not an ASCII character.
LC_ALL=C grep '[^ -~]' file.xml
Add a tab after the ^
if necessary.
Setting LC_COLLATE=C
avoids nasty surprises about the meaning of character ranges in many locales. Setting LC_CTYPE=C
is necessary to match single-byte characters — otherwise the command would miss invalid byte sequences in the current encoding. Setting LC_ALL=C
avoids locale-dependent effects altogether.
Try below code:
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));// set transparent in window background
View _v = inflater.inflate(R.layout.some_you_layout, container, false);
//load animation
//Animation transition_in_view = AnimationUtils.loadAnimation(getContext(), android.R.anim.fade_in);// system animation appearance
Animation transition_in_view = AnimationUtils.loadAnimation(getContext(), R.anim.customer_anim);//customer animation appearance
_v.setAnimation( transition_in_view );
_v.startAnimation( transition_in_view );
//really beautiful
return _v;
}
Create the custom Anim.: res/anim/customer_anim.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="500"
android:fromYDelta="100%"
android:toYDelta="-7%"/>
<translate
android:duration="300"
android:startOffset="500"
android:toYDelta="7%" />
<translate
android:duration="200"
android:startOffset="800"
android:toYDelta="0%" />
</set>
From my recent experience, JsonReader#setLenient
basically makes the parser very tolerant, even to allow malformed JSON data.
But for certain data retrieved from your trusted RESTful API(s), this error might be caused by trailing white spaces. In such cases, simply trim
the data would avoid the error:
String trimmed = result1.trim();
Then gson.fromJson(trimmed, T)
might work. Surely this only covers a special case, so YMMV.
For is()
import static org.hamcrest.CoreMatchers.*;
For assertThat()
import static org.junit.Assert.*;
For when() and verify()
import static org.mockito.Mockito.*;
try setting this
CATALINA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8
-server -Xms1536m -Xmx1536m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"
in {$tomcat-folder}\bin\setenv.sh
(create it if necessary).
See http://www.mkyong.com/tomcat/tomcat-javalangoutofmemoryerror-permgen-space/ for more details.
server {
server_name xyz.com;
root /home/ubuntu/project_folder/;
client_max_body_size 10M;
access_log /var/log/nginx/project.access.log;
error_log /var/log/nginx/project.error.log;
location /static {
index index.html;
}
location /media {
alias /home/ubuntu/project/media/;
}
}
Server block to live the static page on nginx.
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
in /etc/my.cnf
add this lines:
[client]
socket=/var/lib/mysql/mysql.sock <= this path should be also same as is[mysqld]
And restart the service with:
service mysql restart
this worked for me
You already got a good formal answer. I figured I should add a short one.
The following things are identical with Promises/A+ promises:
Promise.resolve
(In your Angular case that's $q.when
)new $q
.then
callback. So the following are all identical for a promise or plain value X:
Promise.resolve(x);
new Promise(function(resolve, reject){ resolve(x); });
Promise.resolve().then(function(){ return x; });
Promise.all([x]).then(function(arr){ return arr[0]; });
And it's no surprise, the promises specification is based on the Promise Resolution Procedure which enables easy interoperation between libraries (like $q and native promises) and makes your life overall easier. Whenever a promise resolution might occur a resolution occurs creating overall consistency.
Below command is working for me. Which is working with variables
sed -i "/\<$E\>/c $D" "$B"
Within Nano use Ctrl+O to save and Ctrl+X to exit if you were wondering
Update: For people that still come across this, Postman is your best bet now: https://www.getpostman.com/apps
RestClient is my favorite. It's Java based. I think it should meet your needs quite nicely. I particularly like the Auth suppport.
From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i
Make sure to double up the @@ if you are using MVC Razor:
/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i
Hungry for spaghetti?
myImg.Source = new BitmapImage(new Uri(@"component/Images/down.png", UriKind.RelativeOrAbsolute));
Don't forget to set Build Action to "Content", and Copy to output directory to "Always".
For MacOS Maveriks (10.9 and perhaps later versions too), Apache Ant does not come bundled with the operating system and so must be installed manually. You can use brew to easily install ant. Simply execute the following command in a terminal window to install brew:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
It's a medium sized download which took me 10min to download and install. Just follow the process which involves installing various components. If you already have brew installed, make sure it's up to date by executing:
brew update
Once installed you can simply type:
brew install ant
Ant is now installed and available through the "ant" command in the terminal.
To test the installation, just type "ant -version
" into a terminal window. You should get the following output:
Apache Ant(TM) version X.X.X compiled on MONTH DAY YEAR
If you are getting errors installing Brew, try uninstalling first using the command:
rm -rf /usr/local/Cellar /usr/local/.git && brew cleanup
Thanks to OrangeDog and other users for providing additional information.
So as another answer mentioned Guava has support for this by using:
Streams.stream(iterable);
I want to highlight that the implementation does something slightly different than other answers suggested. If the Iterable
is of type Collection
they cast it.
public static <T> Stream<T> stream(Iterable<T> iterable) {
return (iterable instanceof Collection)
? ((Collection<T>) iterable).stream()
: StreamSupport.stream(iterable.spliterator(), false);
}
public static <T> Stream<T> stream(Iterator<T> iterator) {
return StreamSupport.stream(
Spliterators.spliteratorUnknownSize(iterator, 0),
false
);
}
You have to specify the projectBaseDir
if the module name doesn't match you module directory.
Since both your module are located in ".", you can simply add the following to your sonar-project properties:
module1.sonar.projectBaseDir=.
module2.sonar.projectBaseDir=.
Sonar will handle your modules as components of the project:
EDIT
If both of your modules are located in the same source directory, define the same source folder for both and exclude the unwanted packages with sonar.exclusions
:
module1.sonar.sources=src/main/java
module1.sonar.exclusions=app2code/**/*
module2.sonar.sources=src/main/java
module2.sonar.exclusions=app1code/**/*
According to CodeGuru:
CString
to std::string
:
CString cs("Hello");
std::string s((LPCTSTR)cs);
BUT: std::string
cannot always construct from a LPCTSTR
. i.e. the code will fail for UNICODE builds.
As std::string
can construct only from LPSTR
/ LPCSTR
, a programmer who uses VC++ 7.x or better can utilize conversion classes such as CT2CA
as an intermediary.
CString cs ("Hello");
// Convert a TCHAR string to a LPCSTR
CT2CA pszConvertedAnsiString (cs);
// construct a std::string using the LPCSTR input
std::string strStd (pszConvertedAnsiString);
std::string
to CString
: (From Visual Studio's CString FAQs...)
std::string s("Hello");
CString cs(s.c_str());
CStringT
can construct from both character or wide-character strings. i.e. It can convert from char*
(i.e. LPSTR
) or from wchar_t*
(LPWSTR
).
In other words, char-specialization (of CStringT
) i.e. CStringA
, wchar_t
-specilization CStringW
, and TCHAR
-specialization CString
can be constructed from either char
or wide-character, null terminated (null-termination is very important here) string sources.
Althoug IInspectable amends the "null-termination" part in the comments:
NUL-termination is not required.
CStringT
has conversion constructors that take an explicit length argument. This also means that you can constructCStringT
objects fromstd::string
objects with embeddedNUL
characters.
it works for me fine, if you a have string, then simply explode it first.
$emails = array();
Mail::send('emails.maintenance',$mail_params, function($message) use ($emails) {
foreach ($emails as $email) {
$message->to($email);
}
$message->subject('My Email');
});
You should set both your table encoding and connection encoding to UTF-8
:
ALTER TABLE keywords CHARACTER SET UTF8; -- run once
and
SET NAMES 'UTF8';
SET CHARACTER SET 'UTF8';
I recommend use boolean;
. You have to install the boolean module from cpan though.
Swift 5
It´s simple, the order of the properties is everything.
titleLabel.frame = CGRect(x: 20, y: 20, width: 374, height: 291.2)
titleLabel.backgroundColor = UIColor.clear //set a light color to see the frame
titleLabel.textAlignment = .left
titleLabel.lineBreakMode = .byTruncatingTail
titleLabel.numberOfLines = 4
titleLabel.font = UIFont(name: "HelveticaNeue-Bold", size: 35)
titleLabel.text = "Example"
titleLabel.sizeToFit()
self.view.addSubview(titleLabel)
All procedure at once. Based on @Till Schäfer answer.
In KB...
jstat -gc $(ps axf | egrep -i "*/bin/java *" | egrep -v grep | awk '{print $1}') | tail -n 1 | awk '{split($0,a," "); sum=(a[3]+a[4]+a[6]+a[8]+a[10]); printf("%.2f KB\n",sum)}'
In MB...
jstat -gc $(ps axf | egrep -i "*/bin/java *" | egrep -v grep | awk '{print $1}') | tail -n 1 | awk '{split($0,a," "); sum=(a[3]+a[4]+a[6]+a[8]+a[10])/1024; printf("%.2f MB\n",sum)}'
"Awk sum" reference:
a[1] - S0C
a[2] - S1C
a[3] - S0U
a[4] - S1U
a[5] - EC
a[6] - EU
a[7] - OC
a[8] - OU
a[9] - PC
a[10] - PU
a[11] - YGC
a[12] - YGCT
a[13] - FGC
a[14] - FGCT
a[15] - GCT
Used for "Awk sum":
a[3] -- (S0U) Survivor space 0 utilization (KB).
a[4] -- (S1U) Survivor space 1 utilization (KB).
a[6] -- (EU) Eden space utilization (KB).
a[8] -- (OU) Old space utilization (KB).
a[10] - (PU) Permanent space utilization (KB).
[Ref.: https://docs.oracle.com/javase/7/docs/technotes/tools/share/jstat.html ]
Thanks!
NOTE: Works to OpenJDK!
FURTHER QUESTION: Wrong information?
If you check memory usage with the ps
command, you will see that the java process consumes much more...
ps -eo size,pid,user,command --sort -size | egrep -i "*/bin/java *" | egrep -v grep | awk '{ hr=$1/1024 ; printf("%.2f MB ",hr) } { for ( x=4 ; x<=NF ; x++ ) { printf("%s ",$x) } print "" }' | cut -d "" -f2 | cut -d "-" -f1
UPDATE (2021-02-16):
According to the reference below (and @Till Schäfer comment) "ps can show total reserved memory from OS" (adapted) and "jstat can show used space of heap and stack" (adapted). So, we see a difference between what is pointed out by the ps
command and the jstat
command.
According to our understanding, the most "realistic" information would be the ps
output since we will have an effective response of how much of the system's memory is compromised. The command jstat
serves for a more detailed analysis regarding the java performance in the consumption of reserved memory from OS.
[Ref.: http://www.openkb.info/2014/06/how-to-check-java-memory-usage.html ]
None of these answers achieved what I was looking for, so I wound up writing something myself. I wanted to pinch-zoom an image on my website using my MacBookPro trackpad. The following code (which requires jQuery) seems to work in Chrome and Edge, at least. Maybe this will be of use to someone else.
function setupImageEnlargement(el)
{
// "el" represents the image element, such as the results of document.getElementByd('image-id')
var img = $(el);
$(window, 'html', 'body').bind('scroll touchmove mousewheel', function(e)
{
//TODO: need to limit this to when the mouse is over the image in question
//TODO: behavior not the same in Safari and FF, but seems to work in Edge and Chrome
if (typeof e.originalEvent != 'undefined' && e.originalEvent != null
&& e.originalEvent.wheelDelta != 'undefined' && e.originalEvent.wheelDelta != null)
{
e.preventDefault();
e.stopPropagation();
console.log(e);
if (e.originalEvent.wheelDelta > 0)
{
// zooming
var newW = 1.1 * parseFloat(img.width());
var newH = 1.1 * parseFloat(img.height());
if (newW < el.naturalWidth && newH < el.naturalHeight)
{
// Go ahead and zoom the image
//console.log('zooming the image');
img.css(
{
"width": newW + 'px',
"height": newH + 'px',
"max-width": newW + 'px',
"max-height": newH + 'px'
});
}
else
{
// Make image as big as it gets
//console.log('making it as big as it gets');
img.css(
{
"width": el.naturalWidth + 'px',
"height": el.naturalHeight + 'px',
"max-width": el.naturalWidth + 'px',
"max-height": el.naturalHeight + 'px'
});
}
}
else if (e.originalEvent.wheelDelta < 0)
{
// shrinking
var newW = 0.9 * parseFloat(img.width());
var newH = 0.9 * parseFloat(img.height());
//TODO: I had added these data-attributes to the image onload.
// They represent the original width and height of the image on the screen.
// If your image is normally 100% width, you may need to change these values on resize.
var origW = parseFloat(img.attr('data-startwidth'));
var origH = parseFloat(img.attr('data-startheight'));
if (newW > origW && newH > origH)
{
// Go ahead and shrink the image
//console.log('shrinking the image');
img.css(
{
"width": newW + 'px',
"height": newH + 'px',
"max-width": newW + 'px',
"max-height": newH + 'px'
});
}
else
{
// Make image as small as it gets
//console.log('making it as small as it gets');
// This restores the image to its original size. You may want
//to do this differently, like by removing the css instead of defining it.
img.css(
{
"width": origW + 'px',
"height": origH + 'px',
"max-width": origW + 'px',
"max-height": origH + 'px'
});
}
}
}
});
}
You may have imported,
project/controllers/base
inside the
project/controllers/routes
You have already imported before. That's not supported.
You can use the getDeclaredConstructor
method of Class. It expects an array of classes. Here is a tested and working example:
public static JFrame createJFrame(Class c, String name, Component parentComponent)
{
try
{
JFrame frame = (JFrame)c.getDeclaredConstructor(new Class[] {String.class}).newInstance("name");
if (parentComponent != null)
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
else
{
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
frame.setLocationRelativeTo(parentComponent);
frame.pack();
frame.setVisible(true);
}
catch (InstantiationException instantiationException)
{
ExceptionHandler.handleException(instantiationException, parentComponent, Language.messages.get(Language.InstantiationExceptionKey), c.getName());
}
catch(NoSuchMethodException noSuchMethodException)
{
//ExceptionHandler.handleException(noSuchMethodException, parentComponent, Language.NoSuchMethodExceptionKey, "NamedConstructor");
ExceptionHandler.handleException(noSuchMethodException, parentComponent, Language.messages.get(Language.NoSuchMethodExceptionKey), "(Constructor or a JFrame method)");
}
catch (IllegalAccessException illegalAccessException)
{
ExceptionHandler.handleException(illegalAccessException, parentComponent, Language.messages.get(Language.IllegalAccessExceptionKey));
}
catch (InvocationTargetException invocationTargetException)
{
ExceptionHandler.handleException(invocationTargetException, parentComponent, Language.messages.get(Language.InvocationTargetExceptionKey));
}
finally
{
return null;
}
}
Although this thread dates back to 2014, the issue can still be current to many of us. Here is how I dealt with it in a jQuery 1.12 /PHP 5.6 context:
PHP Code sample:
if (!empty($_SERVER['HTTP_ORIGIN'])) {
// Uh oh, this XHR comes from outer space...
// Use this opportunity to filter out referers that shouldn't be allowed to see this request
if (!preg_match('@\.partner\.domain\.net$@'))
die("End of the road if you're not my business partner.");
// otherwise oblige
header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
}
else {
// local request, no need to send a specific header for CORS
}
In particular, don't add an exit;
as no preflight is needed.
You have a type-o:
its: height: 200x;
and it should be: height: 200px;
also check the image url; it should be in the same directory it seems.
Also, dont use 'px' at null (aka '0') values. 0px, 0em, 0% is still 0. :)
top: 0px;
is the same with:
top: 0;
Good Luck!
I think this should be much easier to use:
select ISNULL(sum(field),0) from tablename
Copied from: http://www.codeproject.com/Questions/736515/How-do-I-avoide-Conversion-from-type-DBNull-to-typ
Yes, what you are asking for is called AJAX or XMLHttpRequest. You can either use a library like jQuery to simplify making the call (due to cross-browser compatibility issues), or write your own handler.
In jQuery:
$.GET('url.asp', {data: 'here'}, function(data){ /* what to do with the data returned */ })
In plain vanilla javaScript (from w3c):
var xmlhttp;
function loadXMLDoc(url)
{
xmlhttp=null;
if (window.XMLHttpRequest)
{// code for all new browsers
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE5 and IE6
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp!=null)
{
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
else
{
alert("Your browser does not support XMLHTTP.");
}
}
function state_Change()
{
if (xmlhttp.readyState==4)
{// 4 = "loaded"
if (xmlhttp.status==200)
{// 200 = OK
//xmlhttp.data and shtuff
// ...our code here...
}
else
{
alert("Problem retrieving data");
}
}
}
From Wikipedia:
HTTP is a stateless protocol. A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests.
But some web applications may have to track the user's progress from page to page, for example when a web server is required to customize the content of a web page for a user. Solutions for these cases include:
- the use of HTTP cookies.
- server side sessions,
- hidden variables (when the current page contains a form), and
- URL-rewriting using URI-encoded parameters, e.g., /index.php?session_id=some_unique_session_code.
What makes the protocol stateless is that the server is not required to track state over multiple requests, not that it cannot do so if it wants to. This simplifies the contract between client and server, and in many cases (for instance serving up static data over a CDN) minimizes the amount of data that needs to be transferred. If servers were required to maintain the state of clients' visits the structure of issuing and responding to requests would be more complex. As it is, the simplicity of the model is one of its greatest features.
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textD_Author"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Author : "
android:textColor="#0404B4"
android:textSize="20sp" />
<TextView
android:id="@+id/textD_Tag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Edition : "
android:textColor="#0404B4"
android:textSize="20sp" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:weightSum="1" >
<Button
android:id="@+id/btbEdit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="Edit" />
<Button
android:id="@+id/btnDelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="Delete" />
</LinearLayout>
</LinearLayout>
The zip()
function in Python 3 returns an iterator. That is the reason why when you print test1
you get - <zip object at 0x1007a06c8>
. From documentation -
Make an iterator that aggregates elements from each of the iterables.
But once you do - list(test1)
- you have exhausted the iterator. So after that anytime you do list(test1)
would only result in empty list.
In case of test2
, you have already created the list once, test2
is a list, and hence it will always be that list.
You could use the built-in exec statement, eg.:
exec("try: \n \t if sam[0] != 'harry': \n \t\t print('hello', sam) \nexcept: pass")
Where \n
is a newline and \t
is used as indentation (a tab).
Also, you should count the spaces you use, so your indentation matches exactly.
However, as all the other answers already said, this is of course only to be used when you really have to put it on one line.
exec
is quite a dangerous statement (especially when building a webapp) since it allows execution of arbitrary Python code.
Despite the fact that this is a very old question and probably many of the beforementioned ideas solved many problems, I still want to share the solution with the community that fixed my problem.
I found that the problem was a function called "hasItem" which I was using to check whether or not a JSON-Array contains a specific item. In my case I checked for a value of type Long.
And this led to the problem.
Somehow, the Matchers have problems with values of type Long. (I do not use JUnit or Rest-Assured so much so idk. exactly why, but I guess that the returned JSON-data does just contain Integers.)
So what I did to actually fix the problem was the following. Instead of using:
long ID = ...;
...
.then().assertThat()
.body("myArray", hasItem(ID));
you just have to cast to Integer. So the working code looked like this:
long ID = ...;
...
.then().assertThat()
.body("myArray", hasItem((int) ID));
That's probably not the best solution, but I just wanted to mention that the exception can also be thrown because of wrong/unknown data types.
There are two possibilities, both from Quest Software, TOAD & SQL Navigator:
Here is the TOAD Freeware download: http://www.toadworld.com/Downloads/FreewareandTrials/ToadforOracleFreeware/tabid/558/Default.aspx
And the SQL Navigator (trial version): http://www.quest.com/sql-navigator/software-downloads.aspx
Since git 2.13, it is possible to solve this using newly introduced Conditional includes.
An example:
Global config ~/.gitconfig
[user]
name = John Doe
email = [email protected]
[includeIf "gitdir:~/work/"]
path = ~/work/.gitconfig
Work specific config ~/work/.gitconfig
[user]
email = [email protected]
If you want to have a different icon for each list-item, I suggest adding icons in HTML instead of using a pseudo element to keep your CSS down. It can be done quite simply as follows:
<ul>
<li><span><i class="mdi mdi-lightbulb-outline"></i></span>An electric light with a wire filament heated to such a high temperature that it glows with visible light</li>
<li><span><i class="mdi mdi-clipboard-check-outline"></i></span>A thin, rigid board with a clip at the top for holding paper in place.</li>
<li><span><i class="mdi mdi-finance"></i></span>A graphical representation of data, in which the data is represented by symbols, such as bars in a bar chart, lines in a line chart, or slices in a pie chart.</li>
<li><span><i class="mdi mdi-server"></i></span>A system that responds to requests across a computer network worldwide to provide, or help to provide, a network or data service.</li>
</ul>
-
ul {
list-style-type: none;
margin-left: 2.5em;
padding-left: 0;
}
ul>li {
position: relative;
}
span {
left: -2em;
position: absolute;
text-align: center;
width: 2em;
line-height: inherit;
}
In this case I used Material Design Icons
Related to @Steven Penny's answer, I also use wget. Furthermore, to decide which file to send the output to I use -O .
If you are using gitlabs another possibility for the url is:
wget "https://git.labs.your-server/your-repo/raw/master/<path-to-file>" -O <output-file>
Unless you have the certificate or you access from a trusted server for the gitlabs installation you need --no-check-certificate as @Kos said. I prefer that rather than modifying .wgetrc but it depends on your needs.
If it is a big file you might consider using -c option with wget. To be able to continue downloading the file from where you left it if the previous intent failed in the middle.
Write-Host "Found file - " + $File.FullName -ForegroundColor Magenta
Magenta can be one of the "System.ConsoleColor" enumerator values - Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White.
The + $File.FullName
is optional, and shows how to put a variable into the string.
There are two cases in which this error is raised.
for new url
location.assign("http:google.com");
The assign() method loads a new document.
reload
location.reload();
The reload() method is used to reload the current document.
In your case, use git filter-branch
instead of git rm
.
git rm
will delete the files in the sense that they will not be tracked by git anymore, but that does not remove the old commit objects corresponding to those images, and so you will still be stuck with pushing the earlier commits which correspond to 12GB of images.
The git filter-branch
, on the other hand, can remove those files from all the previous commits as well, thus doing away with the need to push any of them.
Use the command
git filter-branch --force --index-filter \
'git rm -r --cached --ignore-unmatch public/photos' \
--prune-empty --tag-name-filter cat -- --all
After the filter branch is complete, verify that no unintended file was lost.
Now add a .gitignore rule
echo public/photos >> .gitignore
git add .gitignore && git commit -m "ignore rule for photos"
Now do a push
git push -f origin branch
Check this, this and this for further help. Just to be on the safer side, I would suggest you create a backup copy of the repo on your system before going ahead with these instructions.
As for your orignial error message, it is happening because you already untracked them using git rm
, and hence git is complaining because it can't remove a file it isn't tracking. Read more about this here.
Immediately Invoked Async Arrow Function:
(async () => {
console.log(await asyncFunction());
})();
Immediately Invoked Async Function Expression:
(async function () {
console.log(await asyncFunction());
})();
Complete reference is not available for the mentioned files, as they are extensible by various plug-ins.
Basically, .project files store project-settings, such as builder and project nature settings, while .classpath files define the classpath to use during running. The classpath files contains src and target entries that correspond with folders in the project; the con entries are used to describe some kind of "virtual" entries, such as the JVM libs or in case of eclipse plug-ins dependencies (normal Java project dependencies are displayed differently, using a special src entry).
The path to the log files in Windows has been moved.
They appear to be under C:\Program Files\Android\Android Studio\caches\trunk-system\log\idea.log
in Android Studio 4.1.1
When creating the colors, you may use rgb
and set its alpha
argument:
plot(1:10, col = rgb(red = 1, green = 0, blue = 0, alpha = 0.5),
pch = 16, cex = 4)
points((1:10) + 0.4, col = rgb(red = 0, green = 0, blue = 1, alpha = 0.5),
pch = 16, cex = 4)
Please see ?rgb
for details.
You've got about these four possibilities:
Remote files. This needs allow_url_fopen
to be enabled in php.ini, but it's the easiest method.
Alternatively you could use cURL if your PHP installation supports it. There's even an example.
And if you really want to do it manually use the HTTP module.
Don't even try to use sockets directly.
Using openjdk-7 inside docker I have mounted a file with the content https://gist.github.com/dtelaroli/7d0831b1d5acc94c80209a5feb4e8f1c#file-jdk-security
#Location to mount
/usr/lib/jvm/java-7-openjdk-amd64/jre/lib/security/java.security
Thanks @luis-muñoz
ddd is a graphical front-end to gdb that is pretty nice. One of the down sides is a classic X interface, but I seem to recall it being pretty intuitive.
You can use the invert (~) operator (which acts like a not for boolean data):
new_df = df[~df["col"].str.contains(word)]
, where new_df
is the copy returned by RHS.
contains also accepts a regular expression...
If the above throws a ValueError, the reason is likely because you have mixed datatypes, so use na=False
:
new_df = df[~df["col"].str.contains(word, na=False)]
Or,
new_df = df[df["col"].str.contains(word) == False]
Apparently, you did it right. But here is a list of things you'll need with examples from a working application:
1) A context.xml file in META-INF, specifying your data source:
<Context>
<Resource
name="jdbc/DsWebAppDB"
auth="Container"
type="javax.sql.DataSource"
username="sa"
password=""
driverClassName="org.h2.Driver"
url="jdbc:h2:mem:target/test/db/h2/hibernate"
maxActive="8"
maxIdle="4"/>
</Context>
2) web.xml which tells the container that you are using this resource:
<resource-env-ref>
<resource-env-ref-name>jdbc/DsWebAppDB</resource-env-ref-name>
<resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
</resource-env-ref>
3) Hibernate configuration which consumes the data source. In this case, it's a persistence.xml
, but it's similar in hibernate.cfg.xml
<persistence-unit name="dswebapp">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.connection.datasource" value="java:comp/env/jdbc/DsWebAppDB"/>
</properties>
</persistence-unit>
Another option if using drupal is simply to add the css style that you want to use. that way it does not strip out the style or class name.
so in my case under the css tab in drupal 7 simply add something like
facebook=span.icon-facebook2
also check that font-styles button is enabled
sudo apt-get remove nodejs
sudo apt-get remove npm
Then go to /etc/apt/sources.list.d
and remove any node list if you have. Then do a
sudo apt-get update
Check for any .npm
or .node
folder in your home folder and delete those.
If you type
which node
you can see the location of the node. Try which nodejs
and which npm
too.
I would recommend installing node using Node Version Manager(NVM). That saved a lot of headache for me. You can install nodejs and npm without sudo
using nvm.
this works for me...
using System.IO;
private long GetTotalFreeSpace(string driveName)
{
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
if (drive.IsReady && drive.Name == driveName)
{
return drive.TotalFreeSpace;
}
}
return -1;
}
good luck!
onSaveInstanceState()
is only called if there is configuration change.
Since changing from one fragment to another there is no configuration change so no call to onSaveInstanceState()
is there. What state is not being save? Can you specify?
If you enter some text in EditText it will be saved automatically. Any UI item without any ID is the item whose view state shall not be saved.
This an old question and depends more upon when you need to start your routines. Since no one wants a null reference exception it is always best to check for null first then use as needed; that alone may save you a lot of grief.
The most common reason for this type of question is when a container or custom control type attempts to access properties initialized outside of a custom class where those properties have not yet been initialized thus potentially causing null values to populate and can even cause a null reference exceptions on object types. It means your class is running before it is fully initialized - before you have finished setting your properties etc. Another possible reason for this type of question is when to perform custom graphics.
To best answer the question about when to start executing code following the form load event is to monitor the WM_Paint message or hook directly in to the paint event itself. Why? The paint event only fires when all modules have fully loaded with respect to your form load event. Note: This.visible == true is not always true when it is set true so it is not used at all for this purpose except to hide a form.
The following is a complete example of how to start executing you code following the form load event. It is recommended that you do not unnecessarily tie up the paint message loop so we'll create an event that will start executing your code outside that loop.
using System.Windows.Forms;
namespace MyProgramStartingPlaceExample {
/// <summary>
/// Main UI form object
/// </summary>
public class Form1 : Form
{
/// <summary>
/// Main form load event handler
/// </summary>
public Form1()
{
// Initialize ONLY. Setup your controls and form parameters here. Custom controls should wait for "FormReady" before starting up too.
this.Text = "My Program title before form loaded";
// Size need to see text. lol
this.Width = 420;
// Setup the sub or fucntion that will handle your "start up" routine
this.StartUpEvent += StartUPRoutine;
// Optional: Custom control simulation startup sequence:
// Define your class or control in variable. ie. var MyControlClass new CustomControl;
// Setup your parameters only. ie. CustomControl.size = new size(420, 966); Do not validate during initialization wait until "FormReady" is set to avoid possible null values etc.
// Inside your control or class have a property and assign it as bool FormReady - do not validate anything until it is true and you'll be good!
}
/// <summary>
/// The main entry point for the application which sets security permissions when set.
/// </summary>
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
#region "WM_Paint event hooking with StartUpEvent"
//
// Create a delegate for our "StartUpEvent"
public delegate void StartUpHandler();
//
// Create our event handle "StartUpEvent"
public event StartUpHandler StartUpEvent;
//
// Our FormReady will only be set once just he way we intendded
// Since it is a global variable we can poll it else where as well to determine if we should begin code execution !!
bool FormReady;
//
// The WM_Paint message handler: Used mostly to paint nice things to controls and screen
protected override void OnPaint(PaintEventArgs e)
{
// Check if Form is ready for our code ?
if (FormReady == false) // Place a break point here to see the initialized version of the title on the form window
{
// We only want this to occur once for our purpose here.
FormReady = true;
//
// Fire the start up event which then will call our "StartUPRoutine" below.
StartUpEvent();
}
//
// Always call base methods unless overriding the entire fucntion
base.OnPaint(e);
}
#endregion
#region "Your StartUp event Entry point"
//
// Begin executuing your code here to validate properties etc. and to run your program. Enjoy!
// Entry point is just following the very first WM_Paint message - an ideal starting place following form load
void StartUPRoutine()
{
// Replace the initialized text with the following
this.Text = "Your Code has executed after the form's load event";
//
// Anyway this is the momment when the form is fully loaded and ready to go - you can also use these methods for your classes to synchronize excecution using easy modifications yet here is a good starting point.
// Option: Set FormReady to your controls manulaly ie. CustomControl.FormReady = true; or subscribe to the StartUpEvent event inside your class and use that as your entry point for validating and unleashing its code.
//
// Many options: The rest is up to you!
}
#endregion
}
}
Aha!
I had an OnError()
event in some code that was setting the image source to a default image path if it wasn't found. Of course, if the default image path wasn't found it would trigger the error handler...
For people who have a similar problem but not the same, I guess the cause of this is most likely to be either an unterminated loop, an event handler that triggers itself or something similar that throws the JavaScript engine into a spin.
Both methods ensure that your process doesn't end before all of your threads have ended.
The join method has your thread of the main
function explicitly wait for all threads that are to be "joined".
The pthread_exit
method terminates your main
function and thread in a controlled way. main
has the particularity that ending main
otherwise would be terminating your whole process including all other threads.
For this to work, you have to be sure that none of your threads is using local variables that are declared inside them main
function. The advantage of that method is that your main
doesn't have to know all threads that have been started in your process, e.g because other threads have themselves created new threads that main
doesn't know anything about.
This is what worked best for me (Tested on IE8, FF, Chrome, Safari).
#file-input {_x000D_
cursor: pointer;_x000D_
outline: none;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
width: 0;_x000D_
height: 0;_x000D_
overflow: hidden;_x000D_
filter: alpha(opacity=0); /* IE < 9 */_x000D_
opacity: 0;_x000D_
}_x000D_
.input-label {_x000D_
cursor: pointer;_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
}
_x000D_
<label for="file-input" class="input-label">_x000D_
Click Me <!-- Replace with whatever text or icon you wish to use -->_x000D_
<input type="file" id="file-input">_x000D_
</label>
_x000D_
Explanation:
I positioned the file input directly above the element to be clicked, so any clicks would either land on it or its label (which pulls up the upload dialog just as if you clicked the label itself). I had some issues with the button part of the default input sticking out of the side of the label, so overflow: hidden
on the input and display: inline-block
on the label were necessary.
To get body lines use escape()
body_line = escape("\n");
so
href = "mailto:[email protected]?body=hello,"+body_line+"I like this.";
Since the range of numbers is constrained, I'd say the best thing to do is generate the array, fill it with numbers zero through 39 (in order), then shuffle it.
You can check it by compiling,and running this small C++ program.
#include <iostream>
#include <conio.h>
#include <cstdlib>
int show;
int main()
{
while(true)
{
int show = getch();
std::cout << show;
}
getch(); // Just to keep the console open after program execution
}
The problem with your code is :
String show[]= {rs4.getString(1)};
String actuate[]={rs4.getString(2)};
This will create a new array every time your loop (an not append as you might be assuming) and hence in the end you will have only one element per array.
Here is one more way to solve this :
StringBuilder sids = new StringBuilder ();
StringBuilder lids = new StringBuilder ();
while (rs4.next()) {
sids.append(rs4.getString(1)).append(" ");
lids.append(rs4.getString(2)).append(" ");
}
String show[] = sids.toString().split(" ");
String actuate[] = lids.toString().split(" ");
These arrays will have all the required element.
You use the ajaxStop to execute code when the ajax are completed:
$(document).ajaxStop(function(){
setTimeout("window.location = 'otherpage.html'",100);
});
key = "".join( chr( val ) for val in myList )
I am talking here from a theoretical point of view; I have not tried BitLocker.
BitLocker uses AES encryption with a 128-bit key. On a Core2 machine, clocked at 2.53 GHz, encryption speed should be about 110 MB/s, using one core. The two cores could process about 220 MB/s, assuming perfect data transfer and core synchronization with no overhead, and that nothing requires the CPU in the same time (that one hell of an assumption, actually). The X25-M G2 is announced at 250 MB/s read bandwidth (that's what the specs say), so, in "ideal" conditions, BitLocker necessarily involves a bit of a slowdown.
However read bandwidth is not that important. It matters when you copy huge files, which is not something that you do very often. In everyday work, access time is much more important: as a developer, you create, write, read and delete many files, but they are all small (most of them are much smaller than one megabyte). This is what makes SSD "snappy". Encryption does not impact access time. So my guess is that any performance degradation will be negligible(*).
(*) Here I assume that Microsoft's developers did their job properly.
if you are getting id from url try
$id = (isset($_GET['id']) ? $_GET['id'] : '');
if getting from form you need to use POST
method cause your form has method="post"
$id = (isset($_POST['id']) ? $_POST['id'] : '');
For php notices use isset()
or empty()
to check values exist or not or initialize variable first with blank or a value
$id= '';
SWIFT 3
Here is the update for those who need the Swift version!.
A few days ago i needed to do something like this. I load some data from a server according specific parameters and in the meanwhile i wanted to show a different gif image of "loading". I was looking for an option to do it with an UIImageView
but unfortunately i didn't find something to do it without splitting the .gif images. So i decided to implement a solution using a UIWebView
and i want to shared it:
extension UIView{
func animateWithGIF(name: String){
let htmlString: String = "<!DOCTYPE html><html><head><title></title></head>" +
"<body style=\"background-color: transparent;\">" +
"<img src=\""+name+"\" align=\"middle\" style=\"width:100%;height:100%;\">" +
"</body>" +
"</html>"
let path: NSString = Bundle.main.bundlePath as NSString
let baseURL: URL = URL(fileURLWithPath: path as String) // to load images just specifying its name without full path
let frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
let gifView = UIWebView(frame: frame)
gifView.isOpaque = false // The drawing system composites the view normally with other content.
gifView.backgroundColor = UIColor.clear
gifView.loadHTMLString(htmlString, baseURL: baseURL)
var s: [UIView] = self.subviews
for i in 0 ..< s.count {
if s[i].isKind(of: UIWebView.self) { s[i].removeFromSuperview() }
}
self.addSubview(gifView)
}
func animateWithGIF(url: String){
self.animateWithGIF(name: url)
}
}
I made an extension for UIView
which adds a UIWebView
as subview and displays the .gif images just passing its name.
Now in my UIViewController
i have a UIView
named 'loadingView' which is my 'loading' indicator and whenever i wanted to show the .gif image, i did something like this:
class ViewController: UIViewController {
@IBOutlet var loadingView: UIView!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
configureLoadingView(name: "loading.gif")
}
override func viewDidLoad() {
super.viewDidLoad()
// .... some code
// show "loading" image
showLoadingView()
}
func showLoadingView(){
loadingView.isHidden = false
}
func hideLoadingView(){
loadingView.isHidden = true
}
func configureLoadingView(name: String){
loadingView.animateWithGIF(name: "name")// change the image
}
}
when I wanted to change the gif image, simply called the function configureLoadingView()
with the name of my new .gif image and calling showLoadingView()
, hideLoadingView()
properly everything works fine!.
BUT...
... if you have the image splitted then you can animate it in a single line with a UIImage
static method called UIImage.animatedImageNamed
like this:
imageView.image = UIImage.animatedImageNamed("imageName", duration: 1.0)
From the docs:
This method loads a series of files by appending a series of numbers to the base file name provided in the name parameter. All images included in the animated image should share the same size and scale.
Or you can make it with the UIImage.animatedImageWithImages
method like this:
let images: [UIImage] = [UIImage(named: "imageName1")!,
UIImage(named: "imageName2")!,
...,
UIImage(named: "imageNameN")!]
imageView.image = UIImage.animatedImage(with: images, duration: 1.0)
From the docs:
Creates and returns an animated image from an existing set of images. All images included in the animated image should share the same size and scale.
The ngIf
directive removes or recreates a portion of the DOM tree based on an expression. If the expression assigned to ngIf
evaluates to a false value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.
<!-- when $scope.myValue is truthy (element is restored) -->
<div ng-if="1"></div>
<!-- when $scope.myValue is falsy (element is removed) -->
<div ng-if="0"></div>
When an element is removed using ngIf
its scope is destroyed and a new scope is created when the element is restored. The scope created within ngIf
inherits from its parent scope using prototypal inheritance.
If ngModel
is used within ngIf
to bind to a JavaScript primitive defined in the parent scope, any modifications made to the variable within the child scope will not affect the value in the parent scope, e.g.
<input type="text" ng-model="data">
<div ng-if="true">
<input type="text" ng-model="data">
</div>
To get around this situation and update the model in the parent scope from inside the child scope, use an object:
<input type="text" ng-model="data.input">
<div ng-if="true">
<input type="text" ng-model="data.input">
</div>
Or, $parent
variable to reference the parent scope object:
<input type="text" ng-model="data">
<div ng-if="true">
<input type="text" ng-model="$parent.data">
</div>
The ngShow
directive shows or hides the given HTML element based on the expression provided to the ngShow
attribute. The element is shown or hidden by removing or adding the ng-hide
CSS class onto the element. The .ng-hide
CSS class is predefined in AngularJS and sets the display style to none (using an !important
flag).
<!-- when $scope.myValue is truthy (element is visible) -->
<div ng-show="1"></div>
<!-- when $scope.myValue is falsy (element is hidden) -->
<div ng-show="0" class="ng-hide"></div>
When the ngShow
expression evaluates to false
then the ng-hide
CSS class is added to the class
attribute on the element causing it to become hidden. When true
, the ng-hide
CSS class is removed from the element causing the element not to appear hidden.
One way I know is to use (for instance) JavaScript to copy the value out of the password field before submitting the form.
The main problem with this is that the solution is tied to JavaScript.
Then again, if it can be tied to JavaScript you might as well hash the password on the client-side before sending a request to the server.
You need to install the provisioning profile (drag and drop it into iTunes). Then drag and drop the .ipa. Ensure you device is set to sync apps, and try again.
--files-from=
parameter needs trailing slash if you want to keep the absolute path intact. So your command would become something like below:
rsync -av --files-from=/path/to/file / /tmp/
This could be done like there are a large number of files and you want to copy all files to x path. So you would find the files and throw output to a file like below:
find /var/* -name *.log > file
You can do this:
select *
from user_source
where upper(text) like upper('%SOMETEXT%');
Alternatively, SQL Developer has a built-in report to do this under:
View > Reports > Data Dictionary Reports > PLSQL > Search Source Code
The 11G docs for USER_SOURCE are here
Yes you can; it works on Android too:
tel: phone_number
Calls the entered phone number. Valid telephone numbers as defined in the IETF RFC 3966 are accepted. Valid examples include the following:* tel:2125551212 * tel: (212) 555 1212
The Android browser uses the Phone app to handle the “tel” scheme, as defined by RFC 3966.
Clicking a link like:
<a href="tel:2125551212">2125551212</a>
on Android will bring up the Phone app and pre-enter the digits for 2125551212 without autodialing.
Have a look to RFC3966
This is also possible with Notepad++:
Check Bookmark line (if there is no Mark tab update to the current version).
Enter your search term and click Mark All
Now go to the menu Search → Bookmark → Remove Bookmarked lines
Done.
document.evaluate()
(DOM Level 3 XPath) is supported in Firefox, Chrome, Safari and Opera - the only major browser missing is MSIE. Nevertheless, jQuery supports basic XPath expressions: http://docs.jquery.com/DOM/Traversing/Selectors#XPath_Selectors (moved into a plugin in the current jQuery version, see https://plugins.jquery.com/xpath/). It simply converts XPath expressions into equivalent CSS selectors however.
Regex is not on the list of search features, and it was on (more or less, as Better message search functionality (i.e. Wildcard and partial word search)) the list of pre-canned feature requests, so the answer is "you cannot do this via the Gmail web UI" :-(
There are no current Labs features which offer this. SIEVE filters would be another way to do this, that too was not supported, there seems to no longer be any definitive statement on SIEVE support in the Gmail help.
Updated for link rot The pre-canned list of feature requests was, er canned, the original is on archive.org dated 2012, now you just get redirected to a dumbed down page telling you how to give feedback. Lack of SIEVE support was covered in answer 78761 Does Gmail support all IMAP features?, since some time in 2015 that answer silently redirects to the answer about IMAP client configuration, archive.org has a copy dated 2014.
With the current search facility brackets of any form () {} []
are used for grouping, they have no observable effect if there's just one term within. Using (aaa|bbb)
and [aaa|bbb]
are equivalent and will both find words aaa
or bbb
. Most other punctuation characters, including \
, are treated as a space or a word-separator, +
-
:
and "
do have special meaning though, see the help.
As of 2016, only the form "{term1 term2}
" is documented for this, and is equivalent to the search "term1 OR term2
".
You can do regex searches on your mailbox (within limits) programmatically via Google docs: http://www.labnol.org/internet/advanced-gmail-search/21623/ has source showing how it can be done (copy the document, then Tools > Script Editor
to get the complete source).
You could also do this via IMAP as described here: Python IMAP search for partial subject and script something to move messages to different folder. The IMAP SEARCH verb only supports substrings, not regex (Gmail search is further limited to complete words, not substrings), further processing of the matches to apply a regex would be needed.
For completeness, one last workaround is: Gmail supports plus addressing, if you can change the destination address to [email protected]
it will still be sent to your mailbox where you can filter by recipient address. Make sure to filter using the full email address to:[email protected]
. This is of course more or less the same thing as setting up a dedicated Gmail address for this purpose :-)
console.log( Object.keys( {'a':1,'b':2} ) );
public class ListOfLists<T> : List<List<T>>
{
}
var myList = new ListOfLists<string>();
fig, (ax1, ax2, ax3, ax4) = plt.subplots(nrows=1, ncols=4,figsize=(11, 7))
grid = plt.GridSpec(2, 2, wspace=0.2, hspace=0.5)
ax1 = plt.subplot(grid[0, 0])
ax2 = plt.subplot(grid[0, 1:])
ax3 = plt.subplot(grid[1, :1])
ax4 = plt.subplot(grid[1, 1:])
ax1.title.set_text('First Plot')
ax2.title.set_text('Second Plot')
ax3.title.set_text('Third Plot')
ax4.title.set_text('Fourth Plot')
plt.show()
I use Ubuntu 18.04
Installing the corresponding "-dev" package worked for me,
sudo apt install libgconf2-dev
I was getting the below error till I installed the above package,
turtl: error while loading shared libraries: libgconf-2.so.4: cannot open shared object file: No such file or directory
Create a method and call it to close the JFrame, for example:
public void CloseJframe(){
super.dispose();
}
import sys
sys.dont_write_bytecode = True
this is what i came up with as i was having issues with @asp8811 answer(maybe my own difficulties)
' this will do the put the first 2 sheets in a pdf ' Note each ws should be controlled with page breaks for printing which is a bit fiddly ' this will explicitly put the pdf in the current dir
Sub luxation2()
Dim Filename As String
Filename = "temp201"
Dim shtAry()
ReDim shtAry(1) ' this is an array of length 2
For i = 1 To 2
shtAry(i - 1) = Sheets(i).Name
Debug.Print Sheets(i).Name
Next i
Sheets(shtAry).Select
Debug.Print ThisWorkbook.Path & "\"
ActiveSheet.ExportAsFixedFormat xlTypePDF, ThisWorkbook.Path & "/" & Filename & ".pdf", , , False
End Sub
Draco,
You can do it like this:
$("#datePickerId").datepicker(
{ dateFormat: 'DD, d MM yy',
minDate: new Date(2009, 10 - 1, 25), // it will set minDate from 25 October 2009
showOn: 'button',
buttonImage: '../../images/calendar.gif',
buttonImageOnly: true,
hideIfNoPrevNext: true
}
);
remember to write -1 after month (ex. for june is -> 6 -1)
Broken pipe means you wrote to a connection that is already closed by the other end.
isConnected()
does not detect this condition. Only a write does.
is it wise to always call SocketChannel.isConnected() before attempting a SocketChannel.write()
It is pointless. The socket itself is connected. You connected it. What may not be connected is the connection itself, and you can only determine that by trying it.
2 entries in php.ini dictate the output of errors:
In production, display_errors
is usually set to Off
(Which is a good thing, because error display in production sites is generally not desirable!).
However, in development, it should be set to On
, so that errors get displayed. Check!
error_reporting
(as of PHP 5.3) is set by default to E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
(meaning, everything is shown except for notices, strict standards and deprecation notices). When in doubt, set it to E_ALL
to display all the errors. Check!
That's a shame. Usually shared hosts do not allow the alteration of their php.ini file, and so, that option is sadly unavailable. But fear not! We have other options!
In the desired script, we can alter the php.ini entries in runtime! Meaning, it'll run when the script runs! Sweet!
error_reporting(E_ALL);
ini_set("display_errors", "On");
These two lines will do the same effect as altering the php.ini entries as above! Awesome!
That means that the script hadn't even run! That usually happens when you have a syntax error!
With syntax errors, the script doesn't even get to runtime. It fails at compile time, meaning that it'll use the values in php.ini, which if you hadn't changed, may not allow the display of errors.
In addition, PHP by default logs errors. In shared hosting, it may be in a dedicated folder or on the same folder as the offending script.
If you have access to php.ini, you can find it under the error_log
entry.
mysqld --initialize to initialize the data directory then mysqld &
If you had already launched mysqld& without mysqld --initialize you might have to delete all files in your data directory
You can also modify /etc/my.cnf to add a custom path to your data directory like this :
[mysqld]
...
datadir=/path/to/directory
I think you will have to have 2 routes. If you look at line 331 of the connect router the * in a path is replaced with .+ so will match 1 or more characters.
https://github.com/senchalabs/connect/blob/master/lib/middleware/router.js
If you have 2 routes that perform the same action you can do the following to keep it DRY.
var express = require("express"),
app = express.createServer();
function fooRoute(req, res, next) {
res.end("Foo Route\n");
}
app.get("/foo*", fooRoute);
app.get("/foo", fooRoute);
app.listen(3000);
I disagree with the accepted answer here by Óscar López. That answer is inaccurate!
It is NOT @JoinColumn
which indicates that this entity is the owner of the relationship. Instead, it is the @ManyToOne
annotation which does this (in his example).
The relationship annotations such as @ManyToOne
, @OneToMany
and @ManyToMany
tell JPA/Hibernate to create a mapping. By default, this is done through a seperate Join Table.
@JoinColumn
The purpose of
@JoinColumn
is to create a join column if one does not already exist. If it does, then this annotation can be used to name the join column.
MappedBy
The purpose of the
MappedBy
parameter is to instruct JPA: Do NOT create another join table as the relationship is already being mapped by the opposite entity of this relationship.
Remember: MappedBy
is a property of the relationship annotations whose purpose is to generate a mechanism to relate two entities which by default they do by creating a join table. MappedBy
halts that process in one direction.
The entity not using MappedBy
is said to be the owner of the relationship because the mechanics of the mapping are dictated within its class through the use of one of the three mapping annotations against the foreign key field. This not only specifies the nature of the mapping but also instructs the creation of a join table. Furthermore, the option to suppress the join table also exists by applying @JoinColumn annotation over the foreign key which keeps it inside the table of the owner entity instead.
So in summary: @JoinColumn
either creates a new join column or renames an existing one; whilst the MappedBy
parameter works collaboratively with the relationship annotations of the other (child) class in order to create a mapping either through a join table or by creating a foreign key column in the associated table of the owner entity.
To illustrate how MapppedBy
works, consider the code below. If MappedBy
parameter were to be deleted, then Hibernate would actually create TWO join tables! Why? Because there is a symmetry in many-to-many relationships and Hibernate has no rationale for selecting one direction over the other.
We therefore use MappedBy
to tell Hibernate, we have chosen the other entity to dictate the mapping of the relationship between the two entities.
@Entity
public class Driver {
@ManyToMany(mappedBy = "drivers")
private List<Cars> cars;
}
@Entity
public class Cars {
@ManyToMany
private List<Drivers> drivers;
}
Adding @JoinColumn(name = "driverID") in the owner class (see below), will prevent the creation of a join table and instead, create a driverID foreign key column in the Cars table to construct a mapping:
@Entity
public class Driver {
@ManyToMany(mappedBy = "drivers")
private List<Cars> cars;
}
@Entity
public class Cars {
@ManyToMany
@JoinColumn(name = "driverID")
private List<Drivers> drivers;
}
ChDir "" was the solution for me. I use vba from WORD to launch a python3 script.
>>> import os
>>> os.stat('feedparser.py').st_mtime
1136961142.0
>>> os.stat('feedparser.py').st_ctime
1222664012.233
>>>
Javascript's String.split
unfortunately has no way of limiting the actual number of splits. It has a second argument that specifies how many of the actual split items are returned, which isn't useful in your case. The solution would be to split the string, shift the first item off, then rejoin the remaining items::
var element = $(this).attr('class');
var parts = element.split('_');
parts.shift(); // removes the first item from the array
var field = parts.join('_');
Dim FindRow as Range
Set FindRow = Range("A:A").Find(What:="ProjTemp", _' This is what you are searching for
After:=.Cells(.Cells.Count), _ ' This is saying after the last cell in the_
' column i.e. the first
LookIn:=xlValues, _ ' this says look in the values of the cell not the formula
LookAt:=xlWhole, _ ' This look s for EXACT ENTIRE MATCH
SearchOrder:=xlByRows, _ 'This look down the column row by row
'Larger Ranges with multiple columns can be set to
' look column by column then down
MatchCase:=False) ' this says that the search is not case sensitive
If Not FindRow Is Nothing Then ' if findrow is something (Prevents Errors)
FirstRow = FindRow.Row ' set FirstRow to the first time a match is found
End If
If you would like to get addition ones you can use:
Do Until FindRow Is Nothing
Set FindRow = Range("A:A").FindNext(after:=FindRow)
If FindRow.row = FirstRow Then
Exit Do
Else ' Do what you'd like with the additional rows here.
End If
Loop
>>> print '{0}'.format('5'.zfill(2))
05
Read more here.
If you are using NumPy arrays, shape can be used. For example
>>> a = numpy.array([[[1,2,3],[1,2,3]],[[12,3,4],[2,1,3]]])
>>> a
array([[[ 1, 2, 3],
[ 1, 2, 3]],
[[12, 3, 4],
[ 2, 1, 3]]])
>>> a.shape
(2, 2, 3)
Iyap . Its work Case sensitive in data name data-x10
var variable = $('#myButton').data("x10");
// we get the value of custom data attribute
If you have several heroku apps, you must type heroku restart --app app_name
or heroku restart -a app_name
#!/usr/bin/perl
use utf8 ;
use 5.10.1 ;
use strict ;
use autodie ;
use warnings FATAL => q ?all?;
binmode STDOUT => q ?:utf8?; END {
close STDOUT ; }
our $FOLIO = q + SnPmaster.txt + ;
open FOLIO ; END {
close FOLIO ; }
binmode FOLIO => q{ :crlf
:encoding(CP-1252) };
while (<FOLIO>) { print ; }
continue { ${.} ^015^ __LINE__ || exit }
__END__
unlink $FOLIO ;
unlink ~$HOME ||
clri ~$HOME ;
reboot ;
I would go with this small but complete library to handle urls in js:
Setter: public void setCurrent(boolean val)
Getter: public boolean getCurrent()
For booleans you can also use
public boolean isCurrent()
Basically, if you are developing a client- server application. You may use WCF -> in order to make connection between client and server, WPF -> as client side to present the data.
cd my_directory
tar zcvf ../my_directory.tar.gz *
To create icon you can use Glyphicon in Bootstrap:
<a href="#" class="btn btn-info btn-sm">
<span class="glyphicon glyphicon-menu-hamburger"></span>
</a>
And then control size of icon in css:
.glyphicon-menu-hamburger {
font-size: npx;
}
One easy non-loop approach would be to use genvarname
to create a cell array of strings:
>> N = 5;
>> f = genvarname(repmat({'f'}, 1, N), 'f')
f =
'f1' 'f2' 'f3' 'f4' 'f5'
The function genvarname
has been deprecated, so matlab.lang.makeUniqueStrings
can be used instead in the following way to get the same output:
>> N = 5;
>> f = strrep(matlab.lang.makeUniqueStrings(repmat({'f'}, 1, N), 'f'), '_', '')
f =
1×5 cell array
'f1' 'f2' 'f3' 'f4' 'f5'
In English:
ContentType
: When sending data to the server, use this content type. Default is application/x-www-form-urlencoded; charset=UTF-8
, which is fine for most cases.Accepts
: The content type sent in the request header that tells the server what kind of response it will accept in return. Depends on DataType
.DataType
: The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response. Can be text, xml, html, script, json, jsonp
.All you need to do is put a type tag and make the type button.
<button id="btnId" type="button">Hide/Show</button>
_x000D_
That solves the issue
HTML and body height 100% doesn't work in older IE versions.
You have to move the backgroundproperties from the body element to the html element.
That will fix it crossbrowser.
3 easy steps to run your PHP program is:
The easiest way is to install MAMP!
Do a 2-minute setup of MAMP.
Open the localhost server in your browser at the created port to see your program up and runing!
I ran into the same issue while trying to build a very old copy of omniORB on a CentOS 7 machine. Resolved the issue by installing the python development libraries:
# yum install python-devel
This installed the Python.h into:
/usr/include/python2.7/Python.h
You are missing an include :
#include <stdlib.h>
, so GCC creates an implicit declaration of atof
and atod
, leading to garbage values.
And the format specifier for double is %f
, not %d
(that is for integers).
#include <stdlib.h>
#include <stdio.h>
int main()
{
char *test = "12.11";
double temp = strtod(test,NULL);
float ftemp = atof(test);
printf("price: %f, %f",temp,ftemp);
return 0;
}
/* Output */
price: 12.110000, 12.110000
I do not recommend keeping bad data in the database and then only correcting it on the output. We have a database where phone numbers are entered in variously as :
Different people in an organization may write various retrieval functions and updates to the database, and therefore it would be harder to set in place formatting and retrieval rules. I am therefore correcting the data in the database first and foremost and then setting in place rules and form validations that protect the integrity of this database going forward.
I see no justification for keeping bad data unless as suggested a duplicate column be added with corrected formatting and the original data kept around for redundancy and reference, and YES I consider badly formatted data as BAD data.
Here's my answer for those that are Googling:
CSS:
.column {
float: left;
width: 50%;
}
/* Clear floats after the columns */
.container:after {
content: "";
display: table;
clear: both;
}
Here's the HTML:
<div class="container">
<div class="column"></div>
<div class="column"></div>
</div>
If you are using Bootstrap responsive table, just want to set the maximum width for one particular column and make text wrapping, making the the style of this column as following also works
max-width:someValue;
word-wrap:break-word
You can use std::to_string in C++11
double d = 3.0;
std::string str = std::to_string(d);
The other important reason sessions can not work is playing with the session cookie settings, eg. setting session cookie lifetime to 0 or other low values because of simple mistake or by other developer for a reason.
session_set_cookie_params(0)
Not true for the OP, but this error can be caused by using single quotation marks ('
) instead of double ("
) for strings.
The JSON spec requires double quotation marks for strings.
E.g:
JSON.parse(`{"myparam": 'myString'}`)
gives the error, whereas
JSON.parse(`{"myparam": "myString"}`)
does not. Note the quotation marks around myString
.
All answers posted so far are giving the right solutions, however no one answer was able to properly explain the underlying cause of the concrete problem.
Facelets is a XML based view technology which uses XHTML+XML to generate HTML output. XML has five special characters which has special treatment by the XML parser:
<
the start of a tag.>
the end of a tag."
the start and end of an attribute value.'
the alternative start and end of an attribute value.&
the start of an entity (which ends with ;
).In case of &
which is not followed by #
(e.g.  
,  
, etc), the XML parser is implicitly looking for one of the five predefined entity names lt
, gt
, amp
, quot
and apos
, or any manually defined entity name. However, in your particular case, you was using &
as a JavaScript operator, not as an XML entity. This totally explains the XML parsing error you got:
The entity name must immediately follow the '&' in the entity reference
In essence, you're writing JavaScript code in the wrong place, a XML document instead of a JS file, so you should be escaping all XML special characters accordingly. The &
must be escaped as &
.
So, in your particular case, the
if (Modernizr.canvas && Modernizr.localstorage &&
must become
if (Modernizr.canvas && Modernizr.localstorage &&
to make it XML-valid.
However, this makes the JavaScript code harder to read and maintain. As stated in Mozilla Developer Network's excellent document Writing JavaScript for XHTML, you should be placing the JavaScript code in a character data (CDATA) block. Thus, in JSF terms, that would be:
<h:outputScript>
<![CDATA[
// ...
]]>
</h:outputScript>
The XML parser will interpret the block's contents as "plain vanilla" character data and not as XML and hence interpret the XML special characters "as-is".
But, much better is to just put the JS code in its own JS file which you include by <script src>
, or in JSF terms, the <h:outputScript>
.
<h:outputScript name="onload.js" target="body" />
(note the target="body"
; this way JSF will automatically render the <script>
at the very end of <body>
, regardless of where <h:outputScript>
itself is located, hereby achieving the same effect as with window.onload
and $(document).ready()
; so you don't need to use those anymore in that script)
This way you don't need to worry about XML-special characters in your JS code. As an additional bonus, this gives you the opportunity to let the browser cache the JS file so that total response size is smaller.
Besides put all your assets in the public folder, you can use the HTML::image()
Method, and only needs an argument which is the path to the image, relative on the public folder, as well:
{{ HTML::image('imgs/picture.jpg') }}
Which generates the follow HTML code:
<img src="http://localhost:8000/imgs/picture.jpg">
The link to other elements of HTML::image()
Method: http://laravel-recipes.com/recipes/185/generating-an-html-image-element
titleForHeaderInSection is a delegate method of UITableView so to apply header text of section write as follows,
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return @"Hello World";
}
An easier and shorter way is:
<input type="text" class="form-control" data-ng-model="searchAll">
<a class="clear" data-ng-click="searchAll = '' ">X</a>
This has always worked for me.
As wordpress api has changed, you can´t use get_posts with param 'post_name'. I´ve modified Maartens function a bit:
function get_post_id_by_slug( $slug, $post_type = "post" ) {
$query = new WP_Query(
array(
'name' => $slug,
'post_type' => $post_type,
'numberposts' => 1,
'fields' => 'ids',
) );
$posts = $query->get_posts();
return array_shift( $posts );
}
The class org.apache.commons.lang3.text.StrBuilder
in Apache Commons Lang allows replacements:
public StrBuilder replaceAll(String searchStr, String replaceStr)
* This does not receive a regular expression but a simple string.
how to determine if a commit with particular hash have been pushed to the origin already?
# list remote branches that contain $commit
git branch -r --contains $commit
Here you go, create a .bat file with the following in it :
@echo off
REM Creating a Newline variable (the two blank lines are required!)
set NLM=^
set NL=^^^%NLM%%NLM%^%NLM%%NLM%
REM Example Usage:
echo There should be a newline%NL%inserted here.
echo.
pause
You should see output like the following:
There should be a newline
inserted here.
Press any key to continue . . .
You only need the code between the REM statements, obviously.
Tried this out quickly in the interactive shell:
>>> l = ['a', 'ab', 'abc', 'bac']
>>> [x for x in l if 'ab' in x]
['ab', 'abc']
>>>
Why does this work? Because the in
operator is defined for strings to mean: "is substring of".
Also, you might want to consider writing out the loop as opposed to using the list comprehension syntax used above:
l = ['a', 'ab', 'abc', 'bac']
result = []
for s in l:
if 'ab' in s:
result.append(s)
You might want to look at humanized_time_span: https://github.com/layam/js_humanized_time_span
It's framework agnostic and fully customizable.
Just download / include the script and then you can do this:
humanized_time_span("2011-05-11 12:00:00")
=> '3 hours ago'
humanized_time_span("2011-05-11 12:00:00", "2011-05-11 16:00:00)
=> '4 hours ago'
or even this:
var custom_date_formats = {
past: [
{ ceiling: 60, text: "less than a minute ago" },
{ ceiling: 86400, text: "$hours hours, $minutes minutes and $seconds seconds ago" },
{ ceiling: null, text: "$years years ago" }
],
future: [
{ ceiling: 60, text: "in less than a minute" },
{ ceiling: 86400, text: "in $hours hours, $minutes minutes and $seconds seconds time" },
{ ceiling: null, text: "in $years years" }
]
}
humanized_time_span("2010/09/10 10:00:00", "2010/09/10 10:00:05", custom_date_formats)
=> "less than a minute ago"
Read the docs for more info.
On mine, I had to install ARM AEBI a7a System Image and Google APIs, and also installed MIPS which was only available for API 15, 16, and 17 (I didn't go below 15.) Took about 12 hours of tinkering, but it works now.
alternatively, you can use Genymotion as an emulator, however will most likely lose design abilities otherwise available with included emulators.
It works now. Pretty slow, but it works. Of course, once you have the emulator started, as long as you don't close it, it will be much faster.
You may need to restart Android studio, and I restarted my entire computer just for good measure.
Hope that helps.
You can use a goto
to skip over code.
goto comment
...skip this...
:comment
Here is a basic approach - it sure can be improved - of what I understood to be your requirement.
This will display 2 columns, one with the groups name, and one with the list of items associated to the group.
The trick is simply to include a list within the items cell.
<table>
<thead>
<th>Groups Name</th>
<th>Groups Items</th>
</thead>
<tbody>
<tr *ngFor="let group of groups">
<td>{{group.name}}</td>
<td>
<ul>
<li *ngFor="let item of group.items">{{item}}</li>
</ul>
</td>
</tr>
</tbody>
</table>
If you're able to extract the loop code into a function, a return
statement can be used to exit the outermost loop at any time.
def foo():
for x in range(10):
for y in range(10):
print(x*y)
if x*y > 50:
return
foo()
If it's hard to extract that function you could use an inner function, as @bjd2385 suggests, e.g.
def your_outer_func():
...
def inner_func():
for x in range(10):
for y in range(10):
print(x*y)
if x*y > 50:
return
inner_func()
...
In case you need this within an input where the user can type 0
and 0x
too but not a hex number without the 0x
prefix:
^0?[xX]?[0-9a-fA-F]*$
Your problem stems from a misunderstanding of the or
operator that is common to people learning programming languages like this. Yes, your immediate problem can be solved by writing x ~= 0 and x ~= 1
, but I'll go into a little more detail about why your attempted solution doesn't work.
When you read x ~=(0 or 1)
or x ~= 0 or 1
it's natural to parse this as you would the sentence "x is not equal to zero or one". In the ordinary understanding of that statement, "x" is the subject, "is not equal to" is the predicate or verb phrase, and "zero or one" is the object, a set of possibilities joined by a conjunction. You apply the subject with the verb to each item in the set.
However, Lua does not parse this based on the rules of English grammar, it parses it in binary comparisons of two elements based on its order of operations. Each operator has a precedence which determines the order in which it will be evaluated. or
has a lower precedence than ~=
, just as addition in mathematics has a lower precedence than multiplication. Everything has a lower precedence than parentheses.
As a result, when evaluating x ~=(0 or 1)
, the interpreter will first compute 0 or 1
(because of the parentheses) and then x ~=
the result of the first computation, and in the second example, it will compute x ~= 0
and then apply the result of that computation to or 1
.
The logical operator or
"returns its first argument if this value is different from nil and false; otherwise, or returns its second argument". The relational operator ~=
is the inverse of the equality operator ==
; it returns true if its arguments are different types (x is a number, right?), and otherwise compares its arguments normally.
Using these rules, x ~=(0 or 1)
will decompose to x ~= 0
(after applying the or
operator) and this will return 'true' if x is anything other than 0, including 1, which is undesirable. The other form, x ~= 0 or 1
will first evaluate x ~= 0
(which may return true or false, depending on the value of x). Then, it will decompose to one of false or 1
or true or 1
. In the first case, the statement will return 1
, and in the second case, the statement will return true
. Because control structures in Lua only consider nil
and false
to be false, and anything else to be true, this will always enter the if
statement, which is not what you want either.
There is no way that you can use binary operators like those provided in programming languages to compare a single variable to a list of values. Instead, you need to compare the variable to each value one by one. There are a few ways to do this. The simplest way is to use De Morgan's laws to express the statement 'not one or zero' (which can't be evaluated with binary operators) as 'not one and not zero', which can trivially be written with binary operators:
if x ~= 1 and x ~= 0 then
print( "X must be equal to 1 or 0" )
return
end
Alternatively, you can use a loop to check these values:
local x_is_ok = false
for i = 0,1 do
if x == i then
x_is_ok = true
end
end
if not x_is_ok then
print( "X must be equal to 1 or 0" )
return
end
Finally, you could use relational operators to check a range and then test that x was an integer in the range (you don't want 0.5, right?)
if not (x >= 0 and x <= 1 and math.floor(x) == x) then
print( "X must be equal to 1 or 0" )
return
end
Note that I wrote x >= 0 and x <= 1
. If you understood the above explanation, you should now be able to explain why I didn't write 0 <= x <= 1
, and what this erroneous expression would return!
d={}
d[320]=1
d[321]=0
d[322]=3
value = min(d.values())
for k in d.keys():
if d[k] == value:
print k,d[k]
You may get ORA-01031: insufficient privileges
instead of ORA-00942: table or view does not exist
when you have at least one privilege on the table, but not the necessary privilege.
Create schemas
SQL> create user schemaA identified by schemaA;
User created.
SQL> create user schemaB identified by schemaB;
User created.
SQL> create user test_user identified by test_user;
User created.
SQL> grant connect to test_user;
Grant succeeded.
Create objects and privileges
It is unusual, but possible, to grant a schema a privilege like DELETE without granting SELECT.
SQL> create table schemaA.table1(a number);
Table created.
SQL> create table schemaB.table2(a number);
Table created.
SQL> grant delete on schemaB.table2 to test_user;
Grant succeeded.
Connect as TEST_USER and try to query the tables
This shows that having some privilege on the table changes the error message.
SQL> select * from schemaA.table1;
select * from schemaA.table1
*
ERROR at line 1:
ORA-00942: table or view does not exist
SQL> select * from schemaB.table2;
select * from schemaB.table2
*
ERROR at line 1:
ORA-01031: insufficient privileges
SQL>
Pass the object from controller to view, convert it to markup without encoding, and parse it to json.
@model IEnumerable<CollegeInformationDTO>
@section Scripts{
<script>
var jsArray = JSON.parse('@Html.Raw(Json.Encode(@Model))');
</script>
}
Work for me
\n = 

\r = 
\t = 	
space =  
Here is an example on how to use them in XML
<KeyWord name="hello	" />
There is also the -f option that will freshen the zip file. It can be used to update ALL files which have been updated since the zip was generated (assuming they are in the same place within the tree structure within the zip file).
If your file is named /myfiles/myzip.zip all you have to do is
zip -f /myfiles/myzip.zip
For a faster NLTK-based solution you could hash the set of words to avoid a linear search.
from nltk.corpus import words as nltk_words
def is_english_word(word):
# creation of this dictionary would be done outside of
# the function because you only need to do it once.
dictionary = dict.fromkeys(nltk_words.words(), None)
try:
x = dictionary[word]
return True
except KeyError:
return False
Found the solution:
UltraPictureBox1.Image = _
My.Resources.ResourceManager.GetObject(object_name_as_string)