None of the configuration above worked for me on my CentOS 7 server. After hours of searching, that's what worked for me:
Edit file phpMyAdmin.conf
sudo nano /etc/httpd/conf.d/phpMyAdmin.conf
And replace this at the top:
<Directory /usr/share/phpMyAdmin/>
AddDefaultCharset UTF-8
<IfModule mod_authz_core.c>
# Apache 2.4
<RequireAny>
#Require ip 127.0.0.1
#Require ip ::1
Require all granted
</RequireAny>
</IfModule>
<IfModule !mod_authz_core.c>
# Apache 2.2
Order Deny,Allow
Deny from All
Allow from 127.0.0.1
Allow from ::1
</IfModule>
</Directory>
Daniel's answer is probably the most ideal one as it doesn't involve changing OS files. However, I found myself in a situation where I needed a 3rd party program which invoked python by calling usr/bin/python
, but required Python 2.7.16, while the default Python was 2.7.5. That meant I had to make usr/bin/python
point to a Python version of 2.7.16 version, which meant that yum
wouldn't work.
What I ended up doing is editing the file /usr/bin/yum
and replacing the shebang there to use to the system default Python (in my case, that meant changing #! /usr/bin/python
to #! /usr/bin/python2
). However, after that running yum
gave me an error:
ImportError: No module named urlgrabber.grabber
I solved that by replacing the shebang in /usr/libexec/urlgrabber-ext-down
the same way as in /usr/bin/yum
. I.e., #! /usr/bin/python
to #! /usr/bin/python2
. After that yum
worked.
This is a hack and should be used with care. As mentioned in other comments, modifying OS files should be last resort only.
do the following:
sudo nano /etc/yum.repos.d/CentOS-Base.repo
under the section updates
, comment out the mirrorlist line (put a #
in front of the line), then on a new line write:
baseurl=http://centos.intergenia.de/$releasever/updates/$basearch/
now try:
yum install php-mbstring
(afterwards you'll probably want to uncomment the mirrorlist and comment out the baseurl)
I dug myself into a slight variant on this problem by mistakenly running the setfacl
command. I ran:
sudo setfacl -m user:nginx:r /home/foo/bar
I abandoned this route in favor of adding nginx
to the foo
group, but that custom ACL was foiling nginx's attempts to access the file. I cleared it by running:
sudo setfacl -b /home/foo/bar
And then nginx was able to access the files.
On newer versions of yum, this information is stored in the "yumdb" when the package is installed. This is the only 100% accurate way to get the information, and you can use:
yumdb search from_repo repoid
(or repoquery and grep -- don't grep yum output). However the command "find-repos-of-install" was part of yum-utils for a while which did the best guess without that information:
http://james.fedorapeople.org/yum/commands/find-repos-of-install.py
As floyd said, a lot of repos. include a unique "dist" tag in their release, and you can look for that ... however from what you said, I guess that isn't the case for you?
First a password login has to be established to remote machine
you have to enable a password login by enabling the property ie) PasswordAuthentication yes in sshd_config file.Then restart the sshd service and copy the pub key to remote server (aws ec2 in my case), key will be copied without any error
This is an addition to the answer by Abdull somewhere in this thread:
I had to modify instead of adding a port
semanage port -m -t http_port_t -p tcp 5000
because I get this error on adding the port
ValueError: Port tcp/5000 already defined
For my point of view, First thing is to install soap into Centos
yum install php-soap
Second, see if the soap package exist or not
yum search php-soap
third, thus you must see some result of soap package you installed, now type a command in your terminal in the root folder for searching the location of soap for specific path
find -name soap.so
fourth, you will see the exact path where its installed/located, simply copy the path and find the php.ini to add the extension path,
usually the path of php.ini file in centos 6 is in
/etc/php.ini
fifth, add a line of code from below into php.ini file
extension='/usr/lib/php/modules/soap.so'
and then save the file and exit.
sixth run apache restart command in Centos. I think there is two command that can restart your apache ( whichever is easier for you )
service httpd restart
OR
apachectl restart
Lastly, check phpinfo() output in browser, you should see SOAP section where SOAP CLIENT, SOAP SERVER etc are listed and shown Enabled.
Did you restart the server after you changed the config file?
Can you telnet to the server from a different machine?
Can you telnet to the server from the server itself?
telnet <ip address> 80
telnet localhost 80
This was the only solution what worked for me:
Install Vagrant plugin: vagrant-vbguest, which can keep your VirtualBox Guest Additions up to date.
vagrant plugin install vagrant-vbguest
Source: https://github.com/aidanns/vagrant-reload/issues/4#issuecomment-230134083
If only names of regular files immediately contained within a directory (assume it's ~/dirs
) are needed, you can do
find ~/docs -type f -maxdepth 1 > filenames.txt
yum -y remove php*
to remove all php packages then you can install the 5.6 ones.
This worked for me:
sudo dnf install java-<version>-devel
as noted here, this is what worked best for me:
sudo apt-get install python3 python3-pip python3-setuptools
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 10
so do the following edit my.cnf:
[mysqld]
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
language = /usr/share/mysql/English
bind-address = xxx.xxx.xxx.xxx
# skip-networking
after edit hit service mysqld restart
login into mysql and hit this query:
GRANT ALL ON foo.* TO bar@'xxx.xxx.xxx.xxx' IDENTIFIED BY 'PASSWORD';
thats it make sure your iptables allow connection from 3306 if not put the following:
iptables -A INPUT -i lo -p tcp --dport 3306 -j ACCEPT
iptables -A OUTPUT -p tcp --sport 3306 -j ACCEPT
As seen in Install crontab on CentOS, the crontab package in CentOS is vixie-cron
. Hence, do install it with:
yum install vixie-cron
And then start it with:
service crond start
To make it persistent, so that it starts on boot, use:
chkconfig crond on
On CentOS 7 you need to use cronie
:
yum install cronie
On CentOS 6 you can install vixie-cron
, but the real package is cronie
:
yum install vixie-cron
and
yum install cronie
In both cases you get the same output:
.../...
==================================================================
Package Arch Version Repository Size
==================================================================
Installing:
cronie x86_64 1.4.4-12.el6 base 73 k
Installing for dependencies:
cronie-anacron x86_64 1.4.4-12.el6 base 30 k
crontabs noarch 1.10-33.el6 base 10 k
exim x86_64 4.72-6.el6 epel 1.2 M
Transaction Summary
==================================================================
Install 4 Package(s)
A couple of issues
>
in -exec
without something like bash -c '... > ...'
. Though the >
will overwrite the file, so you want to redirect the entire find
anyway rather than each -exec
. +30
is older
than 30 days, -30
would be modified in last 30 days.-exec
really isn't needed, you could list everything with various -printf
options. Something like below should work
find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt
Example with -printf
find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt
This will list files in format "permissions owner group time date filename". -printf
is generally preferable to -exec
in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec
. Depending on the version of find
, you may also be able to use -ls
, which has a similar format to above.
Try the following to see if you have the proper repository installed:
# yum search java | grep 'java-'
This is going to return a list of available packages that have java in the title. Specifically we are interested in the java- anything, as the jdk will typically be in 'java-version#' type format... Anyhow, if you have to install a repo look at Dag Wieers repo:
http://dag.wieers.com/rpm/FAQ.php#B
After you've got it installed try yum search again... This time you'll have a bunch of java stuff.
# yum search java | grep 'java-'
This will return the list of the available java packages. You can install one like this:
# yum install java-1.7.0-openjdk.x86_64
It specifies the size of the log file to trigger rotation. For example size 50M
will trigger a log rotation once the file is 50MB or greater in size. You can use the suffix M
for megabytes, k
for kilobytes, and G
for gigabytes. If no suffix is used, it will take it to mean bytes. You can check the example at the end. There are three directives available size
, maxsize
, and minsize
. According to manpage:
minsize size
Log files are rotated when they grow bigger than size bytes,
but not before the additionally specified time interval (daily,
weekly, monthly, or yearly). The related size option is simi-
lar except that it is mutually exclusive with the time interval
options, and it causes log files to be rotated without regard
for the last rotation time. When minsize is used, both the
size and timestamp of a log file are considered.
size size
Log files are rotated only if they grow bigger then size bytes.
If size is followed by k, the size is assumed to be in kilo-
bytes. If the M is used, the size is in megabytes, and if G is
used, the size is in gigabytes. So size 100, size 100k, size
100M and size 100G are all valid.
maxsize size
Log files are rotated when they grow bigger than size bytes even before
the additionally specified time interval (daily, weekly, monthly,
or yearly). The related size option is similar except that it
is mutually exclusive with the time interval options, and it causes
log files to be rotated without regard for the last rotation time.
When maxsize is used, both the size and timestamp of a log file are
considered.
Here is an example:
"/var/log/httpd/access.log" /var/log/httpd/error.log {
rotate 5
mail [email protected]
size 100k
sharedscripts
postrotate
/usr/bin/killall -HUP httpd
endscript
}
Here is an explanation for both files /var/log/httpd/access.log
and /var/log/httpd/error.log
. They are rotated whenever it grows over 100k in size, and the old logs files are mailed (uncompressed) to [email protected]
after going through 5 rotations, rather than being removed. The sharedscripts
means that the postrotate
script will only be run once (after the old logs have been compressed), not once for each log which is rotated. Note that the double quotes around the first filename at the beginning of this section allows logrotate to rotate logs with spaces in the name. Normal shell quoting rules apply, with ,
, and \
characters supported.
If git already installed first remove old git
sudo yum remove git*
Add IUS CentOS 7 repo
sudo yum -y install https://repo.ius.io/ius-release-el7.rpm
sudo yum -y install git2u-all
Now check git version after installing git2u-all package. If docker is installed on your machine then ius-release may create problem.
git --version
bingo!!
I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.
To answer the question in the header: To install make in ubuntu you have to install build-essentials
sudo apt-get install build-essential
I just had the same issue and found that a client had disabled this function from their php.ini
file:
; This directive allows you to disable certain functions for security reasons.
; It receives a comma-delimited list of function names. This directive is
; *NOT* affected by whether Safe Mode is turned On or Off.
disable_functions = phpinfo;
More information: Enabling and disabling phpinfo() for security reasons
There are two ways to resolve this error:
Include /etc/apache2/httpd.conf
Add the above line in file /etc/apache2/apache2.conf
Add this line at the end of the file /etc/apache2/apache2.conf:
ServerName localhost
Instead of sudo, try
su - username command
In my experience, sudo is not always available on RHEL systems, but su is, because su is part of the coreutils package whereas sudo is in the sudo package.
If php_mcrypt installed on 64bit but reported missing by an installer, check the extension path:
vi /etc/php.d/mcrypt.ini
; Enable mcrypt extension module ;extension=module.so extension=/usr/lib64/php/modules/mcrypt.so
I am using Cent OS 6.6 with Apache and for me error log files are in
/usr/local/apache/log
Search here for centos jre install all users:
The easiest way to set an environment variable in CentOS is to use export as in
$> export JAVA_HOME=/usr/java/jdk.1.5.0_12
$> export PATH=$PATH:$JAVA_HOME
However, variables set in such a manner are transient i.e. they will disappear the moment you exit the shell. Obviously this is not helpful when setting environment variables that need to persist even when the system reboots.
In such cases, you need to set the variables within the system wide profile. In CentOS (I’m using v5.2), the folder /etc/profile.d/ is the recommended place to add customizations to the system profile.
For example, when installing the Sun JDK, you might need to set the JAVA_HOME and JRE_HOME environment variables. In this case:
Create a new file called java.sh
vim /etc/profile.d/java.sh
Within this file, initialize the necessary environment variables
export JRE_HOME=/usr/java/jdk1.5.0_12/jre
export PATH=$PATH:$JRE_HOME/bin
export JAVA_HOME=/usr/java/jdk1.5.0_12
export JAVA_PATH=$JAVA_HOME
export PATH=$PATH:$JAVA_HOME/bin
Now when you restart your machine, the environment variables within java.sh will be automatically initialized (checkout /etc/profile if you are curious how the files in /etc/profile.d/ are loaded).
PS: If you want to load the environment variables within java.sh
without having to restart the machine, you can use the source command as in:
$> source java.sh
First, you should disable selinux
, edit file /etc/sysconfig/selinux
so it looks like this:
SELINUX=disabled
SELINUXTYPE=targeted
Save file and restart system.
Then you can add the new rule to iptables
:
iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT
and restart iptables with /etc/init.d/iptables restart
If it doesn't work you should check other network settings.
I think the $() syntax is easier to read...
variable=$(ps -ef | grep "port 10 -" | grep -v "grep port 10 -"| awk '{printf "%s", $12}')
But the real issue is probably that $12
should not be qouted with ""
Edited since the question was changed, This returns valid data, but it is not clear what the expected output of ps -ef
is and what is expected in variable.
According to official Microsoft docs for Ubuntu 18.04 you should run next commands:
sudo su
curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
curl https://packages.microsoft.com/config/ubuntu/18.04/prod.list > /etc/apt/sources.list.d/mssql-release.list
apt-get update
ACCEPT_EULA=Y apt-get install msodbcsql17
exit
If you are using python3.7, it is very important to run:
sudo apt-get install python3.7-dev
If you are using RHEL/CentOS 7 (the OP was not, but I thought I'd share the solution for my case), then you will need to use firewalld instead of the iptables service mentioned in other answers.
firewall-cmd --zone=public --add-port=80/tcp --permanent
firewall-cmd --reload
And then check that it is running with:
firewall-cmd --permanent --zone=public --list-all
It should list 80/tcp
under ports
If you want to make it easier on yourself, there are CentOS RPMs for new Python versions floating around the net. E.g. see:
The error is due to corrupt or missing SSL chain certificate files in the PKI directory. You’ll need to make sure the files ca-bundle, following steps: In your console/terminal:
mkdir /usr/src/ca-certificates && cd /usr/src/ca-certificates
Enter this site: https://rpmfind.net/linux/rpm2html/search.php?query=ca-certificates , get your ca-certificate, for yout SO, for example: ftp://rpmfind.net/linux/fedora/linux/updates/24/x86_64/c/ca-certificates-2016.2.8-1.0.fc24.noarch.rpm << CentOS. Copy url of download and paste in url: wget your_url_donwload_ca-ceritificated.rpm now, install yout rpm:
rpm2cpio your_url_donwload_ca-ceritificated.rpm | cpio -idmv
now restart your service: my example this command:
sudo service2 httpd restart
very great good look
example:
sudo vim /usr/local/netbeans-8.2/etc/netbeans.conf
You need to install the psycopg2
module.
On CentOS: Make sure Python 2.7+ is installed. If not, follow these instructions: http://toomuchdata.com/2014/02/16/how-to-install-python-on-centos/
# Python 2.7.6:
$ wget http://python.org/ftp/python/2.7.6/Python-2.7.6.tar.xz
$ tar xf Python-2.7.6.tar.xz
$ cd Python-2.7.6
$ ./configure --prefix=/usr/local --enable-unicode=ucs4 --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"
$ make && make altinstall
$ yum install postgresql-libs
# First get the setup script for Setuptools:
$ wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py
# Then install it for Python 2.7 and/or Python 3.3:
$ python2.7 ez_setup.py
$ easy_install-2.7 psycopg2
Even though this is a CentOS question, here are the instructions for Ubuntu:
$ sudo apt-get install python3-pip python-distribute python-dev
$ easy_install psycopg2
Use ./catalina.sh start
to start Tomcat. Do ./catalina.sh
to get the usage.
I am using apache-tomcat-6.0.36.
pip install -U pip
pip install -U cython
The most popular answer is incomplete:
Since this search will generally be performed only for files from installed packages, yum whatprovides is made blisteringly fast by disabling all external repos (the implicit "installed" repo can't be disabled).
yum --disablerepo=* whatprovides <file>
This one works like a charm!
First
<IfModule dir_module>
DirectoryIndex index.html
DirectoryIndex index.php
</IfModule>
then after that from
<Files ".ht*">
Require all denied
</Files>
to
<Files ".ht*">
Require all granted
</Files>
I solved this by deleting d:\test\mongodb\data\mongod.lock file. When you will reconnect mongo db than this file will auto generate in same folder. it works for me.
I agree that in 95% of cases, all you need is sudo yum update openssl
However, if you need a specific version of openssl or specific functionality, which is not in CentOS repository, you probably need to compile from source. The other answers here were incomplete. Below is what worked (CentOS 6.9), although this may introduce incompatibilities with installed software, and will not auto-update the openssl.
Choose openssl version from https://www.openssl.org/source/
Log-in as root:
cd /usr/local/src/
# OPTIONALLY CHANGE openssl-1.1.0f.tar.gz to the version which you want
wget https://www.openssl.org/source/openssl-1.1.0f.tar.gz
sha256sum openssl-1.1.0f.tar.gz #confirm this matches the published hash
tar -zxf openssl-1.1.0f.tar.gz
cd /usr/local/src/openssl-1.1.0f
./config --prefix=/usr/local --openssldir=/usr/local/openssl
make
make test
make install
export LD_LIBRARY_PATH=/usr/local/lib64
#make export permanent
echo "export LD_LIBRARY_PATH=/usr/local/lib64" > /etc/profile.d/ld_library_path.sh
chmod ugo+x /etc/profile.d/ld_library_path.sh
openssl version #confirm it works
#recommended reboot here
openssl version #confirm it works after reboot
[This answer is target on linux platform only]
The first thing you should know is most of the locale config file located path can be get from localedef --help
:
$ localedef --help | tail -n 5
System's directory for character maps : /usr/share/i18n/charmaps
repertoire maps: /usr/share/i18n/repertoiremaps
locale path : /usr/lib/locale:/usr/share/i18n
For bug reporting instructions, please see:
<https://bugs.launchpad.net/ubuntu/+source/glibc/+bugs>
See the last /usr/share/i18n
? This is where your xx_XX.UTF-8 config file located:
$ ls /usr/share/i18n/locales/zh_*
/usr/share/i18n/locales/zh_CN /usr/share/i18n/locales/zh_HK /usr/share/i18n/locales/zh_SG /usr/share/i18n/locales/zh_TW
Now what ? We need to compile them into archive binary. One of the way, e.g. assume I have /usr/share/i18n/locales/en_LOVE
, I can add it into compile list, i.e. /etc/locale-gen
file:
$ tail -1 /etc/locale.gen
en_LOVE.UTF-8 UTF-8
And compile it to binary with sudo locale-gen
:
$ sudo locale-gen
Generating locales (this might take a while)...
en_AG.UTF-8... done
en_AU.UTF-8... done
en_BW.UTF-8... done
...
en_LOVE.UTF-8... done
Generation complete.
And now update the system default locale with desired LANG
, LC_ALL
...etc with this update-locale
:
sudo update-locale LANG=en_LOVE.UTF-8
update-locale
actually also means to update this /etc/default/locale
file which will source by system on login to setup environment variables:
$ head /etc/default/locale
# File generated by update-locale
LANG=en_LOVE.UTF-8
LC_NUMERIC="en_US.UTF-8"
...
But we may not want to reboot to take effect, so we can just source it to environment variable in current shell session:
$ . /etc/default/locale
How about sudo dpkg-reconfigure locales
? If you play around it you will know this command basically act as GUI to simplify the above steps, i.e. Edit /etc/locale.gen
-> sudo locale-gen
-> sudo update-locale LANG=en_LOVE.UTF-8
For python, as long as /etc/locale.gen
contains that locale candidate and locale.gen
get compiled, setlocale(category, locale)
should work without throws locale.Error: unsupoorted locale setting
. You can check the correct string en_US.UTF-8
/en_US/....etc
to be set in setlocale()
, by observing /etc/locale.gen
file, and then uncomment and compile it as desired. zh_CN GB2312
without dot in that file means the correct string is zh_CN
and zh_CN.GB2312
.
on command line type journalctl -xe
and the results will be
SELinux is preventing /usr/sbin/httpd from name_bind access on the tcp_socket port 83 or 80
This means that the SELinux is running on your machine and you need to disable it. then edit the configuration file by type the following
nano /etc/selinux/config
Then find the line SELINUX=enforce
and change to SELINUX=disabled
Then type the following and run the command to start httpd
setenforce 0
Lastly start a server
systemctl start httpd
Use the below Steps to reset the password.
$ sudo systemctl start mysqld
Reset the MySql server root password.
$sudo grep 'temporary password' /var/log/mysqld.log
Output Something like-:
10.744785Z 1 [Note] A temporary password is generated for root@localhost: o!5y,oJGALQa
Use the above password during reset mysql_secure_installation process.
<pre>
$ sudo mysql_secure_installation
</pre>
Securing the MySQL server deployment.
Enter password for user root:
You have successfully reset the root password of MySql Server. Use the below command to check the mysql server connecting or not.
$ mysql -u root -p
http://gotechnies.com/install-latest-mysql-5-7-rhelcentos-7/
You can use --python
option to npm like so:
npm install --python=python2.7
or set it to be used always:
npm config set python python2.7
Npm will in turn pass this option to node-gyp when needed.
(note: I'm the one who opened an issue on Github to have this included in the docs, as there were so many questions about it ;-) )
Using wget
wget -O /tmp/myfile 'http://www.google.com/logo.jpg'
or curl:
curl -o /tmp/myfile 'http://www.google.com/logo.jpg'
Just wanted to add a comment in BRPocock, but I don't have the sufficient privilegies.
So my contribution was for everyone trying to install IBM Integration Toolkit from IBM's Integration Bus bundle.
When you try to run "Installation Manager" command from folder /Integration_Toolkit/IM_Linux (the file to run is "install") you get the error showed in this post.
Further instructions to fix this problem you'll find in this IBM's web page: https://www-304.ibm.com/support/docview.wss?uid=swg21459143
Hope this helps for anybody trying to install that.
Put the IPtables configuration in the traditional file and it will be loaded after boot:
/etc/sysconfig/iptables
compgen -c python | grep -P '^python\d'
This lists some other python things too, But hey, You can identify all python versions among them.
Cron is a time-based scheduling service in Linux / Unix-like computer operating systems. Cron job are used to schedule commands to be executed periodically. You can setup commands or scripts, which will repeatedly run at a set time. Cron is one of the most useful tool in Linux or UNIX like operating systems. The cron service (daemon) runs in the background and constantly checks the /etc/crontab file, /etc/cron./* directories. It also checks the /var/spool/cron/ directory.
In the following example, the crontab command shown below will activate the cron tasks automatically every ten minutes:
*/10 * * * * /usr/bin/php /opt/test.php
In the above sample, the */10 * * * * represents when the task should happen. The first figure represents minutes – in this case, on every "ten" minute. The other figures represent, respectively, hour, day, month and day of the week.
*
is a wildcard, meaning "every time".
Start with finding out your PHP binary by typing in command line:
whereis php
The output should be something like:
php: /usr/bin/php /etc/php.ini /etc/php.d /usr/lib64/php /usr/include/php /usr/share/php /usr/share/man/man1/php.1.gz
Specify correctly the full path in your command.
crontab -e
To see what you got in crontab.
To exit from vim editor without saving just click:
Shift+:
And then type q!
Ok... I know that there are 1.000.000 answers to this questions already, - but I have spent at least 6 effective hours, figuring this one out; and I have googled it hundreds of times and not found a single post about it. So I figured that I would add the solution to my problem here.
If I commented these two lines out in my .conf-files in the /etc/apache2/[[SERVER-NAME].conf
-file:
php_admin_value engine Off
IPCComTimeout 31
I have no idea what they do or how they got there, - but it is in every one of my .conf
-files. And if I remove those lines and ensure that there is a symlink in /etc/apache2/sites-enabled/
-folder, then it doesn't download the index.php - and every works as it should.
I have VirtualMin installed on an Ubuntu 16.04 VPS. I upgraded to PHP version 7.2. Shortly after that, I updated the Ubuntu-version and struck a 'Kernel Offset: Disabled'-error. So I had to go delete the latest Ubuntu-version, - and when my OS booted up again: BOOM! I got the error that his post talks about: For every site on my VPS, it simply downloaded the index.php instead of showing it.
I tried all kinds of stuff:
a2enmod [MODULE_NAME]
. And I found the module name by Googling around. I had to active about 6-8 modules, before I got past that step in the validation - and it took a couple of minutes before the cache ran out, - so doing this was a tedious step.yum install java-1.8.0
and then:
alternatives --config java
and check:
java -version
You might just have to install the packages.
yum install php-pdo php-mysqli
After they're installed, restart Apache.
httpd restart
or
apachectl restart
To update and answer the question without breaking mail servers. Later versions of CentOS 7 have MariaDB included as the base along with PostFix which relies on MariaDB. Removing using yum will also remove postfix and perl-DBD-MySQL. To get around this and keep postfix in place, first make a copy of /usr/lib64/libmysqlclient.so.18 (which is what postfix depends on) and then use:
rpm -qa | grep mariadb
then remove the mariadb packages using (changing to your versions):
rpm -e --nodeps "mariadb-libs-5.5.56-2.el7.x86_64"
rpm -e --nodeps "mariadb-server-5.5.56-2.el7.x86_64"
rpm -e --nodeps "mariadb-5.5.56-2.el7.x86_64"
Delete left over files and folders (which also removes any databases):
rm -f /var/log/mariadb
rm -f /var/log/mariadb/mariadb.log.rpmsave
rm -rf /var/lib/mysql
rm -rf /usr/lib64/mysql
rm -rf /usr/share/mysql
Put back the copy of /usr/lib64/libmysqlclient.so.18 you made at the start and you can restart postfix.
There is more detail at https://code.trev.id.au/centos-7-remove-mariadb-replace-mysql/ which describes how to replace mariaDB with MySQL
I tried changing the repository list with:
http://security.ubuntu.com/ubuntu bionic-security main universe http://archive.ubuntu.com/ubuntu bionic main restricted universe
But none of them seem to work, but I finally found a repository that works running the following command
add-apt-repository ppa:ondrej/php
And then updating and installing normally the package using apt-get
As you can see it's installed at last.
grep -r -e string directory
-r
is for recursive; -e
is optional but its argument specifies the regex to search for. Interestingly, POSIX grep
is not required to support -r
(or -R
), but I'm practically certain that System V in practice they (almost) all do. Some versions of grep
did, sogrep
support -R
as well as (or conceivably instead of) -r
; AFAICT, it means the same thing.
Using Git Bash on Windows 10 and Python36 for Windows I found the virtualenvwrapper.sh in a slightly different place and running this resolved the issue
source virtualenvwrapper.sh
/c/users/[myUserName]/AppData/Local/Programs/Python36/Scripts
With CentOS 6.5+ and PHP 5.5:
yum install php55u-gd
service httpd restart
If you get an error like: cannot map zero-fill pages: Cannot allocate memory in Unknown on line 0
, it could be because you don't have a swap file. I suggest you take a look at the tutorial mentioned in this answer: https://stackoverflow.com/a/20275282/828366
Tutorial: https://www.digitalocean.com/community/articles/how-to-add-swap-on-centos-6
As I understand, you want to recursively copy test directory into /home/server/
path...
This can be done as:
-cp -rf /home/server/folder/test/* /home/server/
Hope this helps
Use this command to find your active zone(s):
firewall-cmd --get-active-zones
It will say either public, dmz, or something else. You should only apply to the zones required.
In the case of public try:
firewall-cmd --zone=public --add-port=2888/tcp --permanent
Then remember to reload the firewall for changes to take effect.
firewall-cmd --reload
Otherwise, substitute public for your zone, for example, if your zone is dmz:
firewall-cmd --zone=dmz --add-port=2888/tcp --permanent
Well, I think nginx by itself doesn't have that in its setup, because the Ubuntu-maintained package does it as a convention to imitate Debian's apache setup. You could create it yourself if you wanted to emulate the same setup.
Create /etc/nginx/sites-available
and /etc/nginx/sites-enabled
and then edit the http
block inside /etc/nginx/nginx.conf
and add this line
include /etc/nginx/sites-enabled/*;
Of course, all the files will be inside sites-available
, and you'd create a symlink for them inside sites-enabled
for those you want enabled.
php -i |grep 'Configuration File'
You cannot exactly get a list of commands started with nohup
but you can see them along with your other processes by using the command ps x
. Commands started with nohup
will have a question mark in the TTY column.
All OS comes with a default version of python and it resides in /usr/bin. All scripts that come with the OS (e.g. yum) point this version of python residing in /usr/bin. When you want to install a new version of python you do not want to break the existing scripts which may not work with new version of python.
The right way of doing this is to install the python as an alternate version.
e.g.
wget http://www.python.org/ftp/python/2.7.3/Python-2.7.3.tar.bz2
tar xf Python-2.7.3.tar.bz2
cd Python-2.7.3
./configure --prefix=/usr/local/
make && make altinstall
Now by doing this the existing scripts like yum still work with /usr/bin/python. and your default python version would be the one installed in /usr/local/bin. i.e. when you type python you would get 2.7.3
This happens because. $PATH variable has /usr/local/bin before usr/bin.
/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
If python2.7 still does not take effect as the default python version you would need to do
export PATH="/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin"
Paul Dardeau answer is perfect, the only thing is, what if all the files inside those folders are not PDF files and you want to grab it all no matter the extension. Well just change it to
find . -name "*.*" -type f -exec cp {} ./pdfsfolder \;
Just to sum up!
Such difference between the output of du -sh
and df -h
may happen if some large file has been deleted, but is still opened by some process. Check with the command lsof | grep deleted
to see which processes have opened descriptors to deleted files. You can restart the process and the space will be freed.
The problem with rc.local is that the commands are accessed as root which is different than logging to as a user and using sudo.
I solved this problem by adding a .sh script with the startup commands i want to etc/profile.d. Any .sh file in profile.d will load automatically and any command will be treated as if you used the regular sudo.
The only downside to this is the specified user needs to loggin for things to start which in my situation was always the case.
My non pythonic approach would be using & suffix. That is:
python flashpolicyd.py &
To stop the script
killall flashpolicyd.py
also piping & suffix with disown would put the process under superparent (upper):
python flashpolicyd.pi & disown
To run it as a full daemon from a shell, you'll need to use setsid
and redirect its output. You can redirect the output to a logfile, or to /dev/null
to discard it. Assuming your script is called myscript.sh, use the following command:
setsid myscript.sh >/dev/null 2>&1 < /dev/null &
This will completely detach the process from your current shell (stdin, stdout and stderr). If you want to keep the output in a logfile, replace the first /dev/null
with your /path/to/logfile.
You have to redirect the output, otherwise it will not run as a true daemon (it will depend on your shell to read and write output).
Make sure you have the last version for youtube-dl
sudo youtube-dl -U
after that you can solve this problem by installing the missing ffmpeg
on ubuntu and debian:
sudo apt-get install ffmpeg
and macOS use the command:
brew install ffmpeg
using (var fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
using (var sw = new StreamWriter(fs))
{
sw.WriteLine(message);
}
request.getContextPath()-
returns root path of your application, while
../
- returns parent directory of a file.
You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.
Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.
<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>
PS- This is the one reason I can figure out. Don't know if there is any more significance to it.
var currentTallest = 0,_x000D_
currentRowStart = 0,_x000D_
rowDivs = new Array(),_x000D_
$el,_x000D_
topPosition = 0;_x000D_
_x000D_
$('.blocks').each(function() {_x000D_
_x000D_
$el = $(this);_x000D_
topPostion = $el.position().top;_x000D_
_x000D_
if (currentRowStart != topPostion) {_x000D_
_x000D_
// we just came to a new row. Set all the heights on the completed row_x000D_
for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {_x000D_
rowDivs[currentDiv].height(currentTallest);_x000D_
}_x000D_
_x000D_
// set the variables for the new row_x000D_
rowDivs.length = 0; // empty the array_x000D_
currentRowStart = topPostion;_x000D_
currentTallest = $el.height();_x000D_
rowDivs.push($el);_x000D_
_x000D_
} else {_x000D_
_x000D_
// another div on the current row. Add it to the list and check if it's taller_x000D_
rowDivs.push($el);_x000D_
currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest);_x000D_
_x000D_
}_x000D_
_x000D_
// do the last row_x000D_
for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {_x000D_
rowDivs[currentDiv].height(currentTallest);_x000D_
}_x000D_
_x000D_
});?
_x000D_
$('.blocks') would be changed to use whatever CSS selector you need to equalize.
_x000D_
This solution takes punctuation into account for new sentences, handles quotations, converts minor words to lowercase and ignores acronyms or all-caps words.
var stopWordsArray = new Array("a", "all", "am", "an", "and", "any", "are", "as", "at", "be", "but", "by", "can", "can't", "did", "didn't", "do", "does", "doesn't", "don't", "else", "for", "get", "gets", "go", "got", "had", "has", "he", "he's", "her", "here", "hers", "hi", "him", "his", "how", "i'd", "i'll", "i'm", "i've", "if", "in", "is", "isn't", "it", "it's", "its", "let", "let's", "may", "me", "my", "no", "of", "off", "on", "our", "ours", "she", "so", "than", "that", "that's", "thats", "the", "their", "theirs", "them", "then", "there", "there's", "these", "they", "they'd", "they'll", "they're", "they've", "this", "those", "to", "too", "try", "until", "us", "want", "wants", "was", "wasn't", "we", "we'd", "we'll", "we're", "we've", "well", "went", "were", "weren't", "what", "what's", "when", "where", "which", "who", "who's", "whose", "why", "will", "with", "won't", "would", "yes", "yet", "you", "you'd", "you'll", "you're", "you've", "your");
// Only significant words are transformed. Handles acronyms and punctuation
String.prototype.toTitleCase = function() {
var newSentence = true;
return this.split(/\s+/).map(function(word) {
if (word == "") { return; }
var canCapitalise = true;
// Get the pos of the first alpha char (word might start with " or ')
var firstAlphaCharPos = word.search(/\w/);
// Check for uppercase char that is not the first char (might be acronym or all caps)
if (word.search(/[A-Z]/) > 0) {
canCapitalise = false;
} else if (stopWordsArray.indexOf(word) != -1) {
// Is a stop word and not a new sentence
word.toLowerCase();
if (!newSentence) {
canCapitalise = false;
}
}
// Is this the last word in a sentence?
newSentence = (word.search(/[\.!\?:]['"]?$/) > 0)? true : false;
return (canCapitalise)? word.replace(word[firstAlphaCharPos], word[firstAlphaCharPos].toUpperCase()) : word;
}).join(' ');
}
// Pass a string using dot notation:
alert("A critical examination of Plato's view of the human nature".toTitleCase());
var str = "Ten years on: a study into the effectiveness of NCEA in New Zealand schools";
str.toTitleCase());
str = "\"Where to from here?\" the effectivness of eLearning in childhood education";
alert(str.toTitleCase());
/* Result:
A Critical Examination of Plato's View of the Human Nature.
Ten Years On: A Study Into the Effectiveness of NCEA in New Zealand Schools.
"Where to From Here?" The Effectivness of eLearning in Childhood Education. */
New version, now you also have the GC= try to replace both DPB and GC with those
DPB="DBD9775A4B774B77B4894C77DFE8FE6D2CCEB951E8045C2AB7CA507D8F3AC7E3A7F59012A2" GC="BAB816BBF4BCF4BCF4"
password will be "test"
Each time you do e.nextElement()
you skip one. So you skip two elements in each iteration of your loop.
import * as express from "express";
This is the suggested way of doing it because it is the standard for JavaScript (ES6/2015) since last year.
In any case, in your tsconfig.json file, you should target the module option to commonjs which is the format supported by nodejs.
Does this work without alternation?
^((part)1(, \22)?)?(part2)?$
or why not this?
^((part)1(, (\22))?)?(\4)?$
The first works for all conditions the second for all but part2
(using GNU sed 4.1.5)
const mergeByProperty = (target, source, prop) => {
source.forEach(sourceElement => {
let targetElement = target.find(targetElement => {
return sourceElement[prop] === targetElement[prop];
})
targetElement ? Object.assign(targetElement, sourceElement) : target.push(sourceElement);
})
}
var target /* arr1 */ = [{name: "lang", value: "English"}, {name: "age", value: "18"}];
var source /* arr2 */ = [{name : "childs", value: '5'}, {name: "lang", value: "German"}];
mergeByProperty(target, source, 'name');
console.log(target)
_x000D_
This answer was getting old, libs like lodash and underscore are much less needed these days. In this new version, the target (arr1) array is the one we’re working with and want to keep up to date. The source (arr2) array is where the new data is coming from, and we want it merged into our target array.
We loop over the source array looking for new data, and for every object that is not yet found in our target array we simply add that object using target.push(sourceElement) If, based on our key property ('name'), an object is already in our target array - we update its properties and values using Object.assign(targetElement, sourceElement). Our “target” will always be the same array and with updated content.
I always arrive here from google and I'm always not satisfy from the answers. YOU answer is good but it'll be easier and neater using underscore.js
DEMO: http://jsfiddle.net/guya/eAWKR/
Here is a more general function that will merge 2 arrays using a property of their objects. In this case the property is 'name'
var arr1 = [{name: "lang", value: "English"}, {name: "age", value: "18"}];
var arr2 = [{name : "childs", value: '5'}, {name: "lang", value: "German"}];
function mergeByProperty(arr1, arr2, prop) {
_.each(arr2, function(arr2obj) {
var arr1obj = _.find(arr1, function(arr1obj) {
return arr1obj[prop] === arr2obj[prop];
});
arr1obj ? _.extend(arr1obj, arr2obj) : arr1.push(arr2obj);
});
}
mergeByProperty(arr1, arr2, 'name');
console.log(arr1);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.core.min.js"></script>
_x000D_
[{name: "lang", value: "German"}, {name: "age", value: "18"}, {name : "childs", value: '5'}]
On my machine using Node.js, I ran the following:
console.log('Testing Array:');
console.time('using[]');
for(var i=0; i<200000000; i++){var arr = []};
console.timeEnd('using[]');
console.time('using new');
for(var i=0; i<200000000; i++){var arr = new Array};
console.timeEnd('using new');
console.log('Testing Object:');
console.time('using{}');
for(var i=0; i<200000000; i++){var obj = {}};
console.timeEnd('using{}');
console.time('using new');
for(var i=0; i<200000000; i++){var obj = new Object};
console.timeEnd('using new');
Note, this is an extension of what is found here: Why is arr = [] faster than arr = new Array?
my output was the following:
Testing Array:
using[]: 1091ms
using new: 2286ms
Testing Object:
using{}: 870ms
using new: 5637ms
so clearly {} and [] are faster than using new for creating empty objects/arrays.
If you just need to make simple get requests and don't need support for any other HTTP methods take a look at: simple-get:
var get = require('simple-get');
get('http://example.com', function (err, res) {
if (err) throw err;
console.log(res.statusCode); // 200
res.pipe(process.stdout); // `res` is a stream
});
Update for PHP 7 (thanks shock_gone_wild)
PHP 7 introduces the so called null coalescing operator which simplifies the below statements to:
$var = $var ?? "default";
Before PHP 7
No, there is no special operator or special syntax for this. However, you could use the ternary operator:
$var = isset($var) ? $var : "default";
Or like this:
isset($var) ?: $var = 'default';
Some googling found this, where people had a discussion about this.
An unsigned char is basically a single byte. So, you would use this if you need one byte of data (for example, maybe you want to use it to set flags on and off to be passed to a function, as is often done in the Windows API).
Try putting display:table block inside a cell
Simplyfing for the begginers:
If you want to select an element immediatly after another element you use the +
selector.
For example:
div + p
The "+" element selects all <p>
elements that are placed immediately after <div>
elements
If you want to learn more about selectors use this table
Try =Year(Now())
and format the cell as General
.
The prompt command will echo text to the output:
prompt A useful comment.
select(*) from TableA;
Will be displayed as:
SQL> A useful comment.
SQL>
COUNT(*)
----------
0
self.view.backgroundColor = UIColor.redColor()
In Swift 3:
self.view.backgroundColor = UIColor.red
Actually, the simplest way to manipulate this is to
And then the URL www.yoursite.com/data will read that index.php file. If you want to take it further, open a subfolder (e.g. "List") in it, put another index.php in that folder and you can have www.yoursite.com/data/list run that PHP file.
This way you can have full control over this, very useful for SEO.
I fought with this one for a while. My goal was to have a table with headers where the widths of the each header column was the the same as the corresponding body column and was the minimum size necessary to fit the data. also the body data was scrollable underneath header.
I solved this by using divs and not tables. Each "table" was a div with the header being a div of divs and the body being a div of divs. I used the style as indicated by @sushil above. I added a bit of javascript/jQuery to balance the columns. Maybe 20-30 lines.
Unfortunately I lost the code and have to rebuild it. I know this is a bit old, but maybe it will help someone else.
I was able to do this in a centralized way, here is the result:
I have following Activity
and I extend from it if I need custom fonts:
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.LayoutInflater.Factory;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
public class CustomFontActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
getLayoutInflater().setFactory(new Factory() {
@Override
public View onCreateView(String name, Context context,
AttributeSet attrs) {
View v = tryInflate(name, context, attrs);
if (v instanceof TextView) {
setTypeFace((TextView) v);
}
return v;
}
});
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private View tryInflate(String name, Context context, AttributeSet attrs) {
LayoutInflater li = LayoutInflater.from(context);
View v = null;
try {
v = li.createView(name, null, attrs);
} catch (Exception e) {
try {
v = li.createView("android.widget." + name, null, attrs);
} catch (Exception e1) {
}
}
return v;
}
private void setTypeFace(TextView tv) {
tv.setTypeface(FontUtils.getFonts(this, "MTCORSVA.TTF"));
}
}
But if I am using an activity from support package e.g. FragmentActivity
then I use this Activity
:
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
public class CustomFontFragmentActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// we can't setLayout Factory as its already set by FragmentActivity so we
// use this approach
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
View v = super.onCreateView(name, context, attrs);
if (v == null) {
v = tryInflate(name, context, attrs);
if (v instanceof TextView) {
setTypeFace((TextView) v);
}
}
return v;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public View onCreateView(View parent, String name, Context context,
AttributeSet attrs) {
View v = super.onCreateView(parent, name, context, attrs);
if (v == null) {
v = tryInflate(name, context, attrs);
if (v instanceof TextView) {
setTypeFace((TextView) v);
}
}
return v;
}
private View tryInflate(String name, Context context, AttributeSet attrs) {
LayoutInflater li = LayoutInflater.from(context);
View v = null;
try {
v = li.createView(name, null, attrs);
} catch (Exception e) {
try {
v = li.createView("android.widget." + name, null, attrs);
} catch (Exception e1) {
}
}
return v;
}
private void setTypeFace(TextView tv) {
tv.setTypeface(FontUtils.getFonts(this, "MTCORSVA.TTF"));
}
}
I haven't tested this code with Fragment
s yet, but hopefully it will work.
My FontUtils
is simple which also solves the pre-ICS issue mentioned here https://code.google.com/p/android/issues/detail?id=9904:
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.graphics.Typeface;
public class FontUtils {
private static Map<String, Typeface> TYPEFACE = new HashMap<String, Typeface>();
public static Typeface getFonts(Context context, String name) {
Typeface typeface = TYPEFACE.get(name);
if (typeface == null) {
typeface = Typeface.createFromAsset(context.getAssets(), "fonts/"
+ name);
TYPEFACE.put(name, typeface);
}
return typeface;
}
}
Set the Format to Custom and then specify the format:
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "MM/dd/yyyy hh:mm:ss";
or however you want to lay it out. You could then type in directly the date/time. If you use MMM, you'll need to use the numeric value for the month for entry, unless you write some code yourself for that (e.g., 5 results in May)
Don't know about the picker for date and time together. Sounds like a custom control to me.
For Android API level 13 and you need to use this:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int maxX = size.x;
int maxY = size.y;
Then (0,0) is top left corner and (maxX,maxY) is bottom right corner of the screen.
The 'getWidth()' for screen size is deprecated since API 13
Furthermore getwidth() and getHeight() are methods of android.view.View class in android.So when your java class extends View class there is no windowManager overheads.
int maxX=getwidht();
int maxY=getHeight();
as simple as that.
To me it happened in DogController
that autowired DogService
that autowired DogRepository
. Dog
class used to have field name
but I changed it to coolName
, but didn't change methods in DogRepository
: Dog findDogByName(String name)
. I change that method to Dog findDogByCoolName(String name)
and now it works.
You can install the python-distutils
package. sudo apt-get install python-distutils
should suffice.
You could store intermediate values in a cell or column (which you could hide if you choose)
C1: = VLOOKUP(A1, B:B, 1, 0)
D1: = IF(C1 > 10, C1 - 10, C1)
Consider C#'s out keyword. The compiler requires the caller of a method to apply the out keyword to any out args, even though it knows already if they are. This is intended to enhance readability. Although with modern IDEs I'm inclined to think that this is a job for syntax (or semantic) highlighting.
MD5 encrypting is possible, but decrypting is still unknown (to me). However, there are many ways to compare these things.
Using compare methods like so:
<?php
$db_pass = $P$BX5675uhhghfhgfhfhfgftut/0;
$my_pass = "mypass";
if ($db_pass === md5($my_pass)) {
// password is matched
} else {
// password didn't match
}
Only for WordPress users.
If you have access to your PHPMyAdmin, focus you have because you paste that hashing here: $P$BX5675uhhghfhgfhfhfgftut/0, WordPress user_pass
is not only MD5 format it also uses utf8_mb4_cli
charset so what to do?
That's why I use another Approach if I forget my WordPress password I use
I install other WordPress with new password :P, and I then go to PHPMyAdmin and copy that hashing from the database and paste that hashing to my current PHPMyAdmin password ( which I forget )
EASY is use this :
I USE THIS APPROACH FOR MY SELF WHEN I DESIGN THEMES AND PLUGINS
WORDPRESS USE THIS
https://developer.wordpress.org/reference/functions/wp_hash_password/
Easiest is to use strftime
(docs).
If it's for use on the view side, better to wrap it in a helper, though.
You can try
lstCountry.SelectedItem.Text
Select-Object creates a new psobject and copies the properties you requested to it. You can verify this with GetType():
PS > $a.GetType().fullname
System.DayOfWeek
PS > $b.GetType().fullname
System.Management.Automation.PSCustomObject
You could write a windows service that does nothing but execute your batch file. Since services run in their own desktop session, the command window won't be visible by the user.
If you want recursive to include subprojects, you can always write it yourself:
Paste into the top-level build.gradle
:
task allDeps << {
println "All Dependencies:"
allprojects.each { p ->
println()
println " $p.name ".center( 60, '*' )
println()
p.configurations.all.findAll { !it.allDependencies.empty }.each { c ->
println " ${c.name} ".center( 60, '-' )
c.allDependencies.each { dep ->
println "$dep.group:$dep.name:$dep.version"
}
println "-" * 60
}
}
}
Run with:
gradle allDeps
Use the formula by tigeravatar:
=COUNTIF($B$2:$B$5,A2)>0 – tigeravatar Aug 28 '13 at 14:50
as conditional formatting. Highlight column A. Choose conditional formatting by forumula. Enter the formula (above) - this finds values in col B that are also in A. Choose a format (I like to use FILL and a bold color).
To find all of those values, highlight col A. Data > Filter and choose Filter by color.
Try this...
//global declaration
private TextView timeUpdate;
Calendar calendar;
.......
timeUpdate = (TextView) findViewById(R.id.timeUpdate); //initialize in onCreate()
.......
//in onStart()
calendar = Calendar.getInstance();
//date format is: "Date-Month-Year Hour:Minutes am/pm"
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy HH:mm a"); //Date and time
String currentDate = sdf.format(calendar.getTime());
//Day of Name in full form like,"Saturday", or if you need the first three characters you have to put "EEE" in the date format and your result will be "Sat".
SimpleDateFormat sdf_ = new SimpleDateFormat("EEEE");
Date date = new Date();
String dayName = sdf_.format(date);
timeUpdate.setText("" + dayName + " " + currentDate + "");
The result is...
happy coding.....
The version of EnterpriseLibrary on my machine had other parameters. This was working:
SqlParameter retval = new SqlParameter("@ReturnValue", System.Data.SqlDbType.Int);
retval.Direction = System.Data.ParameterDirection.ReturnValue;
cmd.Parameters.Add(retval);
db.ExecuteNonQuery(cmd);
object o = cmd.Parameters["@ReturnValue"].Value;
SELECT cast( cast(round(37.0/38.0,2) AS DECIMAL(18,2)) as varchar(100)) + ' %'
RESULT: 0.97 %
From Stroustrup's speech at "Going Native 2012":
template<int M, int K, int S> struct Unit { // a unit in the MKS system
enum { m=M, kg=K, s=S };
};
template<typename Unit> // a magnitude with a unit
struct Value {
double val; // the magnitude
explicit Value(double d) : val(d) {} // construct a Value from a double
};
using Speed = Value<Unit<1,0,-1>>; // meters/second type
using Acceleration = Value<Unit<1,0,-2>>; // meters/second/second type
using Second = Unit<0,0,1>; // unit: sec
using Second2 = Unit<0,0,2>; // unit: second*second
constexpr Value<Second> operator"" s(long double d)
// a f-p literal suffixed by ‘s’
{
return Value<Second> (d);
}
constexpr Value<Second2> operator"" s2(long double d)
// a f-p literal suffixed by ‘s2’
{
return Value<Second2> (d);
}
Speed sp1 = 100m/9.8s; // very fast for a human
Speed sp2 = 100m/9.8s2; // error (m/s2 is acceleration)
Speed sp3 = 100/9.8s; // error (speed is m/s and 100 has no unit)
Acceleration acc = sp1/0.5s; // too fast for a human
While the documentation recommends using weak
on properties for subviews, since iOS 6 it seems to be fine to use strong
(the default ownership qualifier) instead. That's caused by the change in UIViewController
that views are not unloaded anymore.
That said, I am torn between using
@property (nonatomic, weak) IBOutlet UIButton *button;
and
@property (nonatomic) IBOutlet UIButton *button;
in iOS 6 and after:
Using weak
clearly states that the controller doesn't want ownership of the button.
But omitting weak
doesn't hurt in iOS 6 without view unloading, and is shorter. Some may point out that is also faster, but I have yet to encounter an app that is too slow because of weak
IBOutlet
s.
Not using weak
may be perceived as an error.
Bottom line: Since iOS 6 we can't get this wrong anymore as long as we don't use view unloading. Time to party. ;)
Take a look at my jquery videoBG plugin
http://syddev.com/jquery.videoBG/
Make any HTML5 video a site background... has an image fallback for browsers that don't support html5
Really easy to use
Let me know if you need any help.
If you are using Gradle, include right jar of driver as below:
compile("org.mongodb:mongo-java-driver:3.3.0")
Or if using Maven then do it in Maven style, it should solve your problem.
Beside all this, There is also a scenario where this error occures-
When you or your library project define custom attribute int attr.xml, And you use these attributes in your layout file without defining namespace .
Generally we use this namespace definition in header of our layout file.
xmlns:android="http://schemas.android.com/apk/res/android"
Then make sure all attributes in your file shoud start with
android:ATTRIBUTE-NAME
You need to identfy if some of your attirbute is not starting with something other than android:ATTRIBUTE-NAME like
temp:ATTRIBUTE-NAME
In this case you have this "temp" also as namespace, generally by including-
xmlns:temp="http://schemas.android.com/apk/res-auto"
What you are looking for is a query with WITH
clause, if your dbms supports it. Then
WITH NewScores AS (
SELECT *
FROM Score
WHERE InsertedDate >= DATEADD(mm, -3, GETDATE())
)
SELECT
<and the rest of your query>
;
Note that there is no ;
in the first half. HTH.
Working Fiddle on <body onload="myFunction()">
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function myFunction(){
alert("Page is loaded");
}
</script>
</head>
<body onload="myFunction()">
<h1>Hello World!</h1>
</body>
</html>
I modified Sean Vieira's code to suit my needs. null and undefined don't count as object at all, and numbers, boolean values and empty strings return false.
'use strict';_x000D_
_x000D_
// Speed up calls to hasOwnProperty_x000D_
var hasOwnProperty = Object.prototype.hasOwnProperty;_x000D_
_x000D_
var isObjectEmpty = function(obj) {_x000D_
// null and undefined are not empty_x000D_
if (obj == null) return false;_x000D_
if(obj === false) return false;_x000D_
if(obj === true) return false;_x000D_
if(obj === "") return false;_x000D_
_x000D_
if(typeof obj === "number") {_x000D_
return false;_x000D_
} _x000D_
_x000D_
// Assume if it has a length property with a non-zero value_x000D_
// that that property is correct._x000D_
if (obj.length > 0) return false;_x000D_
if (obj.length === 0) return true;_x000D_
_x000D_
// Otherwise, does it have any properties of its own?_x000D_
// Note that this doesn't handle_x000D_
// toString and valueOf enumeration bugs in IE < 9_x000D_
for (var key in obj) {_x000D_
if (hasOwnProperty.call(obj, key)) return false;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
return true;_x000D_
};_x000D_
_x000D_
exports.isObjectEmpty = isObjectEmpty;
_x000D_
I was using above command but it was not working. This command worked for me:
python -m pip uninstall pip setuptools
extend(L)
extends the list by appending all the items in the given list L
.
>>> a
[1, 2, 3]
a.extend([4]) #is eqivalent of a[len(a):] = [4]
>>> a
[1, 2, 3, 4]
a = [1, 2, 3]
>>> a
[1, 2, 3]
>>> a[len(a):] = [4]
>>> a
[1, 2, 3, 4]
For the answer above, the default serial port is
serialParams.BaudRate = 9600;
serialParams.ByteSize = 8;
serialParams.StopBits = TWOSTOPBITS;
serialParams.Parity = NOPARITY;
To download your repository as zip file via curl
:
curl -L -o master.zip http://github.com/zoul/Finch/zipball/master/
If your repository is private:
curl -u 'username' -L -o master.zip http://github.com/zoul/Finch/zipball/master/
Source: Github Help
One main difference is the Local
part of LocalDateTime
. If you live in Germany and create a LocalDateTime
instance and someone else lives in USA and creates another instance at the very same moment (provided the clocks are properly set) - the value of those objects would actually be different. This does not apply to Instant
, which is calculated independently from time zone.
LocalDateTime
stores date and time without timezone, but it's initial value is timezone dependent. Instant
's is not.
Moreover, LocalDateTime
provides methods for manipulating date components like days, hours, months. An Instant
does not.
apart from the nanosecond precision advantage of Instant and the time-zone part of LocalDateTime
Both classes have the same precision. LocalDateTime
does not store timezone. Read javadocs thoroughly, because you may make a big mistake with such invalid assumptions: Instant and LocalDateTime.
In Python 2.7.3:
import urllib2
import socket
class MyException(Exception):
pass
try:
urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError as e:
print type(e) #not catch
except socket.timeout as e:
print type(e) #catched
raise MyException("There was an error: %r" % e)
A Runnable is basically a type of class (Runnable is an Interface) that can be put into a thread, describing what the thread is supposed to do.
The Runnable Interface requires of the class to implement the method run()
like so:
public class MyRunnableTask implements Runnable {
public void run() {
// do stuff here
}
}
And then use it like this:
Thread t = new Thread(new MyRunnableTask());
t.start();
If you did not have the Runnable
interface, the Thread class, which is responsible to execute your stuff in the other thread, would not have the promise to find a run()
method in your class, so you could get errors. That is why you need to implement the interface.
Note that you do not need to define a class as usual, you can do all of that inline:
Thread t = new Thread(new Runnable() {
public void run() {
// stuff here
}
});
t.start();
This is similar to the above, only you don't create another named class.
EventArgs e
is a parameter called e that contains the event data, see the EventArgs MSDN page for more information.
Object Sender
is a parameter called Sender that contains a reference to the control/object that raised the event.
Event Arg Class: http://msdn.microsoft.com/en-us/library/system.eventargs.aspx
Example:
protected void btn_Click (object sender, EventArgs e){
Button btn = sender as Button;
btn.Text = "clicked!";
}
Edit: When Button is clicked, the btn_Click event handler will be fired. The "object sender" portion will be a reference to the button which was clicked
I hope I am not overstating the obvious, but why not do it directly in the ASP side? Unless you are dynamically altering the SQL based on certain conditions in your program, you should avoid codebehind as much as possible.
You could do the above all in ASP directly without code using the SqlDataSource control and a property in your dropdownlist.
<asp:GridView ID="gvSubjects" runat="server" DataKeyNames="SubjectID" OnRowDataBound="GridView_RowDataBound" OnDataBound="GridView_DataBound">
<Columns>
<asp:TemplateField HeaderText="Subjects">
<ItemTemplate>
<asp:DropDownList ID="ddlSubjects" runat="server" DataSourceID="sdsSubjects" DataTextField="SubjectName" DataValueField="SubjectID">
</asp:DropDownList>
<asp:SqlDataSource ID="sdsSubjects" runat="server"
SelectCommand="SELECT SubjectID,SubjectName FROM Students.dbo.Subjects"></asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In case we are in the same page do following
sudo apt-get install php -y
sudo apt-get install php-{bcmath,bz2,intl,gd,mbstring,mysql,zip,fpm} -y
To enable PHP 7.2 FPM in Apache2 do:
a2enmod proxy_fcgi setenvif
a2enconf php7.2-fpm
After that, I faced above issue. There are similar questions like this.
I don't know why but it only happened for my .php files in /var/www/html/
root folder. everything was ok for sub-directories. (for example wordpress and phpmyadmin worked fine)
So here is my solution. I decided to enable php module. so I ran this command:
a2enmod php7.2
but I got this errors:
Considering dependency mpm_prefork for php7.2: Considering conflict mpm_event for mpm_prefork: ERROR: Module mpm_event is enabled - cannot proceed due to conflicts. It needs to be disabled first! Considering conflict mpm_worker for mpm_prefork: ERROR: Could not enable dependency mpm_prefork for php7.2, aborting
so I decided to disable mpm by running following commands:
sudo a2dismod mpm_prefork
sudo a2dismod mpm_worker
sudo a2dismod mpm_event
then restart apache:
systemctl restart apache2
then enable php7.2 (my installed version):
sudo a2enmod php7.2
and right now everything works fine.
try
cat ~/.mysql_history
this will show you all mysql commands ran on the system
reload
is a builtin in Python 2, but not in Python 3, so the error you're seeing is expected.
If you truly must reload a module in Python 3, you should use either:
importlib.reload
for Python 3.4 and aboveimp.reload
for Python 3.0 to 3.3 (deprecated since Python 3.4 in favour of importlib
) I've seen this anti-pattern from people who don't quite get the & address-of operator. If they need to call a function with a pointer, they'll always allocate on the heap so they get a pointer.
void FeedTheDog(Dog* hungryDog);
Dog* badDog = new Dog;
FeedTheDog(badDog);
delete badDog;
Dog goodDog;
FeedTheDog(&goodDog);
Your error message is pretty explicit about what is going wrong:
laravel/framework v5.2.9 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
Do you have mbstring
installed on your server and is it enabled?
You can install mbstring
as part of the libapache2-mod-php5 package:
sudo apt-get install libapache2-mod-php5
Or standalone with:
sudo apt-get install php-mbstring
Installing it will also enable it, however you can also enable it by editing your php.ini
file and remove the ;
that is commenting it out if it is already installed.
If this is on your local machine, then follow the appropriate steps to install this on your environment.
SJLJ (setjmp/longjmp): – available for 32 bit and 64 bit – not “zero-cost”: even if an exception isn’t thrown, it incurs a minor performance penalty (~15% in exception heavy code) – allows exceptions to traverse through e.g. windows callbacks
DWARF (DW2, dwarf-2) – available for 32 bit only – no permanent runtime overhead – needs whole call stack to be dwarf-enabled, which means exceptions cannot be thrown over e.g. Windows system DLLs.
SEH (zero overhead exception) – will be available for 64-bit GCC 4.8.
source: https://wiki.qt.io/MinGW-64-bit
Convert the Special characters to apostrophe,
Data <- gsub("[^0-9A-Za-z///' ]","'" , Data ,ignore.case = TRUE)
Below code it to remove extra ''' apostrophe
Data <- gsub("''","" , Data ,ignore.case = TRUE)
Use gsub(..)
function for replacing the special character with apostrophe
Try this query:
SELECT column_name
FROM table_name
GROUP BY column_name
HAVING COUNT(column_name) = 1;
One of the aspects of .NET I like the most are generics. Even if you write procedural code in F#, you will still benefit from type inference. It makes writing generic code easy.
In C#, you write concrete code by default, and you have to put in some extra work to write generic code.
In F#, you write generic code by default. After spending over a year of programming in both F# and C#, I find that library code I write in F# is both more concise and more generic than the code I write in C#, and is therefore also more reusable. I miss many opportunities to write generic code in C#, probably because I'm blinded by the mandatory type annotations.
There are however situations where using C# is preferable, depending on one's taste and programming style.
Don't forget to call this.
style.setFillPattern(CellStyle.Align_Fill);
Parameter may differ according to your need. Maybe CellStyle.FINE_DOTS or so.
In sproc, you can use the following condition:
DECLARE @USER_ID VARCAHR(15)=NULL --THIS VALUE IS NULL OR EMPTY DON'T MATTER
IF(COALESCE(@USER_ID,'')='')
PRINT 'HUSSAM'
This is a solution how to make autocomplete drop down list with VBA :
Firstly you need to insert a combo box into the worksheet and change its properties, and then running the VBA code to enable the autocomplete.
Get into the worksheet which contains the drop down list you want it to be autocompleted.
Before inserting the Combo box, you need to enable the Developer tab in the ribbon.
a). In Excel 2010 and 2013, click File > Options. And in the Options dialog box, click Customize Ribbon in the right pane, check the Developer box, then click the OK button.
b). In Outlook 2007, click Office button > Excel Options. In the Excel Options dialog box, click Popular in the right bar, then check the Show Developer tabin the Ribbon box, and finally click the OK button.
Then click Developer > Insert > Combo Box under ActiveX Controls.
Draw the combo box in current opened worksheet and right click it. Select Properties in the right-clicking menu.
Turn off the Design Mode with clicking Developer > Design Mode.
Right click on the current opened worksheet tab and click View Code.
Make sure that the current worksheet code editor is opened, and then copy and paste the below VBA code into it.
Code borrowed from extendoffice.com
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'Update by Extendoffice: 2018/9/21
Dim xCombox As OLEObject
Dim xStr As String
Dim xWs As Worksheet
Dim xArr
Set xWs = Application.ActiveSheet
On Error Resume Next
Set xCombox = xWs.OLEObjects("TempCombo")
With xCombox
.ListFillRange = ""
.LinkedCell = ""
.Visible = False
End With
If Target.Validation.Type = 3 Then
Target.Validation.InCellDropdown = False
Cancel = True
xStr = Target.Validation.Formula1
xStr = Right(xStr, Len(xStr) - 1)
If xStr = "" Then Exit Sub
With xCombox
.Visible = True
.Left = Target.Left
.Top = Target.Top
.Width = Target.Width + 5
.Height = Target.Height + 5
.ListFillRange = xStr
If .ListFillRange = "" Then
xArr = Split(xStr, ",")
Me.TempCombo.List = xArr
End If
.LinkedCell = Target.Address
End With
xCombox.Activate
Me.TempCombo.DropDown
End If
End Sub
Private Sub TempCombo_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Select Case KeyCode
Case 9
Application.ActiveCell.Offset(0, 1).Activate
Case 13
Application.ActiveCell.Offset(1, 0).Activate
End Select
End Sub
Click File > Close and Return to Microsoft Excel to close the Microsoft Visual Basic for Application window.
Now, just click the cell with drop down list, you can see the drop-down list is displayed as a combo box, then type the first letter into the box, the corresponding word will be completed automatically.
Note: This VBA code is not applied to merged cells.
Source : How To Autocomplete When Typing In Excel Drop Down List?
According to the Cloudera documentation - What's New in CDH 5.7.0 it includes Spark 1.6.0.
You could try something like this if you want to use cut
:
echo "1:2:3:4:5" | cut -d ":" -f5
You can also use grep
try like this :
echo " 1:2:3:4:5" | grep -o '[^:]*$'
You could use toPrecision() and toFixed() methods of Number type. Check this link How can I format numbers as money in JavaScript?
What is the difference between the following ways of handling InterruptedException? What is the best way to do it?
You've probably come to ask this question because you've called a method that throws InterruptedException
.
First of all, you should see throws InterruptedException
for what it is: A part of the method signature and a possible outcome of calling the method you're calling. So start by embracing the fact that an InterruptedException
is a perfectly valid result of the method call.
Now, if the method you're calling throws such exception, what should your method do? You can figure out the answer by thinking about the following:
Does it make sense for the method you are implementing to throw an InterruptedException
? Put differently, is an InterruptedException
a sensible outcome when calling your method?
If yes, then throws InterruptedException
should be part of your method signature, and you should let the exception propagate (i.e. don't catch it at all).
Example: Your method waits for a value from the network to finish the computation and return a result. If the blocking network call throws an
InterruptedException
your method can not finish computation in a normal way. You let theInterruptedException
propagate.int computeSum(Server server) throws InterruptedException { // Any InterruptedException thrown below is propagated int a = server.getValueA(); int b = server.getValueB(); return a + b; }
If no, then you should not declare your method with throws InterruptedException
and you should (must!) catch the exception. Now two things are important to keep in mind in this situation:
Someone interrupted your thread. That someone is probably eager to cancel the operation, terminate the program gracefully, or whatever. You should be polite to that someone and return from your method without further ado.
Even though your method can manage to produce a sensible return value in case of an InterruptedException
the fact that the thread has been interrupted may still be of importance. In particular, the code that calls your method may be interested in whether an interruption occurred during execution of your method. You should therefore log the fact an interruption took place by setting the interrupted flag: Thread.currentThread().interrupt()
Example: The user has asked to print a sum of two values. Printing "
Failed to compute sum
" is acceptable if the sum can't be computed (and much better than letting the program crash with a stack trace due to anInterruptedException
). In other words, it does not make sense to declare this method withthrows InterruptedException
.void printSum(Server server) { try { int sum = computeSum(server); System.out.println("Sum: " + sum); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // set interrupt flag System.out.println("Failed to compute sum"); } }
By now it should be clear that just doing throw new RuntimeException(e)
is a bad idea. It isn't very polite to the caller. You could invent a new runtime exception but the root cause (someone wants the thread to stop execution) might get lost.
Other examples:
Implementing
Runnable
: As you may have discovered, the signature ofRunnable.run
does not allow for rethrowingInterruptedExceptions
. Well, you signed up on implementingRunnable
, which means that you signed up to deal with possibleInterruptedExceptions
. Either choose a different interface, such asCallable
, or follow the second approach above.
Calling
Thread.sleep
: You're attempting to read a file and the spec says you should try 10 times with 1 second in between. You callThread.sleep(1000)
. So, you need to deal withInterruptedException
. For a method such astryToReadFile
it makes perfect sense to say, "If I'm interrupted, I can't complete my action of trying to read the file". In other words, it makes perfect sense for the method to throwInterruptedExceptions
.String tryToReadFile(File f) throws InterruptedException { for (int i = 0; i < 10; i++) { if (f.exists()) return readFile(f); Thread.sleep(1000); } return null; }
This post has been rewritten as an article here.
Let's say you have these lines of code:
test line one
test line two
test line three
test line four
Using Search and Replace Ctrl+H with Regex let's find this: ^
and replace it with "
, we'll have this:
"test line one
"test line two
"test line three
"test line four
Now let's search this: $
and replace it with "
, now we'll have this:
"test line one"
"test line two"
"test line three"
"test line four"
I use the following code on http://www.diagnomics.com/
Smooth transition from b/w to color with magnifying effect (scale)
img.color_flip {
filter: url(filters.svg#grayscale); /* Firefox 3.5+ */
filter: gray; /* IE5+ */
-webkit-filter: grayscale(1); /* Webkit Nightlies & Chrome Canary */
-webkit-transition: all .5s ease-in-out;
}
img.color_flip:hover {
filter: none;
-webkit-filter: grayscale(0);
-webkit-transform: scale(1.1);
}
printf("%0k.yf" float_variable_name)
Here k
is the total number of characters you want to get printed. k = x + 1 + y
(+ 1
for the dot) and float_variable_name
is the float variable that you want to get printed.
Suppose you want to print x digits before the decimal point and y digits after it. Now, if the number of digits before float_variable_name is less than x, then it will automatically prepend that many zeroes before it.
You must declare the reportfile as variable for console.
Problem is all the Dokumentations you can find are not running so .. I was give 1 day of my live to find the right way ....
Example: for batch/console
cmd.exe /K set FFREPORT=file='C:\ffmpeg\proto\test.log':level=32 && C:\ffmpeg\bin\ffmpeg.exe -loglevel warning -report -i inputfile f outputfile
Exemple Javascript:
var reortlogfile = "cmd.exe /K set FFREPORT=file='C:\ffmpeg\proto\" + filename + ".log':level=32 && C:\ffmpeg\bin\ffmpeg.exe" .......;
You can change the dir and filename how ever you want.
Frank from Berlin
import yaml
data = dict(
A = 'a',
B = dict(
C = 'c',
D = 'd',
E = 'e',
)
)
with open('data.yml', 'w') as outfile:
yaml.dump(data, outfile, default_flow_style=False)
The default_flow_style=False
parameter is necessary to produce the format you want (flow style), otherwise for nested collections it produces block style:
A: a
B: {C: c, D: d, E: e}
I would use a StringBuilder class for doing string manipulation as it will more efficient (being mutable)
string flights = "Flight A, B,C,D";
StringBuilder message = new StringBuilder();
message.Append("Hi We have these flights for you: ");
message.Append(flights);
message.Append(" . Which one do you want?");
Another disadvantage of case classes versus Enumerations when you will need to iterate or filter across all instances. This is a built-in capability of Enumeration (and Java enums as well) while case classes don't automatically support such capability.
In other words: "there's no easy way to get a list of the total set of enumerated values with case classes".
Remove the url from header and footer using below method
@page { size: letter; margin-top: 4mm;margin-bottom: 4mm }
If you are a linux user Update node to a later version by running
sudo apt update
sudo apt install build-essential checkinstall libssl-dev
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.35.1/install.sh | bash
nvm --version
nvm ls
nvm ls-remote
nvm install [version.number]
this should solve your problem
shell> mysqldump --no-data --routines --events test > dump-defs.sql
To read characters try
scan("/PathTo/file.csv", "")
If you're reading numeric values, then just use
scan("/PathTo/file.csv")
scan
by default will use white space as separator. The type of the second arg defines 'what' to read (defaults to double()).
It appears that in PHP you are obtaining the value of the submit button, not the select input. If you are using GET you will want to use $_GET['website_string']
or POST would be $_POST['website_string']
.
You will probably want the following HTML:
<select name="website_string">
<option value="" selected="selected"></option>
<option value="abc">ABC</option>
<option value="def">def</option>
<option value="hij">hij</option>
</select>
<input type="submit" />
With some PHP that looks like this:
<?php
$website_string = $_POST['website_string']; // or $_GET['website_string'];
?>
When working with graphical user interfaces, you need to remember that drawing on a pane is done in the Java AWT/Swing event queue. You can't just use the Graphics
object outside the paint()
/paintComponent()
/etc. methods.
However, you can use a technique called "Frame buffering". Basically, you need to have a BufferedImage and draw directly on it (see it's createGraphics()
method; that graphics context you can keep and reuse for multiple operations on a same BufferedImage
instance, no need to recreate it all the time, only when creating a new instance). Then, in your JPanel
's paintComponent()
, you simply need to draw the BufferedImage
instance unto the JPanel
. Using this technique, you can perform zoom, translation and rotation operations quite easily through affine transformations.
If you are calling the sign_up API (AWS Cognito) using Python3, you can use the following code.
def registerUser(userObj):
''' Registers the user to AWS Cognito.
'''
# Mobile number is not a mandatory field.
if(len(userObj['user_mob_no']) == 0):
mobilenumber = ''
else:
mobilenumber = userObj['user_country_code']+userObj['user_mob_no']
secretKey = bytes(settings.SOCIAL_AUTH_COGNITO_SECRET, 'latin-1')
clientId = settings.SOCIAL_AUTH_COGNITO_KEY
digest = hmac.new(secretKey,
msg=(userObj['user_name'] + clientId).encode('utf-8'),
digestmod=hashlib.sha256
).digest()
signature = base64.b64encode(digest).decode()
client = boto3.client('cognito-idp', region_name='eu-west-1' )
try:
response = client.sign_up(
ClientId=clientId,
Username=userObj['user_name'],
Password=userObj['password1'],
SecretHash=signature,
UserAttributes=[
{
'Name': 'given_name',
'Value': userObj['given_name']
},
{
'Name': 'family_name',
'Value': userObj['family_name']
},
{
'Name': 'email',
'Value': userObj['user_email']
},
{
'Name': 'phone_number',
'Value': mobilenumber
}
],
ValidationData=[
{
'Name': 'email',
'Value': userObj['user_email']
},
]
,
AnalyticsMetadata={
'AnalyticsEndpointId': 'string'
},
UserContextData={
'EncodedData': 'string'
}
)
except ClientError as error:
return {"errorcode": error.response['Error']['Code'],
"errormessage" : error.response['Error']['Message'] }
except Exception as e:
return {"errorcode": "Something went wrong. Try later or contact the admin" }
return {"success": "User registered successfully. "}
error.response['Error']['Code'] will be InvalidPasswordException, UsernameExistsException etc. So in the main function or where you are calling the function, you can write the logic to provide a meaningful message to the user.
An example for the response (error.response):
{
"Error": {
"Message": "Password did not conform with policy: Password must have symbol characters",
"Code": "InvalidPasswordException"
},
"ResponseMetadata": {
"RequestId": "c8a591d5-8c51-4af9-8fad-b38b270c3ca2",
"HTTPStatusCode": 400,
"HTTPHeaders": {
"date": "Wed, 17 Jul 2019 09:38:32 GMT",
"content-type": "application/x-amz-json-1.1",
"content-length": "124",
"connection": "keep-alive",
"x-amzn-requestid": "c8a591d5-8c51-4af9-8fad-b38b270c3ca2",
"x-amzn-errortype": "InvalidPasswordException:",
"x-amzn-errormessage": "Password did not conform with policy: Password must have symbol characters"
},
"RetryAttempts": 0
}
}
For further reference : https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cognito-idp.html#CognitoIdentityProvider.Client.sign_up
One way is to associating unique properties with your file while creation.
properties = "{ \
key='somekey' and \
value='somevalue'
}"
then create a query.
query = "title = " + "\'" + title + "\'" + \
AND + "mimeType = " + "\'" + mimeType + "\'" + \
AND + "trashed = false" + \
AND + "properties has " + properties
All the file properties(title, etc) already known to you can go here + properties.
Flexbox
#outer{_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
}
_x000D_
CSS grid
#outer {_x000D_
display: inline-grid;_x000D_
grid-template-rows: 100px 100px 100px;_x000D_
grid-template-columns: 100px 100px 100px;_x000D_
grid-gap: 3px;_x000D_
}
_x000D_
You can solve the issue in many ways.
In Java, all strings are immutable. When you are trying to modify a String
, what you are really doing is creating a new one. However, when you use a StringBuilder
, you are actually modifying the contents, instead of creating a new one.
>>> '\\&' == '\&'
True
>>> len('\\&')
2
>>> print('\\&')
\&
Or in other words: '\\&'
only contains one backslash. It's just escaped in the python shell's output for clarity.
Sometimes, when I know that I am working with numbers, I use this logic (if result is not greater than zero
):
if (!$result['column']>0){
}
FormBorderStyle = FormBorderStyle.Sizable;
TopMost = false;
WindowState = FormWindowState.Normal;
THIS CODE MAKE YOUR WINDOWS FULL SCREEN THIS WILL ALSO COVER WHOLE SCREEN
"how can i return a array in a c++ method and how must i declare it? int[] test(void); ??"
template <class X>
class Array
{
X *m_data;
int m_size;
public:
// there constructor, destructor, some methods
int Get(X* &_null_pointer)
{
if(!_null_pointer)
{
_null_pointer = new X [m_size];
memcpy(_null_pointer, m_data, m_size * sizeof(X));
return m_size;
}
return 0;
}
};
just for int
class IntArray
{
int *m_data;
int m_size;
public:
// there constructor, destructor, some methods
int Get(int* &_null_pointer)
{
if(!_null_pointer)
{
_null_pointer = new int [m_size];
memcpy(_null_pointer, m_data, m_size * sizeof(int));
return m_size;
}
return 0;
}
};
example
Array<float> array;
float *n_data = NULL;
int data_size;
if(data_size = array.Get(n_data))
{ // work with array }
delete [] n_data;
example for int
IntArray array;
int *n_data = NULL;
int data_size;
if(data_size = array.Get(n_data))
{ // work with array }
delete [] n_data;
u[8] = (u[8] | 0x80) & 0xBF // what's the purpose ?
u[6] = (u[6] | 0x40) & 0x4F // what's the purpose ?
These lines clamp the values of byte 6 and 8 to a specific range. rand.Read
returns random bytes in the range 0-255
, which are not all valid values for a UUID. As far as I can tell, this should be done for all the values in the slice though.
If you are on linux, you can alternatively call /usr/bin/uuidgen
.
package main
import (
"fmt"
"log"
"os/exec"
)
func main() {
out, err := exec.Command("uuidgen").Output()
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s", out)
}
Which yields:
$ go run uuid.go
dc9076e9-2fda-4019-bd2c-900a8284b9c4
For >= 2nd row values insert into table-
$file = fopen($filename, "r");
//$sql_data = "SELECT * FROM prod_list_1 ";
$count = 0; // add this line
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
//print_r($emapData);
//exit();
$count++; // add this line
if($count>1){ // add this line
$sql = "INSERT into prod_list_1(p_bench,p_name,p_price,p_reason) values ('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')";
mysql_query($sql);
} // add this line
}
In the case you want to pass a dynamic sized 2-d array to a function, using some pointers could work for you.
void func1(int *arr, int n, int m){
...
int i_j_the_element = arr[i * m + j]; // use the idiom of i * m + j for arr[i][j]
...
}
void func2(){
...
int arr[n][m];
...
func1(&(arr[0][0]), n, m);
}
The example code above was really helpful to me, however (as has been hinted at above), I think you need to use NSMutableURLRequest
rather than NSURLRequest
. In its current form, I couldn't get it to respond to the setHTTPMethod
call. Changing the type fixed things right up.
The best and easiest way to clear a JLIST is:
myJlist.setListData(new String[0]);
It uses the equals method on the objects. So unless Thing overrides equals and uses the variables stored in the objects for comparison, it will not return true on the contains()
method.
you have to set the tableName you want to your dtimage that is for instance
dtImage.TableName="mydtimage";
if(!ds.Tables.Contains(dtImage.TableName))
ds.Tables.Add(dtImage);
it will be reflected in dataset because dataset is a container of your datatable dtimage and you have a reference on your dtimage
Use DATE_FORMAT
from Date Conversions:
In your initializer:
DateTime::DATE_FORMATS[:my_date_format] = "%a %b %d %H:%M:%S %Z %Y"
In your view:
date = DateTime.parse("2011-05-19 10:30:14")
date.to_formatted_s(:my_date_format)
date.to_s(:my_date_format)
<?php
function fWriteFile($sFileName,$sFileContent="No Data",$ROOT)
{
$word = new COM("word.application") or die("Unable to instantiate Word");
//bring it to front
$word->Visible = 1;
//open an empty document
$word->Documents->Add();
//do some weird stuff
$word->Selection->TypeText($sFileContent);
$word->Documents[1]->SaveAs($ROOT."/".$sFileName.".doc");
//closing word
$word->Quit();
//free the object
$word = null;
return $sFileName;
}
?>
<?php
$PATH_ROOT=dirname(__FILE__);
$Return ="<table>";
$Return .="<tr><td>Row[0]</td></tr>";
$Return .="<tr><td>Row[1]</td></tr>";
$sReturn .="</table>";
fWriteFile("test",$Return,$PATH_ROOT);
?>
You can bind to all of the radio buttons at once by name:
$('input[name=someRadioGroup]:radio').change(...);
Working example here: http://jsfiddle.net/Ey4fa/
if anybody unable to update windows online, I suggest you go to http://download.wsusoffline.net/ and download Most recent version.
Then install update generator -> select your operating system. and hit START, just wait few minutes let him download updates and complete all it's process. hope this help.
If you want the quick and dirty way and don't worry about XSS attack, use params.merge
to keep previous parameters. e.g.
<%= link_to 'Link', params.merge({:per_page => 20}) %>
see: https://stackoverflow.com/a/4174493/445908
Otherwise , check this answer: params.merge and cross site scripting
The accepted answer is shortsighted and the question a bit loose in that:
1) Neither explicitly mention whether a covering index is present in the left, right, or both sides.
2) Neither takes into account the size of input left side set and input right side set.
(The question just mentions an overall large result set).
I believe the optimizer is smart enough to convert between "in" vs "exists" when there is a significant cost difference due to (1) and (2), otherwise it may just be used as a hint (e.g. exists to encourage use of an a seekable index on the right side).
Both forms can be converted to join forms internally, have the join order reversed, and run as loop, hash or merge--based on the estimated row counts (left and right) and index existence in left, right, or both sides.
SELECT T.TABLE_NAME, C.COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS C
INNER JOIN INFORMATION_SCHEMA.TABLES T ON T.TABLE_NAME = C.TABLE_NAME
WHERE TABLE_TYPE = 'BASE TABLE'
AND COLUMN_NAME = 'ColName'
This returns tables only and ignores views for anyone who is interested!
Adding a slight variation on Aaronaught's solution, I typically parametrize page number (@PageNum) and page size (@PageSize). This way each page click event just sends in the requested page number along with a configurable page size:
begin
with My_CTE as
(
SELECT col1,
ROW_NUMBER() OVER(ORDER BY col1) AS row_number
FROM
My_Table
WHERE
<<<whatever>>>
)
select * from My_CTE
WHERE RowNum BETWEEN (@PageNum - 1) * (@PageSize + 1)
AND @PageNum * @PageSize
end
Are these structures padded or packed?
They're padded.
The only possibility that initially springs to mind, where they could be packed, is if char
and int
were the same size, so that the minimum size of the char/int/char
structure would allow for no padding, ditto for the int/char
structure.
However, that would require both sizeof(int)
and sizeof(char)
to be four (to get the twelve and eight sizes). The whole theory falls apart since it's guaranteed by the standard that sizeof(char)
is always one.
Were char
and int
the same width, the sizes would be one and one, not four and four. So, in order to then get a size of twelve, there would have to be padding after the final field.
When does padding or packing take place?
Whenever the compiler implementation wants it to. Compilers are free to insert padding between fields, and following the final field (but not before the first field).
This is usually done for performance as some types perform better when they're aligned on specific boundaries. There are even some architectures that will refuse to function (i.e, crash) is you try to access unaligned data (yes, I'm looking at you, ARM).
You can generally control packing/padding (which is really opposite ends of the same spectrum) with implementation-specific features such as #pragma pack
. Even if you cannot do that in your specific implementation, you can check your code at compile time to ensure it meets your requirement (using standard C features, not implementation-specific stuff).
For example:
// C11 or better ...
#include <assert.h>
struct strA { char a; int b; char c; } x;
struct strB { int b; char a; } y;
static_assert(sizeof(struct strA) == sizeof(char)*2 + sizeof(int), "No padding allowed");
static_assert(sizeof(struct strB) == sizeof(char) + sizeof(int), "No padding allowed");
Something like this will refuse to compile if there is any padding in those structures.
I had no programming background and wanted to learn PHP. It took me about 6 months practicing beside my normal job to develop my skills enough to write some simple applications for a website. Java is a bit more complex...
I've used neocomplcache for about half a year. It is a plugin that collects a cache of words in all your buffers and then provides them for you to auto-complete with.
There is an array of screenshots on the project page in the previous link. Neocomplcache also has a ton of configuration options, of which there are basic examples on the project page as well.
If you need more depth, you can look at the relevant section in my vimrc - just search for the word neocomplcache.
Is not as old as other questions, but I just struggled with this in an Ionic-Laravel app, and nothing works from here (and other posts), so I installed https://github.com/barryvdh/laravel-cors complement in Laravel and started and it works pretty well.
open my Computer ==>
right click inside my computer and select properties ==>
Click on Advanced System Settings ==>
Environment Variables ==>
from the System Variables box select "PATH" ==>
Edit... ==>
then add this at the end of whatever you find their
;C:\PostgreSQL\9.2\bin; C:\PostgreSQL\9.2\lib
after that continue to click OK
open cmd/command prompt.... open psql in command prompt with this
psql -U username database
eg. i have a database name FRIENDS and a user MEE.. it will be
psql -U MEE FRIENDS
you will be then prompted to give the password of the user in question. Thanks
It may be useful to notice that very good answers given above may not be enough. It is because of one more tick is required here:
This command works for me:
./mysql -u root -p
(PS: I'm working on mac through terminal)
String temp = s.Replace("\r\n","").Trim();
s
being the original string. (Note capitals)
There's a decent overview of how Facebook does it here on nfriedly.com
There's also Browser Fingerprinting, which is not the same as a cookie, but serves a like purpose in that it helps you identify a user with a fair degree of certainty. There's a post here on Stack Overflow that references upon one method of fingerprinting
Thing I did: Using less fragment when possible. Unfortunately, it's possible in almost case. So, I end up with a lot of fragments and a little of activities. Some drawbacks I've realized:
ActionBar
& Menu: When 2 fragment has different title, menu, thatbackstack
there is no way to restore the old title. You may need an Toolbar in every fragment for this case, but let believe me, that will spend you more time. startForResult
, activity has but fragment hasn't.My solution for this is using an Activity to wrap a fragment inside. So we have separate action bar, menu, startActivityForResult
, animation,...
The term for T&&
when used with type deduction (such as for perfect forwarding) is known colloquially as a forwarding reference. The term "universal reference" was coined by Scott Meyers in this article, but was later changed.
That is because it may be either r-value or l-value.
Examples are:
// template
template<class T> foo(T&& t) { ... }
// auto
auto&& t = ...;
// typedef
typedef ... T;
T&& t = ...;
// decltype
decltype(...)&& t = ...;
More discussion can be found in the answer for: Syntax for universal references
There is one tool with source code available at http://www.codeproject.com/Articles/205011/SQL-Server-Database-Comparison-Tool
That should give flexibility as code is available.
Try putting it in quotes:
find . -name '*test.c'
This is how ended up getting the current scroll position live from the view. All I am doing is using the on scroll event listener and the scrollEventThrottle. I am then passing it as an event to handle scroll function I made and updating my props.
export default class Anim extends React.Component {
constructor(props) {
super(props);
this.state = {
yPos: 0,
};
}
handleScroll(event){
this.setState({
yPos : event.nativeEvent.contentOffset.y,
})
}
render() {
return (
<ScrollView onScroll={this.handleScroll.bind(this)} scrollEventThrottle={16} />
)
}
}
const fileInput = document.querySelector('input');
fileInput.addEventListener('change', (e) => {
// get a reference to the file
const file = e.target.files[0];
// encode the file using the FileReader API
const reader = new FileReader();
reader.onloadend = () => {
// use a regex to remove data url part
const base64String = reader.result
.replace('data:', '')
.replace(/^.+,/, '');
// log to console
// logs wL2dvYWwgbW9yZ...
console.log(base64String);
};
reader.readAsDataURL(file);});
i Did it, just follow this tutorial. helps a lot
Is a copy from javadb (because is down)
http://informatictips.blogspot.pt/2013/09/using-message-handler-to-alter-soap.html
or
http://www.javadb.com/using-a-message-handler-to-alter-the-soap-header-in-a-web-service-client
In my case, when using IntelliJ, I had multiple modules in the project. The main module was dependent on another module which had the maven dependencies on Spring.
The main module had Entity
s and so did the second module. But when I ran the main module, only the Entity
s from the second module got recognized as managed classes.
I then added Spring dependencies on the main module as well, and guess what? It recognized all the Entity
s.
When you write the statement
*src = "anotherstring";
the compiler sees the constant string "abcdefghijklmnop"
like an array. Imagine you had written the following code instead:
char otherstring[14] = "anotherstring";
...
*src = otherstring;
Now, it's a bit clearer what is going on. The left-hand side, *src
, refers to a char
(since src
is of type pointer-to-char
) whereas the right-hand side, otherstring
, refers to a pointer.
This isn't strictly forbidden because you may want to store the address that a pointer points to. However, an explicit cast is normally used in that case (which isn't too common of a case). The compiler is throwing up a red flag because your code is likely not doing what you think it is.
It appears to me that you are trying to assign a string. Strings in C aren't data types like they are in C++ and are instead implemented with char
arrays. You can't directly assign values to a string like you are trying to do. Instead, you need to use functions like strncpy
and friends from <string.h>
and use char
arrays instead of char
pointers. If you merely want the pointer to point to a different static string, then drop the *
.
I had this issue start happening when debugging from one web project to a web service in the same solution. The web service was returning responses that the web project couldnt understand. It would kind of work again at some points, then stop again.
It was because there was not an explicit reference between these projects, so the web service was not getting built when hitting F5 to start debugging. Once I added that, the errors went away.
Use the same function (cor
) on a data frame, e.g.:
> cor(VADeaths)
Rural Male Rural Female Urban Male Urban Female
Rural Male 1.0000000 0.9979869 0.9841907 0.9934646
Rural Female 0.9979869 1.0000000 0.9739053 0.9867310
Urban Male 0.9841907 0.9739053 1.0000000 0.9918262
Urban Female 0.9934646 0.9867310 0.9918262 1.0000000
Or, on a data frame also holding discrete variables, (also sometimes referred to as factors), try something like the following:
> cor(mtcars[,unlist(lapply(mtcars, is.numeric))])
mpg cyl disp hp drat wt qsec vs am gear carb
mpg 1.0000000 -0.8521620 -0.8475514 -0.7761684 0.68117191 -0.8676594 0.41868403 0.6640389 0.59983243 0.4802848 -0.55092507
cyl -0.8521620 1.0000000 0.9020329 0.8324475 -0.69993811 0.7824958 -0.59124207 -0.8108118 -0.52260705 -0.4926866 0.52698829
disp -0.8475514 0.9020329 1.0000000 0.7909486 -0.71021393 0.8879799 -0.43369788 -0.7104159 -0.59122704 -0.5555692 0.39497686
hp -0.7761684 0.8324475 0.7909486 1.0000000 -0.44875912 0.6587479 -0.70822339 -0.7230967 -0.24320426 -0.1257043 0.74981247
drat 0.6811719 -0.6999381 -0.7102139 -0.4487591 1.00000000 -0.7124406 0.09120476 0.4402785 0.71271113 0.6996101 -0.09078980
wt -0.8676594 0.7824958 0.8879799 0.6587479 -0.71244065 1.0000000 -0.17471588 -0.5549157 -0.69249526 -0.5832870 0.42760594
qsec 0.4186840 -0.5912421 -0.4336979 -0.7082234 0.09120476 -0.1747159 1.00000000 0.7445354 -0.22986086 -0.2126822 -0.65624923
vs 0.6640389 -0.8108118 -0.7104159 -0.7230967 0.44027846 -0.5549157 0.74453544 1.0000000 0.16834512 0.2060233 -0.56960714
am 0.5998324 -0.5226070 -0.5912270 -0.2432043 0.71271113 -0.6924953 -0.22986086 0.1683451 1.00000000 0.7940588 0.05753435
gear 0.4802848 -0.4926866 -0.5555692 -0.1257043 0.69961013 -0.5832870 -0.21268223 0.2060233 0.79405876 1.0000000 0.27407284
carb -0.5509251 0.5269883 0.3949769 0.7498125 -0.09078980 0.4276059 -0.65624923 -0.5696071 0.05753435 0.2740728 1.00000000
A timer is a better idea, IMO. That way, if your service is asked to stop, it can respond to that very quickly, and just not call the timer tick handler again... if you're sleeping, the service manager will either have to wait 50 seconds or kill your thread, neither of which is terribly nice.
Exactly.
Projection means choosing which columns (or expressions) the query shall return.
Selection means which rows are to be returned.
if the query is
select a, b, c from foobar where x=3;
then "a, b, c" is the projection part, "where x=3" the selection part.
Assuming the parent has a fixed width, e.g #page { width: 1000px; }
and is centered #page { margin: auto; }
, you want the child to fit the width of browser viewport you could simply do:
#page {
margin: auto;
width: 1000px;
}
.fullwidth {
margin-left: calc(500px - 50vw); /* 500px is half of the parent's 1000px */
width: 100vw;
}
Common reasons for the error:
=
) instead of equality (==
/===
)foo() = 42
instead of passing arguments (foo(42)
) getFoo() = 42
instead of getFoo().theAnswer = 42
or array indexing getArray() = 42
instead of getArray()[0]= 42
In this particular case you want to use ==
(or better ===
- What exactly is Type Coercion in Javascript?) to check for equality (like if(one === "rock" && two === "rock")
, but it the actual reason you are getting the error is trickier.
The reason for the error is Operator precedence. In particular we are looking for &&
(precedence 6) and =
(precedence 3).
Let's put braces in the expression according to priority - &&
is higher than =
so it is executed first similar how one would do 3+4*5+6
as 3+(4*5)+6
:
if(one= ("rock" && two) = "rock"){...
Now we have expression similar to multiple assignments like a = b = 42
which due to right-to-left associativity executed as a = (b = 42)
. So adding more braces:
if(one= ( ("rock" && two) = "rock" ) ){...
Finally we arrived to actual problem: ("rock" && two)
can't be evaluated to l-value that can be assigned to (in this particular case it will be value of two
as truthy).
Note that if you'd use braces to match perceived priority surrounding each "equality" with braces you get no errors. Obviously that also producing different result than you'd expect - changes value of both variables and than do &&
on two strings "rock" && "rock"
resulting in "rock"
(which in turn is truthy) all the time due to behavior of logial &&:
if((one = "rock") && (two = "rock"))
{
// always executed, both one and two are set to "rock"
...
}
For even more details on the error and other cases when it can happen - see specification:
LeftHandSideExpression = AssignmentExpression
...
Throw a SyntaxError exception if the following conditions are all true:
...
IsStrictReference(lref) is true
and The Reference Specification Type explaining IsStrictReference:
... function calls are permitted to return references. This possibility is admitted purely for the sake of host objects. No built-in ECMAScript function defined by this specification returns a reference and there is no provision for a user-defined function to return a reference...
Safari on iPad user agent string in iPhone OS 3.2 SDK beta 3:
Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10
More info: http://developer.apple.com/library/safari/#technotes/tn2010/tn2262/_index.html
While a bit more cryptic than join
, you can also multiply the array by a string.
@arr * " "
(this error message is typically misleading, and is usually a general permissions error)
On Windows
in AndroidManifest.xml set theme holo like this:
<activity
android:name="your Fragment or activity"
android:label="@string/xxxxxx"
android:theme="@android:style/Theme.Holo" >
There are two things you need to check:
To ensure that your user account has administrator privilege, run lusrmgr.msc
from the Windows Start > Run menu to bring up the Local Users and Groups
Windows. Double-click on your user account that appears under Users
, and verifies that it is a member of Administrators
.
To disable UAC (as an administrator), from Control Panel
:
Change User Account Control
settings in the search results.Never notify
and click OK.open up the User Accounts
window from Control Panel
. Click on the Turn User Account Control on or off
option, and un-check the checkbox.
Alternately, if you don't want to disable UAC, you will have to install XAMPP in a different folder, outside of C:\Program Files (x86)
, such as C:\xampp
.
Hope this helps.
If the client quota is exceeded it is a server error, avoid 5xx in this instance.
This is the best and simplest way to understand joins:
Credits go to the writer of this article HERE
What you want to do is separate the content of the table from the header of the table.
You want only the <th>
elements to be scrolled.
You can easily define this separation in HTML with the <tbody>
and the <thead>
elements.
Now the header and the body of the table are still connected to each other, they will still have the same width (and same scroll properties). Now to let them not 'work' as a table anymore you can set the display: block
. This way <thead>
and <tbody>
are separated.
table tbody, table thead
{
display: block;
}
Now you can set the scroll to the body of the table:
table tbody
{
overflow: auto;
height: 100px;
}
And last, because the <thead>
doesn't share the same width as the body anymore, you should set a static width to the header of the table:
th
{
width: 72px;
}
You should also set a static width for <td>
. This solves the issue of the unaligned columns.
td
{
width: 72px;
}
<tr>
element, that includes the header row:
<tr>
<th>head1</th>
<th>head2</th>
<th>head3</th>
<th>head4</th>
</tr>
I hope this is what you meant.
Addendum
If you would like to have more control over the column widths, have them to vary in width between each other, and course keep the header and body columns aligned, you can use the following example:
table th:nth-child(1), td:nth-child(1) { min-width: 50px; max-width: 50px; }
table th:nth-child(2), td:nth-child(2) { min-width: 100px; max-width: 100px; }
table th:nth-child(3), td:nth-child(3) { min-width: 150px; max-width: 150px; }
table th:nth-child(4), td:nth-child(4) { min-width: 200px; max-width: 200px; }
{{widget.title}}
Try this it will work
Try pfiles PID
to show all open files for a process.
According to the documentation.
If you are running on the TensorFlow or CNTK backends, your code will automatically run on GPU if any available GPU is detected.
You can check what all devices are used by tensorflow by -
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
Also as suggested in this answer
import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
This will print whether your tensorflow is using a CPU or a GPU backend. If you are running this command in jupyter notebook, check out the console from where you have launched the notebook.
If you are sceptic whether you have installed the tensorflow gpu version or not. You can install the gpu version via pip.
pip install tensorflow-gpu
I had the same error when was trying to update linked table.
The issue was that linked table had no PRIMARY KEY.
After adding primary key constraint on database side and re linking this table to access problem was solved.
Hope it will help somebody.
The following should work for you:
[\n\r].*Object Name:\s*([^\n\r]*)
Your desired match will be in capture group 1.
[\n\r][ \t]*Object Name:[ \t]*([^\n\r]*)
Would be similar but not allow for things such as " blah Object Name: blah" and also make sure that not to capture the next line if there is no actual content after "Object Name:"
For generic use (run python/haskell/ruby/C++... from vim based on the filetype
), there's a nice plugin called vim-quickrun. It supports many programming languages by default. It is easily configurable, too, so one can define preferred behaviours for any filetype if needed. The github repo does not have a fancy readme, but it is well documented with the doc file.
Adding a shell script e.g. run.sh
makes it much more easier:
#!/usr/bin/env bash
export JAVA_PROGRAM_ARGS=`echo "$@"`
mvn exec:java -Dexec.mainClass="test.Main" -Dexec.args="$JAVA_PROGRAM_ARGS"
Then you are able to execute:
./run.sh arg1 arg2 arg3
$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
must be
$q = $dbh->prepare("DESCRIBE database.table");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
out has gotten a new more succint syntax in C#7 https://docs.microsoft.com/en-us/dotnet/articles/csharp/whats-new/csharp-7#more-expression-bodied-members and even more exciting is the C#7 tuple enhancements that are a more elegant choice than using ref and out IMHO.
The reason for this error is very simple. Your AJAX is trying to call over HTTP whereas your server is running over HTTPS, so your server is denying calling your AJAX. This can be fixed by adding the following line inside the head tag of your main HTML file:
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
This might seem like overkill, but if in another case you were trying to load a canvas from js (like I am doing), you could use a setInterval function and an if statement to constantly check if the canvas has loaded.
//set up the interval
var thisInterval = setInterval(function{
//this if statment checks if the id "thisCanvas" is linked to something
if(document.getElementById("thisCanvas") != null){
//do what you want
//clearInterval() will remove the interval if you have given your interval a name.
clearInterval(thisInterval)
}
//the 500 means that you will loop through this every 500 milliseconds (1/2 a second)
},500)
(In this example the canvas I am trying to load has an id of "thisCanvas")
Cern's ROOT produces some pretty nice stuff, I use it to display Neural Network data a lot.
I have been working on to write a custom module in Drupal 7 and got the same error:
Notice: Trying to get property of non-object
My code is something like this:
function example_node_access($node, $op, $account) {
if ($node->type == 'page' && $op == 'update') {
drupal_set_message('This poll has been published, you may not make changes to it.','error');
return NODE_ACCESS_DENY;
}
}
Solution:
I just added a condition if (is_object($sqlResult))
, and everything went fine.
Here is my final code:
function mediaten_node_access($node, $op, $account) {
if (is_object($node)){
if ($node->type == 'page' && $op == 'update') {
drupal_set_message('This poll has been published, you may not make changes.','error');
return NODE_ACCESS_DENY;
}
}
}
to indent a ul
dropdown menu, use
/* Main Level */
ul{
margin-left:10px;
}
/* Second Level */
ul ul{
margin-left:15px;
}
/* Third Level */
ul ul ul{
margin-left:20px;
}
/* and so on... */
You can indent the li
s and (if applicable) the a
s (or whatever content elements you have) as well , each with differing effects.
You could also use padding-left
instead of margin-left
, again depending on the effect you want.
Update
By default, many browsers use padding-left
to set the initial indentation. If you want to get rid of that, set padding-left: 0px;
Still, both margin-left
and padding-left
settings impact the indentation of lists in different ways. Specifically: margin-left
impacts the indentation on the outside of the element's border, whereas padding-left
affects the spacing on the inside of the element's border. (Learn more about the CSS box model here)
Setting padding-left: 0;
leaves the li's bullet icons hanging over the edge of the element's border (at least in Chrome), which may or may not be what you want.
Examples of padding-left vs margin-left and how they can work together on ul: https://jsfiddle.net/daCrosby/bb7kj8cr/1/
I noticed some of the answers were not triggering the HTML5 required
attribute (as stuff was being executed on the action of clicking rather than the action of form send, causing to bypass it when the inputs were empty):
<form id='xform'></form>
with some inputs with the required attribute and place a <input type='submit'>
at the end.<input type='text' name='xconf' value='' required>
modal_1_accept
to the accept button.modal_2_accept
to the accept button.m2_Txt
to the displayed text holder.The JS to intercept before the form is sent:
$("#xform").submit(function(e){
var msg, conf, preventSend;
if($("#xform").attr("data-send")!=="ready"){
msg="Error."; //default error msg
preventSend=false;
conf=$("[name='xconf']").val().toLowerCase().replace(/^"|"$/g, "");
if(conf===""){
msg="The field is empty.";
preventSend=true;
}else if(conf!=="ok"){
msg="You didn't write \"ok\" correctly.";
preventSend=true;
}
if(preventSend){ //validation failed, show the error
$("#m2_Txt").html(msg); //displayed text on modal_2_errMsg
$("#modal_2_errMsg").modal("show");
}else{ //validation passed, now let's confirm the action
$("#modal_1_confirm").modal("show");
}
e.preventDefault();
return false;
}
});
`9. Also some stuff when clicking the Buttons from the modals:
$("#modal_1_accept").click(function(){
$("#modal_1_confirm").modal("hide");
$("#xform").attr("data-send", "ready").submit();
});
$("#modal_2_accept").click(function(){
$("#modal_2_errMsg").modal("hide");
});
Important Note: So just be careful if you add an extra way to show the modal, as simply clicking the accept button $("#modal_1_accept")
will assume the validation passed and it will add the "ready"
attribute:
$("#modal_1_confirm").modal("show");
is shown only when it passed
the validation, so clicking $("#modal_1_accept")
should be
unreachable without first getting the form validated.I don't know is there any method in Python API.But you can use this simple code to add Salt-and-Pepper noise to an image.
import numpy as np
import random
import cv2
def sp_noise(image,prob):
'''
Add salt and pepper noise to image
prob: Probability of the noise
'''
output = np.zeros(image.shape,np.uint8)
thres = 1 - prob
for i in range(image.shape[0]):
for j in range(image.shape[1]):
rdn = random.random()
if rdn < prob:
output[i][j] = 0
elif rdn > thres:
output[i][j] = 255
else:
output[i][j] = image[i][j]
return output
image = cv2.imread('image.jpg',0) # Only for grayscale image
noise_img = sp_noise(image,0.05)
cv2.imwrite('sp_noise.jpg', noise_img)
I had the same problem and found that there was no package.json in my project (but only the package-lock.json). I then
..and all worked out fine. Took a while to figure it out, but that did it for me.
For C++, you could do:
export CXXFLAGS=-m32
This works with cmake.
This may also be achieved using matplotlib.pyplot.quiver
, as noted in the linked answer;
plt.quiver([0, 0, 0], [0, 0, 0], [1, -2, 4], [1, 2, -7], angles='xy', scale_units='xy', scale=1)
plt.xlim(-10, 10)
plt.ylim(-10, 10)
plt.show()
Why don't use associative array, so you can use it easily
function unserializeForm($str) {
$returndata = array();
$strArray = explode("&", $str);
$i = 0;
foreach ($strArray as $item) {
$array = explode("=", $item);
$returndata[$array[0]] = $array[1];
}
return $returndata;
}
Regards
Instead of using urllib.request.urlopen() remove request for python 2.
urllib.urlopen() you do not have to request in python 2.x for what you are trying to do. Hope it works for you. This was tested using python 2.7 I was receiving the same error message and this resolved it.
TCPView is a Windows program that will show you detailed listings of all TCP and UDP endpoints on your system, including the local and remote addresses and state of TCP connections. On Windows Server 2008, Vista, NT, 2000 and XP TCPView also reports the name of the process that owns the endpoint. TCPView provides a more informative and conveniently presented subset of the Netstat program that ships with Windows. The TCPView download includes Tcpvcon, a command-line version with the same functionality.
http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx
Was able to set the auth using the HttpsURLConnection
URL myUrl = new URL(httpsURL);
HttpsURLConnection conn = (HttpsURLConnection)myUrl.openConnection();
String userpass = username + ":" + password;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
//httpsurlconnection
conn.setRequestProperty("Authorization", basicAuth);
few of the changes fetched from this post. and Base64 is from java.util package.
=LEFT(A1,FIND(IF(
ISERROR(
FIND("_",A1)
),A1,RIGHT(A1,
LEN(A1)-FIND("~",
SUBSTITUTE(A1,"_","~",
LEN(A1)-LEN(SUBSTITUTE(A1,"_",""))
)
)
)
),A1,1)-2)
The question did not state precisely what output is expected but assuming that for month you want the month number (January = 1) and for the year you want the numeric 4 digit year then assuming that we have just run the code in the question:
cycle(date1)
## [1] 3
as.integer(date1)
## [1] 2012
I think setting your header to Access-Control-Allow-Origin: *
would do the trick here. Had the same issue and I resolved it like that.
Yes, a struct
is identical to a class
except for the default access level (member-wise and inheritance-wise). (and the extra meaning class
carries when used with a template)
Every functionality supported by a class is consequently supported by a struct. You'd use methods the same as you'd use them for a class.
struct foo {
int bar;
foo() : bar(3) {} //look, a constructor
int getBar()
{
return bar;
}
};
foo f;
int y = f.getBar(); // y is 3
This happened to me when I was on develop branch and my master branch is not with latest update.
So when I tried to git push from develop branch I had that error.
I fixed it by switching to master branch, git pull, then go back to develop branch and git push.
$ git fetch && git checkout master
$ git pull
$ git fetch && git checkout develop
$ git push
UPDATE
only changes the values you specify:
UPDATE table SET cell='new_value' WHERE whatever='somevalue'
Your logic is flawed... basically, you need to:
You're not doing step 2.
Here's the code you want:
Properties prop = new Properties();
prop.load(new FileInputStream("/displayCategerization.properties"));
for (Map.Entry<Object, Object> entry : prop.entrySet())
{
List<String> categoryList = categoryMap.get((String) entry.getKey());
if (categoryList == null)
{
categoryList = new ArrayList<String>();
LogDisplayService.categoryMap.put((String) entry.getKey(), categoryList);
}
categoryList.add((String) entry.getValue());
}
Note also the "correct" way to iterate over the entries of a map/properties - via its entrySet()
.
The code below is the simplest way to filter an array with respect to another array. Both arrays can have objects inside them instead of values.
let array1 = [1, 3, 47, 1, 6, 7];
let array2 = [3, 6];
let filteredArray1 = array1.filter(el => array2.includes(el));
console.log(filteredArray1);
_x000D_
Output: [3, 6]
Query Analyzer buffers messages. The PRINT and RAISERROR statements both use this buffer, but the RAISERROR statement has a WITH NOWAIT option. To print a message immediately use the following:
RAISERROR ('Your message', 0, 1) WITH NOWAIT
RAISERROR will only display 400 characters of your message and uses a syntax similar to the C printf function for formatting text.
Please note that the use of RAISERROR with the WITH NOWAIT option will flush the message buffer, so all previously buffered information will be output also.
You can simply place a forward declaration of your second()
function in your main.cpp
above main()
. If your second.cpp
has more than one function and you want all of it in main()
, put all the forward declarations of your functions in second.cpp
into a header file and #include
it in main.cpp
.
Like this-
Second.h:
void second();
int third();
double fourth();
main.cpp:
#include <iostream>
#include "second.h"
int main()
{
//.....
return 0;
}
second.cpp:
void second()
{
//...
}
int third()
{
//...
return foo;
}
double fourth()
{
//...
return f;
}
Note that: it is not necessary to #include "second.h"
in second.cpp
. All your compiler need is forward declarations and your linker will do the job of searching the definitions of those declarations in the other files.
The option that I do is by using the popular Plus Messenger on Android. The play store link is: https://play.google.com/store/apps/details?id=org.telegram.plus&hl=en
You can click on the Channel and in Channel info below the group name, you can find Channel Id.
Supergroup and Channel Ids will looks like 1068773197 on plus messenger. For your usage on API, you can prefix -100 which would make it -1001068773197.
Select constraint_name,constraint_type from user_constraints where table_name** **= ‘TABLE_NAME’ ;
(This will list the primary key and then)
Select column_name,position from user_cons_cloumns where constraint_name=’PK_XYZ’;
(This will give you the column, here PK_XYZ is the primay key name)
Today, I was testing this with iOS 9 Beta and found the solution.
To solve it, go to:
We store our URLs in a database and load them at runtime.
public class ServiceClientFactory<TChannel> : ClientBase<TChannel> where TChannel : class
{
public TChannel Create(string url)
{
this.Endpoint.Address = new EndpointAddress(new Uri(url));
return this.Channel;
}
}
Implementation
var client = new ServiceClientFactory<yourServiceChannelInterface>().Create(newUrl);
For batch processing with files in folder aiming for 190 VBR and file extension = .mp3 instead of .ac3.mp3 you can use the following code
Change .ac3 to whatever the source audio format is.
for f in *.ac3 ; do ffmpeg -i "$f" -acodec libmp3lame -q:a 2 "${f%.*}.mp3"; done
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
var assemblyPath = assembly.GetFiles()[0].Name;
var assemblyDir = System.IO.Path.GetDirectoryName(assemblyPath);
columns by index:
# selected column index: 1, 6, 7
new = old.iloc[: , [1, 6, 7]].copy()
Perfect answer for your question can be found on MYSQL site itself.refer their manual(without using PHP)
http://forums.mysql.com/read.php?20,17671,27914
According to them use LONGBLOB datatype. with that you can only store images less than 1MB only by default,although it can be changed by editing server config file.i would also recommend using MySQL workBench for ease of database management
To get current skin URL use this Mage::getDesign()->getSkinUrl()
You can get this error if you define a project as an .exe but intent to create a .lib or a .dll
This answer says to use
mapfile -t myArray < file.txt
I made a shim for mapfile
if you want to use mapfile
on bash < 4.x for whatever reason. It uses the existing mapfile
command if you are on bash >= 4.x
Currently, only options -d
and -t
work. But that should be enough for that command above. I've only tested on macOS. On macOS Sierra 10.12.6, the system bash is 3.2.57(1)-release
. So the shim can come in handy. You can also just update your bash with homebrew, build bash yourself, etc.
It uses this technique to set variables up one call stack.
David Thomas’s answer describes a way to use $('#elem').attr('style', …)
, but warns that using it will delete previously-set styles in the style
attribute. Here is a way of using attr()
without that problem:
var $elem = $('#elem');
$elem.attr('style', $elem.attr('style') + '; ' + 'width: 100px !important');
As a function:
function addStyleAttribute($element, styleAttribute) {
$element.attr('style', $element.attr('style') + '; ' + styleAttribute);
}
addStyleAttribute($('#elem'), 'width: 100px !important');
Here is a JS Bin demo.
Using apache commons-io and Java 8 you can use
List<String> lines = FileUtils.readLines(file);
List<String> updatedLines = lines.stream().filter(s -> !s.contains(searchString)).collect(Collectors.toList());
FileUtils.writeLines(file, updatedLines, false);
JavaScript does not offer this functionality natively. And I doubt you could even create this type of functionality. For example:
var Bobby = {name: "Bobby"};
var Dad = {name: "Dad", children: [ Bobby ]};
var Mom = {name: "Mom", children: [ Bobby ]};
Who does Bobby belong to?
For AWS S3, setting the Cross-origin resource sharing (CORS) to the following worked for me:
[
{
"AllowedHeaders": [
"Authorization"
],
"AllowedMethods": [
"GET",
"HEAD"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": []
}
]
Try:
if (isset($_FILES['uploaded_file']) &&
$_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK) {
$mail->AddAttachment($_FILES['uploaded_file']['tmp_name'],
$_FILES['uploaded_file']['name']);
}
Basic example can also be found here.
The function definition for AddAttachment
is:
public function AddAttachment($path,
$name = '',
$encoding = 'base64',
$type = 'application/octet-stream')
One corner case to keep in mind, which surprised me when I first found out about it: Windows allows leading space characters in file names! For example, the following are all legal, and distinct, file names on Windows (minus the quotes):
"file.txt"
" file.txt"
" file.txt"
One takeaway from this: Use caution when writing code that trims leading/trailing whitespace from a filename string.
If you want to run a single independent queued operation and you’re not concerned with other concurrent operations, you can use the global concurrent queue:
dispatch_queue_t globalConcurrentQueue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
This will return a concurrent queue with the given priority as outlined in the documentation:
DISPATCH_QUEUE_PRIORITY_HIGH Items dispatched to the queue will run at high priority, i.e. the queue will be scheduled for execution before any default priority or low priority queue.
DISPATCH_QUEUE_PRIORITY_DEFAULT Items dispatched to the queue will run at the default priority, i.e. the queue will be scheduled for execution after all high priority queues have been scheduled, but before any low priority queues have been scheduled.
DISPATCH_QUEUE_PRIORITY_LOW Items dispatched to the queue will run at low priority, i.e. the queue will be scheduled for execution after all default priority and high priority queues have been scheduled.
DISPATCH_QUEUE_PRIORITY_BACKGROUND Items dispatched to the queue will run at background priority, i.e. the queue will be scheduled for execution after all higher priority queues have been scheduled and the system will run items on this queue on a thread with background status as per setpriority(2) (i.e. disk I/O is throttled and the thread’s scheduling priority is set to lowest value).
If you want to declare such a data.frame
with many columns, it'll probably be a pain to type all the column classes out by hand. Especially if you can make use of rep
, this approach is easy and fast (about 15% faster than the other solution that can be generalized like this):
If your desired column classes are in a vector colClasses
, you can do the following:
library(data.table)
setnames(setDF(lapply(colClasses, function(x) eval(call(x)))), col.names)
lapply
will result in a list of desired length, each element of which is simply an empty typed vector like numeric()
or integer()
.
setDF
converts this list
by reference to a data.frame
.
setnames
adds the desired names by reference.
Speed comparison:
classes <- c("character", "numeric", "factor",
"integer", "logical","raw", "complex")
NN <- 300
colClasses <- sample(classes, NN, replace = TRUE)
col.names <- paste0("V", 1:NN)
setDF(lapply(colClasses, function(x) eval(call(x))))
library(microbenchmark)
microbenchmark(times = 1000,
read = read.table(text = "", colClasses = colClasses,
col.names = col.names),
DT = setnames(setDF(lapply(colClasses, function(x)
eval(call(x)))), col.names))
# Unit: milliseconds
# expr min lq mean median uq max neval cld
# read 2.598226 2.707445 3.247340 2.747835 2.800134 22.46545 1000 b
# DT 2.257448 2.357754 2.895453 2.401408 2.453778 17.20883 1000 a
It's also faster than using structure
in a similar way:
microbenchmark(times = 1000,
DT = setnames(setDF(lapply(colClasses, function(x)
eval(call(x)))), col.names),
struct = eval(parse(text=paste0(
"structure(list(",
paste(paste0(col.names, "=",
colClasses, "()"), collapse = ","),
"), class = \"data.frame\")"))))
#Unit: milliseconds
# expr min lq mean median uq max neval cld
# DT 2.068121 2.167180 2.821868 2.211214 2.268569 143.70901 1000 a
# struct 2.613944 2.723053 3.177748 2.767746 2.831422 21.44862 1000 b
Use fabs
instead of abs
to find absolute value of double
(or float
) data types. Include the <math.h>
header for fabs
function.
double d1 = fabs(-3.8951);
The quotes around type="text/javascript" are ending your string before you want to. Use single quotes inside to avoid this problem.
Use this
type='text/javascript'
I suspect that this occurs after an attempt to undeploy your app. Do you ever kill off that thread that you've initialised during the init()
process ? I would do this in the corresponding destroy()
method.
One that worked for me was:
.+(\\.+)$
Explanation:
.+ - any character except newline
( - create a group
\\.+ - match a backslash, and any characters after it
) - end group
$ - this all has to happen at the end of the string
I personally dont recommend to apply style on HTML tag, it might have after effects somewhere later part of the development.
so i personally suggest to apply background-image property to the body tag.
body{
width:100%;
height: 100%;
background-image: url("./images/bg.jpg");
background-position: center;
background-size: 100% 100%;
background-repeat: no-repeat;
}
This simple trick solved my problem. this works for most of the screens larger/smaller ones.
there are so many ways to do it, i found this the simpler with minimum after effects
I am in the same situation pointed out by malcook in his comment: unfortunately the answer by Thierry does not work with ggplot2 version 0.9.3.1.
png("figure_%d.png")
set.seed(2014)
library(ggplot2)
dataset <- data.frame(category = rep(LETTERS[1:5], 100),
x = rnorm(500, mean = rep(1:5, 100)),
y = rnorm(500, mean = rep(1:5, 100)))
dataset$fCategory <- factor(dataset$category)
subdata <- subset(dataset, category %in% c("A", "D", "E"))
ggplot(dataset, aes(x = x, y = y, colour = fCategory)) + geom_point()
ggplot(subdata, aes(x = x, y = y, colour = fCategory)) + geom_point()
Here it is the first figure:
and the second figure:
As we can see the colors do not stay fixed, for example E switches from magenta to blu.
As suggested by malcook in his comment and by hadley in his comment the code which uses limits
works properly:
ggplot(subdata, aes(x = x, y = y, colour = fCategory)) +
geom_point() +
scale_colour_discrete(drop=TRUE,
limits = levels(dataset$fCategory))
gives the following figure, which is correct:
This is the output from sessionInfo()
:
R version 3.0.2 (2013-09-25)
Platform: x86_64-pc-linux-gnu (64-bit)
locale:
[1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
[3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
[5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
[7] LC_PAPER=en_US.UTF-8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
attached base packages:
[1] methods stats graphics grDevices utils datasets base
other attached packages:
[1] ggplot2_0.9.3.1
loaded via a namespace (and not attached):
[1] colorspace_1.2-4 dichromat_2.0-0 digest_0.6.4 grid_3.0.2
[5] gtable_0.1.2 labeling_0.2 MASS_7.3-29 munsell_0.4.2
[9] plyr_1.8 proto_0.3-10 RColorBrewer_1.0-5 reshape2_1.2.2
[13] scales_0.2.3 stringr_0.6.2
ThulasiRam, I prefer your suggestion. It works well for me in a slightly different syntax/context:
var dt_to = $.datepicker.formatDate('yy-mm-dd', new Date());
If you decide to utilize datepicker from JQuery UI, make sure you use proper references in your document's < head > section:
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
This error message is very confusing. I just fixed the other 'warnings' in my project and I really had only one (simple one):
warning C4101: 'i': unreferenced local variable
After I commented this unused i
, and compiled it, the other error went away.