Had the same problem. Solved as given below. Use command :
sudo tail -f /var/log/messages|grep -i mysql
to check if SELinux policy is causing the issue. If so, first check if SELinux policy is enabled using command #sestatus
. If it shows enabled, then disable it.
To disable:
# vi /etc/sysconfig/selinux
sestatus
and it should show "disabled"Uninstall and reinstall mysql. It should be working.
At rigth side in Navigator -> Instance-> Click on Startup/Shutdown -> Click on Start Server
It will work surely
From your question, it seems you are running homestead. In that case, make sure you're running the commands in your VM. Many devs including me often make mistake and run artisan commands outside of VM which the commands will try to connect to our local database accessible through localhost which is different from the database used by homestead. Cd to your Homestead directory and run
vagrant ssh
then cd into code if that is where you keep your projects and cd into your project and run php artisan migrate again
I hope this will help other people.
This theme required awhile to find results and reasons:
using MaiaDB 5.4. via SuSE-LINUX tumblweed
some files in the appointed directory havn't been necessary in any direct relation with mariadb. I.e: I placed some hints, a text-file, some bakup-copys somewhere in the same appointed directory for mysql mariadb and this caused endless error-messages and blocking the server from starting. Mariadb appears to be very sensible and hostile with the presence of other files not beeing database files(comments,backups,experimantal files etc) .
using libreoffice as client then there already this generated much problems with the creation and working on a database and caused some crashes.The crashes eventually produced bad tables.
May be because of that or may be because of the presence of not yet deleted but unusable tables !! the mysql mariadb server crashed and didn't want to do it' job not even start.
Error message always same : "Table 'some.table' doesn't exist in engine"
But when it started then tables appeared as normal, but it was unpossible to work on them.
So what to do without a more precise Error Message ?? The unusable tables showed up with: "CHECK TABLE" or on the command line of the system with "mysqlcheck " So I deleted by filemanager or on the system-level as root or as allowed user all the questionable files and then problem was solved.
Proposal: the Error Message could be a bit more precisely for example: "corrupted tables" (which can be found by CHECK TABLE, but only if the server is running) or by mysqlcheck even whe server is not running - but here are other disturbing files like hints/bakups a.s.o not visible.
ANYWAY it helped a lot to have backup-copies of the original database-files on a backup volume. This helped to check out and test it again and again until solution was found.
Good luck all - Herbert
The yum install php-soap
command will install the Soap module for php 5.x
For installing the correct version for your environment I recommend to create a file info.php
and put this code: <?php echo phpinfo(); ?>
In the header you'll see the version you're using:
Now that you know the correct version you can run this command: yum search php-soap
This command will return the avaliable versions:
php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php54-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php55-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php56-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php70-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php71-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php72-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php73-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php74-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
rh-php70-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
rh-php71-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
rh-php72-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
Now you just need to choose the correct module to your php version.
For this example, you should run this command php72-php-soap.x86_64
I found the proper solution for this error! Either you don't have any database installed or your default database in this file config/database.php is set to some other database like this
'default' => 'sqlite',
'default' => env('DB_CONNECTION', 'sqlite'), //laravel 5.2
change the default to which one you have installed or install that database which is made to be default! I had installed mysql and php artisan migrate worked after i changed that line to this:
'default' => 'mysql',
'default' => env('DB_CONNECTION', 'mysql'), //laravel5.2
Run the following on the command line :
$ mysql.server start
I also have the similar problem, and later on I found it is because I changed my hostname (not localhost
).
Therefore I get it resolved by specifying the --host=127.0.0.1
mysql -p mydatabase --host=127.0.0.1
If you are using yum in AIM Linux Amazon EC2. For security, make a backup complete of directory /var/lib/mysql
sudo yum reinstall -y mysql55-server
sudo service mysqld start
This problem will occurred due to some unnecessary changes made in my.cnf file.
Try to diff /etc/mysql/my.cnf
with one of working mysql servers my.cnf file.
I just replaced /etc/mysql/my.cnf
file with new my.cnf file and this works for me.
I recommend to use bellow formula suggested on Apache:
MaxClients = (total RAM - RAM for OS - RAM for external programs) / (RAM per httpd process)
Find my script here which is running on Rhel 6.7. you can made change according to your OS.
#!/bin/bash
echo "HostName=`hostname`"
#Formula
#MaxClients . (RAM - size_all_other_processes)/(size_apache_process)
total_httpd_processes_size=`ps -ylC httpd --sort:rss | awk '{ sum += $9 } END { print sum }'`
#echo "total_httpd_processes_size=$total_httpd_processes_size"
total_http_processes_count=`ps -ylC httpd --sort:rss | wc -l`
echo "total_http_processes_count=$total_http_processes_count"
AVG_httpd_process_size=$(expr $total_httpd_processes_size / $total_http_processes_count)
echo "AVG_httpd_process_size=$AVG_httpd_process_size"
total_httpd_process_size_MB=$(expr $AVG_httpd_process_size / 1024)
echo "total_httpd_process_size_MB=$total_httpd_process_size_MB"
total_pttpd_used_size=$(expr $total_httpd_processes_size / 1024)
echo "total_pttpd_used_size=$total_pttpd_used_size"
total_RAM_size=`free -m |grep Mem |awk '{print $2}'`
echo "total_RAM_size=$total_RAM_size"
total_used_size=`free -m |grep Mem |awk '{print $3}'`
echo "total_used_size=$total_used_size"
size_all_other_processes=$(expr $total_used_size - $total_pttpd_used_size)
echo "size_all_other_processes=$size_all_other_processes"
remaining_memory=$(($total_RAM_size - $size_all_other_processes))
echo "remaining_memory=$remaining_memory"
MaxClients=$((($total_RAM_size - $size_all_other_processes) / $total_httpd_process_size_MB))
echo "MaxClients=$MaxClients"
exit
After doing setup of PHPMyAdmin, I was also facing the same problem,
sudo /usr/local/mysql/support-files/mysql.server start
This worked for me. However, if this doesnt work then make sure that mysqld is running and try connecting.
Im posting this as a potensial Answer!
What i did to solve this was the following:
sudo rm /usr/local/mysql
sudo rm -rf /usr/local/mysql*
sudo rm -rf /Library/StartupItems/MySQLCOM
sudo rm -rf /Library/PreferencePanes/MySQL*
vim /etc/hostconfig and removed the line MYSQLCOM=-YES-
rm -rf ~/Library/PreferencePanes/MySQL*
sudo rm -rf /Library/Receipts/mysql*
sudo rm -rf /Library/Receipts/MySQL*
sudo rm -rf /var/db/receipts/com.mysql.*
Library/Application Support/appsolute
folder (MAMP application support folder)Hopefully this helps :)
Running sudo chown _mysql /usr/local/var/mysql/*
helped me finally after trying multitude of options from all these SO answers. The issue with permissions probably arose from improper shutdown of the machine.
I manually started mysql in the system preferences pane by initialising the database and then starting it. This solved my problem.
This error is caused by PDO
not being available to PHP.
If you are getting the error on the command line, or not via the same interface your website uses for PHP, you are potentially invoking a different version of PHP, or utlising a different php.ini
configuration file when checking phpinfo()
.
Ensure PDO is loaded, and the PDO drivers for your database are also loaded.
I tried this tool and it gave me good results.
I face the same problem and changing
$cfg['Servers'][$i]['host'] = 'localhost';
to
$cfg['Servers'][$i]['host'] = '127.0.0.1';
Solved this issue.
If you are running MYSQL through XAMPP:
Open XAMPP mysql configuration file (on OSX):
/Applications/XAMPP/etc/my.cnf
Copy the socket path:
socket = /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock
Open rails project's database configuration file: myproject/config/database.yml
Add the socket config to the development database config:
-->
development:
adapter: mysql2
encoding: utf8
reconnect: false
database: difiuri_falcioni
pool: 5
username: root
password:
host: localhost
socket: /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock
Enjoy :)
I've just had this problem. after a day of checking finally I've got the answer with that The mysql.sock file is created when MariaDB starts and is removed when MariaDB is shutdown. It won't exist if MariaDB is not running. maybe you didn't install MariaDB. YOU COULD FOLLOW THE INSTRUCTION BELOW: https://www.linode.com/docs/databases/mariadb/how-to-install-mariadb-on-centos-7 BEST
In my case, I got this issue on vps, cPanel.
I was try most of the above answers, but not success.
ERROR! The server quit without updating PID file (/var/lib/mysql/111318.vps-11.com.pid).
[ERROR] Fatal error: Can't open and lock privilege tables: Table './mysql/db' is marked as crashed and should be repaired
[~]# myisamchk -r /var/lib/mysql/mysql/db.MYI
https://forums.cpanel.net/threads/mysql-is-not-running.407142/
This is a problem if you are running out of disk space. Solution is to free some space from the HDD.
Please read more to have the explanation :
If you are running MySQL at LINUX check the free space of HDD with the command disk free :
df
if you are getting something like that :
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/sda2 5162828 4902260 0 100% /
udev 156676 84 156592 1% /dev
/dev/sda3 3107124 70844 2878444 3% /home
Then this is the problem and now you have the solution!
Since mysql.sock wants to be created at the mysql folder which is almost always under the root folder could not achieve it because lack of space.
If you are periodicaly give the ls command under the mysql directory (at openSUSE 11.1 is at /var/lib/mysql) you will get something like :
hostname:/var/lib/mysql #
.protected IT files ibdata1 mysqld.log systemtemp
.tmp NEWS greekDB mysql mysqld.pid test
ARXEIO TEMP1 ib_logfile0 mysql.sock polis
DATING deisi ib_logfile1 mysql_upgrade_info restore
The mysql.sock file appearing and disappearing often (you must to try allot with the ls to hit a instance with the mysql.sock file on folder).
This caused by not enough disk space.
I hope that i will help some people!!!! Thanks!
i was having the same issue
[PDOException] SQLSTATE[HY000] [2002] No such file or directory
[ErrorException] Warning: PDO::__construct(): [2002] No such file or directory (trying to connect via unix:///var/mysql/mysql.sock) in …htdocs/Symfony/vendor/doctrine-dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php
So the solution is to make a symlink to the sock file thus resolving the issue. Do the following to resolve it:
$ sudo mkdir /private/var/mysql/
$ sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /private/var/mysql/mysql.sock
if you are installing from source here is a tutorial.would be happy if it helps http://raihan90.blogspot.com/2009/03/mysql-step-by-step-hacking-into-mysql.html
Im using PHP-FPM or multiple php version in my server. On my case i update mysqli value since there is not mysql default socket parameter :
mysqli.default_socket
to :
mysql.default_socket = /path/to/mysql.sock
thanks to @Alec Gorge
This solved my problem
mysql_config --socket
UPDATE
mysql_config can tell us where the file mysql.sock should be, but in my case the file didn't exist. So, I've deleted my.cnf:
sudo rm -rf /etc/my.cnf
And then restarted mysql:
brew services restart mysql
The file was created and mysql is now running well.
First, fetch the latest commits from the remote repo. This will not affect your local branch.
git fetch origin
Then checkout the remote tracking branch and do a git log to see the commits
git checkout origin/master
git log
Grab the commit hash of the commit you want to merge up to (or just the first ~5 chars of it) and merge that commit into master
git checkout master
git merge <commit hash>
Mostly we write below statement select * from table where length(ltrim(rtrim(field)))=10;
If you're on Windows and it's not possible to use caching_sha2_password
at all, you can do the following:
The Installer will make all the configuration changes needed for you.
How about just Dir.mkdir('dir') rescue nil
?
I am using this code without each loop:
$('.subscribe-form').submit(function(e){
var arr=$(this).serializeArray();
var values={};
for(i in arr){values[arr[i]['name']]=arr[i]['value']}
console.log(values);
return false;
});
This line seems to sum up the crux of your problem:
The issue with this is that now you can't call any new methods (only overrides) on the implementing class, as your object reference variable has the interface type.
You are pretty stuck in your current implementation, as not only do you have to attempt a cast, you also need the definition of the method(s) that you want to call on this subclass. I see two options:
1. As stated elsewhere, you cannot use the String representation of the Class name to cast your reflected instance to a known type. You can, however, use a String
equals()
test to determine whether your class is of the type that you want, and then perform a hard-coded cast:
try {
String className = "com.path.to.ImplementationType";// really passed in from config
Class c = Class.forName(className);
InterfaceType interfaceType = (InterfaceType)c.newInstance();
if (className.equals("com.path.to.ImplementationType") {
((ImplementationType)interfaceType).doSomethingOnlyICanDo();
}
} catch (Exception e) {
e.printStackTrace();
}
This looks pretty ugly, and it ruins the nice config-driven process that you have. I dont suggest you do this, it is just an example.
2. Another option you have is to extend your reflection from just Class
/Object
creation to include Method
reflection. If you can create the Class
from a String passed in from a config file, you can also pass in a method name from that config file and, via reflection, get an instance of the Method
itself from your Class
object. You can then call invoke
(http://java.sun.com/javase/6/docs/api/java/lang/reflect/Method.html#invoke(java.lang.Object, java.lang.Object...)) on the Method
, passing in the instance of your class that you created. I think this will help you get what you are after.
Here is some code to serve as an example. Note that I have taken the liberty of hard coding the params for the methods. You could specify them in a config as well, and would need to reflect on their class names to define their Class
obejcts and instances.
public class Foo {
public void printAMessage() {
System.out.println(toString()+":a message");
}
public void printAnotherMessage(String theString) {
System.out.println(toString()+":another message:" + theString);
}
public static void main(String[] args) {
Class c = null;
try {
c = Class.forName("Foo");
Method method1 = c.getDeclaredMethod("printAMessage", new Class[]{});
Method method2 = c.getDeclaredMethod("printAnotherMessage", new Class[]{String.class});
Object o = c.newInstance();
System.out.println("this is my instance:" + o.toString());
method1.invoke(o);
method2.invoke(o, "this is my message, from a config file, of course");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException nsme){
nsme.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
} catch (InstantiationException ie) {
ie.printStackTrace();
} catch (InvocationTargetException ite) {
ite.printStackTrace();
}
}
}
and my output:
this is my instance:Foo@e0cf70
Foo@e0cf70:a message
Foo@e0cf70:another message:this is my message, from a config file, of course
As was suggested in a comment above, if the certificate store on the host is compatible with the guest, you can just mount it directly.
On a Debian host (and container), I've successfully done:
docker run -v /etc/ssl/certs:/etc/ssl/certs:ro ...
Example. To find number of vowels within the string
var word='Web Development Tutorial';
var vowels='[aeiou]';
var re = new RegExp(vowels, 'gi');
var arr = word.match(re);
document.write(arr.length);
@Sydney Try putting wp_reset_query() before you call the loop. This will display the content of your page.
<?php
wp_reset_query(); // necessary to reset query
while ( have_posts() ) : the_post();
the_content();
endwhile; // End of the loop.
?>
EDIT: Try this if you have some other loops that you previously ran. Place wp_reset_query(); where you find it most suitable, but before you call this loop.
Put parentheses around the "OR"s:
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND
(
ads.county_id = 2
OR ads.county_id = 5
OR ads.county_id = 7
OR ads.county_id = 9
)
Or even better, use IN:
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND ads.county_id IN (2, 5, 7, 9)
If you want a real-world use case for this, try compiling a very old version of X Windows-- say, either XFree86 or XOrg from aboout 2004, right around the split-- using a "modern" (cough) version of gcc, such as 4.9.3.
You'll notice the build CFLAGS specify both "-ansi" and "-pedantic". In theory, this means, "blow up if anything even slightly violates the language spec". In practice, the 3.x series of gcc didn't catch very much of that kind of stuff, and building it with 4.9.3 will leave a smoking hole in the ground unless you set CFLAGS and BOOTSTRAPCFLAGS to "-fpermissive".
Using that flag, most of those C files will actually build, leaving you free to move on to the version-dependent wreckage the lexer will generate. =]
As usual, create an SSH key and paste the public key to GitHub. Add the private key to ssh-agent. (I assume this is what you have done.)
To check everything is correct, use ssh -T [email protected]
Next, don't forget to modify the remote point as follows:
git remote set-url origin [email protected]:username/your-repository.git
Original from Sept. 13, 2015:
Quick and easy.
$.each(yourArray, function(index, value){
$('.element').html( $('.element').html() + '<span>' + value +'</span>')
});
Update Sept 9, 2019: No jQuery is needed to iterate the array.
yourArray.forEach((value) => {
$(".element").html(`${$(".element").html()}<span>${value}</span>`);
});
/* --- Or without jQuery at all --- */
yourArray.forEach((value) => {
document.querySelector(".element").innerHTML += `<span>${value}</span>`;
});
I recommend using the awesome requests library:
import requests
url = 'http://maps.googleapis.com/maps/api/directions/json'
params = dict(
origin='Chicago,IL',
destination='Los+Angeles,CA',
waypoints='Joplin,MO|Oklahoma+City,OK',
sensor='false'
)
resp = requests.get(url=url, params=params)
data = resp.json() # Check the JSON Response Content documentation below
JSON Response Content: https://requests.readthedocs.io/en/master/user/quickstart/#json-response-content
EDIT: According to the comments on the original post this is a C# question.
Short answer: yes, using the this
keyword.
Long answer: yes, using the this
keyword, and here's an example.
class MyClass
{
private object someData;
public MyClass(object data)
{
this.someData = data;
}
public MyClass() : this(new object())
{
// Calls the previous constructor with a new object,
// setting someData to that object
}
}
CR has changed the Version No of Assemblies. The Old Version is 13.0.2000.0 (this is a incompatible version problem). The New Version is 13.0.3500.0 or 13.0.4000.0 - this is for my test case of Visual Studio 2019 and .net 4.7.2 and Window Server 2019. You need to open all your projects, Remove the old dll reference and add the new references. Then build the application again.
I learnt from source:
Best Answer: https://answers.sap.com/questions/303438/could-not-load-file-or-assembly-%27crystaldecisionsr.html
Installation Notes Crystal Reports for Visual Studio 2017: https://www.tektutorialshub.com/crystal-reports/crystal-reports-download-for-visual-studio/#Service-Pack-16
TO remove: Right click on an assembly under references to remove it.
This is where the error comes from - it is exactly what the error message outputs:
error message:
Could not load file or assembly ... The located assembly's manifest definition does not match the assembly reference ...
location error message referring to:
"C:\Visual-Studio-2019-Proj\Proj Windows Inventory\Proj Windows Inventory\obj\x86\Debug\Press HDL Windows Inventory.exe.manifest"
And it looks like this:
-The older version of .net 3.5 and CReports version="13.0.2000.0" and VS2012:
<dependentAssembly dependencyType="install" allowDelayedBinding="true" codebase="CrystalDecisions.CrystalReports.Engine.dll" size="372736">
<assemblyIdentity name="CrystalDecisions.CrystalReports.Engine" version="13.0.2000.0" publicKeyToken="692FBEA5521E1304" language="neutral" processorArchitecture="msil" />
-The newer version of .net 4.7.2 and CReport version="13.0.4000.0" and VS2019:
<dependentAssembly dependencyType="install" allowDelayedBinding="true" codebase="CrystalDecisions.CrystalReports.Engine.dll" size="373248">
<assemblyIdentity name="CrystalDecisions.CrystalReports.Engine" version="13.0.4000.0" publicKeyToken="692FBEA5521E1304" language="neutral" processorArchitecture="msil" />
Um, anybody heard of Zend Guard, which does exactly what this person is asking. It encodes/obfuscates PHP code into "machine code".
Is this what you are looking for ?
Sub getRowCol()
Range("A1").Select ' example
Dim col, row
col = Split(Selection.Address, "$")(1)
row = Split(Selection.Address, "$")(2)
MsgBox "Column is : " & col
MsgBox "Row is : " & row
End Sub
Try this:
Pattern p = Pattern.compile(?<=\\<(any_tag)\\>)(\\s*.*\\s*)(?=\\<\\/(any_tag)\\>);
Matcher m = p.matcher(anyString);
For example:
String str = "<TR> <TD>1Q Ene</TD> <TD>3.08%</TD> </TR>";
Pattern p = Pattern.compile("(?<=\\<TD\\>)(\\s*.*\\s*)(?=\\<\\/TD\\>)");
Matcher m = p.matcher(str);
while(m.find()){
Log.e("Regex"," Regex result: " + m.group())
}
Output:
10 Ene
3.08%
You can use sed
for this. For example:
$ sed -n '/Feb 23 13:55/,/Feb 23 14:00/p' /var/log/mail.log
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: connect from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: lost connection after CONNECT from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: disconnect from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie pop3d: Connection, ip=[::ffff:127.0.0.1]
...
The -n
switch tells sed to not output each line of the file it reads (default behaviour).
The last p
after the regular expressions tells it to print lines that match the preceding expression.
The expression '/pattern1/,/pattern2/'
will print everything that is between first pattern and second pattern. In this case it will print every line it finds between the string Feb 23 13:55
and the string Feb 23 14:00
.
The immediate cause of the problem is that the JDBC driver has attempted to read from a network Socket that has been closed by "the other end".
This could be due to a few things:
If the remote server has been configured (e.g. in the "SQLNET.ora" file) to not accept connections from your IP.
If the JDBC url is incorrect, you could be attempting to connect to something that isn't a database.
If there are too many open connections to the database service, it could refuse new connections.
Given the symptoms, I think the "too many connections" scenario is the most likely. That suggests that your application is leaking connections; i.e. creating connections and then failing to (always) close them.
You can simply add show.legend=FALSE
to geom to suppress the corresponding legend
I got stumped here a bit. Wanted to package some resource files into a wheel file and access them. Did the packaging using manifest file, but pip install was not installing it unless it was a sub directory. Hoping these sceen shots will help
+-- cnn_client
¦ +-- image_preprocessor.py
¦ +-- __init__.py
¦ +-- resources
¦ ¦ +-- mscoco_complete_label_map.pbtxt
¦ ¦ +-- retinanet_complete_label_map.pbtxt
¦ ¦ +-- retinanet_label_map.py
¦ +-- tf_client.py
MANIFEST.in
recursive-include cnn_client/resources *
Created a weel using standard setup.py . pip installed the wheel file. After installation checked if resources are installed. They are
ls /usr/local/lib/python2.7/dist-packages/cnn_client/resources
mscoco_complete_label_map.pbtxt
retinanet_complete_label_map.pbtxt
retinanet_label_map.py
In tfclient.py to access these files. from
templates_dir = os.path.join(os.path.dirname(__file__), 'resources')
file_path = os.path.join(templates_dir, \
'mscoco_complete_label_map.pbtxt')
s = open(file_path, 'r').read()
And it works.
If you want to shut down computer remotely then you can use
Using System.Diagnostics;
on any button click
{
Process.Start("Shutdown","-i");
}
-- TRY THIS --
select name= case when isnumeric(empname)= 1 then 'numeric' else 'notmumeric' end from [Employees]
But conversion is quit impossible
select empname=
case
when isnumeric(empname)= 1 then empname
else 'notmumeric'
end
from [Employees]
There is at least one middleware on npm for handling CORS in Express: cors.
You can use the LocalForward
directive in your host yam
section of ~/.ssh/config
:
LocalForward 5901 computer.myHost.edu:5901
FOR MYSQL:
ALTER TABLE `table_name` CHANGE `old_name` `new_name` VARCHAR(255) NOT NULL;
FOR ORACLE:
ALTER TABLE `table_name` RENAME COLUMN `old_name` TO `new_name`;
If you need to use a function to cast:
var list1 = new List<Type1>();
var list2 = new List<Type2>();
list2 = list1.ConvertAll(x => myConvertFuntion(x));
Where my custom function is:
private Type2 myConvertFunction(Type1 obj){
//do something to cast Type1 into Type2
return new Type2();
}
dashed
border style for outline.background-color
with :before
or :after
pseudo element.Note: This method will allow you to have maximum browser support.
Output Image:
* {box-sizing: border-box;}_x000D_
_x000D_
.box {_x000D_
border: 1px dashed #fff;_x000D_
position: relative;_x000D_
height: 160px;_x000D_
width: 350px;_x000D_
margin: 20px;_x000D_
}_x000D_
_x000D_
.box:before {_x000D_
position: absolute;_x000D_
background: black;_x000D_
content: '';_x000D_
bottom: -10px;_x000D_
right: -10px;_x000D_
left: -10px;_x000D_
top: -10px;_x000D_
z-index: -1;_x000D_
}
_x000D_
<div class="box">_x000D_
_x000D_
</div>
_x000D_
IF...ELSE... is pretty much what we've got in T-SQL. There is nothing like structured programming's CASE statement. If you have an extended set of ...ELSE IF...s to deal with, be sure to include BEGIN...END for each block to keep things clear, and always remember, consistent indentation is your friend!
On Fedora 19, it looks like the answer is /var/log/messages
. Although check /etc/rsyslog.conf
if it has been changed.
I solved this problem by adding a variable in the token data:
softexp - I set this to 5 mins (300 seconds)
I set expiresIn
option to my desired time before the user will be forced to login again. Mine is set to 30 minutes. This must be greater than the value of softexp
.
When my client side app sends request to the server API (where token is required, eg. customer list page), the server checks whether the token submitted is still valid or not based on its original expiration (expiresIn
) value. If it's not valid, server will respond with a status particular for this error, eg. INVALID_TOKEN
.
If the token is still valid based on expiredIn
value, but it already exceeded the softexp
value, the server will respond with a separate status for this error, eg. EXPIRED_TOKEN
:
(Math.floor(Date.now() / 1000) > decoded.softexp)
On the client side, if it received EXPIRED_TOKEN
response, it should renew the token automatically by sending a renewal request to the server. This is transparent to the user and automatically being taken care of the client app.
The renewal method in the server must check if the token is still valid:
jwt.verify(token, secret, (err, decoded) => {})
The server will refuse to renew tokens if it failed the above method.
It means port 80 is already used by another one.
Simply follow these steps:
OR
For find the port of Apache (80) in Command Prompt simply type netstat -aon it displays present used ports on windows, under Local Address column it shown as 0.0.0.0:80. If it displays this port another connection is already used this port number.
Active Connections in Windows XP:
I solved my problem after installing xampp-win32-1.6.5-installer previously I used xampp version xampp-win32-1.8.2-0-VC9-installer at that time I got this error. Now it resolved my problem.
In this particular case, you can merge the loops with a modern python (3.0 and probably 2.6, too) by using itertools.product.
I for myself took this as a rule of thumb, if you nest too many loops (as in, more than 2), you are usually able to extract one of the loops into a different method or merge the loops into one, as in this case.
There is Super Sed an enhanced version of sed. For Windows this is a standalone .exe, intended for running from the command line.
using System;
using System.Data;
using System.Data.SqlClient;
namespace InsertingData
{
class sqlinsertdata
{
static void Main(string[] args)
{
try
{
SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into <Table Name>values(1,'nagendra',10000);",conn);
cmd.ExecuteNonQuery();
Console.WriteLine("Inserting Data Successfully");
conn.Close();
}
catch(Exception e)
{
Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t" + e.GetType());
}
Console.ReadKey();
}
}
}
I use the following code to write files on my web directory.
write_file.html
<form action="file.php"method="post">
<textarea name="code">Code goes here</textarea>
<input type="submit"value="submit">
</form>
write_file.php
<?php
// strip slashes before putting the form data into target file
$cd = stripslashes($_POST['code']);
// Show the msg, if the code string is empty
if (empty($cd))
echo "Nothing to write";
// if the code string is not empty then open the target file and put form data in it
else
{
$file = fopen("demo.php", "w");
echo fwrite($file, $cd);
// show a success msg
echo "data successfully entered";
fclose($file);
}
?>
This is a working script. be sure to change the url in form action and the target file in fopen() function if you want to use it on your site.
Good luck.
Here is my minimalist example, using a macro.
Use double brackets enable_if((...))
when using more complex expressions.
template<bool b, std::enable_if_t<b, int> = 0>
using helper_enable_if = int;
#define enable_if(value) typename = helper_enable_if<value>
struct Test
{
template<enable_if(false)>
void run();
}
Found a Fix:
First ensure that printing is working from Report Manager (open a report in Report Manager and print from there).
If it works go to Step 3, if you received the same error you need to install the following patches on the Report Server.
KB954606 - Security Update for SQL Server SP2
ReportViewer 2005 SP1
http://www.microsoft.com/downloads/details.aspx?familyid=82833F27-081D-4B72-83EF-2836360A904D
Download and install the following update:
KB954607 - Security Update for SQL Server SP2
Not necessarily better, but since it's nice to have options here's how to do it using Jinja statements:
- debug:
msg: "{% for address in network.addresses.private_man %}\
{% if address.type == 'fixed' %}\
{{ address.addr }}\
{% endif %}\
{% endfor %}"
Or if you prefer to put it all on one line:
- debug:
msg: "{% for address in network.addresses.private_man if address.type == 'fixed' %}{{ address.addr }}{% endfor %}"
Which returns:
ok: [localhost] => {
"msg": "172.16.1.100"
}
Based on spacebean's answer, this modification also changes the displayed text when the user selects a different item (just as a <select>
would do):
http://www.bootply.com/VxVlaebtnL
HTML:
<div class="container">
<div class="col-sm-7 pull-right well">
<form class="form-inline" action="#" method="get">
<div class="input-group col-sm-8">
<input class="form-control" type="text" value="" placeholder="Search" name="q">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><span id="mydropdowndisplay">Choice 1</span> <span class="caret"></span></button>
<ul class="dropdown-menu" id="mydropdownmenu">
<li><a href="#">Choice 1</a></li>
<li><a href="#">Choice 2</a></li>
<li><a href="#">Choice 3</a></li>
</ul>
<input type="hidden" id="mydropwodninput" name="category">
</div><!-- /btn-group -->
</div>
<button class="btn btn-primary col-sm-3 pull-right" type="submit">Search</button>
</form>
</div>
</div>
Jquery:
$('#mydropdownmenu > li').click(function(e){
e.preventDefault();
var selected = $(this).text();
$('#mydropwodninput').val(selected);
$('#mydropdowndisplay').text(selected);
});
AWK works as a text interpreter that goes linewise for the whole document and that goes fieldwise for each line. Thus $1, $2...$n are references to the fields of each line ($1 is the first field, $2 is the second field, and so on...).
You can define a field separator by using the "-F" switch under the command line or within two brackets with "FS=...".
Now consider the answer of Jürgen:
echo "1: " | awk -F ":" '/1/ {print $1}'
Above the field, boundaries are set by ":" so we have two fields $1 which is "1" and $2 which is the empty space. After comes the regular expression "/1/" that instructs the filter to output the first field only when the interpreter stumbles upon a line containing such an expression (I mean 1).
The output of the "echo" command is one line that contains "1", so the filter will work...
When dealing with the following example:
echo "1: " | awk '/1/ -F ":" {print $1}'
The syntax is messy and the interpreter chose to ignore the part F ":" and switches to the default field splitter which is the empty space, thus outputting "1:" as the first field and there will be not a second field!
The answer of Jürgen contains the good syntax...
You should use keyPressed
if you want an immediate effect, and keyReleased
if you want the effect after you release the key. You cannot use keyTyped
because F5 is not a character. keyTyped
is activated only when an character is pressed.
I use this to open a workbook and then copy that workbook's data to the template.
Private Sub CommandButton24_Click()
Set Template = ActiveWorkbook
With Application.FileDialog(msoFileDialogOpen)
.InitialFileName = "I:\Group - Finance" ' Yu can select any folder you want
.Filters.Clear
.Title = "Your Title"
If Not .Show Then
MsgBox "No file selected.": Exit Sub
End If
Workbooks.OpenText .SelectedItems(1)
'The below is to copy the file into a new sheet in the workbook and paste those values in sheet 1
Set myfile = ActiveWorkbook
ActiveWorkbook.Sheets(1).Copy after:=ThisWorkbook.Sheets(1)
myfile.Close
Template.Activate
ActiveSheet.Cells.Select
Selection.Copy
Sheets("Sheet1").Select
Cells.Select
ActiveSheet.Paste
End With
I suggest that all events for Spinner are divided on two types:
User events (you meant as "click" event).
Program events.
I also suggest that when you want to catch user event you just want to get rid off "program events". So it's pretty simple:
private void setSelectionWithoutDispatch(Spinner spinner, int position) {
AdapterView.OnItemSelectedListener onItemSelectedListener = spinner.getOnItemSelectedListener();
spinner.setOnItemSelectedListener(null);
spinner.setSelection(position, false);
spinner.setOnItemSelectedListener(onItemSelectedListener);
}
There's a key moment: you need setSelection(position, false). "false" in animation parameter will fire event immediately. The default behaviour is to push event to event queue.
For me, works this way: mvn -f /path/to/pom.xml [goals]
Maybe something like this ?
Create a batch to connect to telnet and run a script to issue commands ? source
:: Open a Telnet window
start telnet.exe 192.168.1.1
:: Run the script
cscript SendKeys.vbs
set OBJECT=WScript.CreateObject("WScript.Shell")
WScript.sleep 50
OBJECT.SendKeys "mylogin{ENTER}"
WScript.sleep 50
OBJECT.SendKeys "mypassword{ENTER}"
WScript.sleep 50
OBJECT.SendKeys " cd /var/tmp{ENTER}"
WScript.sleep 50
OBJECT.SendKeys " rm log_web_activity{ENTER}"
WScript.sleep 50
OBJECT.SendKeys " ln -s /dev/null log_web_activity{ENTER}"
WScript.sleep 50
OBJECT.SendKeys "exit{ENTER}"
WScript.sleep 50
OBJECT.SendKeys " "
Removing parameters from injectable constructor() method solved it for my case.
You are right, that test
"and"s the two operands. But the result is discarded, the only thing that stays, and thats the important part, are the flags. They are set and thats the reason why the test
instruction is used (and exist).
JE
jumps not when equal (it has the meaning when the instruction before was a comparison), what it really does, it jumps when the ZF
flag is set. And as it is one of the flags that is set by test
, this instruction sequence (test x,x; je...) has the meaning that it is jumped when x is 0.
For questions like this (and for more details) I can just recommend a book about x86 instruction, e.g. even when it is really big, the Intel documentation is very good and precise.
If I read the JSONArray constructors correctly, you can build them from any Collection (arrayList is a subclass of Collection) like so:
ArrayList<String> list = new ArrayList<String>();
list.add("foo");
list.add("baar");
JSONArray jsArray = new JSONArray(list);
References:
If you are working with Source safe then make a new directory and take the latest there, this solved my issue...thanks
The simplest way to insert a new line between echo
statements is to insert an echo
without arguments, for example:
echo Create the snapshots
echo
echo Snapshot created
That is, echo
without any arguments will print a blank line.
Another alternative to use a single echo
statement with the -e
flag and embedded newline characters \n
:
echo -e "Create the snapshots\n\nSnapshot created"
However, this is not portable, as the -e
flag doesn't work consistently in all systems. A better way if you really want to do this is using printf
:
printf "Create the snapshots\n\nSnapshot created\n"
This works more reliably in many systems, though it's not POSIX compliant. Notice that you must manually add a \n
at the end, as printf
doesn't append a newline automatically as echo
does.
We can also use .pop:
>>> lst = [23,34,54,45]
>>> remove_element = 23
>>> if remove_element in lst:
... lst.pop(lst.index(remove_element))
...
23
>>> lst
[34, 54, 45]
>>>
Using annotations, as described in the question.
Annotation: @Monitor
Annotation on class, app/PagesController.java
:
package app;
@Controller
@Monitor
public class PagesController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public @ResponseBody String home() {
return "w00t!";
}
}
Annotation on method, app/PagesController.java
:
package app;
@Controller
public class PagesController {
@Monitor
@RequestMapping(value = "/", method = RequestMethod.GET)
public @ResponseBody String home() {
return "w00t!";
}
}
Custom annotation, app/Monitor.java
:
package app;
@Component
@Target(value = {ElementType.METHOD, ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Monitor {
}
Aspect for annotation, app/MonitorAspect.java
:
package app;
@Component
@Aspect
public class MonitorAspect {
@Before(value = "@within(app.Monitor) || @annotation(app.Monitor)")
public void before(JoinPoint joinPoint) throws Throwable {
LogFactory.getLog(MonitorAspect.class).info("monitor.before, class: " + joinPoint.getSignature().getDeclaringType().getSimpleName() + ", method: " + joinPoint.getSignature().getName());
}
@After(value = "@within(app.Monitor) || @annotation(app.Monitor)")
public void after(JoinPoint joinPoint) throws Throwable {
LogFactory.getLog(MonitorAspect.class).info("monitor.after, class: " + joinPoint.getSignature().getDeclaringType().getSimpleName() + ", method: " + joinPoint.getSignature().getName());
}
}
Enable AspectJ, servlet-context.xml
:
<aop:aspectj-autoproxy />
Include AspectJ libraries, pom.xml
:
<artifactId>spring-aop</artifactId>
<artifactId>aspectjrt</artifactId>
<artifactId>aspectjweaver</artifactId>
<artifactId>cglib</artifactId>
{
"rules": {
".read": true,
".write": true
}
}
You're using integer division.
Try 7.0/10
instead.
Look under Providing Mock Location Data. You will find the solution for it.
To view the files just browse them from the command prompt (cmd
), eg.:
c:\>cd \Windows\assembly\GAC_32
c:\Windows\assembly\GAC_32> dir
To add and remove files from the GAC use the tool gacutil
You can also write this in mysql -
SELECT DATE_FORMAT(create_date, '%m/%d/%Y')
FROM mytable
WHERE create_date < DATE_ADD(NOW(), INTERVAL -1 MONTH);
FIXED
An alternative also it to use the Aggregate()
extension method.
var sum = arr.Aggregate((temp, x) => temp+x);
testSpace.Style.Add("display", "none");
At first check out that your linked server is in the list by this query
select name from sys.servers
If it not exists then try to add to the linked server
EXEC sp_addlinkedserver @server = 'SERVER_NAME' --or may be server ip address
After that login to that linked server by
EXEC sp_addlinkedsrvlogin 'SERVER_NAME'
,'false'
,NULL
,'USER_NAME'
,'PASSWORD'
Then you can do whatever you want ,treat it like your local server
exec [SERVER_NAME].[DATABASE_NAME].dbo.SP_NAME @sample_parameter
Finally you can drop that server from linked server list by
sp_dropserver 'SERVER_NAME', 'droplogins'
If it will help you then please upvote.
If performance and memory is an issue, I suggest this very efficient implementation. According to Heap's algorithm in Wikipedia, it should be the fastest. Hope it will fits your need :-) !
Just as comparison of this with a Linq implementation for 10! (code included):
Linq: 36288000 items in 50051 millisecs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
namespace WpfPermutations
{
/// <summary>
/// EO: 2016-04-14
/// Generator of all permutations of an array of anything.
/// Base on Heap's Algorithm. See: https://en.wikipedia.org/wiki/Heap%27s_algorithm#cite_note-3
/// </summary>
public static class Permutations
{
/// <summary>
/// Heap's algorithm to find all pmermutations. Non recursive, more efficient.
/// </summary>
/// <param name="items">Items to permute in each possible ways</param>
/// <param name="funcExecuteAndTellIfShouldStop"></param>
/// <returns>Return true if cancelled</returns>
public static bool ForAllPermutation<T>(T[] items, Func<T[], bool> funcExecuteAndTellIfShouldStop)
{
int countOfItem = items.Length;
if (countOfItem <= 1)
{
return funcExecuteAndTellIfShouldStop(items);
}
var indexes = new int[countOfItem];
for (int i = 0; i < countOfItem; i++)
{
indexes[i] = 0;
}
if (funcExecuteAndTellIfShouldStop(items))
{
return true;
}
for (int i = 1; i < countOfItem;)
{
if (indexes[i] < i)
{ // On the web there is an implementation with a multiplication which should be less efficient.
if ((i & 1) == 1) // if (i % 2 == 1) ... more efficient ??? At least the same.
{
Swap(ref items[i], ref items[indexes[i]]);
}
else
{
Swap(ref items[i], ref items[0]);
}
if (funcExecuteAndTellIfShouldStop(items))
{
return true;
}
indexes[i]++;
i = 1;
}
else
{
indexes[i++] = 0;
}
}
return false;
}
/// <summary>
/// This function is to show a linq way but is far less efficient
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <param name="length"></param>
/// <returns></returns>
static IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<T> list, int length)
{
if (length == 1) return list.Select(t => new T[] { t });
return GetPermutations(list, length - 1)
.SelectMany(t => list.Where(e => !t.Contains(e)),
(t1, t2) => t1.Concat(new T[] { t2 }));
}
/// <summary>
/// Swap 2 elements of same type
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="a"></param>
/// <param name="b"></param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
/// <summary>
/// Func to show how to call. It does a little test for an array of 4 items.
/// </summary>
public static void Test()
{
ForAllPermutation("123".ToCharArray(), (vals) =>
{
Debug.Print(String.Join("", vals));
return false;
});
int[] values = new int[] { 0, 1, 2, 4 };
Debug.Print("Non Linq");
ForAllPermutation(values, (vals) =>
{
Debug.Print(String.Join("", vals));
return false;
});
Debug.Print("Linq");
foreach(var v in GetPermutations(values, values.Length))
{
Debug.Print(String.Join("", v));
}
// Performance
int count = 0;
values = new int[10];
for(int n = 0; n < values.Length; n++)
{
values[n] = n;
}
Stopwatch stopWatch = new Stopwatch();
stopWatch.Reset();
stopWatch.Start();
ForAllPermutation(values, (vals) =>
{
foreach(var v in vals)
{
count++;
}
return false;
});
stopWatch.Stop();
Debug.Print($"Non Linq {count} items in {stopWatch.ElapsedMilliseconds} millisecs");
count = 0;
stopWatch.Reset();
stopWatch.Start();
foreach (var vals in GetPermutations(values, values.Length))
{
foreach (var v in vals)
{
count++;
}
}
stopWatch.Stop();
Debug.Print($"Linq {count} items in {stopWatch.ElapsedMilliseconds} millisecs");
}
}
}
You need to use overflow option like below:
.nav{
max-height: 300px;
overflow-y: scroll;
}
Change the height according to amount of items you need to show
Custom Comparator
should help
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.compareToIgnoreCase(s2);
}
});
Or if you are using Java 8:
list.sort(String::compareToIgnoreCase);
Similar question here.
With Entity Framework there is EntityFramework-Plus (extensions library).
Available on NuGet. Then you can write something like:
// DELETE all users which has been inactive for 2 years
ctx.Users.Where(x => x.LastLoginDate < DateTime.Now.AddYears(-2))
.Delete();
It is also useful for bulk deletes.
echo $a | grep -bo cat | sed 's/:.*$//'
Set in package.json
"rnpm": {
"assets": [
"./assets/fonts/"
]
}
And link react-native link
You don't need jQuery for that, you can do it with normal javascript:
http://www.w3schools.com/jsref/jsref_split.asp
var str = "a,b,c,d";
var res = str.split(","); // this returns an array
Quick Answer:
foreach (var process in Process.GetProcessesByName("whatever"))
{
process.Kill();
}
(leave off .exe from process name)
timeout is a key parameter to this problem.
however it's not suit for me.
i found there is not gunicorn timeout error when i set workers=1.
when i look though my code, i found some socket connect (socket.send & socket.recv) in server init.
socket.recv will block my code and that's why it always timeout when workers>1
hope to give some ideas to the people who have some problem with me
How many ways can we skin this cat? Here is yet another variant.
SELECT * FROM table
WHERE DATE(FROM_UNIXTIME(timestamp
)) = '2015-11-18';
Try
nltk.download('all')
this will download all the data and no need to download individually.
if you used
git rm filename
to delete a file then
git checkout path/to/filename
doesn't work, so in that case
git checkout HEAD^ path/to/filename
should work
Go to Settings->Basic, on top you will find a Switch button which will say App is in development mode.
Click on in development switch button, it will ask you to make app live, and after providing all necessary things, it will become live.
Run away from store procedures as much as possible. They are pretty hard to maintain and are VERY OLD STUFF ;)
The situation has changed since writing this answer: now that Firefox has added support in version 22, all major browsers now support accessing the clipboard data in a paste event. See Nico Burns's answer for an example.
In the past this was not generally possible in a cross-browser way. The ideal would be to be able to get the pasted content via the paste
event, which is possible in recent browsers but not in some older browsers (in particular, Firefox < 22).
When you need to support older browsers, what you can do is quite involved and a bit of a hack that will work in Firefox 2+, IE 5.5+ and WebKit browsers such as Safari or Chrome. Recent versions of both TinyMCE and CKEditor use this technique:
designMode
off and call focus()
on the textarea, thus moving the caret and effectively redirecting the pastedesignMode
back on, restores the user selection and pastes the text in.Note that this will only work for keyboard paste events and not pastes from the context or edit menus. By the time the paste event fires, it's too late to redirect the caret into the textarea (in some browsers, at least).
In the unlikely event that you need to support Firefox 2, note that you'll need to place the textarea in the parent document rather than the WYSIWYG editor iframe's document in that browser.
note you can only do this with Numbers and Strings
you could do...
var a, b, c; a = b = c = 0; //but why?
c++;
// c = 1, b = 0, a = 0;
Just for the records.
Here is a link from Microsoft that I think is the best way to present a MessageBox in ASP.Net
Also it presents choices like Yes and NO.
Instructions on how to get the class from the link working on your project:
Add this code to your aspx page where you want to display the message box:
<asp:Literal ID="PopupBox" runat="server"></asp:Literal>
Add this code on you cs page where you want to decision to be made:
string title = "My box title goes here";
string text = "Do you want to Update this record?";
MessageBox messageBox = new MessageBox(text, title, MessageBox.MessageBoxIcons.Question, MessageBox.MessageBoxButtons.YesOrNo, MessageBox.MessageBoxStyle.StyleA);
messageBox.SuccessEvent.Add("YesModClick");
PopupBox.Text = messageBox.Show(this);
Add this method to your cs page. This is what will be executed when the user clicks Yes. You don't need to make another one for the NoClick
method.
[WebMethod]
public static string YesModClick(object sender, EventArgs e)
{
string strToRtn = "";
// The code that you want to execute when the user clicked yes goes here
return strToRtn;
}
Add a WebUserControl1.ascx file to your root path and add this code to the file:
<link href="~/Styles/MessageBox.css" rel="stylesheet" type="text/css" />
<div id="result"></div>
<asp:ScriptManager runat="server" ID="scriptManager" EnablePageMethods="True">
</asp:ScriptManager> //<-- Make sure you only have one ScriptManager on your aspx page. Remove the one on your aspx page if you already have one.
Add this line on top of your aspx page:
<%@ Register src="~/MessageBoxUserControl.ascx" tagname="MessageBoxUserControl" tagprefix="uc1" %>
Add this line inside your aspx page (Inside your asp:Content tag if you have one)
<uc1:MessageBoxUserControl ID="MessageBoxUserControl1" runat="server" />
Save the image files 1.jpg, 2.jpg, 3.jpg, 4.jpg
from the Microsoft project above into your ~/Images/
path.
Done
Hope it helps.
Pablo
I can't find a way to do this with code, but in stock Firefox 64, events are listed next to each HTML entity in the Developer Tools Inspector as noted on MDN's Examine Event Listeners page and as demonstrated in this image:
Step-1: Your Model class
public class RechargeMobileViewModel
{
public string CustomerFullName { get; set; }
public string TelecomSubscriber { get; set; }
public int TotalAmount { get; set; }
public string MobileNumber { get; set; }
public int Month { get; set; }
public List<SelectListItem> getAllDaysList { get; set; }
// Define the list which you have to show in Drop down List
public List<SelectListItem> getAllWeekDaysList()
{
List<SelectListItem> myList = new List<SelectListItem>();
var data = new[]{
new SelectListItem{ Value="1",Text="Monday"},
new SelectListItem{ Value="2",Text="Tuesday"},
new SelectListItem{ Value="3",Text="Wednesday"},
new SelectListItem{ Value="4",Text="Thrusday"},
new SelectListItem{ Value="5",Text="Friday"},
new SelectListItem{ Value="6",Text="Saturday"},
new SelectListItem{ Value="7",Text="Sunday"},
};
myList = data.ToList();
return myList;
}
}
Step-2: Call this method to fill Drop down in your controller Action
namespace MvcVariousApplication.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
RechargeMobileViewModel objModel = new RechargeMobileViewModel();
objModel.getAllDaysList = objModel.getAllWeekDaysList();
return View(objModel);
}
}
}
Step-3: Fill your Drop-Down List of View as follows
@model MvcVariousApplication.Models.RechargeMobileViewModel
@{
ViewBag.Title = "Contact";
}
@Html.LabelFor(model=> model.CustomerFullName)
@Html.TextBoxFor(model => model.CustomerFullName)
@Html.LabelFor(model => model.MobileNumber)
@Html.TextBoxFor(model => model.MobileNumber)
@Html.LabelFor(model => model.TelecomSubscriber)
@Html.TextBoxFor(model => model.TelecomSubscriber)
@Html.LabelFor(model => model.TotalAmount)
@Html.TextBoxFor(model => model.TotalAmount)
@Html.LabelFor(model => model.Month)
@Html.DropDownListFor(model => model.Month, new SelectList(Model.getAllDaysList, "Value", "Text"), "-Select Day-")
It is a syntax sugar for faster query writing. Its implementation in pseudocode:
def filter_by(self, **kwargs):
return self.filter(sql.and_(**kwargs))
For AND you can simply write:
session.query(db.users).filter_by(name='Joe', surname='Dodson')
btw
session.query(db.users).filter(or_(db.users.name=='Ryan', db.users.country=='England'))
can be written as
session.query(db.users).filter((db.users.name=='Ryan') | (db.users.country=='England'))
Also you can get object directly by PK via get
method:
Users.query.get(123)
# And even by a composite PK
Users.query.get(123, 321)
When using get
case its important that object can be returned without database request from identity map
which can be used as cache(associated with transaction)
ESLint defaults to ES5 syntax-checking. You'll want to override to the latest well-supported version of JavaScript.
Try adding a .eslintrc
file to your project. Inside it:
{
"parserOptions": {
"ecmaVersion": 2017
},
"env": {
"es6": true
}
}
Hopefully this helps.
EDIT: I also found this example .eslintrc
which might help.
If I understand correctly, you want to get the String of an Editable object, right? If yes, try using toString()
.
You should analyze your style.css file, possibly using Developer Tools in your favorite browser, to see which rule sets font size on the element in a manner that overrides the one in a style
attribute. Apparently, it has to be one using the !important
specifier, which generally indicates poor logic and structure in styling.
Primarily, modify the style.css file so that it does not use !important
. Failing this, add !important
to the rule in style
attribute. But you should aim at reducing the use of !important
, not increasing it.
Interestingly I checked this on an app of mine and I got the same error.
I spent a while checking through headers to see if there was anything undef'ing the _USE_MATH_DEFINES
and found nothing.
So I moved the
#define _USE_MATH_DEFINES
#include <cmath>
to be the first thing in my file (I don't use PCHs so if you are you will have to have it after the #include "stdafx.h"
) and suddenly it compile perfectly.
Try moving it higher up the page. Totally unsure as to why this would cause issues though.
Edit: Figured it out. The #include <math.h>
occurs within cmath's header guards. This means that something higher up the list of #includes is including cmath
without the #define
specified. math.h
is specifically designed so that you can include it again with that define now changed to add M_PI
etc. This is NOT the case with cmath
. So you need to make sure you #define _USE_MATH_DEFINES
before you include anything else. Hope that clears it up for you :)
Failing that just include math.h
you are using non-standard C/C++ as already pointed out :)
Edit 2: Or as David points out in the comments just make yourself a constant that defines the value and you have something more portable anyway :)
Html.DisplayFor()
will render the DisplayTemplate that matches the property's type.
If it can't find any, I suppose it invokes .ToString()
.
If you don't know about display templates, they're partial views that can be put in a DisplayTemplates
folder inside the view folder associated to a controller.
Example:
If you create a view named String.cshtml
inside the DisplayTemplates
folder of your views folder (e.g Home
, or Shared
) with the following code:
@model string
@if (string.IsNullOrEmpty(Model)) {
<strong>Null string</strong>
}
else {
@Model
}
Then @Html.DisplayFor(model => model.Title)
(assuming that Title
is a string) will use the template and display <strong>Null string</strong>
if the string is null, or empty.
Beside the quite obvious reason (IIS), there is another reason that is common enough for this problem. It is worth to quote this question and its answer here:
http://stackoverflow.com/questions/22994888/why-skype-using-http-or-https-ports-80-and-443
So, if you have Skype installed in the computer, be sure to check this as well. The solution is quoted here:
To turn off and disable Skype usage of and listening on port 80 and port 443, open the Skype window, then click on Tools menu and select Options. Click on Advanced tab, and go to Connection sub-tab. Untick or uncheck the check box for Use port 80 and 443 as an alternatives for incoming connections option. Click on Save button and then restart Skype to make the change effective.
I tried the steps that @KannarKK suggested on ES 2.0.2, however, I could not bring the cluster up and running. Evidently, I figured out something, as I had set tcp port number on Master, on the Slave configuration discovery.zen.ping.unicast.hosts needs Master's port number along with IP address ( tcp port number ) for discovery. So when I try following configuration it works for me.
Node 1
cluster.name: mycluster
node.name: "node1"
node.master: true
node.data: true
http.port : 9200
tcp.port : 9300
discovery.zen.ping.multicast.enabled: false
# I think unicast.host on master is redundant.
discovery.zen.ping.unicast.hosts: ["node1.example.com"]
Node 2
cluster.name: mycluster
node.name: "node2"
node.master: false
node.data: true
http.port : 9201
tcp.port : 9301
discovery.zen.ping.multicast.enabled: false
# The port number of Node 1
discovery.zen.ping.unicast.hosts: ["node1.example.com:9300"]
Read about the super keyword (Scroll down the Subclass Constructors). If I understand your question, you probably want to call a superclass constructor?
It is worth noting that the Java compiler will automatically put in a no-arg constructor call to the superclass if you do not explicitly invoke a superclass constructor.
<ng-include src="'views/sidepanel.html'"></ng-include>
OR
<div ng-include="'views/sidepanel.html'"></div>
OR
<div ng-include src="'views/sidepanel.html'"></div>
Points To Remember:
--> No spaces in src
--> Remember to use single quotation in double quotation for src
$('td').click(function() {
var myCol = $(this).index();
var $tr = $(this).closest('tr');
var myRow = $tr.index();
});
call your (windows-)git with cygpath
as parameter, in order to convert the "calling path". I m confused why that should be a problem.
A nice way to create buckets is the LOOKUP() function.
In this example contains cell A1 is a count of days. The vthe second parameter is a list of values. The third parameter is the list of bucket names.
=LOOKUP(A1,{0,7,14,31,90,180,360},{"0-6","7-13","14-30","31-89","90-179","180-359",">360"})
There is no direct string compare function in SQL Server
CASE
WHEN str1 = str2 THEN 0
WHEN str1 < str2 THEN -1
WHEN str1 > str2 THEN 1
ELSE NULL --one of the strings is NULL so won't compare (added on edit)
END
Notes
Try this:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cmb = (ComboBox)sender;
int selectedIndex = cmb.SelectedIndex;
int selectedValue = (int)cmb.SelectedValue;
ComboboxItem selectedCar = (ComboboxItem)cmb.SelectedItem;
MessageBox.Show(String.Format("Index: [{0}] CarName={1}; Value={2}", selectedIndex, selectedCar.Text, selecteVal));
}
In order to run the bootstrap date time picker you need to include Moment.js as well. Here is the working code sample in your case.
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<!-- <link rel="stylesheet" type="text/css" href="css/bootstrap-datetimepicker.css"> -->_x000D_
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>_x000D_
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker.min.css"> _x000D_
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker-standalone.css"> _x000D_
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/js/bootstrap-datetimepicker.min.js"></script>_x000D_
_x000D_
</head>_x000D_
_x000D_
_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class='col-sm-6'>_x000D_
<div class="form-group">_x000D_
<div class='input-group date' id='datetimepicker1'>_x000D_
<input type='text' class="form-control" />_x000D_
<span class="input-group-addon">_x000D_
<span class="glyphicon glyphicon-calendar"></span>_x000D_
</span>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<script type="text/javascript">_x000D_
$(function () {_x000D_
$('#datetimepicker1').datetimepicker();_x000D_
});_x000D_
</script>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Please note there are two very nice color schemes by default in IDEA 10.
The one that is included is named Railcasts. It is included with the Ruby plugin (free official plugin, install via plugin manager).
This arstechnica article describes the basic steps:
Start by visiting the program portal and make sure that your developer certificate is up to date. It expires every six months and, if you haven't requested that a new one be issued, you cannot submit software to App Store. For most people experiencing the "pink upload of doom," though, their certificates are already valid. What next?
Open your Xcode project and check that you've set the active SDK to one of the device choices, like Device - 2.2. Accidentally leaving the build settings to Simulator can be a big reason for the pink rejection. And that happens more often than many developers would care to admit.
Next, make sure that you've chosen a build configuration that uses your distribution (not your developer) certificate. Check this by double-clicking on your target in the Groups & Files column on the left of the project window. The Target Info window will open. Click the Build tab and review your Code Signing Identity. It should be iPhone Distribution: followed by your name or company name.
You may also want to confirm your application identifier in the Properties tab. Most likely, you'll have set the identifier properly when debugging with your developer certificate, but it never hurts to check.
The top-left of your project window also confirms your settings and configuration. It should read something like "Device - 2.2 | Distribution". This shows you the active SDK and configuration.
If your settings are correct but you still aren't getting that upload finished properly, clean your builds. Choose Build > Clean (Command-Shift-K) and click Clean. Alternatively, you can manually trash the build folder in your Project from Finder. Once you've cleaned, build again fresh.
If this does not produce an app that when zipped properly loads to iTunes Connect, quit and relaunch Xcode. I'm not kidding. This one simple trick solves more signing problems and "pink rejections of doom" than any other solution already mentioned.
You can also replace "-moz-user-select:none" with "-moz-user-select:inherit". This will inherit the style value from any parent style or from the default style if no parent style was defined.
Humm, what? ssh is not something built in to Windows like in most *nix cases.
You'd probably want to use Putty to begin with. And: http://kb.siteground.com/how_to_generate_an_ssh_key_on_windows_using_putty/
This regular expression /^(\([0-9]{3}\)\s*|[0-9]{3}\-)[0-9]{3}-[0-9]{4}$/
validates all of the following:
'123-345-3456';
'(078)789-8908';
'(078) 789-8908'; // Note the space
To break down what's happening:
(XXX)
or XXX-
, with optionally spaces after the closing parenthesis.XXX-XXX
If you want to do this in PHP:
// replace time() with the time stamp you want to add one day to
$startDate = time();
date('Y-m-d H:i:s', strtotime('+1 day', $startDate));
If you want to add the date in MySQL:
-- replace CURRENT_DATE with the date you want to add one day to
SELECT DATE_ADD(CURRENT_DATE, INTERVAL 1 DAY);
I believe python arrays just admit values. So convert it to list:
kOUT = np.zeros(N+1)
kOUT = kOUT.tolist()
Objects does not support push property, but you can save it as well using the index as key,
var tempData = {};_x000D_
for ( var index in data ) {_x000D_
if ( data[index].Status == "Valid" ) { _x000D_
tempData[index] = data; _x000D_
} _x000D_
}_x000D_
data = tempData;
_x000D_
I think this is easier if remove the object if its status is invalid, by doing.
for(var index in data){_x000D_
if(data[index].Status == "Invalid"){ _x000D_
delete data[index]; _x000D_
} _x000D_
}
_x000D_
And finally you don't need to create a var temp –
There is no need to download any binaries or files or follow difficult installation instructions.
All you really needed to do is:
sudo apt update && sudo apt install android-sdk
Update: Ubuntu 18.04 only
Use this code in drawable folder.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#3f5063" />
<corners
android:bottomLeftRadius="30dp"
android:bottomRightRadius="0dp"
android:topLeftRadius="30dp"
android:topRightRadius="0dp" />
<padding
android:bottom="2dp"
android:left="2dp"
android:right="2dp"
android:top="2dp" />
<gradient
android:angle="45"
android:centerColor="#015664"
android:endColor="#636969"
android:startColor="#2ea4e7" />
<stroke
android:width="1dp"
android:color="#000000" />
</shape>
For an external (cross-site) solution, you can use: Get contents of a link tag with JavaScript - not CSS
It uses $.ajax()
function, so it includes jquery.
Lots of answers here, but some don't take into account
-l
)*.log
instead of log*
logs
that matches log*
)Here's a solution that handles all of them:
ls 2>/dev/null -Ubad1 -- log* | wc -l
Explanation:
-U
causes ls
to not sort the entries, meaning it doesn't need to load the entire directory listing in memory-b
prints C-style escapes for nongraphic characters, crucially causing newlines to be printed as \n
.-a
prints out all files, even hidden files (not strictly needed when the glob log*
implies no hidden files)-d
prints out directories without attempting to list the contents of the directory, which is what ls
normally would do-1
makes sure that it's on one column (ls does this automatically when writing to a pipe, so it's not strictly necessary)2>/dev/null
redirects stderr so that if there are 0 log files, ignore the error message. (Note that shopt -s nullglob
would cause ls
to list the entire working directory instead.)wc -l
consumes the directory listing as it's being generated, so the output of ls
is never in memory at any point in time.--
File names are separated from the command using --
so as not to be understood as arguments to ls
(in case log*
is removed)The shell will expand log*
to the full list of files, which may exhaust memory if it's a lot of files, so then running it through grep is be better:
ls -Uba1 | grep ^log | wc -l
This last one handles extremely large directories of files without using a lot of memory (albeit it does use a subshell). The -d
is no longer necessary, because it's only listing the contents of the current directory.
A solution that I have found from here is pretty simple if you have python 3.x available in your command line. First, save a file (ctrl_c.py) with the contents:
import ctypes
import sys
kernel = ctypes.windll.kernel32
pid = int(sys.argv[1])
kernel.FreeConsole()
kernel.AttachConsole(pid)
kernel.SetConsoleCtrlHandler(None, 1)
kernel.GenerateConsoleCtrlEvent(0, 0)
sys.exit(0)
Then call:
python ctrl_c.py 12345
If that doesn't work, I recommend trying out the windows-kill project: https://github.com/alirdn/windows-kill
Updated for pandas
0.20
given that ix
is deprecated. This demonstrates not only how to use loc
, iloc
, at
, iat
, set_value
, but how to accomplish, mixed positional/label based indexing.
loc
- label based
Allows you to pass 1-D arrays as indexers. Arrays can be either slices (subsets) of the index or column, or they can be boolean arrays which are equal in length to the index or columns.
Special Note: when a scalar indexer is passed, loc
can assign a new index or column value that didn't exist before.
# label based, but we can use position values
# to get the labels from the index object
df.loc[df.index[2], 'ColName'] = 3
df.loc[df.index[1:3], 'ColName'] = 3
iloc
- position based
Similar to loc
except with positions rather that index values. However, you cannot assign new columns or indices.
# position based, but we can get the position
# from the columns object via the `get_loc` method
df.iloc[2, df.columns.get_loc('ColName')] = 3
df.iloc[2, 4] = 3
df.iloc[:3, 2:4] = 3
at
- label based
Works very similar to loc
for scalar indexers. Cannot operate on array indexers. Can! assign new indices and columns.
Advantage over loc
is that this is faster.
Disadvantage is that you can't use arrays for indexers.
# label based, but we can use position values
# to get the labels from the index object
df.at[df.index[2], 'ColName'] = 3
df.at['C', 'ColName'] = 3
iat
- position based
Works similarly to iloc
. Cannot work in array indexers. Cannot! assign new indices and columns.
Advantage over iloc
is that this is faster.
Disadvantage is that you can't use arrays for indexers.
# position based, but we can get the position
# from the columns object via the `get_loc` method
IBM.iat[2, IBM.columns.get_loc('PNL')] = 3
set_value
- label based
Works very similar to loc
for scalar indexers. Cannot operate on array indexers. Can! assign new indices and columns
Advantage Super fast, because there is very little overhead!
Disadvantage There is very little overhead because pandas
is not doing a bunch of safety checks. Use at your own risk. Also, this is not intended for public use.
# label based, but we can use position values
# to get the labels from the index object
df.set_value(df.index[2], 'ColName', 3)
set_value
with takable=True
- position based
Works similarly to iloc
. Cannot work in array indexers. Cannot! assign new indices and columns.
Advantage Super fast, because there is very little overhead!
Disadvantage There is very little overhead because pandas
is not doing a bunch of safety checks. Use at your own risk. Also, this is not intended for public use.
# position based, but we can get the position
# from the columns object via the `get_loc` method
df.set_value(2, df.columns.get_loc('ColName'), 3, takable=True)
Since the permission policy on my device is a bit paranoid (cannot adb pull
application data), I wrote a script to copy files recursively.
Note: this recursive file/folder copy script is intended for Android!
copy-r:
#! /system/bin/sh
src="$1"
dst="$2"
dir0=`pwd`
myfind() {
local fpath=$1
if [ -e "$fpath" ]
then
echo $fpath
if [ -d "$fpath" ]
then
for fn in $fpath/*
do
myfind $fn
done
fi
else
: echo "$fpath not found"
fi
}
if [ ! -z "$dst" ]
then
if [ -d "$src" ]
then
echo 'the source is a directory'
mkdir -p $dst
if [[ "$dst" = /* ]]
then
: # Absolute path
else
# Relative path
dst=`pwd`/$dst
fi
cd $src
echo "COPYING files and directories from `pwd`"
for fn in $(myfind .)
do
if [ -d $fn ]
then
echo "DIR $dst/$fn"
mkdir -p $dst/$fn
else
echo "FILE $dst/$fn"
cat $fn >$dst/$fn
fi
done
echo "DONE"
cd $dir0
elif [ -f "$src" ]
then
echo 'the source is a file'
srcn="${src##*/}"
if [ -z "$srcn" ]
then
srcn="$src"
fi
if [[ "$dst" = */ ]]
then
mkdir -p $dst
echo "copying $src" '->' "$dst/$srcn"
cat $src >$dst/$srcn
elif [ -d "$dst" ]
then
echo "copying $src" '->' "$dst/$srcn"
cat $src >$dst/$srcn
else
dstdir=${dst%/*}
if [ ! -z "$dstdir" ]
then
mkdir -p $dstdir
fi
echo "copying $src" '->' "$dst"
cat $src >$dst
fi
else
echo "$src is neither a file nor a directory"
fi
else
echo "Use: copy-r src-dir dst-dir"
echo "Use: copy-r src-file existing-dst-dir"
echo "Use: copy-r src-file dst-dir/"
echo "Use: copy-r src-file dst-file"
fi
Here I provide the source of a lightweight find
for Android because on some devices this utility is missing. Instead of myfind
one can use find
, if it is defined on the device.
Installation:
$ adb push copy-r /sdcard/
Running within adb shell
(rooted):
# . /sdcard/copy-r files/ /sdcard/files3
or
# source /sdcard/copy-r files/ /sdcard/files3
(The hash #
above is the su
prompt, while .
is the command that causes the shell to run the specified file, almost the same as source
).
After copying, I can adb pull
the files from the sd-card.
Writing files to the app directory was trickier, I tried to set r/w permissions on files
and its subdirectories, it did not work (well, it allowed me to read, but not write, which is strange), so I had to do:
String[] cmdline = { "sh", "-c", "source /sdcard/copy-r /sdcard/files4 /data/data/com.example.myapp/files" };
try {
Runtime.getRuntime().exec(cmdline);
} catch (IOException e) {
e.printStackTrace();
}
in the application's onCreate().
PS just in case someone needs the code to unprotect application's directories to enable adb shell
access on a non-rooted phone,
setRW(appContext.getFilesDir().getParentFile());
public static void setRW(File... files) {
for (File file : files) {
if (file.isDirectory()) {
setRW(file.listFiles()); // Calls same method again.
} else {
}
file.setReadable(true, false);
file.setWritable(true, false);
}
}
although for some unknown reason I could read but not write.
A cleaner alternative of putting your config file into a subfolder of src/main/resources would be to enhance your classpath locations. This is extremely easy to do with Maven.
For instance, place your property file in a new folder src/main/config, and add the following to your pom:
<build>
<resources>
<resource>
<directory>src/main/config</directory>
</resource>
</resources>
</build>
From now, every files files under src/main/config is considered as part of your classpath (note that you can exclude some of them from the final jar if needed: just add in the build section:
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<excludes>
<exclude>my-config.properties</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
so that my-config.properties can be found in your classpath when you run your app from your IDE, but will remain external from your jar in your final distribution).
Clean way which I found useful
git revert --no-commit HEAD~3..
This command reverts last 3 commits with only one commit.
Also doesn't rewrite history.
The ..
helps create a range. Meaning HEAD~3..
is the same as HEAD~3..HEAD
For Python 3:
import urllib.request, urllib.error
url = 'http://www.google.com/asdfsf'
try:
conn = urllib.request.urlopen(url)
except urllib.error.HTTPError as e:
# Return code error (e.g. 404, 501, ...)
# ...
print('HTTPError: {}'.format(e.code))
except urllib.error.URLError as e:
# Not an HTTP-specific error (e.g. connection refused)
# ...
print('URLError: {}'.format(e.reason))
else:
# 200
# ...
print('good')
If checking for truth:
if foo
For false:
if not foo
For none:
if foo is None
For non-none:
if foo is not None
For getattr()
the correct behaviour is not to return None
, but raise an AttributError
error instead - unless your class is something like defaultdict
.
The row_number() function would be the best approach to this problem.
UPDATE T
SET T.Number = R.rowNum
FROM Test T
JOIN (
SELECT T2.id,row_number() over (order by T2.Id desc) rowNum from Test T2
) R on T.id=R.id
This question is kind of old and in July 2011 Google released the Compatibility Package, revision 3) which includes the ViewPager
that works with Android 1.6 upwards. The GestureListener
answers posted for this question don't feel very elegant on Android. If you're looking for the code used in switching between photos in the Android Gallery or switching views in the new Play Market app then it's definitely ViewPager
.
Here's some links for more info:
You are doing it right. The empty code block is what is causing your issue. It's not the condition structure :)
DECLARE @StartDate AS DATETIME
DECLARE @EndDate AS DATETIME
SET @StartDate = NULL
SET @EndDate = NULL
IF (@StartDate IS NOT NULL AND @EndDate IS NOT NULL)
BEGIN
print 'yoyoyo'
END
IF (@StartDate IS NULL AND @EndDate IS NULL AND 1=1 AND 2=2)
BEGIN
print 'Oh hey there'
END
I had to use a similar solution for Portuguese (Brazil):
<?php
$scheduled_day = '2018-07-28';
$days = ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb'];
$day = date('w',strtotime($scheduled_day));
$scheduled_day = date('d-m-Y', strtotime($scheduled_day))." ($days[$day])";
// provides 28-07-2018 (Sáb)
No you can't, as Mladen Prajdic said. Think of a view as a "static filter" on a table or a combination of tables. For example: a view may combine tables Order
and Customer
so you get a new "table" of rows from Order
along with new columns containing the customer's name and the customer number (combination of tables). Or you might create a view that selects only unprocessed orders from the Order
table (static filter).
You'd then select from the view like you would select from any other "normal" table - all "non-static" filtering must be done outside the view (like "Get all the orders for customers called Miller" or "Get unprocessed orders that came in on Dec 24th").
:javascript
$(document).ready( function() {
$('body').addClass( 'test' );
} );
Docs: http://haml.info/docs/yardoc/file.REFERENCE.html#javascript-filter
I just had to do import Foundation
!
I was using Kitura for Swift server side and kept forgetting this!
Not a direct answer to this question but rather to the "issue" of $event.currentTarget
apparently be set to null.
This is due to the fact that console.log shows deep mutable objects at the last state of execution, not at the state when console.log was called.
You can check this for more information: Consecutive calls to console.log produce inconsistent results
The copy
command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.
Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).
I tried a variation of your command as follows in SQL*Plus (with no errors):
copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;
After I executed the above statement, I also truncate the new_emp table and executed this command:
copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;
With SQL Developer, you could do the following to perform a similar approach to copying objects:
On the tool bar, select Tools>Database copy.
Identify source and destination connections with the copy options you would like.
For object type, select table(s).
The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).
Map.Entry
These built-in classes are an option, too. Both implement the Map.Entry
interface.
If you set the style table-layout: fixed;
on your table, you can override the browser's automatic column resizing. The browser will then set column widths based on the width of cells in the first row of the table. Change your <thead>
to <caption>
and remove the <td>
inside of it, and then set fixed widths for the cells in <tbody>
.
This answer might seem silly but I had my laptop's power plan set to something other than High performance (in Windows). I would constantly get out of memory warnings in Visual Studio and things would run a bit slow. After I changed the power setting to High performance, I no longer see any problem.
Yes it is correct. you can do it with an inner class.
The <TouchableHighlight>
element is the source of the error. The <TouchableHighlight>
element must have a child element.
Try running the code like this:
render() {
const {height, width} = Dimensions.get('window');
return (
<View style={styles.container}>
<Image
style={{
height:height,
width:width,
}}
source={require('image!foo')}
resizeMode='cover'
/>
<TouchableHighlight style={styles.button}>
<Text> This text is the target to be highlighted </Text>
</TouchableHighlight>
</View>
);
}
The Wikipedia page on sorting algorithms has a great comparison chart.
http://en.wikipedia.org/wiki/Sorting_algorithm#Comparison_of_algorithms
Update: In an effort to answer my own question, here is what I've been able to uncover so far. If anyone else out there has something, I'd still be interested to find out more.
Based on JSON Schema
Commercial (No endorsement intended or implied, may or may not meet requirement)
jQuery
YAML
See Also
Using getLines() on scala.io.Source discards what characters were used for line terminators (\n, \r, \r\n, etc.)
The following should preserve it character-for-character, and doesn't do excessive string concatenation (performance problems):
def fileToString(file: File, encoding: String) = {
val inStream = new FileInputStream(file)
val outStream = new ByteArrayOutputStream
try {
var reading = true
while ( reading ) {
inStream.read() match {
case -1 => reading = false
case c => outStream.write(c)
}
}
outStream.flush()
}
finally {
inStream.close()
}
new String(outStream.toByteArray(), encoding)
}
I had the same problem and any solution worked for me.
The cause was I am using allowRequest to accept or reject the connection using a token I pass in a query parameter.
I have a typo in the query parameter name in the client side, so the connection was always rejected, but the browser complained about cors...
As soon as I fixed the typo, it started working as expected, and I don't need to use anything extra, the global express cors settings is enough.
So, if anything is working for you, and you are using allowRequest, check that this function is working properly, because the errors it throws shows up as cors errors in the browser. Unless you add there the cors headers manually when you want to reject the connection, I guess.
Use the FormBorderStyle
property. Make it FixedSingle
:
this.FormBorderStyle = FormBorderStyle.FixedSingle;
{{ word|striptags('<b>,<a>,<pre>')|raw }}
if you want to allow multiple tags
If you want the structure of a particular data table(dataTable1) with column headers (without data) into another data table(dataTable2), you can follow the below code:
DataTable dataTable2 = dataTable1.Clone();
dataTable2.Clear();
Now you can fill dataTable2 according to your condition. :)
?php
/* Database config */
$db_host = 'localhost';
$db_user = '~';
$db_pass = '~';
$db_database = 'banners';
/* End config */
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_database);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
AndAlso is much like And, except it works like && in C#, C++, etc.
The difference is that if the first clause (the one before AndAlso) is true, the second clause is never evaluated - the compound logical expression is "short circuited".
This is sometimes very useful, e.g. in an expression such as:
If Not IsNull(myObj) AndAlso myObj.SomeProperty = 3 Then
...
End If
Using the old And in the above expression would throw a NullReferenceException if myObj were null.
for some applications, for example google chrome, they store it under /opt. you can follow the above instruction using dpkg -l to get the correct naming then dpkg -L to get the detail.
hope it helps
I know this is old, but it's the first example of saving form data to a txt file I found in a quick search. So I've made a couple edits to the above code that makes it work more smoothly. It's now easier to add more fields, including the radio button as @user6573234 requested.
https://jsfiddle.net/cgeiser/m0j7Lwyt/1/
<!DOCTYPE html>
<html>
<head>
<style>
form * {
display: block;
margin: 10px;
}
</style>
<script language="Javascript" >
function download() {
var filename = window.document.myform.docname.value;
var name = window.document.myform.name.value;
var text = window.document.myform.text.value;
var problem = window.document.myform.problem.value;
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' +
"Your Name: " + encodeURIComponent(name) + "\n\n" +
"Problem: " + encodeURIComponent(problem) + "\n\n" +
encodeURIComponent(text));
pom.setAttribute('download', filename);
pom.style.display = 'none';
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom);
}
</script>
</head>
<body>
<form name="myform" method="post" >
<input type="text" id="docname" value="test.txt" />
<input type="text" id="name" placeholder="Your Name" />
<div style="display:unblock">
Option 1 <input type="radio" value="Option 1" onclick="getElementById('problem').value=this.value; getElementById('problem').show()" style="display:inline" />
Option 2 <input type="radio" value="Option 2" onclick="getElementById('problem').value=this.value;" style="display:inline" />
<input type="text" id="problem" />
</div>
<textarea rows=3 cols=50 id="text" />Please type in this box.
When you click the Download button, the contents of this box will be downloaded to your machine at the location you specify. Pretty nifty. </textarea>
<input id="download_btn" type="submit" class="btn" style="width: 125px" onClick="download();" />
</form>
</body>
</html>
You can call tesseract API function from C code:
#include <tesseract/baseapi.h>
#include <tesseract/ocrclass.h>; // ETEXT_DESC
using namespace tesseract;
class TessAPI : public TessBaseAPI {
public:
void PrintRects(int len);
};
...
TessAPI *api = new TessAPI();
int res = api->Init(NULL, "rus");
api->SetAccuracyVSpeed(AVS_MOST_ACCURATE);
api->SetImage(data, w0, h0, bpp, stride);
api->SetRectangle(x0,y0,w0,h0);
char *text;
ETEXT_DESC monitor;
api->RecognizeForChopTest(&monitor);
text = api->GetUTF8Text();
printf("text: %s\n", text);
printf("m.count: %s\n", monitor.count);
printf("m.progress: %s\n", monitor.progress);
api->RecognizeForChopTest(&monitor);
text = api->GetUTF8Text();
printf("text: %s\n", text);
...
api->End();
And build this code:
g++ -g -I. -I/usr/local/include -o _test test.cpp -ltesseract_api -lfreeimageplus
(i need FreeImage for picture loading)
File -> Settings -> Editor -> General -> Appearance check "Show Line Numbers"
This is the current location as of phpStorm 8.0.2 on Ubuntu 14.04
iOS makes phone numbers clickable by defaults (for obvious reasons). Of course, that adds an extra tag which is overriding your styling if your phone number isn’t already a link.
To fix it, try adding this to your stylesheet: a[href^=tel] { color: inherit; text-decoration: none; }
That should keep your phone numbers styled as you expect without adding extra markup.
Try this:
printf '\n%s\n' 'I want this on a new line!'
That allows you to separate the formatting from the actual text. You can use multiple placeholders and multiple arguments.
quantity=38; price=142.15; description='advanced widget'
$ printf '%8d%10.2f %s\n' "$quantity" "$price" "$description"
38 142.15 advanced widget
Yes you can; it works on Android too:
tel: phone_number
Calls the entered phone number. Valid telephone numbers as defined in the IETF RFC 3966 are accepted. Valid examples include the following:* tel:2125551212 * tel: (212) 555 1212
The Android browser uses the Phone app to handle the “tel” scheme, as defined by RFC 3966.
Clicking a link like:
<a href="tel:2125551212">2125551212</a>
on Android will bring up the Phone app and pre-enter the digits for 2125551212 without autodialing.
Have a look to RFC3966
As I found the default Bootstrap <hr/>
size unsightly, here's some simple HTML and CSS to balance out the element visually:
HTML:
<hr class="half-rule"/>
CSS:
.half-rule {
margin-left: 0;
text-align: left;
width: 50%;
}
I had a problem with most of these solutions . The fact that I couldn't find the bin folder in my c drive. I tried solution offered here " https://www.howtosolutions.net/2017/08/fixing-mysql-10061-error-after-migration-of-database-files/ "and vwala "welcome to the mysql monitor ...."
You need to add a name
attribute to your dropdown list, then you need to add a required
attribute, and then you can reference the error using myForm.[input name].$error.required
:
HTML:
<form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
<input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
<select name="service_id" class="Sitedropdown" style="width: 220px;"
ng-model="ServiceID"
ng-options="service.ServiceID as service.ServiceName for service in services"
required>
<option value="">Select Service</option>
</select>
<span ng-show="myForm.service_id.$error.required">Select service</span>
</form>
Controller:
function Ctrl($scope) {
$scope.services = [
{ServiceID: 1, ServiceName: 'Service1'},
{ServiceID: 2, ServiceName: 'Service2'},
{ServiceID: 3, ServiceName: 'Service3'}
];
$scope.save = function(myForm) {
console.log('Selected Value: '+ myForm.service_id.$modelValue);
alert('Data Saved! without validate');
};
}
Here's a working plunker.
Try also the pytracemalloc project which provides the memory usage per Python line number.
EDIT (2014/04): It now has a Qt GUI to analyze snapshots.
In Angular Http 7, the DELETE method accepts as a second parameter options
object in which you provide the request parameters as params
object along with the headers
object. This is different than Angular6.
See example:
this.httpClient.delete('https://api-url', {
headers: {},
params: {
'param1': paramValue1,
'param2': paramValue2
}
});
$(this).parent().css('z-index',3000);
The easy way to change version is first to check your available version using nvm ls then select version from the list nvm use version
You can either have the newly inserted ID being output to the SSMS console like this:
INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')
You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar()
(instead of .ExecuteNonQuery()
) to read the resulting ID
back.
Or if you need to capture the newly inserted ID
inside T-SQL (e.g. for later further processing), you need to create a table variable:
DECLARE @OutputTbl TABLE (ID INT)
INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')
This way, you can put multiple values into @OutputTbl
and do further processing on those. You could also use a "regular" temporary table (#temp
) or even a "real" persistent table as your "output target" here.
states_list = states.split(' ')
In regards to your edit:
from random import choice
random_state = choice(states_list)
For your first question try
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
(available since API 8)
To access individual files in this directory use either File.list() or File.listFiles(). Seems that reporting download progress is only possible in notification, see here.
Have you looked at the EXIF data of the images? It may know the orientation of the camera when the picture was taken.
On laravel 5.6 it has a very simple solution:
User::where('username', $username)->first()->groupName;
It will return groupName as a string.
You can run a container that restart always by:
$ docker run -dit --restart unless-stopped <image name OR image hash>
If you want to change a running container's configs, you should update it by:
$ docker update --restart=<options> <container ID OR name>
And if you want to see current policy of the container, run the following command before above at the first place:
docker inspect gateway | grep RestartPolicy -A 3
After all, Not to forget to make installed docker daemon enable at system boot by:
$ systemctl enable docker
To see a full list of restart policies, see: Restart Policies
For those who develop in Android, use TextUtils.
String items = TextUtils.join("", arr);
Assuming arr is of type String[] arr= {"1","2","3"};
The output would be 123
I suspect the condition you are looking for is DUP_VAL_ON_INDEX
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
DBMS_OUTPUT.PUT_LINE('OH DEAR. I THINK IT IS TIME TO PANIC!')
LENGTH()
does return the string length (just verified). I suppose that your data is padded with blanks - try
SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;
instead.
As OraNob
mentioned, another cause could be that CHAR
is used in which case LENGTH()
would also return the column width, not the string length. However, the TRIM()
approach also works in this case.
I just want to clarify, because some of the answers refer to venv
and others refer to virtualenv
.
Use of the -p
or --python
flag is supported on virtualenv
, but not on venv
. If you have more than one Python version and you want to specify which one to create the venv
with, do it on the command line, like this:
malikarumi@Tetuoan2:~/Projects$ python3.6 -m venv {path to pre-existing dir you want venv in}
You can of course upgrade with venv
as others have pointed out, but that assumes you have already upgraded the Python that was used to create that venv
in the first place. You can't upgrade to a Python version you don't already have on your system somewhere, so make sure to get the version you want, first, then make all the venvs you want from it.
It seems as of now, the only solution is still to install SublimeREPL.
To extend on Raghav's answer, it can be quite annoying to have to go into the Tools->SublimeREPL->Python->Run command every time you want to run a script with input, so I devised a quick key binding that may be handy:
To enable it, go to Preferences->Key Bindings - User, and copy this in there:
[
{"keys":["ctrl+r"] ,
"caption": "SublimeREPL: Python - RUN current file",
"command": "run_existing_window_command",
"args":
{
"id": "repl_python_run",
"file": "config/Python/Main.sublime-menu"
}
},
]
Naturally, you would just have to change the "keys" argument to change the shortcut to whatever you'd like.
The LGoodDatePicker library includes a (swing) DatePicker component, which allows the user to choose dates from a calendar. (By default, the users can also type dates from the keyboard, but keyboard entry can be disabled if desired). The DatePicker has automatic data validation, which means (among other things) that any date that the user enters will always be converted to your desired date format.
Fair disclosure: I'm the primary developer.
Since the DatePicker is a swing component, you can add it to any other swing container including (in your scenario) the cells of a JTable.
The most commonly used date formats are automatically supported, and additional date formats can be added if desired.
To enforce your desired date format, you would most likely want to set your chosen format to be the default "display format" for the DatePicker. Formats can be specified by using the Java 8 DateTimeFormatter Patterns. No matter what the user types (or clicks), the date will always be converted to the specified format as soon as the user is done.
Besides the DatePicker, the library also has the TimePicker and DateTimePicker components. I pasted screenshots of all the components (and the demo program) below.
The library can be installed into your Java project from the project release page.
The project home page is on Github at:
https://github.com/LGoodDatePicker/LGoodDatePicker .
One possible C loop would be:
#include <stdio.h>
int main()
{
int c;
while ((c = getchar()) != EOF)
{
/*
** Do something with c, such as check against '\n'
** and increment a line counter.
*/
}
}
For now, I would ignore feof
and similar functions. Exprience shows that it is far too easy to call it at the wrong time and process something twice in the belief that eof hasn't yet been reached.
Pitfall to avoid: using char
for the type of c. getchar
returns the next character cast to an unsigned char
and then to an int
. This means that on most [sane] platforms the value of EOF
and valid "char
" values in c
don't overlap so you won't ever accidentally detect EOF
for a 'normal' char
.
Using a regular expression you can count the number of lines as
str.split(/\r\n|\r|\n/).length
Alternately you can try split method as below.
var lines = $("#ptest").val().split("\n");
alert(lines.length);
working solution: http://jsfiddle.net/C8CaX/
I encountered a similar problem only with a nested img in my anchor:
<a href="some/link">
<img src="some/src">
</a>
When I applied
@media print {
a[href]:after {
content: none !important;
}
}
I lost my img and the entire anchor width for some reason, so instead I used:
@media print {
a[href]:after {
visibility: hidden;
}
}
which worked perfectly.
Bonus tip: inspect print preview
You can't ref
a property, but if your functions need both get
and set
access you can pass around an instance of a class with a property defined:
public class Property<T>
{
public delegate T Get();
public delegate void Set(T value);
private Get get;
private Set set;
public T Value {
get {
return get();
}
set {
set(value);
}
}
public Property(Get get, Set set) {
this.get = get;
this.set = set;
}
}
Example:
class Client
{
private string workPhone; // this could still be a public property if desired
public readonly Property<string> WorkPhone; // this could be created outside Client if using a regular public property
public int AreaCode { get; set; }
public Client() {
WorkPhone = new Property<string>(
delegate () { return workPhone; },
delegate (string value) { workPhone = value; });
}
}
class Usage
{
public void PrependAreaCode(Property<string> phone, int areaCode) {
phone.Value = areaCode.ToString() + "-" + phone.Value;
}
public void PrepareClientInfo(Client client) {
PrependAreaCode(client.WorkPhone, client.AreaCode);
}
}
It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.
Edit: This is what the forums say:
By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.
To disable:
/system/bin/bugmailer.sh must be deleted/renamed.
There should be a folder on your SD card called "bug reports".
Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948
And this one: http://forum.xda-developers.com/showthread.php?t=1405639
Assuming a simple table:
CREATE TABLE dbo.foo(ID INT IDENTITY(1,1), name SYSNAME);
We can capture IDENTITY
values in a table variable for further consumption.
DECLARE @IDs TABLE(ID INT);
-- minor change to INSERT statement; add an OUTPUT clause:
INSERT dbo.foo(name)
OUTPUT inserted.ID INTO @IDs(ID)
SELECT N'Fred'
UNION ALL
SELECT N'Bob';
SELECT ID FROM @IDs;
The nice thing about this method is (a) it handles multi-row inserts (SCOPE_IDENTITY()
only returns the last value) and (b) it avoids this parallelism bug, which can lead to wrong results, but so far is only fixed in SQL Server 2008 R2 SP1 CU5.
You can check if the array is empty by retrieving total elements count using JScript's VBArray()
object (works with arrays of variant type, single or multidimensional):
Sub Test()
Dim a() As Variant
Dim b As Variant
Dim c As Long
' Uninitialized array of variant
' MsgBox UBound(a) ' gives 'Subscript out of range' error
MsgBox GetElementsCount(a) ' 0
' Variant containing an empty array
b = Array()
MsgBox GetElementsCount(b) ' 0
' Any other types, eg Long or not Variant type arrays
MsgBox GetElementsCount(c) ' -1
End Sub
Function GetElementsCount(aSample) As Long
Static oHtmlfile As Object ' instantiate once
If oHtmlfile Is Nothing Then
Set oHtmlfile = CreateObject("htmlfile")
oHtmlfile.parentWindow.execScript ("function arrlength(arr) {try {return (new VBArray(arr)).toArray().length} catch(e) {return -1}}"), "jscript"
End If
GetElementsCount = oHtmlfile.parentWindow.arrlength(aSample)
End Function
For me it takes about 0.3 mksec for each element + 15 msec initialization, so the array of 10M elements takes about 3 sec. The same functionality could be implemented via ScriptControl
ActiveX (it is not available in 64-bit MS Office versions, so you can use workaround like this).
C# extension method code, focus element, enter text, call change().
public static void EnterText(this IWebDriver driver, IWebElement element, string textToEnter)
{
var js = (IJavaScriptExecutor)driver;
js.ExecuteScript("arguments[0].focus();", element);
js.ExecuteScript("arguments[0].setAttribute('value', arguments[1])", element, textToEnter);
js.ExecuteScript("$(arguments[0]).change();", element);
}
Called by:
driver.EnterText(element, text);
Something like that :
options(digits=2)
Definition of digits option :
digits: controls the number of digits to print when printing numeric values.
Simple math.
double result = ((double)number) / 100.0;
Although you may want to use decimal
rather than double
: decimal vs double! - Which one should I use and when?
Erik Aigner,
Please use $dirty(The field has been modified) and $invalid (The field content is not valid).
Please check below examples for angular form validation
1)
Validation example HTML for user enter inputs:
<form ng-app="myApp" ng-controller="validateCtrl" name="myForm" novalidate>
<p>Email:<br>
<input type="email" name="email" ng-model="email" required>
<span ng-show="myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">Email is required.</span>
<span ng-show="myForm.email.$error.email">Invalid email address.</span>
</span>
</p>
</form>
2)
Validation example HTML/Js for user submits :
<form ng-app="myApp" ng-controller="validateCtrl" name="myForm" novalidate form-submit-validation="">
<p>Email:<br>
<input type="email" name="email" ng-model="email" required>
<span ng-show="submitted || myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">Email is required.</span>
<span ng-show="myForm.email.$error.email">Invalid email address.</span>
</span>
</p>
<p>
<input type="submit">
</p>
</form>
Custom Directive :
app.directive('formSubmitValidation', function () {
return {
require: 'form',
compile: function (tElem, tAttr) {
tElem.data('augmented', true);
return function (scope, elem, attr, form) {
elem.on('submit', function ($event) {
scope.$broadcast('form:submit', form);
if (!form.$valid) {
$event.preventDefault();
}
scope.$apply(function () {
scope.submitted = true;
});
});
}
}
};
})
3)
you don't want use directive use ng-change function like below
<form ng-app="myApp" ng-controller="validateCtrl" name="myForm" novalidate ng-change="submitFun()">
<p>Email:<br>
<input type="email" name="email" ng-model="email" required>
<span ng-show="submitted || myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">Email is required.</span>
<span ng-show="myForm.email.$error.email">Invalid email address.</span>
</span>
</p>
<p>
<input type="submit">
</p>
</form>
Controller SubmitFun() JS:
var app = angular.module('example', []);
app.controller('exampleCntl', function($scope) {
$scope.submitFun = function($event) {
$scope.submitted = true;
if (!$scope.myForm.$valid)
{
$event.preventDefault();
}
}
});
There's a kind of hack-tastic way to do it if you have php enabled on your server. Change this line:
url: 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml',
to this line:
url: '/path/to/phpscript.php',
and then in the php script (if you have permission to use the file_get_contents() function):
<?php
header('Content-type: application/xml');
echo file_get_contents("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
?>
Php doesn't seem to mind if that url is from a different origin. Like I said, this is a hacky answer, and I'm sure there's something wrong with it, but it works for me.
Edit: If you want to cache the result in php, here's the php file you would use:
<?php
$cacheName = 'somefile.xml.cache';
// generate the cache version if it doesn't exist or it's too old!
$ageInSeconds = 3600; // one hour
if(!file_exists($cacheName) || filemtime($cacheName) > time() + $ageInSeconds) {
$contents = file_get_contents('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
file_put_contents($cacheName, $contents);
}
$xml = simplexml_load_file($cacheName);
header('Content-type: application/xml');
echo $xml;
?>
Caching code take from here.
You can use Apache Commons Configuration library. The best part of this is, it won't even mess up the properties file and keeps it intact (even comments).
PropertiesConfiguration conf = new PropertiesConfiguration("propFile.properties");
conf.setProperty("key", "value");
conf.save();
If you remove the check for the ModelsState.IsValid and let it error, if you copy this line ((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors
and paste it in the watch section in Visual Studio it will give you exactly what the error is. Saves a lot of time checking where the error is.
Just to add that there is also java.text.MessageFormat with the benefit of having numeric argument indexes.
Appending the 1st example from the documentation
int planet = 7;
String event = "a disturbance in the Force";
String result = MessageFormat.format(
"At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
planet, new Date(), event);
Result:
At 12:30 PM on Jul 3, 2053, there was a disturbance in the Force on planet 7.
from datetime import date, timedelta
first_day_of_current_month = date.today().replace(day=1)
last_day_of_previous_month = first_day_of_current_month - timedelta(days=1)
print "Previous month:", last_day_of_previous_month.month
Or:
from datetime import date, timedelta
prev = date.today().replace(day=1) - timedelta(days=1)
print prev.month
<select name="aa" onchange="report(this.value)">
<option value="">Please select</option>
<option value="daily">daily</option>
<option value="monthly">monthly</option>
</select>
using
function report(period) {
if (period=="") return; // please select - possibly you want something else here
const report = "script/"+((period == "daily")?"d":"m")+"_report.php";
loadXMLDoc(report,'responseTag');
document.getElementById('responseTag').style.visibility='visible';
document.getElementById('list_report').style.visibility='hidden';
document.getElementById('formTag').style.visibility='hidden';
}
Unobtrusive version:
<select id="aa" name="aa">
<option value="">Please select</option>
<option value="daily">daily</option>
<option value="monthly">monthly</option>
</select>
using
window.addEventListener("load",function() {
document.getElementById("aa").addEventListener("change",function() {
const period = this.value;
if (period=="") return; // please select - possibly you want something else here
const report = "script/"+((period == "daily")?"d":"m")+"_report.php";
loadXMLDoc(report,'responseTag');
document.getElementById('responseTag').style.visibility='visible';
document.getElementById('list_report').style.visibility='hidden';
document.getElementById('formTag').style.visibility='hidden';
});
});
jQuery version - same select with ID
$(function() {
$("#aa").on("change",function() {
const period = this.value;
if (period=="") return; // please select - possibly you want something else here
var report = "script/"+((period == "daily")?"d":"m")+"_report.php";
loadXMLDoc(report,'responseTag');
$('#responseTag').show();
$('#list_report').hide();
$('#formTag').hide();
});
});
Just intall and enable Coffee-Bytes plugin (Eclipse)
The thing with your method is that you clutter your HTML with javascript. If you put your javascript in an external file you can access your HTML unobtrusive and this is much neater.
Lateron you can expand your code with addEventListener/attackEvent(IE) to prevent memory leaks.
This is without jQuery
<a href="123.com" id="elementid">link</a>
window.onload = function () {
var el = document.getElementById('elementid');
el.onclick = function (e) {
var ev = e || window.event;
// here u can use this or el as the HTML node
}
}
You say you want to manipulate it with jQuery. So you can use jQuery. Than it is even better to do it like this:
// this is the window.onload startup of your JS as in my previous example. The difference is
// that you can add multiple onload functions
$(function () {
$('a#elementid').bind('click', function (e) {
// "this" points to the <a> element
// "e" points to the event object
});
});
WebClient is a higher-level abstraction built on top of HttpWebRequest to simplify the most common tasks. For instance, if you want to get the content out of an HttpWebResponse, you have to read from the response stream:
var http = (HttpWebRequest)WebRequest.Create("http://example.com");
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
With WebClient, you just do DownloadString
:
var client = new WebClient();
var content = client.DownloadString("http://example.com");
Note: I left out the using
statements from both examples for brevity. You should definitely take care to dispose your web request objects properly.
In general, WebClient is good for quick and dirty simple requests and HttpWebRequest is good for when you need more control over the entire request.
df['original_category'] = df['original_category'].apply(lambda x:x.lower())
One way to do this is using a shared service.
However I find the following solution much simpler, it allows to share data between 2 siblings.(I tested this only on Angular 5)
In you parent component template:
<!-- Assigns "AppSibling1Component" instance to variable "data" -->
<app-sibling1 #data></app-sibling1>
<!-- Passes the variable "data" to AppSibling2Component instance -->
<app-sibling2 [data]="data"></app-sibling2>
app-sibling2.component.ts
import { AppSibling1Component } from '../app-sibling1/app-sibling1.component';
...
export class AppSibling2Component {
...
@Input() data: AppSibling1Component;
...
}
public class FindDigitFromString
{
public static void main(String[] args)
{
String s=" Hi How Are You 11 ";
String s1=s.replaceAll("[^0-9]+", "");
//*replacing all the value of string except digit by using "[^0-9]+" regex.*
System.out.println(s1);
}
}
Output: 11
My best solution (so far) for calculating the number of days difference:
// This assumes that you already have two Date objects: startDate, endDate
// Also, that you want to ignore any time portions
Calendar startCale=new GregorianCalendar();
Calendar endCal=new GregorianCalendar();
startCal.setTime(startDate);
endCal.setTime(endDate);
endCal.add(Calendar.YEAR,-startCal.get(Calendar.YEAR));
endCal.add(Calendar.MONTH,-startCal.get(Calendar.MONTH));
endCal.add(Calendar.DATE,-startCal.get(Calendar.DATE));
int daysDifference=endCal.get(Calendar.DAY_OF_YEAR);
Note, however, that this assumes less than a year's difference!
I think I have a solution:
In your personal style sheet page, assign the width & height to match your image dimensions.
Create an additional separate "class" on that top div that appropriates the space with spans...(Shown below)
<div class="span6 columns" class="carousel">
<div id="myCarousel" class="carousel slide">
<div class="carousel-inner">
<div class="item active">
Without touching the bootstrap.css, in your own style sheet, call "carousel"(or whatever label you choose) to match the width and height of your original pix!
.carousel {
width: 320px;
height: 200px;
}
So in my case, I am using small 320x200 images to carousel with. There is probably preset dimensions in the bootstrap.css, but I don't like changing that so I can try to stay current with future releases. Hope this helps~~
I run
#react-native run-android
from terminal and met that problem. For manually, go to Android Studio -> Android SDK -> SDK Platform Click Show Packages Detail and check :
+ Google APIs
+ Android SDK Platform 23
+ Intel x86 Atom_64 System Image
+ Google APIs Intel x86 Atom_64 System Image
When install packages, check accept license => can solve the problem.
As you would like to get argument (United
) for which value is given (5
) you might also consider using bidirectional map (e.g. provided by Guava: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/BiMap.html).
SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'database_name';
Try this query:
SELECT *
FROM table
WHERE MONTH(FROM_UNIXTIME(columnName))= MONTH(CURDATE())
$day_number = date('N', $date);
This will return a 1 for Monday to 7 for Sunday, for the date that is stored in $date. Omitting the second argument will cause date() to return the number for the current day.