As an alternative you can just put this line in your code blocks and check php logs, for really slow functions it's pretty useful:
trigger_error("Task done at ". strftime('%H:%m:%S', time()), E_USER_NOTICE);
For serious debugging use XDebug + Cachegrind, see https://blog.nexcess.net/2011/01/29/diagnosing-slow-php-execution-with-xdebug-and-kcachegrind/
In addition to @Cristian's answer above, I had to do two more steps to get it working correctly. I will sum all of it here:
R.java
class and the press F6
(Refactor->Move...). It will allow you to move the class to another package, and all references to that class will be updated.build.gradle
file : android / defaultconfig / application ID [source].The documentation for css() says that setting the style property to the empty string will remove that property if it does not reside in a stylesheet:
Setting the value of a style property to an empty string — e.g.
$('#mydiv').css('color', '')
— removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's.css()
method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or<style>
element.
Since your styles are inline, you can write:
$(selector).css("-moz-user-select", "");
Another way you can do this is by using the substitute function. Substitute "(", ")" and "," with spaces. e.g.
=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1, "(", " "), ")", " "), ",", " ")
The problem is that "i" is incremented, so by the time the click event is executed the value of i equals len. One possible solution is to capture the value of i inside a function:
var len = menuitems.length;
for (var i = 0; i < len; i++){
(function(i) {
$('<li/>',{
'html':'<img src="'+menuitems[i].icon+'">'+menuitems[i].name,
'click':function(){
menuitems[i].action();
},
'class':o.itemClass
}).appendTo('.'+o.listClass);
})(i);
}
In the above sample, the anonymous function creates a new scope which captures the current value of i, so that when the click event is triggered the local variable is used instead of the i from the for loop.
Can you try the following?
psexec \\server cmd /c "echo . | powershell script.ps1"
>>> d={'a':1,'b':2,'c':3}
>>> for kv in d.items():
... print kv[0],'\t',kv[1]
...
a 1
c 3
b 2
char[] chars = new char[10];
Arrays.fill(chars, '*');
String text = new String(chars);
For those having problems with AOT, you need to do it a little differently with a useFactory:
export function getCulture() {
return 'fr-CA';
}
@NgModule({
providers: [
{ provide: LOCALE_ID, useFactory: getCulture },
//otherProviders...
]
})
Wanted to add that my problem was in an activity where I tried to make a FragmentTransaction
in onCreate BEFORE I called super.onCreate()
. I just moved super.onCreate()
to top of function and was worked fine.
If we want to make reverse engineering (almost) impossible, we can put the application on a highly tamper-resistant chip, which executes all sensitive stuff internally, and communicates with some protocol to make controlling GUI possible on the host. Even tamper-resistant chips are not 100% crack proof; they just set the bar a lot higher than software methods. Of course, this is inconvenient: the application requires some little USB wart which holds the chip to be inserted into the device.
The question doesn't reveal the motivation for wanting to protect this application so jealously.
If the aim is to improve the security of the payment method by concealing whatever security flaws the application may have (known or otherwise), it is completely wrongheaded. The security-sensitive bits should in fact be open-sourced, if that is feasible. You should make it as easy as possible for any security researcher who reviews your application to find those bits and scrutinize their operation, and to contact you. Payment applications should not contain any embedded certificates. That is to say, there should be no server appliaction which trusts a device simply because it has a fixed certificate from the factory. A payment transaction should be made on the user's credentials alone, using a correctly designed end-to-end authentication protocol which precludes trusting the application, or the platform, or the network, etc.
If the aim is to prevent cloning, short of that tamper-proof chip, there isn't anything you can do to protect the program from being reverse-engineered and copied, so that someone incorporates a compatible payment method into their own application, giving rise to "unauthorized clients". There are ways to make it difficult to develop unauthorized clients. One would be to create checksums based on snapshots of the program's complete state: all state variables, for everything. GUI, logic, whatever. A clone program will not have exactly the same internal state. Sure, it is a state machine which has similar externally visible state transitions (as can be observed by inputs and outputs), but hardly the same internal state. A server application can interrogate the program: what is your detailed state? (i.e. give me a checksum over all of your internal state variables). This can be compared against dummy client code which executes on the server in parallel, going through the genuine state transitions. A third party clone will have to replicate all of the relevant state changes of the genuine program in order to give the correct responses, which will hamper its development.
You should form the command with the contents of the textboxes:
sql = "insert into Main (Firt Name, Last Name) values(" + textbox2.Text +
"," + textbox3.Text+ ")";
This, of course, provided that you manage to open the connection correctly.
It would be helpful to know what is happening with your current code. If you are getting some error displayed in that message box, it would be great to know what it's saying.
You should also validate the inputs before actually running the command (i.e. make sure they don't contain malicious code).
I tried maximum to use the comparator with primitive type itself. At-last i concluded that there is no way to cheat the comparator.This is my implementation.
public class ArrSortComptr {
public static void main(String[] args) {
int[] array = { 3, 2, 1, 5, 8, 6 };
int[] sortedArr=SortPrimitiveInt(new intComp(),array);
System.out.println("InPut "+ Arrays.toString(array));
System.out.println("OutPut "+ Arrays.toString(sortedArr));
}
static int[] SortPrimitiveInt(Comparator<Integer> com,int ... arr)
{
Integer[] objInt=intToObject(arr);
Arrays.sort(objInt,com);
return intObjToPrimitive(objInt);
}
static Integer[] intToObject(int ... arr)
{
Integer[] a=new Integer[arr.length];
int cnt=0;
for(int val:arr)
a[cnt++]=new Integer(val);
return a;
}
static int[] intObjToPrimitive(Integer ... arr)
{
int[] a=new int[arr.length];
int cnt=0;
for(Integer val:arr)
if(val!=null)
a[cnt++]=val.intValue();
return a;
}
}
class intComp implements Comparator<Integer>
{
@Override //your comparator implementation.
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
return o1.compareTo(o2);
}
}
@Roman: I can't say that this is a good example but since you asked this is what came to my mind. Suppose in an array you want to sort number's just based on their absolute value.
Integer d1=Math.abs(o1);
Integer d2=Math.abs(o2);
return d1.compareTo(d2);
Another example can be like you want to sort only numbers greater than 100.It actually depends on the situation.I can't think of any more situations.Maybe Alexandru can give more examples since he say's he want's to use a comparator for int array.
Google says to check out getenv():
Returns an unmodifiable string map view of the current system environment.
I'm not sure how system variables differ from environment variables, however, so if you could clarify I could help out more.
click()
to the QMainWindow custom slot you have created).Code example:
MainWindow.h
// ...
include "newwindow.h"
// ...
public slots:
void openNewWindow();
// ...
private:
NewWindow *mMyNewWindow;
// ...
}
MainWindow.cpp
// ...
MainWindow::MainWindow()
{
// ...
connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
// ...
}
// ...
void MainWindow::openNewWindow()
{
mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
mMyNewWindow->show();
// ...
}
This is an example on how display a custom new window. There are a lot of ways to do this.
This is what worked for me on windows:
Edit the pg_hba.conf file locates at C:\Program Files\PostgreSQL\9.3\data.
# IPv4 local connections:
host all all 127.0.0.1/32 trust
Change the method from trust to md5 and restart the postgres service on windows.
After that, you can login using postgres user without password by using pgadmin. You can change password using File->Change password.
If postgres user does not have superuser privileges , then you cannot change the password. In this case , login with another user(pgsql)with superuser access and provide privileges to other users by right clicking on users and selecting properties->Role privileges.
File file = new File(dir, "App.apk");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
startActivity(intent);
I had the same problem and after several attempts, it worked out for me this way. I don't know why, but setting data and type separately screwed up my intent.
in vb.net just do this
mylist.addrange(intsArray)
or
Dim mylist As New List(Of Integer)(intsArray)
If you have XDocument it is easier to use LINQ-to-XML:
var document = XDocument.Load(fileName);
var name = document.Descendants(XName.Get("Name", @"http://demo.com/2011/demo-schema")).First().Value;
If you are sure that XPath is the only solution you need:
using System.Xml.XPath;
var document = XDocument.Load(fileName);
var namespaceManager = new XmlNamespaceManager(new NameTable());
namespaceManager.AddNamespace("empty", "http://demo.com/2011/demo-schema");
var name = document.XPathSelectElement("/empty:Report/empty:ReportInfo/empty:Name", namespaceManager).Value;
I found out that you need to add the pointer eg:
div{
cursor: url('cursorurl.png'), pointer;
}
<a target="_blank" title="Share this page" href="http://www.sharethis.com/share?url=[INSERT URL]&title=[INSERT TITLE]&summary=[INSERT SUMMARY]&img=[INSERT IMAGE URL]&pageInfo=%7B%22hostname%22%3A%22[INSERT DOMAIN NAME]%22%2C%22publisher%22%3A%22[INSERT PUBLISHERID]%22%7D"><img width="86" height="25" alt="Share this page" src="http://w.sharethis.com/images/share-classic.gif"></a>
Instructions
First, insert these lines wherever you want within your newsletter code. Then:
If you are using this on an email newsletter, make sure you add our sharing buttons to the destination page. This will ensure that you get complete sharing analytics for your page. Make sure you replace "INSERT PUBLISHERID" with your own.
If you are loading the XML file from a remote location, I would check to see if the file is actually being downloaded correctly using a sniffer like Fiddler.
I wrote a quick console app to run your code and parse the file and it works fine for me.
The validate_required function seems to expect an HTML form control (e.g, text input field) as first argument, and check whether there is a value there at all. That is not what you want in this case.
Also, when you write ['password'].value
, you create a new array of length one, containing the string
'password'
, and then read the non-existing property "value"
from it, yielding the undefined value.
What you may want to try instead is:
if (password.value != cpassword.value) { cpassword.focus(); return false; }
(You also need to write the error message somehow, but I can't see from your code how that is done.).
mysqladmin
is not a SQL statement. It's a little helper utility program you'll find on your MySQL server... and "flush-hosts" is one of the things it can do. ("status" and "shutdown" are a couple of other things that come to mind).
You type that command from a shell prompt.
Alternately, from your query browser (such as phpMyAdmin), the SQL statement you're looking for is simply this:
FLUSH HOSTS;
The problem is you are not in the correct directory. A simple fix in Jupyter is to do the following command:
Here is an example command to use in Jupyter:
%%bash
cd /home/ec2-user/ml_volume/GitHub_BMM
git show
Note you need to do the commands in the same cell.
To test if the POST variable has an element called 'userID' you would be better off using array_key_exists .. which actually tests for the existence of the array key not whether its value has been set .. a subtle and probably only semantic difference, but it does improve readability.
and right now your $uid is being set to a boolean value depending whether $__POST['userID'] is set or not ... If I recall from memory you might want to try ...
$uid = (array_key_exists('userID', $_POST)?$_POST['userID']:'guest';
Then you can use an identifiable 'guest' user and render your code that much more readable :)
Another point re isset() even though it is unlikely to apply in this scenario, it's worth remembering if you don't want to get caught out later ... an array element can be legitimately set to NULL ... i.e. it can exist, but be as yet unpopulated, and this could be a valid, acceptable, and testable condition. but :
a = array('one'=>1, 'two'=>null, 'three'=>3);
isset(a['one']) == true
isset(a['two']) == false
array_key_exists(a['one']) == true
array_key_exists(a['two']) == true
Bw sure you know which function you want to use for which purpose.
This is about recent additions to AngularJS, to serve as future answer (also for another question).
Angular newer versions (now in 1.3 beta), AngularJS natively supports this option, using ngModelOptions
, like
ng-model-options="{ updateOn: 'default blur', debounce: { default: 500, blur: 0 } }"
Example:
<input type="text" name="username"
ng-model="user.name"
ng-model-options="{updateOn: 'default blur', debounce: {default: 500, blur: 0} }" />
sudo apt-get install php7.0-mysql
for php7.0 works well for me
To remove newlines, use tr:
tr -d '\n'
If you want to replace each newline with a single space:
tr '\n' ' '
The error ba: Event not found
is coming from csh, and is due to csh trying to match !ba
in your history list. You can escape the !
and write the command:
sed ':a;N;$\!ba;s/\n/ /g' # Suitable for csh only!!
but sed is the wrong tool for this, and you would be better off using a shell that handles quoted strings more reasonably. That is, stop using csh and start using bash.
This is what worked best for me:
string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, @"../"));
Getting the 'right' path wasn't the problem, adding '../' obviously does that, but after that, the given string isn't usable, because it will just add the '../' at the end.
Surrounding it with Path.GetFullPath()
will give you the absolute path, making it usable.
The answer about threading is good, but you need to be a bit more specific about what you want to do.
If you have two functions that both use a lot of CPU, threading (in CPython) will probably get you nowhere. Then you might want to have a look at the multiprocessing module or possibly you might want to use jython/IronPython.
If CPU-bound performance is the reason, you could even implement things in (non-threaded) C and get a much bigger speedup than doing two parallel things in python.
Without more information, it isn't easy to come up with a good answer.
Today i also face this type of problem during visual studio 2015 Community installation. As i have 64bit OS. I used https://www.microsoft.com/en-us/download/details.aspx?id=49093 link to update KB2999226 mannualy.
Try It. Good luck.
I had the same problem. Another way to generate the correct .crt file is like this:
Sometimes you get a .PEM file with an entire certificate chain inside. The file may look like this....
-----BEGIN RSA PRIVATE KEY-----
blablablabase64private...
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
blablablabase64CRT1...
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
blablablabase64CRT2...
-----END CERTIFICATE-----
...
If you remove the entire private key
section, you will have a valid chained .crt
Invoking an overridable method in the constructor allows subclasses to subvert the code, so you can't guarantee that it works anymore. That's why you get a warning.
In your example, what happens if a subclass overrides getTitle()
and returns null ?
To "fix" this, you can use a factory method instead of a constructor, it's a common pattern of objects instanciation.
You can use onchange
event of the checkbox to enable/disable button based on checked
value
<input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " />
<input type="checkbox" onchange="document.getElementById('sendNewSms').disabled = !this.checked;" />
This could be a bit tricky in the most general case.
On the face of it, InetAddress.getLocalHost()
should give you the IP address of this host. The problem is that a host could have lots of network interfaces, and an interface could be bound to more than one IP address. And to top that, not all IP addresses will be reachable outside of your machine or your LAN. For example, they could be IP addresses for virtual network devices, private network IP addresses, and so on.
What this means is that the IP address returned by InetAddress.getLocalHost()
might not be the right one to use.
How can you deal with this?
NetworkInterface.getNetworkInterfaces()
to get all of the known network interfaces on the host, and then iterate over each NI's addresses.InetAddress.getByName()
to look up the primary IP address. (But how do you get it, and how do you deal with a DNS-based load balancer?)In summary, InetAddress.getLocalHost()
will typically work, but you may need to provide an alternative method for the cases where your code is run in an environment with "complicated" networking.
I am able to get all the IP addresses associated all Network Interfaces, but how do i distinguish them?
In fact, the InetAddress API provides methods for testing for loopback, link local, site local, multicast and broadcast addresses. You can use these to sort out which of the IP addresses you get back is most appropriate.
From here
<nul set /p =Testing testing
and also to echo beginning with spaces use
echo.Message goes here
There is the conditional expression:
a if cond else b
but this is an expression, not a statement.
In if statements, the if
(or elif
or else
) can be written on the same line as the body of the block if the block is just one like:
if something: somefunc()
else: otherfunc()
but this is discouraged as a matter of formatting-style.
You can use MemberwiseClone
obj myobj2 = (obj)myobj.MemberwiseClone();
The copy is a shallow copy which means the reference properties in the clone are pointing to the same values as the original object but that shouldn't be an issue in your case as the properties in obj
are of value types.
If you own the source code, you can also implement ICloneable
I've read this whole thread, and I just want to point out what seems like an inconsistency to me.
The compiler prevents you from doing the assignment with Lists:
List<Tiger> myTigersList = new List<Tiger>() { new Tiger(), new Tiger(), new Tiger() };
List<Animal> myAnimalsList = myTigersList; // Compiler error
But the compiler is perfectly fine with arrays:
Tiger[] myTigersArray = new Tiger[3] { new Tiger(), new Tiger(), new Tiger() };
Animal[] myAnimalsArray = myTigersArray; // No problem
The argument about whether the assignment is known to be safe falls apart here. The assignment I did with the array is not safe. To prove that, if I follow that up with this:
myAnimalsArray[1] = new Giraffe();
I get a runtime exception "ArrayTypeMismatchException". How does one explain this? If the compiler really wants to prevent me from doing something stupid, it should have prevented me from doing the array assignment.
By default, mysql search my.cnf first at /etc folder. If there is no /etc/my.cnf file inside this folder, I advise you to create new one in this folder as indicated by the documentation (https://dev.mysql.com/doc/refman/5.6/en/option-files.html).
You can also search for existing my.cnf furnished by your mysql installation. You can launch the following command
sudo find / -name "*.cnf"
You can use the following configuration file with myisam table and without innodb mysql support (from port installation of mysql on mac os x maverick). Please verify each command in this configuration file.
# Example MySQL config file for large systems.
#
# This is for a large system with memory = 512M where the system runs mainly
# MySQL.
#
# MySQL programs look for option files in a set of
# locations which depend on the deployment platform.
# You can copy this option file to one of those
# locations. For information about these locations, see:
# http://dev.mysql.com/doc/mysql/en/option-files.html
#
# In this file, you can use all long options that a program supports.
# If you want to know which options a program supports, run the program
# with the "--help" option.
# The following options will be passed to all MySQL clients
[client]
#password = your_password
port = 3306
socket = /opt/local/var/run/mysql5/mysqld.sock
# Here follows entries for some specific programs
# The MySQL server
[mysqld]
port = 3306
socket = /opt/local/var/run/mysql5/mysqld.sock
skip-locking
key_buffer_size = 256M
max_allowed_packet = 1M
table_open_cache = 256
sort_buffer_size = 1M
read_buffer_size = 1M
read_rnd_buffer_size = 4M
myisam_sort_buffer_size = 64M
thread_cache_size = 8
query_cache_size= 16M
# Try number of CPU's*2 for thread_concurrency
thread_concurrency = 8
# Don't listen on a TCP/IP port at all. This can be a security enhancement,
# if all processes that need to connect to mysqld run on the same host.
# All interaction with mysqld must be made via Unix sockets or named pipes.
# Note that using this option without enabling named pipes on Windows
# (via the "enable-named-pipe" option) will render mysqld useless!
#
#skip-networking
# Replication Master Server (default)
# binary logging is required for replication
log-bin=mysql-bin
# binary logging format - mixed recommended
binlog_format=mixed
# required unique id between 1 and 2^32 - 1
# defaults to 1 if master-host is not set
# but will not function as a master if omitted
server-id = 1
# Replication Slave (comment out master section to use this)
#
# To configure this host as a replication slave, you can choose between
# two methods :
#
# 1) Use the CHANGE MASTER TO command (fully described in our manual) -
# the syntax is:
#
# CHANGE MASTER TO MASTER_HOST=<host>, MASTER_PORT=<port>,
# MASTER_USER=<user>, MASTER_PASSWORD=<password> ;
#
# where you replace <host>, <user>, <password> by quoted strings and
# <port> by the master's port number (3306 by default).
#
# Example:
#
# CHANGE MASTER TO MASTER_HOST='125.564.12.1', MASTER_PORT=3306,
# MASTER_USER='joe', MASTER_PASSWORD='secret';
#
# OR
#
# 2) Set the variables below. However, in case you choose this method, then
# start replication for the first time (even unsuccessfully, for example
# if you mistyped the password in master-password and the slave fails to
# connect), the slave will create a master.info file, and any later
# change in this file to the variables' values below will be ignored and
# overridden by the content of the master.info file, unless you shutdown
# the slave server, delete master.info and restart the slaver server.
# For that reason, you may want to leave the lines below untouched
# (commented) and instead use CHANGE MASTER TO (see above)
#
# required unique id between 2 and 2^32 - 1
# (and different from the master)
# defaults to 2 if master-host is set
# but will not function as a slave if omitted
#server-id = 2
#
# The replication master for this slave - required
#master-host = <hostname>
#
# The username the slave will use for authentication when connecting
# to the master - required
#master-user = <username>
#
# The password the slave will authenticate with when connecting to
# the master - required
#master-password = <password>
#
# The port the master is listening on.
# optional - defaults to 3306
#master-port = <port>
#
# binary logging - not required for slaves, but recommended
#log-bin=mysql-bin
# Uncomment the following if you are using InnoDB tables
#innodb_data_home_dir = /opt/local/var/db/mysql5
#innodb_data_file_path = ibdata1:10M:autoextend
#innodb_log_group_home_dir = /opt/local/var/db/mysql5
# You can set .._buffer_pool_size up to 50 - 80 %
# of RAM but beware of setting memory usage too high
#innodb_buffer_pool_size = 256M
#innodb_additional_mem_pool_size = 20M
# Set .._log_file_size to 25 % of buffer pool size
#innodb_log_file_size = 64M
#innodb_log_buffer_size = 8M
#innodb_flush_log_at_trx_commit = 1
#innodb_lock_wait_timeout = 50
[mysqldump]
quick
max_allowed_packet = 16M
[mysql]
no-auto-rehash
# Remove the next comment character if you are not familiar with SQL
#safe-updates
[myisamchk]
key_buffer_size = 128M
sort_buffer_size = 128M
read_buffer = 2M
write_buffer = 2M
[mysqlhotcopy]
interactive-timeout
ngOnInit()
is called after ngOnChanges()
was called the first time. ngOnChanges()
is called every time inputs are updated by change detection.
ngAfterViewInit()
is called after the view is initially rendered. This is why @ViewChild()
depends on it. You can't access view members before they are rendered.
The declaration of x
is inside foo
but the x=5
initialization takes place outside of foo
!
What we need to understand here is that
static int x = 5;
is not the same as
static int x;
x = 5;
Other answers have used the important words here, scope and lifetime, and pointed out that the scope of x
is from the point of its declaration in the function foo
to the end of the function foo
. For example I checked by moving the declaration to the end of the function, and that makes x
undeclared at the x++;
statement.
So the static int x
(scope) part of the statement actually applies where you read it, somewhere INSIDE the function and only from there onwards, not above it inside the function.
However the x = 5
(lifetime) part of the statement is initialization of the variable and happening OUTSIDE of the function as part of the program loading. Variable x
is born with a value of 5
when the program loads.
I read this in one of the comments: "Also, this doesn't address the really confusing part, which is the fact that the initializer is skipped on subsequent calls." It is skipped on all calls. Initialization of the variable is outside of the function code proper.
The value of 5 is theoretically set regardless of whether or not foo is called at all, although a compiler might optimize the function away if you don't call it anywhere. The value of 5 should be in the variable before foo is ever called.
Inside of foo
, the statement static int x = 5;
is unlikely to be generating any code at all.
I found the address x
uses when I put a function foo
into a program of mine, and then (correctly) guessed that the same location would be used if I ran the program again. The partial screen capture below shows that x
has the value 5
even before the first call to foo
.
Your query would work already - except that you are running into naming conflicts or just confusing the output column (the CASE
expression) with source column result
, which has different content.
...
GROUP BY model.name, attempt.type, attempt.result
...
You need to GROUP BY
your CASE
expression instead of your source column:
...
GROUP BY model.name, attempt.type
, CASE WHEN attempt.result = 0 THEN 0 ELSE 1 END
...
Or provide a column alias that's different from any column name in the FROM
list - or else that column takes precedence:
SELECT ...
, CASE WHEN attempt.result = 0 THEN 0 ELSE 1 END AS result1
...
GROUP BY model.name, attempt.type, result1
...
The SQL standard is rather peculiar in this respect. Quoting the manual here:
An output column's name can be used to refer to the column's value in
ORDER BY
andGROUP BY
clauses, but not in theWHERE
orHAVING
clauses; there you must write out the expression instead.
And:
If an
ORDER BY
expression is a simple name that matches both an output column name and an input column name,ORDER BY
will interpret it as the output column name. This is the opposite of the choice thatGROUP BY
will make in the same situation. This inconsistency is made to be compatible with the SQL standard.
Bold emphasis mine.
These conflicts can be avoided by using positional references (ordinal numbers) in GROUP BY
and ORDER BY
, referencing items in the SELECT
list from left to right. See solution below.
The drawback is, that this may be harder to read and vulnerable to edits in the SELECT
list (one might forget to adapt positional references accordingly).
But you do not have to add the column day
to the GROUP BY
clause, as long as it holds a constant value (CURRENT_DATE-1
).
Rewritten and simplified with proper JOIN syntax and positional references it could look like this:
SELECT m.name
, a.type
, CASE WHEN a.result = 0 THEN 0 ELSE 1 END AS result
, CURRENT_DATE - 1 AS day
, count(*) AS ct
FROM attempt a
JOIN prod_hw_id p USING (hard_id)
JOIN model m USING (model_id)
WHERE ts >= '2013-11-06 00:00:00'
AND ts < '2013-11-07 00:00:00'
GROUP BY 1,2,3
ORDER BY 1,2,3;
Also note that I am avoiding the column name time
. That's a reserved word and should never be used as identifier. Besides, your "time" obviously is a timestamp
or date
, so that is rather misleading.
You can use following example for building SQL statement.
DECLARE @sqlCommand varchar(1000)
DECLARE @columnList varchar(75)
DECLARE @city varchar(75)
SET @columnList = 'CustomerID, ContactName, City'
SET @city = '''London'''
SET @sqlCommand = 'SELECT ' + @columnList + ' FROM customers WHERE City = ' + @city
EXEC (@sqlCommand)
With using this approach you can ensure that the data values being passed into the query are the correct datatypes and avoind use of more quotes.
DECLARE @sqlCommand nvarchar(1000)
DECLARE @columnList varchar(75)
DECLARE @city varchar(75)
SET @columnList = 'CustomerID, ContactName, City'
SET @city = 'London'
SET @sqlCommand = 'SELECT ' + @columnList + ' FROM customers WHERE City = @city'
EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75)', @city = @city
I looked thru the answers above, I recommend pejman's Dec 29 '16 at 13:31 suggestion but he/she has not left a full answer. Here it is, I will put this as --> (you need a service and a listener $watch on one of the scopes from controllers for changes in the service area)
var app =
angular.module('myApp', ['ngRoute', 'ngSanitize']);
app.service('bridgeService', function () {
var msg = "";
return msg;
});
app.controller('CTRL_1'
, function ($scope, $http, bridgeService)
{
$http.get(_restApi, config)
.success(
function (serverdata, status, config) {
$scope.scope1Box = bridgeService.msg = serverdata;
});
});
app.controller('CTRL_2'
, function ($scope, $http, bridgeService)
{
$scope.$watch( function () {
return (bridgeService.msg);
}, function (newVal, oldVal) {
$scope.scope2Box = newVal;
}, true
);
});
Here are two functions to get the page height and the scroll amounts (x,y) without the use of the (bloated) dimensions plugin:
// getPageScroll() by quirksmode.com
function getPageScroll() {
var xScroll, yScroll;
if (self.pageYOffset) {
yScroll = self.pageYOffset;
xScroll = self.pageXOffset;
} else if (document.documentElement && document.documentElement.scrollTop) {
yScroll = document.documentElement.scrollTop;
xScroll = document.documentElement.scrollLeft;
} else if (document.body) {// all other Explorers
yScroll = document.body.scrollTop;
xScroll = document.body.scrollLeft;
}
return new Array(xScroll,yScroll)
}
// Adapted from getPageSize() by quirksmode.com
function getPageHeight() {
var windowHeight
if (self.innerHeight) { // all except Explorer
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) {
windowHeight = document.documentElement.clientHeight;
} else if (document.body) { // other Explorers
windowHeight = document.body.clientHeight;
}
return windowHeight
}
In addition to grouping by the field name, you may also group by ordinal, or position of the field within the table. 1 corresponds to the first field (regardless of name), 2 is the second, and so on.
This is generally ill-advised if you're grouping on something specific, since the table/view structure may change. Additionally, it may be difficult to quickly comprehend what your SQL query is doing if you haven’t memorized the table fields.
If you are returning a unique set, or quickly performing a temporary lookup, this is nice shorthand syntax to reduce typing. If you plan to run the query again at some point, I’d recommend replacing those to avoid future confusion and unexpected complications (due to scheme changes).
In case of changing all the keys at once. Here I am stemming the keys.
a = {'making' : 1, 'jumping' : 2, 'climbing' : 1, 'running' : 2}
b = {ps.stem(w) : a[w] for w in a.keys()}
print(b)
>>> {'climb': 1, 'jump': 2, 'make': 1, 'run': 2} #output
It depends.
Start with Basic I/O, take a look at Properties, take a look at Preferences API and maybe even Java API for XML Processing and Java Architecture for XML Binding
And if none of those meet your particular needs, you could even look at using some kind of Database
Copy the python file to /bin:
sudo cp -i /path/to/your_script.py /bin
Add A New Cron Job:
sudo crontab -e
Scroll to the bottom and add the following line (after all the #'s
):
@reboot python /bin/your_script.py &
The “&” at the end of the line means the command is run in the background and it won’t stop the system booting up.
Test it:
sudo reboot
Add this file to your Desktop: test_code.py (run it to check that it works for you)
from os.path import expanduser
import datetime
file = open(expanduser("~") + '/Desktop/HERE.txt', 'w')
file.write("It worked!\n" + str(datetime.datetime.now()))
file.close()
Run the following commands:
sudo cp -i ~/Desktop/test_code.py /bin
sudo crontab -e
Add the following line and save it:
@reboot python /bin/test_code.py &
Now reboot your computer and you should find a new file on your Desktop: HERE.txt
It's required for extensibility -- if someone uses an API you've developed, the enums you define are static; they can't be added to or modified. However, if you let it implement an interface, the person using the API can develop their own enum using the same interface. You can then register this enum with an enum manager which conglomerates the enums together with the standard interface.
Edit: @Helper Method has the perfect example of this. Think about having other libraries defining new operators and then telling a manager class that 'hey, this enum exists -- register it'. Otherwise, you'd only be able to define Operators in your own code - there'd be no extensibility.
the solution that does work is this:
$str = preg_replace('/\\\"/',"\"", $str);
However you have to be extremely careful here because you need to make sure that all your values have their quotes escaped (which is generally true anyway, but especially so now that you will be stripping all the escapes from PHP's idiotic (and dysfunctional) "helper" functionality of adding unnecessary backslashes in front of all your object ids and values).
So, php, by default, double escapes your values that have a quote in them, so if you have a value of My name is "Joe"
in your DB, php will bring this back as
My name is \\"Joe\\"
.
This may or may not be useful to you. If it's not you can then take the extra step of replacing the leading slash there like this:
$str = preg_replace('/\\\\\"/',"\"", $str);
yeah... it's ugly... but it works.
You're then left with something that vaguely resembles actual JSON.
Git has two types of branches: local
and remote
. To use git pull
and git push
as you'd like, you have to tell your local branch (my_test
) which remote branch it's tracking. In typical Git fashion this can be done in both the config file and with commands.
Commands
Make sure you're on your master
branch with
1)git checkout master
then create the new branch with
2)git branch --track my_test origin/my_test
and check it out with
3)git checkout my_test
.
You can then push
and pull
without specifying which local and remote.
However if you've already created the branch then you can use the -u
switch to tell git's push
and pull
you'd like to use the specified local and remote branches from now on, like so:
git pull -u my_test origin/my_test
git push -u my_test origin/my_test
Config
The commands to setup remote branch tracking are fairly straight forward but I'm listing the config way as well as I find it easier if I'm setting up a bunch of tracking branches. Using your favourite editor open up your project's .git/config
and add the following to the bottom.
[remote "origin"]
url = [email protected]:username/repo.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "my_test"]
remote = origin
merge = refs/heads/my_test
This specifies a remote called origin
, in this case a GitHub style one, and then tells the branch my_test
to use it as it's remote.
You can find something very similar to this in the config after running the commands above.
Some useful resources:
The query either returned no rows or is erroneus, thus FALSE
is returned. Change it to
if (!$dbc || mysqli_num_rows($dbc) == 0)
mysqli_num_rows
:
Return Values
Returns TRUE on success or FALSE on failure. For SELECT, SHOW, DESCRIBE or EXPLAIN mysqli_query() will return a result object.
Looking at Standard .NET event patterns we find
The standard signature for a .NET event delegate is:
void OnEventRaised(object sender, EventArgs args);
[...]
The argument list contains two arguments: the sender, and the event arguments. The compile time type of sender is System.Object, even though you likely know a more derived type that would always be correct. By convention, use object.
Below on same page we find an example of the typical event definition which is something like
public event EventHandler<EventArgs> EventName;
Had we defined
class MyClass
{
public event Action<MyClass, EventArgs> EventName;
}
the handler could have been
void OnEventRaised(MyClass sender, EventArgs args);
where sender
has the correct (more derived) type.
Date d=new Date(new Date().getTime()+28800000);
String s=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(d);
HH will return 0-23 for hours.
kk will return 1-24 for hours.
See more here: Customizing Formats
use method setIs24HourView(Boolean is24HourView) to set time picker to set 24 hour view.
curl --write-out "%{http_code}\n" --silent --output /dev/null "$URL"
works. If not, you have to hit return to view the code itself.
You could do this:
if (!discount.nil? && !discount.zero?)
The order is important here, because if discount
is nil
, then it will not have a zero?
method. Ruby's short-circuit evaluation should prevent it from trying to evaluate discount.zero?
, however, if discount
is nil
.
This is something I face regularly, & I've generalised the script Wolfgang provided above to work with any branch
I also added an "are you sure" prompt, & some feedback output
#!/bin/bash
# reset the current repository
# WF 2012-10-15
# AT 2012-11-09
# see http://stackoverflow.com/questions/1628088/how-to-reset-my-local-repository-to-be-just-like-the-remote-repository-head
timestamp=`date "+%Y-%m-%d-%H_%M_%S"`
branchname=`git rev-parse --symbolic-full-name --abbrev-ref HEAD`
read -p "Reset branch $branchname to origin (y/n)? "
[ "$REPLY" != "y" ] ||
echo "about to auto-commit any changes"
git commit -a -m "auto commit at $timestamp"
if [ $? -eq 0 ]
then
echo "Creating backup auto-save branch: auto-save-$branchname-at-$timestamp"
git branch "auto-save-$branchname-at-$timestamp"
fi
echo "now resetting to origin/$branchname"
git fetch origin
git reset --hard origin/$branchname
import java.util.*;
class Ss
{
int id, salary;
String name;
void Ss(int id, int salary, String name)
{
this.id = id;
this.salary = salary;
this.name = name;
}
void display()
{
System.out.println("The id of employee:" + id);
System.out.println("The name of employye:" + name);
System.out.println("The salary of employee:" + salary);
}
}
class employee
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
Ss s = new Ss(sc.nextInt(), sc.nextInt(), sc.nextLine());
s.display();
}
}
I agree with the previous answers in that they are useful to mantain data consistency. However, there was an interesting post by Jeff Atwood some weeks ago that discussed the pros and cons of normalized and consistent data.
In a few words, a denormalized database can be faster when handling huge amounts of data; and you may not care about precise consistency depending on the application, but it forces you to be much more careful when dealing with data, as the DB won't be.
After multiple tests, this is the best way I found :)
Set<User> test = httpService.get(url).toResponseSet(User[].class);
All you need there
public <T> Set<T> toResponseSet(Class<T[]> setType) {
HttpEntity<?> body = new HttpEntity<>(objectBody, headers);
ResponseEntity<T[]> response = template.exchange(url, method, body, setType);
return Sets.newHashSet(response.getBody());
}
To submit a single file, you can simply use the File
object from the input
's .files
array directly as the value of body:
in your fetch()
initializer:
const myInput = document.getElementById('my-input');
// Later, perhaps in a form 'submit' handler or the input's 'change' handler:
fetch('https://example.com/some_endpoint', {
method: 'POST',
body: myInput.files[0],
});
This works because File
inherits from Blob
, and Blob
is one of the permissible BodyInit
types defined in the Fetch Standard.
MD5 encrypting is possible, but decrypting is still unknown (to me). However, there are many ways to compare these things.
Using compare methods like so:
<?php
$db_pass = $P$BX5675uhhghfhgfhfhfgftut/0;
$my_pass = "mypass";
if ($db_pass === md5($my_pass)) {
// password is matched
} else {
// password didn't match
}
Only for WordPress users.
If you have access to your PHPMyAdmin, focus you have because you paste that hashing here: $P$BX5675uhhghfhgfhfhfgftut/0, WordPress user_pass
is not only MD5 format it also uses utf8_mb4_cli
charset so what to do?
That's why I use another Approach if I forget my WordPress password I use
I install other WordPress with new password :P, and I then go to PHPMyAdmin and copy that hashing from the database and paste that hashing to my current PHPMyAdmin password ( which I forget )
EASY is use this :
I USE THIS APPROACH FOR MY SELF WHEN I DESIGN THEMES AND PLUGINS
WORDPRESS USE THIS
https://developer.wordpress.org/reference/functions/wp_hash_password/
you can use this code
private List myList = new ArrayList();
private void addItemToList(Object obj){
if(myList.size()<10){
myList.add(0,obj);
}else{
myList.add(0,obj);
myList.remove(10);
}
}
You can use $http.get()
method to fetch your JSON
file. Then assign response data to a $scope
object. In HTML
to create table use ng-repeat for $scope object. ng-repeat
will loop the rows in-side this loop you can bind data to columns dynamically.
I have checked your code and you have created static table
<table>
<tr>
<th>Name</th>
<th>Relationship</th>
</tr>
<tr ng-repeat="indivisual in members">
<td>{{ indivisual.Name }}</td>
<td>{{ indivisual.Relation }}</td>
</tr>
</table>
so better your can go to my code to create dynamic table as per data you column and row will be increase or decrease..
It is a xml error for some reason may be because of deleting a view or string in another view or may be for missing " or /> ..... etc
But here I am using a good technique to figure out where is the problem exactly :-
I know it is not the solution of the main problem but it will make you find where is the error quickly and save you time.
Update
There is another way you can find out easily, as Bennik2000 write in comment, you can look at the right scrollbar for red lines, they also indicate errors.
Update
I found a very simple way to get where is the error exactly if it is in resource file or even java file.
1- Go to Project Window.
2- Open the file that has the error.
3- Click F2 to go to the nearest error appears (it will go to the correct line)
This is significantly faster than the EXISTS
way:
SELECT [EmailAddress], [CustomerName] FROM [Customers] WHERE [EmailAddress] IN
(SELECT [EmailAddress] FROM [Customers] GROUP BY [EmailAddress] HAVING COUNT(*) > 1)
You need to use regular expressions to identify the unwanted characters. For the most easily readable code, you want the str_replace_all
from the stringr
package, though gsub
from base R works just as well.
The exact regular expression depends upon what you are trying to do. You could just remove those specific characters that you gave in the question, but it's much easier to remove all punctuation characters.
x <- "a1~!@#$%^&*(){}_+:\"<>?,./;'[]-=" #or whatever
str_replace_all(x, "[[:punct:]]", " ")
(The base R equivalent is gsub("[[:punct:]]", " ", x)
.)
An alternative is to swap out all non-alphanumeric characters.
str_replace_all(x, "[^[:alnum:]]", " ")
Note that the definition of what constitutes a letter or a number or a punctuatution mark varies slightly depending upon your locale, so you may need to experiment a little to get exactly what you want.
Sorting by C and D needs to be put into number form for the corresponding column, ie 3 and 4, respectively. Eg Order By 2 asc")
You can use any of the following:
\b #A word break and will work for both spaces and end of lines.
(^|\s) #the | means or. () is a capturing group.
/\b(stackoverflow)\b/
Also, if you don't want to include the space in your match, you can use lookbehind/aheads.
(?<=\s|^) #to look behind the match
(stackoverflow) #the string you want. () optional
(?=\s|$) #to look ahead.
This is a common question -- especially in today's environment of virtual environments. Unfortunately, the answer is not as straight-forward as one might assume.
dd is the obvious first choice, but dd is essentially a copy and that forces you to write every block of data (thus, initializing the file contents)... And that initialization is what takes up so much I/O time. (Want to make it take even longer? Use /dev/random instead of /dev/zero! Then you'll use CPU as well as I/O time!) In the end though, dd is a poor choice (though essentially the default used by the VM "create" GUIs). E.g:
dd if=/dev/zero of=./gentoo_root.img bs=4k iflag=fullblock,count_bytes count=10G
truncate is another choice -- and is likely the fastest... But that is because it creates a "sparse file". Essentially, a sparse file is a section of disk that has a lot of the same data, and the underlying filesystem "cheats" by not really storing all of the data, but just "pretending" that it's all there. Thus, when you use truncate to create a 20 GB drive for your VM, the filesystem doesn't actually allocate 20 GB, but it cheats and says that there are 20 GB of zeros there, even though as little as one track on the disk may actually (really) be in use. E.g.:
truncate -s 10G gentoo_root.img
fallocate is the final -- and best -- choice for use with VM disk allocation, because it essentially "reserves" (or "allocates" all of the space you're seeking, but it doesn't bother to write anything. So, when you use fallocate to create a 20 GB virtual drive space, you really do get a 20 GB file (not a "sparse file", and you won't have bothered to write anything to it -- which means virtually anything could be in there -- kind of like a brand new disk!) E.g.:
fallocate -l 10G gentoo_root.img
First, you want to use
model <- lm(Total ~ Coupon, data=df)
not model <-lm(df$Total ~ df$Coupon, data=df)
.
Second, by saying lm(Total ~ Coupon)
, you are fitting a model that uses Total
as the response variable, with Coupon
as the predictor. That is, your model is of the form Total = a + b*Coupon
, with a
and b
the coefficients to be estimated. Note that the response goes on the left side of the ~
, and the predictor(s) on the right.
Because of this, when you ask R to give you predicted values for the model, you have to provide a set of new predictor values, ie new values of Coupon
, not Total
.
Third, judging by your specification of newdata
, it looks like you're actually after a model to fit Coupon
as a function of Total
, not the other way around. To do this:
model <- lm(Coupon ~ Total, data=df)
new.df <- data.frame(Total=c(79037022, 83100656, 104299800))
predict(model, new.df)
You can face this wrong in specific database which is created after SSMS update. Open SSMS and select your databases and open your required database then click Security--> Users--> and right click on Users and click again on 'New User' and add 'NT AUTHORITY\Authenticated Users' and save you work and go to your Form on Web/Desktop whatever do you. Enjoy....
Can you learn to draw, sculpt, or paint in ten weeks? Anyone can learn to punch the keys to program, just as anyone can pick up a brush, but it takes time and talent to cultivate the artistry to develop. Do yourself a favor and put the time and effort in to learning, not cramming. The lessons you learn by a concerted effort to know how to develop will serve you much better than binging on it to meet some arbitrary date.
Just you need to use
//for bold
android:textStyle="bold"
//for italic
android:textStyle="italic"
//for normal
android:textStyle="normal"
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="@string/userName"
android:layout_gravity="left"
android:textSize="16sp"
/>
$( "#btn1" ).click(function() {
$('#btn2').css('display','none');
});
The exception is caused by disabled Download Manager. And there is no way to activate/deactivate Download Manager directly, since it's system application and we don't have access to it.
Only alternative way is redirect user to settings of Download Manager Application.
try {
//Open the specific App Info page:
Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + "com.android.providers.downloads"));
startActivity(intent);
} catch ( ActivityNotFoundException e ) {
e.printStackTrace();
//Open the generic Apps page:
Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
startActivity(intent);
}
There's a typo in your code (the tag a is closed too early). You can either use:
<a href="whatever" onclick="return confirm('are you sure?')"><img ...></a>
note the return (confirm): the value returned by scripts in intrinsic evens decides whether the default browser action is run or not; in case you need to run a big piece of code you can of course call another function:
<script type="text/javascript">
function confirm_delete() {
return confirm('are you sure?');
}
</script>
...
<a href="whatever" onclick="return confirm_delete()"><img ...></a>
(note that delete is a keyword)
For completeness: modern browsers also support DOM events, allowing you to register more than one handler for the same event on each object, access the details of the event, stop the propagation and much more; see DOM Events.
Just run into this with another cause:
running unit tests in release mode but the library being loaded was the debug mode version which had not been updated
I guess I'm unclear about what the OP was really asking for... Do you want to pass the whole array/list and operate on it inside the function? Or do you want the same thing done on every value/item in the array/list. If the latter is what you wish I have found a method which works well.
I'm more familiar with programming languages such as Fortran and C, in which you can define elemental functions which operate on each element inside an array. I finally tracked down the python equivalent to this and thought I would repost the solution here. The key is to 'vectorize' the function. Here is an example:
def myfunc(a,b):
if (a>b): return a
else: return b
vecfunc = np.vectorize(myfunc)
result=vecfunc([[1,2,3],[5,6,9]],[7,4,5])
print(result)
Output:
[[7 4 5]
[7 6 9]]
It may be that it's not loading the template you expect. I added a new class that inherited from UpdateView
- I thought it would automatically pick the template from what I named my class, but it actually loaded it based on the model
property on the class, which resulted in another (wrong) template being loaded. Once I explicitly set template_name
for the new class, it worked fine.
FYI in Spark 2.4 a lot of you will probably encounter this issue. Kryo serialization has gotten better but in many cases you cannot use spark.kryo.unsafe=true or the naive kryo serializer.
spark.kryo.unsafe="false"
OR
spark.serializer="org.apache.spark.serializer.JavaSerializer"
I modify custom RDD transformations that I encounter or personally write by using explicit broadcast variables and utilizing the new inbuilt twitter-chill api, converting them from rdd.map(row =>
to rdd.mapPartitions(partition => {
functions.
val sampleMap = Map("index1" -> 1234, "index2" -> 2345)
val outputRDD = rdd.map(row => {
val value = sampleMap.get(row._1)
value
})
import com.twitter.chill.MeatLocker
val sampleMap = Map("index1" -> 1234, "index2" -> 2345)
val brdSerSampleMap = spark.sparkContext.broadcast(MeatLocker(sampleMap))
rdd.mapPartitions(partition => {
val deSerSampleMap = brdSerSampleMap.value.get
partition.map(row => {
val value = sampleMap.get(row._1)
value
}).toIterator
})
This new way will only call the broadcast variable once per partition which is better. You will still need to use Java Serialization if you do not register classes.
What do you mean by "initialize an array to zero"? Arrays don't contain "zero" -- they can contain "zero elements", which is the same as "an empty list". Or, you could have an array with one element, where that element is a zero: my @array = (0);
my @array = ();
should work just fine -- it allocates a new array called @array
, and then assigns it the empty list, ()
. Note that this is identical to simply saying my @array;
, since the initial value of a new array is the empty list anyway.
Are you sure you are getting an error from this line, and not somewhere else in your code? Ensure you have use strict; use warnings;
in your module or script, and check the line number of the error you get. (Posting some contextual code here might help, too.)
I personally always use
from package.subpackage.subsubpackage import module
and then access everything as
module.function
module.modulevar
etc. The reason is that at the same time you have short invocation, and you clearly define the module namespace of each routine, something that is very useful if you have to search for usage of a given module in your source.
Needless to say, do not use the import *, because it pollutes your namespace and it does not tell you where a given function comes from (from which module)
Of course, you can run in trouble if you have the same module name for two different modules in two different packages, like
from package1.subpackage import module
from package2.subpackage import module
in this case, of course you run into troubles, but then there's a strong hint that your package layout is flawed, and you have to rethink it.
In a web-based database application that uses a pop-up window to display print-outs of database data, this worked well enough for our needs (tested in Chrome 48):
<form method="post"
target="print_popup"
action="/myFormProcessorInNewWindow.aspx"
onsubmit="window.open('about:blank','print_popup','width=1000,height=800');">
The trick is to match the target
attribute on the <form>
tag with the second argument in the window.open
call in the onsubmit
handler.
asyncio.wait
is more low level than asyncio.gather
.
As the name suggests, asyncio.gather
mainly focuses on gathering the results. It waits on a bunch of futures and returns their results in a given order.
asyncio.wait
just waits on the futures. And instead of giving you the results directly, it gives done and pending tasks. You have to manually collect the values.
Moreover, you could specify to wait for all futures to finish or just the first one with wait
.
Perhaps not what the OP was after, but for those searching the URL to simply access a readable object on S3 is more like:
https://<region>.amazonaws.com/<bucket-name>/<key>
Where <region>
is something like s3-ap-southeast-2
.
Click on the item in the S3 GUI to get the link for your bucket.
(Extension of @lepe
's and @redsquare
answer for ASP.NET MVC
+ jquery.validate.unobtrusive.js
)
The jquery validation plugin (not the Microsoft unobtrusive one) allows you to put a .cancel
class on your submit button to bypass validation completely (as shown in accepted answer).
To skip validation while still using a submit-button, add a class="cancel" to that input.
<input type="submit" name="submit" value="Submit"/>
<input type="submit" class="cancel" name="cancel" value="Cancel"/>
(don't confuse this with type='reset'
which is something completely different)
Unfortunately the jquery.validation.unobtrusive.js
validation handling (ASP.NET MVC) code kinda screws up the jquery.validate plugin's default behavior.
This is what I came up with to allow you to put .cancel
on the submit button as shown above. If Microsoft ever 'fixes' this then you can just remvoe this code.
// restore behavior of .cancel from jquery validate to allow submit button
// to automatically bypass all jquery validation
$(document).on('click', 'input[type=image].cancel,input[type=submit].cancel', function (evt)
{
// find parent form, cancel validation and submit it
// cancelSubmit just prevents jQuery validation from kicking in
$(this).closest('form').data("validator").cancelSubmit = true;
$(this).closest('form').submit();
return false;
});
Note: If at first try it appears that this isn't working - make sure you're not roundtripping to the server and seeing a server generated page with errors. You'll need to bypass validation on the server side by some other means - this just allows the form to be submitted client side without errors (the alternative would be adding .ignore
attributes to everything in your form).
(Note: you may need to add button
to the selector if you're using buttons to submit)
You wont be able to get python to tell you where the JSON is incorrect. You will need to use a linter online somewhere like this
This will show you error in the JSON you are trying to decode.
There are some great answers mentioned here. Another approach you could take would be to use some free SDKs available online like Atooma, tranql and Neura, that can be integrated with your Android application (it takes less than 20 min to integrate). Along with giving you the accurate location of your user, it can also give you good insights about your user’s activities. Also, some of them consume less than 1% of your battery
Another simple way to solve this problem is to edit your build.gradle
(app):
android
tag and change compileSdkVersion 26
to compileSdkVersion 27
defaultConfig
tag and change targetSdkVersion 26
to targetSdkVersion 27
dependencies
tag and change implementation 'com.android.support:appcompat-v7:26.1.0'
to implementation 'com.android.support:appcompat-v7:27.1.1'
Try resetting your network settings
Settings -> General -> Reset -> Reset Network Settings
And try deleting the contents of your mac/pc lockdown folder. Here's the link, follow the steps on "Reset the Lockdown folder".
http://support.apple.com/kb/ts2529
This one worked for me.
If you need a name for the csv columns, you can use this method
$example= array_map(function($v) {$column = str_getcsv($v, ";");return array("foo" => $column[0],"bar" => $column[1]);},file('file.csv'));
Converting From Array to String is So Easy !
var A = ['Sunday','Monday','Tuesday','Wednesday','Thursday']
array = A + ""
That's it Now A is a string. :)
In Retrofit2, When you want to send your parameters in raw you must use Scalars.
first add this in your gradle:
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.retrofit2:converter-scalars:2.3.0'
Your Interface
public interface ApiInterface {
String URL_BASE = "http://10.157.102.22/rest/";
@Headers("Content-Type: application/json")
@POST("login")
Call<User> getUser(@Body String body);
}
Activity
public class SampleActivity extends AppCompatActivity implements Callback<User> {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiInterface.URL_BASE)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
// prepare call in Retrofit 2.0
try {
JSONObject paramObject = new JSONObject();
paramObject.put("email", "[email protected]");
paramObject.put("pass", "4384984938943");
Call<User> userCall = apiInterface.getUser(paramObject.toString());
userCall.enqueue(this);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onResponse(Call<User> call, Response<User> response) {
}
@Override
public void onFailure(Call<User> call, Throwable t) {
}
}
I think table-cell
needs to have a parent display:table
element.
Your best bet is to change that column to a timestamp. MySQL will automatically use the first timestamp in a row as a 'last modified' value and update it for you. This is configurable if you just want to save creation time.
See doc http://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html
FOR IMAGE VIEW (set these parameters)
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:scaleType = "fitCenter"
android:adjustViewBounds = "true"
Now whatever the size of the image is there, it's width will match the parent and height will be according to match the ratio. I have tested this and I am 100% sure.
// Results will be:
Image width -> stretched as match parent
Image height -> according to image width (maximum to aspect ratio)
// like the first one
It won't work if your file InputStream.Position is set to the end of the stream. My additional lines:
Stream stream = file.InputStream;
stream.Position = 0;
Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.
The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.
-Xmssize Specifies the initial heap size.
-Xmxsize Specifies the maximum heap size.
-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.
Sizes are expressed in bytes. Append the letter k
or K
to indicate kilobytes, m
or M
to indicate megabytes, g
or G
to indicate gigabytes.
How is the java memory pool divided?
Java (JVM) Memory Model – Memory Management in Java
Judging by the desktop folder location you are using Windows. The command in Windows would be:
adb pull /sdcard/log.txt %USERPROFILE%\Desktop\
Do you mean that for a select element with an id of "next" you need to perform some specific script?
$("#next").change(function(){
//enter code here
});
I had the exact same problem with my instance. My problem was that I forgot to allow port 80 access to the server. Maybe that's your issue as well?
Check with your WHM and make sure that port is open for the IP address of your site,
array_change_value_case
by continue
function array_change_value_case($array, $case = CASE_LOWER){
if ( ! is_array($array)) return false;
foreach ($array as $key => &$value){
if (is_array($value))
call_user_func_array(__function__, array (&$value, $case ) ) ;
else
$array[$key] = ($case == CASE_UPPER )
? strtoupper($array[$key])
: strtolower($array[$key]);
}
return $array;
}
$arrays = array ( 1 => 'ONE', 2=> 'TWO', 3 => 'THREE',
'FOUR' => array ('a' => 'Ahmed', 'b' => 'basem',
'c' => 'Continue'),
5=> 'FIVE',
array('AbCdeF'));
$change_case = array_change_value_case($arrays, CASE_UPPER);
echo "<pre>";
print_r($change_case);
Array ( [1] => one [2] => two [3] => three [FOUR] => Array ( [a] => ahmed [b] => basem [c] => continue ) [5] => five [6] => Array ( [0] => abcdef ) )
Add any file in the documentation which will include your content, for example toc.h:
@ mainpage Manual SDK
<hr/>
@ section pageTOC Content
-# @ref Description
-# @ref License
-# @ref Item
...
And in your Doxyfile
:
INPUT = toc.h \
Example (in Russian):
You need to make sure the frame is fully loaded the best way to do it is to use onload:
<iframe id="nesgt" src="" onload="custom()"></iframe>
function custom(){
document.getElementById("nesgt").contentWindow.document;
}
this function will run automatically when the iframe is fully loaded.
it could be done with setTimeout but we can't get the exact time of the frame load.
hope this helps someone.
PLAIN JAVASCRIPT:
DEMO: http://codepen.io/tazotodua/pen/orhdp
var shownnn = "yes";_x000D_
var dropd = document.getElementById("image-dropdown");_x000D_
_x000D_
function showww() {_x000D_
dropd.style.height = "auto";_x000D_
dropd.style.overflow = "y-scroll";_x000D_
}_x000D_
_x000D_
function hideee() {_x000D_
dropd.style.height = "30px";_x000D_
dropd.style.overflow = "hidden";_x000D_
}_x000D_
//dropd.addEventListener('mouseover', showOrHide, false);_x000D_
//dropd.addEventListener('click',showOrHide , false);_x000D_
_x000D_
_x000D_
function myfuunc(imgParent) {_x000D_
hideee();_x000D_
var mainDIVV = document.getElementById("image-dropdown");_x000D_
imgParent.parentNode.removeChild(imgParent);_x000D_
mainDIVV.insertBefore(imgParent, mainDIVV.childNodes[0]);_x000D_
}
_x000D_
#image-dropdown {_x000D_
display: inline-block;_x000D_
border: 1px solid;_x000D_
}_x000D_
#image-dropdown {_x000D_
height: 30px;_x000D_
overflow: hidden;_x000D_
}_x000D_
/*#image-dropdown:hover {} */_x000D_
_x000D_
#image-dropdown .img_holder {_x000D_
cursor: pointer;_x000D_
}_x000D_
#image-dropdown img.flagimgs {_x000D_
height: 30px;_x000D_
}_x000D_
#image-dropdown span.iTEXT {_x000D_
position: relative;_x000D_
top: -8px;_x000D_
}
_x000D_
<!-- not tested in mobiles -->_x000D_
_x000D_
_x000D_
<div id="image-dropdown" onmouseleave="hideee();">_x000D_
<div class="img_holder" onclick="myfuunc(this);" onmouseover="showww();">_x000D_
<img class="flagimgs first" src="http://www.google.com/tv/images/socialyoutube.png" /> <span class="iTEXT">First</span>_x000D_
</div>_x000D_
<div class="img_holder" onclick="myfuunc(this);" onmouseover="showww();">_x000D_
<img class="flagimgs second" src="http://www.google.com/cloudprint/learn/images/icons/fiabee.png" /> <span class="iTEXT">Second</span>_x000D_
</div>_x000D_
<div class="img_holder" onclick="myfuunc(this);" onmouseover="showww();">_x000D_
<img class="flagimgs second" src="http://www.google.com/tv/images/lplay.png" /> <span class="iTEXT">Third</span>_x000D_
</div>_x000D_
<div class="img_holder" onclick="myfuunc(this);" onmouseover="showww();">_x000D_
<img class="flagimgs second" src="http://www.google.com/cloudprint/learn/images/icons/cloudprintlite.png" /> <span class="iTEXT">Fourth</span>_x000D_
</div>_x000D_
</div>
_x000D_
In case you also want to include your real name in the from-field, you can use the following format
mailx -r "[email protected] (My Name)" -s "My Subject" ...
If you happen to have non-ASCII characters in you name, like My AEÆoeøaaå (Æ= C3 86, ø= C3 B8, å= C3 A5), you have to encode them like this:
mailx -r "[email protected] (My =?utf-8?Q?AE=C3=86oe=C3=B8aa=C3=A5?=)" -s "My Subject" ...
Hope this can save someone an hour of hard work/research!
I solved same issue by adding polyfill following:
<script src="https://cdn.polyfill.io/v3/polyfill.min.js?features=default,Array.prototype.includes,Array.prototype.find"></script>
A polyfill is a piece of code (usually JavaScript on the Web) used to provide modern functionality on older browsers that do not natively support it.
Hope someone find this helpful.
With Java 8, you could pass a supplier to a helper method like below,
if(CommonUtil.resolve(()-> a.b().c()).isPresent()) {
}
Above replaces boiler plate code like below,
if(a!=null && a.b()!=null && a.b().c()!=null) {
}
//CommonUtil.java
public static <T> Optional<T> resolve(Supplier<T> resolver) {
try {
T result = resolver.get();
return Optional.ofNullable(result);
} catch (NullPointerException var2) {
return Optional.empty();
}
}
if ($name ) { #since undef and '' both evaluate to false #this should work only when string is defined and non-empty... #unless you're expecting someting like $name="0" which is false. #notice though that $name="00" is not false }
The best way for accomplishing this operation in Laravel 3
seems to be the use of the Fluent
interface to truncate the table as shown below
DB::query("TRUNCATE TABLE mytable");
If you haven't yet commited the changes, then:
git diff > mypatch.patch
But sometimes it happens that part of the stuff you're doing are new files that are untracked and won't be in your git diff
output. So, one way to do a patch is to stage everything for a new commit (git add
each file, or just git add .
) but don't do the commit, and then:
git diff --cached > mypatch.patch
Add the 'binary' option if you want to add binary files to the patch (e.g. mp3 files):
git diff --cached --binary > mypatch.patch
You can later apply the patch:
git apply mypatch.patch
How do I have a div not take up space until it is timed to come in (using CSS for the timing.)
Here is my solution to the same problem.
Moreover I have an onclick
on the last frame loading another slideshow, and it must not be clickable until the last frame is visible.
Basically my solution is to keep the div
1 pixel high using a scale(0.001)
, zooming it when I need it. If you don't like the zoom effect you can restore the opacity
to 1 after zooming the slide.
#Slide_TheEnd {
-webkit-animation-delay: 240s;
animation-delay: 240s;
-moz-animation-timing-function: linear;
-webkit-animation-timing-function: linear;
animation-timing-function: linear;
-moz-animation-duration: 20s;
-webkit-animation-duration: 20s;
animation-duration: 20s;
-moz-animation-name: Slide_TheEnd;
-webkit-animation-name: Slide_TheEnd;
animation-name: Slide_TheEnd;
-moz-animation-iteration-count: 1;
-webkit-animation-iteration-count: 1;
animation-iteration-count: 1;
-moz-animation-direction: normal;
-webkit-animation-direction: normal;
animation-direction: normal;
-moz-animation-fill-mode: forwards;
-webkit-animation-fill-mode: forwards;
animation-fill-mode: forwards;
transform: scale(0.001);
background: #cf0;
text-align: center;
font-size: 10vh;
opacity: 0;
}
@-moz-keyframes Slide_TheEnd {
0% { opacity: 0; transform: scale(0.001); }
10% { opacity: 1; transform: scale(1); }
95% { opacity: 1; transform: scale(1); }
100% { opacity: 0; transform: scale(0.001); }
}
Other keyframes are removed for the sake of bytes. Please disregard the odd coding, it is made by a php script picking values from an array and str_replacing a template: I'm too lazy to retype everything for every proprietary prefix on a 100+ divs slideshow.
If you deal with bandwidth problems, try to compress data at the client side first, then base64-it.
Nice example of such magic is at http://jszip.stuartk.co.uk/ and more discussion to this topic is at JavaScript implementation of Gzip
Personally I like the & function for this
Assuming that you are using cells A1 and A2 for John Smith
=left(a1,1) & b1
If you want to add text between, for example a period
=left(a1,1) & "." & b1
I feel so damn silly. In my case, it turns out my Android Studio had two projects, one was for my React Native app root and the other for /android. If I closed the project and opened the /android project, I could access AVD Manager again.
Try out these videos egghead.io They are awesome to get started
There are several parts of hibernate logging you can control based on the logger hierarchy of the hibernate package (more on logger hierarchy here).
<!-- Log everything in hibernate -->
<Logger name="org.hibernate" level="info" additivity="false">
<AppenderRef ref="Console" />
</Logger>
<!-- Log SQL statements -->
<Logger name="org.hibernate.SQL" level="debug" additivity="false">
<AppenderRef ref="Console" />
<AppenderRef ref="File" />
</Logger>
<!-- Log JDBC bind parameters -->
<Logger name="org.hibernate.type.descriptor.sql" level="trace" additivity="false">
<AppenderRef ref="Console" />
<AppenderRef ref="File" />
</Logger>
The above was taken from here.
Additionally you could have the property show-sql:true
in your configuration file since that supersedes the logging framework settings. More on that here.
I use this c code for printing coloured shell output. The code is based on this post.
//General Formatting
#define GEN_FORMAT_RESET "0"
#define GEN_FORMAT_BRIGHT "1"
#define GEN_FORMAT_DIM "2"
#define GEN_FORMAT_UNDERSCORE "3"
#define GEN_FORMAT_BLINK "4"
#define GEN_FORMAT_REVERSE "5"
#define GEN_FORMAT_HIDDEN "6"
//Foreground Colors
#define FOREGROUND_COL_BLACK "30"
#define FOREGROUND_COL_RED "31"
#define FOREGROUND_COL_GREEN "32"
#define FOREGROUND_COL_YELLOW "33"
#define FOREGROUND_COL_BLUE "34"
#define FOREGROUND_COL_MAGENTA "35"
#define FOREGROUND_COL_CYAN "36"
#define FOREGROUND_COL_WHITE "37"
//Background Colors
#define BACKGROUND_COL_BLACK "40"
#define BACKGROUND_COL_RED "41"
#define BACKGROUND_COL_GREEN "42"
#define BACKGROUND_COL_YELLOW "43"
#define BACKGROUND_COL_BLUE "44"
#define BACKGROUND_COL_MAGENTA "45"
#define BACKGROUND_COL_CYAN "46"
#define BACKGROUND_COL_WHITE "47"
#define SHELL_COLOR_ESCAPE_SEQ(X) "\x1b["X"m"
#define SHELL_FORMAT_RESET ANSI_COLOR_ESCAPE_SEQ(GEN_FORMAT_RESET)
int main(int argc, char* argv[])
{
//The long way
fputs(SHELL_COLOR_ESCAPE_SEQ(GEN_FORMAT_DIM";"FOREGROUND_COL_YELLOW), stdout);
fputs("Text in gold\n", stdout);
fputs(SHELL_FORMAT_RESET, stdout);
fputs("Text in default color\n", stdout);
//The short way
fputs(SHELL_COLOR_ESCAPE_SEQ(GEN_FORMAT_DIM";"FOREGROUND_COL_YELLOW)"Text in gold\n"SHELL_FORMAT_RESET"Text in default color\n", stdout);
return 0;
}
The .NET garbage collector takes care of all this for you.
It is able to determine when objects are no longer referenced and will (eventually) free the memory that had been allocated to them.
JE
and JZ
are just different names for exactly the same thing: a
conditional jump when ZF
(the "zero" flag) is equal to 1.
(Similarly, JNE
and JNZ
are just different names for a conditional jump
when ZF
is equal to 0.)
You could use them interchangeably, but you should use them depending on what you are doing:
JZ
/JNZ
are more appropriate when you are explicitly testing
for something being equal to zero:
dec ecx
jz counter_is_now_zero
JE
and JNE
are more appropriate after a CMP
instruction:
cmp edx, 42
je the_answer_is_42
(A CMP
instruction performs a subtraction, and throws the value of the result away, while keeping the flags; which is why you get ZF=1
when the operands are equal
and ZF=0
when they're not.)
This May be helpful:
//I personally prefer dynamic import (angular 8)
{ path: 'pages', loadChildren: () => import('./pages/pages.module').then(mod => mod.PageModule) }
In child routing it should look like: { path: 'about', component: AboutComponent },
Note that there is no pages
in path of child routing and in routerLink
or nsRouterLink
it should look like routerLink="/pages/about"
I hope thi help someone out there.
Verification, do not forget the to_s
def nottolonng?(value)
if value.to_s.length <=8
return true
else
return false
end
end
As of today, the UI of developer tools in Google chrome has changed where we select the log level of log statements being shown in the console. There is a logging level drop down beside "Filter" text box. Supported values are Verbose
, Info
, Warnings
and Errors
with Info
being the default selection.
Any log whose severity is equal or higher will get shown in the "Console" tab e.g. if selected log level is Info
then all the logs having level Info
, Warning
and Error
will get displayed in console.
When I changed it to Verbose
then my console.debug
and console.log
statements started showing up in the console. Till the time Info
level was selected they were not getting shown.
Type casting to integer may create problem but even long type can not hold every bit of double after narrowing down to decimal places. If you know your values will never exceed Long.MAX_VALUE value, this might be a clean solution.
So use the following with the above known risk.
double mValue = 1234567890.123456;
long mStrippedValue = new Double(mValue).longValue();
I think that Andrei Coscodan answer is the best when you can't make many assumptions. But sometimes having a one-liner is nice if you can make some some assumptions. This solution assumes that 'date \t' will return one of two formats. On WindowsXP 'date /t 'returns "11/23/2011", but on Windows7 it returns "Wed 11/23/2011".
FOR /f "tokens=1-4 delims=/ " %%a in ('date /t') do (set mm=%%a&set dd=%%b&set yyyy=%%c& (if "%%a:~0,1" gtr "9" set mm=%%b&setdd=%%c&set yyyy=%%d))
:: Test results
echo day in 'DD' format is '%dd%'; month in 'MM' format is '%mm%'; year in 'YYYY' format is '%yyyy%'
Thanks to Andrei Consodan answer to help me with this one-line solution.
The rules are as follows:
And try:
Lifepaths.class.getResourceAsStream("/initialization/Lifepaths.txt")
instead of
Lifepaths.class.getClass().getResourceAsStream("/initialization/Lifepaths.txt")
(not sure if it makes a difference, but the former will use the correct ClassLoader/ JAR, while I'm not sure with the latter)
I arranged a little. This works great.
@SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MM yyyy");
Date date = new Date();
String dateOfDay = simpleDateFormat.format(date);
String timeofday = android.text.format.DateFormat.format("HH:mm:ss", new Date().getTime()).toString();
@SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM yyyy hh:mm:ss");
try {
Date date1 = dateFormat.parse(06 09 2018 + " " + 10:12:56);
Date date2 = dateFormat.parse(dateOfDay + " " + timeofday);
printDifference(date1, date2);
} catch (ParseException e) {
e.printStackTrace();
}
@SuppressLint("SetTextI18n")
private void printDifference(Date startDate, Date endDate) {
//milliseconds
long different = endDate.getTime() - startDate.getTime();
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
Toast.makeText(context, elapsedDays + " " + elapsedHours + " " + elapsedMinutes + " " + elapsedSeconds, Toast.LENGTH_SHORT).show();
}
The code date.to_time.to_i
should work fine. The Rails console session below shows an example:
>> Date.new(2009,11,26).to_time
=> Thu Nov 26 00:00:00 -0800 2009
>> Date.new(2009,11,26).to_time.to_i
=> 1259222400
>> Time.at(1259222400)
=> Thu Nov 26 00:00:00 -0800 2009
Note that the intermediate DateTime object is in local time, so the timestamp might be a several hours off from what you expect. If you want to work in UTC time, you can use the DateTime's method "to_utc".
var tests = new[] {"000000001000", "000000001005", "000000331150"};
foreach (var test in tests)
{
Console.WriteLine("{0} <=> {1:f2}", test, Convert.ToDecimal(test) / 100);
}
Since you didn't ask for the currency symbol, I've used "f2" instead of "C"
I don't think you can delete from multiple tables at once (though I'm not certain).
It sounds to me, however, that you would be best to achieve this effect with a relationship that cascades deletes. If you did this you would be able to delete the record from one table and the records in the other would be automatically deleted.
As an example, say the two tables represent a customer, and the customer's orders. If you setup the relationship to cascade deletes, you could simply delete record in the customer table, and the orders would get deleted automatically.
See the MSDN doc on cascading referential integrity constraints.
I use the Intellij Community Edition. Go to the "Run/Debug Configurations" > Runner tab > Environment variables > click button "...". Add: SPRING_PROFILES_ACTIVE = local
The method join()
blocks the calling thread until the thread whose join() method is called is terminated.
By using Ado.net
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace PBDataAccess
{
public class AddContact
{
// for preparing connection to sql server database
private SqlConnection conn;
// for preparing sql statement or stored procedure that
// we want to execute on database server
private SqlCommand cmd;
// used for storing the result in datatable, basically
// dataset is collection of datatable
private DataSet ds;
// datatable just for storing single table
private DataTable dt;
// data adapter we use it to manage the flow of data
// from sql server to dataset and after fill the data
// inside dataset using fill() method
private SqlDataAdapter da;
// created a method, which will return the dataset
public DataSet GetAllContactType()
{
// retrieving the connection string from web.config, which will
// tell where our database is located and on which database we want
// to perform opearation, in this case we are working on stored
// procedure so you might have created it somewhere in your database.
// connection string will include the name of the datasource, your
// database name, user name and password.
using (conn = new SqlConnection(ConfigurationManager.ConnectionString["conn"]
.ConnectionString))
{
// Addcontact is the name of the stored procedure
using (cmd = new SqlCommand("Addcontact", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// here we are passing the parameters that
// Addcontact stored procedure expect.
cmd.Parameters.Add("@CommandType",
SqlDbType.VarChar, 50).Value = "GetAllContactType";
// here created the instance of SqlDataAdapter
// class and passed cmd object in it
da = new SqlDataAdapter(cmd);
// created the dataset object
ds = new DataSet();
// fill the dataset and your result will be
stored in dataset
da.Fill(ds);
}
}
return ds;
}
}
****** Stored Procedure ******
CREATE PROCEDURE Addcontact
@CommandType VARCHAR(MAX) = NULL
AS
BEGIN
IF (@CommandType = 'GetAllContactType')
BEGIN
SELECT * FROM Contacts
END
END
I had this same issue when trying to handle popping alerts and fading them. I searched around various places and found this to be my solution. Adding and removing the 'in' class fixed my issue.
window.setTimeout(function() { // hide alert message
$("#alert_message").removeClass('in');
}, 5000);
When using .remove() and similarly the .alert('close') solution I seemed to hit an issue with the alert being removed from the document, so if I wanted to use the same alert div again I was unable to. This solution means the alert is reusable without refreshing the page. (I was using aJax to submit a form and present feedback to the user)
$('#Some_Button_Or_Event_Here').click(function () { // Show alert message
$('#alert_message').addClass('in');
});
Using empty
is enough:
if(!empty($variable)){
// Do stuff
}
Additionally, if you want an integer value it might also be worth checking that intval($variable) !== FALSE
.
Same thing happened with me, when i have enabled 2-way authentication for github. Things i did to resolve:
Doing this will solve your issue.
Tangential: String.format() rocks:
public String toString() {
return String.format("%s %s", getMake(), getReg());
}
private static void printAll() {
for (Car car: cars)
System.out.println(car); // invokes Car.toString()
}
A good solution that can work is go to files > and check the reallocate all files
Create a folder where you want to keep the code, and right click on it. Choose SVN Checkout... and type http://wittytwitter.googlecode.com/svn/trunk into the URL of repository field.
You can also run
svn checkout http://wittytwitter.googlecode.com/svn/trunk
from the command line in the folder you want to keep it (svn.exe has to be in your path, of course).
to add to John's answer:
what you want to pass to the shuffle
function is a deck of cards from the class deckOfCards
that you've declared in main; however, the deck of cards or vector<Card> deck
that you've declared in your class is private, so not accessible from outside the class. this means you'd want a getter function, something like this:
class deckOfCards
{
private:
vector<Card> deck;
public:
deckOfCards();
static int count;
static int next;
void shuffle(vector<Card>& deck);
Card dealCard();
bool moreCards();
vector<Card>& getDeck() { //GETTER
return deck;
}
};
this will in turn allow you to call your shuffle function from main like this:
deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck.getDeck()); // shuffle the cards in the deck
however, you have more problems, specifically when calling cout
. first, you're calling the dealCard
function wrongly; as dealCard
is a memeber function of a class, you should be calling it like this cardDeck.dealCard();
instead of this dealCard(cardDeck);
.
now, we come to your second problem - print to standard output. you're trying to print your deal card, which is an object of type Card
by using the following instruction:
cout << cardDeck.dealCard();// deal the cards in the deck
yet, the cout
doesn't know how to print it, as it's not a standard type. this means you should overload your <<
operator to print whatever you want it to print when calling with a Card
type.
From SQL Server 2012 you can use the IIF
function for this.
SELECT IIF(Obsolete = 'N' OR InStock = 'Y', 1, 0) AS Salable, *
FROM Product
This is effectively just a shorthand (albeit not standard SQL) way of writing CASE
.
I prefer the conciseness when compared with the expanded CASE
version.
Both IIF()
and CASE
resolve as expressions within a SQL statement and can only be used in well-defined places.
The CASE expression cannot be used to control the flow of execution of Transact-SQL statements, statement blocks, user-defined functions, and stored procedures.
If your needs can not be satisfied by these limitations (for example, a need to return differently shaped result sets dependent on some condition) then SQL Server does also have a procedural IF
keyword.
IF @IncludeExtendedInformation = 1
BEGIN
SELECT A,B,C,X,Y,Z
FROM T
END
ELSE
BEGIN
SELECT A,B,C
FROM T
END
Care must sometimes be taken to avoid parameter sniffing issues with this approach however.
Make sure that when you are running your python code that it is in the python3 context. I had the same issue and all I had to do was input the command as:
sudo python3 REPLACE.py
versus
sudo python REPLACE.py
the latter code is incorrect because tkinter is apparently unnavailable in python1 or python2.
According to my understanding to your question, as an example: you had a style at the beginning in style sheet (ex. background-color: red), then using java script you changed it to another style (ex. background-color: green), now you want to reset the style to its original value in style sheet (background-color: red) without mentioning or even knowing its value (ex. element.style.backgroundColor = 'red')...!
If I'm correct, I have a good solution for you which is using another class name for the element:
steps:
if you want to edit or set a new style, get the element by the new class name and edit the style as desired.
I hope this helps. Regards!
Yes, use gzip for this. The best way is to read data as input and redirect the compressed to output file i.e.
cat test.csv | gzip > test.csv.gz
cat test.csv
will send the data as stdout and using pipe-sign gzip will read that data as stdin. Make sure to redirect the gzip output to some file as compressed data will not be written to the terminal.
let weekday = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][new Date().getDay()]
This thread helped me a lot with my problem, but I've used $.queue in a different way and thought I would post what I came up with here. What I needed was a sequence of events (frames) to be triggered, but the sequence to be built dynamically. I have a variable number of placeholders, each of which should contain an animated sequence of images. The data is held in an array of arrays, so I loop through the arrays to build each sequence for each of the placeholders like this:
/* create an empty queue */
var theQueue = $({});
/* loop through the data array */
for (var i = 0; i < ph.length; i++) {
for (var l = 0; l < ph[i].length; l++) {
/* create a function which swaps an image, and calls the next function in the queue */
theQueue.queue("anim", new Function("cb", "$('ph_"+i+"' img').attr('src', '/images/"+i+"/"+l+".png');cb();"));
/* set the animation speed */
theQueue.delay(200,'anim');
}
}
/* start the animation */
theQueue.dequeue('anim');
This is a simplified version of the script I have arrived at, but should show the principle - when a function is added to the queue, it is added using the Function constructor - this way the function can be written dynamically using variables from the loop(s). Note the way the function is passed the argument for the next() call, and this is invoked at the end. The function in this case has no time dependency (it doesn't use $.fadeIn or anything like that), so I stagger the frames using $.delay.
Until I get a better option, this is the most "bootstrappy" answer I can work out:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/6cbrjrt5/
I have switched to using LESS and including the Bootstrap Source NuGet package to ensure compatibility (by giving me access to the bootstrap variables.less
file:
in _layout.cshtml master page
body-content
containernavbar-fixed-bottom
on the footer<hr/>
before the footer (as now redundant)Relevant page HTML:
<div class="container-fluid body-content">
@RenderBody()
</div>
<footer class="navbar-fixed-bottom">
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
In Site.less
HTML
and BODY
heights to 100%BODY
overflow
to hidden
body-content
div position
to absolute
body-content
div top
to @navbar-height
instead of hard-wiring valuebody-content
div bottom
to 30px
.body-content
div left
and right
to 0body-content
div overflow-y
to auto
Site.less
html {
height: 100%;
body {
height: 100%;
overflow: hidden;
.container-fluid.body-content {
position: absolute;
top: @navbar-height;
bottom: 30px;
right: 0;
left: 0;
overflow-y: auto;
}
}
}
The remaining problem is there seems to be no defining variable for the footer height
in bootstrap. If someone call tell me if there is a magic 30px variable defined in Bootstrap I would appreciate it.
In TF1, the statement x.assign(1)
does not actually assign the value 1
to x
, but rather creates a tf.Operation
that you have to explicitly run to update the variable.* A call to Operation.run()
or Session.run()
can be used to run the operation:
assign_op = x.assign(1)
sess.run(assign_op) # or `assign_op.op.run()`
print(x.eval())
# ==> 1
(* In fact, it returns a tf.Tensor
, corresponding to the updated value of the variable, to make it easier to chain assignments.)
However, in TF2 x.assign(1)
will now assign the value eagerly:
x.assign(1)
print(x.numpy())
# ==> 1
Linq to Dropdown with empty item, selected item (works 100%)
(Strongly Typed,Chances for error minimum) Any model changes will be reflected in the binding
Controller
public ActionResult ManageSurveyGroup()
{
tbl_Survey sur = new tbl_Survey();
sur.Survey_Est = "3";
return View(sur);
}
View
@{
//Step One : Getting all the list
var CompEstdList = (from ComType in db.tbl_CompEstdt orderby ComType.Comp_EstdYr select ComType).ToList();
//Step Two : Adding a no Value item **
CompEstdList.Insert(0, new eDurar.Models.tbl_CompEstdt { Comp_Estdid = 0, Comp_EstdYr = "--Select Company Type--" });
//Step Three : Setting selected Value if value is present
var selListEstd= CompEstdList.Select(s => new SelectListItem { Text = s.Comp_EstdYr, Value = s.Comp_Estdid.ToString() });
}
@Html.DropDownListFor(model => model.Survey_Est, selListEstd)
@Html.ValidationMessageFor(model => model.Survey_Est)
This method for binding data also possible
var selList = CompTypeList.Select(s => new SelectListItem { Text = s.CompTyp_Name, Value = s.CompTyp_Id.ToString(), Selected = s.CompTyp_Id == 3 ? true : false });
Partitioning data is often used for distributing load horizontally, this has performance benefit, and helps in organizing data in a logical fashion. Example: if we are dealing with a large employee
table and often run queries with WHERE
clauses that restrict the results to a particular country or department . For a faster query response Hive table can be PARTITIONED BY (country STRING, DEPT STRING)
. Partitioning tables changes how Hive structures the data storage and Hive will now create subdirectories reflecting the partitioning structure like
.../employees/country=ABC/DEPT=XYZ.
If query limits for employee from country=ABC
, it will only scan the contents of one directory country=ABC
. This can dramatically improve query performance, but only if the partitioning scheme reflects common filtering. Partitioning feature is very useful in Hive, however, a design that creates too many partitions may optimize some queries, but be detrimental for other important queries. Other drawback is having too many partitions is the large number of Hadoop files and directories that are created unnecessarily and overhead to NameNode since it must keep all metadata for the file system in memory.
Bucketing is another technique for decomposing data sets into more manageable parts. For example, suppose a table using date
as the top-level partition and employee_id
as the second-level partition leads to too many small partitions. Instead, if we bucket the employee table and use employee_id
as the bucketing column, the value of this column will be hashed by a user-defined number into buckets. Records with the same employee_id
will always be stored in the same bucket. Assuming the number of employee_id
is much greater than the number of buckets, each bucket will have many employee_id
. While creating table you can specify like CLUSTERED BY (employee_id) INTO XX BUCKETS;
where XX is the number of buckets . Bucketing has several advantages. The number of buckets is fixed so it does not fluctuate with data. If two tables are bucketed by employee_id
, Hive can create a logically correct sampling. Bucketing also aids in doing efficient map-side joins etc.
create simple method to do that for you:
public void addMulti(String[] strings,List list){
for (int i = 0; i < strings.length; i++) {
list.add(strings[i]);
}
}
Then you can create
String[] wrong ={"1","2","3","4","5","6"};
and add it with this method to your list.
The standard streams have a boolalpha
flag that determines what gets displayed -- when it's false, they'll display as 0
and 1
. When it's true, they'll display as false
and true
.
There's also an std::boolalpha
manipulator to set the flag, so this:
#include <iostream>
#include <iomanip>
int main() {
std::cout<<false<<"\n";
std::cout << std::boolalpha;
std::cout<<false<<"\n";
return 0;
}
...produces output like:
0
false
For what it's worth, the actual word produced when boolalpha
is set to true is localized--that is, <locale>
has a num_put
category that handles numeric conversions, so if you imbue a stream with the right locale, it can/will print out true
and false
as they're represented in that locale. For example,
#include <iostream>
#include <iomanip>
#include <locale>
int main() {
std::cout.imbue(std::locale("fr"));
std::cout << false << "\n";
std::cout << std::boolalpha;
std::cout << false << "\n";
return 0;
}
...and at least in theory (assuming your compiler/standard library accept "fr" as an identifier for "French") it might print out faux
instead of false
. I should add, however, that real support for this is uneven at best--even the Dinkumware/Microsoft library (usually quite good in this respect) prints false
for every language I've checked.
The names that get used are defined in a numpunct
facet though, so if you really want them to print out correctly for particular language, you can create a numpunct
facet to do that. For example, one that (I believe) is at least reasonably accurate for French would look like this:
#include <array>
#include <string>
#include <locale>
#include <ios>
#include <iostream>
class my_fr : public std::numpunct< char > {
protected:
char do_decimal_point() const { return ','; }
char do_thousands_sep() const { return '.'; }
std::string do_grouping() const { return "\3"; }
std::string do_truename() const { return "vrai"; }
std::string do_falsename() const { return "faux"; }
};
int main() {
std::cout.imbue(std::locale(std::locale(), new my_fr));
std::cout << false << "\n";
std::cout << std::boolalpha;
std::cout << false << "\n";
return 0;
}
And the result is (as you'd probably expect):
0
faux
what error do you get is it a SmtpFailedrecipientException? if so you can check the innerexceptions list and view the StatusCode to get more information. the link below has some good information
Edit for the new information
Thisis a problem with finding your SMTP server from what I can see, though you say that it only happens on some emails. Are you using more than one smtp server and if so maybe you can tract the issue down to one in particular, if not it may be that the speed/amount of emails you are sending is causing your smtp server some issue.
If you would like to use linq, so you can try following:
Dictionary<string, object> dict = new Dictionary<string, object>();
var arr = dict.Select(z => z.Value).ToArray();
I don't know which one is faster or better. Both work for me.
Not very "elegant" and kinda a waste, but if you really care what the code looks like you could make your own fancy flag and then do a str_replace.
Example:<br />
$myoutput = "After this sentence there is a line break.<b>.|..</b> Here is a new line.";<br />
$myoutput = str_replace(".|..","<br />",$myoutput);<br />
or
how about:<br />
$myoutput = "After this sentence there is a line break.<b>E(*)3</b> Here is a new line.";<br />
$myoutput = str_replace("E(*)3","<br />",$myoutput);<br />
I call the first method "middle finger style" and the second "goatse style".
If you want the sum of all non-blank lines for all files of a given file extension throughout a project:
while read line
do grep -cve '^\s*$' "$line"
done < <(find $1 -name "*.$2" -print) | awk '{s+=$1} END {print s}'
First arg is the project's base directory, second is the file extension. Sample usage:
./scriptname ~/Dropbox/project/src java
It's little more than a collection of previous solutions.
npm install
,if the issue is not yet fixed try the following one after the other.npm cache clean
,thennpm install -g npm
,then
npm install
,Finallyng serve --o
to run the project.
Hope this will help....Try make 2> file
. Compiler warnings come out on the standard error stream, not the standard output stream. If my suggestion doesn't work, check your shell manual for how to divert standard error.
The best method I know of is to use a Perceptual Hash. There appears to be a good open source implementation of such a hash available at:
The main idea is that each image is reduced down to a small hash code or 'fingerprint' by identifying salient features in the original image file and hashing a compact representation of those features (rather than hashing the image data directly). This means that the false positives rate is much reduced over a simplistic approach such as reducing images down to a tiny thumbprint sized image and comparing thumbprints.
phash offers several types of hash and can be used for images, audio or video.
You'll have to actually USE jQuery to build the div, if you want to write maintainable or usable code.
//create a div
var $newDiv = $('<div>');
//set the id
$newDiv.attr("id","myId");
For reference purpose, for anyone searching how to change the path via code, I am quoting a useful post by a Delphi programmer from this web page: http://www.tek-tips.com/viewthread.cfm?qid=686382
TonHu (Programmer) 22 Oct 03 17:57 I found where I read the original posting, it's here: http://news.jrsoftware.org/news/innosetup.isx/msg02129....
The excerpt of what you would need is this:
You must specify the string "Environment" in LParam. In Delphi you'd do it this way:
SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, 0, Integer(PChar('Environment')));
It was suggested by Jordan Russell, http://www.jrsoftware.org, the author of (a.o.) InnoSetup, ("Inno Setup is a free installer for Windows programs. First introduced in 1997, Inno Setup today rivals and even surpasses many commercial installers in feature set and stability.") (I just would like more people to use InnoSetup )
HTH
Update: This supports only with UWP - Windows Community Toolkit
There is a much easier way now. You can use the RssParser class. The sample code is given below.
public async void ParseRSS()
{
string feed = null;
using (var client = new HttpClient())
{
try
{
feed = await client.GetStringAsync("https://visualstudiomagazine.com/rss-feeds/news.aspx");
}
catch { }
}
if (feed != null)
{
var parser = new RssParser();
var rss = parser.Parse(feed);
foreach (var element in rss)
{
Console.WriteLine($"Title: {element.Title}");
Console.WriteLine($"Summary: {element.Summary}");
}
}
}
For non-UWP use the Syndication from the namespace System.ServiceModel.Syndication
as others suggested.
public static IEnumerable <FeedItem> GetLatestFivePosts() {
var reader = XmlReader.Create("https://sibeeshpassion.com/feed/");
var feed = SyndicationFeed.Load(reader);
reader.Close();
return (from itm in feed.Items select new FeedItem {
Title = itm.Title.Text, Link = itm.Id
}).ToList().Take(5);
}
public class FeedItem {
public string Title {
get;
set;
}
public string Link {
get;
set;
}
}
For anyone interested in a shorter way:
gotdata = len(dlist)>1 and dlist[1] or 'null'
But for best performance, I suggest using False
instead of 'null'
, then a one line test will suffice:
gotdata = len(dlist)>1 and dlist[1]
http://www.rgraph.net/ is excellent for graph and charts.
Using !important will override element.style via CSS like Change
color: #7D7D7D;
to
color: #7D7D7D !important;
That should do it.
Have a look at the sizemode property of the picturebox.
pictureBox1.SizeMode =PictureBoxSizeMode.StretchImage;
Try this:
$objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
Using JNA, supporting old and new JVM to get process id
public static long getProcessId(Process p){
long pid = -1;
try {
pid = p.pid();
} catch (NoSuchMethodError e) {
try
{
//for windows
if (p.getClass().getName().equals("java.lang.Win32Process") || p.getClass().getName().equals("java.lang.ProcessImpl")) {
Field f = p.getClass().getDeclaredField("handle");
f.setAccessible(true);
long handl = f.getLong(p);
Kernel32 kernel = Kernel32.INSTANCE;
WinNT.HANDLE hand = new WinNT.HANDLE();
hand.setPointer(Pointer.createConstant(handl));
pid = kernel.GetProcessId(hand);
f.setAccessible(false);
}
//for unix based operating systems
else if (p.getClass().getName().equals("java.lang.UNIXProcess"))
{
Field f = p.getClass().getDeclaredField("pid");
f.setAccessible(true);
pid = f.getLong(p);
f.setAccessible(false);
}
}
catch(Exception ex)
{
pid = -1;
}
}
return pid;
}
There is ES 6 crossbrowser + mobile vanila js decision:
function stopParentScroll(selector) {
let last_touch;
let MouseWheelHandler = (e, selector) => {
let delta;
if(e.deltaY)
delta = e.deltaY;
else if(e.wheelDelta)
delta = e.wheelDelta;
else if(e.changedTouches){
if(!last_touch){
last_touch = e.changedTouches[0].clientY;
}
else{
if(e.changedTouches[0].clientY > last_touch){
delta = -1;
}
else{
delta = 1;
}
}
}
let prevent = function() {
e.stopPropagation();
e.preventDefault();
e.returnValue = false;
return false;
};
if(selector.scrollTop === 0 && delta < 0){
return prevent();
}
else if(selector.scrollTop === (selector.scrollHeight - selector.clientHeight) && delta > 0){
return prevent();
}
};
selector.onwheel = e => {MouseWheelHandler(e, selector)};
selector.onmousewheel = e => {MouseWheelHandler(e, selector)};
selector.ontouchmove = e => {MouseWheelHandler(e, selector)};
}
What we did is, before initialization of new chart, remove/destroy the previews Chart instance, if exist already, then create a new chart, for example
if(myGraf != undefined)
myGraf.destroy();
myGraf= new Chart(document.getElementById("CanvasID"),
{
...
}
Hope this helps.
The best way to achieve this nowadays is to use display: flex;
. However you might run into an issue when trying to support IE11. According to https://caniuse.com using flexbox :
IE 11 does not vertically align items correctly when min-height is used
The solution is to use display: table;
on the parent and display: table-row;
on the child both with height: 100%;
as a replacement for min-height: 100%;
.
Most of the solutions listed here use display:
table
, table-row
and/or table-cell
, but they don't replicate the same behaviour as min-height: 100%;
, which is:
height
property);min-height
;While using this solution, the behaviour is the same and the property min-height
is not needed which allows to get around the bug.
The reason why it works is because, unlike most elements, elements using display:
table
and table-row
will always be as tall as their content. This makes their height
property behave similarly to min-height
.
html, body {_x000D_
height: 100px;_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
#containment {_x000D_
display: table;_x000D_
height: 100%;_x000D_
background: pink;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
#containment-shadow-left {_x000D_
display: table-row;_x000D_
height: 100%;_x000D_
background: aqua;_x000D_
}_x000D_
_x000D_
#content {_x000D_
padding: 15px;_x000D_
}_x000D_
_x000D_
#demo {_x000D_
display: none;_x000D_
background-color: red;_x000D_
height: 200px;_x000D_
}_x000D_
_x000D_
#demo-checkbox:checked ~ #demo {_x000D_
display: block;_x000D_
}
_x000D_
<div id="containment">_x000D_
<div id="containment-shadow-left">_x000D_
<div id="content">_x000D_
<input id="demo-checkbox" type="checkbox">_x000D_
<label for="demo-checkbox">Click here for overflow demo</label>_x000D_
<div id="demo">This is taller than #containment</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Sorry, not enough rep to add a comment, but from zmbq's answer:
Anyway, to see if a cookie exists, you can check Cookies.Get(string), this will not modify the cookie collection.
is maybe not fully correct, as Cookies.Get(string) will actually create a cookie with that name, if it does not already exist. However, as he said, you need to be looking at Request.Cookies, not Response.Cookies So, something like:
bool cookieExists = HttpContext.Current.Request.Cookies["cookie_name"] != null;
IMPORTANT NOTE
I am posting this as an answer, not a comment, as it is rather important info and it will attract more attention in this format.
As other fellows pointed, you can force a device to show you a numeric keyboard with type="number"
/ type="tel"
, but I must emphasize that you have to be extremely cautious with this.
If someone expects a number beginning with zeros, such as 000222
, then she is likely to have trouble, as some browsers (desktop Chrome, for instance) will send to the server 222
, which is not what she wants.
About type="tel"
I can't say anything similar but personally I do not use it, as its behavior on different telephones can vary. I have confined myself to the simple pattern="[0-9]*"
which do not work in Android
Data are store in this path. You can search data location, just put the below address in your search location (url address):
C:\xampp\mysql\data
while(i<10){
$('#Postsoutput').prepend('<div id="first'+i+'">'+i+'</div>');
/* get the dynamic Div*/
$('#first'+i).hide(1000);
$('#first'+i).show(1000);
i++;
}
Add a jQuery function,
(function($){
$.fn.regex = function(pattern, fn, fn_a){
var fn = fn || $.fn.text;
return this.filter(function() {
return pattern.test(fn.apply($(this), fn_a));
});
};
})(jQuery);
Then,
$('span').regex(/Sent/)
will select all span elements with text matches /Sent/.
$('span').regex(/tooltip.year/, $.fn.attr, ['class'])
will select all span elements with their classes match /tooltip.year/.
Other type of format :
$headers[] = 'Accept: application/json';
$headers[] = 'Content-Type: application/json';
$headers[] = 'Content-length: 0';
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);
Use a loop
for(var i = 0; i < obj.length; ++i){
//do something with obj[i]
for(var ind in obj[i]) {
console.log(ind);
for(var vals in obj[i][ind]){
console.log(vals, obj[i][ind][vals]);
}
}
}
Example from the guide:
\newcommand{\example}[2][YYY]{Mandatory arg: #2;
Optional arg: #1.}
This defines \example to be a command with two arguments,
referred to as #1 and #2 in the {<definition>}--nothing new so far.
But by adding a second optional argument to this \newcommand
(the [YYY]) the first argument (#1) of the newly defined
command \example is made optional with its default value being YYY.
Thus the usage of \example is either:
\example{BBB}
which prints:
Mandatory arg: BBB; Optional arg: YYY.
or:
\example[XXX]{AAA}
which prints:
Mandatory arg: AAA; Optional arg: XXX.
I believe that this question deserves an updated. Just compare with other approaches.
Here's how you do redirection (3xx) from one url to another in Flask (0.12.2):
#!/usr/bin/env python
from flask import Flask, redirect
app = Flask(__name__)
@app.route("/")
def index():
return redirect('/you_were_redirected')
@app.route("/you_were_redirected")
def redirected():
return "You were redirected. Congrats :)!"
if __name__ == "__main__":
app.run(host="0.0.0.0",port=8000,debug=True)
For other official references, here.
"Could you suggest a simpler code main thing is uploading the file Data base entry is secondary"
^--- As per OP's request. ---^
<!DOCTYPE html>
<head>
<title></title>
</head>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file"><span>Filename:</span></label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Change upload folder to preferred name. Presently saves to upload/
<?php
$allowedExts = array("jpg", "jpeg", "gif", "png", "mp3", "mp4", "wma");
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if ((($_FILES["file"]["type"] == "video/mp4")
|| ($_FILES["file"]["type"] == "audio/mp3")
|| ($_FILES["file"]["type"] == "audio/wma")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
The @Nadun's version did not work for me, sizing wasn't working well. Removed the direction="column"
or changing it to row
, helps with building vertical login forms with responsive sizing.
<Grid
container
spacing={0}
alignItems="center"
justify="center"
style={{ minHeight: "100vh" }}
>
<Grid item xs={6}></Grid>
</Grid>;
As a more general pattern to follow, I tend to use an @After
block in the test:
@After
public void after() {
verifyNoMoreInteractions(<your mock1>, <your mock2>...);
}
Then the test is free to verify only what should be called.
Also, I found that I often forgot to check for "no interactions", only to later discover that things were being called that shouldn't have been.
So I find this pattern useful for catching all unexpected calls that haven't specifically been verified.
copy con
to write text, It so easy to write a long textExample:
C:\COPY CON [drive:][path][File name]
.... Content
F6
1 file(s) is copied
You can connect two iPhones and transfer data via Bluetooth using either the high-level GameKit framework or the lower-level (but still easy to work with) Bonjour discovery mechanisms. Bonjour also works transparently between Bluetooth and WiFi on the iPhone under 3.0, so it's a good choice if you would like to support iPhone-to-iPhone data transfers on those two types of networks.
For more information, you can also look at the responses to these questions:
I'm suggest that you learn about Jquery, most popular JS library. With jquery it's simple to acomplish what you want.Simle example below:
$(“#DIV_YOU_WANT_CHANGE”).click(function() {
$(this).addClass(“.your_class_with_new_color”);
});
what may be happening is your company decrypts certain traffic and re-encrypts it with their certificate (which you probably already have in your keychain or trusted root certificates)
if you're using node 7 or later I've found this fix to be compatible with node and node-gyp (for Windows you'll need to do this differently, but you basically just need to add this environment variable):
export NODE_EXTRA_CA_CERTS="absolute_path_to_your_certificates.pem"
(in Windows you may need to remove the quotes - see comments)
the pem file can have multiple certificates: https://nodejs.org/api/cli.html#cli_node_extra_ca_certs_file
make sure your certificates are in proper pem format (you need real line breaks not literal \n
)
I couldn't seem to get it to work with relative paths (.
or ~
)
This fix basically tells npm and node-gyp to use the check against the regular CAs, but also allow this certificate when it comes across it
Ideally you would be able to use your system's trusted certificates, but unfortunately this is not the case.
Shared hosting no ssh or shell access?
Here is how i did it;
Just update your eclipse.ini file (you can find it in the root-directory of eclipse) by this:
-vm
path/javaw.exe
for example:
-vm
C:/Program Files/Java/jdk1.7.0_09/jre/bin/javaw.exe
For a div-Element you could just set the opacity via a class to enable or disable the effect.
.mute-all {
opacity: 0.4;
}
You can use reduce()
to sum a list of integers.
int sum = integers.values().stream().reduce(0, Integer::sum);
See String Formatting Operations:
%d
is the format code for an integer. %f
is the format code for a float.
%s
prints the str()
of an object (What you see when you print(object)
).
%r
prints the repr()
of an object (What you see when you print(repr(object))
.
For a float %s, %r and %f all display the same value, but that isn't the case for all objects. The other fields of a format specifier work differently as well:
>>> print('%10.2s' % 1.123) # print as string, truncate to 2 characters in a 10-place field.
1.
>>> print('%10.2f' % 1.123) # print as float, round to 2 decimal places in a 10-place field.
1.12
function showViewPortSize(display) {
if (display) {
var height = window.innerHeight;
var width = window.innerWidth;
jQuery('body')
.prepend('<div id="viewportsize" style="z-index:9999;position:fixed;bottom:0px;left:0px;color:#fff;background:#000;padding:10px">Height: ' + height + '<br>Width: ' + width + '</div>');
jQuery(window)
.resize(function() {
height = window.innerHeight;
width = window.innerWidth;
jQuery('#viewportsize')
.html('Height: ' + height + '<br>Width: ' + width);
});
}
}
$(document)
.ready(function() {
showViewPortSize(true);
});
I'm not suggested this as the best answer, just an alternative but you can also do something like:
flag = reader[0] == "True"
flag will be True
id reader[0] is "True", otherwise it will be False
.