Thanks for all Contributions;
that is happening with me in XML; I just Change application/XML to be text/XML which solve my Problem
Create "topN" query on "clientip" and then histogram with count on "clientip" and set "topN" query as source. Then you will see count of different ips per time.
Similarly I fixed it like this (notice python34
):
sudo yum install python34-devel
Try this:
location / {
root /path/to/root;
expires 30d;
access_log off;
}
location ~* ^.*\.php$ {
if (!-f $request_filename) {
return 404;
}
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
}
Hopefully it works. Regular expressions have higher priority than plain strings, so all requests ending in .php
should be forwared to Apache if only a corresponding .php
file exists. Rest will be handled as static files. The actual algorithm of evaluating location is here.
Some times there are problems with funtion/features that do not interact with the DOM
try to change the value sharply and then assign the $scope
document.getElementById ("textWidget") value = "<NewVal>";
$scope.widget.title = "<NewVal>";
The variable $token
is not being retrieved from the session when it's in there
var_dump(extension_loaded('curl'));
If you are using Angular UI Router, you can listen for the $viewContentLoaded
event.
"$viewContentLoaded - fired once the view is loaded, after the DOM is rendered. The '$scope' of the view emits the event." - Link
$scope.$on('$viewContentLoaded',
function(event){ ... });
This works
npm config delete http-proxy
npm config delete https-proxy
npm config rm proxy
npm config rm https-proxy
set HTTP_PROXY=null
set HTTPS_PROXY=null
To keep the accordion nature intact when wanting to also use 'hide' and 'show' functions like .collapse( 'hide' )
, you must initialize the collapsible panels with the parent property set in the object with toggle: false
before making any calls to 'hide' or 'show'
// initialize collapsible panels
$('#accordion .collapse').collapse({
toggle: false,
parent: '#accordion'
});
// show panel one (will collapse others in accordion)
$( '#collapseOne' ).collapse( 'show' );
// show panel two (will collapse others in accordion)
$( '#collapseTwo' ).collapse( 'show' );
// hide panel two (will not collapse/expand others in accordion)
$( '#collapseTwo' ).collapse( 'hide' );
The first argument of all methods is usually called self
. It refers to the instance for which the method is being called.
Let's say you have:
class A(object):
def foo(self):
print 'Foo'
def bar(self, an_argument):
print 'Bar', an_argument
Then, doing:
a = A()
a.foo() #prints 'Foo'
a.bar('Arg!') #prints 'Bar Arg!'
There's nothing special about this being called self
, you could do the following:
class B(object):
def foo(self):
print 'Foo'
def bar(this_object):
this_object.foo()
Then, doing:
b = B()
b.bar() # prints 'Foo'
In your specific case:
dangerous_device = MissileDevice(some_battery)
dangerous_device.move(dangerous_device.RIGHT)
(As suggested in comments MissileDevice.RIGHT
could be more appropriate here!)
You could declare all your constants at module level though, so you could do:
dangerous_device.move(RIGHT)
This, however, is going to depend on how you want your code to be organized!
For me the issue was the IP address that charles was telling me to route to in my proxy settings was incorrect. To solve I ended up going to ifconfig
in the terminal and the trying the different IP addresses (listed next to inet
) at port 8888
for the current active connections
There is not only 1 %SystemRoot%\System32
on Windows x64. There are 2 such directories.
The real %SystemRoot%\System32
directory is for 64-bit applications. This directory contains a 64-bit cmd.exe
.
But there is also %SystemRoot%\SysWOW64
for 32-bit applications. This directory is used if a 32-bit application accesses %SystemRoot%\System32
. It contains a 32-bit cmd.exe
.
32-bit applications can access %SystemRoot%\System32
for 64-bit applications by using the alias %SystemRoot%\Sysnative
in path.
For more details see the Microsoft documentation about File System Redirector.
So the subdirectory run
was created either in %SystemRoot%\System32
for 64-bit applications and 32-bit cmd
is run for which this directory does not exist because there is no subdirectory run
in %SystemRoot%\SysWOW64
which is %SystemRoot%\System32
for 32-bit cmd.exe
or the subdirectory run
was created in %SystemRoot%\System32
for 32-bit applications and 64-bit cmd
is run for which this directory does not exist because there is no subdirectory run
in %SystemRoot%\System32
as this subdirectory exists only in %SystemRoot%\SysWOW64
.
The following code could be used at top of the batch file in case of subdirectory run
is in %SystemRoot%\System32
for 64-bit applications:
@echo off
set "SystemPath=%SystemRoot%\System32"
if not "%ProgramFiles(x86)%" == "" if exist %SystemRoot%\Sysnative\* set "SystemPath=%SystemRoot%\Sysnative"
Every console application in System32\run
directory must be executed with %SystemPath%
in the batch file, for example %SystemPath%\run\YourApp.exe
.
How it works?
There is no environment variable ProgramFiles(x86) on Windows x86 and therefore there is really only one %SystemRoot%\System32
as defined at top.
But there is defined the environment variable ProgramFiles(x86) with a value on Windows x64. So it is additionally checked on Windows x64 if there are files in %SystemRoot%\Sysnative
. In this case the batch file is processed currently by 32-bit cmd.exe
and only in this case %SystemRoot%\Sysnative
needs to be used at all. Otherwise %SystemRoot%\System32
can be used also on Windows x64 as when the batch file is processed by 64-bit cmd.exe
, this is the directory containing the 64-bit console applications (and the subdirectory run
).
Note: %SystemRoot%\Sysnative
is not a directory! It is not possible to cd
to %SystemRoot%\Sysnative
or use if exist %SystemRoot%\Sysnative
or if exist %SystemRoot%\Sysnative\
. It is a special alias existing only for 32-bit executables and therefore it is necessary to check if one or more files exist on using this path by using if exist %SystemRoot%\Sysnative\cmd.exe
or more general if exist %SystemRoot%\Sysnative\*
.
JavaScript's object literal syntax, which is typically used to instantiate objects (seriously, no one uses new Object
or new Array
), is as follows:
var obj = {
'key': 'value',
'another key': 'another value',
anUnquotedKey: 'more value!'
};
For arrays it's:
var arr = [
'value',
'another value',
'even more values'
];
If you need objects within objects, that's fine too:
var obj = {
'subObject': {
'key': 'value'
},
'another object': {
'some key': 'some value',
'another key': 'another value',
'an array': [ 'this', 'is', 'ok', 'as', 'well' ]
}
}
This convenient method of being able to instantiate static data is what led to the JSON data format.
JSON is a little more picky, keys must be enclosed in double-quotes, as well as string values:
{"foo":"bar", "keyWithIntegerValue":123}
What is your PHP version? Extension "Mysql" was deprecated in PHP 5.5.0. Use extension Mysqli (like mysqli_query).
use default js match() function:
if( element.attr('class') !== undefined && element.attr('class').match(/class1|class2|class3|class4|class5/) ) {
console.log("match");
}
to use variables in regexp, use this:
var reg = new RegExp(variable, 'g');
$(this).match(reg);
by the way, this is the fastest way: http://jsperf.com/hasclass-vs-is-stackoverflow/22
What's wrong with just invoking the commands?
foo:
echo line1
echo line2
....
And for your second question, you need to escape the $
by using $$
instead, i.e. bash -c '... echo $$a ...'
.
EDIT: Your example could be rewritten to a single line script like this:
gcc $(for i in `find`; do echo $i; done)
The set
statement doesn't treat spaces the way you expect; your variable is really named Pathname[space]
and is equal to [space]C:\Program Files
.
Remove the spaces from both sides of the =
sign, and put the value in double quotes:
set Pathname="C:\Program Files"
Also, if your command prompt is not open to C:\, then using cd
alone can't change drives.
Use
cd /d %Pathname%
or
pushd %Pathname%
instead.
It should be:
function moveItem() {
jQuery(".stripTransmitter ul li a").trigger('click');
}
setInterval(moveItem,2000);
setInterval(f, t)
calls the the argument function, f
, once every t
milliseconds.
Note that re.match(pattern, string, flags=0)
only returns matches at the beginning of the string. If you want to locate a match anywhere in the string, use re.search(pattern, string, flags=0)
instead (https://docs.python.org/3/library/re.html). This will scan the string and return the first match object. Then you can extract the matching string with match_object.group(0)
as the folks suggested.
Another situation that can cause this problem is incorrect casting in your queries.
I know it may sound obvious, but I have run into this by using tablename
instead of Tablename
. Check your queries, and make sure that you're using the same case as the actual names of the columns in your table.
Here is how i fixed it.
it will reinstall your pip within the environment and uninstall the previous version automatically.
now boom!! install whatever you like
require.paths
is deprecated.
Go to your project folder and type
npm install socket.io
that should install it in the local ./node_modules folder where node will look for it.
I keep my things like this:
cd ~/Sites/
mkdir sweetnodeproject
cd sweetnodeproject
npm install socket.io
Create an app.js file
// app.js
var socket = require('socket.io')
now run my app
node app.js
Make sure you're using npm >= 1.0
and node >= 4.0
.
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
label.text = @"Your String.";
label.layer.cornerRadius = 8.0;
[self.view addSubview:label];
Following all instructions, this is what I did and worked:
mysql> SELECT CONNECTION_ID();//This is my ID for this session.
+-----------------+
| CONNECTION_ID() |
+-----------------+
| 20 |
+-----------------+
1 row in set (0.00 sec)
mysql> select @max_allowed_packet //Mysql do not found @max_allowed_packet
+---------------------+
| @max_allowed_packet |
+---------------------+
| NULL |
+---------------------+
1 row in set (0.00 sec)
mysql> Select @@global.max_allowed_packet; //That is better... I have max_allowed_packet=32M inside my.ini
+-----------------------------+
| @@global.max_allowed_packet |
+-----------------------------+
| 33554432 |
+-----------------------------+
1 row in set (0.00 sec)
mysql> **SET GLOBAL max_allowed_packet=1073741824**; //Now I'm changing the value.
Query OK, 0 rows affected (0.00 sec)
mysql> select @max_allowed_packet; //Mysql not found @max_allowed_packet
+---------------------+
| @max_allowed_packet |
+---------------------+
| NULL |
+---------------------+
1 row in set (0.00 sec)
mysql> Select @@global.max_allowed_packet;//The new value. And I still have max_allowed_packet=32M inisde my.ini
+-----------------------------+
| @@global.max_allowed_packet |
+-----------------------------+
| 1073741824 |
+-----------------------------+
1 row in set (0.00 sec)
So, as we can see, the max_allowed_packet has been changed outside from my.ini.
Lets leave the session and check again:
mysql> exit
Bye
C:\Windows\System32>mysql -uroot -pPassword
Warning: Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 21
Server version: 5.6.26-log MySQL Community Server (GPL)
Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> SELECT CONNECTION_ID();//This is my ID for this session.
+-----------------+
| CONNECTION_ID() |
+-----------------+
| 21 |
+-----------------+
1 row in set (0.00 sec)
mysql> Select @@global.max_allowed_packet;//The new value still here and And I still have max_allowed_packet=32M inisde my.ini
+-----------------------------+
| @@global.max_allowed_packet |
+-----------------------------+
| 1073741824 |
+-----------------------------+
1 row in set (0.00 sec)
Now I will stop the server
2016-02-03 10:28:30 - Server is stopped
mysql> SELECT CONNECTION_ID();
ERROR 2013 (HY000): Lost connection to MySQL server during query
Now I will start the server
2016-02-03 10:31:54 - Server is running
C:\Windows\System32>mysql -uroot -pPassword
Warning: Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 5.6.26-log MySQL Community Server (GPL)
Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> SELECT CONNECTION_ID();
+-----------------+
| CONNECTION_ID() |
+-----------------+
| 9 |
+-----------------+
1 row in set (0.00 sec)
mysql> Select @@global.max_allowed_packet;//The previous new value has gone. Now I see what I have inside my.ini again.
+-----------------------------+
| @@global.max_allowed_packet |
+-----------------------------+
| 33554432 |
+-----------------------------+
1 row in set (0.00 sec)
Conclusion, after SET GLOBAL max_allowed_packet=1073741824, the server will have the new max_allowed_packet until it is restarted, as someone stated previously.
TROUBLESHOOTING STEPS (Doc ID 730066.1)
Connection Timeout errors ORA-3135 and ORA-3136 A connection timeout error can be issued when an attempt to connect to the database does not complete its connection and authentication phases within the time period allowed by the following: SQLNET.INBOUND_CONNECT_TIMEOUT and/or INBOUND_CONNECT_TIMEOUT_ server-side parameters.
Starting with Oracle 10.2, the default for these parameters is 60 seconds where in previous releases it was 0, meaning no timeout.
On a timeout, the client program will receive the ORA-3135 (or possibly TNS-3135) error:
ORA-3135 connection lost contact
and the database will log the ORA-3136 error in its alert.log:
... Sat May 10 02:21:38 2008 WARNING: inbound connection timed out (ORA-3136) ...
When a database session is in the authentication phase, it will issue a sequence of SQL statements. The authentication is not complete until all these are parsed, executed, fetched completely. Some of the SQL statements in this list e.g. on 10.2 are:
select value$ from props$ where name = 'GLOBAL_DB_NAME'
select privilege#,level from sysauth$ connect by grantee#=prior privilege#
and privilege#>0 start with grantee#=:1 and privilege#>0
select SYS_CONTEXT('USERENV', 'SERVER_HOST'), SYS_CONTEXT('USERENV', 'DB_UNIQUE_NAME'),
SYS_CONTEXT('USERENV', 'INSTANCE_NAME'), SYS_CONTEXT('USERENV', 'SERVICE_NAME'),
INSTANCE_NUMBER, STARTUP_TIME, SYS_CONTEXT('USERENV', 'DB_DOMAIN')
from v$instance where INSTANCE_NAME=SYS_CONTEXT('USERENV', 'INSTANCE_NAME')
select privilege# from sysauth$ where (grantee#=:1 or grantee#=1) and privilege#>0
ALTER SESSION SET NLS_LANGUAGE= 'AMERICAN' NLS_TERRITORY= 'AMERICA' NLS_CURRENCY= '$'
NLS_ISO_CURRENCY= 'AMERICA' NLS_NUMERIC_CHARACTERS= '.,' NLS_CALENDAR= 'GREGORIAN'
NLS_DATE_FORMAT= 'DD-MON-RR' NLS_DATE_LANGUAGE= 'AMERICAN' NLS_SORT= 'BINARY' TIME_ZONE= '+02:00'
NLS_COMP= 'BINARY' NLS_DUAL_CURRENCY= '$' NLS_TIME_FORMAT= 'HH.MI.SSXFF AM' NLS_TIMESTAMP_FORMAT=
'DD-MON-RR HH.MI.SSXFF AM' NLS_TIME_TZ_FORMAT= 'HH.MI.SSXFF AM TZR' NLS_TIMESTAMP_TZ_FORMAT=
'DD-MON-RR HH.MI.SSXFF AM TZR'
NOTE: The list of SQL above is not complete and does not represent the ordering of the authentication SQL . Differences may also exist from release to release.
The above SQL statements need to be Parsed, Executed and Fetched as happens for all SQL inside an Oracle Database. It follows that any problem encountered during these phases which appears as a hang or severe slow performance may result in a timeout.
Symptoms of such hangs will be seen by the authenticating session as waits for: • cursor: pin S wait on X • latch: row cache objects • row cache lock Other types of wait events are possible; this list may not be complete.
The issue here is that the authenticating session is blocked waiting to get a shared resource which is held by another session inside the database. That blocker session is itself occupied in a long-running activity (or its own hang) which prevents it from releasing the shared resource needed by the authenticating session in a timely fashion. This results in the timeout being eventually reported to the authenticating session.
In such situations, we need to find out the blocker process holding the shared resource needed by the authenticating session in order to see what is happening to it.
Typical diagnostics used in such cases are the following:
$ sqlplus -prelim '/ as sysdba' oradebug setmypid oradebug unlimit oradebug dump systemstate 266 ...wait 90 seconds oradebug dump systemstate 266 ...wait 90 seconds oradebug dump systemstate 266 quit
Examples of issues which can result in Authentication hangs
Unpublished Bug 7039896 workaround parameter _enable_shared_pool_durations=false see Note 7039896.8
Other approaches to avoid the problem
In some cases, it may be possible to avoid problems with Authentication SQL by pinning such statements in the Shared Pool soon after the instance is started and they are freshly loaded. You can use the following artcile to advise on this: Document 726780.1 How to Pin a Cursor in the Shared Pool using DBMS_SHARED_POOL.KEEP
Pinning will prevent them from being flushed out due to inactivity and aging and will therefore prevent them for needing to be reloaded in the future i.e. needing to be reparsed and becoming susceptible to Authentication hang issues.
iterate through the array and check its name value.
Keep in mind that search spiders don't index JS code. So, if you put your URL
inside JS code and make sure to also include it inside a traditional HTML link elsewhere on the page.
That is, if you want the linked pages to be indexed by Google, etc.
Important benefit of the dynamic resources
if application startup takes extremely long time, you must use dynamic resources, because static resources are always loaded when the window or app is created, while dynamic resources are loaded when they’re first used.
However, you won’t see any benefit unless your resource is extremely large and complex.
On macos Sierra this work for me, where python is managed by anaconda:
anaconda search -t conda mysql-python
anaconda show CEFCA/mysql-python
conda install --channel https://conda.anaconda.org/CEFCA mysql-python
The to use with SQLAlchemy:
Python 2.7.13 |Continuum Analytics, Inc.| (default, Dec 20 2016, 23:05:08) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. Anaconda is brought to you by Continuum Analytics. Please check out: http://continuum.io/thanks and https://anaconda.org
>>> from sqlalchemy import *
>>>dbengine = create_engine('mysql://....')
You may use any of these 2 variants:
/^[A-Z]+$/i
/^[A-Za-z]+$/
to match an input string of ASCII alphabets.
[A-Za-z]
will match all the alphabets (both lowercase and uppercase).^
and $
will make sure that nothing but these alphabets will be matched.Code:
preg_match('/^[A-Z]+$/i', "abcAbc^Xyz", $m);
var_dump($m);
Output:
array(0) {
}
Test case is for OP's comment that he wants to match only if there are 1 or more alphabets present in the input. As you can see in the test case that matches failed because there was ^
in the input string abcAbc^Xyz
.
Note: Please note that the above answer only matches ASCII alphabets and doesn't match Unicode characters. If you want to match Unicode letters then use:
/^\p{L}+$/u
Here, \p{L}
matches any kind of letter from any language
Check out the implode() function as an alternative. This will convert the array into a list. The first param is how you want the items separated. Here I have used a comma with a space after it.
$invite = implode(', ', $_POST['invite']);
echo $invite;
Angular's $http has a cache built in. According to the docs:
cache – {boolean|Object} – A boolean value or object created with $cacheFactory to enable or disable caching of the HTTP response. See $http Caching for more information.
So you can set cache
to true in its options:
$http.get(url, { cache: true}).success(...);
or, if you prefer the config type of call:
$http({ cache: true, url: url, method: 'GET'}).success(...);
You can also use a cache factory:
var cache = $cacheFactory('myCache');
$http.get(url, { cache: cache })
You can implement it yourself using $cacheFactory (especially handly when using $resource):
var cache = $cacheFactory('myCache');
var data = cache.get(someKey);
if (!data) {
$http.get(url).success(function(result) {
data = result;
cache.put(someKey, data);
});
}
INNER JOIN
is ANSI syntax that you should use.
It is generally considered more readable, especially when you join lots of tables.
It can also be easily replaced with an OUTER JOIN
whenever a need arises.
The WHERE
syntax is more relational model oriented.
A result of two tables JOIN
ed is a cartesian product of the tables to which a filter is applied which selects only those rows with joining columns matching.
It's easier to see this with the WHERE
syntax.
As for your example, in MySQL (and in SQL generally) these two queries are synonyms.
Also, note that MySQL also has a STRAIGHT_JOIN
clause.
Using this clause, you can control the JOIN
order: which table is scanned in the outer loop and which one is in the inner loop.
You cannot control this in MySQL using WHERE
syntax.
The substr()
function will probably help you here:
$str = substr($str, 1);
Strings are indexed starting from 0, and this functions second parameter takes the cutstart. So make that 1, and the first char is gone.
You can do as yAnTar advised
ALTER TABLE TABLE_NAME ADD Id INT AUTO_INCREMENT PRIMARY KEY
OR
You can add a constraint
ALTER TABLE TABLE_NAME ADD CONSTRAINT constr_ID UNIQUE (user_id, game_id, date, time)
But I think to not lose your existing data, you can add an indentity column and then make a composite key.
To resize the storage of the Android emulator in Linux:
1) install qemu
2) Locate the directory containing the img files of the virtual machine. Something like ~/.android/avd/.avd and cd to it.
3) Resize the ext4 images: i.e. for growing from 500Mb to 4Gb execute
qemu-img resize userdata.img +3.5GB
qemu-img resize userdata-qemu.img +3.5GB
4) grow the filesystem:
e2fsck -f userdata.img
resize2fs userdata.img
e2fsck -f userdata-qemu.img
resize2fs userdata-qemu.img
5) For the sd card image, optional: rescue the data:
mkdir 1
mount -o loop sdcard.img 1
cp -a 1 2
umount 1
6) resize the image from 100Mb to Gb:
qemu-img resize sdcard.img +3.9GB
7) re-generate the filesystem:
mkfs.vfat sdcard.img
8) optional: restore the old data:
mount -o loop sdcard.img 1
cp -a 2/* 1
mount -o loop sdcard.img 1
Remember load jquery before bootstrap js
For people who want to use multiple images of course importing them one by one would be a problem. The solution is to move the images folder to the public folder. So if you had an image at public/images/logo.jpg, you could display that image this way:
function Header() {
return (
<div>
<img src="images/logo.jpg" alt="logo"/>
</div>
);
}
Yes, no need to use /public/ in the source.
Read further: https://daveceddia.com/react-image-tag/.
simply use this code in textbox :
private void textBox1_TextChanged(object sender, EventArgs e)
{
double parsedValue;
if (!double.TryParse(textBox1.Text, out parsedValue))
{
textBox1.Text = "";
}
}
How about git log --pretty=oneline | wc -l
That should count all the commits from the perspective of your current branch.
A lot of great editors have come out since my original answer. I currently use the following text editors: Sublime Text 3 (Mac/Windows), Visual Studio Code (Mac/Windows) and Atom (Mac/Windows). I also use the following IDEs: Visual Studio 2015 (Windows/Paid & Free Versions) and Jetrbrains WebStorm (Windows/Paid, tried the demo and liked it).
My preference is using Sublime Text 3.
Microsoft Web Matrix and Dreamweaver are great.
Visual Studio and Expression Web are also great but may be overkill for you.
For just plain text editors, Sublime Text 2 is really cool
Add this line on Click on button
loginButton.setReadPermissions(Arrays.asList( "public_profile", "email", "user_birthday", "user_friends"));
Delegate :- Create
@protocol addToCartDelegate <NSObject>
-(void)addToCartAction:(ItemsModel *)itemsModel isAdded:(BOOL)added;
@end
Send and please assign delegate to view you are sending data
[self.delegate addToCartAction:itemsModel isAdded:YES];
You can set a default encoding-set whenever you run eclipse.exe.
-Dfile.encoding=UTF-8
Is this going to put people off coming to Scala?
I don't think it is the main factor that will affect how popular Scala will become, because Scala has a lot of power and its syntax is not as foreign to a Java/C++/PHP programmer as Haskell, OCaml, SML, Lisps, etc..
But I do think Scala's popularity will plateau at less than where Java is today, because I also think the next mainstream language must be much simplified, and the only way I see to get there is pure immutability, i.e. declarative like HTML, but Turing complete. However, I am biased because I am developing such a language, but I only did so after ruling out over a several month study that Scala could not suffice for what I needed.
Is this going to give Scala a bad name in the commercial world as an academic plaything that only dedicated PhD students can understand? Are CTOs and heads of software going to get scared off?
I don't think Scala's reputation will suffer from the Haskell complex. But I think that some will put off learning it, because for most programmers, I don't yet see a use case that forces them to use Scala, and they will procrastinate learning about it. Perhaps the highly-scalable server side is the most compelling use case.
And, for the mainstream market, first learning Scala is not a "breath of fresh air", where one is writing programs immediately, such as first using HTML or Python. Scala tends to grow on you, after one learns all the details that one stumbles on from the start. However, maybe if I had read Programming in Scala from the start, my experience and opinion of the learning curve would have been different.
Was the library re-design a sensible idea?
Definitely.
If you're using Scala commercially, are you worried about this? Are you planning to adopt 2.8 immediately or wait to see what happens?
I am using Scala as the initial platform of my new language. I probably wouldn't be building code on Scala's collection library if I was using Scala commercially otherwise. I would create my own category theory based library, since the one time I looked, I found Scalaz's type signatures even more verbose and unwieldy than Scala's collection library. Part of that problem perhaps is Scala's way of implementing type classes, and that is a minor reason I am creating my own language.
I decided to write this answer, because I wanted to force myself to research and compare Scala's collection class design to the one I am doing for my language. Might as well share my thought process.
The 2.8 Scala collections use of a builder abstraction is a sound design principle. I want to explore two design tradeoffs below.
WRITE-ONLY CODE: After writing this section, I read Carl Smotricz's comment which agrees with what I expect to be the tradeoff. James Strachan and davetron5000's comments concur that the meaning of That (it is not even That[B]) and the mechanism of the implicit is not easy to grasp intuitively. See my use of monoid in issue #2 below, which I think is much more explicit. Derek Mahar's comment is about writing Scala, but what about reading the Scala of others that is not "in the common cases".
One criticism I have read about Scala, is that it is easier to write it, than read the code that others have written. And I find this to be occasionally true for various reasons (e.g. many ways to write a function, automatic closures, Unit for DSLs, etc), but I am undecided if this is major factor. Here the use of implicit function parameters has pluses and minuses. On the plus side, it reduces verbosity and automates selection of the builder object. In Odersky's example the conversion from a BitSet, i.e. Set[Int], to a Set[String] is implicit. The unfamiliar reader of the code might not readily know what the type of collection is, unless they can reason well about the all the potential invisible implicit builder candidates which might exist in the current package scope. Of course, the experienced programmer and the writer of the code will know that BitSet is limited to Int, thus a map to String has to convert to a different collection type. But which collection type? It isn't specified explicitly.
AD-HOC COLLECTION DESIGN: After writing this section, I read Tony Morris's comment and realized I am making nearly the same point. Perhaps my more verbose exposition will make the point more clear.
In "Fighting Bit Rot with Types" Odersky & Moors, two use cases are presented. They are the restriction of BitSet to Int elements, and Map to pair tuple elements, and are provided as the reason that the general element mapping function, A => B, must be able to build alternative destination collection types. However, afaik this is flawed from a category theory perspective. To be consistent in category theory and thus avoid corner cases, these collection types are functors, in which each morphism, A => B, must map between objects in the same functor category, List[A] => List[B], BitSet[A] => BitSet[B]. For example, an Option is a functor that can be viewed as a collection of sets of one Some( object ) and the None. There is no general map from Option's None, or List's Nil, to other functors which don't have an "empty" state.
There is a tradeoff design choice made here. In the design for collections library of my new language, I chose to make everything a functor, which means if I implement a BitSet, it needs to support all element types, by using a non-bit field internal representation when presented with a non-integer type parameter, and that functionality is already in the Set which it inherits from in Scala. And Map in my design needs to map only its values, and it can provide a separate non-functor method for mapping its (key,value) pair tuples. One advantage is that each functor is then usually also an applicative and perhaps a monad too. Thus all functions between element types, e.g. A => B => C => D => ..., are automatically lifted to the functions between lifted applicative types, e.g. List[A] => List[B] => List[C] => List[D] => .... For mapping from a functor to another collection class, I offer a map overload which takes a monoid, e.g. Nil, None, 0, "", Array(), etc.. So the builder abstraction function is the append method of a monoid and is supplied explicitly as a necessary input parameter, thus with no invisible implicit conversions. (Tangent: this input parameter also enables appending to non-empty monoids, which Scala's map design can't do.) Such conversions are a map and a fold in the same iteration pass. Also I provide a traversable, in the category sense, "Applicative programming with effects" McBride & Patterson, which also enables map + fold in a single iteration pass from any traversable to any applicative, where most every collection class is both. Also the state monad is an applicative and thus is a fully generalized builder abstraction from any traversable.
So afaics the Scala collections is "ad-hoc" in the sense that it is not grounded in category theory, and category theory is the essense of higher-level denotational semantics. Although Scala's implicit builders are at first appearance "more generalized" than a functor model + monoid builder + traversable -> applicative, they are afaik not proven to be consistent with any category, and thus we don't know what rules they follow in the most general sense and what the corner cases will be given they may not obey any category model. It is simply not true that adding more variables makes something more general, and this was one of huge benefits of category theory is it provides rules by which to maintain generality while lifting to higher-level semantics. A collection is a category.
I read somewhere, I think it was Odersky, as another justification for the library design, is that programming in a pure functional style has the cost of limited recursion and speed where tail recursion isn't used. I haven't found it difficult to employ tail recursion in every case that I have encountered so far.
Additionally I am carrying in my mind an incomplete idea that some of Scala's tradeoffs are due to trying to be both an mutable and immutable language, unlike for example Haskell or the language I am developing. This concurs with Tony Morris's comment about for comprehensions. In my language, there are no loops and no mutable constructs. My language will sit on top of Scala (for now) and owes much to it, and this wouldn't be possible if Scala didn't have the general type system and mutability. That might not be true though, because I think Odersky & Moors ("Fighting Bit Rot with Types") are incorrect to state that Scala is the only OOP language with higher-kinds, because I verified (myself and via Bob Harper) that Standard ML has them. Also appears SML's type system may be equivalently flexible (since 1980s), which may not be readily appreciated because the syntax is not so much similar to Java (and C++/PHP) as Scala. In any case, this isn't a criticism of Scala, but rather an attempt to present an incomplete analysis of tradeoffs, which is I hope germane to the question. Scala and SML don't suffer from Haskell's inability to do diamond multiple inheritance, which is critical and I understand is why so many functions in the Haskell Prelude are repeated for different types.
@Component
@Controller
@Repository
@Service
@RestController
These are all StereoType annotations.this are usefull for the making our classes as spring beans in ioc container,
In General to get rid of
Object of class stdClass could not be converted to string.
try to use echo '<pre>'; print_r($sql_query);
for my SQL Query got the result as
stdClass Object
(
[num_rows] => 1
[row] => Array
(
[option_id] => 2
[type] => select
[sort_order] => 0
)
[rows] => Array
(
[0] => Array
(
[option_id] => 2
[type] => select
[sort_order] => 0
)
)
)
In order to acces there are different methods E.g.: num_rows, row, rows
echo $query2->row['option_id'];
Will give the result as 2
%s/\s*$/\*/g
this will do the trick, and ensure leading spaces are ignored.
After Python 3.4, you can also use pathlib
's class Path
to move file.
from pathlib import Path
Path("path/to/current/file.foo").rename("path/to/new/destination/for/file.foo")
https://docs.python.org/3.4/library/pathlib.html#pathlib.Path.rename
An IP gives you an quite unreliable location, you could Ajax the location upon load with JS if it isn't critical to have the location at first. (Also, the user need's to give you it's permission to access it.)
For API 23+ you need to request the read/write permissions even if they are already in your manifest.
// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
/**
* Checks if the app has permission to write to device storage
*
* If the app does not has permission then the user will be prompted to grant permissions
*
* @param activity
*/
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
For official documentation about requesting permissions for API 23+, check https://developer.android.com/training/permissions/requesting.html
You push your local repository to the remote repository using the git push
command after first establishing a relationship between the two with the git remote add [alias] [url]
command. If you visit your Github repository, it will show you the URL to use for pushing. You'll first enter something like:
git remote add origin [email protected]:username/reponame.git
Unless you started by running git clone
against the remote repository, in which case this step has been done for you already.
And after that, you'll type:
git push origin master
After your first push, you can simply type:
git push
when you want to update the remote repository in the future.
My answer is intended for comment though but since i havent got enough reputation, i think it will still be relevant as an answer and help some one.
I find datatable
in library DT
robust to handle rownames
, and columnames
Library DT
datatable(df, rownames = FALSE) # no row names
refer to https://rstudio.github.io/DT/ for usage scenarios
Another way is to use the subplots
function and pass the width ratio with gridspec_kw
:
import numpy as np
import matplotlib.pyplot as plt
# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)
# plot it
f, (a0, a1) = plt.subplots(1, 2, gridspec_kw={'width_ratios': [3, 1]})
a0.plot(x, y)
a1.plot(y, x)
f.tight_layout()
f.savefig('grid_figure.pdf')
To anyone else who finds this older question, you can now download all old versions.
Xcode
-> Preferences
-> Components
(Click on Simulators tab).
Install all the versions you want/need.
To show all installed simulators:
Target -> In dropdown "deployment target" choose the installed version with lowest version nr.
You should now see all your available simulators in the dropdown.
dim lastRow as long 'in VBA it's a long
lastrow = wks.range("A65000").end(xlup).row
Give this a try :P
s = '#'.repeat(10)_x000D_
_x000D_
document.body.innerHTML = s
_x000D_
Otro example, custom Data Pagination for JOIN
CODE in Controller CakePHP 2.6 is OK:
$this->SenasaPedidosFacturadosSds->recursive = -1;
// Filtro
$where = array(
'joins' => array(
array(
'table' => 'usuarios',
'alias' => 'Usuarios',
'type' => 'INNER',
'conditions' => array(
'Usuarios.usuario_id = SenasaPedidosFacturadosSds.usuarios_id'
)
),
array(
'table' => 'senasa_pedidos',
'alias' => 'SenasaPedidos',
'type' => 'INNER',
'conditions' => array(
'SenasaPedidos.id = SenasaPedidosFacturadosSds.senasa_pedidos_id'
)
),
array(
'table' => 'clientes',
'alias' => 'Clientes',
'type' => 'INNER',
'conditions' => array(
'Clientes.id_cliente = SenasaPedidos.clientes_id'
)
),
),
'fields'=>array(
'SenasaPedidosFacturadosSds.*',
'Usuarios.usuario_id',
'Usuarios.apellido_nombre',
'Usuarios.senasa_establecimientos_id',
'Clientes.id_cliente',
'Clientes.consolida_doc_sanitaria',
'Clientes.requiere_senasa',
'Clientes.razon_social',
'SenasaPedidos.id',
'SenasaPedidos.domicilio_entrega',
'SenasaPedidos.sds',
'SenasaPedidos.pt_ptr'
),
'conditions'=>array(
'Clientes.requiere_senasa'=>1
),
'order' => 'SenasaPedidosFacturadosSds.created DESC',
'limit'=>100
);
$this->paginate = $where;
// Get datos
$data = $this->Paginator->paginate();
exit(debug($data));
OR Example 2, NOT active conditions:
$this->SenasaPedidosFacturadosSds->recursive = -1;
// Filtro
$where = array(
'joins' => array(
array(
'table' => 'usuarios',
'alias' => 'Usuarios',
'type' => 'INNER',
'conditions' => array(
'Usuarios.usuario_id = SenasaPedidosFacturadosSds.usuarios_id'
)
),
array(
'table' => 'senasa_pedidos',
'alias' => 'SenasaPedidos',
'type' => 'INNER',
'conditions' => array(
'SenasaPedidos.id = SenasaPedidosFacturadosSds.senasa_pedidos_id'
)
),
array(
'table' => 'clientes',
'alias' => 'Clientes',
'type' => 'INNER',
'conditions' => array(
'Clientes.id_cliente = SenasaPedidos.clientes_id',
'Clientes.requiere_senasa = 1'
)
),
),
'fields'=>array(
'SenasaPedidosFacturadosSds.*',
'Usuarios.usuario_id',
'Usuarios.apellido_nombre',
'Usuarios.senasa_establecimientos_id',
'Clientes.id_cliente',
'Clientes.consolida_doc_sanitaria',
'Clientes.requiere_senasa',
'Clientes.razon_social',
'SenasaPedidos.id',
'SenasaPedidos.domicilio_entrega',
'SenasaPedidos.sds',
'SenasaPedidos.pt_ptr'
),
//'conditions'=>array(
// 'Clientes.requiere_senasa'=>1
//),
'order' => 'SenasaPedidosFacturadosSds.created DESC',
'limit'=>100
);
$this->paginate = $where;
// Get datos
$data = $this->Paginator->paginate();
exit(debug($data));
You could access your class's __dict__
attribute:
for i in range(3)
self.__dict__['group%d' % i]=self.getGroup(selected, header+i)
But why can't you just use an array named group
?
This will do it assuming you want this to happen each time you open the command line:
echo cd ../../../d/work_space_for_my_company/project/code_source >> ~/.bashrc
Now when you open the shell it will move up three directories from home and change to code_source.
This code simply appends the line "cd ../../../d/work_space_for_my_company/project/code_source" to a file named ".bashrc". The ">>" creates a file if it does not exist and then appends. The .bashrc file is useful for running commands at start-up/log-in time (i.e. loading modules etc.)
Don't know about plugins but this shouldn't be too hard:
;(function($) {
$.fn.counter = function(options) {
// Set default values
var defaults = {
start: 0,
end: 10,
time: 10,
step: 1000,
callback: function() { }
}
var options = $.extend(defaults, options);
// The actual function that does the counting
var counterFunc = function(el, increment, end, step) {
var value = parseInt(el.html(), 10) + increment;
if(value >= end) {
el.html(Math.round(end));
options.callback();
} else {
el.html(Math.round(value));
setTimeout(counterFunc, step, el, increment, end, step);
}
}
// Set initial value
$(this).html(Math.round(options.start));
// Calculate the increment on each step
var increment = (options.end - options.start) / ((1000 / options.step) * options.time);
// Call the counter function in a closure to avoid conflicts
(function(e, i, o, s) {
setTimeout(counterFunc, s, e, i, o, s);
})($(this), increment, options.end, options.step);
}
})(jQuery);
Usage:
$('#foo').counter({
start: 1000,
end: 4500,
time: 8,
step: 500,
callback: function() {
alert("I'm done!");
}
});
Example:
I guess the usage is self-explanatory; in this example, the counter will start from 1000 and count up to 4500 in 8 seconds in 500ms intervals, and will call the callback function when the counting is done.
If the shell scripts start with #!/bin/bash
, they will always run with bash
from /bin
. If they however start with #!/usr/bin/env bash
, they will search for bash
in $PATH
and then start with the first one they can find.
Why would this be useful? Assume you want to run bash
scripts, that require bash 4.x or newer, yet your system only has bash
3.x installed and currently your distribution doesn't offer a newer version or you are no administrator and cannot change what is installed on that system.
Of course, you can download bash source code and build your own bash from scratch, placing it to ~/bin
for example. And you can also modify your $PATH
variable in your .bash_profile
file to include ~/bin
as the first entry (PATH=$HOME/bin:$PATH
as ~
will not expand in $PATH
). If you now call bash
, the shell will first look for it in $PATH
in order, so it starts with ~/bin
, where it will find your bash
. Same thing happens if scripts search for bash
using #!/usr/bin/env bash
, so these scripts would now be working on your system using your custom bash
build.
One downside is, that this can lead to unexpected behavior, e.g. same script on the same machine may run with different interpreters for different environments or users with different search paths, causing all kind of headaches.
The biggest downside with env
is that some systems will only allow one argument, so you cannot do this #!/usr/bin/env <interpreter> <arg>
, as the systems will see <interpreter> <arg>
as one argument (they will treat it as if the expression was quoted) and thus env
will search for an interpreter named <interpreter> <arg>
. Note that this is not a problem of the env
command itself, which always allowed multiple parameters to be passed through but with the shebang parser of the system that parses this line before even calling env
. Meanwhile this has been fixed on most systems but if your script wants to be ultra portable, you cannot rely that this has been fixed on the system you will be running.
It can even have security implications, e.g. if sudo
was not configured to clean environment or $PATH
was excluded from clean up. Let me demonstrate this:
Usually /bin
is a well protected place, only root
is able to change anything there. Your home directory is not, though, any program you run is able to make changes to it. That means malicious code could place a fake bash
into some hidden directory, modify your .bash_profile
to include that directory in your $PATH
, so all scripts using #!/usr/bin/env bash
will end up running with that fake bash
. If sudo
keeps $PATH
, you are in big trouble.
E.g. consider a tool creates a file ~/.evil/bash
with the following content:
#!/bin/bash
if [ $EUID -eq 0 ]; then
echo "All your base are belong to us..."
# We are root - do whatever you want to do
fi
/bin/bash "$@"
Let's make a simple script sample.sh
:
#!/usr/bin/env bash
echo "Hello World"
Proof of concept (on a system where sudo
keeps $PATH
):
$ ./sample.sh
Hello World
$ sudo ./sample.sh
Hello World
$ export PATH="$HOME/.evil:$PATH"
$ ./sample.sh
Hello World
$ sudo ./sample.sh
All your base are belong to us...
Hello World
Usually the classic shells should all be located in /bin
and if you don't want to place them there for whatever reason, it's really not an issue to place a symlink in /bin
that points to their real locations (or maybe /bin
itself is a symlink), so I would always go with #!/bin/sh
and #!/bin/bash
. There's just too much that would break if these wouldn't work anymore. It's not that POSIX would require these position (POSIX does not standardize path names and thus it doesn't even standardize the shebang feature at all) but they are so common, that even if a system would not offer a /bin/sh
, it would probably still understand #!/bin/sh
and know what to do with it and may it only be for compatibility with existing code.
But for more modern, non standard, optional interpreters like Perl, PHP, Python, or Ruby, it's not really specified anywhere where they should be located. They may be in /usr/bin
but they may as well be in /usr/local/bin
or in a completely different hierarchy branch (/opt/...
, /Applications/...
, etc.). That's why these often use the #!/usr/bin/env xxx
shebang syntax.
I use BuildConfig.VERSION_NAME.toString();
. What's the difference between that and getting it from the packageManager?
No XML based solutions have worked for me, sorry.
You cannot attach events before the elements you attach them to has loaded
This works -
Plain JS
Recommended to use eventListener
// Should only be triggered on first page load
console.log('ho');
window.addEventListener("load", function() {
document.getElementById('my-form').addEventListener("submit", function(e) {
e.preventDefault(); // before the code
/* do what you want with the form */
// Should be triggered on form submit
console.log('hi');
})
});
_x000D_
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
_x000D_
but if you do not need more than one listener you can use onload and onsubmit
// Should only be triggered on first page load
console.log('ho');
window.onload = function() {
document.getElementById('my-form').onsubmit = function() {
/* do what you want with the form */
// Should be triggered on form submit
console.log('hi');
// You must return false to prevent the default form behavior
return false;
}
}
_x000D_
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
_x000D_
jQuery
// Should only be triggered on first page load
console.log('ho');
$(function() {
$('#my-form').on("submit", function(e) {
e.preventDefault(); // cancel the actual submit
/* do what you want with the form */
// Should be triggered on form submit
console.log('hi');
});
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
_x000D_
Demi Magus answer worked for me until Rails 5.
On Apache2/Passenger/Ruby (2.4)/Rails (5.1.6), I had to put
export SECRET_KEY_BASE=GENERATED_CODE
from Demi Magus answer in /etc/apache2/envvars, cause /etc/profile seems to be ignored.
Source: https://www.phusionpassenger.com/library/indepth/environment_variables.html#apache
I have also one solution. I always use this method. Try this
<ScrollView
android:id="@+id/createdrill_scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="15dp" >
<net.thepaksoft.fdtrainer.NestedListView
android:id="@+id/crewList"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:layout_weight="1"
android:background="@drawable/round_shape"
android:cacheColorHint="#00000000" >
</net.thepaksoft.fdtrainer.NestedListView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="15dp" >
<net.thepaksoft.fdtrainer.NestedListView
android:id="@+id/benchmarksList"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:layout_weight="1"
android:background="@drawable/round_shape"
android:cacheColorHint="#00000000" >
</net.thepaksoft.fdtrainer.NestedListView>
</LinearLayout>
</ScrollView>
NestedListView.java class:
public class NestedListView extends ListView implements OnTouchListener, OnScrollListener {
private int listViewTouchAction;
private static final int MAXIMUM_LIST_ITEMS_VIEWABLE = 99;
public NestedListView(Context context, AttributeSet attrs) {
super(context, attrs);
listViewTouchAction = -1;
setOnScrollListener(this);
setOnTouchListener(this);
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (getAdapter() != null && getAdapter().getCount() > MAXIMUM_LIST_ITEMS_VIEWABLE) {
if (listViewTouchAction == MotionEvent.ACTION_MOVE) {
scrollBy(0, -1);
}
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int newHeight = 0;
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (heightMode != MeasureSpec.EXACTLY) {
ListAdapter listAdapter = getAdapter();
if (listAdapter != null && !listAdapter.isEmpty()) {
int listPosition = 0;
for (listPosition = 0; listPosition < listAdapter.getCount()
&& listPosition < MAXIMUM_LIST_ITEMS_VIEWABLE; listPosition++) {
View listItem = listAdapter.getView(listPosition, null, this);
//now it will not throw a NPE if listItem is a ViewGroup instance
if (listItem instanceof ViewGroup) {
listItem.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
listItem.measure(widthMeasureSpec, heightMeasureSpec);
newHeight += listItem.getMeasuredHeight();
}
newHeight += getDividerHeight() * listPosition;
}
if ((heightMode == MeasureSpec.AT_MOST) && (newHeight > heightSize)) {
if (newHeight > heightSize) {
newHeight = heightSize;
}
}
} else {
newHeight = getMeasuredHeight();
}
setMeasuredDimension(getMeasuredWidth(), newHeight);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (getAdapter() != null && getAdapter().getCount() > MAXIMUM_LIST_ITEMS_VIEWABLE) {
if (listViewTouchAction == MotionEvent.ACTION_MOVE) {
scrollBy(0, 1);
}
}
return false;
}
}
iOS7 onwards, we have below default methods :
- (UIView *)snapshotViewAfterScreenUpdates:(BOOL)afterUpdates
Calling above method is faster than trying to render the contents of the current view into a bitmap image yourself.
If you want to apply a graphical effect, such as blur, to a snapshot, use the drawViewHierarchyInRect:afterScreenUpdates:
method instead.
Inspired by the answers to this question, I made a simple counter batch script that keeps printing the progress value (0-100%) on the same line (overwritting the previous one). Maybe this will also be valuable to others looking for a similar solution.
Remark: The *
are non-printable characters, these should be entered using [Alt
+ Numpad 0
+ Numpad 8
] key combination, which is the backspace
character.
@ECHO OFF
FOR /L %%A in (0, 10, 100) DO (
ECHO|SET /P="****%%A%%"
CALL:Wait 1
)
GOTO:EOF
:Wait
SET /A "delay=%~1+1"
CALL PING 127.0.0.1 -n %delay% > NUL
GOTO:EOF
For the second parameter,i.e. keep some tags, you may need some code like this by using HTMLagilityPack:
public string StripTags(HtmlNode documentNode, IList keepTags)
{
var result = new StringBuilder();
foreach (var childNode in documentNode.ChildNodes)
{
if (childNode.Name.ToLower() == "#text")
{
result.Append(childNode.InnerText);
}
else
{
if (!keepTags.Contains(childNode.Name.ToLower()))
{
result.Append(StripTags(childNode, keepTags));
}
else
{
result.Append(childNode.OuterHtml.Replace(childNode.InnerHtml, StripTags(childNode, keepTags)));
}
}
}
return result.ToString();
}
More explanation on this page: http://nalgorithm.com/2015/11/20/strip-html-tags-of-an-html-in-c-strip_html-php-equivalent/
Hashing algorithms such as sha1 and md5 are not suitable for password storing. They are designed to be very efficient. This means that brute forcing is very fast. Even if a hacker obtains a copy of your hashed passwords, it is pretty fast to brute force it. If you use a salt, it makes rainbow tables less effective, but does nothing against brute force. Using a slower algorithm makes brute force ineffective. For instance, the bcrypt algorithm can be made as slow as you wish (just change the work factor), and it uses salts internally to protect against rainbow tables. I would go with such an approach or similar (e.g. scrypt or PBKDF2) if I were you.
Or you could use the object tag:
<!--[if IE]>
<object classid="clsid:25336920-03F9-11CF-8FD0-00AA00686F13" data="http://www.google.be">
<p>backup content</p>
</object>
<![endif]-->
<!--[if !IE]> <-->
<object type="text/html" data="http://www.flickr.com" style="width:100%; height:100%">
<p>backup content</p>
</object>
<!--> <![endif]-->
If you have
<div>
<input type="checkbox" class="check-with-label" id="idinput" />
<label class="label-for-check" for="idinput">My Label</label>
</div>
you can do
.check-with-label:checked + .label-for-check {
font-weight: bold;
}
See this working. Note that this won't work in non-modern browsers.
Okay adding to @null's awesome post about using the Asset Catalog.
You may need to do the following to get the App's Icon linked and working for Ad-Hoc distributions / production to be seen in Organiser, Test flight and possibly unknown AppStore locations.
After creating the Asset Catalog, take note of the name of the Launch Images and App Icon names listed in the .xassets
in Xcode.
By Default this should be
AppIcon
LaunchImage
[To see this click on your .xassets folder/icon in Xcode.] (this can be changed, so just take note of this variable for later)
What is created now each build is the following data structures in your .app:
For App Icons:
iPhone
AppIcon57x57.png
(iPhone non retina) [Notice the Icon name prefix][email protected]
(iPhone retina)And the same format for each of the other icon resolutions.
iPad
AppIcon72x72~ipad.png
(iPad non retina) AppIcon72x72@2x~ipad.png
(iPad retina)(For iPad it is slightly different postfix)
Main Problem
Now I noticed that in my Info.plist
in Xcode 5.0.1 it automatically attempted and failed to create a key for "Icon files (iOS 5)
" after completing the creation of the Asset Catalog.
If it did create a reference successfully / this may have been patched by Apple or just worked, then all you have to do is review the image names to validate the format listed above.
Final Solution:
Add the following key to you main .plist
I suggest you open your main .plist
with a external text editor such as TextWrangler rather than in Xcode to copy and paste the following key in.
<key>CFBundleIcons</key>
<dict>
<key>CFBundlePrimaryIcon</key>
<dict>
<key>CFBundleIconFiles</key>
<array>
<string>AppIcon57x57.png</string>
<string>[email protected]</string>
<string>AppIcon72x72~ipad.png</string>
<string>AppIcon72x72@2x~ipad.png</string>
</array>
</dict>
</dict>
Please Note I have only included my example resolutions, you will need to add them all.
If you want to add this Key in Xcode without an external editor, Use the following:
Icon files (iOS 5)
- DictionaryPrimary Icon
- DictionaryIcon files
- ArrayItem 0
- String = AppIcon57x57.png
And for each other item / app icon.Now when you finally archive your project the final .xcarchive payload .plist will now include the above stated icon locations to build and use.
<key>IconPaths</key>
<array>
<string>Applications/Example.app/AppIcon57x57.png</string>
<string>Applications/Example.app/[email protected]</string>
<string>Applications/Example.app/AppIcon72x72~ipad.png</string>
<string>Applications/Example.app/AppIcon72x72@2x~ipad.png</string>
</array>
Grokking lookaround rapidly.
How to distinguish lookahead and lookbehind?
Take 2 minutes tour with me:
(?=) - positive lookahead
(?<=) - positive lookbehind
Suppose
A B C #in a line
Now, we ask B, Where are you?
B has two solutions to declare it location:
One, B has A ahead and has C bebind
Two, B is ahead(lookahead) of C and behind (lookhehind) A.
As we can see, the behind and ahead are opposite in the two solutions.
Regex is solution Two.
This is because h1
is a block element, so it will extend across the line (or the width you give).
You can make the border go only around the text by setting display:inline
on the h1
I had been facing similar problem in downloading big files this works fine for me now:
safe_mode = off
max_input_time = 9000
memory_limit = 1073741824
post_max_size = 1073741824
file_uploads = On
upload_max_filesize = 1073741824
max_file_uploads = 100
allow_url_fopen = On
Hope this helps.
In case this helps anyone:
I had a similar issue, and following Nates instructions I added:
<system.web>
<customErrors mode="Off"/>
</system.web>
This showed me more information about the error:
"ExceptionMessage": "Unable to load the specified metadata resource.", "ExceptionType": "System.Data.Entity.Core.MetadataException", "StackTrace": " at System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoaderCompositeResource.LoadResources(...
This is when I remembered that I had moved the edmx file to a different location and had forgotten to change the connectionstrings node in the config (connectionsstrings node was placed in a seperate file using "configSource", but that's another story).
scope - https://www.googleapis.com/auth/userinfo.profile
return youraccess_token = access_token
get https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=youraccess_token
you will get json:
{
"id": "xx",
"name": "xx",
"given_name": "xx",
"family_name": "xx",
"link": "xx",
"picture": "xx",
"gender": "xx",
"locale": "xx"
}
To Tahir Yasin:
This is a php example.
You can use json_decode function to get userInfo array.
$q = 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=xxx';
$json = file_get_contents($q);
$userInfoArray = json_decode($json,true);
$googleEmail = $userInfoArray['email'];
$googleFirstName = $userInfoArray['given_name'];
$googleLastName = $userInfoArray['family_name'];
Please check that your class and namespace name is the same...
It happens when the namespace and class name are the same. do one thing write the full name of the namespace when you want to use the namespace.
using Student.Models.Db;
namespace Student.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
List<Student> student = null;
return View();
}
}
new Date().toString();
http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/
Dateformatter can make it to any string you want
I had same issue reported here. I solved the issue moving the mainTest.cpp from a subfolder src/mainTest/ to the main folder src/ I guess this was your problem too.
You can pass your json Input as a POST request along with authorization header in this way
public static JSONObject getHttpConn(String json){
JSONObject jsonObject=null;
try {
HttpPost httpPost=new HttpPost("http://google.com/");
org.apache.http.client.HttpClient client = HttpClientBuilder.create().build();
StringEntity stringEntity=new StringEntity("d="+json);
httpPost.addHeader("content-type", "application/x-www-form-urlencoded");
String authorization="test:test@123";
String encodedAuth = "Basic " + Base64.encode(authorization.getBytes());
httpPost.addHeader("Authorization", security.get("Authorization"));
httpPost.setEntity(stringEntity);
HttpResponse reponse=client.execute(httpPost);
InputStream inputStream=reponse.getEntity().getContent();
String jsonResponse=IOUtils.toString(inputStream);
jsonObject=JSONObject.fromObject(jsonResponse);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonObject;
}
This Method will return a json response.In same way you can use GET method
Same issue here and whatever I tried after searching around, did not work. Until I saw a remark somewhere about global or local installs. Looking in:
C:\Users\YourName\AppData\Roaming\npm\gulp
I indeed found an outdated version. So I reinstalled gulp with:
npm install gulp --global
That magically solved my problem.
Put the query arguments in hidden input fields:
<form action="http://spufalcons.com/index.aspx">
<input type="hidden" name="tab" value="gymnastics" />
<input type="hidden" name="path" value="gym" />
<input type="submit" value="SPU Gymnastics"/>
</form>
The final
keyword in java is used to restrict the user. The java final
keyword can be used in many context. Final can be:
The final
keyword can be applied with the variables, a final
variable that has no value, is called blank final
variable or uninitialized final
variable. It can be initialized in the constructor only. The blank final
variable can be static
also which will be initialized in the static
block only.
Java final variable:
If you make any variable as final
, you cannot change the value of final
variable(It will be constant).
Example of final
variable
There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because final variable once assigned a value can never be changed.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400; // this will make error
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Java final class:
If you make any class as final
, you cannot extend it.
Example of final class
final class Bike{}
class Honda1 extends Bike{ //cannot inherit from final Bike,this will make error
void run(){
System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda1 honda= new Honda();
honda.run();
}
}
Java final method:
If you make any method as final, you cannot override it.
Example of final
method
(run() in Honda cannot override run() in Bike)
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
shared from: http://www.javatpoint.com/final-keyword
Here you go, no frameworks, short and simple:
var el = document.getElementById('elId');
var elTop = el.getBoundingClientRect().top - document.body.getBoundingClientRect().top;
window.addEventListener('scroll', function(){
if (document.documentElement.scrollTop > elTop){
el.style.position = 'fixed';
el.style.top = '0px';
}
else
{
el.style.position = 'static';
el.style.top = 'auto';
}
});
The problem seems to be that you have misunderstood how async/await work with Entity Framework.
So, let's look at this code:
public IQueryable<URL> GetAllUrls()
{
return context.Urls.AsQueryable();
}
and example of it usage:
repo.GetAllUrls().Where(u => <condition>).Take(10).ToList()
What happens there?
IQueryable
object (not accessing database yet) using repo.GetAllUrls()
IQueryable
object with specified condition using .Where(u => <condition>
IQueryable
object with specified paging limit using .Take(10)
.ToList()
. Our IQueryable
object is compiled to sql (like select top 10 * from Urls where <condition>
). And database can use indexes, sql server send you only 10 objects from your database (not all billion urls stored in database)Okay, let's look at first code:
public async Task<IQueryable<URL>> GetAllUrlsAsync()
{
var urls = await context.Urls.ToListAsync();
return urls.AsQueryable();
}
With the same example of usage we got:
await context.Urls.ToListAsync();
.Why async/await is preferred to use? Let's look at this code:
var stuff1 = repo.GetStuff1ForUser(userId);
var stuff2 = repo.GetStuff2ForUser(userId);
return View(new Model(stuff1, stuff2));
What happens here?
var stuff1 = ...
userId
var stuff2 = ...
userId
So let's look to an async version of it:
var stuff1Task = repo.GetStuff1ForUserAsync(userId);
var stuff2Task = repo.GetStuff2ForUserAsync(userId);
await Task.WhenAll(stuff1Task, stuff2Task);
return View(new Model(stuff1Task.Result, stuff2Task.Result));
What happens here?
So good code here:
using System.Data.Entity;
public IQueryable<URL> GetAllUrls()
{
return context.Urls.AsQueryable();
}
public async Task<List<URL>> GetAllUrlsByUser(int userId) {
return await GetAllUrls().Where(u => u.User.Id == userId).ToListAsync();
}
Note, than you must add using System.Data.Entity
in order to use method ToListAsync()
for IQueryable.
Note, that if you don't need filtering and paging and stuff, you don't need to work with IQueryable
. You can just use await context.Urls.ToListAsync()
and work with materialized List<Url>
.
There are already great solutions on this page, but all have assumed the dataset is uniformly/evenly sampled/distributed. I will try to provide a more general example of randomly sampled data. I will also use this MATLAB tutorial as an example:
Adding the required modules:
import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack
import scipy.signal
Generating sample data:
N = 600 # Number of samples
t = np.random.uniform(0.0, 1.0, N) # Assuming the time start is 0.0 and time end is 1.0
S = 1.0 * np.sin(50.0 * 2 * np.pi * t) + 0.5 * np.sin(80.0 * 2 * np.pi * t)
X = S + 0.01 * np.random.randn(N) # Adding noise
Sorting the data set:
order = np.argsort(t)
ts = np.array(t)[order]
Xs = np.array(X)[order]
Resampling:
T = (t.max() - t.min()) / N # Average period
Fs = 1 / T # Average sample rate frequency
f = Fs * np.arange(0, N // 2 + 1) / N; # Resampled frequency vector
X_new, t_new = scipy.signal.resample(Xs, N, ts)
Plotting the data and resampled data:
plt.xlim(0, 0.1)
plt.plot(t_new, X_new, label="resampled")
plt.plot(ts, Xs, label="org")
plt.legend()
plt.ylabel("X")
plt.xlabel("t")
Now calculating the FFT:
Y = scipy.fftpack.fft(X_new)
P2 = np.abs(Y / N)
P1 = P2[0 : N // 2 + 1]
P1[1 : -2] = 2 * P1[1 : -2]
plt.ylabel("Y")
plt.xlabel("f")
plt.plot(f, P1)
P.S. I finally got time to implement a more canonical algorithm to get a Fourier transform of unevenly distributed data. You may see the code, description, and example Jupyter notebook here.
This works because Integer::min
resolves to an implementation of the Comparator<Integer>
interface.
The method reference of Integer::min
resolves to Integer.min(int a, int b)
, resolved to IntBinaryOperator
, and presumably autoboxing occurs somewhere making it a BinaryOperator<Integer>
.
And the min()
resp max()
methods of the Stream<Integer>
ask the Comparator<Integer>
interface to be implemented.
Now this resolves to the single method Integer compareTo(Integer o1, Integer o2)
. Which is of type BinaryOperator<Integer>
.
And thus the magic has happened as both methods are a BinaryOperator<Integer>
.
I'd do it this way:
grid1.DataContext = dt.AsEnumerable().Where(x => x < 10).AsEnumerable().CopyToDataTable().AsDataView();
and do whatever query i want between the two AsEnumerable(). If you don't need space for query, you can just do directly this:
grid1.DataContext = dt.AsDataView();
A simpler way to do this would be:
Sub populateB()
For Each Cel in Range("A1:A100")
If Cel.value <> "" Then Cel.Offset(0, 1).value = "Your Text"
Next
End Sub
Yes it makes sense to use requireJS with Angular, I spent several days to test several technical solutions.
I made an Angular Seed with RequireJS on Server Side. Very simple one. I use SHIM notation for no AMD module and not AMD because I think it's very difficult to deal with two different Dependency injection system.
I use grunt and r.js to concatenate js files on server depends on the SHIM configuration (dependency) file. So I refer only one js file in my app.
For more information go on my github Angular Seed : https://github.com/matohawk/angular-seed-requirejs
I managed to fix it finally. The problem is not related to HikariCP.
The problem persisted because of some complex methods in REST controllers executing multiple changes in DB through JPA repositories. For some reasons calls to these interfaces resulted in a growing number of "freezed" active connections, exhausting the pool. Either annotating these methods as @Transactional
or enveloping all the logic in a single call to transactional service method seem to solve the problem.
The exit code of the last command ran.
Add property of show header in gridview
<asp:GridView ID="dgvUsers" runat="server" **showHeader="True"** CssClass="table table-hover table-striped" GridLines="None"
AutoGenerateColumns="False">
and in columns add header template
<HeaderTemplate>
//header column names
</HeaderTemplate>
SELECT * FROM Member WHERE month(date_created) = month(NOW() - INTERVAL 1 MONTH);
I suggest to use
for string only state values
export default class Home extends React.Component<{}, { [key: string]: string }> { }
for string key and any type of state values
export default class Home extends React.Component<{}, { [key: string]: any}> { }
for any key / any values
export default class Home extends React.Component<{}, { [key: any]: any}> {}
you can also try this trick:
ps aux | grep puma
sample output:
myname 77921 0.0 0.0 2433828 1972 s000 R+ 11:17AM 0:00.00 grep puma
myname 67661 0.0 2.3 2680504 191204 s002 S+ 11:00AM 0:18.38 puma 3.11.2 (tcp://localhost:3000) [my_proj]
then:
kill -9 67661
If double-clicking the .jar file in Windows Explorer works, then you should be able to use this:
start myapp.jar
in your batch file.
The Windows start
command does exactly the same thing behind the scenes as double-clicking a file.
Yes, it will always be the same. From the documentation
Appends the specified element to the end of this list. Parameters: e element to be appended to this list Returns: true (as specified by Collection.add(java.lang.Object))
ArrayList add()
implementation
public boolean More ...add(E e) {
ensureCapacity(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
Owing to changes in React V16 where componentWillReceiveProps() has been deprecated, this is the methodology that I use for updating a component. Notice that the below example is in Typescript and uses the static getDerivedStateFromProps method to get the initial state and updated state whenever the Props are updated.
class SomeClass extends React.Component<Props, State> {
static getDerivedStateFromProps(nextProps: Readonly<Props>): Partial<State> | null {
return {
time: nextProps.time
};
}
timerInterval: any;
componentDidMount() {
this.timerInterval = setInterval(this.tick.bind(this), 1000);
}
tick() {
this.setState({ time: this.props.time });
}
componentWillUnmount() {
clearInterval(this.timerInterval);
}
render() {
return <div>{this.state.time}</div>;
}
}
Yes basically this is what virtualenv do , and this is what the activate
command is for, from the doc here:
activate script
In a newly created virtualenv there will be a bin/activate shell script, or a Scripts/activate.bat batch file on Windows.
This will change your $PATH to point to the virtualenv bin/ directory. Unlike workingenv, this is all it does; it's a convenience. But if you use the complete path like /path/to/env/bin/python script.py you do not need to activate the environment first. You have to use source because it changes the environment in-place. After activating an environment you can use the function deactivate to undo the changes.
The activate script will also modify your shell prompt to indicate which environment is currently active.
so you should just use activate
command which will do all that for you:
> \path\to\env\bin\activate.bat
The way I worked about the same problem
IntervalTrees
or LineSweepAlgo
GrahamScanAlgo
to find a closed path with adjacent verticesDinicAlgo
to Dissolve themnote: my scenario was different given the polygons had a common vertice. But Hope this can help
If you use phpMyAdmin, it can tell you this information.
Just go to "Databases" (menu on top) and click "Enable Statistics".
You will see something like this:
This will probably lose some accuracy as the sizes go up, but it should be accurate enough for your purposes.
You can check if string contains numbers only:
Regex.IsMatch(myStringVariable, @"^-?\d+$")
But number can be bigger than Int32.MaxValue
or less than Int32.MinValue
- you should keep that in mind.
Another option - create extension method and move ugly code there:
public static bool IsInteger(this string s)
{
if (String.IsNullOrEmpty(s))
return false;
int i;
return Int32.TryParse(s, out i);
}
That will make your code more clean:
if (myStringVariable.IsInteger())
// ...
I find this Angular How-to: Editable Config Files from Microsoft Dev blogs being the best solution. You can configure dev build settings or prod build settings.
//import com.google.gson.JsonObject;
JsonObject complaint = new JsonObject();
complaint.addProperty("key", "value");
To use the window
object is not a good idea. As I see in comments,
'use strict';
function showMessage() {
window.say_hello = 'hello!';
}
console.log(say_hello);
This will throw an error to use the say_hello
variable we need to first call the showMessage function
.
This usually happens when the repo is cloned between Windows and Linux/Unix machines.
Just tell git to ignore filemode change. Here are several ways to do so:
Config ONLY for current repo:
git config core.filemode false
Config globally:
git config --global core.filemode false
Add in ~/.gitconfig:
[core]
filemode = false
Just select one of them.
I'm surprised no one mentioned the implicit style above. My preference is to use parens to wrap the string while lining the string lines up visually. Personally I think this looks cleaner and more compact than starting the beginning of the string on a tabbed new line.
Note that these parens are not part of a method call — they're only implicit string literal concatenation.
Python 2:
def fun():
print ('{0} Here is a really '
'long sentence with {1}').format(3, 5)
Python 3 (with parens for print function):
def fun():
print(('{0} Here is a really '
'long sentence with {1}').format(3, 5))
Personally I think it's cleanest to separate concatenating the long string literal from printing it:
def fun():
s = ('{0} Here is a really '
'long sentence with {1}').format(3, 5)
print(s)
The key is to select the target of your emulator to, for example: Google APIs (ver 18). If you select, for example, just Jellybean 18 (without API) you will not be able to test apps that require Google services such as map. Keep in mind that you must first download the Google API of your favorite version with the Android SDK Manager.
This is a good practice and it is far better than juggling with most workarounds.
Use the ASCII table to pick a range of letters, where the: $range_start , $range_end is a value from the decimal column in the ASCII table.
I find that this method is nicer compared to the method described where the range of characters is specifically defined within another string.
// range is numbers (48) through capital and lower case letters (122)
$range_start = 48;
$range_end = 122;
$random_string = "";
$random_string_length = 10;
for ($i = 0; $i < $random_string_length; $i++) {
$ascii_no = round( mt_rand( $range_start , $range_end ) ); // generates a number within the range
// finds the character represented by $ascii_no and adds it to the random string
// study **chr** function for a better understanding
$random_string .= chr( $ascii_no );
}
echo $random_string;
See More:
All of these three solutions give the same results if the input is a string:
1.
def reverse(text):
result = ""
for i in range(len(text),0,-1):
result += text[i-1]
return (result)
2.
text[::-1]
3.
"".join(reversed(text))
<ul>
<li><input class="checkboxes" name="BoxSelect[]" type="checkbox" value="Box 1" required><label>Box 1</label></li>
<li><input class="checkboxes" name="BoxSelect[]" type="checkbox" value="Box 2" required><label>Box 2</label></li>
<li><input class="checkboxes" name="BoxSelect[]" type="checkbox" value="Box 3" required><label>Box 3</label></li>
<li><input class="checkboxes" name="BoxSelect[]" type="checkbox" value="Box 4" required><label>Box 4</label></li>
</ul>
<script type="text/javascript">
$(document).ready(function(){
var checkboxes = $('.checkboxes');
checkboxes.change(function(){
if($('.checkboxes:checked').length>0) {
checkboxes.removeAttr('required');
} else {
checkboxes.attr('required', 'required');
}
});
});
</script>
Window -> New Window
This opens a new window and you can then open another project in it. You can use this as a workaround hopefully.
It actually allows you to work in same workspace.
I have fixed it by deleting the .metadata/.lock
file.
If you like doing things the hard way:
my (undef,undef,undef,$mday,$mon,$year) = localtime;
$year = $year+1900;
$mon += 1;
if (length($mon) == 1) {$mon = "0$mon";}
if (length($mday) == 1) {$mday = "0$mday";}
my $today = "$mon/$mday/$year";
I came across this for css
span, p{overflow:hidden; white-space: nowrap;}
DataType
has a second constructor that takes a string. However, internally, this is actually the same as using the UIHint
attribute.
Adding a new core DataType is not possible since the DataType
enumeration is part of the .NET framework. The closest thing you can do is to create a new class that inherits from the DataTypeAttribute
. Then you can add a new constructor with your own DataType
enumeration.
public NewDataTypeAttribute(DataType dataType) : base(dataType)
{ }
public NewDataTypeAttribute(NewDataType newDataType) : base (newDataType.ToString();
You can also go through this link. But I will recommend you using Jquery for the same.
I got this error when trying to modify directly after running Query. Turns out, after making a view from that exact same query, I was able to modify the values.
try:
RewriteRule ^/apple(.*)?$ /folder1$1 [NC]
Where the folder you want to appear in the url is in the first part of the statement - this is what it will match against and the second part 'rewrites' it to your existing folder. the [NC] flag means that it will ignore case differences eg Apple/ will still forward.
See here for a tutorial: http://www.sitepoint.com/article/guide-url-rewriting/
There is also a nice test utility for windows you can download from here: http://www.helicontech.com/download/rxtest.zip Just to note for the tester you need to leave out the domain name - so the test would be against /folder1/login.php
to redirect from /folder1 to /apple try this:
RewriteRule ^/folder1(.*)?$ /apple$1 [R]
to redirect and then rewrite just combine the above in the htaccess file:
RewriteRule ^/folder1(.*)?$ /apple$1 [R]
RewriteRule ^/apple(.*)?$ /folder1$1 [NC]
Adding alternative base R approach, which remains fast under various cases.
rowsummean <- function(df) {
rowsum(df$speed, df$dive) / tabulate(df$dive)
}
Borrowing the benchmarks from @Ari:
10 rows, 2 groups
10 million rows, 10 groups
10 million rows, 1000 groups
Try entering the url inside the function
$location.url('http://www.google.com')
FYI (merged version of Tvanfosson)
it will return actual date => date when you are calling function
export const today = {
iso: {
start: () => new Date(new Date().setHours(0, 0, 0, 0)).toISOString(),
now: () => new Date().toISOString(),
end: () => new Date(new Date().setHours(23, 59, 59, 999)).toISOString()
},
local: {
start: () => new Date(new Date(new Date().setHours(0, 0, 0, 0)).toString().split('GMT')[0] + ' UTC').toISOString(),
now: () => new Date(new Date().toString().split('GMT')[0] + ' UTC').toISOString(),
end: () => new Date(new Date(new Date().setHours(23, 59, 59, 999)).toString().split('GMT')[0] + ' UTC').toISOString()
}
}
// how to use
today.local.now(); //"2018-09-07T01:48:48.000Z" BAKU +04:00
today.iso.now(); // "2018-09-06T21:49:00.304Z" *
* it is applicable for Instant time type on Java8 which convert your local time automatically depending on your region.(if you are planning write global app)
I wanted a solution for this similar to apt-get --print-uris
, but unfortunately apt-cyg doesn't do this. The following is a solution that allowed me to download only the packages I needed, with their dependencies, and copy them to the target for installation. Here is a bash script that parses the output of apt-cyg
into a list of URIs:
#!/usr/bin/bash
package=$1
depends=$( \
apt-cyg depends $package \
| perl -ne 'while ($x = /> ([^>\s]+)/g) { print "$1\n"; }' \
| sort \
| uniq)
depends=$(echo -e "$depends\n$package")
for curpkg in $depends; do
if ! grep -q "^$curpkg " /etc/setup/installed.db; then
apt-cyg show $curpkg \
| perl -ne '
if ($x = /install: ([^\s]+)/) {
print "$1\n";
}
if (/\[prev\]/) {
exit;
}'
fi
done
The above will print out the paths of the packages that need downloading, relative to the cygwin mirror root, omitting any packages that are already installed. To download them, I wrote the output to a file cygwin-packages-list
and then used wget:
mirror=http://cygwin.mirror.constant.com/
uris=$(for line in $(cat cygwin-packages-list); do echo "$mirror$line"; done)
wget -x $uris
The installer can then be used to install from a local cache directory. Note that for this to work I needed to copy setup.ini
from a previous cygwin package cache to the directory with the downloaded files (otherwise the installer doesn't know what's what).
How about something like this :
string url = "http://www.example.com/aaa/bbb.jpg";
Uri uri = new Uri(url);
string path_Query = uri.PathAndQuery;
string extension = Path.GetExtension(path_Query);
path_Query = path_Query.Replace(extension, string.Empty);// This will remove extension
Here is the complete process to create a local repo and push the changes to new remote branch
Creating local repository:-
Initially user may have created the local git repository.
$ git init
:- This will make the local folder as Git repository,
Link the remote branch:-
Now challenge is associate the local git repository with remote master branch.
$ git remote add RepoName RepoURL
usage: git remote add []
Test the Remote
$ git remote show
--->Display the remote name
$ git remote -v
--->Display the remote branches
Now Push to remote
$git add .
----> Add all the files and folder as git staged'
$git commit -m "Your Commit Message"
- - - >Commit the message
$git push
- - - - >Push the changes to the upstream
List<String> list = new List<String> { "6", "1", "2", "4", "6", "5", "1" };
var q = from s in list
group s by s into g
where g.Count() > 1
select g.First();
foreach (var item in q)
{
Console.WriteLine(item);
}
In swift 2.2 - XCode 7.3, we use #selector
for NSNotificationCenter
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(rotate), name: UIDeviceOrientationDidChangeNotification, object: nil)
@echo off
echo Type your text here.
:top
set /p boompanes=
pause
echo %boompanes%> practice.txt
hope this helps. you should change the string names(IDK what its called) and the file name
If you have a large data.frame
and are low on memory use [
. . . . or rm
and within
to remove columns of a data.frame
, as subset
is currently (R 3.6.2) using more memory - beside the hint of the manual to use subset
interactively.
getData <- function() {
n <- 1e7
set.seed(7)
data.frame(a = runif(n), b = runif(n), c = runif(n), d = runif(n))
}
DF <- getData()
tt <- sum(.Internal(gc(FALSE, TRUE, TRUE))[13:14])
DF <- DF[setdiff(names(DF), c("a", "c"))] ##
#DF <- DF[!(names(DF) %in% c("a", "c"))] #Alternative
#DF <- DF[-match(c("a","c"),names(DF))] #Alternative
sum(.Internal(gc(FALSE, FALSE, TRUE))[13:14]) - tt
#0.1 MB are used
DF <- getData()
tt <- sum(.Internal(gc(FALSE, TRUE, TRUE))[13:14])
DF <- subset(DF, select = -c(a, c)) ##
sum(.Internal(gc(FALSE, FALSE, TRUE))[13:14]) - tt
#357 MB are used
DF <- getData()
tt <- sum(.Internal(gc(FALSE, TRUE, TRUE))[13:14])
DF <- within(DF, rm(a, c)) ##
sum(.Internal(gc(FALSE, FALSE, TRUE))[13:14]) - tt
#0.1 MB are used
DF <- getData()
tt <- sum(.Internal(gc(FALSE, TRUE, TRUE))[13:14])
DF[c("a", "c")] <- NULL ##
sum(.Internal(gc(FALSE, FALSE, TRUE))[13:14]) - tt
#0.1 MB are used
I set up Visual Studio Code as a default to open .txt file. And next I did use simple command: git config --global core.editor "'C:\Users\UserName\AppData\Local\Code\app-0.7.10\Code.exe\'"
. And everything works pretty well.
using(var client = new System.Net.WebClient()) {
client.UploadData(address,"PUT",data);
}
When you execute a program the child program inherits its environment variables from the parent. For instance if $HOME
is set to /root
in the parent then the child's $HOME
variable is also set to /root
.
This only applies to environment variable that are marked for export. If you set a variable at the command-line like
$ FOO="bar"
That variable will not be visible in child processes. Not unless you export it:
$ export FOO
You can combine these two statements into a single one in bash (but not in old-school sh):
$ export FOO="bar"
Here's a quick example showing the difference between exported and non-exported variables. To understand what's happening know that sh -c
creates a child shell process which inherits the parent shell's environment.
$ FOO=bar
$ sh -c 'echo $FOO'
$ export FOO
$ sh -c 'echo $FOO'
bar
Note: To get help on shell built-in commands use help export
. Shell built-ins are commands that are part of your shell rather than independent executables like /bin/ls
.
use clear:left; or clear:both in your css.
#map { float:left; width:700px; height:500px; }
#list { float:left; width:200px; background:#eee; list-style:none; padding:0; }
#similar { float:left; width:200px; background:#000; clear:both; }
<div id="map"></div>
<ul id="list"></ul>
<div id ="similar">
this text should be below, not next to ul.
</div>
Look at the HttpServletResponse#sendRedirect(String location)
method.
Use it as:
response.sendRedirect(request.getContextPath() + "/welcome.jsp")
Alternatively, look at HttpServletResponse#setHeader(String name, String value)
method.
The redirection is set by adding the location header:
response.setHeader("Location", request.getContextPath() + "/welcome.jsp");
Write-Host -NoNewline "Enabling feature XYZ......."
If both columns can contain NULL
, but you still want to merge them to a single string, the easiest solution is to use CONCAT_WS():
SELECT FirstName AS First_Name
, LastName AS Last_Name
, CONCAT_WS('', ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone
FROM TABLE1
This way you won't have to check for NULL
-ness of each column separately.
Alternatively, if both columns are actually defined as NOT NULL
, CONCAT() will be quite enough:
SELECT FirstName AS First_Name
, LastName AS Last_Name
, CONCAT(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone
FROM TABLE1
As for COALESCE
, it's a bit different beast: given the list of arguments, it returns the first that's not NULL
.
Now you can convert it by using PyInstaller. It works with even Python 3.
Steps:
pip install pyinstaller
pyinstaller <filename>
Follow these steps:
This command can explicitly set the base URL for your rewrites. If you wish to start in the root of your domain, you would include the following line before your RewriteRule:
RewriteBase /
(I'm assuming you mean browser-side JavaScript)
Ask him why, despite his infinite knowledge of JavaScript, it is still a good idea to use existing frameworks such as jQuery, Mootools, Prototype, etc.
Answer: Good coders code, great coders reuse. Thousands of man hours have been poured into these libraries to abstract DOM capabilities away from browser specific implementations. There's no reason to go through all of the different browser DOM headaches yourself just to reinvent the fixes.
Try this sample SQL scripts for easy understanding,
CREATE TABLE TABLE1 (REFNO VARCHAR(10))
CREATE TABLE TABLE2 (REFNO VARCHAR(10))
--TRUNCATE TABLE TABLE1
--TRUNCATE TABLE TABLE2
INSERT INTO TABLE1 SELECT 'TEST_NAME'
INSERT INTO TABLE1 SELECT 'KUMAR'
INSERT INTO TABLE1 SELECT 'SIVA'
INSERT INTO TABLE1 SELECT 'SUSHANT'
INSERT INTO TABLE2 SELECT 'KUMAR'
INSERT INTO TABLE2 SELECT 'SIVA'
INSERT INTO TABLE2 SELECT 'SUSHANT'
SELECT * FROM TABLE1
SELECT * FROM TABLE2
DELETE T1 FROM TABLE1 T1 JOIN TABLE2 T2 ON T1.REFNO = T2.REFNO
Your case is:
DELETE pgc
FROM guide_category pgc
LEFT JOIN guide g
ON g.id_guide = gc.id_guide
WHERE g.id_guide IS NULL
Just need to add: new SimpleDateFormat("bla bla bla", Locale.US)
public static void main(String[] args) throws ParseException {
java.util.Date fecha = new java.util.Date("Mon Dec 15 00:00:00 CST 2014");
DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);
Date date;
date = (Date)formatter.parse(fecha.toString());
System.out.println(date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
String formatedDate = cal.get(Calendar.DATE) + "/" +
(cal.get(Calendar.MONTH) + 1) +
"/" + cal.get(Calendar.YEAR);
System.out.println("formatedDate : " + formatedDate);
}
Getting a bit like code golf here, but since nearly all the answers so far are bash (barring one lonely cmd one), here's a windows cross-platform command that uses powershell (because awesome):
ls *.avi|%{ ffmpeg -i $_ <ffmpeg options here> $_.name.replace($_.extension, ".mp4")}
You can change *.avi to whatever matches your source footage.
int32
and time.Duration
are different types. You need to convert the int32
to a time.Duration
, such as time.Sleep(time.Duration(rand.Int31n(1000)) * time.Millisecond)
.
I solved mine by doing:
For some reasons it worked for me . Good luck !!
In short you have to do like this
repositories {
maven { url "http://maven.springframework.org/release" }
maven { url "https://maven.fabric.io/public" }
}
Detail:
You need to specify each maven URL in its own curly braces. Here is what I got working with skeleton dependencies for the web services project I’m going to build up:
apply plugin: 'java'
sourceCompatibility = 1.7
version = '1.0'
repositories {
maven { url "http://maven.springframework.org/release" }
maven { url "http://maven.restlet.org" }
mavenCentral()
}
dependencies {
compile group:'org.restlet.jee', name:'org.restlet', version:'2.1.1'
compile group:'org.restlet.jee', name:'org.restlet.ext.servlet',version.1.1'
compile group:'org.springframework', name:'spring-web', version:'3.2.1.RELEASE'
compile group:'org.slf4j', name:'slf4j-api', version:'1.7.2'
compile group:'ch.qos.logback', name:'logback-core', version:'1.0.9'
testCompile group:'junit', name:'junit', version:'4.11'
}
?you should do these steps :
??simply here is the summery of those 5 steps:
.mother_Element {
position : relative;
height : 20%;
width : 5%;
text-align : center
}
.child_Element {
height : 1.2 em;
width : 5%;
margin : auto;
position : absolute;
top:0;
bottom:0;
left:0;
right:0;
}
If you don't want to disable this exception, all you need to do is to let your application pump some messages at least once every 60 seconds. It will prevent this exception to happen. Try calling System.Threading.Thread.CurrentThread.Join(10) once in a while. There are other calls you can do that let the messages pump.
use below.
from tkinter import *
root=Tk()
.....
root.mainloop()
If you use native sql, you can refer to my code, otherwise just ignore my answer.
SELECT * FROM table WHERE tags LIKE "%banana%";
from sqlalchemy import text
bar_tags = "banana"
# '%' attention to spaces
query_sql = """SELECT * FROM table WHERE tags LIKE '%' :bar_tags '%'"""
# db is sqlalchemy session object
tags_res_list = db.execute(text(query_sql), {"bar_tags": bar_tags}).fetchall()
You May use first split and rejoin it using white space. it will work sure.
String[] Larray = L.split("[\\n]+");
L = "";
for(int i = 0; i<Larray.lengh; i++){
L = L+" "+Larray[i];
}
See from How to Replace String in File works in a simple way and is an answer that works with replace
fin = open("data.txt", "rt")
fout = open("out.txt", "wt")
for line in fin:
fout.write(line.replace('pyton', 'python'))
fin.close()
fout.close()
The correct API to use is UIView systemLayoutSizeFittingSize:
, passing either UILayoutFittingCompressedSize
or UILayoutFittingExpandedSize
.
For a normal UIView
using autolayout this should just work as long as your constraints are correct. If you want to use it on a UITableViewCell
(to determine row height for example) then you should call it against your cell contentView
and grab the height.
Further considerations exist if you have one or more UILabel's in your view that are multiline. For these it is imperitive that the preferredMaxLayoutWidth
property be set correctly such that the label provides a correct intrinsicContentSize
, which will be used in systemLayoutSizeFittingSize's
calculation.
EDIT: by request, adding example of height calculation for a table view cell
Using autolayout for table-cell height calculation isn't super efficient but it sure is convenient, especially if you have a cell that has a complex layout.
As I said above, if you're using a multiline UILabel
it's imperative to sync the preferredMaxLayoutWidth
to the label width. I use a custom UILabel
subclass to do this:
@implementation TSLabel
- (void) layoutSubviews
{
[super layoutSubviews];
if ( self.numberOfLines == 0 )
{
if ( self.preferredMaxLayoutWidth != self.frame.size.width )
{
self.preferredMaxLayoutWidth = self.frame.size.width;
[self setNeedsUpdateConstraints];
}
}
}
- (CGSize) intrinsicContentSize
{
CGSize s = [super intrinsicContentSize];
if ( self.numberOfLines == 0 )
{
// found out that sometimes intrinsicContentSize is 1pt too short!
s.height += 1;
}
return s;
}
@end
Here's a contrived UITableViewController subclass demonstrating heightForRowAtIndexPath:
#import "TSTableViewController.h"
#import "TSTableViewCell.h"
@implementation TSTableViewController
- (NSString*) cellText
{
return @"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
}
#pragma mark - Table view data source
- (NSInteger) numberOfSectionsInTableView: (UITableView *) tableView
{
return 1;
}
- (NSInteger) tableView: (UITableView *)tableView numberOfRowsInSection: (NSInteger) section
{
return 1;
}
- (CGFloat) tableView: (UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath
{
static TSTableViewCell *sizingCell;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sizingCell = (TSTableViewCell*)[tableView dequeueReusableCellWithIdentifier: @"TSTableViewCell"];
});
// configure the cell
sizingCell.text = self.cellText;
// force layout
[sizingCell setNeedsLayout];
[sizingCell layoutIfNeeded];
// get the fitting size
CGSize s = [sizingCell.contentView systemLayoutSizeFittingSize: UILayoutFittingCompressedSize];
NSLog( @"fittingSize: %@", NSStringFromCGSize( s ));
return s.height;
}
- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath
{
TSTableViewCell *cell = (TSTableViewCell*)[tableView dequeueReusableCellWithIdentifier: @"TSTableViewCell" ];
cell.text = self.cellText;
return cell;
}
@end
A simple custom cell:
#import "TSTableViewCell.h"
#import "TSLabel.h"
@implementation TSTableViewCell
{
IBOutlet TSLabel* _label;
}
- (void) setText: (NSString *) text
{
_label.text = text;
}
@end
And, here's a picture of the constraints defined in the Storyboard. Note that there are no height/width constraints on the label - those are inferred from the label's intrinsicContentSize
:
It looks like this is the case when Chrome is not compliant with WebSocket standard. When the server initiates close and sends close frame to a client, Chrome considers this to be an error and reports it to JS side with code 1006 and no reason message. In my tests, Chrome never responds to server-initiated close frames (close code 1000) suggesting that code 1006 probably means that Chrome is reporting its own internal error.
P.S. Firefox v57.00 handles this case properly and successfully delivers server's reason message to JS side.
Get the port number using netstat
:
netstat -b
And then use the Wireshark filter:
tcp.port == portnumber
Yes, you can enforce the constraint only when the value is not NULL. This can be easily tested with the following example:
CREATE DATABASE t;
USE t;
CREATE TABLE parent (id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (id INT NULL,
parent_id INT NULL,
FOREIGN KEY (parent_id) REFERENCES parent(id)
) ENGINE=INNODB;
INSERT INTO child (id, parent_id) VALUES (1, NULL);
-- Query OK, 1 row affected (0.01 sec)
INSERT INTO child (id, parent_id) VALUES (2, 1);
-- ERROR 1452 (23000): Cannot add or update a child row: a foreign key
-- constraint fails (`t/child`, CONSTRAINT `child_ibfk_1` FOREIGN KEY
-- (`parent_id`) REFERENCES `parent` (`id`))
The first insert will pass because we insert a NULL in the parent_id
. The second insert fails because of the foreign key constraint, since we tried to insert a value that does not exist in the parent
table.
You can iterate through the key-value pair and write it into file
pair = {'name': name,'location': location}
with open('F:\\twitter.json', 'a') as f:
f.writelines('{}:{}'.format(k,v) for k, v in pair.items())
f.write('\n')
In Simple Terms, a Shallow Copy is similar to Call By Reference and a Deep Copy is similar to Call By Value
In Call By Reference, Both formal and actual parameters of a function refers to same memory location and the value.
In Call By Value, Both formal and actual parameters of a functions refers to different memory location but having the same value.
The correct answer is, that, because the '%'
-sign is part of your search expression, it should be part of your VALUE, so whereever you SET @LastName
(be it from a programming language or from TSQL) you should set it to '%' + [userinput] + '%'
or, in your example:
DECLARE @LastName varchar(max)
SET @LastName = 'ning'
SELECT Employee WHERE LastName LIKE '%' + @LastName + '%'
if you are using jQuery, try this
$('<div>').is('*') // true
$({tagName: 'a'}).is('*') // false
$({}).is('*') // false
$([]).is('*') // false
$(0).is('*') // false
$(NaN).is('*') // false
I want to comment/partially answer/share my thoughts. I am using the overflow-y:scroll technique for a big upcoming project of mine. Using it has two MAJOR advantages.
a) You can use a drawer with action buttons from the bottom of the screen; if the document scrolls and the bottom bar disappears, tapping on a button located at the bottom of the screen will first make the bottom bar appear, and then be clickable. Also, the way this thing works, causes trouble with modals that have buttons at the far bottom.
b) When using an overflown element, the only things that are repainted in case of major css changes are the ones in the viewable screen. This gave me a huge performance boost when using javascript to alter css of multiple elements on the fly. For example, if you have a list of 20 elements you need repainted and only two of them are on-screen in the overflown element, only those are repainted while the rest are repainted when scrolling. Without it all 20 elements are repainted.
..of course it depends on the project and if you need any of the functionality I mentioned. Google uses overflown elements for gmail to use the functionality I described on a). Imo, it's worth the while, even considering the small height in older iphones (372px as you said).
First of all you should do such things only if it is really necessary - e.g. to use some old-style API with char*
arguments which are not modified. If an API function modifies the string which was const originally, then this is unspecified behaviour, very likely crash.
Use cast:
(char*)const_char_ptr
For me it was caused because I renamed the entity class.When I rolled it back it was Ok.
this may help
string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, @"../../")) + "Orders.xml";
if (File.Exists(parentOfStartupPath))
{
// file found
}
You can set up a meta-table to track the number of entries, this may be faster than iteration if this information is a needed frequently.
As many said, this is due to stash
being a shell script on Windows, but since Git 2.18.0 the Windows installer has an option for an experimental feature of a much faster (~90%) built-in version of stash -
https://github.com/git-for-windows/build-extra/pull/203.
I have added a Maven/Java project with 1 Domain class with the following features:
Where are the Jacoco results? After testing and running 'mvn clean', you can find the results in 'target/site/jacoco/index.html'. Open this file in the browser.
Enjoy!
I tried to keep the project as simple as possible. The project puts many suggestions from these posts together in an example project. Thank you, contributors!
The general theory can be found in wikipedia's article on Kademlia. The specific protocol specification used in bittorrent is here: http://wiki.theory.org/BitTorrentDraftDHTProtocol
scanf
(and cousins) have one slightly strange characteristic: white space in (most placed in) the format string matches an arbitrary amount of white space in the input. As it happens, at least in the default "C" locale, a new-line is classified as white space.
This means the trailing '\n'
is trying to match not only a new-line, but any succeeding white-space as well. It won't be considered matched until you signal the end of the input, or else enter some non-white space character.
One way to deal with that is something like this:
scanf("%2000s %2000[^\n]%c", a, b, c);
if (c=='\n')
// we read the whole line
else
// the rest of the line was more than 2000 characters long. `c` contains a
// character from the input, and there's potentially more after that as well.
Depending on the situation, you might also want to check the return value from scanf
, which tells you the number of conversions that were successful. In this case, you'd be looking for 3
to indicate that all the conversions were successful.
if you want to use md5 encryptioon you can do it in your php script
$pass = $_GET['pass'];
$newPass = md5($pass)
and then insert it into the database that way, however MD5 is a one way encryption method and is near on impossible to decrypt without difficulty
#include <stdio.h>
#include <malloc.h>
tydef struct node
{
int info;
struct node *link;
} *start;
void main()
{
rev();
}
void rev()
{
struct node *p = start, *q = NULL, *r;
while (p != NULL)
{
r = q;
q = p;
p = p->link;
q->link = r;
}
start = q;
}
From another perspective, files that both unicode and ascii encodings fail to read because they have a byte 0xc0
in them, seem to get read by iso-8859-1 properly. The caveat is that the file shouldn't have unicode characters in it of course.
This wll work.
public class CryptoUtils {
private final String TRANSFORMATION = "AES";
private final String encodekey = "1234543444555666";
public String encrypt(String inputFile)
throws CryptoException {
return doEncrypt(encodekey, inputFile);
}
public String decrypt(String input)
throws CryptoException {
// return doCrypto(Cipher.DECRYPT_MODE, key, inputFile);
return doDecrypt(encodekey,input);
}
private String doEncrypt(String encodekey, String inputStr) throws CryptoException {
try {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
byte[] key = encodekey.getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] inputBytes = inputStr.getBytes();
byte[] outputBytes = cipher.doFinal(inputBytes);
return Base64Utils.encodeToString(outputBytes);
} catch (NoSuchPaddingException | NoSuchAlgorithmException
| InvalidKeyException | BadPaddingException
| IllegalBlockSizeException | IOException ex) {
throw new CryptoException("Error encrypting/decrypting file", ex);
}
}
public String doDecrypt(String encodekey,String encrptedStr) {
try {
Cipher dcipher = Cipher.getInstance(TRANSFORMATION);
dcipher = Cipher.getInstance("AES");
byte[] key = encodekey.getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
dcipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
// decode with base64 to get bytes
byte[] dec = Base64Utils.decode(encrptedStr.getBytes());
byte[] utf8 = dcipher.doFinal(dec);
// create new string based on the specified charset
return new String(utf8, "UTF8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
DATETIME
supports 1753/1/1 to "eternity" (9999/12/31), whileDATETIME2
support 0001/1/1 through eternity.
Answer:
I suppose you try to save DateTime
with '0001/1/1' value. Just set breakpoint and debug it, if so then replace DateTime
with null
or set normal date.
REST is just a software architecture style for exposing resources.
A typical REST call to return information about customer 34456 could look like:
http://example.com/customer/34456
Have a look at the IBM tutorial for REST web services
Good to also check the other combinators in the family and to get back to what is this specific one.
ul li
ul > li
ul + ul
ul ~ ul
Example checklist:
ul li
- Looking inside - Selects all the li
elements placed (anywhere) inside the ul
; Descendant selectorul > li
- Looking inside - Selects only the direct li
elements of ul
; i.e. it will only select direct children li
of ul
; Child Selector or Child combinator selectorul + ul
- Looking outside - Selects the ul
immediately following the ul
; It is not looking inside, but looking outside for the immediately following element; Adjacent Sibling Selectorul ~ ul
- Looking outside - Selects all the ul
which follows the ul
doesn't matter where it is, but both ul
should be having the same parent; General Sibling SelectorThe one we are looking at here is General Sibling Selector
Assuming your <input type="file" > has an id of upload this should hopefully do the trick:
var fullPath = document.getElementById('upload').value;
if (fullPath) {
var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
var filename = fullPath.substring(startIndex);
if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
filename = filename.substring(1);
}
alert(filename);
}
In Selenium IDE you can do:
Command | clickAndWait Target | //input[@value='Next' and @title='next']
It should work fine.
You can simply add another join like this:
SELECT dashboard_data.headline, dashboard_data.message, dashboard_messages.image_id, images.filename
FROM dashboard_data
INNER JOIN dashboard_messages
ON dashboard_message_id = dashboard_messages.id
INNER JOIN images
ON dashboard_messages.image_id = images.image_id
However be aware that, because it is an INNER JOIN
, if you have a message without an image, the entire row will be skipped. If this is a possibility, you may want to do a LEFT OUTER JOIN
which will return all your dashboard messages and an image_filename only if one exists (otherwise you'll get a null)
SELECT dashboard_data.headline, dashboard_data.message, dashboard_messages.image_id, images.filename
FROM dashboard_data
INNER JOIN dashboard_messages
ON dashboard_message_id = dashboard_messages.id
LEFT OUTER JOIN images
ON dashboard_messages.image_id = images.image_id
Are you sure you should be using POST not PUT?
POST is usually used with application/x-www-urlencoded
formats. If you are using a REST API, you should maybe be using PUT? If you are uploading a file you probably need to use multipart/form-data
. Not always, but usually, that is the right thing to do..
Also you don't seem to be using the credentials to log in - you need to use the Credentials property of the HttpWebRequest object to send the username and password.
You have two options, and I'll leave selection up to you.
Shared Preferences
This is a framework unique to Android that allows you to store primitive values (such as int
, boolean,
and String
, although strictly speaking String
isn't a primitive) in a key-value framework. This means that you give a value a name, say, "homeScore" and store the value to this key.
SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("homeScore", YOUR_HOME_SCORE);
// Apply the edits!
editor.apply();
// Get from the SharedPreferences
SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
int homeScore = settings.getInt("homeScore", 0);
Internal Storage
This, in my opinion, is what you might be looking for. You can store anything you want to a file, so this gives you more flexibility. However, the process can be trickier because everything will be stored as bytes, and that means you have to be careful to keep your read and write processes working together.
int homeScore;
byte[] homeScoreBytes;
homeScoreBytes[0] = (byte) homeScore;
homeScoreBytes[1] = (byte) (homeScore >> 8); //you can probably skip these two
homeScoreBytes[2] = (byte) (homeScore >> 16); //lines, because I've never seen a
//basketball score above 128, it's
//such a rare occurance.
FileOutputStream outputStream = getApplicationContext().openFileOutput(FILENAME, Context.MODE_PRIVATE);
outputStream.write(homeScoreBytes);
outputStream.close();
Now, you can also look into External Storage, but I don't recommend that in this particular case, because the external storage might not be there later. (Note that if you pick this, it requires a permission)
Surprised no one mentioned this:
public Task<int> BlahAsync()
{
// ...
}
int result = BlahAsync().GetAwaiter().GetResult();
Not as pretty as some of the other methods here, but it has the following benefits:
Wait
)AggregateException
(like Result
)Task
and Task<T>
(try it out yourself!)Also, since GetAwaiter
is duck-typed, this should work for any object that is returned from an async method (like ConfiguredAwaitable
or YieldAwaitable
), not just Tasks.
edit: Please note that it's possible for this approach (or using .Result
) to deadlock, unless you make sure to add .ConfigureAwait(false)
every time you await, for all async methods that can possibly be reached from BlahAsync()
(not just ones it calls directly). Explanation.
// In BlahAsync() body
await FooAsync(); // BAD!
await FooAsync().ConfigureAwait(false); // Good... but make sure FooAsync() and
// all its descendants use ConfigureAwait(false)
// too. Then you can be sure that
// BlahAsync().GetAwaiter().GetResult()
// won't deadlock.
If you're too lazy to add .ConfigureAwait(false)
everywhere, and you don't care about performance you can alternatively do
Task.Run(() => BlahAsync()).GetAwaiter().GetResult()
After you get the error, run
EXEC sp_who2
Look for the database in the list. It's possible that a connection was not terminated. If you find any connections to the database, run
KILL <SPID>
where <SPID>
is the SPID for the sessions that are connected to the database.
Try your script after all connections to the database are removed.
Unfortunately, I don't have a reason why you're seeing the problem, but here is a link that shows that the problem has occurred elsewhere.
Concerning more advanced usage, I find these two pages a must read:
I believe your 1:m relationships should already implicitly create DISTINCT JOINs.
But, if you're goal is just C's in each A, it might be easier to just use DISTINCT on the outer-most query.
SELECT DISTINCT a.valueA, c.valueC
FROM C
INNER JOIN B ON B.lookupC = C.id
INNER JOIN A ON A.lookupB = B.id
ORDER BY a.valueA, c.valueC
With python >= 3.5
you can use mock_object.assert_not_called()
.
As an alternative to the chosen answer, and with the same safe semantics of Marcel's, here is a compact way of using a Python dictionary to specify the values. It has the benefit of being easy to modify as you add or remove columns to insert:
meta_cols=('SongName','SongArtist','SongAlbum','SongGenre')
insert='insert into Songs ({0}) values ({1})'.
.format(','.join(meta_cols), ','.join( ['%s']*len(meta_cols) ))
args = [ meta[i] for i in meta_cols ]
cursor=db.cursor()
cursor.execute(insert,args)
db.commit()
Where meta is the dictionary holding the values to insert. Update can be done in the same way:
meta_cols=('SongName','SongArtist','SongAlbum','SongGenre')
update='update Songs set {0} where id=%s'.
.format(','.join([ '{0}=%s'.format(c) for c in meta_cols ]))
args = [ meta[i] for i in meta_cols ]
args.append( songid )
cursor=db.cursor()
cursor.execute(update,args)
db.commit()
Check chart.Boxplot from package PerformanceAnalytics
. It lets you define the symbol to use for the mean of the distribution.
By default, the chart.Boxplot(data)
command adds the mean as a red circle and the median as a black line.
Here is the output with sample data; MWE:
#install.packages(PerformanceAnalytics)
library(PerformanceAnalytics)
chart.Boxplot(cars$speed)
As Ennui mentioned, IE 10 supports the -ms
prefixed version of Flexbox (IE 11 supports it unprefixed). The errors I can see in your code are:
display: -ms-flexbox
instead of display: -ms-flex
flex
values, like flex: 0 1 auto
to avoid ambiguitySo the final updated code is...
.flexbox form {
display: -webkit-flex;
display: -moz-flex;
display: -ms-flexbox;
display: -o-flex;
display: flex;
/* Direction defaults to 'row', so not really necessary to specify */
-webkit-flex-direction: row;
-moz-flex-direction: row;
-ms-flex-direction: row;
-o-flex-direction: row;
flex-direction: row;
}
.flexbox form input[type=submit] {
width: 31px;
}
.flexbox form input[type=text] {
width: auto;
/* Flex should have 3 values which is shorthand for
<flex-grow> <flex-shrink> <flex-basis> */
-webkit-flex: 1 1 auto;
-moz-flex: 1 1 auto;
-ms-flex: 1 1 auto;
-o-flex: 1 1 auto;
flex: 1 1 auto;
/* I don't think you need 'display: flex' on child elements * /
display: -webkit-flex;
display: -moz-flex;
display: -ms-flex;
display: -o-flex;
display: flex;
/**/
}
In Kotlin you can try this,
like i am using cardview for clicking,
(Example : on double click i perform like and dislike.)
cardviewPostCard.setOnClickListener(object : DoubleClickListener() {
override fun onDoubleClick(v: View?) {
if (holder.toggleButtonLike.isChecked) {
holder.toggleButtonLike.setChecked(false) //
} else {
holder.toggleButtonLike.setChecked(true)
}
}
})
and here is your DoubleClickListener class,
abstract class DoubleClickListener : View.OnClickListener {
var lastClickTime: Long = 0
override fun onClick(v: View?) {
val clickTime = System.currentTimeMillis()
if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA) {
onDoubleClick(v)
}
lastClickTime = clickTime
}
abstract fun onDoubleClick(v: View?)
companion object {
private const val DOUBLE_CLICK_TIME_DELTA: Long = 300 //milliseconds
}
}
Reply to MVC4 DataType.Date EditorFor won't display date value in Chrome, fine in IE
In the Model you need to have following type of declaration:
[DataType(DataType.Date)]
public DateTime? DateXYZ { get; set; }
OR
[DataType(DataType.Date)]
public Nullable<System.DateTime> DateXYZ { get; set; }
You don't need to use following attribute:
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
At the Date.cshtml use this template:
@model Nullable<DateTime>
@using System.Globalization;
@{
DateTime dt = DateTime.Now;
if (Model != null)
{
dt = (System.DateTime)Model;
}
if (Request.Browser.Type.ToUpper().Contains("IE") || Request.Browser.Type.Contains("InternetExplorer"))
{
@Html.TextBox("", String.Format("{0:d}", dt.ToShortDateString()), new { @class = "datefield", type = "date" })
}
else
{
//Tested in chrome
DateTimeFormatInfo dtfi = CultureInfo.CreateSpecificCulture("en-US").DateTimeFormat;
dtfi.DateSeparator = "-";
dtfi.ShortDatePattern = @"yyyy/MM/dd";
@Html.TextBox("", String.Format("{0:d}", dt.ToString("d", dtfi)), new { @class = "datefield", type = "date" })
}
}
Have fun! Regards, Blerton
As an aside, apart from the answer by mipadi (which should work by the way), you should know that doing:
git branch -D master
git checkout master
also does exactly what you want without having to redownload everything
(your quote paraphrased). That is because your local repo contains a copy of the remote repo (and that copy is not the same as your local directory, it is not even the same as your checked out branch).
Wiping out a branch is perfectly safe and reconstructing that branch is very fast and involves no network traffic. Remember, git is primarily a local repo by design. Even remote branches have a copy on the local. There's only a bit of metadata that tells git that a specific local copy is actually a remote branch. In git, all files are on your hard disk all the time.
If you don't have any branches other than master, you should:
git checkout -b 'temp'
git branch -D master
git checkout master
git branch -D temp
var arr = _.map(obj)
You can use _.map
function (of both lodash
and underscore
) with object
as well, it will internally handle that case, iterate over each value and key with your iteratee, and finally return an array. Infact, you can use it without any iteratee (just _.map(obj)
) if you just want a array of values. The good part is that, if you need any transformation in between, you can do it in one go.
Example:
var obj = {_x000D_
key1: {id: 1, name: 'A'},_x000D_
key2: {id: 2, name: 'B'},_x000D_
key3: {id: 3, name: 'C'}_x000D_
};_x000D_
_x000D_
var array1 = _.map(obj, v=>v);_x000D_
console.log('Array 1: ', array1);_x000D_
_x000D_
/*Actually you don't need the callback v=>v if you_x000D_
are not transforming anything in between, v=>v is default*/_x000D_
_x000D_
//SO simply you can use_x000D_
var array2 = _.map(obj);_x000D_
console.log('Array 2: ', array2);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
_x000D_
However, if you want to transform your object you can do so, even if you need to preserve the key, you can do that ( _.map(obj, (v, k) => {...}
) with additional argument in map
and then use it how you want.
However there are other Vanilla JS solution to this (as every lodash
solution there should pure JS version of it) like:
Object.keys
and then map
them to valuesObject.values
(in ES-2017)Object.entries
and then map
each key/value pairs (in ES-2017)for...in
loop and use each keys for feting valuesAnd a lot more. But since this question is for lodash
(and assuming someone already using it) then you don't need to think a lot about version, support of methods and error handling if those are not found.
There are other lodash solutions like _.values
(more readable for specific perpose), or getting pairs and then map and so on. but in the case your code need flexibility that you can update it in future as you need to preserve keys
or transforming values a bit, then the best solution is to use a single _.map
as addresed in this answer. That will bt not that difficult as per readability also.
You can use a regular expression to test for a match and capture the first two digits:
import re
for i in range(1000):
match = re.match(r'(1[56])', str(i))
if match:
print(i, 'begins with', match.group(1))
The regular expression (1[56])
matches a 1 followed by either a 5 or a 6 and stores the result in the first capturing group.
Output:
15 begins with 15
16 begins with 16
150 begins with 15
151 begins with 15
152 begins with 15
153 begins with 15
154 begins with 15
155 begins with 15
156 begins with 15
157 begins with 15
158 begins with 15
159 begins with 15
160 begins with 16
161 begins with 16
162 begins with 16
163 begins with 16
164 begins with 16
165 begins with 16
166 begins with 16
167 begins with 16
168 begins with 16
169 begins with 16
Is there any way to make a text box fill the width of its container without expanding beyond it?
Yes: by using the CSS3 property ‘box-sizing: border-box’, you can redefine what ‘width’ means to include the external padding and border.
Unfortunately because it's CSS3, support isn't very mature, and as the spec process isn't finished yet, it has different temporary names in browsers in the meantime. So:
input.wide {
width: 100%;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}
The old-school alternative is simply to put a quantity of ‘padding-right’ on the enclosing <div> or <td> element equal to about how much extra left-and-right padding/border in ‘px’ you think browsers will give the input. (Typically 6px for IE<8.)
I know a lot's of time has passed since this publish, but I've fallen in a similar situation and create a simples class to simplify my life.
public struct StringMaskFormatter {
public var pattern : String = ""
public var replecementChar : Character = "*"
public var allowNumbers : Bool = true
public var allowText : Bool = false
public init(pattern:String, replecementChar:Character="*", allowNumbers:Bool=true, allowText:Bool=true)
{
self.pattern = pattern
self.replecementChar = replecementChar
self.allowNumbers = allowNumbers
self.allowText = allowText
}
private func prepareString(string:String) -> String {
var charSet : NSCharacterSet!
if allowText && allowNumbers {
charSet = NSCharacterSet.alphanumericCharacterSet().invertedSet
}
else if allowText {
charSet = NSCharacterSet.letterCharacterSet().invertedSet
}
else if allowNumbers {
charSet = NSCharacterSet.decimalDigitCharacterSet().invertedSet
}
let result = string.componentsSeparatedByCharactersInSet(charSet)
return result.joinWithSeparator("")
}
public func createFormattedStringFrom(text:String) -> String
{
var resultString = ""
if text.characters.count > 0 && pattern.characters.count > 0
{
var finalText = ""
var stop = false
let tempString = prepareString(text)
var formatIndex = pattern.startIndex
var tempIndex = tempString.startIndex
while !stop
{
let formattingPatternRange = formatIndex ..< formatIndex.advancedBy(1)
if pattern.substringWithRange(formattingPatternRange) != String(replecementChar) {
finalText = finalText.stringByAppendingString(pattern.substringWithRange(formattingPatternRange))
}
else if tempString.characters.count > 0 {
let pureStringRange = tempIndex ..< tempIndex.advancedBy(1)
finalText = finalText.stringByAppendingString(tempString.substringWithRange(pureStringRange))
tempIndex = tempIndex.advancedBy(1)
}
formatIndex = formatIndex.advancedBy(1)
if formatIndex >= pattern.endIndex || tempIndex >= tempString.endIndex {
stop = true
}
resultString = finalText
}
}
return resultString
}
}
The follow link send to the complete source code: https://gist.github.com/dedeexe/d9a43894081317e7c418b96d1d081b25
This solution was base on this article: http://vojtastavik.com/2015/03/29/real-time-formatting-in-uitextfield-swift-basics/
try this:
import time
import os
n = 0
for x in range(10): #enter your value here
print(n)
time.sleep(1) #to wait a second
os.system('cls') #to clear previous number
#use ('clear') if you are using linux or mac!
n = n + 1