If you have Pillow
installed with scipy
and it is still giving you error then check your scipy
version because it has been removed from scipy since 1.3.0rc1
.
rather install scipy 1.1.0
by :
pip install scipy==1.1.0
check https://github.com/scipy/scipy/issues/6212
The method imread
in scipy.misc
requires the forked package of PIL
named Pillow
. If you are having problem installing the right version of PIL try using imread
in other packages:
from matplotlib.pyplot import imread
im = imread(image.png)
To read jpg
images without PIL
use:
import cv2 as cv
im = cv.imread(image.jpg)
You can try
from scipy.misc.pilutil import imread
instead of from scipy.misc import imread
Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.
I use next code for disable options in selections
<select class="sel big" id="form_code" name="code" readonly="readonly">
<option value="user_played_game" selected="true">1 Game</option>
<option value="coins" disabled="">2 Object</option>
<option value="event" disabled="">3 Object</option>
<option value="level" disabled="">4 Object</option>
<option value="game" disabled="">5 Object</option>
</select>
// Disable selection for options
$('select option:not(:selected)').each(function(){
$(this).attr('disabled', 'disabled');
});
Locking a file is usually a platform-specific operation, so you may need to allow for the possibility of running on different operating systems. For example:
import os
def my_lock(f):
if os.name == "posix":
# Unix or OS X specific locking here
elif os.name == "nt":
# Windows specific locking here
else:
print "Unknown operating system, lock unavailable"
Is it "safe" to use
$_SERVER['HTTP_HOST']
for all links on a site without having to worry about XSS attacks, even when used in forms?
Yes, it's safe to use $_SERVER['HTTP_HOST']
, (and even $_GET
and $_POST
) as long as you verify them before accepting them. This is what I do for secure production servers:
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
$reject_request = true;
if(array_key_exists('HTTP_HOST', $_SERVER)){
$host_name = $_SERVER['HTTP_HOST'];
// [ need to cater for `host:port` since some "buggy" SAPI(s) have been known to return the port too, see http://goo.gl/bFrbCO
$strpos = strpos($host_name, ':');
if($strpos !== false){
$host_name = substr($host_name, $strpos);
}
// ]
// [ for dynamic verification, replace this chunk with db/file/curl queries
$reject_request = !array_key_exists($host_name, array(
'a.com' => null,
'a.a.com' => null,
'b.com' => null,
'b.b.com' => null
));
// ]
}
if($reject_request){
// log errors
// display errors (optional)
exit;
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
echo 'Hello World!';
// ...
The advantage of $_SERVER['HTTP_HOST']
is that its behavior is more well-defined than $_SERVER['SERVER_NAME']
. Contrast ??:
Contents of the Host: header from the current request, if there is one.
with:
The name of the server host under which the current script is executing.
Using a better defined interface like $_SERVER['HTTP_HOST']
means that more SAPIs will implement it using reliable well-defined behavior. (Unlike the other.) However, it is still totally SAPI dependent ??:
There is no guarantee that every web server will provide any of these [
$_SERVER
entries]; servers may omit some, or provide others not listed here.
To understand how to properly retrieve the host name, first and foremost you need to understand that a server which contains only code has no means of knowing (pre-requisite for verifying) its own name on the network. It needs to interface with a component that supplies it its own name. This can be done via:
local config file
local database
hardcoded source code
external request (curl)
client/attacker's Host:
request
etc
Usually its done via the local (SAPI) config file. Note that you have configured it correctly, e.g. in Apache ??:
A couple of things need to be 'faked' to make the dynamic virtual host look like a normal one.
The most important is the server name which is used by Apache to generate self-referential URLs, etc. It is configured with the
ServerName
directive, and it is available to CGIs via theSERVER_NAME
environment variable.The actual value used at run time is controlled by the UseCanonicalName setting.
With
UseCanonicalName Off
the server name comes from the contents of theHost:
header in the request. WithUseCanonicalName DNS
it comes from a reverse DNS lookup of the virtual host's IP address. The former setting is used for name-based dynamic virtual hosting, and the latter is used for** IP-based hosting.If Apache cannot work out the server name because there is no
Host:
header or the DNS lookup fails then the value configured withServerName
is used instead.
Java 7 Time API
DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm");
LocalTime lt = LocalTime.parse("14:10");
System.out.println(df.format(lt.plusMinutes(10)));
Within an htaccess file, the scope of the <Files>
directive only applies to that directory (I guess to avoid confusion when rules/directives in the htaccess of subdirectories get applied superceding ones from the parent).
So you can have:
<Files "log.txt">
Order Allow,Deny
Deny from all
</Files>
For Apache 2.4+, you'd use:
<Files "log.txt">
Require all denied
</Files>
In an htaccess file in your inscription
directory. Or you can use mod_rewrite to sort of handle both cases deny access to htaccess file as well as log.txt:
RewriteRule /?\.htaccess$ - [F,L]
RewriteRule ^/?inscription/log\.txt$ - [F,L]
5 step to do what you want if you made the pull request from a forked repository:
And everything is done, good luck!
if you have this failure and have other failures too, like "Unsupported Modules Detected: Compilation is not supported for following modules” maybe you need to solve them first and then it will be solved too. that's what happened to me.
Like this:
target:
$(shell cd ....); \
# ... commands execution in this directory
# ... no need to go back (using "cd -" or so)
# ... next target will be automatically in prev dir
Good luck!
.aar is a standard zip archive, the same one used in .jar. Just change the extension and, assuming it's not corrupt or anything, it should be fine.
If you needed to, you could extract it to your filesystem and then repackage it as a jar.
1) Rename it to .jar
2) Extract: jar xf filename.jar
3) Repackage: jar cf output.jar input-file(s)
<input type="text" name="name" id="event" onkeydown="return alphaOnly(event);" required />
function alphaOnly(event) {
var key = event.keyCode;`enter code here`
return ((key >= 65 && key <= 90) || key == 8);
};
Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.
note I changed the varchar2(32000) to CLOB
set serveroutput ON
CREATE TABLE testclob
(
id NUMBER,
c CLOB,
d VARCHAR2(4000)
);
DECLARE
reallybigtextstring CLOB := '123';
i INT;
BEGIN
WHILE Length(reallybigtextstring) <= 60000 LOOP
reallybigtextstring := reallybigtextstring
|| '000000000000000000000000000000000';
END LOOP;
INSERT INTO testclob
(id,
c,
d)
VALUES (0,
reallybigtextstring,
'done');
dbms_output.Put_line('I have finished inputting your clob: '
|| Length(reallybigtextstring));
END;
/
SELECT *
FROM testclob;
"I have finished inputting your clob: 60030"
This problem mainly caused by your connected username not have the access to the shell in GCE. So you use the following steps to solve this issue.
gcloud auth list
If you are using the correct login. please follow the below steps. otherwise use
gcloud auth revoke --all
gcloud auth login [your-iam-user]
and you get the token or it automatically detect the token.
gcloud compute --project "{projectid}" ssh --zone "{zone_name}" "{instance_name}" .
if you dont know this above line click to compute engine-> ssh dropdown arrow-> view google command-> copy
that code and use it
Now it update your metadata and it is available in your computer's folder Users->username
~/.ssh/google_compute_engine.ppk
~/.ssh/google_compute_engine.pub
Then you create a new ppk file using puttygen
and you give the username, which you want like my_work_space
. Then
save the publickey and privatekey in a folder.
Next step: Copy the public key data from puttygen and create new ssh key in gcloud metadata
cloud console ->compute engine->metadata->ssh key->add new item->paste the key and save it
and now return your shell commandline tool then enter
sudo chown -R my_work_space /home/my_work_space
now you connect this private key using sftp to anywhere. and it opens the files without showing the permission errors
:) happy hours.
Functions defined in classes (even within functions within classes) don't really pickle. However, this works:
def f(x):
return x*x
class calculate(object):
def run(self):
p = Pool()
return p.map(f, [1,2,3])
cl = calculate()
print cl.run()
Try to use switch case
statement but normally it's not the performance bottleneck.
A PDB file contains information used by the debugger. It is not required to run your application and it does not need to be included in your released version.
You can disable pdb files from being created in Visual Studio. If you are building from the command line or a script then omit the /Debug
switch.
Check if your form's action
URL includes the www
part of the domain, while the original page you have opened is viewed without www
.
Typically done for Canonical Urls..
I struggled for hours before stumbling upon this article and found the hint of Cross Domain.
textBox1.Background = Brushes.Blue;
textBox1.Foreground = Brushes.Yellow;
WPF Foreground and Background is of type System.Windows.Media.Brush
. You can set another color like this:
using System.Windows.Media;
textBox1.Background = Brushes.White;
textBox1.Background = new SolidColorBrush(Colors.White);
textBox1.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0, 0));
textBox1.Background = System.Windows.SystemColors.MenuHighlightBrush;
On Ubuntu 14.04 running Docker 1.3.1, I found the container root filesystem on the host machine in the following directory:
/var/lib/docker/devicemapper/mnt/<container id>/rootfs/
Full Docker version information:
Client version: 1.3.1
Client API version: 1.15
Go version (client): go1.3.3
Git commit (client): 4e9bbfa
OS/Arch (client): linux/amd64
Server version: 1.3.1
Server API version: 1.15
Go version (server): go1.3.3
Git commit (server): 4e9bbfa
You can use GREATEST function with not nullable fields. If one of this values (or both) can be NULL, don't use it (result can be NULL).
select
if(
fieldA is NULL,
if(fieldB is NULL, NULL, fieldB), /* second NULL is default value */
if(fieldB is NULL, field A, GREATEST(fieldA, fieldB))
) as maxValue
You can change NULL to your preferred default value (if both values is NULL).
Centos 7 php install comes with the ModSecurity package installed and enabled which prevents web access to phpMyAdmin. At the end of phpMyAdmin.conf, you should find
# This configuration prevents mod_security at phpMyAdmin directories from
# filtering SQL etc. This may break your mod_security implementation.
#
#<IfModule mod_security.c>
# <Directory /usr/share/phpMyAdmin/>
# SecRuleInheritance Off
# </Directory>
#</IfModule>
which gives you the answer to the problem. By adding
SecRuleEngine Off
in the block "Directory /usr/share/phpMyAdmin/", you can solve the 'denied access' to phpmyadmin, but you may create security issues.
You can use PowerShell to generate a self-signed certificate with the new-selfsignedcertificate cmdlet:
New-SelfSignedCertificate -DnsName "localhost" -CertStoreLocation "cert:\LocalMachine\My"
Note: makecert.exe is deprecated.
Cmdlet Reference: https://technet.microsoft.com/itpro/powershell/windows/pkiclient/new-selfsignedcertificate
In Java, generics are implemented by means of type erasure. For instance, the following code.
List<String> hello = List.of("a", "b");
String example = hello.get(0);
Is compiled to the following.
List hello = List.of("a", "b");
String example = (String) hello.get(0);
And List.of
is defined as.
static <E> List<E> of(E e1, E e2);
Which after type erasure becomes.
static List of(Object e1, Object e2);
The compiler has no idea what are generic types at runtime, so if you write something like this.
Object list = List.of("a", "b");
List<Integer> actualList = (List<Integer>) list;
Java Virtual Machine has no idea what generic types are while running a program, so this compiles and runs, as for Java Virtual Machine, this is a cast to List
type (this is the only thing it can verify, so it verifies only that).
But now add this line.
Integer hello = actualList.get(0);
And JVM will throw an unexpected ClassCastException
, as Java compiler inserted an implicit cast.
java.lang.ClassCastException: java.base/java.lang.String cannot be cast to java.base/java.lang.Integer
An unchecked
warning tells a programmer that a cast may cause a program to throw an exception somewhere else. Suppressing the warning with @SuppressWarnings("unchecked")
tells the compiler that the programmer believes the code to be safe and won't cause unexpected exceptions.
Why would you want to do that? Java type system isn't good enough to represent all possible type usage patterns. Sometimes you may know that a cast is safe, but Java doesn't provide a way to say so - to hide warnings like this, @SupressWarnings("unchecked")
can be used, so that a programmer can focus on real warnings. For instance, Optional.empty()
returns a singleton to avoid allocation of empty optionals that don't store a value.
private static final Optional<?> EMPTY = new Optional<>();
public static<T> Optional<T> empty() {
@SuppressWarnings("unchecked")
Optional<T> t = (Optional<T>) EMPTY;
return t;
}
This cast is safe, as the value stored in an empty optional cannot be retrieved so there is no risk of unexpected class cast exceptions.
Asking for purpose, there are different answers:
Using JSON to serialize objects (JavaScriptObjectNotation), each dictionary element maps to an indivual object property, so different entries defining a value for the same property has no meaning.
However, I came over the same question from a very specific use case: Writing JSON samples for API testing, I was wondering how to add comments into our JSON file without breaking the usability. The JSON spec does not know comments, so I came up with a very simple approach:
To use duplicate keys to comment our JSON samples. Example:
{
"property1" : "value1", "REMARK" : "... prop1 controls ...",
"property2" : "value2", "REMARK" : "... value2 raises an exception ...",
}
The JSON serializers which we are using have no problems with these "REMARK" duplicates and our application code simply ignores this little overhead.
So, even though there is no meaning on the application layer, these duplicates for us provide a valuable workaround to add comments to our testing samples without breaking the usability of the JSON.
You can limit the number of files uploaded by changing in dropezone.js
Dropzone.prototype.defaultOptions = { maxFiles: 10, }
To delete untracked on *nix without the purge extension you can use
hg pull
hg update -r MY_BRANCH -C
hg status -un|xargs rm
Which is using
update -r --rev REV revision
update -C --clean discard uncommitted changes (no backup)
status -u --unknown show only unknown (not tracked) files
status -n --no-status hide status prefix
\dt will list tables, and "\pset pager off" shows them in the same window, without switching to a separate one. Love that feature to death in dbshell.
imagine an excel page. With columns populated with formulas to calculate you tax return.
All the logic is done declared in the cells, the order of the calculation is by determine by formula itself rather than procedurally.
That is sort of what declarative programming is all about. You declare the problem space and the solution rather than the flow of the program.
Prolog is the only declarative language I've use. It requires a different kind of thinking but it's good to learn if just to expose you to something other than the typical procedural programming language.
use absolute path where the image actually exists (e.g) '/home/artitra/pictures/filename.jpg'
or create static folder inside your project directory like this
| templates
- static/
- images/
- yourimagename.jpg
then do this
app = Flask(__name__, static_url_path='/static')
then you can access your image like this in index.html
src ="/static/images/yourimage.jpg"
in img tag
I had same issue using different dependancy what helped me is to set scope to compile.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>compile</scope>
</dependency>
For Python 3.x, use input()
. For Python 2.x, use raw_input()
. Don't forget you can add a prompt string in your input()
call to create one less print statement. input("GUESS THAT NUMBER!")
.
If I understand your question correctly you want records from the settings database if they don't have a join accross to the character_settings table or if that joined record has character_id = 1.
You should therefore do
SELECT `settings`.*, `character_settings`.`value`
FROM (`settings`)
LEFT OUTER JOIN `character_settings`
ON `character_settings`.`setting_id` = `settings`.`id`
WHERE `character_settings`.`character_id` = '1' OR
`character_settings`.character_id is NULL
This should do it
replacements = {'zero':'0', 'temp':'bob', 'garbage':'nothing'}
with open('path/to/input/file') as infile, open('path/to/output/file', 'w') as outfile:
for line in infile:
for src, target in replacements.iteritems():
line = line.replace(src, target)
outfile.write(line)
EDIT: To address Eildosa's comment, if you wanted to do this without writing to another file, then you'll end up having to read your entire source file into memory:
lines = []
with open('path/to/input/file') as infile:
for line in infile:
for src, target in replacements.iteritems():
line = line.replace(src, target)
lines.append(line)
with open('path/to/input/file', 'w') as outfile:
for line in lines:
outfile.write(line)
Edit: If you are using Python 3.x, use replacements.items()
instead of replacements.iteritems()
A good explanation for this can be found here
To summarize : The number N in int(N) is often confused by the maximum size allowed for the column, as it does in the case of varchar(N).
But this is not the case with Integer data types- the number N in the parentheses is not the maximum size for the column, but simply a parameter to tell MySQL what width to display the column at when the table's data is being viewed via the MySQL console (when you're using the ZEROFILL attribute).
The number in brackets will tell MySQL how many zeros to pad incoming integers with. For example: If you're using ZEROFILL on a column that is set to INT(5) and the number 78 is inserted, MySQL will pad that value with zeros until the number satisfies the number in brackets. i.e. 78 will become 00078 and 127 will become 00127. To sum it up: The number in brackets is used for display purposes.
In a way, the number in brackets is kind of usless unless you're using the ZEROFILL attribute.
So the size for the int would remain same i.e., -2147483648 to 2147483648 for signed and 0 to 4294967295 for unsigned (~ 2.15 billions and 4.2 billions, which is one of the reasons why developers remain unaware of the story behind the Number N in parentheses, as it hardly affects the database unless it contains over 2 billions of rows), and in terms of bytes it would be 4 bytes.
For more information on Integer Types size/range, refer to MySQL Manual
I just want to mention a thing, there are many tools can do text processing, e.g. sort, cut, split, join, paste, comm, uniq, column, rev, tac, tr, nl, pr, head, tail.....
they are very handy but you have to learn their options etc.
A lazy way (not the best way) to learn text processing might be: only learn grep , sed and awk. with this three tools, you can solve almost 99% of text processing problems and don't need to memorize above different cmds and options. :)
AND, if you 've learned and used the three, you knew the difference. Actually, the difference here means which tool is good at solving what kind of problem.
a more lazy way might be learning a script language (python, perl or ruby) and do every text processing with it.
@object.as_json
as_json has very flexible way to configure complex object according to model relations
EXAMPLE
Model campaign belongs to shop and has one list
Model list has many list_tasks and each of list_tasks has many comments
We can get one json which combines all those data easily.
@campaign.as_json(
{
except: [:created_at, :updated_at],
include: {
shop: {
except: [:created_at, :updated_at, :customer_id],
include: {customer: {except: [:created_at, :updated_at]}}},
list: {
except: [:created_at, :updated_at, :observation_id],
include: {
list_tasks: {
except: [:created_at, :updated_at],
include: {comments: {except: [:created_at, :updated_at]}}
}
}
},
},
methods: :tags
})
Notice methods: :tags can help you attach any additional object which doesn't have relations with others. You just need to define a method with name tags in model campaign. This method should return whatever you need (e.g. Tags.all)
Official documentation for as_json
Before changing stored procedure please check what is the output of your current one. In SQL Server Management run following:
DECLARE @NewId int
EXEC @return_value = [dbo].[usp_InsertContract]
N'Gary',
@NewId OUTPUT
SELECT @NewId
See what it returns. This may give you some hints of why your out param is not filled.
#include<stdio.h>
#include<string.h>
#define filename "somefile.txt"
int main()
{
FILE *fp;
int count[26] = {0}, i, c;
char ch;
char alpha[27] = "abcdefghijklmnopqrstuwxyz";
fp = fopen(filename,"r");
if(fp == NULL)
printf("file not found\n");
while( (ch = fgetc(fp)) != EOF) {
c = 0;
while(alpha[c] != '\0') {
if(alpha[c] == ch) {
count[c]++;
}
c++;
}
}
for(i = 0; i<26;i++) {
printf("character %c occured %d number of times\n",alpha[i], count[i]);
}
return 0;
}
Add following css to your .validate method to change the css or functionality
errorElement: "div", wrapper: "div", errorPlacement: function(error, element) { offset = element.offset(); error.insertAfter(element) error.css('color','red'); }
If you are not using eclipse. Then you can change the ant java property directly on the file as mentioned here.
http://pissedoff-techie.blogspot.in/2014/09/ant-picks-up-incorrect-java-version.html
I'm resurrecting the dead here, but because a range can be defined as "A:A", using a for each loop ends up with a potential infinite loop. The solution, as far as I know, is to use the Do Until
loop.
Do Until Selection.Value = ""
Rem Do things here...
Loop
I landed on this question as I was looking for a clean iterator of columns only (Series
, no names).
Unless I am mistaken, there is no such thing, which, if true, is a bit annoying. In particular, one would sometimes like to assign a few individual columns (Series) to variables, e.g.:
x, y = df[['x', 'y']] # does not work
There is df.items()
that gets close, but it gives an iterator of tuples (column_name, column_series)
. Interestingly, there is a corresponding df.keys()
which returns df.columns
, i.e. the column names as an Index
, so a, b = df[['x', 'y']].keys()
assigns properly a='x'
and b='y'
. But there is no corresponding df.values()
, and for good reason, as df.values
is a property and returns the underlying numpy
array.
One (inelegant) way is to do:
x, y = (v for _, v in df[['x', 'y']].items())
but it's less pythonic than I'd like.
The other answers cover what it is quite well. I'm not repeating that. Just some points that might be useful to you.
Usually, memoisation is an operation you can apply on any function that computes something (expensive) and returns a value. Because of this, it's often implemented as a decorator. The implementation is straightforward and it would be something like this
memoised_function = memoise(actual_function)
or expressed as a decorator
@memoise
def actual_function(arg1, arg2):
#body
You can run easy_install to install python packages in your home directory even without root access. There's a standard way to do this using site.USER_BASE which defaults to something like $HOME/.local or $HOME/Library/Python/2.7/bin and is included by default on the PYTHONPATH
To do this, create a .pydistutils.cfg in your home directory:
cat > $HOME/.pydistutils.cfg <<EOF
[install]
user=1
EOF
Now you can run easy_install without root privileges:
easy_install boto
Alternatively, this also lets you run pip without root access:
pip install boto
This works for me.
Source from Wesley Tanaka's blog : http://wtanaka.com/node/8095
Simply use this:
List<string> list = new List<string>() { "single value" };
You can even omit the () braces:
List<string> list = new List<string> { "single value" };
Update: of course this also works for more than one entry:
List<string> list = new List<string> { "value1", "value2", ... };
It depends on what the problem with the arguments is.
If the argument has the wrong type, raise a TypeError. For example, when you get a string instead of one of those Booleans.
if not isinstance(save, bool):
raise TypeError(f"Argument save must be of type bool, not {type(save)}")
Note, however, that in Python we rarely make any checks like this. If the argument really is invalid, some deeper function will probably do the complaining for us. And if we only check the boolean value, perhaps some code user will later just feed it a string knowing that non-empty strings are always True. It might save him a cast.
If the arguments have invalid values, raise ValueError. This seems more appropriate in your case:
if recurse and not save:
raise ValueError("If recurse is True, save should be True too")
Or in this specific case, have a True value of recurse imply a True value of save. Since I would consider this a recovery from an error, you might also want to complain in the log.
if recurse and not save:
logging.warning("Bad arguments in import_to_orm() - if recurse is True, so should save be")
save = True
128 characters. This is the max length of the sysname
datatype (nvarchar(128)
).
Forgot to put the variable in the sql statement without quotations.
$update_query =
"UPDATE db.tablename SET insert_time=NOW() WHERE username='" .$somename."'";
This will return in hh:mm:ss format
public static string ConvertTime(long secs)
{
TimeSpan ts = TimeSpan.FromSeconds(secs);
string displayTime = $"{ts.Hours}:{ts.Minutes}:{ts.Seconds}";
return displayTime;
}
The usual way to check whether something can be converted to an int
is to try
it and see, following the EAFP principle:
try:
int_value = int(string_value)
except ValueError:
# it wasn't an int, do something appropriate
else:
# it was an int, do something appropriate
So, in your case:
for item in mylist:
try:
int_value = int(item)
except ValueError:
pass
else:
mynewlist.append(item) # or append(int_value) if you want numbers
In most cases, a loop around some trivial code that ends with mynewlist.append(item)
can be turned into a list comprehension, generator expression, or call to map
or filter
. But here, you can't, because there's no way to put a try
/except
into an expression.
But if you wrap it up in a function, you can:
def raises(func, *args, **kw):
try:
func(*args, **kw)
except:
return True
else:
return False
mynewlist = [item for item in mylist if not raises(int, item)]
… or, if you prefer:
mynewlist = filter(partial(raises, int), item)
It's cleaner to use it this way:
def raises(exception_types, func, *args, **kw):
try:
func(*args, **kw)
except exception_types:
return True
else:
return False
This way, you can pass it the exception (or tuple of exceptions) you're expecting, and those will return True
, but if any unexpected exceptions are raised, they'll propagate out. So:
mynewlist = [item for item in mylist if not raises(ValueError, int, item)]
… will do what you want, but:
mynewlist = [item for item in mylist if not raises(ValueError, item, int)]
… will raise a TypeError
, as it should.
You can use from pkg.components.core import GameLoopEvents
, for example I use pycharm, the below is my project structure image, I just import from the root package, then it works:
if you just want the number of occurences then you can do this, $ grep -c "string_to_count" file_name
Here's how I live search a html table:
<input type='text' onkeyup="filterTo(this.value, 'myTable')" placeholder='Search...'>
<table id='myTable'>...</table>
function filterTo(input, table) {
var tr = document.getElementById(table).getElementsByTagName('tr');
for (var i = 1; i < tr.length; i++) {
var td = tr[i].getElementsByTagName('td');
var hide = true;
for (var j=0; j<td.length; j++) {
if (td[j].innerHTML.toUpperCase().indexOf(input.toUpperCase()) > -1) { hide=false; break }
}
tr[i].style.display = hide ? 'none' : '';
} }
Best thing to use is HTMLAgilityPack. You can also look into using Fizzler or CSQuery depending on your needs for selecting the elements from the retrieved page. Using LINQ or Regukar Expressions is just to error prone, especially when the HTML can be malformed, missing closing tags, have nested child elements etc.
You need to stream the page into an HtmlDocument object and then select your required element.
// Call the page and get the generated HTML
var doc = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlNode.ElementsFlags["br"] = HtmlAgilityPack.HtmlElementFlag.Empty;
doc.OptionWriteEmptyNodes = true;
try
{
var webRequest = HttpWebRequest.Create(pageUrl);
Stream stream = webRequest.GetResponse().GetResponseStream();
doc.Load(stream);
stream.Close();
}
catch (System.UriFormatException uex)
{
Log.Fatal("There was an error in the format of the url: " + itemUrl, uex);
throw;
}
catch (System.Net.WebException wex)
{
Log.Fatal("There was an error connecting to the url: " + itemUrl, wex);
throw;
}
//get the div by id and then get the inner text
string testDivSelector = "//div[@id='test']";
var divString = doc.DocumentNode.SelectSingleNode(testDivSelector).InnerHtml.ToString();
[EDIT] Actually, scrap that. The simplest method is to use FizzlerEx, an updated jQuery/CSS3-selectors implementation of the original Fizzler project.
Code sample directly from their site:
using HtmlAgilityPack;
using Fizzler.Systems.HtmlAgilityPack;
//get the page
var web = new HtmlWeb();
var document = web.Load("http://example.com/page.html");
var page = document.DocumentNode;
//loop through all div tags with item css class
foreach(var item in page.QuerySelectorAll("div.item"))
{
var title = item.QuerySelector("h3:not(.share)").InnerText;
var date = DateTime.Parse(item.QuerySelector("span:eq(2)").InnerText);
var description = item.QuerySelector("span:has(b)").InnerHtml;
}
I don't think it can get any simpler than that.
As Chris said before me, just an a
should override. For example:
a { color:red; }
a:hover { color:blue; }
.nav a { color:green; }
In this instance the .nav a
would ALWAYS be green, the :hover wouldn't apply to it.
If there's some other rule affecting it, you COULD use !important
, but you shouldn't. It's a bad habit to fall into.
.nav a { color:green !important; } /*I'm a bad person and shouldn't use !important */
Then it'll always be green, irrelevant of any other rule.
Create a linked server to the source server. The easiest way is to right click "Linked Servers" in Management Studio; it's under Management -> Server Objects.
Then you can copy the table using a 4-part name, server.database.schema.table
:
select *
into DbName.dbo.NewTable
from LinkedServer.DbName.dbo.OldTable
This will both create the new table with the same structure as the original one and copy the data over.
On linux: print('\007')
will make the system bell sound.
if (!empty($web)) {
?>
<span class="field-label">Website: </span><a href="http://<?php the_field('website'); ?>" target="_blank"><?php the_field('website'); ?></a>
<?php
} else { echo "Niente";}
For >= Python3.4:
import importlib
importlib.reload(module)
For <= Python3.3:
import imp
imp.reload(module)
For Python2.x:
Use the in-built reload()
function.
reload(module)
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener
{
private JLabel label;
private JTextField field;
public Test()
{
super("The title");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setPreferredSize(new Dimension(400, 90));
((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13) );
setLayout(new FlowLayout());
JButton btn = new JButton("Change");
btn.setActionCommand("myButton");
btn.addActionListener(this);
label = new JLabel("flag");
field = new JTextField(5);
add(field);
add(btn);
add(label);
pack();
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("myButton"))
{
label.setText(field.getText());
}
}
public static void main(String[] args)
{
new Test();
}
}
Once you have your PropertyInfo
(from GetProperty
), you need to call GetValue
and pass in the instance that you want to get the value from. In your case:
d.GetType().GetProperty("value2").GetValue(d, null);
With:
global index_add_counter
You are not defining, just declaring so it's like saying there is a global index_add_counter
variable elsewhere, and not create a global called index_add_counter
. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global
keyword and initialize your variable:
index_add_counter = 0
Now you can import it with:
from app import index_add_counter
The construction:
global index_add_counter
is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:
index_add_counter = 0
def test():
global index_add_counter # means: in this scope, use the global name
print(index_add_counter)
If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.
I had this issue under Windows 10 when using Visual Studio 2015 Professional, while Visual Studio 2015 Express worked! Under Windows 7, both Visual Studio versions used to work.
New projects created from the Visual Studio 2015 Professional IDE successfully compile, but CMake would fail to find the compiler reporting:
The C compiler identification is unknown
The CXX compiler identification is unknown
I upgraded CMake from 3.4.1 to 3.11.4, and now the problem is gone.
Easiest way to check if they are authenticated is Request.User.IsAuthenticated
I think (from memory)
Yes. Try the following in your python interpreter:
and
>>>False and 3/0
False
>>>True and 3/0
ZeroDivisionError: integer division or modulo by zero
or
>>>True or 3/0
True
>>>False or 3/0
ZeroDivisionError: integer division or modulo by zero
I'm using httpie
$ pip install httpie
And you can use it like this
$ http PUT localhost:8001/api/v1/ports/my
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 93
Content-Type: application/json
Date: Fri, 06 Mar 2015 02:46:41 GMT
Server: nginx/1.4.6 (Ubuntu)
X-Powered-By: HHVM/3.5.1
{
"data": [],
"message": "Failed to manage ports in 'my'. Request body is empty",
"success": false
}
The code you listed kind of looks like a Lehmer RNG. If this is the case, then 2147483647
is the largest 32-bit signed integer, 2147483647
is the largest 32-bit prime, and 48271
is a full-period multiplier that is used to generate the numbers.
If this is true, you could modify RandomNumberGenerator
to take in an extra parameter seed
, and then set this.seed
to seed
; but you'd have to be careful to make sure the seed would result in a good distribution of random numbers (Lehmer can be weird like that) -- but most seeds will be fine.
To lose the focus when other view is touched , both views should be set as view.focusableInTouchMode(true).
But it seems that use focuses in touch mode are not recommended. Please take a look here: http://android-developers.blogspot.com/2008/12/touch-mode.html
Adding this answer for people like me for whom a TRUE/FALSE answer is perfectly acceptable
OR(IF(ISNUMBER(SEARCH($G$1:$G$7,A1)),TRUE,FALSE))
or case-sensitive
OR(IF(ISNUMBER(FIND($G$1:$G$7,A1)),TRUE,FALSE))
Where the range for the search terms is G1:G7
Remember to press CTRL+SHIFT+ENTER
execl("/home/vlc",
"/home/vlc", "/home/my movies/the movie i want to see.mkv",
(char*) NULL);
You need to specify all arguments, included argv[0]
which isn't taken from the executable.
Also make sure the final NULL
gets cast to char*
.
Details are here: http://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html
You can approach it from either an "allow list" or a "block list" way:
// Block list
// Remove the values you don't want
var result = _.omit(credentials, ['age']);
// Allow list
// Only allow certain values
var result = _.pick(credentials, ['fname', 'lname']);
If it's reusable business logic, you can partial it out as well:
// Partial out a "block list" version
var clean = _.partial(_.omit, _, ['age']);
// and later
var result = clean(credentials);
A similar approach can be achieved without Lodash:
const transform = (obj, predicate) => {
return Object.keys(obj).reduce((memo, key) => {
if(predicate(obj[key], key)) {
memo[key] = obj[key]
}
return memo
}, {})
}
const omit = (obj, items) => transform(obj, (value, key) => !items.includes(key))
const pick = (obj, items) => transform(obj, (value, key) => items.includes(key))
// Partials
// Lazy clean
const cleanL = (obj) => omit(obj, ['age'])
// Guarded clean
const cleanG = (obj) => pick(obj, ['fname', 'lname'])
// "App"
const credentials = {
fname:"xyz",
lname:"abc",
age:23
}
const omitted = omit(credentials, ['age'])
const picked = pick(credentials, ['age'])
const cleanedL = cleanL(credentials)
const cleanedG = cleanG(credentials)
I always use pseudo elements :before
and :after
for changing the appearance of checkboxes and radio buttons. it's works like a charm.
Refer this link for more info
Steps
visibility:hidden
or opacity:0
or position:absolute;left:-9999px
etc.:before
element and pass either an empty or a non-breaking space '\00a0'
;:checked
state, pass the unicode content: "\2713"
, which is a checkmark;:focus
style to make the checkbox accessible.Here is how I did it.
.box {_x000D_
background: #666666;_x000D_
color: #ffffff;_x000D_
width: 250px;_x000D_
padding: 10px;_x000D_
margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
margin: 1.5em 0;_x000D_
padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
visibility: hidden;_x000D_
}_x000D_
label {_x000D_
cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
border: 1px solid #333;_x000D_
content: "\00a0";_x000D_
display: inline-block;_x000D_
font: 16px/1em sans-serif;_x000D_
height: 16px;_x000D_
margin: 0 .25em 0 0;_x000D_
padding: 0;_x000D_
vertical-align: top;_x000D_
width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
background: #fff;_x000D_
color: #333;_x000D_
content: "\2713";_x000D_
text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
<div class="box">_x000D_
<p>_x000D_
<input type="checkbox" id="c1" name="cb">_x000D_
<label for="c1">Option 01</label>_x000D_
</p>_x000D_
<p>_x000D_
<input type="checkbox" id="c2" name="cb">_x000D_
<label for="c2">Option 02</label>_x000D_
</p>_x000D_
<p>_x000D_
<input type="checkbox" id="c3" name="cb">_x000D_
<label for="c3">Option 03</label>_x000D_
</p>_x000D_
</div>_x000D_
</div>
_x000D_
Much more stylish using :before
and :after
body{_x000D_
font-family: sans-serif; _x000D_
}_x000D_
_x000D_
.container {_x000D_
margin-top: 50px;_x000D_
margin-left: 20px;_x000D_
margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
width: 100%;_x000D_
margin: 15px auto;_x000D_
position: relative;_x000D_
display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
width: auto;_x000D_
opacity: 0.00000001;_x000D_
position: absolute;_x000D_
left: 0;_x000D_
margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
content: '';_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
margin: 4px;_x000D_
width: 22px;_x000D_
height: 22px;_x000D_
transition: transform 0.28s ease;_x000D_
border-radius: 3px;_x000D_
border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
content: '';_x000D_
display: block;_x000D_
width: 10px;_x000D_
height: 5px;_x000D_
border-bottom: 2px solid #7bbe72;_x000D_
border-left: 2px solid #7bbe72;_x000D_
-webkit-transform: rotate(-45deg) scale(0);_x000D_
transform: rotate(-45deg) scale(0);_x000D_
transition: transform ease 0.25s;_x000D_
will-change: transform;_x000D_
position: absolute;_x000D_
top: 12px;_x000D_
left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
-webkit-transform: rotate(-45deg) scale(1);_x000D_
transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
min-height: 34px;_x000D_
display: block;_x000D_
padding-left: 40px;_x000D_
margin-bottom: 0;_x000D_
font-weight: normal;_x000D_
cursor: pointer;_x000D_
vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
-webkit-transform: translateY(-50%);_x000D_
transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
<div class="checkbox">_x000D_
<input type="checkbox" id="checkbox" name="" value="">_x000D_
<label for="checkbox"><span>Checkbox</span></label>_x000D_
</div>_x000D_
_x000D_
<div class="checkbox">_x000D_
<input type="checkbox" id="checkbox2" name="" value="">_x000D_
<label for="checkbox2"><span>Checkbox</span></label>_x000D_
</div>_x000D_
</div>
_x000D_
The pattern you want is something like this in multiline mode:
^\s*$
Explanation:
^
is the beginning of string anchor.$
is the end of string anchor.\s
is the whitespace character class.*
is zero-or-more repetition of.In multiline mode, ^
and $
also match the beginning and end of the line.
You can also check if a given string line
is "blank" (i.e. containing only whitespaces) by trim()
-ing it, then checking if the resulting string isEmpty()
.
In Java, this would be something like this:
if (line.trim().isEmpty()) {
// line is "blank"
}
The regex solution can also be simplified without anchors (because of how matches
is defined in Java) as follows:
if (line.matches("\\s*")) {
// line is "blank"
}
String String.trim()
boolean String.isEmpty()
true
if, and only if, length()
is 0
. boolean String.matches(String regex)
Answered here: Convert an image to grayscale in HTML/CSS
You don't even need to use two images which sounds like a pain or an image manipulation library, you can do it with cross browser support (current versions) and just use CSS. This is a progressive enhancement approach which just falls back to color versions on older browsers:
img {
filter: url(filters.svg#grayscale);
/* Firefox 3.5+ */
filter: gray;
/* IE6-9 */
-webkit-filter: grayscale(1);
/* Google Chrome & Safari 6+ */
}
img:hover {
filter: none;
-webkit-filter: none;
}
and filters.svg file like this:
<svg xmlns="http://www.w3.org/2000/svg">
<filter id="grayscale">
<feColorMatrix type="matrix" values="0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0" />
</filter>
</svg>
You can trigger Lambda functions directly from other Lambda functions directly in an asynchronous manner.
https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#invocation-async-destinations
Set height and width parameters in CSS file
.ImageStyle{_x000D_
_x000D_
max-height: 17vw;_x000D_
min-height: 17vw;_x000D_
max-width:17vw;_x000D_
min-width: 17vw;_x000D_
_x000D_
}
_x000D_
Not least important is why these symbols occur in url. See https://www.php.net/manual/en/function.parse-str.php#76792, specifically:
parse_str('foo[]=1&foo[]=2&foo[]=3', $bar);
the above produces:
$bar = ['foo' => ['1', '2', '3'] ];
and what is THE method to separate query vars in arrays (in php, at least).
Perl solutions:
perl -lpe 'print "Project_Name=sowstest" if $. == 8' file
-l
strips newlines and adds them back in, eliminating the need for "\n"-p
loops over the input file, printing every line-e
executes the code in single quotes$.
is the line number
perl -slpe 'print $s if $. == $n' -- -n=8 -s="Project_Name=sowstest" file
-s
enables a rudimentary argument parser--
prevents -n and -s from being parsed by the standard perl argument parserperl -lpe 'BEGIN{$n=shift; $s=shift}; print $s if $. == $n' 8 "Project_Name=sowstest" file
setenv n 8 ; setenv s "Project_Name=sowstest"
echo $n ; echo $s
perl -slpe 'print $ENV{s} if $. == $ENV{n}' file
ENV
is the hash which contains all environment variables
perl -MGetopt::Std -lpe 'BEGIN{getopt("ns",\%o)}; print $o{s} if $. == $o{n}' -- -n 8 -s "Project_Name=sowstest" file
perl -MGetopt::Long -lpe 'BEGIN{GetOptions(\%o,"line=i","string=s")}; print $o{string} if $. == $o{line}' -- --line 8 --string "Project_Name=sowstest" file
Getopt is the recommended standard-library solution.
This may be overkill for one-line perl scripts, but it can be done
The specific Date
constructor is deprecated, and Calendar
should be used instead.
The JavaDoc
for Date describes which constructors are deprecated and how to replace them using a Calendar
.
It has advantage when you use ASP.Net MVC. When you use HTML helper to build some control in view it uses property names in name attribure of html input:
@Html.TextBoxFor(m => m.CanBeRenamed)
It makes something like that:
<input type="text" name="CanBeRenamed" />
So now, if you need to validate your property in Validate method you can do this:
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
if (IsNotValid(CanBeRenamed)) {
yield return new ValidationResult(
$"Property {nameof(CanBeRenamed)} is not valid",
new [] { $"{nameof(CanBeRenamed)}" })
}
}
In case if you rename you property using refactoring tools, your validation will not be broken.
Update table set column = (select...)
never worked for me since set only expects 1 value - SQL Error: ORA-01427: single-row subquery returns more than one row.
here's the solution:
BEGIN
For i in (select id, name, desc from table1)
LOOP
Update table2 set name = i.name, desc = i.desc where id = i.id;
END LOOP;
END;
That's how exactly you run it on SQLDeveloper worksheet. They say it's slow but that's the only solution that worked for me on this case.
You can try below method,
SELECT EXTRACT(YEAR FROM APP_SUBMITTED_DATE)-EXTRACT(YEAR FROM BIRTH_DATE) FROM SOME_TABLE;
It will compare years and give age accordingly.
You can also use SYSDATE
instead of APP_SUBMITTED_DATE
.
Regards.
In controller you can use MvcHtmlString
public class HomeController : Controller
{
public ActionResult Index()
{
string rawHtml = "<HTML></HTML>";
ViewBag.EncodedHtml = MvcHtmlString.Create(rawHtml);
return View();
}
}
In your View you can simply use that dynamic property which you set in your Controller like below
<div>
@ViewBag.EncodedHtml
</div>
When you are in the shell directory for the device. Just run
su - root
Then you should be able to access the data/ folder.
A Function will not work, nor is it necessary:
Sub OpenWorkbook()
Dim r1 As Range, r2 As Range, o As Workbook
Set r1 = ThisWorkbook.Sheets("Sheet1").Range("A1")
Set o = Workbooks.Open(Filename:="C:\TestFolder\ABC.xlsx")
Set r2 = ActiveWorkbook.Sheets("Sheet1").Range("B2")
[r1] = [r2]
o.Close
End Sub
Use the below code. I hope it help for you.
NSString *needToChangeStr=@"BOOK";
NSString *display_string=[NSString stringWithFormat:@"This is %@",book];
NSMutableAttributedString *attri_str=[[NSMutableAttributedString alloc]initWithString:display_string];
int begin=[display_string length]-[needToChangeStr length];
int end=[needToChangeStr length];
[attri_str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:30] range:NSMakeRange(begin, end)];
See at the bottom of this page at Python wiki, there are at least 2 options to "unescape" html.
from zipfile import ZipFile
ZipFile("YOURZIP.zip").extractall("YOUR_DESTINATION_DIRECTORY")
The directory where you will extract your files doesn't need to exist before, you name it at this moment
YOURZIP.zip is the name of the zip if your project is in the same directory. If not, use the PATH i.e : C://....//YOURZIP.zip
Think to escape the /
by an other /
in the PATH
If you have a permission denied
try to launch your ide (i.e: Anaconda) as administrator
YOUR_DESTINATION_DIRECTORY will be created in the same directory than your project
Posting another alternative to be more complete. When I tried the "pre" based answers, they added extra vertical line breaks as well.
Each tab can be converted to a sequence non-breaking spaces which require no wrapping.
" "
This is not recommended for repeated/extensive use within a page. A div margin/padding approach would appear much cleaner.
Well, you have [[
and ]]
to go to the start and end of file. This works in vi.
I tried this: Create a file header.html like
<!-- Meta -->
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<!-- JS -->
<script type="text/javascript" src="js/lib/jquery-1.11.1.min.js" ></script>
<script type="text/javascript" src="js/lib/angular.min.js"></script>
<script type="text/javascript" src="js/lib/angular-resource.min.js"></script>
<script type="text/javascript" src="js/lib/angular-route.min.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css">
<title>Your application</title>
Now include header.html in your HTML pages like:
<head>
<script type="text/javascript" src="js/lib/jquery-1.11.1.min.js" ></script>
<script>
$(function(){ $("head").load("header.html") });
</script>
</head>
Works perfectly fine.
On modern hardware, a binary tree is nearly always suboptimal due to bad cache and space behaviour. This also goes for the (semi)balanced variants. If you find them, it is where performance doesn't count (or is dominated by the compare function), or more likely for historic or ignorance reasons.
you have to rename each column
SELECT col1 as MyCol1,
col2 as MyCol2,
.......
FROM `foobar`
When the LinkButton Enabled property is false it just renders a standard hyperlink. When you right click any disabled hyperlink you don't get the option to open in anything.
try
lbnkVidTtile1.Enabled = true;
I'm sorry if I misunderstood. Could I just make sure that you understand the purpose of a LinkButton? It is to give the appearance of a HyperLink but the behaviour of a Button. This means that it will have an anchor tag, but there is JavaScript wired up that performs a PostBack to the page. If you want to link to another page then it is recommended here that you use a standard HyperLink control.
I just ran out of stack at work, it was a database and it was running some threads, basically the previous developer had thrown a big array on the stack, and the stack was low anyway. The software was compiled using Microsoft Visual Studio 2015.
Even though the thread had run out of stack, it silently failed and continued on, it only stack overflowed when it came to access the contents of the data on the stack.
The best advice i can give is to not declare arrays on the stack - especially in complex applications and particularly in threads, instead use heap. That's what it's there for ;)
Also just keep in mind it may not fail immediately when declaring the stack, but only on access. My guess is that the compiler declares stack under windows "optimistically", i.e. it will assume that the stack has been declared and is sufficiently sized until it comes to use it and then finds out that the stack isn't there.
Different operating systems may have different stack declaration policies. Please leave a comment if you know what these policies are.
Your calls are made recursively which pushes functions on to the stack infinitely that causes max call stack exceeded error due to recursive behavior. Instead try using setTimeout which is a callback.
Also based on your markup your selector is wrong. it should be #advisersDiv
function fadeIn() {
$('#pulseDiv').find('div#advisersDiv').delay(400).addClass("pulse");
setTimeout(fadeOut,1); //<-- Provide any delay here
};
function fadeOut() {
$('#pulseDiv').find('div#advisersDiv').delay(400).removeClass("pulse");
setTimeout(fadeIn,1);//<-- Provide any delay here
};
fadeIn();
I have hard time when trying to
So I made 2020 answer here
My directory looks like this
+-- docker-compose.yml
+-- mongo-entrypoint
+-- entrypoint.js
My docker-compose.yml
looks like this
version: '3.4'
services:
mongo-container:
# If you need to connect to your db from outside this container
network_mode: host
image: mongo:4.2
environment:
- MONGO_INITDB_ROOT_USERNAME=admin
- MONGO_INITDB_ROOT_PASSWORD=pass
ports:
- "27017:27017"
volumes:
- "$PWD/mongo-entrypoint/:/docker-entrypoint-initdb.d/"
command: mongod
Please change admin
and pass
with your need.
Inside mongo-entrypoint
, I have entrypoint.js
file with this content:
var db = connect("mongodb://admin:pass@localhost:27017/admin");
db = db.getSiblingDB('new_db'); // we can not use "use" statement here to switch db
db.createUser(
{
user: "user",
pwd: "pass",
roles: [ { role: "readWrite", db: "new_db"} ],
passwordDigestor: "server",
}
)
Here again you need to change admin:pass
to your root mongo credentials in your docker-compose.yml
that you stated before. In additional you need to change new_db
, user
, pass
to your new database name and credentials that you need.
Now you can:
docker-compose up -d
And connect to this db from localhost, please note that I already have mongo cli, you can install it or you can exec to the container above to use mongo
command:
mongo new_db -u user -p pass
Or you can connect from other computer
mongo host:27017/new_db -u user -p pass
My git repository: https://github.com/sexydevops/docker-compose-mongo
Hope it can help someone, I lost my afternoon for this ;)
To answer your questions there are simply two steps:-
git pull
git checkout -- .
.This will show the latest changes in your local repo from your remote git repo. cleaning all the local unstaged changes.Please note git checkout -- .
will discard all your changes in the local working directory. In case you want to discard any change for selective file use git checkout -- <filename>
. And in case you don't want to lose your unstaged changes use git stash
as it will clean your local working directory of all the unstaged changes while saving it if you need it in the future.
You have several options:
JS
var json_arr = JSON.stringify(arr);
PHP
$arr = json_decode($_POST['arr']);
Sending an array via FormData
.
JS
// Use <#> or any other delimiter you want
var serial_arr = arr.join("<#>");
PHP
$arr = explode("<#>", $_POST['arr']);
When I use postman to send a file which is 5.6M to an external network, I faced the same issue. The same action is succeeded on my own computer and local testing environment.
After checking all the server configs and HTTP headers, I found that the reason is Postman may have some trouble simulating requests to external HTTP requests. Finally, I did the sendfile request on the chrome HTML page successfully. Just as a reference :)
You may need the following two functions: pad
- to pad(when doing encryption) and unpad
- to unpad (when doing decryption) when the length of input is not a multiple of BLOCK_SIZE.
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[:-ord(s[len(s)-1:])]
So you're asking the length of key? You can use the md5sum of the key rather than use it directly.
More, according to my little experience of using PyCrypto, the IV is used to mix up the output of a encryption when input is same, so the IV is chosen as a random string, and use it as part of the encryption output, and then use it to decrypt the message.
And here's my implementation, hope it will be useful for you:
import base64
from Crypto.Cipher import AES
from Crypto import Random
class AESCipher:
def __init__( self, key ):
self.key = key
def encrypt( self, raw ):
raw = pad(raw)
iv = Random.new().read( AES.block_size )
cipher = AES.new( self.key, AES.MODE_CBC, iv )
return base64.b64encode( iv + cipher.encrypt( raw ) )
def decrypt( self, enc ):
enc = base64.b64decode(enc)
iv = enc[:16]
cipher = AES.new(self.key, AES.MODE_CBC, iv )
return unpad(cipher.decrypt( enc[16:] ))
If you're encoding a string to put in a URL component (a querystring parameter), you should call encodeURIComponent
.
If you're encoding an existing URL, call encodeURI
.
If you are splitting a string in Lua, you should try the string.gmatch() or string.sub() methods. Use the string.sub() method if you know the index you wish to split the string at, or use the string.gmatch() if you will parse the string to find the location to split the string at.
Example using string.gmatch() from Lua 5.1 Reference Manual:
t = {}
s = "from=world, to=Lua"
for k, v in string.gmatch(s, "(%w+)=(%w+)") do
t[k] = v
end
I know this is not the problem you had, however another reason this could happen is you have a non background thread open in your application.
using System;
using System.Threading;
using System.Windows.Forms;
namespace Sandbox_Form
{
static class Program
{
private static Thread thread;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
thread = new Thread(BusyWorkThread);
thread.IsBackground = false;
thread.Start();
Application.Run(new Form());
}
public static void BusyWorkThread()
{
while (true)
{
Thread.Sleep(1000);
}
}
}
}
When IsBackground
is false
it will keep your program open till the thread completes, if you set IsBackground
to true
the thread will not keep the program open. Things like BackgroundWoker
, ThreadPool
, and Task
all internally use a thread with IsBackground
set to true
.
Angular RC5 & RC6
If you are getting the above mentioned error in your Jasmine tests, it is most likely because you have to declare the unrenderable component in your TestBed.configureTestingModule({})
.
The TestBed configures and initializes an environment for unit testing and provides methods for mocking/creating/injecting components and services in unit tests.
If you don't declare the component before your unit tests are executed, Angular will not know what <courses></courses>
is in your template file.
Here is an example:
import {async, ComponentFixture, TestBed} from "@angular/core/testing";
import {AppComponent} from "../app.component";
import {CoursesComponent} from './courses.component';
describe('CoursesComponent', () => {
let component: CoursesComponent;
let fixture: ComponentFixture<CoursesComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent,
CoursesComponent
],
imports: [
BrowserModule
// If you have any other imports add them here
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CoursesComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
As at PHP 7.3:
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BEARER);
curl_setopt($ch,CURLOPT_XOAUTH2_BEARER,$bearerToken);
Use where_in()
$ids = array('20', '15', '22', '46', '86');
$this->db->where_in('id', $ids );
Make sudo run a shell, like this:
sudo sh -c "echo foo > ~root/out"
As a follow on, you could select "all nodes with a particular attribute" like this:
//*[@id='4']
Cross-browser URL parsing, works around the relative path problem for IE 6, 7, 8 and 9:
function ParsedUrl(url) {
var parser = document.createElement("a");
parser.href = url;
// IE 8 and 9 dont load the attributes "protocol" and "host" in case the source URL
// is just a pathname, that is, "/example" and not "http://domain.com/example".
parser.href = parser.href;
// IE 7 and 6 wont load "protocol" and "host" even with the above workaround,
// so we take the protocol/host from window.location and place them manually
if (parser.host === "") {
var newProtocolAndHost = window.location.protocol + "//" + window.location.host;
if (url.charAt(1) === "/") {
parser.href = newProtocolAndHost + url;
} else {
// the regex gets everything up to the last "/"
// /path/takesEverythingUpToAndIncludingTheLastForwardSlash/thisIsIgnored
// "/" is inserted before because IE takes it of from pathname
var currentFolder = ("/"+parser.pathname).match(/.*\//)[0];
parser.href = newProtocolAndHost + currentFolder + url;
}
}
// copies all the properties to this object
var properties = ['host', 'hostname', 'hash', 'href', 'port', 'protocol', 'search'];
for (var i = 0, n = properties.length; i < n; i++) {
this[properties[i]] = parser[properties[i]];
}
// pathname is special because IE takes the "/" of the starting of pathname
this.pathname = (parser.pathname.charAt(0) !== "/" ? "/" : "") + parser.pathname;
}
Usage (demo JSFiddle here):
var myUrl = new ParsedUrl("http://www.example.com:8080/path?query=123#fragment");
Result:
{
hash: "#fragment"
host: "www.example.com:8080"
hostname: "www.example.com"
href: "http://www.example.com:8080/path?query=123#fragment"
pathname: "/path"
port: "8080"
protocol: "http:"
search: "?query=123"
}
This is a modified answer based on the accepted answer wherein the data would be coming from JSON.
JSON Data Ouptut:
0 :{emails: "SAMPLE Co., [email protected]"}, 1:{emails: "Another CO. , [email protected]"}
JS:
$.getJSON('yourlink_goes_here', { if_you_have_parameters}, function(data) {
var csvContent = "data:text/csv;charset=utf-8,";
var dataString = '';
$.each(data, function(k, v) {
dataString += v.emails + "\n";
});
csvContent += dataString;
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "your_filename.csv");
document.body.appendChild(link); // Required for FF
link.click();
});
GetCursorPos() will return to you the x/y if you pass in a pointer to a POINT structure.
Hiding the cursor can be done with ShowCursor().
Just send xml bytes directly:
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import requests
xml = """<?xml version='1.0' encoding='utf-8'?>
<a>?</a>"""
headers = {'Content-Type': 'application/xml'} # set what your server accepts
print requests.post('http://httpbin.org/post', data=xml, headers=headers).text
{
"origin": "x.x.x.x",
"files": {},
"form": {},
"url": "http://httpbin.org/post",
"args": {},
"headers": {
"Content-Length": "48",
"Accept-Encoding": "identity, deflate, compress, gzip",
"Connection": "keep-alive",
"Accept": "*/*",
"User-Agent": "python-requests/0.13.9 CPython/2.7.3 Linux/3.2.0-30-generic",
"Host": "httpbin.org",
"Content-Type": "application/xml"
},
"json": null,
"data": "<?xml version='1.0' encoding='utf-8'?>\n<a>\u0431</a>"
}
HTMLInputElement.setSelectionRange( selectionStart, selectionEnd );
// References
var e = document.getElementById( "helloworldinput" );
// Move caret to beginning on focus
e.addEventListener( "focus", function( event )
{
// References
var e = event.target;
// Action
e.setSelectionRange( 0, 0 ); // Doesn’t work for focus event
window.setTimeout( function()
{
e.setSelectionRange( 0, 0 ); // Works
//e.setSelectionRange( 1, 1 ); // Move caret to second position
//e.setSelectionRange( 1, 2 ); // Select second character
}, 0 );
}, false );
Browser compatibility (only for types: text, search, url, tel and password): https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange#Specifications
Building off of ngoozeff
's answer, if you want to make a command run completely in the background (i.e., if you want to hide its output and prevent it from being killed when you close its Terminal window), you can do this instead:
cmd="google-chrome";
"${cmd}" &>/dev/null & disown;
&>/dev/null
sets the command’s stdout
and stderr
to /dev/null
instead of inheriting them from the parent process. &
makes the shell run the command in the background. disown
removes the “current” job, last one stopped or put in the background, from under the shell’s job control.In some shells you can also use &!
instead of & disown
; they both have the same effect. Bash doesn’t support &!
, though.
Also, when putting a command inside of a variable, it's more proper to use eval "${cmd}"
rather than "${cmd}"
:
cmd="google-chrome";
eval "${cmd}" &>/dev/null & disown;
If you run this command directly in Terminal, it will show the PID of the process which the command starts. But inside of a shell script, no output will be shown.
Here's a function for it:
#!/bin/bash
# Run a command in the background.
_evalBg() {
eval "$@" &>/dev/null & disown;
}
cmd="google-chrome";
_evalBg "${cmd}";
Because your <form>
element is inside the foreach loop, you are generating multiple forms. I assume you want multiple checkboxes in one form.
Try this...
<form method="post">
foreach{
<?php echo'
<input id="'.$userid.'" value="'.$userid.'" name="invite[]" type="checkbox">
<input type="submit">';
?>
}
</form>
sudo make uninstall
did the trick for me using the Ruby 2.4 tar from the official downloads page.
Simply casting to an int truncates the float, which if your system internally represent 2.0 as 1.9999999999, you will not get what you expect. The various printf conversions deal with this and properly round the number when converting. So to get a more accurate value, the conversion is even more complicated than you might first expect:
package main
import (
"fmt"
"strconv"
)
func main() {
floats := []float64{1.9999, 2.0001, 2.0}
for _, f := range floats {
t := int(f)
s := fmt.Sprintf("%.0f", f)
if i, err := strconv.Atoi(s); err == nil {
fmt.Println(f, t, i)
} else {
fmt.Println(f, t, err)
}
}
}
Code on Go Playground
I actually prefer to use the html button form element and make it runat=server. The button element can hold other elements inside it. You can even add formatting inside it with span's or strong's. Here is an example:
<button id="BtnSave" runat="server"><img src="Images/save.png" />Save</button>
Another way to read/write Excel files is to use Windmill. It provides a fluent API to process Excel and CSV files.
try (Stream<Row> rowStream = Windmill.parse(FileSource.of(new FileInputStream("myFile.xlsx")))) {
rowStream
// skip the header row that contains the column names
.skip(1)
.forEach(row -> {
System.out.println(
"row n°" + row.rowIndex()
+ " column 'User login' value : " + row.cell("User login").asString()
+ " column n°3 number value : " + row.cell(2).asDouble().value() // index is zero-based
);
});
}
Windmill
.export(Arrays.asList(bean1, bean2, bean3))
.withHeaderMapping(
new ExportHeaderMapping<Bean>()
.add("Name", Bean::getName)
.add("User login", bean -> bean.getUser().getLogin())
)
.asExcel()
.writeTo(new FileOutputStream("Export.xlsx"));
I'm assuming you are having at least OSX 10.7, so go ahead into the applications folder (Click on Finder icon > On the Sidebar, you'll find "Applications", click on it ), delete the "Xcode" icon. That will remove Xcode from your system completely. Restart your mac.
Now go to https://developer.apple.com/download/more/ and download an older version of Xcode, as needed and install. You need an Apple ID to login to that portal.
You can try the following :
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowFullscreen">true</item>
</style>
queryParams
queryParams
is another input of routerLink
where they can be passed like
<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}">Somewhere</a>
fragment
<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}" [fragment]="yyy">Somewhere</a>
routerLinkActiveOptions
To also get routes active class set on parent routes:
[routerLinkActiveOptions]="{ exact: false }"
To pass query parameters to this.router.navigate(...)
use
let navigationExtras: NavigationExtras = {
queryParams: { 'session_id': sessionId },
fragment: 'anchor'
};
// Navigate to the login page with extras
this.router.navigate(['/login'], navigationExtras);
See also https://angular.io/guide/router#query-parameters-and-fragments
$(".testClick").click(function () {
var value = $(this).attr("href");
alert(value );
});
When you use $(".className") you are getting the set of all elements that have that class. Then when you call attr it simply returns the value of the first item in the collection.
Actually, the correct solution is:
composer require vendor/package
Taken from the CLI documentation for Composer:
The
require
command adds new packages to thecomposer.json
file from the current directory.
php composer.phar require
After adding/changing the requirements, the modified requirements will be installed or updated.
If you do not want to choose requirements interactively, you can just pass them to the command.
php composer.phar require vendor/package:2.* vendor/package2:dev-master
While it is true that composer update
installs new packages found in composer.json, it will also update the composer.lock file and any installed packages according to any fuzzy logic (>
or *
chars after the colons) found in composer.json! This can be avoided by using composer update vendor/package
, but I wouldn't recommend making a habit of it, as you're one forgotten argument away from a potentially broken project…
Keep things sane and stick with composer require vendor/package
for adding new dependencies!
import java.lang.reflect.Field;
public class test {
public int i = 5;
public Integer test = 5;
public String omghi = "der";
public static String testStatic = "THIS IS STATIC";
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
test t = new test();
for(Field f : t.getClass().getFields()) {
System.out.println(f.getGenericType() +" "+f.getName() + " = " + f.get(t));
}
}
}
You were just one step away from incorporating the row count into the base dataset.
Using the tidy()
function from the broom
package, convert the frequency table into a data frame and inner join with df
:
df <- data.frame(name=c('black','black','black','red','red'),
type=c('chair','chair','sofa','sofa','plate'),
num=c(4,5,12,4,3))
library(broom)
df <- merge(df, tidy(table(df[ , c("name","type")])), by=c("name","type"))
df
name type num Freq
1 black chair 4 2
2 black chair 5 2
3 black sofa 12 1
4 red plate 3 1
5 red sofa 4 1
In Visual Studio, you can't just open a .cpp
file and expect it to run. You must create a project first, or open the .cpp in some existing project.
In your case, there is no project, so there is no project to build.
Go to File --> New --> Project --> Visual C++ --> Win32 Console Application
. You can uncheck "create a directory for solution". On the next page, be sure to check "Empty project".
Then, You can add .cpp
files you created outside the Visual Studio by right clicking in the Solution explorer
on folder icon "Source" and Add->Existing Item.
Obviously You can create new .cpp this way too (Add --> New). The .cpp file will be created in your project directory.
Then you can press ctrl+F5 to compile without debugging and can see output on console window.
Yes you can. The default location for script files is data/db
If you put any script there you can call it as
load("myjstest.js") // or
load("/data/db/myjstest.js")
I'd suggest marking the Hibernate DAO class with @Primary
, i.e. (assuming you used @Repository
on HibernateDeviceDao
):
@Primary
@Repository
public class HibernateDeviceDao implements DeviceDao
This way it will be selected as the default autowire candididate, with no need to autowire-candidate
on the other bean.
Also, rather than using @Autowired @Qualifier
, I find it more elegant to use @Resource
for picking specific beans, i.e.
@Resource(name="jdbcDeviceDao")
DeviceDao deviceDao;
If you are at the office and behind the company proxy, try to imports all company proxy cacert into jre\lib\security
because gradle uses jre's certificates.
Plus, config your gradle.properties. It should work
More details go to that thread: https://groups.google.com/forum/#!msg/adt-dev/kdP2iNgcQFM/BDY7H0os18oJ
From an answer of @NimChimpsky in similar question:
Resource resource = new ClassPathResource("storedProcedures.sql");
InputStream resourceInputStream = resource.getInputStream();
Using ClassPathResource and interface Resource. And make sure you are adding the resources directory correctly (adding /src/main/resources/
into the classpath).
Note that Resource have a method to get a java.io.File
so you can also use:
Resource resource = new ClassPathResource("storedProcedures.sql");
FileReader fr = new FileReader(resource.getFile());
Unfortunately, no. Not with HTML and CSS. You need an a
element to make a link, and you can't wrap an entire table row in one.
The closest you can get is linking every table cell. Personally I'd just link one cell and use JavaScript to make the rest clickable. It's good to have at least one cell that really looks like a link, underlined and all, for clarity anyways.
Here's a simple jQuery snippet to make all table rows with links clickable (it looks for the first link and "clicks" it)
$("table").on("click", "tr", function(e) {
if ($(e.target).is("a,input")) // anything else you don't want to trigger the click
return;
location.href = $(this).find("a").attr("href");
});
int main()
{
int m;
while(cin>>m)
{
}
}
This would read from standard input if it space separated or line separated .
Although the question is about equality, for quick visual reference, here the order of some strings sorted using a couple of cultures illustrating some of the idiosyncrasies out there.
Ordinal 0 9 A Ab a aB aa ab ss Ä Äb ß ä äb ? ? ? ? ? A
IgnoreCase 0 9 a A aa ab Ab aB ss ä Ä äb Äb ß ? ? ? ? ? A
--------------------------------------------------------------------
InvariantCulture 0 9 a A A ä Ä aa ab aB Ab äb Äb ss ß ? ? ? ? ?
IgnoreCase 0 9 A a A Ä ä aa Ab aB ab Äb äb ß ss ? ? ? ? ?
--------------------------------------------------------------------
da-DK 0 9 a A A ab aB Ab ss ß ä Ä äb Äb aa ? ? ? ? ?
IgnoreCase 0 9 A a A Ab aB ab ß ss Ä ä Äb äb aa ? ? ? ? ?
--------------------------------------------------------------------
de-DE 0 9 a A A ä Ä aa ab aB Ab äb Äb ß ss ? ? ? ? ?
IgnoreCase 0 9 A a A Ä ä aa Ab aB ab Äb äb ss ß ? ? ? ? ?
--------------------------------------------------------------------
en-US 0 9 a A A ä Ä aa ab aB Ab äb Äb ß ss ? ? ? ? ?
IgnoreCase 0 9 A a A Ä ä aa Ab aB ab Äb äb ss ß ? ? ? ? ?
--------------------------------------------------------------------
ja-JP 0 9 a A A ä Ä aa ab aB Ab äb Äb ß ss ? ? ? ? ?
IgnoreCase 0 9 A a A Ä ä aa Ab aB ab Äb äb ss ß ? ? ? ? ?
Observations:
de-DE
, ja-JP
, and en-US
sort the same wayInvariant
only sorts ss
and ß
differently from the above three culturesda-DK
sorts quite differentlyIgnoreCase
flag matters for all sampled culturesThe code used to generate above table:
var l = new List<string>
{ "0", "9", "A", "Ab", "a", "aB", "aa", "ab", "ss", "ß",
"Ä", "Äb", "ä", "äb", "?", "?", "?", "?", "A", "?" };
foreach (var comparer in new[]
{
StringComparer.Ordinal,
StringComparer.OrdinalIgnoreCase,
StringComparer.InvariantCulture,
StringComparer.InvariantCultureIgnoreCase,
StringComparer.Create(new CultureInfo("da-DK"), false),
StringComparer.Create(new CultureInfo("da-DK"), true),
StringComparer.Create(new CultureInfo("de-DE"), false),
StringComparer.Create(new CultureInfo("de-DE"), true),
StringComparer.Create(new CultureInfo("en-US"), false),
StringComparer.Create(new CultureInfo("en-US"), true),
StringComparer.Create(new CultureInfo("ja-JP"), false),
StringComparer.Create(new CultureInfo("ja-JP"), true),
})
{
l.Sort(comparer);
Console.WriteLine(string.Join(" ", l));
}
First make link with @bold bot . Then Copy text and paste it to remove "via @bold"
$('#myform').on('submit',function(event){
// block form submit event
event.preventDefault();
// Do some stuff here
...
// Continue the form submit
event.currentTarget.submit();
});
Strange behavior with MS Excel
:
If i export to "text based, comma-separated format (csv
)" this is the mime-type I get after uploading on my webserver:
[name] => data.csv
[type] => application/vnd.ms-excel
So Microsoft seems to be doing own things again, regardless of existing standards: https://en.wikipedia.org/wiki/Comma-separated_values
<xsl:text disable-output-escaping="yes">& </xsl:text>
will do the trick.
Here's another way of doing it with a WHS script:
Set objWMIService = GetObject("Winmgmts:root\cimv2")
For Each objComputer in _
objWMIService.InstancesOf("Win32_ComputerSystem")
objComputer.rename "NewComputerName", NULL, NULL
Next
String text = readFileAsString("textfile.txt").replaceAll("\n", "");
Even though the definition of trim() in oracle website is "Returns a copy of the string, with leading and trailing whitespace omitted."
the documentation omits to say that new line characters (leading and trailing) will also be removed.
In short
String text = readFileAsString("textfile.txt").trim();
will also work for you.
(Checked with Java 6)
If you're on android you have multiple choices, where only the first is a kind of "enum":
HTTP
(which has been deprecated in API 22), for exampleHTTP.PLAIN_TEXT_TYPE
orMimeTypeMap
, for examplefinal String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
FileProvider.getType()
.URLConnection
that provides the following methods:
For example
@Override
public String getType(Uri uri) {
return URLConnection.getFileNameMap().getContentTypeFor(
uri.getLastPathSegment());
}
sed can do this:
sed 's/[\t ]/,/g' input.file
That will send to the console,
sed -i 's/[\t ]/,/g' input.file
will edit the file in-place
My C++ templates were there all along, it was my C# ones that were missing.
Similar to CSharpie, after trying many modify/re-installs, oddly the following finally worked for me :
- run the installer, but un-select 'Desktop development with C++'.
- allow installer to complete
- run the installer again, and select 'Desktop development with C++'.
- allow installer to complete
As complement to Mark's answer, the compile function does not have access to scope, but the link function does.
I really recommend this video; Writing Directives by Misko Hevery (the father of AngularJS), where he describes differences and some techniques. (Difference between compile function and link function at 14:41 mark in the video).
Imho this is a flaw in many c compilers. I know for a fact that the compilers i worked with do not store a "static const"variable at an adress but replace the use in the code by the very constant. This can be verified as you will get the same checksum for the produced code when you use a preprocessors #define directive and when you use a static const variable.
Either way you should use static const variables instead of #defines whenever possible as the static const is type safe.
Lawrence has given you a good answer. But if you want more control over what gets exported to where in Excel see Modules: Sample Excel Automation - cell by cell which is slow and Modules: Transferring Records to Excel with Automation You can do things such as export the recordset starting in row 2 and insert custom text in row 1. As well as any custom formatting required.
In CMD, type:
pip freeze
And it will show you a list of all the modules installed including the version number.
Output:
aiohttp==1.1.4
async-timeout==1.1.0
cx-Freeze==4.3.4
Django==1.9.2
django-allauth==0.24.1
django-cors-headers==1.2.2
django-crispy-forms==1.6.0
django-robots==2.0
djangorestframework==3.3.2
easygui==0.98.0
future==0.16.0
httpie==0.9.6
matplotlib==1.5.3
multidict==2.1.2
numpy==1.11.2
oauthlib==1.0.3
pandas==0.19.1
pefile==2016.3.28
pygame==1.9.2b1
Pygments==2.1.3
PyInstaller==3.2
pyparsing==2.1.10
pypiwin32==219
PyQt5==5.7
pytz==2016.7
requests==2.9.1
requests-oauthlib==0.6
six==1.10.0
sympy==1.0
virtualenv==15.0.3
xlrd==1.0.0
yarl==0.7.0
Have you tried setting the selection properties of your tableView like this:
tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES;
If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
in your UITableView delegate. The documentation states:
Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected.
You can have this method return nil in cases where you don't want the selection to happen.
The first problem is that your query string is wrong:
I think this: "INSERT INTO employee(hans,germany) values(?,?)"
should be like this: "INSERT INTO employee(name,country) values(?,?)"
The other problem is that you have a parameterized PreparedStatement and you don't set the parameters before running it.
You should add these to your code:
String inserting = "INSERT INTO employee(name,country) values(?,?)";
System.out.println("insert " + inserting);//
PreparedStatement ps = con.prepareStatement(inserting);
ps.setString(1,"hans"); // <----- this
ps.setString(2,"germany");// <---- and this
ps.executeUpdate();
When you access a OneToOneField you get the value of the field you queried. In this example a book model's 'title' field is a OneToOneField:
>>> from mysite.books.models import Book
>>> b = Book.objects.get(id=50)
>>> b.title
u'The Django Book'
When you access a ForeignKey you get the related model object, which you can then preform further queries against. In this example the same book model's 'publisher' field is a ForeignKey (correlating to the Publisher class model definition):
>>> b = Book.objects.get(id=50)
>>> b.publisher
<Publisher: Apress Publishing>
>>> b.publisher.website
u'http://www.apress.com/'
With ForeignKey fields queries work the other way too, but they're slightly different due to the non-symmetrical nature of the relationship.
>>> p = Publisher.objects.get(name='Apress Publishing')
>>> p.book_set.all()
[<Book: The Django Book>, <Book: Dive Into Python>, ...]
Behind the scenes, book_set is just a QuerySet and can be filtered and sliced like any other QuerySet. The attribute name book_set is generated by appending the lower case model name to _set.
Use collectl
which has extensive process I/O monitoring including monitoring threads.
Be warned that there are I/O counters for I/O being written to cache and I/O going to disk. collectl
reports them separately. If you're not careful you can misinterpret the data. See http://collectl.sourceforge.net/Process.html
Of course, it shows a lot more than just process stats because you'd want one tool to provide everything rather than a bunch of different one that displays everything in different formats, right?
If by ID:
$('#datepicker').datepicker({
format: 'dd/mm/yyyy'
});
If by Class:
$('.datepicker').datepicker({
format: 'dd/mm/yyyy'
});
This should work fine:
Dim result As DialogResult = MessageBox.Show("message", "caption", MessageBoxButtons.YesNoCancel)
If result = DialogResult.Cancel Then
MessageBox.Show("Cancel pressed")
ElseIf result = DialogResult.No Then
MessageBox.Show("No pressed")
ElseIf result = DialogResult.Yes Then
MessageBox.Show("Yes pressed")
End If
If your iframe's URL does not change, you can just recreate it.
If your iframe is not from the same origin (protocol scheme, hostname and port), you will not be able to know the current URL in the iframe, so you will need a script in the iframe document to exchange messages with its parent window (the page's window).
In the iframe document:
window.addEventListener('change', function(e) {
if (e.data === 'Please reload yourself') {
var skipCache = true; // true === Shift+F5
window.location.reload(skipCache);
}
}
In your page:
var iframe = document.getElementById('my-iframe');
var targetOrigin = iframe.src; // Use '*' if you don't care
iframe.postMessage('Please reload yourself', targetOrigin);
read() is equivalent to recv() with a flags parameter of 0. Other values for the flags parameter change the behaviour of recv(). Similarly, write() is equivalent to send() with flags == 0.
You could also use:
var latLon = L.latLng(40.737, -73.923);
var bounds = latLon.toBounds(500); // 500 = metres
map.panTo(latLon).fitBounds(bounds);
This will set the view level to fit the bounds in the map leaflet.
DATE_ADD(FROM_DATE_HERE, INTERVAL INTERVAL_TIME_HERE DAY)
will give the Date after adjusting the INTERVAL
eg.
DATE_ADD(NOW(), INTERVAL -1 DAY) for deducting 1 DAY from current Day
DATE_ADD(NOW(), INTERVAL 2 DAY) for adding 2 Days
You can use like
UPDATE classes WHERE date=(DATE_ADD(date, INTERVAL 1 DAY)) WHERE id=161
I was using a .Net Core 2.1 API with the [FromBody]
attribute and I had to use the following solution to successfully Post to it:
_apiClient = new HttpClient();
_apiClient.BaseAddress = new Uri(<YOUR API>);
var MyObject myObject = new MyObject(){
FirstName = "Me",
LastName = "Myself"
};
var stringified = JsonConvert.SerializeObject(myObject);
var result = await _apiClient.PostAsync("api/appusers", new StringContent(stringified, Encoding.UTF8, "application/json"));
In your classpath you're using an absolute path but you've moved the project onto a new machine with quite possibly a different file structure.
In your classpath you should therefore (and probably in general if you're gonna bundle JARS with your project), use relative pathing:
In your .classpath change
<classpathentry kind="lib" path="C:/Users/Chris/Downloads/last.fm-bindings-0.1.1.jar" sourcepath=""/><classpathentry kind="lib" path="C:/Users/Chris/Downloads/last.fm-bindings-0.1.1.jar" sourcepath=""/>
to
<classpathentry kind="lib" path="last.fm-bindings-0.1.1.jar"/>
You could do this:
if (!discount.nil? && !discount.zero?)
The order is important here, because if discount
is nil
, then it will not have a zero?
method. Ruby's short-circuit evaluation should prevent it from trying to evaluate discount.zero?
, however, if discount
is nil
.
Upper div use higher z-index and lower div use lower z-index then use absolute/fixed/relative position
Here is a 'YouTube-video-id' like id generator e.g. "UcBKmq2XE5a"
StringBuilder builder = new StringBuilder();
Enumerable
.Range(65, 26)
.Select(e => ((char)e).ToString())
.Concat(Enumerable.Range(97, 26).Select(e => ((char)e).ToString()))
.Concat(Enumerable.Range(0, 10).Select(e => e.ToString()))
.OrderBy(e => Guid.NewGuid())
.Take(11)
.ToList().ForEach(e => builder.Append(e));
string id = builder.ToString();
It creates random ids of size 11 characters. You can increase/decrease that as well, just change the parameter of Take method.
0.001% duplicates in 100 million.
The problem is that buttonClickedEvent
is a member function and you need a pointer to member in order to invoke it.
Try this:
void (MyClass::*func)(int);
func = &MyClass::buttonClickedEvent;
And then when you invoke it, you need an object of type MyClass
to do so, for example this
:
(this->*func)(<argument>);
http://www.codeguru.com/cpp/cpp/article.php/c17401/C-Tutorial-PointertoMember-Function.htm
If you are implicitly declaring the variable without var
, the proper way would be to use delete foo
.
However after you delete it, if you try to use this in an operation such as addition a ReferenceError
will be thrown because you can't add a string to an undeclared, undefined identifier. Example:
x = 5;
delete x
alert('foo' + x )
// ReferenceError: x is not defined
It may be safer in some situations to assign it to false, null, or undefined so it's declared and won't throw this type of error.
foo = false
Note that in ECMAScript null
, false
, undefined
, 0
, NaN
, or ''
would all evaluate to false
. Just make sure you dont use the !==
operator but instead !=
when type checking for booleans and you don't want identity checking (so null
would == false
and false == undefined
).
Also note that delete
doesn't "delete" references but just properties directly on the object, e.g.:
bah = {}, foo = {}; bah.ref = foo;
delete bah.ref;
alert( [bah.ref, foo ] )
// ,[object Object] (it deleted the property but not the reference to the other object)
If you have declared a variable with var
you can't delete it:
(function() {
var x = 5;
alert(delete x)
// false
})();
In Rhino:
js> var x
js> delete x
false
Nor can you delete some predefined properties like Math.PI
:
js> delete Math.PI
false
There are some odd exceptions to delete
as with any language, if you care enough you should read:
This will work for sure I guess...
// Declare
Menu menu;
MenuItem menuDoneItem;
// Then in your onCreateOptionMenu() method write the following...
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
this.menu=menu;
inflater.inflate(R.menu.secutity, menu);
}
// In your onOptionItemSelected() method write the following...
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.done_item:
this.menuDoneItem=item;
someOperation();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// Now Making invisible any menu item...
public void menuInvisible(){
setHasOptionsMenu(true);// Take part in populating the action bar menu
menuDoneItem=(MenuItem)menu.findItem(R.id.done_item);
menuRefresh.setVisible(false); // make true to make the menu item visible.
}
//Use the above method whenever you need to make your menu item visible or invisiable
You can also refer this link for more details, it is a very useful one.
Have you tried:
$OutputVariable = (Shell command) | Out-String
Adding only one mode to sql_mode without removing existing ones:
SET sql_mode=(SELECT CONCAT(@@sql_mode,',<mode_to_add>'));
Removing only a specific mode from sql_mode without removing others:
SET sql_mode=(SELECT REPLACE(@@sql_mode,'<mode_to_remove>',''));
In your case, if you want to remove only ONLY_FULL_GROUP_BY
mode, then use below command:
SET sql_mode=(SELECT REPLACE(@@sql_mode, 'ONLY_FULL_GROUP_BY', ''));
Reference: http://johnemb.blogspot.com/2014/09/adding-or-removing-individual-sql-modes.html
This one shows how to print only selected element on the page with dpi/resolution
adjustments
HTML:
<html>
<body>
<header>This is the header</header>
<div id="content">
This is the element you only want to capture
</div>
<button id="print">Download Pdf</button>
<footer>This is the footer</footer>
</body>
</html>
CSS:
body {
background: beige;
}
header {
background: red;
}
footer {
background: blue;
}
#content {
background: yellow;
width: 70%;
height: 100px;
margin: 50px auto;
border: 1px solid orange;
padding: 20px;
}
JS:
$('#print').click(function() {
var w = document.getElementById("content").offsetWidth;
var h = document.getElementById("content").offsetHeight;
html2canvas(document.getElementById("content"), {
dpi: 300, // Set to 300 DPI
scale: 3, // Adjusts your resolution
onrendered: function(canvas) {
var img = canvas.toDataURL("image/jpeg", 1);
var doc = new jsPDF('L', 'px', [w, h]);
doc.addImage(img, 'JPEG', 0, 0, w, h);
doc.save('sample-file.pdf');
}
});
});
OK, it's 15 lines of code but the result is awesome! That's the kind of stuff that made me freak out when I was a child. This is from the PHP manual:
$x = 200;
$y = 200;
$gd = imagecreatetruecolor($x, $y);
$corners[0] = array('x' => 100, 'y' => 10);
$corners[1] = array('x' => 0, 'y' => 190);
$corners[2] = array('x' => 200, 'y' => 190);
$red = imagecolorallocate($gd, 255, 0, 0);
for ($i = 0; $i < 100000; $i++) {
imagesetpixel($gd, round($x),round($y), $red);
$a = rand(0, 2);
$x = ($x + $corners[$a]['x']) / 2;
$y = ($y + $corners[$a]['y']) / 2;
}
header('Content-Type: image/png');
imagepng($gd);
The accepted answer of this question has some issue with chrome when the window is zoomed in to a value >100%. Here is the code recommended by chrome developers as part of a bug i had raised on the same.
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()){
//Your code here
}
});
For reference:
You can add --force-with-lease to the command, it will works.
git push --force-with-lease
--force is destructive because it unconditionally overwrites the remote repository with whatever you have locally. But --force-with-lease ensure you don't overwrite other's work.
See more info here.
I don't think desc
takes an na.rm
argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NA
s, use na.omit
(base) or tidyr::drop_na
:
outcome.df %>%
na.omit() %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
library(tidyr)
outcome.df %>%
drop_na() %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
If you only want to remove NA
s from the HeartAttackDeath column, filter with is.na
, or use tidyr::drop_na
:
outcome.df %>%
filter(!is.na(HeartAttackDeath)) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
outcome.df %>%
drop_na(HeartAttackDeath) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
As pointed out at the dupe, complete.cases
can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:
outcome.df %>%
filter(complete.cases(.)) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
My gut told me the same thing when I came across this design.
I am working on a code base where there are three dbContexts to one database. 2 out of the 3 dbcontexts are dependent on information from 1 dbcontext because it serves up the administrative data. This design has placed constraints on how you can query your data. I ran into this problem where you cannot join across dbcontexts. Instead what you are required to do is query the two separate dbcontexts then do a join in memory or iterate through both to get the combination of the two as a result set. The problem with that is instead of querying for a specific result set you are now loading all your records into memory and then doing a join against the two result sets in memory. It can really slow things down.
I would ask the question "just because you can, should you?"
See this article for the problem I came across related to this design.
The specified LINQ expression contains references to queries that are associated with different contexts
Caucho Quercus can run PHP code on the jvm.
Since it's a NodeList
, not an Array
, you shouldn't really be using brackets or casting to Array
. The property way to get the first node is:
document.getElementsByName(id).item(0)
You can just cast that:
var script = <HTMLScriptElement> document.getElementsByName(id).item(0)
Or, extend NodeList
:
interface HTMLScriptElementNodeList extends NodeList
{
item(index: number): HTMLScriptElement;
}
var scripts = <HTMLScriptElementNodeList> document.getElementsByName('script'),
script = scripts.item(0);
In linuxOS:
sed -i 's/textSerch/textReplace/g' namefile
if "sed" not work try :
perl -i -pe 's/textSerch/textReplace/g' namefile
I know this is an old thread and so are answers here. Adding this answer for future reference:
Add a recycle view in your layout
<android.support.v7.widget.RecyclerView
android:id="@+id/wifiList"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Create a layout to display list items (list_item.xml)
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:padding="5dp"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<android.support.v7.widget.AppCompatTextView
android:id="@+id/ssid"
android:text="@string/app_name"
android:layout_width="match_parent"
android:textSize="17sp"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v7.widget.CardView>
Now create a minimal Adapter to hold data, code here is self explanatory
class WifiAdapter(private val wifiList: ArrayList<ScanResult>) : RecyclerView.Adapter<WifiAdapter.ViewHolder>() {
// holder class to hold reference
inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
//get view reference
var ssid: TextView = view.findViewById(R.id.ssid) as TextView
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
// create view holder to hold reference
return ViewHolder( LayoutInflater.from(parent.context).inflate(R.layout.list_item, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
//set values
holder.ssid.text = wifiList[position].SSID
}
override fun getItemCount(): Int {
return wifiList.size
}
// update your data
fun updateData(scanResult: ArrayList<ScanResult>) {
wifiList.clear()
notifyDataSetChanged()
wifiList.addAll(scanResult)
notifyDataSetChanged()
}
}
Add this class to handle Single click and long click events on List Items
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, RecyclerView recyclerView, int position);
}
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child,recyclerView, recyclerView.getChildPosition(child));
}
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
Lastly Set your adapter to Recycler View and add Touch Listener to start intercepting touch event for single or double tap on list items
wifiAdapter = WifiAdapter(ArrayList())
wifiList.apply {
// vertical layout
layoutManager = LinearLayoutManager(applicationContext)
// set adapter
adapter = wifiAdapter
// Touch handling
wifiList.addOnItemTouchListener(RecyclerTouchListener(applicationContext, wifiList, object : RecyclerTouchListener.ClickListener {
override fun onClick(view: View?, position: Int) {
Toast.makeText(applicationContext, "RV OnCLickj " + position, Toast.LENGTH_SHORT).show()
}
override fun onLongClick(view: View, recyclerView: RecyclerView, position: Int) {
Toast.makeText(applicationContext, "RV OnLongCLickj " + position, Toast.LENGTH_SHORT).show()
}
}
))
}
Bonus ; Update Data
wifiAdapter.updateData(mScanResults as ArrayList<ScanResult>)
Result:
Use This as the solution
This worked for me perfectly..
<div align="center">
<img src="">
</div>
You need to create new Book
objects then put those in a new List
:
List<Book> books_2 = books_1.Select(book => new Book(book.title)).ToList();
Update: Slightly simpler... List<T>
has a method called ConvertAll
that returns a new list:
List<Book> books_2 = books_1.ConvertAll(book => new Book(book.title));
Your datatype for @location nchar(20)
should be @location nvarchar(20)
, since nChar has a fixed length (filled with Spaces).
If Location is nchar too you will have to convert it:
... Cast(Location as nVarchar(200)) like '%'+@location+'%' ...
To enable nullable parameters with and AND
condition just use IsNull or Coalesce for comparison, which is not needed in your example using OR
.
e.g. if you would like to compare for Location AND Date and Time.
@location nchar(20),
@time time,
@date date
as
select DonationsTruck.VechileId, Phone, Location, [Date], [Time]
from Vechile, DonationsTruck
where Vechile.VechileId = DonationsTruck.VechileId
and (((Location like '%'+IsNull(@location,Location)+'%')) and [Date]=IsNUll(@date,date) and [Time] = IsNull(@time,Time))
You need to move your angular app code below the inclusion of the angular libraries. At the time your angular code runs, angular
does not exist yet. This is an error (see your dev tools console).
In this line:
var app = angular.module(`
you are attempting to access a variable called angular
. Consider what causes that variable to exist. That is found in the angular.js script which must then be included first.
<h1>{{2+3}}</h1>
<!-- In production use:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
-->
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-route.js"></script>
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>
<script src="js/directives.js"></script>
<script>
var app = angular.module('myApp',[]);
app.directive('myDirective',function(){
return function(scope, element,attrs) {
element.bind('click',function() {alert('click')});
};
});
</script>
For completeness, it is true that your directive is similar to the already existing directive ng-click
, but I believe the point of this exercise is just to practice writing simple directives, so that makes sense.
Editor's note: disabling SSL verification has security implications. Without verification of the authenticity of SSL/HTTPS connections, a malicious attacker can impersonate a trusted endpoint such as Gmail, and you'll be vulnerable to a Man-in-the-Middle Attack.
Be sure you fully understand the security issues before using this as a solution.
Easy fix for this might be editing config/mail.php and turning off TLS
'encryption' => env('MAIL_ENCRYPTION', ''), //'tls'),
Basically by doing this
$options['ssl']['verify_peer'] = FALSE;
$options['ssl']['verify_peer_name'] = FALSE;
You should loose security also, but in first option there is no need to dive into Vendor's code.
function scrolled() {
//do by scroll start
$(this).off('scroll')[0].setTimeout(function(){
//do by scroll end
$(this).on('scroll',scrolled);
}, 500)
}
$(window).on('scroll',scrolled);
very small Version with start and end ability
Many hours spent to clarify what was that. Please, read this post to get the advanced .HTACCESS
codes and learn what they do.
You can use:
Header append Vary "Accept-Encoding"
#or
Header set Vary "Accept-Encoding"
If speed is what you need and extra dependencies are not a problem, you maybe find numba
quite useful (now it is pretty easy to install, on any platform). The classic ray_tracing
approach you proposed can be easily ported to numba
by using numba @jit
decorator and casting the polygon to a numpy array. The code should look like:
@jit(nopython=True)
def ray_tracing(x,y,poly):
n = len(poly)
inside = False
p2x = 0.0
p2y = 0.0
xints = 0.0
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
return inside
The first execution will take a little longer than any subsequent call:
%%time
polygon=np.array(polygon)
inside1 = [numba_ray_tracing_method(point[0], point[1], polygon) for
point in points]
CPU times: user 129 ms, sys: 4.08 ms, total: 133 ms
Wall time: 132 ms
Which, after compilation will decrease to:
CPU times: user 18.7 ms, sys: 320 µs, total: 19.1 ms
Wall time: 18.4 ms
If you need speed at the first call of the function you can then pre-compile the code in a module using pycc
. Store the function in a src.py like:
from numba import jit
from numba.pycc import CC
cc = CC('nbspatial')
@cc.export('ray_tracing', 'b1(f8, f8, f8[:,:])')
@jit(nopython=True)
def ray_tracing(x,y,poly):
n = len(poly)
inside = False
p2x = 0.0
p2y = 0.0
xints = 0.0
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
return inside
if __name__ == "__main__":
cc.compile()
Build it with python src.py
and run:
import nbspatial
import numpy as np
lenpoly = 100
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in
np.linspace(0,2*np.pi,lenpoly)[:-1]]
# random points set of points to test
N = 10000
# making a list instead of a generator to help debug
points = zip(np.random.random(N),np.random.random(N))
polygon = np.array(polygon)
%%time
result = [nbspatial.ray_tracing(point[0], point[1], polygon) for point in points]
CPU times: user 20.7 ms, sys: 64 µs, total: 20.8 ms
Wall time: 19.9 ms
In the numba code I used: 'b1(f8, f8, f8[:,:])'
In order to compile with nopython=True
, each var needs to be declared before the for loop
.
In the prebuild src code the line:
@cc.export('ray_tracing' , 'b1(f8, f8, f8[:,:])')
Is used to declare the function name and its I/O var types, a boolean output b1
and two floats f8
and a two-dimensional array of floats f8[:,:]
as input.
For my use case, I need to check if multiple points are inside a single polygon - In such a context, it is useful to take advantage of numba parallel capabilities to loop over a series of points. The example above can be changed to:
from numba import jit, njit
import numba
import numpy as np
@jit(nopython=True)
def pointinpolygon(x,y,poly):
n = len(poly)
inside = False
p2x = 0.0
p2y = 0.0
xints = 0.0
p1x,p1y = poly[0]
for i in numba.prange(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
return inside
@njit(parallel=True)
def parallelpointinpolygon(points, polygon):
D = np.empty(len(points), dtype=numba.boolean)
for i in numba.prange(0, len(D)):
D[i] = pointinpolygon(points[i,0], points[i,1], polygon)
return D
Note: pre-compiling the above code will not enable the parallel capabilities of numba (parallel CPU target is not supported by pycc/AOT
compilation) see: https://github.com/numba/numba/issues/3336
Test:
import numpy as np
lenpoly = 100
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in np.linspace(0,2*np.pi,lenpoly)[:-1]]
polygon = np.array(polygon)
N = 10000
points = np.random.uniform(-1.5, 1.5, size=(N, 2))
For N=10000
on a 72 core machine, returns:
%%timeit
parallelpointinpolygon(points, polygon)
# 480 µs ± 8.19 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
0
instead of 1
(thanks @mehdi):for i in numba.prange(0, len(D))
Follow-up on the comparison made by @mehdi, I am adding a GPU-based method below. It uses the point_in_polygon
method, from the cuspatial
library:
import numpy as np
import cudf
import cuspatial
N = 100000002
lenpoly = 1000
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in
np.linspace(0,2*np.pi,lenpoly)]
polygon = np.array(polygon)
points = np.random.uniform(-1.5, 1.5, size=(N, 2))
x_pnt = points[:,0]
y_pnt = points[:,1]
x_poly =polygon[:,0]
y_poly = polygon[:,1]
result = cuspatial.point_in_polygon(
x_pnt,
y_pnt,
cudf.Series([0], index=['geom']),
cudf.Series([0], name='r_pos', dtype='int32'),
x_poly,
y_poly,
)
Following @Mehdi comparison. For N=100000002
and lenpoly=1000
- I got the following results:
time_parallelpointinpolygon: 161.54760098457336
time_mpltPath: 307.1664695739746
time_ray_tracing_numpy_numba: 353.07356882095337
time_is_inside_sm_parallel: 37.45389246940613
time_is_inside_postgis_parallel: 127.13793849945068
time_is_inside_rapids: 4.246025562286377
hardware specs:
Notes:
The cuspatial.point_in_poligon
method, is quite robust and powerful, it offers the ability to work with multiple and complex polygons (I guess at the expense of performance)
The numba
methods can also be 'ported' on the GPU - it will be interesting to see a comparison which includes a porting to cuda
of fastest method mentioned by @Mehdi (is_inside_sm
).
Although many answers are given, I couldn't find one I am happy with. I figured out my own solution which makes property
work for the dynamic case. The source to answer the original question:
#!/usr/local/bin/python3
INITS = { 'ab': 100, 'cd': 200 }
class DP(dict):
def __init__(self):
super().__init__()
for k,v in INITS.items():
self[k] = v
def _dict_set(dp, key, value):
dp[key] = value
for item in INITS.keys():
setattr(
DP,
item,
lambda key: property(
lambda self: self[key], lambda self, value: _dict_set(self, key, value)
)(item)
)
a = DP()
print(a) # {'ab': 100, 'cd': 200}
a.ab = 'ab100'
a.cd = False
print(a.ab, a.cd) # ab100 False
One solution is to wrap it in a subquery
SELECT *
FROM
(
SELECT COUNT(column1),column1 FROM table GROUP BY column1
UNION ALL
SELECT COUNT(column2),column2 FROM table GROUP BY column2
UNION ALL
SELECT COUNT(column3),column3 FROM table GROUP BY column3
) s
To remote server
mysqldump mydbname | ssh host2 "mysql mydbcopy"
To local server
mysqldump mydbname | mysql mydbcopy
If you want to apply the animation on "activity" start. then write below code.
startActivity(intent);
overridePendingTransition(R.anim.opening_anim, R.anim.closing_anim);
If you want to apply the animation on "dialog" then firstly add below code in
styles.xml
file
<style name="my_style”>
<item
name="@android:windowEnterAnimation">@anim/opening_anim</item>
<item
name="@android:windowExitAnimation">@anim/closing_anim</item>
</style>
Use this style as I defined below.
final Dialog dialog = new Dialog(activity);
dialog.getWindow().getAttributes().windowAnimations = R.style.my_style;
If you want to apply the animation on "view" then write below code
txtMessage = (TextView) findViewById(R.id.txtMessage);
// load the animation
Animation animFadein = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.animation);
// start the animation
txtMessage.startAnimation(animFadein);
Below, I have mentioned most of the animation
.xml
code.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="1"
android:fromAlpha="1.0"
android:toAlpha="1.0"/>
</set>
===========================================
<?xml version="1.0" encoding="UTF-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha
android:fromAlpha="0.0"
android:toAlpha="1.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="300"
android:repeatCount="0" />
</set>
==========================================
<?xml version="1.0" encoding="UTF-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha
android:fromAlpha="1.0"
android:toAlpha="0.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="300"
android:repeatCount="0" />
</set>
==========================================
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromYDelta="-100%p" android:toYDelta="0" android:duration="400"/>
</set>
==========================================
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromYDelta="0" android:toYDelta="100%p" android:duration="400"/>
</set>
==========================================
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="100%p" android:toXDelta="0" android:duration="300"/>
<alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="300" />
</set>
==========================================
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="0" android:toXDelta="-100%p" android:duration="300"/>
<alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="300" />
</set>
==========================================
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="-100%p" android:toXDelta="0" android:duration="300"/>
<alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="300" />
</set>
==========================================
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="0" android:toXDelta="100%p" android:duration="300"/>
<alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="300" />
</set>
==========================================
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromYDelta="100%p" android:toYDelta="0" android:duration="300"/>
<alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="300" />
</set>
==========================================
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromYDelta="0" android:toYDelta="-100%p" android:duration="300"/>
<alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="300" />
</set>
==========================================
<?xml version="1.0" encoding="utf-8"?>
<rotate
xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="-90"
android:pivotX="50%"
android:pivotY="50%"
android:duration="0" android:fillAfter="true">
</rotate>
==========================================
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale android:fromYScale="0" android:toYScale="1.0"
android:fromXScale="0" android:toXScale="1.0"
android:duration="500" android:pivotX="100%"
android:pivotY="100%" />
</set>
==========================================
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale android:fromYScale="1.0" android:toYScale="0"
android:fromXScale="1.0" android:toXScale="0"
android:duration="500"/>
</set>
==========================================
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
android:fromXScale="1.0" android:toXScale="0.8"
android:fromYScale="1.0" android:toYScale="0.8"
android:pivotX="50%p" android:pivotY="50%p"
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="100"
/>
<scale
android:fromXScale="1.0" android:toXScale="0.0"
android:fromYScale="1.0" android:toYScale="1.0"
android:pivotX="50%p" android:pivotY="50%p"
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="150"
android:startOffset="100"
/>
==========================================
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
android:fromXScale="0.0" android:toXScale="1.0"
android:fromYScale="1.0" android:toYScale="1.0"
android:pivotX="50%p" android:pivotY="50%p"
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="150"
android:startOffset="250"
/>
<scale
android:fromXScale="0.8" android:toXScale="1.0"
android:fromYScale="0.8" android:toYScale="1.0"
android:pivotX="50%p" android:pivotY="50%p"
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="100"
android:startOffset="400"
/>
========================================
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha android:fromAlpha="0.0"
android:toAlpha="1.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="800"
android:repeatMode="reverse"
android:repeatCount="infinite"/>
</set>
========================================
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true" >
<scale
xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:fromXScale="1"
android:fromYScale="1"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale="3"
android:toYScale="3" >
</scale>
</set>
========================================
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true" >
<scale
xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale="0.5"
android:toYScale="0.5" >
</scale>
</set>
========================================
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true" >
<alpha
android:duration="1000"
android:fromAlpha="0.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:toAlpha="1.0" />
</set>
========================================
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true" >
<alpha
android:duration="1000"
android:fromAlpha="1.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:toAlpha="0.0" />
</set>
========================================
<?xml version="1.0" encoding="utf-8"?>
<set
xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator"
android:fillAfter="true">
<translate
android:fromXDelta="0%p"
android:toXDelta="80%p"
android:duration="1000" />
</set>
========================================
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">
<scale
android:duration="800"
android:fromXScale="1.0"
android:fromYScale="0.0"
android:interpolator="@android:anim/linear_interpolator"
android:toXScale="1.0"
android:toYScale="1.0" />
</set>
========================================
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true" >
<scale
android:duration="800"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:interpolator="@android:anim/linear_interpolator"
android:toXScale="1.0"
android:toYScale="0.0" />
</set>
========================================
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true"
android:interpolator="@android:anim/bounce_interpolator">
<scale
android:duration="800"
android:fromXScale="1.0"
android:fromYScale="0.0"
android:toXScale="1.0"
android:toYScale="1.0" />
</set>
Try
.img{
width:100vw; /* Matches to the Viewport Width */
height:auto;
max-width:100% !important;
}
Only works with display block and inline block, this has no effect on flex items as I've just spent ages trying to find out.
I fixed my problem by switching to the latest .Net Framework. So your target Framework sets your Security Protocol.
when you have this in Web.config
<system.web>
<httpRuntime targetFramework="4.5"/>
</system.web>
you will get this by default:
ServicePointManager.SecurityProtocol = Ssl3 | Tls
when you have this in Web.config
<system.web>
<httpRuntime targetFramework="4.6.1"/>
</system.web>
you will get this by default:
ServicePointManager.SecurityProtocol = Tls12 | Tls11 | Tls
First of all, I recommend writing the item you want to render multiple times (in your case list of fields) as a separate component:
function Field() {
return (
<View>
<View>
<TextInput />
</View>
<View>
<TextInput />
</View>
<View>
<TextInput />
</View>
</View>
);
}
Then, in your case, when rendering based on some number and not a list, I'd move the for loop outside of the render method for a more readable code:
renderFields() {
const noGuest = this.state.guest;
const fields = [];
for (let i=0; i < noGuest; i++) {
// Try avoiding the use of index as a key, it has to be unique!
fields.push(
<Field key={"guest_"+i} />
);
}
return fields;
}
render () {
return (
<View>
<View>
<View><Text>No</Text></View>
<View><Text>Name</Text></View>
<View><Text>Preference</Text></View>
</View>
{this.renderFields()}
</View>;
)
}
However, there are many more ways to render looped content in react native. Most of the ways are covered in this article, so please check it out if you're interested in more details! The examples in article are from React, but everything applies to React Native as well!
<input type="text" autocomplete="off" />
Some time we need to set PATH variable for WINDOWS
%USERPROFILE%\AppData\Roaming\npm
After that test with where grunt
Note: Do not forget to close the command prompt window and reopen it.
private static Scanner in;
I fixed it by declaring in as a private static Scanner class variable. Not sure why that fixed it but that is what eclipse recommended I do.