I've used below command to copy from local linux Centos 7 to AWS EC2.
scp -i user_key.pem file.txt [email protected]:/home/ec2-user
In my case, after 30 minutes changing permissions, got into account that the XLSX file I was trying to transfer was still open in Excel.
You can use AWS API or console UI to create an AMI(Amazon Machine Image) of your running instance. You can specify to reboot the instance when create your AMI. Then you can use AWS API or console UI to launch more instances with the AMI you created.
ECU = EC2 Compute Unit. More from here: http://aws.amazon.com/ec2/faqs/#What_is_an_EC2_Compute_Unit_and_why_did_you_introduce_it
Amazon EC2 uses a variety of measures to provide each instance with a consistent and predictable amount of CPU capacity. In order to make it easy for developers to compare CPU capacity between different instance types, we have defined an Amazon EC2 Compute Unit. The amount of CPU that is allocated to a particular instance is expressed in terms of these EC2 Compute Units. We use several benchmarks and tests to manage the consistency and predictability of the performance from an EC2 Compute Unit. One EC2 Compute Unit provides the equivalent CPU capacity of a 1.0-1.2 GHz 2007 Opteron or 2007 Xeon processor. This is also the equivalent to an early-2006 1.7 GHz Xeon processor referenced in our original documentation. Over time, we may add or substitute measures that go into the definition of an EC2 Compute Unit, if we find metrics that will give you a clearer picture of compute capacity.
My issue - I had port 22 open for "My IP" and changed the internet connection and IP address change caused. So had to change it back.
You can create swap space using the following steps
Here we are creating swap at /home/
dd if=/dev/zero of=/home/swapfile1 bs=1024 count=8388608
Here count is kilobyte count of swap space
mkswap /home/swapfile1
vi /etc/fstab
make entry :
/home/swapfile1 swap swap defaults 0 0
run:
swapon -a
The bottom line is you should almost always use EBS backed instances.
Here's why
I'm a heavy user of Amazon and switched all of my instances to EBS backed storage as soon as the technology came out of beta. I've been very happy with the result.
EBS can still fail - not a silver bullet
Keep in mind that any piece of cloud-based infrastructure can fail at any time. Plan your infrastructure accordingly. While EBS-backed instances provide certain level of durability compared to ephemeral storage instances, they can and do fail. Have an AMI from which you can launch new instances as needed in any availability zone, back up your important data (e.g. databases), and if your budget allows it, run multiple instances of servers for load balancing and redundancy (ideally in multiple availability zones).
When Not To
At some points in time, it may be cheaper to achieve faster IO on Instance Store instances. There was a time when it was certainly true. Now there are many options for EBS storage, catering to many needs. The options and their pricing evolve constantly as technology changes. If you have a significant amount of instances that are truly disposable (they don't affect your business much if they just go away), do the math on cost vs. performance. EBS-backed instances can also die at any point in time, but my practical experience is that EBS is more durable.
Please ignore this answer if it is irrelevant for you, but from my experience I've seen people having an issue with Permission denied (publickey)
because they simply pasted their public key (on a target machine) without the first letter!
This happens when using vim to edit (paste) the key. Since vim by default opens in command mode (not in an insert mode), pasting the key without switching to an insert mode (i.e. i
) will result in skipping the first s
letter, e.g. instead of
ssh-rsa <key>
you end up pasting
sh-rsa <key>
So before trying other solutions, see if you've pasted your key correctly! i.e.
cat ~/.ssh/id_rsa.pub
Only if you're certain, perform the next steps; trying to ssh in a verbose mode (i.e. flag -v
) might point you to the actual issue:
ssh -v -i <private_key> <name>@<ip> -p <port>
As a side note, as it has been already mentioned here by others, in majority of cases starting an empty ssh agent (program that keeps your keys in memory) and adding your key should resolve the issue:
ssh-agent bash
ssh-add <private_key>
You should see the error log. By default, its location is in /var/log/nginx/error.log
In my case, 502 get way because of:
GET /app_dev.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "symfony2.local"
2016/05/25 11:57:28 [error] 22889#22889: *3 upstream sent too big header while reading response header from upstream, client: 127.0.0.1, server: symfony2.local, request: "GET /app_dev.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "symfony2.local"
2016/05/25 11:57:29 [error] 22889#22889: *3 upstream sent too big header while reading response header from upstream, client: 127.0.0.1, server: symfony2.local, request: "GET /app_dev.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "symfony2.local"
2016/05/25 11:57:29 [error] 22889#22889: *3 upstream sent too big header while reading response header from upstream, client: 127.0.0.1, server: symfony2.local, request: "GET /app_dev.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "symfony2.local"
When we know exactly what is wrong, then fix it. For these error, just modify the buffer:
fastcgi_buffers 16 512k;
fastcgi_buffer_size 512k;
For those using CloudFormation, the key properties are EnableDnsSupport and EnableDnsHostnames which should be set to true
VPC: {
Type: 'AWS::EC2::VPC',
Properties: {
CidrBlock: '10.0.0.0/16',
EnableDnsSupport: true,
EnableDnsHostnames: true,
InstanceTenancy: 'default',
Tags: [
{
Key: 'env',
Value: 'dev'
}]
}
}
Download and run a standalone executable to do that.
Sometimes one cannot install awscli that depends on python. docker might be out of the picture too.
Here is my implementation in golang: https://github.com/hmalphettes/go-ec2-describe-tags
A few years late but hopefully this will help someone else...
1) First make sure the EC2 instance has a public IP. If has a Public DNS or Public IP address (circled below) then you should be good. This will be the address you ping.
2) Next make sure the Amazon network rules allow Echo Requests. Go to the Security Group for the EC2.
3) Next, Windows firewall blocks inbound Echo requests by default. Allow Echo requests by creating a windows firewall exception...
4) Done! Hopefully you should now be able to ping your server.
On windows, Try using git bash and use your Linux commands there. Easy approach
chmod 400 *****.pem
ssh -i "******.pem" [email protected]
FileZilla did not work for me, I kept getting this error:
Disconnected: No supported authentication methods available (server sent: publickey)
What did work was the sftp
command.
Connect with the EC2 Instance with
sftp -i "path/to/key.pem" [email protected]
To download path/to/source/file.txt
and path/to/source/dir
:
lcd ~/Desktop
cd path/to/source
get file.txt
get -r dir
To upload localpath/to/source/file.txt
and ~/localpath/to/source/dir
to remotepath/to/dest
:
lcd localpath/to/source
cd remotepath/to/dest
put file.txt
put -r dir
The -i
flag specifies the private key (.pem file) to use. If you don't specify that flag (as in your first command) it will use your default ssh key (usually under ~/.ssh/
).
So in your first command, you are actually asking scp
to upload the .pem file itself using your default ssh key. I don't think that is what you want.
Try instead with:
scp -r -i /Applications/XAMPP/htdocs/keypairfile.pem uploads/* ec2-user@publicdns:/var/www/html/uploads
Adding to all the answers already available for this question, I would like to add the steps I followed to install Python3 on AWS EC2 instance running CentOS 7. You can find the entire details at this link.
https://aws-labs.com/install-python-3-centos-7-2/
First, we need to enable SCL. SCL is a community project that allows you to build, install, and use multiple versions of software on the same system, without affecting system default packages.
sudo yum install centos-release-scl
Now that we have SCL repository, we can install the python3
sudo yum install rh-python36
To access Python 3.6 you need to launch a new shell instance using the Software Collection scl tool:
scl enable rh-python36 bash
If you check the Python version now you’ll notice that Python 3.6 is the default version
python --version
It is important to point out that Python 3.6 is the default Python version only in this shell session. If you exit the session or open a new session from another terminal Python 2.7 will be the default Python version.
Now, Install the python development tools by typing:
sudo yum groupinstall ‘Development Tools’
Now create a virtual environment so that the default python packages don't get messed up.
mkdir ~/my_new_project
cd ~/my_new_project
python -m venv my_project_venv
To use this virtual environment,
source my_project_venv/bin/activate
Now, you have your virtual environment set up with python3.
You can actually add a key pair through the elastic beanstalk config page. it then restarts your instance for you and everything works.
For me none of the packages mentioned above did help.
I finally managed to install lxml
after running:
sudo apt-get install python3.5-dev
If you've changed the search_path
, specify the public schema in the function call:
public.uuid_generate_v4()
This is how I solved the problem
ssh -i <key> ec2-user@<ec2 ip>
I don't believe that the Jenkins user that is installed via apt has a password. If it does, I have never seen documentation. Based on the commands you entered, I am guessing you are using a Debian distro?
Is there any particular reason you must use the jenkins user to do the install instead of the user which was set up when you created your instance?
Check official website https://aws.amazon.com/free/compute/lightsail-vs-ec2/
Amazon Lightsail – The Power of AWS, the Simplicity of a VPS https://aws.amazon.com/blogs/aws/amazon-lightsail-the-power-of-aws-the-simplicity-of-a-vps/
Amazon EC2 vs Amazon Lightsail (comparison on point )
Source : https://www.vpsbenchmarks.com/compare/features/ec2_vs_lightsail
THIS IS JUST A NOTE FOR ANYONE DEALING WITH THIS PROBLEM USING THE RUBY DRIVER
I had this same problem when using the Ruby Gem.
To set slaveOk in Ruby, you just pass it as an argument when you create the client like this:
mongo_client = MongoClient.new("localhost", 27017, { slave_ok: true })
https://github.com/mongodb/mongo-ruby-driver/wiki/Tutorial#making-a-connection
mongo_client = MongoClient.new # (optional host/port args)
Notice that 'args' is the third optional argument.
If you're wanting to use Environment variables using apache/tomcat, I found that the only way they could be found was setting them in tomcat/bin/setenv.sh (where catalina_opts are set - might be catalina.sh in your setup)
export AWS_ACCESS_KEY_ID=*********;
export AWS_SECRET_ACCESS_KEY=**************;
If you're using ubuntu, try logging in as ubuntu $printenv then log in as root $printenv, the environmental variables won't necessarily be the same....
If you only want to use environmental variables you can use: com.amazonaws.auth.EnvironmentVariableCredentialsProvider
instead of:
com.amazonaws.auth.DefaultAWSCredentialsProviderChain
(which by default checks all 4 possible locations)
anyway after hours of trying to figure out why my environmental variables weren't being found...this worked for me.
It will not be ok until you add your user to the group www by the following commands:
sudo usermod -a -G www <USER>
This solves the permission problem.
Set the default path by adding this:
local_root=/var/www/html
Using AWS Management Console:
ephemeral is just another name of root volume when you launch Instance from AMI backed from Amazon EC2 instance store
So Everything will be stored on ephemeral.
if you have launched your instance from AMI backed by EBS volume then your instance does not have ephemeral.
No.
You get charged for:
So... if you stop the EC2 instance you will only have to pay for the storage of the image on S3 (assuming you store an image ofcourse) and any IP addresses you've reserved.
If you are using elastic bean and EB CLI, just use eb ssh
to login to instance. You can use options as specified in the following link
http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb3-ssh.html
Almost everything in EC2 is multi-tenant. What the network performance indicates is what priority you will have compared with other instances sharing the same infrastructure.
If you need a guaranteed level of bandwidth, then EC2 will likely not work well for you.
#1- Run this to configure the region once and for all:
aws configure set region us-east-1 --profile admin
Change admin
next to the profile if it's different.
Change us-east-1
if your region is different.
#2- Run your command again:
aws ecs list-container-instances --cluster default
While creating the user like 'myuser'@'localhost', the user gets limited to be connected only from localhost. Create a user only for remote access and use your remote client IP address from where you will be connecting to the MySQL server. If you can bear the risk of allowing connections from all remote hosts (usually when using dynamic IP address), you can use 'myuser'@'%'. I did this, and also removed bind_address from /etc/mysql/mysql.cnf (Ubuntu) and now it connects flawlessly.
mysql> select host,user from mysql.user;
+-----------+-----------+
| host | user |
+-----------+-----------+
| % | myuser |
| localhost | mysql.sys |
| localhost | root |
+-----------+-----------+
3 rows in set (0.00 sec)
All meta-data related to EC2 resource can be accessed by the EC2 instance itself with the help of the following command being executed:
CURL :
http://169.254.169.254/<api-version>/meta-data/<metadata-requested>
For your case: "metadata-requested" should be instance-id , "api-version" is usually latest that can be used.
Additional Note: You can also get information related to below EC2 attributes using the above command.
ami-id, ami-launch-index, ami-manifest-path, block-device-mapping/, hostname, iam/, instance-action, instance-id, instance-type, local-hostname, local-ipv4, mac, metrics/, network/, placement/, profile, public-hostname, public-ipv4, public-keys/, reservation-id, security-groups, services/,
For more details please follow this link : https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html
What you can do...
Create a new Instance Profile / Role that has the AmazonEC2RoleForSSM policy attached.
Attach this Instance Profile to the instance.
I came here through Google looking for an answer to how to setup cloud init to not disable PasswordAuthentication on AWS. Both the answers don't address the issue. Without it, if you create an AMI then on instance initialization cloud init will again disable this option.
The correct method to do this, is instead of manually changing sshd_config you need to correct the setting for cloud init (Open source tool used to configure an instance during provisioning. Read more at: https://cloudinit.readthedocs.org/en/latest/). The configuration file for cloud init is found at: /etc/cloud/cloud.cfg
This file is used for setting up a lot of the configuration used by cloud init. Read through this file for examples of items you can configure on cloud-init. This includes items like default username on a newly created instance)
To enable or disable password login over SSH you need to change the value for the parameter ssh_pwauth. After changing the parameter ssh_pwauth from 0 to 1 in the file /etc/cloud/cloud.cfg bake an AMI. If you launch from this newly baked AMI it will have password authentication enabled after provisioning.
You can confirm this by checking the value of the PasswordAuthentication in the ssh config as mentioned in the other answers.
use RewriteBase /{your folder}/ on your .htaccess
You need to configure the security group as stated by cyraxjoe. Along with that you also need to open System port. Steps to open port in windows :-
Had a similar issue. Here are the steps used to setup SSH keys and forwarding on the Mac. Made these notes for myself - may help someone... check against your config.
The assumption here is there are no keys setup. If you already have the keys setup skip this section.
$ ssh-keygen -t rsa -b 4096
Generating public/private rsa key pair.
Enter a file in which to save the key (/Users/you/.ssh/id_rsa): [Press enter] Enter passphrase (empty for no passphrase): [Type a passphrase] Enter same passphrase again: [Type passphrase again]
Modify ~/.ssh/config adding the entry for the key file:
~/.ssh/config should look similar to:
Host *
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/id_rsa
Store the private key in the keychain:
$ ssh-add -K ~/.ssh/id_rsa
Go test it now with: ssh -A username@yourhostname
Should forward your key to yourhostname. Assuming your keys are added on you should connect without issue.
First off, EC2 and Elastic Compute Cloud are the same thing.
Next, AWS encompasses the range of Web Services that includes EC2 and Elastic Beanstalk. It also includes many others such as S3, RDS, DynamoDB, and all the others.
EC2 is Amazon's service that allows you to create a server (AWS calls these instances) in the AWS cloud. You pay by the hour and only what you use. You can do whatever you want with this instance as well as launch n
number of instances.
Elastic Beanstalk is one layer of abstraction away from the EC2 layer. Elastic Beanstalk will setup an "environment" for you that can contain a number of EC2 instances, an optional database, as well as a few other AWS components such as a Elastic Load Balancer, Auto-Scaling Group, Security Group. Then Elastic Beanstalk will manage these items for you whenever you want to update your software running in AWS. Elastic Beanstalk doesn't add any cost on top of these resources that it creates for you. If you have 10 hours of EC2 usage, then all you pay is 10 compute hours.
For running Wordpress, it is whatever you are most comfortable with. You could run it straight on a single EC2 instance, you could use a solution from the AWS Marketplace, or you could use Elastic Beanstalk.
In the case that you want to reduce system operations and just focus on the website, then Elastic Beanstalk would be the best choice for that. Elastic Beanstalk supports a PHP stack (as well as others). You can keep your site in version control and easily deploy to your environment whenever you make changes. It will also setup an Autoscaling group which can spawn up more EC2 instances if traffic is growing.
Here's the first result off of Google when searching for "elastic beanstalk wordpress": https://www.otreva.com/blog/deploying-wordpress-amazon-web-services-aws-ec2-rds-via-elasticbeanstalk/
This can be done. Following are the steps to setup the GUI
sudo useradd -m awsgui
sudo passwd awsgui
sudo usermod -aG admin awsgui
sudo vim /etc/ssh/sshd_config # edit line "PasswordAuthentication" to yes
sudo /etc/init.d/ssh restart
In security group open port 5901. Then ssh to the server instance. Run following commands to install ui and vnc server:
sudo apt-get update
sudo apt-get install ubuntu-desktop
sudo apt-get install vnc4server
Then run following commands and enter the login password for vnc connection:
su - awsgui
vncserver
vncserver -kill :1
vim /home/awsgui/.vnc/xstartup
Then hit the Insert key, scroll around the text file with the keyboard arrows, and delete the pound (#) sign from the beginning of the two lines under the line that says "Uncomment the following two lines for normal desktop." And on the second line add "sh" so the line reads
exec sh /etc/X11/xinit/xinitrc.
When you're done, hit Ctrl + C on the keyboard, type :wq and hit Enter.
Then start vnc server again.
vncserver
You can download xtightvncviewer
to view desktop(for Ubutnu) from here https://help.ubuntu.com/community/VNC/Clients
In the vnc client, give public DNS plus ":1" (e.g. www.example.com:1). Enter the vnc login password. Make sure to use a normal connection. Don't use the key files.
Additional guide available here: http://www.serverwatch.com/server-tutorials/setting-up-vnc-on-ubuntu-in-the-amazon-ec2-Page-3.html
Mac VNC client can be downloaded from here: https://www.realvnc.com/en/connect/download/viewer/
Port opening on console
sudo iptables -A INPUT -p tcp --dport 5901 -j ACCEPT
If the grey window issue comes. Mostly because of ".vnc/xstartup" file on different user. So run the vnc server also on same user instead of "awsgui" user.
vncserver
See http://wiki.apache.org/httpd/DistrosDefaultLayout for discussion of where you might find Apache httpd configuration files on various platforms, since this can vary from release to release and platform to platform. The most common answer, however, is either /etc/apache/conf or /etc/httpd/conf
Generically, you can determine the answer by running the command:
httpd -V
(That's a capital V). Or, on systems where httpd is renamed, perhaps apache2ctl -V
This will return various details about how httpd is built and configured, including the default location of the main configuration file.
One of the lines of output should look like:
-D SERVER_CONFIG_FILE="conf/httpd.conf"
which, combined with the line:
-D HTTPD_ROOT="/etc/httpd"
will give you a full path to the default location of the configuration file
Check if in your php.ini file has the following line:
;extension=php_gd2.dll
if exists, change it to
extension=php_gd2.dll
and restart apache
(it works on MAC)
Check the permissions on the .pem file...openssh usually doesn't like world-readable private keys, and will fail (iir, scp doesn't do a great job of providing this feedback to the user).
Can you simply ssh with that key to your AWS host?
An old question but worth mentioning another option in the answers. In case the DNS system of your domain has been defined in Amazon Route 53, you can use Amazon CloudFront service in front of your EC2 and attach a free Amazon SSL certificate to it. This way you will benefit from both having a CDN for a faster content delivery and also securing you domain with HTTPS protocol.
I just came across this tonight. Can't say if they are legit, how long in business, and whether they'll be around long, but seems interesting. I may give them a try, and will post update if I do.
Per the website, they say they offer hourly pay-as-you-go and weekly/monthly plans, plus there's a free trial.
Per @Iterator, posting update on my findings for this service, moving out from my comments:
I did the trial/evaluation. The trial can be misleading on how the trial works. You may need to signup to see prices but the trial so far, per the trial software download, doesn't appear to be time limited. It's just feature restricted. You signup to get your own account, but you actually use a generic trial login account to do the trial, not your own account. Your own account is used when you actually pay for the service. The trial limits what you can do, install, save, etc. but good enough to give you an idea of how things work. So it doesn't hurt to signup to evaluate and not pay anything.
Persistence of data is offered via saving files to DropBox (pre-installed, you just need login/configure), etc. There is no concept of AMIs, EBS, or some VM image. Their service is actually like a shared website hosting solution, where users timeshare a Mac machine (like timesharing a Unix/Linux server), and I think they limit or periodically purge what you put on the machine, or perhaps rather they don't backup your files, hence use of DropBox to do the backup. One should contact them to clarify this if desired.
They have various pricing options, as you mention the all day pass, monthly plans at $20, and their is a pay as you go plan at $1/hr. I'd probably go with pay as you go based on my usage. The pay as you go is based on prepaid credits (1 credit = 1 hour, billed at 30 credit increments). One caveat is that you need to periodically use the plan at least once every 60 days for the pay as you go plan or else you lose unused credits. So that's like minimum of spending 1 credit /1 hour every 60 days.
One last comment for now, from my evaluation, you'll need high bandwidth to use the service effectively. It's usable over 1.5 Mbps DSL but kind of slow in response. You'd want to use it from a corporate network with Gbps bandwidth for optimal use. Or at least a higher speed cable/DSL broadband connection. On my last test ~3Mbps seemed sufficient on the low bandwidth profile (they have multiple bandwidth connection profiles, low, medium, high, optimized for some bandwidth ranges). I didn't test on the higher ones. Your mileage may vary.
Try replacing apt-get
with yum
as Amazon Linux based AMI uses the yum
command instead of apt-get
.
edit your .env and add this line after mail config lines
MAIL_ENCRYPTION=""
Save and try to send email
Better Approach:
<script type="text/javascript">
$('#btn').click(function() {
var id = $(this).attr('id');
alert(id);
});
</script>
<input id="btn" type="button" value="click" />
But, if you REALLY need to do the click handler inline, this will work:
<script type="text/javascript">
function display(el) {
var id = $(el).attr('id');
alert(id);
}
</script>
<input id="btn" type="button" value="click" OnClick="display(this);" />
You say you don't want to use the system("pause")
hack. Why not?
If it's because you don't want the program to prompt when it's not being debugged, there's a way around that. This works for me:
void pause () {
system ("pause");
}
int main (int argc, char ** argv) {
// If "launched", then don't let the console close at the end until
// the user has seen the report.
// (See the MSDN ConGUI sample code)
//
do {
HANDLE hConsoleOutput = ::GetStdHandle (STD_OUTPUT_HANDLE);
if (INVALID_HANDLE_VALUE == hConsoleOutput)
break;
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (0 == ::GetConsoleScreenBufferInfo (hConsoleOutput, &csbi))
break;
if (0 != csbi.dwCursorPosition.X)
break;
if (0 != csbi.dwCursorPosition.Y)
break;
if (csbi.dwSize.X <= 0)
break;
if (csbi.dwSize.Y <= 0)
break;
atexit (pause);
} while (0);
I just paste this code into each new console application I'm writing. If the program is being run from a command window, the cursor position won't be <0,0>, and it won't call atexit()
. If it has been launched from you debugger (any debugger) the console cursor position will be <0,0> and the atexit()
call will be executed.
I got the idea from a sample program that used to be in the MSDN library, but I think it's been deleted.
NOTE: The Microsoft Visual Studio implementation of the system() routine requires the COMSPEC environment variable to identify the command line interpreter. If this environment variable gets messed up -- for example, if you've got a problem in the Visual Studio project's debugging properties so that the environment variables aren't properly passed down when the program is launched -- then it will just fail silently.
Answering this has been good, as the comments have led to an improvement in my own understanding of Python variables.
As noted in the comments, when you loop over a list with something like for member in my_list
the member
variable is bound to each successive list element. However, re-assigning that variable within the loop doesn't directly affect the list itself. For example, this code won't change the list:
my_list = [1,2,3]
for member in my_list:
member = 42
print my_list
Output:
[1, 2, 3]
If you want to change a list containing immutable types, you need to do something like:
my_list = [1,2,3]
for ndx, member in enumerate(my_list):
my_list[ndx] += 42
print my_list
Output:
[43, 44, 45]
If your list contains mutable objects, you can modify the current member
object directly:
class C:
def __init__(self, n):
self.num = n
def __repr__(self):
return str(self.num)
my_list = [C(i) for i in xrange(3)]
for member in my_list:
member.num += 42
print my_list
[42, 43, 44]
Note that you are still not changing the list, simply modifying the objects in the list.
You might benefit from reading Naming and Binding.
here i have explained how the empty function and isset works please use the one that is appropriate also you can use is_null function also
<?php
$val = 0;
//evaluates to true because $var is empty
if (empty($val)) {
echo '$val is either 0, empty, or not set at all';
}
//evaluates to true because $VAR IS SET
if (isset($val)) {
echo '$val is set even though it is empty';
}
?>
You can add position: fixed;
with top left right bottom 0
attribute, that solution work on older browsers too.
If you want to embed it, add position: absolute;
to the wrapper, and position: relative
to the div outside of the wrapper.
.wrapper {_x000D_
position: fixed;_x000D_
top: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
bottom: 0;_x000D_
_x000D_
display: grid;_x000D_
border-style: solid;_x000D_
border-color: red;_x000D_
grid-template-columns: repeat(3, 1fr);_x000D_
grid-template-rows: repeat(3, 1fr);_x000D_
grid-gap: 10px;_x000D_
}_x000D_
.one {_x000D_
border-style: solid;_x000D_
border-color: blue;_x000D_
grid-column: 1 / 3;_x000D_
grid-row: 1;_x000D_
}_x000D_
.two {_x000D_
border-style: solid;_x000D_
border-color: yellow;_x000D_
grid-column: 2 / 4;_x000D_
grid-row: 1 / 3;_x000D_
}_x000D_
.three {_x000D_
border-style: solid;_x000D_
border-color: violet;_x000D_
grid-row: 2 / 5;_x000D_
grid-column: 1;_x000D_
}_x000D_
.four {_x000D_
border-style: solid;_x000D_
border-color: aqua;_x000D_
grid-column: 3;_x000D_
grid-row: 3;_x000D_
}_x000D_
.five {_x000D_
border-style: solid;_x000D_
border-color: green;_x000D_
grid-column: 2;_x000D_
grid-row: 4;_x000D_
}_x000D_
.six {_x000D_
border-style: solid;_x000D_
border-color: purple;_x000D_
grid-column: 3;_x000D_
grid-row: 4;_x000D_
}
_x000D_
<html>_x000D_
<div class="wrapper">_x000D_
<div class="one">One</div>_x000D_
<div class="two">Two</div>_x000D_
<div class="three">Three</div>_x000D_
<div class="four">Four</div>_x000D_
<div class="five">Five</div>_x000D_
<div class="six">Six</div>_x000D_
</div>_x000D_
</html>
_x000D_
Here you go. It's a little messy but it works.
$(function () {
var companyList = $("#CompanyList").autocomplete({
change: function() {
alert('changed');
}
});
companyList.autocomplete('option','change').call(companyList);
});
Often, wild cards operate with two type of jokers:
? - any character (one and only one)
* - any characters (zero or more)
so you can easily convert these rules into appropriate regular expression:
// If you want to implement both "*" and "?"
private static String WildCardToRegular(String value) {
return "^" + Regex.Escape(value).Replace("\\?", ".").Replace("\\*", ".*") + "$";
}
// If you want to implement "*" only
private static String WildCardToRegular(String value) {
return "^" + Regex.Escape(value).Replace("\\*", ".*") + "$";
}
And then you can use Regex as usual:
String test = "Some Data X";
Boolean endsWithEx = Regex.IsMatch(test, WildCardToRegular("*X"));
Boolean startsWithS = Regex.IsMatch(test, WildCardToRegular("S*"));
Boolean containsD = Regex.IsMatch(test, WildCardToRegular("*D*"));
// Starts with S, ends with X, contains "me" and "a" (in that order)
Boolean complex = Regex.IsMatch(test, WildCardToRegular("S*me*a*X"));
If you don't like "verbosity" you can always wrap your code in a short method:
private void msgbox(String s){
JOptionPane.showMessageDialog(null, s);
}
and the usage:
msgbox("don't touch that!");
var CurrentMouseXPostion;
var CurrentMouseYPostion;
$(document).mousemove(function(event) {
CurrentMouseXPostion = event.pageX;
CurrentMouseYPostion = event.pageY;
});
Make an eventListener on the main object , in my case the document object, to get the mouse coords every frame and store them in global variables, and like that you can read mouse Y & Z whenever youlike , wherever you like.
The first is the original for loop. You initialize a variable, set a terminating condition, and provide a state incrementing/decrementing counter (There are exceptions, but this is the classic)
For that,
for (int i=0;i<myString.length;i++) {
System.out.println(myString[i]);
}
is correct.
For Java 5 an alternative was proposed. Any thing that implements iterable can be supported. This is particularly nice in Collections. For example you can iterate the list like this
List<String> list = ....load up with stuff
for (String string : list) {
System.out.println(string);
}
instead of
for (int i=0; i<list.size();i++) {
System.out.println(list.get(i));
}
So it's just an alternative notation really. Any item that implements Iterable (i.e. can return an iterator) can be written that way.
What's happening behind the scenes is somethig like this: (more efficient, but I'm writing it explicitly)
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String string=it.next();
System.out.println(string);
}
In the end it's just syntactic sugar, but rather convenient.
You can create a label using the code below. Updated.
let yourLabel: UILabel = UILabel()
yourLabel.frame = CGRect(x: 50, y: 150, width: 200, height: 21)
yourLabel.backgroundColor = UIColor.orange
yourLabel.textColor = UIColor.black
yourLabel.textAlignment = NSTextAlignment.center
yourLabel.text = "test label"
self.view.addSubview(yourLabel)
i think you are not pausing the program before it ended so the output you are putting after getting the inpus is not seeing on the screen right?
do:
getchar();
before the end of the program
don't use USB 3.0 ports for connection beetwen PC and Android phone!
USB 3.0 - Port with blue tongue
USB 2.0 - Port with black tongue
It uses indentation
def func():
funcbody
if cond:
ifbody
outofif
outof_func
For AngularJs you have to use "angular-datatables.min.js" file for datatable settings. You will get this from http://l-lin.github.io/angular-datatables/#/welcome.
After that you can write code like below,
<script>
var app = angular.module('AngularWayApp', ['datatables']);
</script>
<div ng-app="AngularWayApp" ng-controller="AngularWayCtrl">
<table id="example" datatable="ng" class="table">
<thead>
<tr>
<th><b>UserID</b></th>
<th><b>Firstname</b></th>
<th><b>Lastname</b></th>
<th><b>Email</b></th>
<th><b>Actions</b></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users" ng-click="testingClick(user)">
<td>
{{user.UserId}}
</td>
<td>
{{user.FirstName}}
</td>
<td>
{{user.Lastname}}
</td>
<td>
{{user.Email}}
</td>
<td>
<span ng-click="editUser(user)" style="color:blue;cursor: pointer; font-weight:500; font-size:15px" class="btnAdd" data-toggle="modal" data-target="#myModal">Edit</span> |
<span ng-click="deleteUser(user)" style="color:red; cursor: pointer; font-weight:500; font-size:15px" class="btnRed">Delete</span>
</td>
</tr>
</tbody>
</table>
</div>
Lower your gulp version in package.json file to 3.9.1-
"gulp": "^3.9.1",
babel-polyfill
(deprecated as of Babel 7.4) is required. You must also install it in order to get async/await working.
npm i -D babel-core babel-polyfill babel-preset-es2015 babel-preset-stage-0 babel-loader
package.json
"devDependencies": {
"babel-core": "^6.0.20",
"babel-polyfill": "^6.0.16",
"babel-preset-es2015": "^6.0.15",
"babel-preset-stage-0": "^6.0.15"
}
.babelrc
{
"presets": [ "es2015", "stage-0" ]
}
.js with async/await (sample code)
"use strict";
export default async function foo() {
var s = await bar();
console.log(s);
}
function bar() {
return "bar";
}
In the startup file
require("babel-core/register");
require("babel-polyfill");
If you are using webpack you need to put it as the first value of your entry
array in your webpack configuration file (usually webpack.config.js
), as per @Cemen comment:
module.exports = {
entry: ['babel-polyfill', './test.js'],
output: {
filename: 'bundle.js'
},
module: {
loaders: [
{ test: /\.jsx?$/, loader: 'babel', }
]
}
};
If you want to run tests with babel then use:
mocha --compilers js:babel-core/register --require babel-polyfill
While this particular example is for a multiple file upload, it gives the general information one needs:
https://developer.mozilla.org/en-US/docs/DOM/File.type
As far as acting upon a file upon /download/ this is not a Javascript question -- but rather a server configuration. If a user does not have something installed to open PDF or XLS files, their only choice will be to download them.
Adding PropertyPlaceholderConfigurer in configuration is working for me.
@Configuration
@ComponentScan
@EnableJpaRepositories
@EnableTransactionManagement
public class TestConfiguration {
@Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
builder.setType(EmbeddedDatabaseType.DERBY);
return builder.build();
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPackagesToScan(new String[] { "com.test.model" });
// Use hibernate
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);
entityManagerFactoryBean.setJpaProperties(getHibernateProperties());
return entityManagerFactoryBean;
}
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.show_sql", "false");
properties.put("hibernate.dialect", "org.hibernate.dialect.DerbyDialect");
properties.put("hibernate.hbm2ddl.auto", "update");
return properties;
}
@Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(
entityManagerFactory().getObject()
);
return transactionManager;
}
@Bean
PropertyPlaceholderConfigurer propConfig() {
PropertyPlaceholderConfigurer placeholderConfigurer = new PropertyPlaceholderConfigurer();
placeholderConfigurer.setLocation(new ClassPathResource("application_test.properties"));
return placeholderConfigurer;
}
}
And in test class
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestConfiguration.class)
public class DataServiceTest {
@Autowired
private DataService dataService;
@Autowired
private DataRepository dataRepository;
@Value("${Api.url}")
private String baseUrl;
@Test
public void testUpdateData() {
List<Data> datas = (List<Data>) dataRepository.findAll();
assertTrue(datas.isEmpty());
dataService.updateDatas();
datas = (List<Data>) dataRepository.findAll();
assertFalse(datas.isEmpty());
}
}
From the documentation
To create your own link with a pre-filled message that will automatically appear in the text field of a chat, use https://wa.me/whatsappphonenumber/?text=urlencodedtext where whatsappphonenumber is a full phone number in international format and URL-encodedtext is the URL-encoded pre-filled message.
Example:https://wa.me/15551234567?text=I'm%20interested%20in%20your%20car%20for%20sale
val phoneNumber = "13492838472"
val text = "Hey, you know... I love StackOverflow :)"
val uri = Uri.parse("https://wa.me/$phoneNumber/?text=$text")
val sendIntent = Intent(Intent.ACTION_VIEW, uri)
startActivity(sendIntent)
Here is what I have done to make the right scroll bar work. The only thing needed to be considered is when using 'direction: rtl' and whole table also need to be changed. Hopefully this gives you an idea how to do it.
Example:
<table dir='rtl'><tr><td>Display Last</td><td>Display Second</td><td>Display First</td></table>
Check this: JSFiddle
This is for bootstrap v4 compiled via grunt or some other task runner
You would need to change $table-hover-bg
to set the highlight on hover
$table-cell-padding: .75rem !default;
$table-sm-cell-padding: .3rem !default;
$table-bg: transparent !default;
$table-accent-bg: rgba(0,0,0,.05) !default;
$table-hover-bg: rgba(0,0,0,.075) !default;
$table-active-bg: $table-hover-bg !default;
$table-border-width: $border-width !default;
$table-border-color: $gray-lighter !default;
it defines the protocols address family.this determines the type of socket created. pocket pc support AF_INET.
the content in the following page is quite decent http://etutorials.org/Programming/Pocket+pc+network+programming/Chapter+1.+Winsock/Streaming+TCP+Sockets/
Even though you define android:onClick = "DoIt" in XML, you need to make sure your activity (or view context) has public method defined with exact same name and View as parameter. Android wires your definitions with this implementation in activity. At the end, implementation will have same code which you wrote in anonymous inner class. So, in simple words instead of having inner class and listener attachement in activity, you will simply have a public method with implementation code.
You can use the findIndex method with a callback function and its "this" parameter.
Note: old browsers don't know findIndex but a polyfill is available.
Sample code (take care that in the original question, a new object is pushed only if neither of its data is in previoulsy pushed objects):
var a=[{name:"tom", text:"tasty"}], b;
var magic=function(e) {
return ((e.name == this.name) || (e.text == this.text));
};
b={name:"tom", text:"tasty"};
if (a.findIndex(magic,b) == -1)
a.push(b); // nothing done
b={name:"tom", text:"ugly"};
if (a.findIndex(magic,b) == -1)
a.push(b); // nothing done
b={name:"bob", text:"tasty"};
if (a.findIndex(magic,b) == -1)
a.push(b); // nothing done
b={name:"bob", text:"ugly"};
if (a.findIndex(magic,b) == -1)
a.push(b); // b is pushed into a
Found this on github...
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import pandas
Burgos has the right answer. Just to clarify, the Character Set should be changed to "Not Set".
You can use the in-built array method - sort
. This method takes a callback method as a param
// custom sort function to be passed as param/callback to the Array's sort method
function myCustomSort(a, b) {
return (a.toLowerCase() > b.toLowerCase()) ? 1 : -1;
}
// Actual method to be called by entity that needs sorting feature
function sortStrings() {
var op = Array.prototype.sort.call(arguments, myCustomSort);
}
// Testing the implementation
var sortedArray = sortStrings("Burger", "Mayo1", "Pizza", "boxes", "Apples", "Mayo");
console.log(sortedArray); //["Apples", "boxes", "Burger", "Mayo", "Mayo1", "Pizza"]
Key Points to be noted for understanding this code.
myCustomSort
, should return +1 or -1 for each element pair(from the input array) comparison.toLowerCase()
/toUpperCase()
in the custom sorting callback method so that case difference does not affect the correctness of the sorting process.I hope this is clear enough explanation. Feel free to comment if you think, more info is needed.
Cheers!
You have to name your struct like that:
typedef struct car_t {
char
wheel_t
} car_t;
Have you tried Chromebug? It's the Firebug for extensions.
Firstly, using on*
attributes to add event handlers is a very outdated way of achieving what you want. As you've tagged your question with jQuery, here's a jQuery implementation:
<div id="foo">hello world!</div>
<img src="zoom.png" id="image" />
$('#image').click(function() {
$('#foo').css({
'background-color': 'red',
'color': 'white',
'font-size': '44px'
});
});
A more efficient method is to put those styles into a class, and then add that class onclick, like this:
$('#image').click(function() {
$('#foo').addClass('myClass');
});
_x000D_
.myClass {
background-color: red;
color: white;
font-size: 44px;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="foo">hello world!</div>
<img src="https://i.imgur.com/9zbkKVz.png?1" id="image" />
_x000D_
Here's a plain Javascript implementation of the above for those who require it:
document.querySelector('#image').addEventListener('click', () => {
document.querySelector('#foo').classList.add('myClass');
});
_x000D_
.myClass {
background-color: red;
color: white;
font-size: 44px;
}
_x000D_
<div id="foo">hello world!</div>
<img src="https://i.imgur.com/9zbkKVz.png?1" id="image" />
_x000D_
The API appears to have changed (or at least, it doesn't work for me).
Running the following in the Package Manager Console works as expected:
Update-Database -Script -SourceMigration:0
EDIT 30/Dec/2017: This answer appears in top results of Google searches, so I decided to update it. The old answer is still at the end.
dryscape isn't maintained anymore and the library dryscape developers recommend is Python 2 only. I have found using Selenium's python library with Phantom JS as a web driver fast enough and easy to get the work done.
Once you have installed Phantom JS, make sure the phantomjs
binary is available in the current path:
phantomjs --version
# result:
2.1.1
To give an example, I created a sample page with following HTML code. (link):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript scraping test</title>
</head>
<body>
<p id='intro-text'>No javascript support</p>
<script>
document.getElementById('intro-text').innerHTML = 'Yay! Supports javascript';
</script>
</body>
</html>
without javascript it says: No javascript support
and with javascript: Yay! Supports javascript
import requests
from bs4 import BeautifulSoup
response = requests.get(my_url)
soup = BeautifulSoup(response.text)
soup.find(id="intro-text")
# Result:
<p id="intro-text">No javascript support</p>
from selenium import webdriver
driver = webdriver.PhantomJS()
driver.get(my_url)
p_element = driver.find_element_by_id(id_='intro-text')
print(p_element.text)
# result:
'Yay! Supports javascript'
You can also use Python library dryscrape to scrape javascript driven websites.
import dryscrape
from bs4 import BeautifulSoup
session = dryscrape.Session()
session.visit(my_url)
response = session.body()
soup = BeautifulSoup(response)
soup.find(id="intro-text")
# Result:
<p id="intro-text">Yay! Supports javascript</p>
In addition to Roi-Kyi Bryant answer, this code fully works in Excel 2010. Press ALT + F11 and VBA editor will pop up. Double click on ThisWorkbook
on the left side, then paste this code:
Private Sub Workbook_Activate()
Dim hFile As Long
Dim path As String, fileName As String, ribbonXML As String, user As String
hFile = FreeFile
user = Environ("Username")
path = "C:\Users\" & user & "\AppData\Local\Microsoft\Office\"
fileName = "Excel.officeUI"
ribbonXML = "<mso:customUI xmlns:mso='http://schemas.microsoft.com/office/2009/07/customui'>" & vbNewLine
ribbonXML = ribbonXML + " <mso:ribbon>" & vbNewLine
ribbonXML = ribbonXML + " <mso:qat/>" & vbNewLine
ribbonXML = ribbonXML + " <mso:tabs>" & vbNewLine
ribbonXML = ribbonXML + " <mso:tab id='reportTab' label='My Actions' insertBeforeQ='mso:TabFormat'>" & vbNewLine
ribbonXML = ribbonXML + " <mso:group id='reportGroup' label='Reports' autoScale='true'>" & vbNewLine
ribbonXML = ribbonXML + " <mso:button id='runReport' label='Trim' " & vbNewLine
ribbonXML = ribbonXML + "imageMso='AppointmentColor3' onAction='TrimSelection'/>" & vbNewLine
ribbonXML = ribbonXML + " </mso:group>" & vbNewLine
ribbonXML = ribbonXML + " </mso:tab>" & vbNewLine
ribbonXML = ribbonXML + " </mso:tabs>" & vbNewLine
ribbonXML = ribbonXML + " </mso:ribbon>" & vbNewLine
ribbonXML = ribbonXML + "</mso:customUI>"
ribbonXML = Replace(ribbonXML, """", "")
Open path & fileName For Output Access Write As hFile
Print #hFile, ribbonXML
Close hFile
End Sub
Private Sub Workbook_Deactivate()
Dim hFile As Long
Dim path As String, fileName As String, ribbonXML As String, user As String
hFile = FreeFile
user = Environ("Username")
path = "C:\Users\" & user & "\AppData\Local\Microsoft\Office\"
fileName = "Excel.officeUI"
ribbonXML = "<mso:customUI xmlns:mso=""http://schemas.microsoft.com/office/2009/07/customui"">" & _
"<mso:ribbon></mso:ribbon></mso:customUI>"
Open path & fileName For Output Access Write As hFile
Print #hFile, ribbonXML
Close hFile
End Sub
Don't forget to save and re-open workbook. Hope this helps!
ag
(the silver searcher) has pretty simple syntax for this
-G --file-search-regex PATTERN
Only search files whose names match PATTERN.
so
ag -G *.h -G *.cpp CP_Image <path>
Ignoring the check results in a corrupted install. This is the only solution that worked for me:
Create a C# console app with the following code:
Console.WriteLine(string.Format("{0,3}", CultureInfo.InstalledUICulture.Parent.LCID.ToString("X")).Replace(" ", "0"));
Run the app and get the 3 digit code.
Run > Regedit, open the following path: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib
Now, if you don't have a folder underneath that path with the 3 digit code from step 2, create it. If you do have the folder, check that it has the "Counter" and "Help" values set under that path. It probably doesn't -- which is why the check fails.
Create the missing Counter and Help keys (REG_MULTI_SZ). For the values, copy them from the existing path above (probably 009).
The check should now pass.
Using my own local server.
Simply adding http://localhost/my-site
as a URL in:
https://developers.facebook.com/apps/YOUR-APP-ID/fb-login/
worked for me.
You'd need to create a class with CSS -
.greenclass {color:green;}
Then you could add that to elements with
$('selector').addClass("greenclass");
and remove it with -
$('selector').removeClass("greenclass");
In addition to the above answers here is how you might handle a 500 series response from your api where you receive an error message encoded in json:
function callApi(url) {
return fetch(url)
.then(response => {
if (response.ok) {
return response.json().then(response => ({ response }));
}
return response.json().then(error => ({ error }));
})
;
}
let url = 'http://jsonplaceholder.typicode.com/posts/6';
const { response, error } = callApi(url);
if (response) {
// handle json decoded response
} else {
// handle json decoded 500 series response
}
<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>
That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em'
as the measurement, you may want to use other units, like 'px'
.
EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:
In your HTML page, containing the <p>
tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:
<head>
<style type="text/css">
p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>
So above, all <p>
elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:
<head>
<style type="text/css">
.container p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<div class="container">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</div>
<p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>
In the example above, only the <p>
element inside the div, whose class name is 'container', will have the styles applied - and not the <p>
element outside the container.
In addition to the above, you can collect your styles together and remove the style element from the <head>
tag, replacing it with a <link>
tag, which points to an external CSS file. This external file is where you'd now put your <p>
tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.
If you want to pass non-URL state, then you must not use url
when setting up your state
. I found the answer on a PR and did some monkeying around to better understand.
$stateProvider.state('toState', {
templateUrl:'wokka.html',
controller:'stateController',
params: {
'referer': 'some default',
'param2': 'some default',
'etc': 'some default'
}
});
Then you can navigate to it like so:
$state.go('toState', { 'referer':'jimbob', 'param2':37, 'etc':'bluebell' });
Or:
var result = { referer:'jimbob', param2:37, etc:'bluebell' };
$state.go('toState', result);
And in HTML thusly:
<a ui-sref="toState(thingy)" class="list-group-item" ng-repeat="thingy in thingies">{{ thingy.referer }}</a>
This use case is completely uncovered in the documentation, but I think it's a powerful means on transitioning state without using URLs.
redux-loop takes a cue from Elm and provides this pattern.
Reformatted the answer by @epascarello:
u.dotted {_x000D_
border-bottom: 1px dashed #999;_x000D_
text-decoration: none;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<u class="dotted">I like cheese</u>
_x000D_
It's my understanding that the original GetHashCode() returns the memory address of the object, so it's essential to override it if you wish to compare two different objects.
EDITED: That was incorrect, the original GetHashCode() method cannot assure the equality of 2 values. Though objects that are equal return the same hash code.
work with you apply runat="server" in your div section...
<div runat="server" id="hideid">
On your button click event:
protected void btnSubmit_Click(object sender, EventArgs e)
{
hideid.Visible = false;
}
Update for RxJS 6 (April 2018)
It is now perfectly fine to import directly from rxjs
. (As can be seen in Angular 6+). Importing from rxjs/operators
is also fine and it is actually no longer possible to import operators globally (one of major reasons for refactoring rxjs 6
and the new approach using pipe
). Thanks to this treeshaking can now be used as well.
Sample code from rxjs repo:
import { Observable, Subject, ReplaySubject, from, of, range } from 'rxjs';
import { map, filter, switchMap } from 'rxjs/operators';
range(1, 200)
.pipe(filter(x => x % 2 === 1), map(x => x + x))
.subscribe(x => console.log(x));
Backwards compatibility for rxjs < 6?
rxjs team released a compatibility package on npm that is pretty much install & play. With this all your rxjs 5.x
code should run without any issues. This is especially useful now when most of the dependencies (i.e. modules for Angular) are not yet updated.
Winand, Quality was also an issue for me so I did this:
For Each ws In ActiveWorkbook.Worksheets
If ws.PageSetup.PrintArea <> "" Then
'Reverse the effects of page zoom on the exported image
zoom_coef = 100 / ws.Parent.Windows(1).Zoom
areas = Split(ws.PageSetup.PrintArea, ",")
areaNo = 0
For Each a In areas
Set area = ws.Range(a)
' Change xlPrinter to xlScreen to see zooming white space
area.CopyPicture Appearance:=xlPrinter, Format:=xlPicture
Set chartobj = ws.ChartObjects.Add(0, 0, area.Width * zoom_coef, area.Height * zoom_coef)
chartobj.Chart.Paste
'scale the image before export
ws.Shapes(chartobj.Index).ScaleHeight 3, msoFalse, msoScaleFromTopLeft
ws.Shapes(chartobj.Index).ScaleWidth 3, msoFalse, msoScaleFromTopLeft
chartobj.Chart.Export ws.Name & "-" & areaNo & ".png", "png"
chartobj.delete
areaNo = areaNo + 1
Next
End If
Next
See here:https://robp30.wordpress.com/2012/01/11/improving-the-quality-of-excel-image-export/
The simplest solution that I can think of is using Properties class.
Saving the map:
Map<String, String> ldapContent = new HashMap<String, String>();
Properties properties = new Properties();
for (Map.Entry<String,String> entry : ldapContent.entrySet()) {
properties.put(entry.getKey(), entry.getValue());
}
properties.store(new FileOutputStream("data.properties"), null);
Loading the map:
Map<String, String> ldapContent = new HashMap<String, String>();
Properties properties = new Properties();
properties.load(new FileInputStream("data.properties"));
for (String key : properties.stringPropertyNames()) {
ldapContent.put(key, properties.get(key).toString());
}
EDIT:
if your map contains plaintext values, they will be visible if you open file data via any text editor, which is not the case if you serialize the map:
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.ser"));
out.writeObject(ldapContent);
out.close();
EDIT2:
instead of for loop (as suggested by OldCurmudgeon) in saving example:
properties.putAll(ldapContent);
however, for the loading example this is the best that can be done:
ldapContent = new HashMap<Object, Object>(properties);
First the mysqldump command is executed and the output generated is redirected using the pipe. The pipe is sending the standard output into the gzip command as standard input. Following the filename.gz, is the output redirection operator (>) which is going to continue redirecting the data until the last filename, which is where the data will be saved.
For example, this command will dump the database and run it through gzip and the data will finally land in three.gz
mysqldump -u user -pupasswd my-database | gzip > one.gz > two.gz > three.gz
$> ls -l
-rw-r--r-- 1 uname grp 0 Mar 9 00:37 one.gz
-rw-r--r-- 1 uname grp 1246 Mar 9 00:37 three.gz
-rw-r--r-- 1 uname grp 0 Mar 9 00:37 two.gz
My original answer is an example of redirecting the database dump to many compressed files (without double compressing). (Since I scanned the question and seriously missed - sorry about that)
This is an example of recompressing files:
mysqldump -u user -pupasswd my-database | gzip -c > one.gz; gzip -c one.gz > two.gz; gzip -c two.gz > three.gz
$> ls -l
-rw-r--r-- 1 uname grp 1246 Mar 9 00:44 one.gz
-rw-r--r-- 1 uname grp 1306 Mar 9 00:44 three.gz
-rw-r--r-- 1 uname grp 1276 Mar 9 00:44 two.gz
This is a good resource explaining I/O redirection: http://www.codecoffee.com/tipsforlinux/articles2/042.html
If you do not mind using an external library, Thumbnailator can perform scaling of BufferedImage
s.
Thumbnailator will take care of handling the Java 2D processing (such as using Graphics2D
and setting appropriate rendering hints) so that a simple fluent API call can be used to resize images:
BufferedImage image = Thumbnails.of(originalImage).scale(2.0).asBufferedImage();
Although Thumbnailator, as its name implies, is geared toward shrinking images, it will do a decent job enlarging images as well, using bilinear interpolation in its default resizer implementation.
Disclaimer: I am the maintainer of the Thumbnailator library.
If some object bar
holds a reference to a mutable object foo
and encapsulates some of its state in mutable aspects of foo
's state, that will allow code which can change those aspects of foo
to change the corresponding aspects of bar
's state without actually touching bar
or even knowing of its existence. Generally, this means that objects which encapsulate their own state using mutable objects must ensure that no references to those objects are exposed to any code which might unexpectedly mutate them. By contrast, if bar
holds a reference to an object moo
and only uses immutable aspects of moo
other than identity to encapsulate its state, then bar
can freely expose moo
to outside code without worrying about anything the outside code might do to it.
I think one of the fastest is my method that I made.
void prime(long long int number) {
// Establishing Variables
long long int i = 5;
int w = 2;
const long long int lim = sqrt(number);
// Gets 2 and 3 out of the way
if (number == 1) { cout << number << " is hard to classify. \n"; return; }
if (number == 2) { cout << number << " is Prime. \n"; return; }
if (number == 3) { cout << number << " is Prime. \n"; return; }
// Tests Odd Ball Factors
if (number % 2 == 0) { cout << number << " is not Prime. \n"; return; }
if (number % 3 == 0) { cout << number << " is not Prime. \n"; return; }
while (i <= lim) {
if (number % i == 0) { cout << number << " is not Prime. \n"; return; }
// Tests Number
i = i + w; // Increments number
w = 6 - i; // We already tested 2 and 3
// So this removes testing multepules of this
}
cout << number << " is Prime. \n"; return;
}
so I have a solution that isn't perfect but it worked for me. Use the polygon example from Google, and use the pinpoint on Google Maps to get lat & long locations.
I used what I call "ocular copy & paste" where you look at the screen and then write in the numbers you want ;-)
<style>
#map {
height: 500px;
}
</style>
<script>
// This example creates a simple polygon representing the host city of the
// Greatest Outdoor Show On Earth.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 9,
center: {lat: 51.039, lng: -114.204},
mapTypeId: 'terrain'
});
// Define the LatLng coordinates for the polygon's path.
var triangleCoords = [
{lat: 51.183, lng: -114.234},
{lat: 51.154, lng: -114.235},
{lat: 51.156, lng: -114.261},
{lat: 51.104, lng: -114.259},
{lat: 51.106, lng: -114.261},
{lat: 51.102, lng: -114.272},
{lat: 51.081, lng: -114.271},
{lat: 51.081, lng: -114.234},
{lat: 51.009, lng: -114.236},
{lat: 51.008, lng: -114.141},
{lat: 50.995, lng: -114.142},
{lat: 50.998, lng: -114.160},
{lat: 50.984, lng: -114.163},
{lat: 50.987, lng: -114.141},
{lat: 50.979, lng: -114.141},
{lat: 50.921, lng: -114.141},
{lat: 50.921, lng: -114.210},
{lat: 50.893, lng: -114.210},
{lat: 50.892, lng: -114.140},
{lat: 50.888, lng: -114.139},
{lat: 50.878, lng: -114.094},
{lat: 50.878, lng: -113.994},
{lat: 50.840, lng: -113.954},
{lat: 50.854, lng: -113.905},
{lat: 50.922, lng: -113.906},
{lat: 50.935, lng: -113.877},
{lat: 50.943, lng: -113.877},
{lat: 50.955, lng: -113.912},
{lat: 51.183, lng: -113.910}
];
// Construct the polygon.
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
bermudaTriangle.setMap(map);
}
</script>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/jskey=YOUR_API_KEY&callback=initMap">
</script>
This gets you the outline for Calgary. I've attached an image here.
We've released EAP to dotCover and will be releasing the beta version soon.
There is no way you can delete a pull request yourself -- you and the repo owner (and all users with push access to it) can close it, but it will remain in the log. This is part of the philosophy of not denying/hiding what happened during development.
However, if there are critical reasons for deleting it (this is mainly violation of Github Terms of Service), Github support staff will delete it for you.
Whether or not they are willing to delete your PR for you is something you can easily ask them, just drop them an email at [email protected]
UPDATE: Currently Github requires support requests to be created here: https://support.github.com/contact
When Port xxxx is already being used, there's always a PID (Process Id) elaborated with the error. Simply go to the task manager on the machine you are running the application, click on details, and you will identify what the other application is. You can then decide whether you want to end that process or not
You can use move when you need to "transfer" the content of an object somewhere else, without doing a copy (i.e. the content is not duplicated, that's why it could be used on some non-copyable objects, like a unique_ptr). It's also possible for an object to take the content of a temporary object without doing a copy (and save a lot of time), with std::move.
This link really helped me out :
http://thbecker.net/articles/rvalue_references/section_01.html
I'm sorry if my answer is coming too late, but I was also looking for a good link for the std::move, and I found the links above a little bit "austere".
This puts the emphasis on r-value reference, in which context you should use them, and I think it's more detailed, that's why I wanted to share this link here.
#UBUNTU20
if you are opening this file as root, then type
root# visudo
the file will be opened, go to the line where you want to add/modifiy anything simply without any insert or i button pressed.
press ctrl + O
press ctrl + x
press enter
Optimization of the accepted answer:
The accepted answer has some functioning problems, so I want to share my code that does not rely on urllib2:
import requests
from pandas import json_normalize
url = 'https://www.energidataservice.dk/proxy/api/datastore_search?resource_id=nordpoolmarket&limit=5'
response = requests.get(url)
dictr = response.json()
recs = dictr['result']['records']
df = json_normalize(recs)
print(df)
Output:
_id HourUTC HourDK ... ElbasAveragePriceEUR ElbasMaxPriceEUR ElbasMinPriceEUR
0 264028 2019-01-01T00:00:00+00:00 2019-01-01T01:00:00 ... NaN NaN NaN
1 138428 2017-09-03T15:00:00+00:00 2017-09-03T17:00:00 ... 33.28 33.4 32.0
2 138429 2017-09-03T16:00:00+00:00 2017-09-03T18:00:00 ... 35.20 35.7 34.9
3 138430 2017-09-03T17:00:00+00:00 2017-09-03T19:00:00 ... 37.50 37.8 37.3
4 138431 2017-09-03T18:00:00+00:00 2017-09-03T20:00:00 ... 39.65 42.9 35.3
.. ... ... ... ... ... ... ...
995 139290 2017-10-09T13:00:00+00:00 2017-10-09T15:00:00 ... 38.40 38.4 38.4
996 139291 2017-10-09T14:00:00+00:00 2017-10-09T16:00:00 ... 41.90 44.3 33.9
997 139292 2017-10-09T15:00:00+00:00 2017-10-09T17:00:00 ... 46.26 49.5 41.4
998 139293 2017-10-09T16:00:00+00:00 2017-10-09T18:00:00 ... 56.22 58.5 49.1
999 139294 2017-10-09T17:00:00+00:00 2017-10-09T19:00:00 ... 56.71 65.4 42.2
PS: API is for Danish electricity prices
you can simply use onBackPressed();
or if you are using fragment you can use getActivity().onBackPressed()
Same issue on macOS and got it fixed by running the same installer again.
Whereas I COULD NOT get it fixed by
Note: Make sure to select 'XAMPP Core Files' component while running the installer as by default it is not selected.
Though re-running the installer is not smart option when one has to do it every now and then. My installer is xampp-osx-7.0.13-1-installer.dmg
Update: I've got my MAMP working with this simple solution here. So, same should work for XAMPP.
Try this code.
public void send (String fileName) {
String SFTPHOST = "host:IP";
int SFTPPORT = 22;
String SFTPUSER = "username";
String SFTPPASS = "password";
String SFTPWORKINGDIR = "file/to/transfer";
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
System.out.println("preparing the host information for sftp.");
try {
JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
System.out.println("Host connected.");
channel = session.openChannel("sftp");
channel.connect();
System.out.println("sftp channel opened and connected.");
channelSftp = (ChannelSftp) channel;
channelSftp.cd(SFTPWORKINGDIR);
File f = new File(fileName);
channelSftp.put(new FileInputStream(f), f.getName());
log.info("File transfered successfully to host.");
} catch (Exception ex) {
System.out.println("Exception found while tranfer the response.");
} finally {
channelSftp.exit();
System.out.println("sftp Channel exited.");
channel.disconnect();
System.out.println("Channel disconnected.");
session.disconnect();
System.out.println("Host Session disconnected.");
}
}
There is also the strncmp()
function and strncasecmp()
function which is perfect for this situation:
if (strncmp($string_n, "http", 4) === 0)
In general:
if (strncmp($string_n, $prefix, strlen($prefix)) === 0)
The advantage over the substr()
approach is that strncmp()
just does what needs to be done, without creating a temporary string.
This actually works for me:
background-color: #6DB3F2;
background-image: url('images/checked.png');
You can also drop a solid shadow and set the background image:
background-image: url('images/checked.png');
box-shadow: inset 0 0 100% #6DB3F2;
If the first option is not working for some reason and you don't want to use the box shadow you can always use a pseudo element for the image without any extra HTML:
.btn{
position: relative;
background-color: #6DB3F2;
}
.btn:before{
content: "";
display: block;
width: 100%;
height: 100%;
position:absolute;
top:0;
left:0;
background-image: url('images/checked.png');
}
One can access the "Find in Files" window via the drop-down menu selection and search all files in the Entire Solution: Edit > Find and Replace > Find in Files
Other, alternative is to open the "Find in Files" window via the "Standard Toolbars" button as highlighted in the below screen-short:
There is one more possibility. I had the same problem just now and no one of the solutions here helped. Except removing and recreating of the project - I didn't want to try it. What did help, was to clean the project two times immediately one after another! Clean + build could be repeated any number of times - it won't help. Only clean+clean and after that build goes OK. (Eclipse 3.6). Of course, you should disable autobuild for that.
Edit: This post has got its last plus on 15.11.2017. So, the problem (and the solution) remains actual.
You could use id in span directly in your html.
<span id="span_id">Client</span>
Then your jQuery code would be
$("#span_id").text();
Some one helped me to check errors and found that he used val() instead of text(), it is not possible to use val() function in span. So
$("#span_id").val();
will return null.
In Sql Server 2008 R2 database files you can connect with
Server=np:\\.\pipe\YourInstance\tsql\query;InitialCatalog=yourDataBase;Trusted_Connection=True;
only, but in sql Server 2012 you can use this:
Server=(localdb)\v11.0;Integrated Security=true;Database=DB1;
and it depended on your .mdf
.ldf
version.
for finding programmicaly i use this Method that explained in this post
Mount your sql-dump under/docker-entrypoint-initdb.d/yourdump.sql
utilizing a volume mount
mysql:
image: mysql:latest
container_name: mysql-container
ports:
- 3306:3306
volumes:
- ./dump.sql:/docker-entrypoint-initdb.d/dump.sql
environment:
MYSQL_ROOT_PASSWORD: secret
MYSQL_DATABASE: name_db
MYSQL_USER: user
MYSQL_PASSWORD: password
This will trigger an import of the sql-dump during the start of the container, see https://hub.docker.com/_/mysql/ under "Initializing a fresh instance"
You can add .dll file manually. For example if you want to add a dll file in your WPF application, and you are unable to refer it in your project
(Getting error :A reference to the "....dll" could not be added.Please make sure that the file is accessible and that it is a valid assembly or COM component) ,
then COPY that dll file and PASTE in the INSTALLER PROJECT (in application folder).
From what I observed, I see that when your website is public and even though the image url is https, it just works fine.
I had a need to capture and compare old values to the new values entered into a complex scheduling spreadsheet. I needed a general solution which worked even when the user changed many rows at the same time. The solution implemented a CLASS and a COLLECTION of that class.
The class: oldValue
Private pVal As Variant
Private pAdr As String
Public Property Get Adr() As String
Adr = pAdr
End Property
Public Property Let Adr(Value As String)
pAdr = Value
End Property
Public Property Get Val() As Variant
Val = pVal
End Property
Public Property Let Val(Value As Variant)
pVal = Value
End Property
There are three sheets in which i track cells. Each sheet gets its own collection as a global variable in the module named ProjectPlan as follows:
Public prepColl As Collection
Public preColl As Collection
Public postColl As Collection
Public migrColl As Collection
The InitDictionaries SUB is called out of worksheet.open to establish the collections.
Sub InitDictionaries()
Set prepColl = New Collection
Set preColl = New Collection
Set postColl = New Collection
Set migrColl = New Collection
End Sub
There are three modules used to manage each collection of oldValue objects they are Add, Exists, and Value.
Public Sub Add(ByRef rColl As Collection, ByVal sAdr As String, ByVal sVal As Variant)
Dim oval As oldValue
Set oval = New oldValue
oval.Adr = sAdr
oval.Val = sVal
rColl.Add oval, sAdr
End Sub
Public Function Exists(ByRef rColl As Collection, ByVal sAdr As String) As Boolean
Dim oReq As oldValue
On Error Resume Next
Set oReq = rColl(sAdr)
On Error GoTo 0
If oReq Is Nothing Then
Exists = False
Else
Exists = True
End If
End Function
Public Function Value(ByRef rColl As Collection, ByVal sAdr) As Variant
Dim oReq As oldValue
If Exists(rColl, sAdr) Then
Set oReq = rColl(sAdr)
Value = oReq.Val
Else
Value = ""
End If
End Function
The heavy lifting is done in the Worksheet_SelectionChange callback. One of the four is shown below. The only difference is the collection used in the ADD and EXIST calls.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim mode As Range
Set mode = Worksheets("schedule").Range("PlanExecFlag")
If mode.Value = 2 Then
Dim c As Range
For Each c In Target
If Not ProjectPlan.Exists(prepColl, c.Address) Then
Call ProjectPlan.Add(prepColl, c.Address, c.Value)
End If
Next c
End If
End Sub
THe VALUE call is called out of code executed from the Worksheet_Change Callback for example. I need to assign the correct collection based on the sheet name:
Dim rColl As Collection
If sheetName = "Preparations" Then
Set rColl = prepColl
ElseIf sheetName = "Pre-Tasks" Then
Set rColl = preColl
ElseIf sheetName = "Migr-Tasks" Then
Set rColl = migrColl
ElseIf sheetName = "post-Tasks" Then
Set rColl = postColl
Else
End If
and then i am free to compute compare the some current value to the original value.
If Exists(rColl, Cell.Offset(0, 0).Address) Then
tsk_delay = Cell.Offset(0, 0).Value - Value(rColl, Cell.Offset(0, 0).Address)
Else
tsk_delay = 0
End If
Mark
sort
has been replaced in v0.20 by DataFrame.sort_values
and DataFrame.sort_index
. Aside from this, we also have argsort
.
Here are some common use cases in sorting, and how to solve them using the sorting functions in the current API. First, the setup.
# Setup
np.random.seed(0)
df = pd.DataFrame({'A': list('accab'), 'B': np.random.choice(10, 5)})
df
A B
0 a 7
1 c 9
2 c 3
3 a 5
4 b 2
For example, to sort df
by column "A", use sort_values
with a single column name:
df.sort_values(by='A')
A B
0 a 7
3 a 5
4 b 2
1 c 9
2 c 3
If you need a fresh RangeIndex, use DataFrame.reset_index
.
For example, to sort by both col "A" and "B" in df
, you can pass a list to sort_values
:
df.sort_values(by=['A', 'B'])
A B
3 a 5
0 a 7
4 b 2
2 c 3
1 c 9
df2 = df.sample(frac=1)
df2
A B
1 c 9
0 a 7
2 c 3
3 a 5
4 b 2
You can do this using sort_index
:
df2.sort_index()
A B
0 a 7
1 c 9
2 c 3
3 a 5
4 b 2
df.equals(df2)
# False
df.equals(df2.sort_index())
# True
Here are some comparable methods with their performance:
%timeit df2.sort_index()
%timeit df2.iloc[df2.index.argsort()]
%timeit df2.reindex(np.sort(df2.index))
605 µs ± 13.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
610 µs ± 24.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
581 µs ± 7.63 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
For example,
idx = df2.index.argsort()
idx
# array([0, 7, 2, 3, 9, 4, 5, 6, 8, 1])
This "sorting" problem is actually a simple indexing problem. Just passing integer labels to iloc
will do.
df.iloc[idx]
A B
1 c 9
0 a 7
2 c 3
3 a 5
4 b 2
Thanks, Varun Rathore
. It works perfectly!
For those who want graceful collapse from 4 items per row to 2 items per row depending on the screen width:
<ul class="list-group row">
<li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_1</li>
<li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_2</li>
<li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_3</li>
<li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_4</li>
<li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_5</li>
<li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_6</li>
<li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_7</li>
</ul>
I had similar problem and this seem to solve the problem. You just need to initialize the $res object to a class . Suppose here the class name is test.
class test
{
//You can keep the class empty or declare your success variable here
}
$res = new test();
$res->success = false;
Something along these lines ....
//default icon, custom title
int n = JOptionPane.showConfirmDialog(null,"Would you like green eggs and ham?","An Inane Question",JOptionPane.YES_NO_OPTION);
String result = "?";
switch (n) {
case JOptionPane.YES_OPTION:
result = "YES";
break;
case JOptionPane.NO_OPTION:
result = "NO";
break;
default:
;
}
System.out.println("Replace? " + result);
you may also want to look at DialogDemo
The other answers mostly use the flags for setSystemUiVisibility()
method in View
. However, this API is deprecated since Android 11. Check my article about modifying the system UI visibility for more information. The article also explains how to handle the cutouts properly or how to listen to the visibility changes.
Here are code snippets for showing / hiding system bars with the new API as well as the deprecated one for backward compatibility:
/**
* Hides the system bars and makes the Activity "fullscreen". If this should be the default
* state it should be called from [Activity.onWindowFocusChanged] if hasFocus is true.
* It is also recommended to take care of cutout areas. The default behavior is that the app shows
* in the cutout area in portrait mode if not in fullscreen mode. This can cause "jumping" if the
* user swipes a system bar to show it. It is recommended to set [WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER],
* call [showBelowCutout] from [Activity.onCreate]
* (see [Android Developers article about cutouts](https://developer.android.com/guide/topics/display-cutout#never_render_content_in_the_display_cutout_area)).
* @see showSystemUI
* @see addSystemUIVisibilityListener
*/
fun Activity.hideSystemUI() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
window.insetsController?.let {
// Default behavior is that if navigation bar is hidden, the system will "steal" touches
// and show it again upon user's touch. We just want the user to be able to show the
// navigation bar by swipe, touches are handled by custom code -> change system bar behavior.
// Alternative to deprecated SYSTEM_UI_FLAG_IMMERSIVE.
it.systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
// make navigation bar translucent (alternative to deprecated
// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
// - do this already in hideSystemUI() so that the bar
// is translucent if user swipes it up
window.navigationBarColor = getColor(R.color.internal_black_semitransparent_light)
// Finally, hide the system bars, alternative to View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
// and SYSTEM_UI_FLAG_FULLSCREEN.
it.hide(WindowInsets.Type.systemBars())
}
} else {
// Enables regular immersive mode.
// For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE.
// Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY
@Suppress("DEPRECATION")
window.decorView.systemUiVisibility = (
// Do not let system steal touches for showing the navigation bar
View.SYSTEM_UI_FLAG_IMMERSIVE
// Hide the nav bar and status bar
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_FULLSCREEN
// Keep the app content behind the bars even if user swipes them up
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
// make navbar translucent - do this already in hideSystemUI() so that the bar
// is translucent if user swipes it up
@Suppress("DEPRECATION")
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
}
}
/**
* Shows the system bars and returns back from fullscreen.
* @see hideSystemUI
* @see addSystemUIVisibilityListener
*/
fun Activity.showSystemUI() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// show app content in fullscreen, i. e. behind the bars when they are shown (alternative to
// deprecated View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION and View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
window.setDecorFitsSystemWindows(false)
// finally, show the system bars
window.insetsController?.show(WindowInsets.Type.systemBars())
} else {
// Shows the system bars by removing all the flags
// except for the ones that make the content appear under the system bars.
@Suppress("DEPRECATION")
window.decorView.systemUiVisibility = (
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
}
}
Although its pretty late to comment on this I want to add a more complete example using MERGE.
Such Insert+Update statements are usually called "Upsert" statements and can be implemented using MERGE in SQL Server.
A very good example is given here: http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx
The above explains locking and concurrency scenarios as well.
I will be quoting the same for reference:
ALTER PROCEDURE dbo.Merge_Foo2
@ID int
AS
SET NOCOUNT, XACT_ABORT ON;
MERGE dbo.Foo2 WITH (HOLDLOCK) AS f
USING (SELECT @ID AS ID) AS new_foo
ON f.ID = new_foo.ID
WHEN MATCHED THEN
UPDATE
SET f.UpdateSpid = @@SPID,
UpdateTime = SYSDATETIME()
WHEN NOT MATCHED THEN
INSERT
(
ID,
InsertSpid,
InsertTime
)
VALUES
(
new_foo.ID,
@@SPID,
SYSDATETIME()
);
RETURN @@ERROR;
In django 3.1, go to setting of your project and import os
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
If you want to find interactively logged on users, I found a great tip here :https://p0w3rsh3ll.wordpress.com/2012/02/03/get-logged-on-users/ (Win32_ComputerSystem did not help me)
$explorerprocesses = @(Get-WmiObject -Query "Select * FROM Win32_Process WHERE Name='explorer.exe'" -ErrorAction SilentlyContinue)
If ($explorerprocesses.Count -eq 0)
{
"No explorer process found / Nobody interactively logged on"
}
Else
{
ForEach ($i in $explorerprocesses)
{
$Username = $i.GetOwner().User
$Domain = $i.GetOwner().Domain
Write-Host "$Domain\$Username logged on since: $($i.ConvertToDateTime($i.CreationDate))"
}
}
Sometimes the column you want to filter may appear in a different position than column index 2 or have a variable name.
In this case, you can simply refer the column name you want to filter as:
columnNameToFilter = "cell_type"
expr[expr[[columnNameToFilter]] == "hesc", ]
I'm wondering if there is any way to get a value from a Promise or wait (block/sleep) until it has resolved, similar to .NET's IAsyncResult.WaitHandle.WaitOne(). I know JavaScript is single-threaded, but I'm hoping that doesn't mean that a function can't yield.
The current generation of Javascript in browsers does not have a wait()
or sleep()
that allows other things to run. So, you simply can't do what you're asking. Instead, it has async operations that will do their thing and then call you when they're done (as you've been using promises for).
Part of this is because of Javascript's single threadedness. If the single thread is spinning, then no other Javascript can execute until that spinning thread is done. ES6 introduces yield
and generators which will allow some cooperative tricks like that, but we're quite a ways from being able to use those in a wide swatch of installed browsers (they can be used in some server-side development where you control the JS engine that is being used).
Careful management of promise-based code can control the order of execution for many async operations.
I'm not sure I understand exactly what order you're trying to achieve in your code, but you could do something like this using your existing kickOff()
function, and then attaching a .then()
handler to it after calling it:
function kickOff() {
return new Promise(function(resolve, reject) {
$("#output").append("start");
setTimeout(function() {
resolve();
}, 1000);
}).then(function() {
$("#output").append(" middle");
return " end";
});
}
kickOff().then(function(result) {
// use the result here
$("#output").append(result);
});
This will return output in a guaranteed order - like this:
start
middle
end
Update in 2018 (three years after this answer was written):
If you either transpile your code or run your code in an environment that supports ES7 features such as async
and await
, you can now use await
to make your code "appear" to wait for the result of a promise. It is still developing with promises. It does still not block all of Javascript, but it does allow you to write sequential operations in a friendlier syntax.
Instead of the ES6 way of doing things:
someFunc().then(someFunc2).then(result => {
// process result here
}).catch(err => {
// process error here
});
You can do this:
// returns a promise
async function wrapperFunc() {
try {
let r1 = await someFunc();
let r2 = await someFunc2(r1);
// now process r2
return someValue; // this will be the resolved value of the returned promise
} catch(e) {
console.log(e);
throw e; // let caller know the promise was rejected with this reason
}
}
wrapperFunc().then(result => {
// got final result
}).catch(err => {
// got error
});
Once Go lang is installed, GOROOT is the root directory of the installation.
When I exploded Go Lang binary in Windows C:\ directory, my GOROOT should be C:\go. If Installed with Windows installer, it may be C:\Program Files\go (or C:\Program Files (x86)\go, for 64-bit packages)
GOROOT = C:\go
while my GOPATH is location of Go lang source code or workspace.
If my Go lang source code is located at C:\Users\\GO_Workspace, your GOPATH would be as below:
GOPATH = C:\Users\<xyz>\GO_Workspace
You can use standard JS toFixed
method
var num = 5.56789;
var n=num.toFixed(2);
//5.57
In order to add commas (to separate 1000's) you can add regexp as follows (where num
is a number):
num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
//100000 => 100,000
//8000 => 8,000
//1000000 => 1,000,000
Complete example:
var value = 1250.223;
var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
//document.write(num) would write value as follows: $1,250.22
Separation character depends on country and locale. For some countries it may need to be .
I discovered the joy of anaconda: https://www.continuum.io/downloads
C:> conda create -n tensorflow1.1 python=3.5
C:> activate tensorflow1.1
(tensorflow1.1)
C:> pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-1.1.0-cp35-cp35m-win_amd64.whl
voila, a virtual environment is created.
You have to instantiate the object first. The simplest way is:
var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++) {
data.push({label: lab[i], value: val[i]});
}
Or an other, less concise way, but closer to your original code:
for(var i=0; i<4; i++) {
data[i] = {}; // creates a new object
data[i].label = lab[i];
data[i].value = val[i];
}
array()
will not create a new array (unless you defined that function). Either Array()
or new Array()
or just []
.
I recommend to read the MDN JavaScript Guide.
You need to copy the array before you sort it. One way with es6:
const sorted = [...arr].sort();
the spread-syntax as array literal (copied from mdn):
var arr = [1, 2, 3];
var arr2 = [...arr]; // like arr.slice()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator
$('div[contenteditable]').keydown(function(e) {
// trap the return key being pressed
if (e.keyCode === 13 || e.keyCode === 8)
{
return false;
}
});
Or you can change position of specific
div
using class name
$(document).scroll(function(e){
var scrollTop = $(document).scrollTop();
if(scrollTop > 0){
//console.log(scrollTop);
$('.header').css("position","fixed");
} else {
$('.header').css("position","relative");
}
});
Google has ended support for eclipse plugin. If you prefer to use eclipse still you can download Eclipse Android Development Tool from
The syntax to store the command output into a variable is var=$(command)
.
So you can directly do:
result=$(ls -l | grep -c "rahul.*patle")
And the variable $result
will contain the number of matches.
Here's the way to do this via storyboard in XCode 10.2.1. Separator defaults to default
which is the line. Set it to none
to remove the line.
Step 1 :- GO to My Apps App in iTunes Connect
Here you can see your all app which are currently on Appstore.
Step 2 :- Select your app which you want to delete.(click on app-name)
Step 3 :- Select Pricing and Availability Tab.
Step 4 :- Select Remove from sale option.
Step 5 :- Click on save Button.
Now you will see below your app like , Developer Removed it from sale in Red Symbol in place of Green.
Step 6 :- Now again Select your app and Go to App information Tab. you will see Delete App option. (need to scroll bit bottom)
Step 7 :- After clicking on Delete button you will get warning like this ,
Step 8 :- Click on Delete button.
Congratulation , You have Permanently deleted your app successfully from appstore. Now , you cant able to see app on appstore aswellas in your developer account.
Note :-
When you have selected only Remove from sale option you have not deleted app permanently. You can able to make your app live again by clicking on Available in all territories option Again.
They are two different concepts: "void pointer" is a type (void *). "null pointer" is a pointer that has a value of zero (NULL). Example:
void *pointer = NULL;
That's a NULL void pointer.
You can try to apply new architecture approach anounced at Google I/O 2017.
It also includes new ORM library called Room
It contains three main components: @Entity, @Dao and @Database
User.java
@Entity
public class User {
@PrimaryKey
private int uid;
@ColumnInfo(name = "first_name")
private String firstName;
@ColumnInfo(name = "last_name")
private String lastName;
// Getters and setters are ignored for brevity,
// but they're required for Room to work.
}
UserDao.java
@Dao
public interface UserDao {
@Query("SELECT * FROM user")
List<User> getAll();
@Query("SELECT * FROM user WHERE uid IN (:userIds)")
List<User> loadAllByIds(int[] userIds);
@Query("SELECT * FROM user WHERE first_name LIKE :first AND "
+ "last_name LIKE :last LIMIT 1")
User findByName(String first, String last);
@Insert
void insertAll(User... users);
@Delete
void delete(User user);
}
AppDatabase.java
@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
No, how you are doing it is correct.
http://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2.2
You escape it by doubling the braces.
Eg:
x = "{{ Hello }} {0}"
print(x.format(42))
Probably the "best" way to do this (quoted since "best" is a subjective term) is to keep a running (non-integral) tally of where you are, and round that value.
Then use that along with the history to work out what value should be used. For example, using the values you gave:
Value CumulValue CumulRounded PrevBaseline Need
--------- ---------- ------------ ------------ ----
0
13.626332 13.626332 14 0 14 ( 14 - 0)
47.989636 61.615968 62 14 48 ( 62 - 14)
9.596008 71.211976 71 62 9 ( 71 - 62)
28.788024 100.000000 100 71 29 (100 - 71)
---
100
At each stage, you don't round the number itself. Instead, you round the accumulated value and work out the best integer that reaches that value from the previous baseline - that baseline is the cumulative value (rounded) of the previous row.
This works because you're not losing information at each stage but rather using the information more intelligently. The 'correct' rounded values are in the final column and you can see that they sum to 100.
You can see the difference between this and blindly rounding each value, in the third value above. While 9.596008
would normally round up to 10
, the accumulated 71.211976
correctly rounds down to 71
- this means that only 9
is needed to add to the previous baseline of 62
.
This also works for "problematic" sequence like three roughly-1/3
values, where one of them should be rounded up:
Value CumulValue CumulRounded PrevBaseline Need
--------- ---------- ------------ ------------ ----
0
33.333333 33.333333 33 0 33 ( 33 - 0)
33.333333 66.666666 67 33 34 ( 67 - 33)
33.333333 99.999999 100 67 33 (100 - 67)
---
100
By combining Radek and l0co's answers you can access the WSDL behind https:
SSLContext sc = SSLContext.getInstance("TLS");
KeyManagerFactory kmf = KeyManagerFactory
.getInstance(KeyManagerFactory.getDefaultAlgorithm());
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(getClass().getResourceAsStream(keystore),
password.toCharArray());
kmf.init(ks, password.toCharArray());
sc.init(kmf.getKeyManagers(), null, null);
HttpsURLConnection
.setDefaultSSLSocketFactory(sc.getSocketFactory());
yourService = new YourService(url); //Handshake should succeed
check the following link https://www.geeksforgeeks.org/how-to-create-an-unordered_map-of-user-defined-class-in-cpp/ for more details.
Normaly you should never use @ unless this is the only solution. In that specific case the function dns_check_record should be use first to know if the record exists.
Turns out the binding of style to a string doesn't work. The solution would be to bind the background of the style.
<div class="circle" [style.background]="color">
In case than you want to store a complex command to compare text result, for example to compare the version of OS, maybe this can help you:
tasks:
- shell: echo $(cat /etc/issue | awk {'print $7'})
register: echo_content
- shell: echo "It works"
when: echo_content.stdout == "12"
register: out
- debug: var=out.stdout_lines
Underscore.js is a good library for these sorts of operations - it uses the builtin routines such as Array.filter if available, or uses its own if not.
http://documentcloud.github.com/underscore/
The docs will give an idea of use - the javascript lambda syntax is nowhere near as succinct as ruby or others (I always forget to add an explicit return statement for example) and scope is another easy way to get caught out, but you can do most things quite easily with the exception of constructs such as lazy list comprehensions.
From the docs for .select() (.filter() is an alias for the same)
Looks through each value in the list, returning an array of all the values that pass a truth test (iterator). Delegates to the native filter method, if it exists.
var evens = _.select([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [2, 4, 6]
namespace Exception
{
class Program
{
static void Main(string[] args)
{
bool isNumeric;
int n;
do
{
Console.Write("Enter a number:");
isNumeric = int.TryParse(Console.ReadLine(), out n);
} while (isNumeric == false);
Console.WriteLine("Thanks for entering number" + n);
Console.Read();
}
}
}
Let me summarise what you would like to version control and why:
What:
Why:
As others have posted here, there are a couple of solutions on top of existing version control systems such as:
If your only concern is the VBA code in your workbooks, then the approach Demosthenex above proposes or VbaGit (https://github.com/brucemcpherson/VbaGit) work very well working and are relatively simple to implement. The advantages are that you can rely on well proven version control systems and chose one according to your needs (have a look at https://help.github.com/articles/what-are-the-differences-between-svn-and-git/ for a brief comparison between Git and Subversion).
If you not only worry about code but also about the data in your sheets ("hardcoded" values and formula results), you can use a similar strategy for that: Serialise the contents of your sheets into some text format (via Range.Value) and use an existing version control system. Here's a very good blog post about this: https://wiki.ucl.ac.uk/display/~ucftpw2/2013/10/18/Using+git+for+version+control+of+spreadsheet+models+-+part+1+of+3
However, spreadsheet comparison is a non-trivial algorithmic problem. There are a few tools around, such as Microsoft's Spreadsheet Compare (https://support.office.com/en-us/article/Overview-of-Spreadsheet-Compare-13fafa61-62aa-451b-8674-242ce5f2c986), Exceldiff (http://exceldiff.arstdesign.com/) and DiffEngineX (https://www.florencesoft.com/compare-excel-workbooks-differences.html). But it's another challenge to integrate these comparison with a version control system like Git.
Finally, you have to settle on a workflow that suits your needs. For a simple, tailored Git for Excel workflow, have a look at https://www.xltrail.com/blog/git-workflow-for-excel.
You can also use Scroll Behaviour Property. for example add below line to your css
html{_x000D_
scroll-behavior:smooth;_x000D_
}
_x000D_
and this will result a native smooth scrolling feature . Read More about Scroll behavior
How about this?
var obj = {},
var isEmpty = !obj;
var hasContent = !!obj
There is no such method as slideLeft() and slideRight() which looks like slideUp() and slideDown(), but you can simulate these effects using jQuery’s animate() function.
HTML Code:
<div class="text">Lorem ipsum.</div>
JQuery Code:
$(document).ready(function(){
var DivWidth = $(".text").width();
$(".left").click(function(){
$(".text").animate({
width: 0
});
});
$(".right").click(function(){
$(".text").animate({
width: DivWidth
});
});
});
You can see an example here: How to slide toggle a DIV from Left to Right?
Well any Javascript object functions sort-of like a "map"
randomObject['hello'] = 'world';
Typically people build simple objects for the purpose:
var myMap = {};
// ...
myMap[newKey] = newValue;
edit — well the problem with having an explicit "put" function is that you'd then have to go to pains to avoid having the function itself look like part of the map. It's not really a Javascripty thing to do.
13 Feb 2014 — modern JavaScript has facilities for creating object properties that aren't enumerable, and it's pretty easy to do. However, it's still the case that a "put" property, enumerable or not, would claim the property name "put" and make it unavailable. That is, there's still only one namespace per object.
I have similar trouble in test config, because of using AOP. I added this line of code in spring-config.xml
<aop:config proxy-target-class="true"/>
And it works !
The first maximum you would hit is the length of a String which is 231-1 digits. It's much smaller than the maximum of a BigInteger but IMHO it loses much of its value if it can't be printed.
What I suggest for now is to create symlinks in a folder, since VSCode isn't supporting that feature.
First, make a folder called whatever you'd like it to be.
$ mkdir random_project_folder
$ cd random_project_folder
$ ln -s /path/to/folder1/you/want/to/open folder1
$ ln -s /path/to/folder2/you/want/to/open folder2
$ ln -s /path/to/folder3/you/want/to/open folder3
$ code .
And you'll see your folders in the same VSCode window.
In Android studio 2.2 you can directly analyze the apk. Goto build- analyze apk. Select the apk, navigate to androidmanifest.xml. You can see the details of androidmanifest.
This error will also occur when using pdsh to hosts which are not contained in your "known_hosts" file.
I was able to correct this by SSH'ing into each host manually and accepting the question "Do you want to add this to known hosts".
There's no need for you to use super-call of the ActionBarDrawerToggle
which requires the Toolbar. This means instead of using the following constructor:
ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout, Toolbar toolbar, int openDrawerContentDescRes, int closeDrawerContentDescRes)
You should use this one:
ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout, int openDrawerContentDescRes, int closeDrawerContentDescRes)
So basically the only thing you have to do is to remove your custom drawable
:
super(mActivity, mDrawerLayout, R.string.ns_menu_open, R.string.ns_menu_close);
More about the "new" ActionBarDrawerToggle in the Docs (click).
Rather give names of the column on which you want to merge:
exporttab <- merge(x=dwd_nogap, y=dwd_gap, by.x='x1', by.y='x2', fill=-9999)
A call to your parent class's empty constructor super()
is done automatically when you don't do it yourself. That's the reason you've never had to do it in your code. It was done for you.
When your superclass doesn't have a no-arg constructor, the compiler will require you to call super
with the appropriate arguments. The compiler will make sure that you instantiate the class correctly. So this is not something you have to worry about too much.
Whether you call super()
in your constructor or not, it doesn't affect your ability to call the methods of your parent class.
As a side note, some say that it's generally best to make that call manually for reasons of clarity.
TCPDF 5.9.010 (2010-10-27) - Support for CSS properties 'border-spacing' and 'padding' for tables were added.
file
then file -k
then dos2unix -ih
file
will usually be enough. But for tough cases try file -k
or dosunix -ih
.
Details below.
file -k
Short version: file -k somefile.txt
will tell you.
with CRLF line endings
for DOS/Windows line endings.with LF line endings
for MAC line endings.text
. (So if it does not explicitly mention any kind of line endings
then this implicitly means: "CR line endings".)Long version see below.
I sometimes have to check this for PEM certificate files.
The trouble with regular file
is this: Sometimes it's trying to be too smart/too specific.
Let's try a little quiz: I've got some files. And one of these files has different line endings. Which one?
(By the way: this is what one of my typical "certificate work" directories looks like.)
Let's try regular file
:
$ file -- *
0.example.end.cer: PEM certificate
0.example.end.key: PEM RSA private key
1.example.int.cer: PEM certificate
2.example.root.cer: PEM certificate
example.opensslconfig.ini: ASCII text
example.req: PEM certificate request
Huh. It's not telling me the line endings. And I already knew that those were cert files. I didn't need "file" to tell me that.
What else can you try?
You might try dos2unix
with the --info
switch like this:
$ dos2unix --info -- *
37 0 0 no_bom text 0.example.end.cer
0 27 0 no_bom text 0.example.end.key
0 28 0 no_bom text 1.example.int.cer
0 25 0 no_bom text 2.example.root.cer
0 35 0 no_bom text example.opensslconfig.ini
0 19 0 no_bom text example.req
So that tells you that: yup, "0.example.end.cer" must be the odd man out. But what kind of line endings are there? Do you know the dos2unix output format by heart? (I don't.)
But fortunately there's the --keep-going
(or -k
for short) option in file
:
$ file --keep-going -- *
0.example.end.cer: PEM certificate\012- , ASCII text, with CRLF line terminators\012- data
0.example.end.key: PEM RSA private key\012- , ASCII text\012- data
1.example.int.cer: PEM certificate\012- , ASCII text\012- data
2.example.root.cer: PEM certificate\012- , ASCII text\012- data
example.opensslconfig.ini: ASCII text\012- data
example.req: PEM certificate request\012- , ASCII text\012- data
Excellent! Now we know that our odd file has DOS (CRLF
) line endings. (And the other files have Unix (LF
) line endings. This is not explicit in this output. It's implicit. It's just the way file
expects a "regular" text file to be.)
(If you wanna share my mnemonic: "L" is for "Linux" and for "LF".)
Now let's convert the culprit and try again:
$ dos2unix -- 0.example.end.cer
$ file --keep-going -- *
0.example.end.cer: PEM certificate\012- , ASCII text\012- data
0.example.end.key: PEM RSA private key\012- , ASCII text\012- data
1.example.int.cer: PEM certificate\012- , ASCII text\012- data
2.example.root.cer: PEM certificate\012- , ASCII text\012- data
example.opensslconfig.ini: ASCII text\012- data
example.req: PEM certificate request\012- , ASCII text\012- data
Good. Now all certs have Unix line endings.
dos2unix -ih
I didn't know this when I was writing the example above but:
Actually it turns out that dos2unix will give you a header line if you use -ih
(short for --info=h
) like so:
$ dos2unix -ih -- *
DOS UNIX MAC BOM TXTBIN FILE
0 37 0 no_bom text 0.example.end.cer
0 27 0 no_bom text 0.example.end.key
0 28 0 no_bom text 1.example.int.cer
0 25 0 no_bom text 2.example.root.cer
0 35 0 no_bom text example.opensslconfig.ini
0 19 0 no_bom text example.req
And another "actually" moment: The header format is really easy to remember: Here's two mnemonics:
man file
man dos2unix
<system.webServer>
<staticContent>
<remove fileExtension=".woff"/>
<mimeMap fileExtension=".woff" mimeType="application/font-woff" />
<mimeMap fileExtension=".woff2" mimeType="font/woff2" />
</staticContent>
</system.webServer>
another alternative, just in case you want to have a shell script which creates the database if it does not exist and otherwise just keeps it as it is:
psql -U postgres -tc "SELECT 1 FROM pg_database WHERE datname = 'my_db'" | grep -q 1 || psql -U postgres -c "CREATE DATABASE my_db"
I found this to be helpful in devops provisioning scripts, which you might want to run multiple times over the same instance.
For those of you who would like an explanation:
-c = run command in database session, command is given in string
-t = skip header and footer
-q = silent mode for grep
|| = logical OR, if grep fails to find match run the subsequent command
def my_add_fn():
print "SUM:%s"%sum(map(int,raw_input("Enter 2 numbers seperated by a space").split()))
def my_quit_fn():
raise SystemExit
def invalid():
print "INVALID CHOICE!"
menu = {"1":("Sum",my_add_fn),
"2":("Quit",my_quit_fn)
}
for key in sorted(menu.keys()):
print key+":" + menu[key][0]
ans = raw_input("Make A Choice")
menu.get(ans,[None,invalid])[1]()
You can simply do the following inside your TR loop:
$(this).find('td').each (function() {
// do your cool stuff
});
Since the original question was about the SerializableAttribute, it should be noted that this attribute only applies when using the BinaryFormatter or SoapFormatter.
It is a bit confusing, unless you really pay attention to the details, as to when to use it and what its actual purpose is.
It has NOTHING to do with XML or JSON serialization.
Used with the SerializableAttribute are the ISerializable Interface and SerializationInfo Class. These are also only used with the BinaryFormatter or SoapFormatter.
Unless you intend to serialize your class using Binary or Soap, do not bother marking your class as [Serializable]. XML and JSON serializers are not even aware of its existence.
you can also use this to read all the lines in the file one by one then print i
#include <iostream>
#include <fstream>
using namespace std;
bool check_file_is_empty ( ifstream& file){
return file.peek() == EOF ;
}
int main (){
string text[256];
int lineno ;
ifstream file("text.txt");
int num = 0;
while (!check_file_is_empty(file))
{
getline(file , text[num]);
num++;
}
for (int i = 0; i < num ; i++)
{
cout << "\nthis is the text in " << "line " << i+1 << " :: " << text[i] << endl ;
}
system("pause");
return 0;
}
hope this could help you :)
In Java, ==
always just compares two references (for non-primitives, that is) - i.e. it tests whether the two operands refer to the same object.
However, the equals
method can be overridden - so two distinct objects can still be equal.
For example:
String x = "hello";
String y = new String(new char[] { 'h', 'e', 'l', 'l', 'o' });
System.out.println(x == y); // false
System.out.println(x.equals(y)); // true
Additionally, it's worth being aware that any two equal string constants (primarily string literals, but also combinations of string constants via concatenation) will end up referring to the same string. For example:
String x = "hello";
String y = "he" + "llo";
System.out.println(x == y); // true!
Here x
and y
are references to the same string, because y
is a compile-time constant equal to "hello"
.
use Time::Piece;
...
my $t = localtime;
print $t->mdy("/");# 02/29/2000
Proxy support and the Host field:
HTTP 1.1 has a required Host header by spec.
HTTP 1.0 does not officially require a Host header, but it doesn't hurt to add one, and many applications (proxies) expect to see the Host header regardless of the protocol version.
Example:
GET / HTTP/1.1
Host: www.blahblahblahblah.com
This header is useful because it allows you to route a message through proxy servers, and also because your web server can distinguish between different sites on the same server.
So this means if you have blahblahlbah.com and helohelohelo.com both pointing to the same IP. Your web server can use the Host field to distinguish which site the client machine wants.
Persistent connections:
HTTP 1.1 also allows you to have persistent connections which means that you can have more than one request/response on the same HTTP connection.
In HTTP 1.0 you had to open a new connection for each request/response pair. And after each response the connection would be closed. This lead to some big efficiency problems because of TCP Slow Start.
OPTIONS method:
HTTP/1.1 introduces the OPTIONS method. An HTTP client can use this method to determine the abilities of the HTTP server. It's mostly used for Cross Origin Resource Sharing in web applications.
Caching:
HTTP 1.0 had support for caching via the header: If-Modified-Since.
HTTP 1.1 expands on the caching support a lot by using something called 'entity tag'. If 2 resources are the same, then they will have the same entity tags.
HTTP 1.1 also adds the If-Unmodified-Since, If-Match, If-None-Match conditional headers.
There are also further additions relating to caching like the Cache-Control header.
100 Continue status:
There is a new return code in HTTP/1.1 100 Continue. This is to prevent a client from sending a large request when that client is not even sure if the server can process the request, or is authorized to process the request. In this case the client sends only the headers, and the server will tell the client 100 Continue, go ahead with the body.
Much more:
Here is another way:
Browse someone's commit history (Click commits
which is next to branch to see the whole commit history)
Click the commit that with the person's username because there might be so many of them
Then you should see the web address has a hash concatenated to the URL. Add .patch
to this commit URL
You will probably see the person's email address there
Example: https://github.com/[username]/[reponame]/commit/[hash].patch
Source: Chris Herron @ Sourcecon
I faced this issue a lot when using position: absolute;
, I faced this issue by using position: relative
in the child element. don't need to change position: absolute
to relative
, just need to add in the child element look into the beneath two examples:
let toggle = document.getElementById('toggle')
toggle.addEventListener("click", () => {
toggle.classList.toggle('change');
})
_x000D_
.container {
width: 60px;
height: 22px;
background: #333;
border-radius: 20px;
position: relative;
cursor: pointer;
}
.change .slide {
transform: translateX(33px);
}
.slide {
transition: 0.5s;
width: 20px;
height: 20px;
background: #fff;
border-radius: 20px;
margin: 2px 2px;
z-index: 100;
}
.dot {
width: 10px;
height: 16px;
background: red;
position: absolute;
top: 4px;
right: 5px;
z-index: 1;
}
_x000D_
<div class="container" id="toggle">
<div class="slide"></div>
<div class="dot"></div>
</div>
_x000D_
let toggle = document.getElementById('toggle')
toggle.addEventListener("click", () => {
toggle.classList.toggle('change');
})
_x000D_
.container {
width: 60px;
height: 22px;
background: #333;
border-radius: 20px;
position: relative;
cursor: pointer;
}
.change .slide {
transform: translateX(33px);
}
.slide {
transition: 0.5s;
width: 20px;
height: 20px;
background: #fff;
border-radius: 20px;
margin: 2px 2px;
z-index: 100;
// Just add position relative;
position: relative;
}
.dot {
width: 10px;
height: 16px;
background: red;
position: absolute;
top: 4px;
right: 5px;
z-index: 1;
}
_x000D_
<div class="container" id="toggle">
<div class="slide"></div>
<div class="dot"></div>
</div>
_x000D_
You should also use the style 'color' and not 'font-color'
<?php
foreach($months as $key => $month){
if(strpos($filename,$month)!==false){
echo "<style = 'color: #ff0000;'> Movie List for {$key} 2013 </style>";
}
}
?>
In general, the comments on double and single quotes are correct in other suggestions. $Variables only execute in double quotes.
Agree with Markus' suggestion to roll your own exception, but the text of the exception should clarify that the problem is in the argument list, not the individual argument values. I'd propose:
class BadCallError(ValueError):
pass
Used when keyword arguments are missing that were required for the specific call, or argument values are individually valid but inconsistent with each other. ValueError
would still be right when a specific argument is right type but out of range.
Shouldn't this be a standard exception in Python?
In general, I'd like Python style to be a bit sharper in distinguishing bad inputs to a function (caller's fault) from bad results within the function (my fault). So there might also be a BadArgumentError to distinguish value errors in arguments from value errors in locals.
you can download USBview and get all the information you need. Along with the list of devices it will also show you the configuration of each device.
In your case removing ./ should solve the issue. I had another case wherein I was using a directory from the parent directory and docker can only access files present below the directory where Dockerfile is present so if I have a directory structure /root/dir and Dockerfile /root/dir/Dockerfile
I cannot copy do the following
COPY root/src /opt/src
This has been answered a hundred times but this solution worked the best for me and helped address the issue when new devices are introduced and I don't have a size defined.
Swift 5 Helper:
extension UIScreen {
func phoneSizeInInches() -> CGFloat {
switch (self.nativeBounds.size.height) {
case 960, 480:
return 3.5 //iPhone 4
case 1136:
return 4 //iPhone 5
case 1334:
return 4.7 //iPhone 6
case 2208:
return 5.5 //iPhone 6 Plus
case 2436:
return 5.8 //iPhone X
case 1792:
return 6.1 //iPhone XR
case 2688:
return 6.5 //iPhone XS Max
default:
let scale = self.scale
let ppi = scale * 163
let width = self.bounds.size.width * scale
let height = self.bounds.size.height * scale
let horizontal = width / ppi, vertical = height / ppi
let diagonal = sqrt(pow(horizontal, 2) + pow(vertical, 2))
return diagonal
}
}
}
This is because it's easy to memorize a phone's inch sizes, like, "5.5 inch" or "4.7 inch" device but difficult to remember the exact pixel sizes.
if UIScreen.main.phoneSizeInInches() == 4 {
//do something with only 4 inch iPhones
}
This also gives you the opportunity to do something like this:
if UIScreen.main.phoneSizeInInches() < 5.5 {
//do something on all iPhones smaller than the plus
}
The default: tries to uses the screen size and scale to try and calculate the diagonal inches. This is in case some new device size appears, it will try its best to determine and code, such as the last example, should still work.
Add the following property in pom.xml
. Make sure you use the fully qualified class name (i.e. with package name) which contains the main
method:
<properties>
<exec.mainClass>fully-qualified-class-name</exec.mainClass>
</properties>
Now from the terminal, trigger the following command:
mvn clean compile exec:java
NOTE You can pass further arguments via -Dexec.args="xxx"
flag.
Visual studio’s smart indenting does automatically indenting, but we can select a block or all the code for indentation.
Select all the code: Ctrl+a
Use either of the two ways to indentation the code:
Shift+Tab,
Ctrl+k+f.
Just want to add Matas' answer. Maybe it's obvious, but I've searched for a long time to figure out that the variable is accessible only inside the BEGIN-END construction, so if you need to use it in some code later, you need to put this code inside the BEGIN-END block.
Note that these blocks can be nested:
DECLARE x NUMBER;
BEGIN
SELECT PK INTO x FROM table1 WHERE col1 = 'test';
DECLARE y NUMBER;
BEGIN
SELECT PK INTO y FROM table2 WHERE col2 = x;
INSERT INTO table2 (col1, col2)
SELECT y,'text'
FROM dual
WHERE exists(SELECT * FROM table2);
COMMIT;
END;
END;
run command prompt as administrator and use '--user' flag eg. pip install --user --upgrade pandas
You Could try the other format for the case statement
CASE WHEN Product.type_id = 10
THEN
(
Select Statement
)
ELSE
(
Other select statement
)
END
FROM Product
WHERE Product.product_id = $pid
See http://msdn.microsoft.com/en-us/library/ms181765.aspx for more information.
in the folder where the build.xml resides run command only -
ant
and not the command - `
ant build.xml
`
. if you are using the ant file as build xml then the below steps helps you Steps : open cmd Prompt >> switch to the project location >>type ant and click enter key
For me it was enough to reinstall whitelist plugin:
cordova plugin remove cordova-plugin-whitelist
and then
cordova plugin add cordova-plugin-whitelist
It looks like updating from previous versions of Cordova was not succesful.
Yes you need javascript. The simplest way is to just put this at the bottom of your HTML page:
<script type="text/javascript">
alert("Hello world");
</script>
There are more preferred methods, like using jQuery's ready function, but this method will work.
I created different versions of how to reverse a string in python in my repo: https://github.com/fedmich/Python-Codes/tree/master/Reverse%20a%20String
You can do it by using list-comprehension or lambda technique:
# Reverse a string without using reverse() function
s = 'Federico';
li = list( s ) #convert string to list
ret = [ li[i-1] for i in xrange(len(li),0,-1) ] #1 liner lambda
print ( "".join( ret ) )
or by doing a backward for loop
# Reverse a string without using reverse() function
s = 'Federico';
r = []
length = len(s)
for i in xrange(length,0,-1):
r.append( s[ i - 1] )
print ( "".join(r) )
If you don't have access to a subfolder inside the directory tree, Directory.GetFiles stops and throws the exception resulting in a null value in the receiving string[].
Here, see this answer https://stackoverflow.com/a/38959208/6310707
It manages the exception inside the loop and keep on working untill the entire folder is traversed.
Quite simply, a "callable" is something that can be called like a method. The built in function "callable()" will tell you whether something appears to be callable, as will checking for a call property. Functions are callable as are classes, class instances can be callable. See more about this here and here.
Here is an example of how you could do this. Note that I was inspired by a comment in the ng-repeat docs: http://jsfiddle.net/digitalzebra/wnWY6/
Note the ng-repeat directive:
<div ng-app>
<div ng-controller="TestCtrl">
<div ng-repeat="a in range(5) track by $index">{{$index + 1}}</div>
</div>
</div>
Here is the controller:
function TestCtrl($scope) {
$scope.range = function(n) {
return new Array(n);
};
};
I would suggest using CSS Modules:
React
import React from 'react';
import styles from './table.css';
export default class Table extends React.Component {
render () {
return <div className={styles.table}>
<div className={styles.row}>
<div className={styles.cell}>A0</div>
<div className={styles.cell}>B0</div>
</div>
</div>;
}
}
Rendering the Component:
<div class="table__table___32osj">
<div class="table__row___2w27N">
<div class="table__cell___2w27N">A0</div>
<div class="table__cell___1oVw5">B0</div>
</div>
</div>
It sounds like you can pick and choose. If you pick float, you may lose 11 digits of precision. If that's acceptable, go for it -- apparently the Linq designers thought this to be a good tradeoff.
However, if your application needs those extra digits, use decimal. Decimal (implemented correctly) is way more accurate than a float anyway -- no messy translation from base 10 to base 2 and back.
import ImageGrab
img = ImageGrab.grab()
img.save('test.jpg','JPEG')
this requires Python Imaging Library
I've noticed that if I put a shortcut on my desktop on one screen the launched application may appear on that screen (if that app doesn't reposition itself).
This also applies to running things from Windows Explorer - if Explorer is on one screen the launched application will pick that monitor to use.
Again - I think this is when the launching application specifies the default (windows managed) position. Most applications seem to override this default behavior in some way.
A simple window created like so will do this:
hWnd = CreateWindow(windowClass, windowTitle, WS_VISIBLE | WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, SW_SHOW, CW_USEDEFAULT, 0, NULL, NULL, hInst, NULL);
As dfsq said i just had to use removeClass("hide")
instead of toggle()
I experienced a similar issue. None of the suggestions above helped me, though.
Eventually I realized that the Wordpress MySQL-user on my production environment had not been assigned sufficient privileges.
If trying to build phpredis
on a Linux box you might need to give it time to complete modifying the file permissions, with a sleep
command, before running the file:
chmod a+x /usr/bin/php/scripts/phpize \
&& sleep 1 \
&& /usr/bin/php/scripts/phpize
I have a situation which in the Unit test. I copied the app.config file to the unit test project. So the unit test project also contains endpoint information.
For file Type you can rely on FileExtentions and for writing it to disk you can use BinaryWriter. or a FileStream.
Example (Assuming you already have a stream):
FileStream fileStream = File.Create(fileFullPath, (int)stream.Length);
// Initialize the bytes array with the stream length and then fill it with data
byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, bytesInStream.Length);
// Use write method to write to the file specified above
fileStream.Write(bytesInStream, 0, bytesInStream.Length);
//Close the filestream
fileStream.Close();
Application Verifier combined with Debugging Tools for Windows is an amazing setup. You can get both as a part of the Windows Driver Kit or the lighter Windows SDK. (Found out about Application Verifier when researching an earlier question about a heap corruption issue.) I've used BoundsChecker and Insure++ (mentioned in other answers) in the past too, although I was surprised how much functionality was in Application Verifier.
Electric Fence (aka "efence"), dmalloc, valgrind, and so forth are all worth mentioning, but most of these are much easier to get running under *nix than Windows. Valgrind is ridiculously flexible: I've debugged large server software with many heap issues using it.
When all else fails, you can provide your own global operator new/delete and malloc/calloc/realloc overloads -- how to do so will vary a bit depending on compiler and platform -- and this will be a bit of an investment -- but it may pay off over the long run. The desirable feature list should look familiar from dmalloc and electricfence, and the surprisingly excellent book Writing Solid Code:
Note that in our local homebrew system (for an embedded target) we keep the tracking separate from most of the other stuff, because the run-time overhead is much higher.
If you're interested in more reasons to overload these allocation functions/operators, take a look at my answer to "Any reason to overload global operator new and delete?"; shameless self-promotion aside, it lists other techniques that are helpful in tracking heap corruption errors, as well as other applicable tools.
Because I keep finding my own answer here when searching for alloc/free/fence values MS uses, here's another answer that covers Microsoft dbgheap fill values.
Add them to a static map inside (this.getClass().getName()) the parent classes constructor (or create a default one) but this will get updated in runtime. If lazy initialization is an option you can try this approach.
As I found the best way is doing is preloading a stylesheet that contains the font face, and then let browser to load it automatically. I used the font-face in other locations (in the html page), but then I could observe the font changing effect briefly.
<link href="fonts.css?family=Open+Sans" rel="preload stylesheet" as="style">
then in the font.css file, specify as following.
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans Regular'), local('OpenSans-Regular'),
url('open-sans-v16-latin-regular.woff2') format('woff2'); /* Super Modern Browsers */
}
You can't assign a name to fonts when it's preloaded through link tag (correct me if I was wrong I couldn't find a way yet), and thus you have to use font-face to assign the name to the font. Even though it's possible to load a font through link tag, it's not recommended as you can't assign a name to the font with it. Without a name as with font-face, you won't be able to use it anywhere in the web page. According to gtmetrix, style sheet loads at the beginning, then rest of the scripts/style by order, then the font before dom is loaded, and therefore you don't see font changing effect.
When would you use Session Beans or Message Driven Beans ?
How are transactions handled in session beans ?
What is the difference between local and remote session beans ? This question is more about knowing that RPCs are in the picture or not, since a method that is exposed as both Local or Remote might still work differently (side-effects on parameters are possible with Locals, while not possible with Remotes).
A good test is: never ask the questions in the same order. We had the experience with offshoring that sometimes they were actually giving the response in the wrong order :-). As a result you should make sure that you can actually see the person you are interrogating.
Thanks for the answers. Now I know that there are two ways of "SAVE AS" in Vim.
Assumed that I'm editing hello.txt.
In practice, the + symbol is placed directly in the conditional statement and on the side of the optional table (the one which is allowed to contain empty or null values within the conditional).
Try
string reversed(temp.rbegin(), temp.rend());
EDIT: Elaborating as requested.
string::rbegin()
and string::rend()
, which stand for "reverse begin" and "reverse end" respectively, return reverse iterators into the string. These are objects supporting the standard iterator interface (operator*
to dereference to an element, i.e. a character of the string, and operator++
to advance to the "next" element), such that rbegin()
points to the last character of the string, rend()
points to the first one, and advancing the iterator moves it to the previous character (this is what makes it a reverse iterator).
Finally, the constructor we are passing these iterators into is a string constructor of the form:
template <typename Iterator>
string(Iterator first, Iterator last);
which accepts a pair of iterators of any type denoting a range of characters, and initializes the string to that range of characters.
import React from 'react'
import ReactDOM from 'react-dom'
class Doc extends React.Component{
componentDidMount(){
document.title = "dfsdfsdfsd"
}
render(){
return(
<b> test </b>
)
}
}
ReactDOM.render(
<Doc />,
document.getElementById('container')
);
This works for me.
Edit: If you're using webpack-dev-server set inline to true
You have to do the following:
if "%1" == "" (
echo The variable is empty
) ELSE (
echo The variable contains %1
)
an array does not contain index when elements are associative. An array in php can contain mixed values like this:
$var = array("apple", "banana", "foo" => "grape", "carrot", "bar" => "donkey");
print_r($var);
Gives you:
Array
(
[0] => apple
[1] => banana
[foo] => grape
[2] => carrot
[bar] => donkey
)
What are you trying to achieve since you need the index value in an associative array?
This command (as suggested already by @Naftuli Tzvi Kay):
git format-patch -1 HEAD
Replace HEAD
with specific hash or range.
will generate the patch file for the latest commit formatted to resemble UNIX mailbox format.
-<n>
- Prepare patches from the topmost commits.
Then you can re-apply the patch file in a mailbox format by:
git am -3k 001*.patch
See: man git-format-patch
.
Show everything including dir itself but not its long boring contents:
find . -print -name dir -prune
One of The Shortest method i found for single value while i was searching for myself, is just passing single string and setting string as model in view like this.
In your Partial calling side
@Html.Partial("ParitalAction", "String data to pass to partial")
And then binding the model with Partial View like this
@model string
and the using its value in Partial View like this
@Model
You can also play with other datatypes like array, int or more complex data types like IDictionary or something else.
Hope it helps,
You might want this (edit: allow number of the form 0123
):
^\\+?[1-9]$|^\\+?\d+$
however, if it were me, I would instead do
int x = Integer.parseInt(s)
if (x > 0) {...}
I think this might be helpful:
In case of adding new rows for array in loop, Assign the array directly for firsttime in loop instead of initialising an empty array.
for i in range(0,len(0,100)):
SOMECALCULATEDARRAY = .......
if(i==0):
finalArrayCollection = SOMECALCULATEDARRAY
else:
finalArrayCollection = np.vstack(finalArrayCollection,SOMECALCULATEDARRAY)
This is mainly useful when the shape of the array is unknown
find . -name "file_*" -follow -type f -print0 | xargs -0 zcat | agrep -dEOE 'grep'
You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:
/**
* Used to stitch together functional operators into a chain.
* @method pipe
* @return {Observable} the Observable result of all of the operators having
* been called in the order they were passed in.
*
* @example
*
* import { map, filter, scan } from 'rxjs/operators';
*
* Rx.Observable.interval(1000)
* .pipe(
* filter(x => x % 2 === 0),
* map(x => x + x),
* scan((acc, x) => acc + x)
* )
* .subscribe(x => console.log(x))
*/
Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan()
, but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe()
to make a chain of those operators (see example above).
Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do()
. You can think of it as if observable was an array over time, then tap()
would be an equivalent to Array.forEach()
.
The window object represents an open window in a browser. Since you are not running your code within a browser, but via Windows Script Host, the interpreter won't be able to find the window object, since it does not exist, since you're not within a web browser.
If you're modifying your class to accept a Stream instead of a filename, don't bother converting to a MemoryStream. Let the underlying Stream handle the operations:
public class MyClass
{
Stream _s;
public MyClass(Stream s) { _s = s; }
}
But if you really need a MemoryStream for internal operations, you'll have to copy the data out of the source Stream into the MemoryStream:
public MyClass(Stream stream)
{
_ms = new MemoryStream();
CopyStream(stream, _ms);
}
// Merged From linked CopyStream below and Jon Skeet's ReadFully example
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[16*1024];
int read;
while((read = input.Read (buffer, 0, buffer.Length)) > 0)
{
output.Write (buffer, 0, read);
}
}
Yet another option, useful is you want to select also the pages inside the documents to be merged:
pdfjoin image.jpg '-' doc_only_first_pages.pdf '1,2' doc_with_all_pages.pdf '-'
It comes with package texlive-extra-utils
Actually, I solved the problem. I run it by eclipse jetty plugin.
I didn't have the JDK lib in my eclipse, that's why the message keep showing that I need the full JDK installed, that's the main reason.
I installed two versions of jetty plugin, wich is jetty7 and jetty8. I think they conflict with each other or something, so I removed the jetty7, and it works!
If you want to use only text while making swipe actions then you can use iOS default swipe actions but if you want image and text, then you have to customize it. I have found a great tutorial and sample that can resolve this problem.
Try out this repository to get the custom swipe cell. You can add multiple option here.
http://iosbucket.blogspot.in/2016/04/custom-swipe-table-view-cell_16.html
If you have date in DateTime
variable then its a DateTime
object and doesn't contain any format. Formatted date are expressed as string
when you call DateTime.ToString
method and provide format in it.
Lets say you have two DateTime
variable, you can use the compare method for comparision,
DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 2, 0, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;
if (result < 0)
relationship = "is earlier than";
else if (result == 0)
relationship = "is the same time as";
else
relationship = "is later than";
Code snippet taken from msdn.
I improved with one check iteration the good code of Hors Sujet to avoid including folders in the result array:
function getDirContents($dir, &$results = array()){ $files = scandir($dir); foreach($files as $key => $value){ $path = realpath($dir.DIRECTORY_SEPARATOR.$value); if(is_dir($path) == false) { $results[] = $path; } else if($value != "." && $value != "..") { getDirContents($path, $results); if(is_dir($path) == false) { $results[] = $path; } } } return $results; }
Spring security is a filter based framework, it plants a WALL(HttpFireWall) before your application in terms of proxy filters or spring managed beans. Your request has to pass through multiple filters to reach your API.
WebAsyncManagerIntegrationFilter
Provides integration between the SecurityContext and Spring Web's WebAsyncManager.
SecurityContextPersistenceFilter
This filter will only execute once per request, Populates the SecurityContextHolder with information obtained from the configured SecurityContextRepository prior to the request and stores it back in the repository once the request has completed and clearing the context holder.
Request is checked for existing session. If new request, SecurityContext will be created else if request has session then existing security-context will be obtained from respository.
HeaderWriterFilter
Filter implementation to add headers to the current response.
LogoutFilter
If request url is /logout
(for default configuration) or if request url mathces RequestMatcher
configured in LogoutConfigurer
then
LogoutConfigurer
/
or logout success url configured or invokes logoutSuccessHandler configured.UsernamePasswordAuthenticationFilter
HTTP POST
) default /login
or matches .loginProcessingUrl()
configured in FormLoginConfigurer
then UsernamePasswordAuthenticationFilter
attempts authentication.usernameParameter(String)
, passwordParameter(String)
..loginPage()
overrides defaults Authentication
object(UsernamePasswordAuthenticationToken
or any implementation of Authentication
in case of your custom auth filter) is created. authenticationManager.authenticate(authToken)
will be invokedAuthenticationProvider
authenticate method tries all auth providers and checks any of the auth provider supports
authToken/authentication object, supporting auth provider will be used for authenticating. and returns Authentication object in case of successful authentication else throws AuthenticationException
.authenticationSuccessHandler
will be invoked which redirects to the target url configured(default is /
)SecurityContextHolderAwareRequestFilter
, if you are using it to install a Spring Security aware HttpServletRequestWrapper into your servlet container
AnonymousAuthenticationFilter
Detects if there is no Authentication object in the SecurityContextHolder, if no authentication object found, creates Authentication
object (AnonymousAuthenticationToken
) with granted authority ROLE_ANONYMOUS
. Here AnonymousAuthenticationToken
facilitates identifying un-authenticated users subsequent requests.
DEBUG - /app/admin/app-config at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
DEBUG - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@aeef7b36: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
ExceptionTranslationFilter
, to catch any Spring Security exceptions so that either an HTTP error response can be returned or an appropriate AuthenticationEntryPoint can be launched
FilterSecurityInterceptor
There will be FilterSecurityInterceptor
which comes almost last in the filter chain which gets Authentication object from SecurityContext
and gets granted authorities list(roles granted) and it will make a decision whether to allow this request to reach the requested resource or not, decision is made by matching with the allowed AntMatchers
configured in HttpSecurityConfiguration
.
Consider the exceptions 401-UnAuthorized and 403-Forbidden. These decisions will be done at the last in the filter chain
Note: User Request flows not only in above mentioned filters, but there are others filters too not shown here.(ConcurrentSessionFilter
,RequestCacheAwareFilter
,SessionManagementFilter
...)
It will be different when you use your custom auth filter instead of UsernamePasswordAuthenticationFilter
.
It will be different if you configure JWT auth filter and omit .formLogin() i.e, UsernamePasswordAuthenticationFilter
it will become entirely different case.
From Documentation ordering of filters is given as
- ChannelProcessingFilter
- ConcurrentSessionFilter
- SecurityContextPersistenceFilter
- LogoutFilter
- X509AuthenticationFilter
- AbstractPreAuthenticatedProcessingFilter
- CasAuthenticationFilter
- UsernamePasswordAuthenticationFilter
- ConcurrentSessionFilter
- OpenIDAuthenticationFilter
- DefaultLoginPageGeneratingFilter
- DefaultLogoutPageGeneratingFilter
- ConcurrentSessionFilter
- DigestAuthenticationFilter
- BearerTokenAuthenticationFilter
- BasicAuthenticationFilter
- RequestCacheAwareFilter
- SecurityContextHolderAwareRequestFilter
- JaasApiIntegrationFilter
- RememberMeAuthenticationFilter
- AnonymousAuthenticationFilter
- SessionManagementFilter
- ExceptionTranslationFilter
- FilterSecurityInterceptor
- SwitchUserFilter
You can also refer
most common way to authenticate a modern web app?
difference between authentication and authorization in context of Spring Security?
Here a way to create custom rows directly with MySQL request SELECT
:
SELECT ALL *
FROM (
VALUES
ROW (1, 2, 3),
ROW (4, 5, 6),
ROW (7, 8, 9)
) AS dummy (c1, c2, c3)
Gives us a table dummy
:
c1 c2 c3
-------------
1 2 3
4 5 6
7 8 9
Tested with MySQL 8
There is no need to add a listener to the ?android:attr/ratingBarStyleSmall
. Just add
android:isIndicator=false
and it will capture click events, e.g.
<RatingBar
android:id="@+id/myRatingBar"
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numStars="5"
android:isIndicator="false" />
nohup
catches the hangup signal (see man 7 signal
) while the ampersand doesn't (except the shell is confgured that way or doesn't send SIGHUP
at all).
Normally, when running a command using &
and exiting the shell afterwards, the shell will terminate the sub-command with the hangup signal (kill -SIGHUP <pid>
). This can be prevented using nohup
, as it catches the signal and ignores it so that it never reaches the actual application.
In case you're using bash, you can use the command shopt | grep hupon
to find out whether
your shell sends SIGHUP to its child processes or not. If it is off, processes won't be
terminated, as it seems to be the case for you. More information on how bash terminates
applications can be found here.
There are cases where nohup
does not work, for example when the process you start reconnects
the SIGHUP
signal, as it is the case here.
To make the query run faster in big tables where not every line needs to be updated, you can also choose to only update rows that will be modified:
UPDATE dbo.xxx
SET Value = REPLACE(Value, '123', '')
WHERE ID <= 4
AND Value LIKE '%123%'
Use google guava libs to handle is-null-check (deamon's update)
Drawable drawable = Optional.of(Common.getDrawableFromUrl(this, product.getMapPath())).or(getRandomDrawable());
A few comments:
analog=True
in the call to butter
, and you should use scipy.signal.freqz
(not freqs
) to generate the frequency response.Here's my modified version of your script, followed by the plot that it generates.
import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt
def butter_lowpass(cutoff, fs, order=5):
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = butter(order, normal_cutoff, btype='low', analog=False)
return b, a
def butter_lowpass_filter(data, cutoff, fs, order=5):
b, a = butter_lowpass(cutoff, fs, order=order)
y = lfilter(b, a, data)
return y
# Filter requirements.
order = 6
fs = 30.0 # sample rate, Hz
cutoff = 3.667 # desired cutoff frequency of the filter, Hz
# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)
# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()
# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0 # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data. We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)
# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)
plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()
plt.subplots_adjust(hspace=0.35)
plt.show()
See the (quite) recent answer on the matplotlib repository, in which the following solution is suggested:
If you want to set the xticklabels:
ax.set_xticks([1,4,5])
ax.set_xticklabels([1,4,5], fontsize=12)
If you want to only increase the fontsize of the xticklabels, using the default values and locations (which is something I personally often need and find very handy):
ax.tick_params(axis="x", labelsize=12)
To do it all at once:
plt.setp(ax.get_xticklabels(), fontsize=12, fontweight="bold",
horizontalalignment="left")`
your elemId
as its name suggests, is an Id
attribute, these are all you can do to check if it exists:
Vanilla JavaScript: in case you have more advanced selectors:
//you can use it for more advanced selectors
if(document.querySelectorAll("#elemId").length){}
if(document.querySelector("#elemId")){}
//you can use it if your selector has only an Id attribute
if(document.getElementById("elemId")){}
jQuery:
if(jQuery("#elemId").length){}