How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?
I had the error when using gpg-agent as my ssh-agent and using a gpg subkey as my ssh key https://wiki.archlinux.org/index.php/GnuPG#gpg-agent.
I suspect that the problem was caused by having an invalid pin entry tty for gpg caused by my sleep+lock command used in my sway config
bindsym $mod+Shift+l exec "sh -c 'gpg-connect-agent reloadagent /bye>/dev/null; systemctl suspend; swaylock'"
or just the sleep/suspend
Reset the pin entry tty to fix the problem
gpg-connect-agent updatestartuptty /bye > /dev/null
and the fix for my sway sleep+lock command:
bindsym $mod+Shift+l exec "sh -c 'gpg-connect-agent reloadagent /bye>/dev/null; systemctl suspend; swaylock; gpg-connect-agent updatestartuptty /bye > /dev/null'"
Why is "npm install" really slow?
I had similar problems. I was also confused by some solutions leaving me with different versions displaying for different users.
If you have any problems at all, I would first check every account your using any implementation of node
Finally, this solution appears to solve this issue 100%, giving me the confidence that my versions were universal no matter what user privileges I wanted to use:
sudo yum update
sudo yum install build-essential checkinstall libssl-dev
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.35.1/install.sh | bash
(sudo) nvm --version
(sudo) nvm ls-remote
(sudo) nvm install [version.number]
1
If you're still having a problem, next try looking inside your /usr/local/bin directory. If you find either a large binary document named node or a folder named npm, delete them.
rm /usr/local/bin/node
rm -r /usr/local/bin/npm
Personally, before I deleted those, two of my user accounts were using the latest version of node/npm installed correctly via nvm, while a third account of mine remained stubborn by still using a far older installation of both node and npm apparently located inside my /usr/local/bin/ directory. As soon as I deleted both of them with the two above commands, that problematic user account implicitly began running the correct installation, having all three accounts mutually the intended versions.
(Implemented while using Centos 7 Blank x64. Some source code used above was originally supplied by 'phoenixNAP Global IT services' 1)
Invalid http_host header
The error log is straightforward. As it suggested,You need to add 198.211.99.20 to your ALLOWED_HOSTS
setting.
In your project settings.py file,set ALLOWED_HOSTS
like this :
ALLOWED_HOSTS = ['198.211.99.20', 'localhost', '127.0.0.1']
For further reading
read from here.
gpg failed to sign the data fatal: failed to write commit object [Git 2.10.0]
To anybody who is facing this issue on MacOS machines, try this:
brew uninstall gpg
brew install gpg2
brew install pinentry-mac
(if needed)
gpg --full-generate-key
Create a key by using an algorithm.
- Get generated key by executing:
gpg --list-keys
- Set the key here
git config --global user.signingkey <Key from your list>
git config --global gpg.program /usr/local/bin/gpg
git config --global commit.gpgsign true
- If you want to export your Key to GitHub then:
gpg --armor --export <key>
and add this key to GitHub at GPG keys: https://github.com/settings/keys (with START and END line included)
If the issue still exists:
test -r ~/.bash_profile && echo 'export GPG_TTY=$(tty)' >> ~/.bash_profile
echo 'export GPG_TTY=$(tty)' >> ~/.profile
If the issue still exists:
Install https://gpgtools.org and sign the key that you used by pressing Sign from the menu bar: Key->Sign
If the issue still exists:
Go to: ??your global .gitconfig
file which in my case is at: ??/Users/gent/.gitconfig
And modify the .gitconfig file (please make sure Email and Name are the same with the one that you have created while generating the Key):
_x000D_
_x000D_
[user]_x000D_
email = [email protected]_x000D_
name = Gent_x000D_
signingkey = <YOURKEY>_x000D_
[gpg]_x000D_
program = /usr/local/bin/gpg_x000D_
[commit]_x000D_
gpsign = true_x000D_
gpgsign = true_x000D_
[filter "lfs"]_x000D_
process = git-lfs filter-process_x000D_
required = true_x000D_
clean = git-lfs clean -- %f_x000D_
smudge = git-lfs smudge -- %f_x000D_
[credential]_x000D_
helper = osxkeychain
_x000D_
_x000D_
_x000D_
Verify host key with pysftp
Cook book to use different ways of pysftp.CnOpts() and hostkeys options.
Source : https://pysftp.readthedocs.io/en/release_0.2.9/cookbook.html
Host Key checking is enabled by default. It will use ~/.ssh/known_hosts by default. If you wish to disable host key checking (NOT ADVISED) you will need to modify the default CnOpts and set the .hostkeys to None.
import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
with pysftp.Connection('host', username='me', password='pass', cnopts=cnopts):
# do stuff here
To use a completely different known_hosts file, you can override CnOpts looking for ~/.ssh/known_hosts by specifying the file when instantiating.
import pysftp
cnopts = pysftp.CnOpts(knownhosts='path/to/your/knownhostsfile')
with pysftp.Connection('host', username='me', password='pass', cnopts=cnopts):
# do stuff here
If you wish to use ~/.ssh/known_hosts but add additional known host keys you can merge with update additional known_host format files by using .load method.
import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys.load('path/to/your/extra_knownhosts')
with pysftp.Connection('host', username='me', password='pass', cnopts=cnopts):
# do stuff here
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'
Your DemoApplication
class is in the com.ag.digital.demo.boot
package and your LoginBean
class is in the com.ag.digital.demo.bean
package. By default components (classes annotated with @Component
) are found if they are in the same package or a sub-package of your main application class DemoApplication
. This means that LoginBean
isn't being found so dependency injection fails.
There are a couple of ways to solve your problem:
- Move
LoginBean
into com.ag.digital.demo.boot
or a sub-package.
- Configure the packages that are scanned for components using the
scanBasePackages
attribute of @SpringBootApplication
that should be on DemoApplication
.
A few of other things that aren't causing a problem, but are not quite right with the code you've posted:
@Service
is a specialisation of @Component
so you don't need both on LoginBean
- Similarly,
@RestController
is a specialisation of @Component
so you don't need both on DemoRestController
DemoRestController
is an unusual place for @EnableAutoConfiguration
. That annotation is typically found on your main application class (DemoApplication
) either directly or via @SpringBootApplication
which is a combination of @ComponentScan
, @Configuration
, and @EnableAutoConfiguration
.
How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption
This message can also occur when you specify the incorrect decryption password (yeah, lame, but not quite obvious to realize this from the error message, huh?).
I was using the command line to decrypt the recent DataBase backup for my auxiliary tool and suddenly faced this issue.
Finally, after 10 mins of grief and plus reading through this question/answers I have remembered that the password is different and everything worked just fine with the correct password.
Bootstrap - How to add a logo to navbar class?
Use a image style width and height 100% . This will do the trick, because the image can be resized based on the container.
Example:
<a class="navbar-brand" href="#" style="padding: 4px;margin:auto"> <img src="images/logo.png" style="height:100%;width: auto;" title="mycompanylogo"></a>
How to configure Docker port mapping to use Nginx as an upstream proxy?
@T0xicCode's answer is correct, but I thought I would expand on the details since it actually took me about 20 hours to finally get a working solution implemented.
If you're looking to run Nginx in its own container and use it as a reverse proxy to load balance multiple applications on the same server instance then the steps you need to follow are as such:
Link Your Containers
When you docker run
your containers, typically by inputting a shell script into User Data
, you can declare links to any other running containers. This means that you need to start your containers up in order and only the latter containers can link to the former ones. Like so:
#!/bin/bash
sudo docker run -p 3000:3000 --name API mydockerhub/api
sudo docker run -p 3001:3001 --link API:API --name App mydockerhub/app
sudo docker run -p 80:80 -p 443:443 --link API:API --link App:App --name Nginx mydockerhub/nginx
So in this example, the API
container isn't linked to any others, but the
App
container is linked to API
and Nginx
is linked to both API
and App
.
The result of this is changes to the env
vars and the /etc/hosts
files that reside within the API
and App
containers. The results look like so:
/etc/hosts
Running cat /etc/hosts
within your Nginx
container will produce the following:
172.17.0.5 0fd9a40ab5ec
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.3 App
172.17.0.2 API
ENV Vars
Running env
within your Nginx
container will produce the following:
API_PORT=tcp://172.17.0.2:3000
API_PORT_3000_TCP_PROTO=tcp
API_PORT_3000_TCP_PORT=3000
API_PORT_3000_TCP_ADDR=172.17.0.2
APP_PORT=tcp://172.17.0.3:3001
APP_PORT_3001_TCP_PROTO=tcp
APP_PORT_3001_TCP_PORT=3001
APP_PORT_3001_TCP_ADDR=172.17.0.3
I've truncated many of the actual vars, but the above are the key values you need to proxy traffic to your containers.
To obtain a shell to run the above commands within a running container, use the following:
sudo docker exec -i -t Nginx bash
You can see that you now have both /etc/hosts
file entries and env
vars that contain the local IP address for any of the containers that were linked. So far as I can tell, this is all that happens when you run containers with link options declared. But you can now use this information to configure nginx
within your Nginx
container.
Configuring Nginx
This is where it gets a little tricky, and there's a couple of options. You can choose to configure your sites to point to an entry in the /etc/hosts
file that docker
created, or you can utilize the ENV
vars and run a string replacement (I used sed
) on your nginx.conf
and any other conf files that may be in your /etc/nginx/sites-enabled
folder to insert the IP values.
OPTION A: Configure Nginx Using ENV Vars
This is the option that I went with because I couldn't get the
/etc/hosts
file option to work. I'll be trying Option B soon enough
and update this post with any findings.
The key difference between this option and using the /etc/hosts
file option is how you write your Dockerfile
to use a shell script as the CMD
argument, which in turn handles the string replacement to copy the IP values from ENV
to your conf file(s).
Here's the set of configuration files I ended up with:
Dockerfile
FROM ubuntu:14.04
MAINTAINER Your Name <[email protected]>
RUN apt-get update && apt-get install -y nano htop git nginx
ADD nginx.conf /etc/nginx/nginx.conf
ADD api.myapp.conf /etc/nginx/sites-enabled/api.myapp.conf
ADD app.myapp.conf /etc/nginx/sites-enabled/app.myapp.conf
ADD Nginx-Startup.sh /etc/nginx/Nginx-Startup.sh
EXPOSE 80 443
CMD ["/bin/bash","/etc/nginx/Nginx-Startup.sh"]
nginx.conf
daemon off;
user www-data;
pid /var/run/nginx.pid;
worker_processes 1;
events {
worker_connections 1024;
}
http {
# Basic Settings
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 33;
types_hash_max_size 2048;
server_tokens off;
server_names_hash_bucket_size 64;
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Logging Settings
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
# Gzip Settings
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 3;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain text/xml text/css application/x-javascript application/json;
gzip_disable "MSIE [1-6]\.(?!.*SV1)";
# Virtual Host Configs
include /etc/nginx/sites-enabled/*;
# Error Page Config
#error_page 403 404 500 502 /srv/Splash;
}
NOTE: It's important to include daemon off;
in your nginx.conf
file to ensure that your container doesn't exit immediately after launching.
api.myapp.conf
upstream api_upstream{
server APP_IP:3000;
}
server {
listen 80;
server_name api.myapp.com;
return 301 https://api.myapp.com/$request_uri;
}
server {
listen 443;
server_name api.myapp.com;
location / {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
proxy_pass http://api_upstream;
}
}
Nginx-Startup.sh
#!/bin/bash
sed -i 's/APP_IP/'"$API_PORT_3000_TCP_ADDR"'/g' /etc/nginx/sites-enabled/api.myapp.com
sed -i 's/APP_IP/'"$APP_PORT_3001_TCP_ADDR"'/g' /etc/nginx/sites-enabled/app.myapp.com
service nginx start
I'll leave it up to you to do your homework about most of the contents of nginx.conf
and api.myapp.conf
.
The magic happens in Nginx-Startup.sh
where we use sed
to do string replacement on the APP_IP
placeholder that we've written into the upstream
block of our api.myapp.conf
and app.myapp.conf
files.
This ask.ubuntu.com question explains it very nicely:
Find and replace text within a file using commands
GOTCHA
On OSX, sed
handles options differently, the -i
flag specifically.
On Ubuntu, the -i
flag will handle the replacement 'in place'; it
will open the file, change the text, and then 'save over' the same
file.
On OSX, the -i
flag requires the file extension you'd like the resulting file to have. If you're working with a file that has no extension you must input '' as the value for the -i
flag.
GOTCHA
To use ENV vars within the regex that sed
uses to find the string you want to replace you need to wrap the var within double-quotes. So the correct, albeit wonky-looking, syntax is as above.
So docker has launched our container and triggered the Nginx-Startup.sh
script to run, which has used sed
to change the value APP_IP
to the corresponding ENV
variable we provided in the sed
command. We now have conf files within our /etc/nginx/sites-enabled
directory that have the IP addresses from the ENV
vars that docker set when starting up the container. Within your api.myapp.conf
file you'll see the upstream
block has changed to this:
upstream api_upstream{
server 172.0.0.2:3000;
}
The IP address you see may be different, but I've noticed that it's usually 172.0.0.x
.
You should now have everything routing appropriately.
GOTCHA
You cannot restart/rerun any containers once you've run the initial instance launch. Docker provides each container with a new IP upon launch and does not seem to re-use any that its used before. So api.myapp.com
will get 172.0.0.2 the first time, but then get 172.0.0.4 the next time. But Nginx
will have already set the first IP into its conf files, or in its /etc/hosts
file, so it won't be able to determine the new IP for api.myapp.com
. The solution to this is likely to use CoreOS
and its etcd
service which, in my limited understanding, acts like a shared ENV
for all machines registered into the same CoreOS
cluster. This is the next toy I'm going to play with setting up.
OPTION B: Use /etc/hosts
File Entries
This should be the quicker, easier way of doing this, but I couldn't get it to work. Ostensibly you just input the value of the /etc/hosts
entry into your api.myapp.conf
and app.myapp.conf
files, but I couldn't get this method to work.
UPDATE:
See @Wes Tod's answer for instructions on how to make this method work.
Here's the attempt that I made in api.myapp.conf
:
upstream api_upstream{
server API:3000;
}
Considering that there's an entry in my /etc/hosts
file like so: 172.0.0.2 API
I figured it would just pull in the value, but it doesn't seem to be.
I also had a couple of ancillary issues with my Elastic Load Balancer
sourcing from all AZ's so that may have been the issue when I tried this route. Instead I had to learn how to handle replacing strings in Linux, so that was fun. I'll give this a try in a while and see how it goes.
Nginx serves .php files as downloads, instead of executing them
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
root /var/www/html;
index index.php index.html index.htm;
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.2-fpm.sock;
}
}
The above snippets worked for me in case of php7.2
JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images
I am using mixed solution (php+css).
Containers are needed for:
div.imgCont2
container needed to rotate;
div.imgCont1
container needed to zoomOut - width:150%
;
div.imgCont
container needed for scrollbars, when image is zoomOut.
.
<?php
$image_url = 'your image url.jpg';
$exif = @exif_read_data($image_url,0,true);
$orientation = @$exif['IFD0']['Orientation'];
?>
<style>
.imgCont{
width:100%;
overflow:auto;
}
.imgCont2[data-orientation="8"]{
transform:rotate(270deg);
margin:15% 0;
}
.imgCont2[data-orientation="6"]{
transform:rotate(90deg);
margin:15% 0;
}
.imgCont2[data-orientation="3"]{
transform:rotate(180deg);
}
img{
width:100%;
}
</style>
<div class="imgCont">
<div class="imgCont1">
<div class="imgCont2" data-orientation="<?php echo($orientation) ?>">
<img src="<?php echo($image_url) ?>">
</div>
</div>
</div>
How does `scp` differ from `rsync`?
The major difference between these tools is how they copy files.
scp
basically reads the source file and writes it to the destination. It performs a plain linear copy, locally, or over a network.
rsync
also copies files locally or over a network. But it employs a special delta transfer algorithm and a few optimizations to make the operation a lot faster. Consider the call.
rsync A host:B
rsync
will check files sizes and modification timestamps of both A and B, and skip any further processing if they match.
If the destination file B already exists, the delta transfer algorithm will make sure only differences between A and B are sent over the wire.
rsync
will write data to a temporary file T, and then replace the destination file B with T to make the update look "atomic" to processes that might be using B.
Another difference between them concerns invocation. rsync
has a plethora of command line options, allowing the user to fine tune its behavior. It supports complex filter rules, runs in batch mode, daemon mode, etc. scp
has only a few switches.
In summary, use scp
for your day to day tasks. Commands that you type once in a while on your interactive shell. It's simpler to use, and in those cases rsync
optimizations won't help much.
For recurring tasks, like cron
jobs, use rsync
. As mentioned, on multiple invocations it will take advantage of data already transferred, performing very quickly and saving on resources. It is an excellent tool to keep two directories synchronized over a network.
Also, when dealing with large files, use rsync
with the -P
option. If the transfer is interrupted, you can resume it where it stopped by reissuing the command. See Sid Kshatriya's answer.
avrdude: stk500v2_ReceiveMessage(): timeout
I've connected to USB port directly in my laptop and timeout issue has been resolved.
Previously tried by port replicator, but it did not even recognized arduino, thus I chosen wrong port - resulting in timeout message.
So make sure that it is visible by your OS.
Nginx 403 error: directory index of [folder] is forbidden
You might get this because of Nginx policy (eg. "deny"), or you might get this because of Nginx misconfiguration, or you might get this because of filesystem restrictions.
You can determine if its the later (and possibly see evidence of a misconfiguration by using strace (except, the OP won't have access to that):
# pidof nginx
11853 11852
# strace -p 11853 -p 11852 -e trace=file -f
Process 11853 attached - interrupt to quit
Process 11852 attached - interrupt to quit
[pid 11853] stat("/var/www/html/kibanaindex.html", 0x7ffe04e93000) = -1 ENOENT (No such file or directory)
[pid 11853] stat("/var/www/html/kibana", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0
^CProcess 11853 detached
Process 11852 detached
Here I'm inspecting the filesystem activity done by nginx while a ran a test (I had the same error as you).
Here's a selected part of my config at the time
location /kibana/3/ {
alias /var/www/html/kibana;
index index.html;
}
In my case, as strace quite clearly shows, the joining of in the "alias" to the "index" was not what I had expected, and it seems I need to get into the habit of always appending directory names with a /, so in my case, the following worked:
location /kibana/3/ {
alias /var/www/html/kibana/;
index index.html;
}
How to parse XML to R data frame
Use xpath more directly for both performance and clarity.
time_path <- "//start-valid-time"
temp_path <- "//temperature[@type='hourly']/value"
df <- data.frame(
latitude=data[["number(//point/@latitude)"]],
longitude=data[["number(//point/@longitude)"]],
start_valid_time=sapply(data[time_path], xmlValue),
hourly_temperature=as.integer(sapply(data[temp_path], as, "integer"))
leading to
> head(df, 2)
latitude longitude start_valid_time hourly_temperature
1 29.81 -82.42 2014-02-14T18:00:00-05:00 60
2 29.81 -82.42 2014-02-14T19:00:00-05:00 55
How should we manage jdk8 stream for null values
Stuart's answer provides a great explanation, but I'd like to provide another example.
I ran into this issue when attempting to perform a reduce
on a Stream containing null values (actually it was LongStream.average()
, which is a type of reduction). Since average() returns OptionalDouble
, I assumed the Stream could contain nulls but instead a NullPointerException was thrown. This is due to Stuart's explanation of null v. empty.
So, as the OP suggests, I added a filter like so:
list.stream()
.filter(o -> o != null)
.reduce(..);
Or as tangens pointed out below, use the predicate provided by the Java API:
list.stream()
.filter(Objects::nonNull)
.reduce(..);
From the mailing list discussion Stuart linked:
Brian Goetz on nulls in Streams
java.io.IOException: Broken pipe
I agree with @arcy, the problem is on client side, on my case it was because of nginx, let me elaborate
I am using nginx as the frontend (so I can distribute load, ssl, etc ...) and using proxy_pass http://127.0.0.1:8080
to forward the appropiate requests to tomcat.
There is a default value for the nginx variable proxy_read_timeout
of 60s that should be enough, but on some peak moments my setup would error with the java.io.IOException: Broken pipe changing the value will help until the root cause (60s should be enough) can be fixed.
NOTE: I made a new answer so I could expand a bit more with my case (it was the only mention I found about this error on internet after looking quite a lot)
Conditional logic in AngularJS template
You could use the ngSwitch directive:
<div ng-switch on="selection" >
<div ng-switch-when="settings">Settings Div</div>
<span ng-switch-when="home">Home Span</span>
<span ng-switch-default>default</span>
</div>
If you don't want the DOM to be loaded with empty divs, you need to create your custom directive using $http to load the (sub)templates and $compile to inject it in the DOM when a certain condition has reached.
This is just an (untested) example. It can and should be optimized:
HTML:
<conditional-template ng-model="element" template-url1="path/to/partial1" template-url2="path/to/partial2"></div>
Directive:
app.directive('conditionalTemplate', function($http, $compile) {
return {
restrict: 'E',
require: '^ngModel',
link: function(sope, element, attrs, ctrl) {
// get template with $http
// check model via ctrl.$viewValue
// compile with $compile
// replace element with element.replaceWith()
}
};
});
BeautifulSoup: extract text from anchor tag
This will help:
from bs4 import BeautifulSoup
data = '''<div class="image">
<a href="http://www.example.com/eg1">Content1<img
src="http://image.example.com/img1.jpg" /></a>
</div>
<div class="image">
<a href="http://www.example.com/eg2">Content2<img
src="http://image.example.com/img2.jpg" /> </a>
</div>'''
soup = BeautifulSoup(data)
for div in soup.findAll('div', attrs={'class':'image'}):
print(div.find('a')['href'])
print(div.find('a').contents[0])
print(div.find('img')['src'])
If you are looking into Amazon products then you should be using the official API. There is at least one Python package that will ease your scraping issues and keep your activity within the terms of use.
Phone mask with jQuery and Masked Input Plugin
$('.phone').focus(function(e) {
// add mask
$('.phone')
.mask("(99) 99999999?9")
.focusin(function(event)
{
$(this).unmask();
$(this).mask("(99) 99999999?9");
})
.focusout(function(event)
{
var phone, element;
element = $(this);
phone = element.val().replace(/\D/g, '');
element.unmask();
if (phone.length > 10) {
element.mask("(99) 99999-999?9");
} else {
element.mask("(99) 9999-9999?9");
}
}
);
});
OpenSSL Verify return code: 20 (unable to get local issuer certificate)
I had the same problem on OSX OpenSSL 1.0.1i from Macports, and also had to specify CApath as a workaround (and as mentioned in the Ubuntu bug report, even an invalid CApath will make openssl look in the default directory).
Interestingly, connecting to the same server using PHP's openssl functions (as used in PHPMailer 5) worked fine.
java.lang.RuntimeException: Unable to start activity ComponentInfo
<activity
android:name="MyBookActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.ALTERNATIVE" />
</intent-filter>
</activity>
where is your dot before MyBookActivity?
How to convert int to string on Arduino?
use the itoa()
function included in stdlib.h
char buffer[7]; //the ASCII of the integer will be stored in this char array
itoa(-31596,buffer,10); //(integer, yourBuffer, base)
JavaScript Number Split into individual digits
You can work on strings instead of numbers to achieve this. You can do it like this
(111 + '').split('')
This will return an array of strings ['1','1','1']
on which you can iterate upon and call parseInt
method.
parseInt('1') === 1
If you want the sum of individual digits, you can use the reduce function (implemented from Javascript 1.8) like this
(111 + '').split('').reduce(function(previousValue, currentValue){
return parseInt(previousValue,10) + parseInt(currentValue,10);
})
ACCESS_FINE_LOCATION AndroidManifest Permissions Not Being Granted
I was having the same problem and could not figure out what I was doing wrong. Turns out, the auto-complete for Android Studio was changing the text to either all caps or all lower case (depending on whether I typed in upper case or lower cast words before the auto-complete). The OS was not registering the name due to this issue and I would get the error regarding a missing permission. As stated above, ensure your permissions are labeled correctly:
Correct:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Incorrect:
<uses-permission android:name="ANDROID.PERMISSION.ACCESS_FINE_LOCATION" />
Incorrect:
<uses-permission android:name="android.permission.access_fine_location" />
Though this may seem trivial, its easy to overlook.
If there is some setting to make permissions non-case-sensitive, please add a comment with the instructions. Thank you!
Posting array from form
If you want everything in your post to be as $Variables you can use something like this:
foreach($_POST as $key => $value) {
eval("$" . $key . " = " . $value");
}
How to implement a SQL like 'LIKE' operator in java?
public static boolean like(String source, String exp) {
if (source == null || exp == null) {
return false;
}
int sourceLength = source.length();
int expLength = exp.length();
if (sourceLength == 0 || expLength == 0) {
return false;
}
boolean fuzzy = false;
char lastCharOfExp = 0;
int positionOfSource = 0;
for (int i = 0; i < expLength; i++) {
char ch = exp.charAt(i);
// ????
boolean escape = false;
if (lastCharOfExp == '\\') {
if (ch == '%' || ch == '_') {
escape = true;
// System.out.println("escape " + ch);
}
}
if (!escape && ch == '%') {
fuzzy = true;
} else if (!escape && ch == '_') {
if (positionOfSource >= sourceLength) {
return false;
}
positionOfSource++;// <<<----- ???1
} else if (ch != '\\') {// ????,?????????
if (positionOfSource >= sourceLength) {// ?????source????
return false;
}
if (lastCharOfExp == '%') { // ??????%,?????
int tp = source.indexOf(ch);
// System.out.println("?????=%,?????=" + ch + ",position=" + position + ",tp=" + tp);
if (tp == -1) { // ????????,????
return false;
}
if (tp >= positionOfSource) {
positionOfSource = tp + 1;// <<<----- ????
if (i == expLength - 1 && positionOfSource < sourceLength) { // exp??????????,????source?????????
return false;
}
} else {
return false;
}
} else if (source.charAt(positionOfSource) == ch) {// ????????ch??
positionOfSource++;
} else {
return false;
}
}
lastCharOfExp = ch;// <<<----- ??
// System.out.println("?????=" + ch + ",position=" + position);
}
// expr???????,???????,??source???????????source???
if (!fuzzy && positionOfSource < sourceLength) {
// System.out.println("?????=" + lastChar + ",position=" + position );
return false;
}
return true;// ????true
}
Assert.assertEquals(true, like("abc_d", "abc\\_d"));
Assert.assertEquals(true, like("abc%d", "abc\\%%d"));
Assert.assertEquals(false, like("abcd", "abc\\_d"));
String source = "1abcd";
Assert.assertEquals(true, like(source, "_%d"));
Assert.assertEquals(false, like(source, "%%a"));
Assert.assertEquals(false, like(source, "1"));
Assert.assertEquals(true, like(source, "%d"));
Assert.assertEquals(true, like(source, "%%%%"));
Assert.assertEquals(true, like(source, "1%_"));
Assert.assertEquals(false, like(source, "1%_2"));
Assert.assertEquals(false, like(source, "1abcdef"));
Assert.assertEquals(true, like(source, "1abcd"));
Assert.assertEquals(false, like(source, "1abcde"));
// ????case?????
Assert.assertEquals(true, like(source, "_%_"));
Assert.assertEquals(true, like(source, "_%____"));
Assert.assertEquals(true, like(source, "_____"));// 5?
Assert.assertEquals(false, like(source, "___"));// 3?
Assert.assertEquals(false, like(source, "__%____"));// 6?
Assert.assertEquals(false, like(source, "1"));
Assert.assertEquals(false, like(source, "a_%b"));
Assert.assertEquals(true, like(source, "1%"));
Assert.assertEquals(false, like(source, "d%"));
Assert.assertEquals(true, like(source, "_%"));
Assert.assertEquals(true, like(source, "_abc%"));
Assert.assertEquals(true, like(source, "%d"));
Assert.assertEquals(true, like(source, "%abc%"));
Assert.assertEquals(false, like(source, "ab_%"));
Assert.assertEquals(true, like(source, "1ab__"));
Assert.assertEquals(true, like(source, "1ab__%"));
Assert.assertEquals(false, like(source, "1ab___"));
Assert.assertEquals(true, like(source, "%"));
Assert.assertEquals(false, like(null, "1ab___"));
Assert.assertEquals(false, like(source, null));
Assert.assertEquals(false, like(source, ""));
Digital Certificate: How to import .cer file in to .truststore file using?
# Copy the certificate into the directory Java_home\Jre\Lib\Security
# Change your directory to Java_home\Jre\Lib\Security>
# Import the certificate to a trust store.
keytool -import -alias ca -file somecert.cer -keystore cacerts -storepass changeit [Return]
Trust this certificate: [Yes]
changeit is the default truststore password
Language Books/Tutorials for popular languages
For Lisp and Scheme (hell, functional programming in general), there are few things that provide a more solid foundation than The Little Schemer and The Seasoned Schemer. Both provide a very simple and intuitive introduction to both Scheme and functional programming that proves far simpler for new students or hobbyists than any of the typical volumes that rub off like a nonfiction rendition of War & Peace.
Once they've moved beyond the Schemer series, SICP and On Lisp are both fantastic choices.
Batch: Remove file extension
Using cygwin bash to do the chopping
:: e.g. FILE=basename.mp4 => FILE_NO_EXT=basename
set FILE=%1
for /f "delims=" %%a in ('bash -c "FILE=%FILE%; echo ${FILE/.*/}" ') do set FILE_NO_EXT=%%a
What is the default username and password in Tomcat?
In Tomcat 7, under TOMCAT_HOME/conf/tomcat_users.xml
, see the <user />
tag to see password.
Example:
<role rolename="tomcat"/>
<role rolename="role1"/>
<user username="tomcat" password="tomcat" roles="tomcat"/>
<user username="both" password="tomcat" roles="tomcat,role1"/>
<user username="role1" password="tomcat" roles="role1"/>
Excel Date Conversion from yyyymmdd to mm/dd/yyyy
Found another (manual) answer which worked well for me
- Select the column.
- Choose Data tab
- Text to Columns - opens new box
- (choose Delimited), Next
- (uncheck all boxes, use "none" for text qualifier), Next
- use the ymd option from the Date dropdown.
- Click Finish
Distribution certificate / private key not installed
In my case Xcode was not accessing certificates from the keychain, I followed these steps:
- delete certificates from the keychain.
- restart the mac.
- generate new certificates.
- install new certificates.
- clean build folder.
- build project.
- again clean build folder.
- archive now.
It works That's it.
Using String Format to show decimal up to 2 places or simple integer
When dealing with decimals coming from a (T-)SQL database, you want to be able to convert nullable and non-nullable decimals with x decimal places and be able to review the code easily against your table definitions - and of course, display the right number of decimals to the user.
Unfortunately, the Entity Framework doesn't automatically convert something like a SQL decimal(18,2)
into a .NET equivalent with the same number of decimal places (since there is only decimal with full precision available). You have to truncate the decimal places manually.
So, I did it this way:
public static class Extensions
{
public static string ToStringDecimal(this decimal d, byte decimals)
{
var fmt = (decimals>0) ? "0." + new string('0', decimals) : "0";
return d.ToString(fmt);
}
public static string ToStringDecimal(this decimal? d, byte decimals)
{
if (!d.HasValue) return "";
return ToStringDecimal(d.Value, decimals);
}
}
Example Usage:
void Main()
{
decimal d = (decimal)1.2345;
decimal? d2 = null;
Console.WriteLine(d.ToStringDecinal(2)); // prints: "1.23" (2 decimal places)
Console.WriteLine(d.ToStringDecinal(0)); // prints: "1" (show integer number)
Console.WriteLine(d2.ToStringDecimal(2)); // prints: "" (show null as empty string)
}
Running bash script from within python
If sleep.sh
has the shebang #!/bin/sh
and it has appropriate file permissions -- run chmod u+rx sleep.sh
to make sure and it is in $PATH
then your code should work as is:
import subprocess
rc = subprocess.call("sleep.sh")
If the script is not in the PATH then specify the full path to it e.g., if it is in the current working directory:
from subprocess import call
rc = call("./sleep.sh")
If the script has no shebang then you need to specify shell=True
:
rc = call("./sleep.sh", shell=True)
If the script has no executable permissions and you can't change it e.g., by running os.chmod('sleep.sh', 0o755)
then you could read the script as a text file and pass the string to subprocess
module instead:
with open('sleep.sh', 'rb') as file:
script = file.read()
rc = call(script, shell=True)
File inside jar is not visible for spring
If your spring-context.xml and my.config files are in different jars then you will need to use classpath*:my.config
?
More info here
Also, make sure you are using resource.getInputStream()
not resource.getFile()
when loading from inside a jar file.
Navigation Controller Push View Controller
UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"storyBoardName" bundle:nil];
MemberDetailsViewController* controller = [storyboard instantiateViewControllerWithIdentifier:@"viewControllerIdentiferInStoryBoard"];
[self.navigationController pushViewController:viewControllerName animated:YES];
Swift 4:
let storyBoard = UIStoryboard(name: "storyBoardName", bundle:nil)
let memberDetailsViewController = storyBoard.instantiateViewController(withIdentifier: "viewControllerIdentiferInStoryBoard") as! MemberDetailsViewController
self.navigationController?.pushViewController(memberDetailsViewController, animated:true)
JSON parsing using Gson for Java
This is simple code to do it, I avoided all checks but this is the main idea.
public String parse(String jsonLine) {
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("data");
JsonArray jarray = jobject.getAsJsonArray("translations");
jobject = jarray.get(0).getAsJsonObject();
String result = jobject.get("translatedText").getAsString();
return result;
}
To make the use more generic - you will find that Gson's javadocs are pretty clear and helpful.
Visual Studio Code - is there a Compare feature like that plugin for Notepad ++?
I found a flow which is fastest for me, by first associating a keyboard shortcut Alt+k
to "Compare Active File With..." (#a). (Similar to wisbucky's answer but further improved and more step-wise.)
Then, to compare two files:
- Open or focus file B (will be editable in compare view by default). E.g. by drag-drop from File Explorer to VS Code's center.
- Open or focus file A.
- Press
Alt+k
, a quick open menu will be shown with file B focused.
- Press
Enter
.
Result: file A on left and file B on right. (Tested on VS Code 1.27.1)
Remarks
#a - to do so, press Ctrl-k Ctrl-s
to show Keyboard Shortcuts, type compare
on the top search box, and double click the "Keybinding" column for "Compare Active File With...", press Alt+k
then Enter
to assign it.
Using jQuery's ajax method to retrieve images as a blob
You can't do this with jQuery ajax, but with native XMLHttpRequest.
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
//this.response is what you're looking for
handler(this.response);
console.log(this.response, typeof this.response);
var img = document.getElementById('img');
var url = window.URL || window.webkitURL;
img.src = url.createObjectURL(this.response);
}
}
xhr.open('GET', 'http://jsfiddle.net/img/logo.png');
xhr.responseType = 'blob';
xhr.send();
EDIT
So revisiting this topic, it seems it is indeed possible to do this with jQuery 3
_x000D_
_x000D_
jQuery.ajax({_x000D_
url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e',_x000D_
cache:false,_x000D_
xhr:function(){// Seems like the only way to get access to the xhr object_x000D_
var xhr = new XMLHttpRequest();_x000D_
xhr.responseType= 'blob'_x000D_
return xhr;_x000D_
},_x000D_
success: function(data){_x000D_
var img = document.getElementById('img');_x000D_
var url = window.URL || window.webkitURL;_x000D_
img.src = url.createObjectURL(data);_x000D_
},_x000D_
error:function(){_x000D_
_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
<img id="img" width=100%>
_x000D_
_x000D_
_x000D_
or
use xhrFields to set the responseType
_x000D_
_x000D_
jQuery.ajax({_x000D_
url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e',_x000D_
cache:false,_x000D_
xhrFields:{_x000D_
responseType: 'blob'_x000D_
},_x000D_
success: function(data){_x000D_
var img = document.getElementById('img');_x000D_
var url = window.URL || window.webkitURL;_x000D_
img.src = url.createObjectURL(data);_x000D_
},_x000D_
error:function(){_x000D_
_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
<img id="img" width=100%>
_x000D_
_x000D_
_x000D_
Selecting a row of pandas series/dataframe by integer index
The primary purpose of the DataFrame indexing operator, []
is to select columns.
When the indexing operator is passed a string or integer, it attempts to find a column with that particular name and return it as a Series.
So, in the question above: df[2]
searches for a column name matching the integer value 2
. This column does not exist and a KeyError
is raised.
The DataFrame indexing operator completely changes behavior to select rows when slice notation is used
Strangely, when given a slice, the DataFrame indexing operator selects rows and can do so by integer location or by index label.
df[2:3]
This will slice beginning from the row with integer location 2 up to 3, exclusive of the last element. So, just a single row. The following selects rows beginning at integer location 6 up to but not including 20 by every third row.
df[6:20:3]
You can also use slices consisting of string labels if your DataFrame index has strings in it. For more details, see this solution on .iloc vs .loc.
I almost never use this slice notation with the indexing operator as its not explicit and hardly ever used. When slicing by rows, stick with .loc/.iloc
.
Accessing session from TWIG template
I found that the cleanest way to do this is to create a custom TwigExtension and override its getGlobals()
method. Rather than using $_SESSION
, it's also better to use Symfony's Session
class since it handles automatically starting/stopping the session.
I've got the following extension in /src/AppBundle/Twig/AppExtension.php:
<?php
namespace AppBundle\Twig;
use Symfony\Component\HttpFoundation\Session\Session;
class AppExtension extends \Twig_Extension {
public function getGlobals() {
$session = new Session();
return array(
'session' => $session->all(),
);
}
public function getName() {
return 'app_extension';
}
}
Then add this in /app/config/services.yml:
services:
app.twig_extension:
class: AppBundle\Twig\AppExtension
public: false
tags:
- { name: twig.extension }
Then the session can be accessed from any view using:
{{ session.my_variable }}
How to use jquery $.post() method to submit form values
Get the value of your textboxes using val()
and store them in a variable. Pass those values through $.post
. In using the $.Post Submit button
you can actually remove the form.
<script>
username = $("#username").val();
password = $("#password").val();
$("#post-btn").click(function(){
$.post("process.php", { username:username, password:password } ,function(data){
alert(data);
});
});
</script>
How to find a text inside SQL Server procedures / triggers?
Just wrote this for generic full outer cross ref
create table #XRefDBs(xtype varchar(2),SourceDB varchar(100), Object varchar(100), RefDB varchar(100))
declare @sourcedbname varchar(100),
@searchfordbname varchar(100),
@sql nvarchar(4000)
declare curs cursor for
select name
from sysdatabases
where dbid>4
open curs
fetch next from curs into @sourcedbname
while @@fetch_status=0
begin
print @sourcedbname
declare curs2 cursor for
select name
from sysdatabases
where dbid>4
and name <> @sourcedbname
open curs2
fetch next from curs2 into @searchfordbname
while @@fetch_status=0
begin
print @searchfordbname
set @sql =
'INSERT INTO #XRefDBs (xtype,SourceDB,Object, RefDB)
select DISTINCT o.xtype,'''+@sourcedbname+''', o.name,'''+@searchfordbname+'''
from '+@sourcedbname+'.dbo.syscomments c
join '+@sourcedbname+'.dbo.sysobjects o on c.id=o.id
where o.xtype in (''V'',''P'',''FN'',''TR'')
and (text like ''%'+@searchfordbname+'.%''
or text like ''%'+@searchfordbname+'].%'')'
print @sql
exec sp_executesql @sql
fetch next from curs2 into @searchfordbname
end
close curs2
deallocate curs2
fetch next from curs into @sourcedbname
end
close curs
deallocate curs
select * from #XRefDBs
Correct format specifier for double in printf
"%f"
is the (or at least one) correct format for a double. There is no format for a float
, because if you attempt to pass a float
to printf
, it'll be promoted to double
before printf
receives it1. "%lf"
is also acceptable under the current standard -- the l
is specified as having no effect if followed by the f
conversion specifier (among others).
Note that this is one place that printf
format strings differ substantially from scanf
(and fscanf
, etc.) format strings. For output, you're passing a value, which will be promoted from float
to double
when passed as a variadic parameter. For input you're passing a pointer, which is not promoted, so you have to tell scanf
whether you want to read a float
or a double
, so for scanf
, %f
means you want to read a float
and %lf
means you want to read a double
(and, for what it's worth, for a long double
, you use %Lf
for either printf
or scanf
).
1. C99, §6.5.2.2/6: "If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type float are promoted to double. These are called the default argument promotions." In C++ the wording is somewhat different (e.g., it doesn't use the word "prototype") but the effect is the same: all the variadic parameters undergo default promotions before they're received by the function.
How do I get the SQLSRV extension to work with PHP, since MSSQL is deprecated?
Quoting http://php.net/manual/en/intro.mssql.php:
The MSSQL extension is not available anymore on Windows with PHP 5.3 or later.
SQLSRV, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.
Once you downloaded that, follow the instructions at this page:
In a nutshell:
Put the driver file in your PHP extension directory.
Modify the php.ini file to include the driver. For example:
extension=php_sqlsrv_53_nts_vc9.dll
Restart the Web server.
See Also (copied from that page)
The PHP Manual for the SQLSRV extension is located at http://php.net/manual/en/sqlsrv.installation.php and offers the following for Installation:
The SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The SQLSRV download comes with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_sqlsrv_52_ts_vc6.dll file.
The drivers can also be used with PDO.
Delete all documents from index/type without deleting type
I'm using elasticsearch 7.5 and when I use
curl -XPOST 'localhost:9200/materials/_delete_by_query?conflicts=proceed&pretty' -d'
{
"query": {
"match_all": {}
}
}'
which will throw below error.
{
"error" : "Content-Type header [application/x-www-form-urlencoded] is not supported",
"status" : 406
}
I also need to add extra -H 'Content-Type: application/json'
header in the request to make it works.
curl -XPOST 'localhost:9200/materials/_delete_by_query?conflicts=proceed&pretty' -H 'Content-Type: application/json' -d'
{
"query": {
"match_all": {}
}
}'
{
"took" : 465,
"timed_out" : false,
"total" : 2275,
"deleted" : 2275,
"batches" : 3,
"version_conflicts" : 0,
"noops" : 0,
"retries" : {
"bulk" : 0,
"search" : 0
},
"throttled_millis" : 0,
"requests_per_second" : -1.0,
"throttled_until_millis" : 0,
"failures" : [ ]
}
What is the most efficient way of finding all the factors of a number in Python?
a potentially more efficient algorithm than the ones presented here already (especially if there are small prime factons in n
). the trick here is to adjust the limit up to which trial division is needed every time prime factors are found:
def factors(n):
'''
return prime factors and multiplicity of n
n = p0^e0 * p1^e1 * ... * pk^ek encoded as
res = [(p0, e0), (p1, e1), ..., (pk, ek)]
'''
res = []
# get rid of all the factors of 2 using bit shifts
mult = 0
while not n & 1:
mult += 1
n >>= 1
if mult != 0:
res.append((2, mult))
limit = round(sqrt(n))
test_prime = 3
while test_prime <= limit:
mult = 0
while n % test_prime == 0:
mult += 1
n //= test_prime
if mult != 0:
res.append((test_prime, mult))
if n == 1: # only useful if ek >= 3 (ek: multiplicity
break # of the last prime)
limit = round(sqrt(n)) # adjust the limit
test_prime += 2 # will often not be prime...
if n != 1:
res.append((n, 1))
return res
this is of course still trial division and nothing more fancy. and therefore still very limited in its efficiency (especially for big numbers without small divisors).
this is python3; the division //
should be the only thing you need to adapt for python 2 (add from __future__ import division
).
How to handle change text of span
Span does not have 'change' event by default. But you can add this event manually.
Listen to the change event of span.
$("#span1").on('change',function(){
//Do calculation and change value of other span2,span3 here
$("#span2").text('calculated value');
});
And wherever you change the text in span1. Trigger the change event manually.
$("#span1").text('test').trigger('change');
Rails: How to list database tables/objects using the Rails console?
I hope my late answer can be of some help.
This will go to rails database console.
rails db
pretty print your query output
.headers on
.mode columns
(turn headers on and show database data in column mode )
Show the tables
.table
'.help' to see help.
Or use SQL statements like 'Select * from cars'
POST JSON to API using Rails and HTTParty
I solved this by adding .to_json
and some heading information
@result = HTTParty.post(@urlstring_to_post.to_str,
:body => { :subject => 'This is the screen name',
:issue_type => 'Application Problem',
:status => 'Open',
:priority => 'Normal',
:description => 'This is the description for the problem'
}.to_json,
:headers => { 'Content-Type' => 'application/json' } )
Calculating distance between two points, using latitude longitude?
Here's a Java function that calculates the distance between two lat/long points, posted below, just in case it disappears again.
private double distance(double lat1, double lon1, double lat2, double lon2, char unit) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
if (unit == 'K') {
dist = dist * 1.609344;
} else if (unit == 'N') {
dist = dist * 0.8684;
}
return (dist);
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
/*:: This function converts decimal degrees to radians :*/
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
/*:: This function converts radians to decimal degrees :*/
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
System.out.println(distance(32.9697, -96.80322, 29.46786, -98.53506, 'M') + " Miles\n");
System.out.println(distance(32.9697, -96.80322, 29.46786, -98.53506, 'K') + " Kilometers\n");
System.out.println(distance(32.9697, -96.80322, 29.46786, -98.53506, 'N') + " Nautical Miles\n");
C++ obtaining milliseconds time on Linux -- clock() doesn't seem to work properly
Please note that clock
does not measure wall clock time. That means if your program takes 5 seconds, clock
will not measure 5 seconds necessarily, but could more (your program could run multiple threads and so could consume more CPU than real time) or less. It measures an approximation of CPU time used. To see the difference consider this code
#include <iostream>
#include <ctime>
#include <unistd.h>
int main() {
std::clock_t a = std::clock();
sleep(5); // sleep 5s
std::clock_t b = std::clock();
std::cout << "difference: " << (b - a) << std::endl;
return 0;
}
It outputs on my system
$ difference: 0
Because all we did was sleeping and not using any CPU time! However, using gettimeofday
we get what we want (?)
#include <iostream>
#include <ctime>
#include <unistd.h>
#include <sys/time.h>
int main() {
timeval a;
timeval b;
gettimeofday(&a, 0);
sleep(5); // sleep 5s
gettimeofday(&b, 0);
std::cout << "difference: " << (b.tv_sec - a.tv_sec) << std::endl;
return 0;
}
Outputs on my system
$ difference: 5
If you need more precision but want to get CPU time, then you can consider using the getrusage
function.
How to emulate a do-while loop in Python?
The built-in iter function does specifically that:
for x in iter(YOUR_FN, TERM_VAL):
...
E.g. (tested in Py2 and 3):
class Easy:
X = 0
@classmethod
def com(cls):
cls.X += 1
return cls.X
for x in iter(Easy.com, 10):
print(">>>", x)
If you want to give a condition to terminate instead of a value, you always can set an equality, and require that equality to be True
.
WHERE Clause to find all records in a specific month
Can I just ask to compare based on the year and month?
You can. Here's a simple example using the AdventureWorks sample database...
DECLARE @Year INT
DECLARE @Month INT
SET @Year = 2002
SET @Month = 6
SELECT
[pch].*
FROM
[Production].[ProductCostHistory] pch
WHERE
YEAR([pch].[ModifiedDate]) = @Year
AND MONTH([pch].[ModifiedDate]) = @Month
What is the difference between "Class.forName()" and "Class.forName().newInstance()"?
Class.forName()
-->forName() is the static method of Class class it returns Class class object used for reflection not user class object so you can only call Class class methods on it like getMethods()
, getConstructors()
etc.
If you care about only running static block of your(Runtime given) class and only getting information of methods,constructors,Modifier etc of your class you can do with this object which you get using Class.forName()
But if you want to access or call your class method (class which you have given at runtime) then you need to have its object so newInstance method of Class class do it for you.It create new instance of the class and return it to you .You just need to type-cast it to your class.
ex-: suppose Employee is your class then
Class a=Class.forName(args[0]);
//args[0]=cmd line argument to give class at runtime.
Employee ob1=a.newInstance();
a.newInstance()
is similar to creating object using new Employee()
.
now you can access all your class visible fields and methods.
How to add a file to the last commit in git?
Yes, there's a command git commit --amend
which is used to "fix" last commit.
In your case it would be called as:
git add the_left_out_file
git commit --amend --no-edit
The --no-edit flag allow to make amendment to commit without changing commit message.
EDIT: Warning
You should never amend public commits, that you already pushed to public repository, because what amend does is actually removing from history last commit and creating new commit with combined changes from that commit and new added when amending.
Laravel: How do I parse this json data in view blade?
The catch all for me is taking an object, encoding it, and then passing the string into a javascript script
tag. To do this you have to do some replacements.
First replace every \
with a double slash \\
and then every quote"
with a \"
.
$payload = json_encode($payload);
$payload = preg_replace("_\\\_", "\\\\\\", $payload);
$payload = preg_replace("/\"/", "\\\"", $payload);
return View::make('pages.javascript')
->with('payload', $payload)
Then in the blade template
@if(isset($payload))
<script>
window.__payload = JSON.parse("{!!$payload!!}");
</script>
@endif
This basically allows you to take an object on the php side, and then have an object on the javascript side.
How to put an image in div with CSS?
With Javascript/Jquery:
- load image with hidden
img
- when image has been loaded, get width and height
- dynamically create a
div
and set width, height and background
remove the original img
$(document).ready(function() {
var image = $("<img>");
var div = $("<div>")
image.load(function() {
div.css({
"width": this.width,
"height": this.height,
"background-image": "url(" + this.src + ")"
});
$("#container").append(div);
});
image.attr("src", "test0.png");
});
jQuery: get parent tr for selected radio button
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.
Converting String to Int with Swift
Useful for String to Int and other type
extension String {
//Converts String to Int
public func toInt() -> Int? {
if let num = NumberFormatter().number(from: self) {
return num.intValue
} else {
return nil
}
}
//Converts String to Double
public func toDouble() -> Double? {
if let num = NumberFormatter().number(from: self) {
return num.doubleValue
} else {
return nil
}
}
/// EZSE: Converts String to Float
public func toFloat() -> Float? {
if let num = NumberFormatter().number(from: self) {
return num.floatValue
} else {
return nil
}
}
//Converts String to Bool
public func toBool() -> Bool? {
return (self as NSString).boolValue
}
}
Use it like :
"123".toInt() // 123
Java Initialize an int array in a constructor
private int[] data = new int[3];
This already initializes your array elements to 0. You don't need to repeat that again in the constructor.
In your constructor it should be:
data = new int[]{0, 0, 0};
How can I use the $index inside a ng-repeat to enable a class and show a DIV?
The issue here is that ng-repeat
creates its own scope, so when you do selected=$index
it creates a new a selected
property in that scope rather than altering the existing one. To fix this you have two options:
Change the selected property to a non-primitive (ie object or array, which makes javascript look up the prototype chain) then set a value on that:
$scope.selected = {value: 0};
<a ng-click="selected.value = $index">A{{$index}}</a>
See plunker
or
Use the $parent
variable to access the correct property. Though less recommended as it increases coupling between scopes
<a ng-click="$parent.selected = $index">A{{$index}}</a>
See plunker
All possible array initialization syntaxes
var contacts = new[]
{
new
{
Name = " Eugene Zabokritski",
PhoneNumbers = new[] { "206-555-0108", "425-555-0001" }
},
new
{
Name = " Hanying Feng",
PhoneNumbers = new[] { "650-555-0199" }
}
};
'nuget' is not recognized but other nuget commands working
Nuget.exe is placed at .nuget
folder of your project. It can't be executed directly in Package Manager Console, but is executed by Powershell commands because these commands build custom path for themselves.
My steps to solve are:
Update
NuGet can be easily installed in your project using the following command:
Install-Package NuGet.CommandLine
ASP.NET 4.5 has not been registered on the Web server
tl;dr; Clicking OK is the workaround, everything will work fine after that.
I also received this error message.
Configuring Web http://localhost:xxxxx/ for ASP.NET 4.5 failed. You must manually configure this site for
ASP.NET 4.5 in order for the site to run correctly. ASP.NET 4.0 has not been registered on the Web server.
You need to manually configure your Web server for ASP.NET 4.0 in order for your site to run correctly.
Environment: Windows 10, IIS8, VS 2012 Web.
After finding this page, along with several seemingly invasive solutions, I read through the hotfix option at https://support.microsoft.com/en-us/help/3002339/unexpected-dialog-box-appears-when-you-open-projects-in-visual-studio as suggested here.
Please avoid doing anything too drastic, and note the section of that page marked "Workaround" as shown below:
Workaround
To work around this issue, click OK when the dialog box appears after you either create a new project or open an existing Web Site Project or Windows Azure project. After you do this, the project works as expected.
In other words, click OK on the dialog box one time, and the message is gone forever. The project will work just fine.
How to make a div with a circular shape?
By using a border-radius of 50% you can make a circle.
Here is an example:
CSS:
#exampleCircle{
width: 500px;
height: 500px;
background: red;
border-radius: 50%;
}
HTML:
<div id = "exampleCircle"></div>
How to remove all the occurrences of a char in c++ string
70% Faster Solution than the top answer
void removeCharsFromString(std::string& str, const char* charsToRemove)
{
size_t charsToRemoveLen = strlen(charsToRemove);
std::remove_if(str.begin(), str.end(), [charsToRemove, charsToRemoveLen](char ch) -> bool
{
for (int i = 0; i < charsToRemoveLen; ++i) {
if (ch == charsToRemove[i])
return true;
}
return false;
});
}
Using awk to print all columns from the nth to the last
Because of a wrong most upvoted anwser with 340 votes, I just lost 5 minutes of my life! Did anybody try this answer out before upvoting this? Apparantly not. Completely useless.
I have a log where after $5 with an IP address can be more text or no text. I need everything from the IP address to the end of the line should there be anything after $5. In my case, this is actualy withn an awk program, not an awk oneliner so awk must solve the problem. When I try to remove the first 4 fields using the most upvoted but completely wrong answer:
echo " 7 27.10.16. Thu 11:57:18 37.244.182.218" | awk '{$1=$2=$3=$4=""; printf "[%s]\n", $0}'
it spits out wrong and useless response (I added [..] to demonstrate):
[ 37.244.182.218 one two three]
There are even some sugestions to combine substr with this wrong answer. Like that complication is an improvement.
Instead, if columns are fixed width until the cut point and awk is needed, the correct answer is:
echo " 7 27.10.16. Thu 11:57:18 37.244.182.218" | awk '{printf "[%s]\n", substr($0,28)}'
which produces the desired output:
[37.244.182.218 one two three]
How do I convert NSMutableArray to NSArray?
If you're constructing an array via mutability and then want to return an immutable version, you can simply return the mutable array as an "NSArray" via inheritance.
- (NSArray *)arrayOfStrings {
NSMutableArray *mutableArray = [NSMutableArray array];
mutableArray[0] = @"foo";
mutableArray[1] = @"bar";
return mutableArray;
}
If you "trust" the caller to treat the (technically still mutable) return object as an immutable NSArray, this is a cheaper option than [mutableArray copy]
.
Apple concurs:
To determine whether it can change a received object, the receiver of a message must rely on the formal type of the return value. If it receives, for example, an array object typed as immutable, it should not attempt to mutate it. It is not an acceptable programming practice to determine if an object is mutable based on its class membership.
The above practice is discussed in more detail here:
Best Practice: Return mutableArray.copy or mutableArray if return type is NSArray
Get day of week in SQL Server 2005/2008
You can use DATEPART(dw, GETDATE())
but be aware that the result will rely on SQL server setting @@DATEFIRST
value which is the first day of week setting (In Europe default value 7 which is Sunday).
If you want to change the first day of week to another value, you could use SET DATEFIRST
but this may affect everywhere in your query session which you do not want.
Alternative way is to explicitly specify the first day of week value as parameter and avoid depending on @@DATEFIRST
setting. You can use the following formula to achieve that when need it:
(DATEPART(dw, GETDATE()) + @@DATEFIRST + 6 - @WeekStartDay) % 7 + 1
where @WeekStartDay
is the first day of the week you want for your system (from 1 to 7 which means from Monday to Sunday).
I have wrapped it into below function so we can reuse it easily:
CREATE FUNCTION [dbo].[GetDayInWeek](@InputDateTime DATETIME, @WeekStartDay INT)
RETURNS INT
AS
BEGIN
--Note: @WeekStartDay is number from [1 - 7] which is from Monday to Sunday
RETURN (DATEPART(dw, @InputDateTime) + @@DATEFIRST + 6 - @WeekStartDay) % 7 + 1
END
Example usage:
GetDayInWeek('2019-02-04 00:00:00', 1)
It is equivalent to following (but independent to SQL server DATEFIRST setting):
SET DATEFIRST 1
DATEPART(dw, '2019-02-04 00:00:00')
kill -3 to get java thread dump
You could alternatively use jstack (Included with JDK) to take a thread dump and write the output wherever you want. Is that not available in a unix environment?
jstack PID > outfile
How do I correctly clone a JavaScript object?
If you do not use Date
s, functions, undefined, regExp or Infinity within your object, a very simple one liner is JSON.parse(JSON.stringify(object))
:
_x000D_
_x000D_
const a = {_x000D_
string: 'string',_x000D_
number: 123,_x000D_
bool: false,_x000D_
nul: null,_x000D_
date: new Date(), // stringified_x000D_
undef: undefined, // lost_x000D_
inf: Infinity, // forced to 'null'_x000D_
}_x000D_
console.log(a);_x000D_
console.log(typeof a.date); // Date object_x000D_
const clone = JSON.parse(JSON.stringify(a));_x000D_
console.log(clone);_x000D_
console.log(typeof clone.date); // result of .toISOString()
_x000D_
_x000D_
_x000D_
This works for all kind of objects containing objects, arrays, strings, booleans and numbers.
See also this article about the structured clone algorithm of browsers which is used when posting messages to and from a worker. It also contains a function for deep cloning.
Bootstrap 4 navbar color
I got it. This is very simple. Using the class bg
you can achieve this easily.
Let me show you:
<nav class="navbar navbar-expand-lg navbar-dark navbar-full bg-primary"></nav>
This gives you the default blue navbar
If you want to change your favorite color, then simply use the style tag within the nav
:
<nav class="navbar navbar-expand-lg navbar-dark navbar-full" style="background-color: #FF0000">
Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice
Taking for granted that the JSON you posted is actually what you are seeing in the browser, then the problem is the JSON itself.
The JSON snippet you have posted is malformed.
You have posted:
[{
"name" : "shopqwe",
"mobiles" : [],
"address" : {
"town" : "city",
"street" : "streetqwe",
"streetNumber" : "59",
"cordX" : 2.229997,
"cordY" : 1.002539
},
"shoe"[{
"shoeName" : "addidas",
"number" : "631744030",
"producent" : "nike",
"price" : 999.0,
"sizes" : [30.0, 35.0, 38.0]
}]
while the correct JSON would be:
[{
"name" : "shopqwe",
"mobiles" : [],
"address" : {
"town" : "city",
"street" : "streetqwe",
"streetNumber" : "59",
"cordX" : 2.229997,
"cordY" : 1.002539
},
"shoe" : [{
"shoeName" : "addidas",
"number" : "631744030",
"producent" : "nike",
"price" : 999.0,
"sizes" : [30.0, 35.0, 38.0]
}
]
}
]
Java: how do I get a class literal from a generic type?
There are no Class literals for parameterized types, however there are Type objects that correctly define these types.
See java.lang.reflect.ParameterizedType
- http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/ParameterizedType.html
Google's Gson library defines a TypeToken class that allows to simply generate parameterized types and uses it to spec json objects with complex parameterized types in a generic friendly way. In your example you would use:
Type typeOfListOfFoo = new TypeToken<List<Foo>>(){}.getType()
I intended to post links to the TypeToken and Gson classes javadoc but Stack Overflow won't let me post more than one link since I'm a new user, you can easily find them using Google search
WCF ServiceHost access rights
If you are running via the IDE, running as administrator should help. To do this locate the Visual Studio 2008/10 application icon, right click it and select "Run as administrator"
Why does z-index not work?
Your elements need to have a position
attribute. (e.g. absolute
, relative
, fixed
) or z-index
won't work.
XPath to select multiple tags
Not sure if this helps, but with XSL, I'd do something like:
<xsl:for-each select="a/b">
<xsl:value-of select="c"/>
<xsl:value-of select="d"/>
<xsl:value-of select="e"/>
</xsl:for-each>
and won't this XPath select all children of B nodes:
a/b/*
Execute a command line binary with Node.js
@hexacyanide's answer is almost a complete one.
On Windows command prince
could be prince.exe
, prince.cmd
, prince.bat
or just prince
(I'm no aware of how gems are bundled, but npm bins come with a sh script and a batch script - npm
and npm.cmd
).
If you want to write a portable script that would run on Unix and Windows, you have to spawn the right executable.
Here is a simple yet portable spawn function:
function spawn(cmd, args, opt) {
var isWindows = /win/.test(process.platform);
if ( isWindows ) {
if ( !args ) args = [];
args.unshift(cmd);
args.unshift('/c');
cmd = process.env.comspec;
}
return child_process.spawn(cmd, args, opt);
}
var cmd = spawn("prince", ["-v", "builds/pdf/book.html", "-o", "builds/pdf/book.pdf"])
// Use these props to get execution results:
// cmd.stdin;
// cmd.stdout;
// cmd.stderr;
How can I Remove .DS_Store files from a Git repository?
I'm a bit late to the party, but I have a good answer.
To remove the .DS_Store files, use the following commands from a terminal window, but be very careful deleting files with 'find'. Using a specific name with the -name option is one of the safer ways to use it:
cd directory/above/affected/workareas
find . -name .DS_Store -delete
You can leave off the "-delete" if you want to simply list them before and after. That will reassure you that they're gone.
With regard to the ~/.gitignore_global advice: be careful here.
You want to place that nice file into .gitignore within the
top level of each workarea and commit it, so that anyone who clones your repo will gain the benefit of its use.
Aligning two divs side-by-side
If you wrapped your divs, like this:
<div id="main">
<div id="sidebar"></div>
<div id="page-wrap"></div>
</div>
You could use this styling:
#main {
width: 800px;
margin: 0 auto;
}
#sidebar {
width: 200px;
height: 400px;
background: red;
float: left;
}
#page-wrap {
width: 600px;
background: #ffffff;
height: 400px;
margin-left: 200px;
}
This is a slightly different look though, so I'm not sure it's what you're after. This would center all 800px
as a unit, not the 600px
centered with the 200px
on the left side. The basic approach is your sidebar floats left, but inside the main div, and the #page-wrap
has the width of your sidebar as it's left margin to move that far over.
Update based on comments: For this off-centered look, you can do this:
<div id="page-wrap">
<div id="sidebar"></div>
</div>
With this styling:
#sidebar {
position: absolute;
left: -200px;
width: 200px;
height: 400px;
background: red;
}
#page-wrap {
position: relative;
width: 600px;
background: #ffffff;
height: 400px;
margin: 0 auto;
}
How do I count the number of rows and columns in a file using bash?
Perl solution:
perl -ane '$maxc = $#F if $#F > $maxc; END{$maxc++; print "max columns: $maxc\nrows: $.\n"}' file
If your input file is comma-separated:
perl -F, -ane '$maxc = $#F if $#F > $maxc; END{$maxc++; print "max columns: $maxc\nrows: $.\n"}' file
output:
max columns: 5
rows: 2
-a
autosplits input line to @F
array
$#F
is the number of columns -1
-F,
field separator of , instead of whitespace
$.
is the line number (number of rows)
Set QLineEdit to accept only numbers
The best is QSpinBox
.
And for a double value use QDoubleSpinBox
.
QSpinBox myInt;
myInt.setMinimum(-5);
myInt.setMaximum(5);
myInt.setSingleStep(1);// Will increment the current value with 1 (if you use up arrow key) (if you use down arrow key => -1)
myInt.setValue(2);// Default/begining value
myInt.value();// Get the current value
//connect(&myInt, SIGNAL(valueChanged(int)), this, SLOT(myValueChanged(int)));
Closing JFrame with button click
It appears to me that you have two issues here. One is that JFrame does not have a close
method, which has been addressed in the other answers.
The other is that you're having trouble referencing your JFrame. Within actionPerformed
, super
refers to ActionListener. To refer to the JFrame instance there, use MyExtendedJFrame.super
instead (you should also be able to use MyExtendedJFrame.this
, as I see no reason why you'd want to override the behaviour of dispose
or setVisible
).
How to use index in select statement?
The index hint is only available for Microsoft Dynamics database servers.
For traditional SQL Server, the filters you define in your 'Where' clause should persuade the engine to use any relevant indices...
Provided the engine's execution plan can efficiently identify how to read the information (whether a full table scan or an indexed scan) - it must compare the two before executing the statement proper, as part of its built-in performance optimiser.
However, you can force the optimiser to scan by using something like
Select *
From [yourtable] With (Index(0))
Where ...
Or to seek a particular index by using something like
Select *
From [yourtable] With (Index(1))
Where ...
The choice is yours. Look at the table's index properties in the object panel to get an idea of which index you want to use. It ought to match your filter(s).
For best results, list the filters which would return the fewest results first.
I don't know if I'm right in saying, but it seems like the query filters are sequential; if you get your sequence right, the optimiser shouldn't have to do it for you by comparing all the combinations, or at least not begin the comparison with the more expensive queries.
how to reset <input type = "file">
jQuery solution:
$('input').on('change',function(){
$(this).get(0).value = '';
$(this).get(0).type = '';
$(this).get(0).type = 'file';
});
Select Row number in postgres
SELECT tab.*,
row_number() OVER () as rnum
FROM tab;
Here's the relevant section in the docs.
P.S. This, in fact, fully matches the answer in the referenced question.
Checking if an object is null in C#
Your dataList is null as it has not been instantiated, judging by the code you have posted.
Try:
public List<Object> dataList = new List<Object>();
public bool AddData(ref Object data)
bool success = false;
try
{
if (!data.Equals(null)) // I've also used if(data != null) which hasn't worked either
{
dataList.Add(data); //NullReferenceException occurs here
success = doOtherStuff(data);
}
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
return success;
}
Why are Python lambdas useful?
First congrats that managed to figure out lambda. In my opinion this is really powerful construct to act with. The trend these days towards functional programming languages is surely an indicator that it neither should be avoided nor it will be redefined in the near future.
You just have to think a little bit different. I'm sure soon you will love it. But be careful if you deal only with python. Because the lambda is not a real closure, it is "broken" somehow: pythons lambda is broken
Object creation on the stack/heap?
A)
Object* o;
o = new Object();
``
B)
Object* o = new Object();
I think A and B has no difference. In both the cases o is a pointer to class Object. statement new Object() creates an object of class Object from heap memory. Assignment statement assigns the address of allocated memory to pointer o.
One thing I would like to mention that size of allocated memory from heap is always the sizeof(Object) not sizeof(Object) + sizeof(void *).
How to sort a data frame by date
Nowadays, it is the most efficient and comfortable to use lubridate and dplyr libraries.
lubridate
contains a number of functions that make parsing dates into POSIXct
or Date
objects easy. Here we use dmy
which automatically parses dates in Day, Month, Year
formats. Once your data is in a date format, you can sort it with dplyr::arrange
(or any other ordering function) as desired:
d$V3 <- lubridate::dmy(d$V3)
dplyr::arrange(d, V3)
Use of "global" keyword in Python
The keyword global
is only useful to change or create global variables in a local context, although creating global variables is seldom considered a good solution.
def bob():
me = "locally defined" # Defined only in local context
print(me)
bob()
print(me) # Asking for a global variable
The above will give you:
locally defined
Traceback (most recent call last):
File "file.py", line 9, in <module>
print(me)
NameError: name 'me' is not defined
While if you use the global
statement, the variable will become available "outside" the scope of the function, effectively becoming a global variable.
def bob():
global me
me = "locally defined" # Defined locally but declared as global
print(me)
bob()
print(me) # Asking for a global variable
So the above code will give you:
locally defined
locally defined
In addition, due to the nature of python, you could also use global
to declare functions, classes or other objects in a local context. Although I would advise against it since it causes nightmares if something goes wrong or needs debugging.
How do I connect to a terminal to a serial-to-USB device on Ubuntu 10.10 (Maverick Meerkat)?
I get get the same minicom error, "cannot open /dev/ttyUSB0: No such file or directory"
Three notes:
I get the error when the device attached to the serial port end of my Prolific Technology PL2303 USB/Serial adapter is turned off. After turning on the device (an embedded controller running Linux) minicom connected fine.
I have to run as super user (i.e. sudo minicom
)
Sometimes I have to unplug and plug back in the USB-to-serial adapter to get minicom to connect to it.
I am running Ubuntu 10.04 LTS (Lucid Lynx) under VMware (running on Windows 7). In this situation, make sure the device is attached to VM operating system by right clicking on the USB/Serial USB icon in the lower right of the VMware window and select Connect (Disconnect from Host).
Remember to press Ctrl + A to get minicom's prompt, and type X to exit the program. Just exiting the terminal session running minicom will leave the process running.
Do I cast the result of malloc?
From the Wikipedia:
Advantages to casting
Including the cast may allow a C program or function to compile as C++.
The cast allows for pre-1989 versions of malloc that originally returned a char *.
Casting can help the developer identify inconsistencies in type sizing should the destination pointer type change, particularly if the pointer is declared far from the malloc() call (although modern compilers and static analyzers can warn on such behaviour without requiring the cast).
Disadvantages to casting
Under the ANSI C standard, the cast is redundant.
Adding the cast may mask failure to include the header stdlib.h, in
which the prototype for malloc is found. In the absence of a
prototype for malloc, the standard requires that the C compiler
assume malloc returns an int. If there is no cast, a warning is
issued when this integer is assigned to the pointer; however, with
the cast, this warning is not produced, hiding a bug. On certain
architectures and data models (such as LP64 on 64-bit systems, where
long and pointers are 64-bit and int is 32-bit), this error can
actually result in undefined behaviour, as the implicitly declared
malloc returns a 32-bit value whereas the actually defined function
returns a 64-bit value. Depending on calling conventions and memory
layout, this may result in stack smashing. This issue is less likely
to go unnoticed in modern compilers, as they uniformly produce
warnings that an undeclared function has been used, so a warning will
still appear. For example, GCC's default behaviour is to show a
warning that reads "incompatible implicit declaration of built-in
function" regardless of whether the cast is present or not.
If the type of the pointer is changed at its declaration, one may
also, need to change all lines where malloc is called and cast.
Although malloc without casting is preferred method and most experienced programmers choose it, you should use whichever you like having aware of the issues.
i.e: If you need to compile C program as C++ (Although it is a separate language) you must cast the result of use malloc
.
Error 'tunneling socket' while executing npm install
After looking at all of the answers, the one that helped me was providing proxy values in-line with the install command. One of my frustrations was adding the domain to my username. This is not needed. I used the following example to install a specific version of Angular:
npm install -g @angular/[email protected] --proxy "http://username:password@proxy_server:proxy_port" --registry http://registry.npmjs.org
Insert an element at a specific index in a list and return the updated list
Most performance efficient approach
You may also insert the element using the slice indexing in the list. For example:
>>> a = [1, 2, 4]
>>> insert_at = 2 # Index at which you want to insert item
>>> b = a[:] # Created copy of list "a" as "b".
# Skip this step if you are ok with modifying the original list
>>> b[insert_at:insert_at] = [3] # Insert "3" within "b"
>>> b
[1, 2, 3, 4]
For inserting multiple elements together at a given index, all you need to do is to use a list
of multiple elements that you want to insert. For example:
>>> a = [1, 2, 4]
>>> insert_at = 2 # Index starting from which multiple elements will be inserted
# List of elements that you want to insert together at "index_at" (above) position
>>> insert_elements = [3, 5, 6]
>>> a[insert_at:insert_at] = insert_elements
>>> a # [3, 5, 6] are inserted together in `a` starting at index "2"
[1, 2, 3, 5, 6, 4]
To know more about slice indexing, you can refer: Understanding slice notation.
Note: In Python 3.x, difference of performance between slice indexing and list.index(...)
is significantly reduced and both are almost equivalent. However, in Python 2.x, this difference is quite noticeable. I have shared performance comparisons later in this answer.
Alternative using list comprehension (but very slow in terms of performance):
As an alternative, it can be achieved using list comprehension with enumerate
too. (But please don't do it this way. It is just for illustration):
>>> a = [1, 2, 4]
>>> insert_at = 2
>>> b = [y for i, x in enumerate(a) for y in ((3, x) if i == insert_at else (x, ))]
>>> b
[1, 2, 3, 4]
Performance comparison of all solutions
Here's the timeit
comparison of all the answers with list of 1000 elements on Python 3.9.1 and Python 2.7.16. Answers are listed in the order of performance for both the Python versions.
Python 3.9.1
My answer using sliced insertion - Fastest ( 2.25 µsec per loop)
python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
100000 loops, best of 5: 2.25 µsec per loop
Rushy Panchal's answer with most votes using list.insert(...)
- Second (2.33 µsec per loop)
python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
100000 loops, best of 5: 2.33 µsec per loop
ATOzTOA's accepted answer based on merge of sliced lists - Third (5.01 µsec per loop)
python3 -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]"
50000 loops, best of 5: 5.01 µsec per loop
My answer with List Comprehension and enumerate
- Fourth (very slow with 135 µsec per loop)
python3 -m timeit -s "a = list(range(1000))" "[y for i, x in enumerate(a) for y in ((3, x) if i == 500 else (x, )) ]"
2000 loops, best of 5: 135 µsec per loop
Python 2.7.16
My answer using sliced insertion - Fastest (2.09 µsec per loop)
python -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
100000 loops, best of 3: 2.09 µsec per loop
Rushy Panchal's answer with most votes using list.insert(...)
- Second (2.36 µsec per loop)
python -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
100000 loops, best of 3: 2.36 µsec per loop
ATOzTOA's accepted answer based on merge of sliced lists - Third (4.44 µsec per loop)
python -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]"
100000 loops, best of 3: 4.44 µsec per loop
My answer with List Comprehension and enumerate
- Fourth (very slow with 103 µsec per loop)
python -m timeit -s "a = list(range(1000))" "[y for i, x in enumerate(a) for y in ((3, x) if i == 500 else (x, )) ]"
10000 loops, best of 3: 103 µsec per loop
How are ssl certificates verified?
Here is a very simplified explanation:
Your web browser downloads the web server's certificate, which contains the public key of the web server. This certificate is signed with the private key of a trusted certificate authority.
Your web browser comes installed with the public keys of all of the major certificate authorities. It uses this public key to verify that the web server's certificate was indeed signed by the trusted certificate authority.
The certificate contains the domain name and/or ip address of the web server. Your web browser confirms with the certificate authority that the address listed in the certificate is the one to which it has an open connection.
Your web browser generates a shared symmetric key which will be used to encrypt the HTTP traffic on this connection; this is much more efficient than using public/private key encryption for everything. Your browser encrypts the symmetric key with the public key of the web server then sends it back, thus ensuring that only the web server can decrypt it, since only the web server has its private key.
Note that the certificate authority (CA) is essential to preventing man-in-the-middle attacks. However, even an unsigned certificate will prevent someone from passively listening in on your encrypted traffic, since they have no way to gain access to your shared symmetric key.
Interactive shell using Docker Compose
You need to include the following lines in your docker-compose.yml:
version: "3"
services:
app:
image: app:1.2.3
stdin_open: true # docker run -i
tty: true # docker run -t
The first corresponds to -i
in docker run
and the second to -t
.
PHP save image file
Note: you should use the accepted answer if possible. It's better than mine.
It's quite easy with the GD library.
It's built in usually, you probably have it (use phpinfo()
to check)
$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");
imagejpeg($image, "folder/file.jpg");
The above answer is better (faster) for most situations, but with GD you can also modify it in some form (cropping for example).
$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");
imagecopy($image, $image, 0, 140, 0, 0, imagesx($image), imagesy($image));
imagejpeg($image, "folder/file.jpg");
This only works if allow_url_fopen
is true
(it is by default)
Interesting 'takes exactly 1 argument (2 given)' Python error
The call
e.extractAll("th")
for a regular method extractAll()
is indeed equivalent to
Extractor.extractAll(e, "th")
These two calls are treated the same in all regards, including the error messages you get.
If you don't need to pass the instance to a method, you can use a staticmethod
:
@staticmethod
def extractAll(tag):
...
which can be called as e.extractAll("th")
. But I wonder why this is a method on a class at all if you don't need to access any instance.
NuGet Packages are missing
A combination of the 2 answers worked for me. First I modified the .csproj file to remove the reference to 1.0.0 version
< Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild" >
----Error---
< /Target>
and then did
Update-Package -Reinstall
from the and it worked.
MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource
I catch the next case about cors. Maybe it will be useful to somebody.
If you add feature 'WebDav Redirector' to your server, PUT and DELETE requests are failed.
So, you will need to remove 'WebDAVModule' from your IIS server:
- "In the IIS modules Configuration, loop up the WebDAVModule, if your web server has it, then remove it".
Or add to your config:
<system.webServer>
<modules>
<remove name="WebDAVModule"/>
</modules>
<handlers>
<remove name="WebDAV" />
...
</handlers>
How does String substring work in Swift
I'm quite mechanical thinking. Here are the basics...
Swift 4
Swift 5
let t = "abracadabra"
let start1 = t.index(t.startIndex, offsetBy:0)
let end1 = t.index(t.endIndex, offsetBy:-5)
let start2 = t.index(t.endIndex, offsetBy:-5)
let end2 = t.index(t.endIndex, offsetBy:0)
let t2 = t[start1 ..< end1]
let t3 = t[start2 ..< end2]
//or a shorter form
let t4 = t[..<end1]
let t5 = t[start2...]
print("\(t2) \(t3) \(t)")
print("\(t4) \(t5) \(t)")
// result:
// abraca dabra abracadabra
The result is a substring, meaning that it is a part of the original string. To get a full blown separate string just use e.g.
String(t3)
String(t4)
This is what I use:
let mid = t.index(t.endIndex, offsetBy:-5)
let firstHalf = t[..<mid]
let secondHalf = t[mid...]
How to get selected option using Selenium WebDriver with Java
You should be able to get the text using getText()
(for the option element you got using getFirstSelectedOption()
):
Select select = new Select(driver.findElement(By.xpath("//select")));
WebElement option = select.getFirstSelectedOption();
String defaultItem = option.getText();
System.out.println(defaultItem );
Pushing an existing Git repository to SVN
Git -> SVN with complete commit history
I had a Git project and had to move it to SVN. This is how I made it, keeping the whole commit history. The only thing that gets lost is the original commit time since libSVN will set the local time when we do git svn dcommit
.
Howto:
Have a SVN repository where we want to import our stuff to and clone it with git-svn:
git svn clone https://path.to/svn/repository repo.git-svn`
Go there:
cd repo.git-svn
Add the remote of the Git repository (in this example I'm using C:/Projects/repo.git). You want to push to SVN and give it the name old-git:
git remote add old-git file:///C/Projects/repo.git/
Fetch the information from the master branch from the old-git repository to the current repository:
git fetch old-git master
Checkout the master branch of the old-git remote into a new branch called old in the current repository:
git checkout -b old old-git/master`
Rebase to put the HEAD on top of old-git/master. This will maintain all your commits. What this does basically is to take all of your work done in Git and put it on top of the work you are accessing from SVN.
git rebase master
Now go back to your master branch:
git checkout master
And you can see that you have a clean commit history. This is what you want to push to SVN.
Push your work to SVN:
git svn dcommit
That's all. It is very clean, no hacking, and everything works perfectly out of the box. Enjoy.
How do I check for a network connection?
Microsoft windows vista and 7 use NCSI (Network Connectivity Status Indicator) technic:
- NCSI performs a DNS lookup on www.msftncsi.com, then requests http://www.msftncsi.com/ncsi.txt. This file is a plain-text file and contains only the text 'Microsoft NCSI'.
- NCSI sends a DNS lookup request for dns.msftncsi.com. This DNS address should resolve to 131.107.255.255. If the address does not match, then it is assumed that the internet connection is not functioning correctly.
CSS :selected pseudo class similar to :checked, but for <select> elements
the :checked
pseudo-class initially applies to such elements that have the HTML4 selected
and checked
attributes
Source: w3.org
So, this CSS works, although styling the color
is not possible in every browser:
option:checked { color: red; }
An example of this in action, hiding the currently selected item from the drop down list.
_x000D_
_x000D_
option:checked { display:none; }
_x000D_
<select>_x000D_
<option>A</option>_x000D_
<option>B</option>_x000D_
<option>C</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_
To style the currently selected option in the closed dropdown as well, you could try reversing the logic:
select { color: red; }
option:not(:checked) { color: black; } /* or whatever your default style is */
Is it possible to program iPhone in C++
You have to use Objective C to interface with the Cocoa API, so there is no choice. Of course, you can use as much C++ as you like behind the scenes (Objective C++ makes this easy).
It is an insane language indeed, but it's also... kind of fun to use once you're a bit used to it. :-)
Is there a library function for Root mean square error (RMSE) in python?
Here's an example code that calculates the RMSE between two polygon file formats PLY
. It uses both the ml_metrics
lib and the np.linalg.norm
:
import sys
import SimpleITK as sitk
from pyntcloud import PyntCloud as pc
import numpy as np
from ml_metrics import rmse
if len(sys.argv) < 3 or sys.argv[1] == "-h" or sys.argv[1] == "--help":
print("Usage: compute-rmse.py <input1.ply> <input2.ply>")
sys.exit(1)
def verify_rmse(a, b):
n = len(a)
return np.linalg.norm(np.array(b) - np.array(a)) / np.sqrt(n)
def compare(a, b):
m = pc.from_file(a).points
n = pc.from_file(b).points
m = [ tuple(m.x), tuple(m.y), tuple(m.z) ]; m = m[0]
n = [ tuple(n.x), tuple(n.y), tuple(n.z) ]; n = n[0]
v1, v2 = verify_rmse(m, n), rmse(m,n)
print(v1, v2)
compare(sys.argv[1], sys.argv[2])
Delete files older than 10 days using shell script in Unix
Just spicing up the shell script above to delete older files but with logging and calculation of elapsed time
#!/bin/bash
path="/data/backuplog/"
timestamp=$(date +%Y%m%d_%H%M%S)
filename=log_$timestamp.txt
log=$path$filename
days=7
START_TIME=$(date +%s)
find $path -maxdepth 1 -name "*.txt" -type f -mtime +$days -print -delete >> $log
echo "Backup:: Script Start -- $(date +%Y%m%d_%H%M)" >> $log
... code for backup ...or any other operation .... >> $log
END_TIME=$(date +%s)
ELAPSED_TIME=$(( $END_TIME - $START_TIME ))
echo "Backup :: Script End -- $(date +%Y%m%d_%H%M)" >> $log
echo "Elapsed Time :: $(date -d 00:00:$ELAPSED_TIME +%Hh:%Mm:%Ss) " >> $log
The code adds a few things.
- log files named with a timestamp
- log folder specified
- find looks for *.txt files only in the log folder
- type f ensures you only deletes files
- maxdepth 1 ensures you dont enter subfolders
- log files older than 7 days are deleted ( assuming this is for a backup log)
- notes the start / end time
- calculates the elapsed time for the backup operation...
Note: to test the code, just use -print instead of -print -delete. But do check your path carefully though.
Note: Do ensure your server time is set correctly via date - setup timezone/ntp correctly . Additionally check file times with 'stat filename'
Note: mtime can be replaced with mmin for better control as mtime discards all fractions (older than 2 days (+2 days) actually means 3 days ) when it deals with getting the timestamps of files in the context of days
-mtime +$days ---> -mmin +$((60*24*$days))
What's the difference between disabled="disabled" and readonly="readonly" for HTML form input fields?
Disabled means that no data from that form element will be submitted when the form is submitted. Read-only means any data from within the element will be submitted, but it cannot be changed by the user.
For example:
<input type="text" name="yourname" value="Bob" readonly="readonly" />
This will submit the value "Bob" for the element "yourname".
<input type="text" name="yourname" value="Bob" disabled="disabled" />
This will submit nothing for the element "yourname".
Not an enclosing class error Android Studio
It should be
Intent myIntent = new Intent(this, Katra_home.class);
startActivity(myIntent);
You have to use existing activity context to start new activity, new activity is not created yet, and you cannot use its context or call methods upon it.
not an enclosing class error is thrown because of your usage of this
keyword. this
is a reference to the current object — the object whose method or constructor is being called. With this
you can only refer to any member of the current object from within an instance method or a constructor.
Katra_home.this
is invalid construct
How do you get the contextPath from JavaScript, the right way?
I render context path to attribute of link tag with id="contextPahtHolder" and then obtain it in JS code. For example:
<html>
<head>
<link id="contextPathHolder" data-contextPath="${pageContext.request.contextPath}"/>
<body>
<script src="main.js" type="text/javascript"></script>
</body>
</html>
main.js
var CONTEXT_PATH = $('#contextPathHolder').attr('data-contextPath');
$.get(CONTEXT_PATH + '/action_url', function() {});
If context path is empty (like in embedded servlet container istance), it will be empty string. Otherwise it contains contextPath string
Check if Cookie Exists
You need to use HttpContext.Current.Request.Cookies
, not Response.Cookies
.
Side note: cookies are copied to Request on Response.Cookies.Add
, which makes check on either of them to behave the same for newly added cookies. But incoming cookies are never reflected in Response
.
This behavior is documented in HttpResponse.Cookies property:
After you add a cookie by using the HttpResponse.Cookies collection, the cookie is immediately available in the HttpRequest.Cookies collection, even if the response has not been sent to the client.
What is the intended use-case for git stash?
If you hit git stash
when you have changes in the working copy (not in the staging area), git will create a stashed object and pushes onto the stack of stashes (just like you did git checkout -- .
but you won't lose changes). Later, you can pop from the top of the stack.
Response.Redirect with POST instead of Get?
You can use this aproach:
Response.Clear();
StringBuilder sb = new StringBuilder();
sb.Append("<html>");
sb.AppendFormat(@"<body onload='document.forms[""form""].submit()'>");
sb.AppendFormat("<form name='form' action='{0}' method='post'>",postbackUrl);
sb.AppendFormat("<input type='hidden' name='id' value='{0}'>", id);
// Other params go here
sb.Append("</form>");
sb.Append("</body>");
sb.Append("</html>");
Response.Write(sb.ToString());
Response.End();
As result right after client will get all html from server the event onload take place that triggers form submit and post all data to defined postbackUrl.
How can apply multiple background color to one div
With :after and :before you can do that.
HTML:
<div class="a"> </div>
<div class="b"> </div>
<div class="c"> </div>
CSS:
div {
height: 100px;
position: relative;
}
.a {
background: #9C9E9F;
}
.b {
background: linear-gradient(to right, #9c9e9f, #f6f6f6);
}
.a:after, .c:before, .c:after {
content: '';
width: 50%;
height: 100%;
top: 0;
right: 0;
display: block;
position: absolute;
}
.a:after {
background: #f6f6f6;
}
.c:before {
background: #9c9e9f;
left: 0;
}
.c:after {
background: #33CCFF;
right: 0;
height: 80%;
}
And a demo.
Differences between hard real-time, soft real-time, and firm real-time?
The definition has expanded over the years to the detriment of the term. What is now called "Hard" real-time is what used to be simply called real-time. So systems in which missing timing windows (rather than single-sided time deadlines) would result incorrect data or incorrect behavior should be consider real-time. Systems without that characteristic would be considered non-real-time.
That's not to say that time isn't of interest in non-real-time systems, it just means that timing requirements in such systems don't result in fundamentally incorrect results.
Static constant string (class member)
You can either go for the const char*
solution mentioned above, but then if you need string all the time, you're going to have a lot of overhead.
On the other hand, static string needs dynamic initialization, thus if you want to use its value during another global/static variable's initialization, you might hit the problem of initialization order. To avoid that, the cheapest thing is accessing the static string object through a getter, which checks if your object is initialized or not.
//in a header
class A{
static string s;
public:
static string getS();
};
//in implementation
string A::s;
namespace{
bool init_A_s(){
A::s = string("foo");
return true;
}
bool A_s_initialized = init_A_s();
}
string A::getS(){
if (!A_s_initialized)
A_s_initialized = init_A_s();
return s;
}
Remember to only use A::getS()
. Because any threading can only started by main()
, and A_s_initialized
is initialized before main()
, you don't need locks even in a multithreaded environment. A_s_initialized
is 0 by default (before the dynamic initialization), so if you use getS()
before s is initialized, you call the init function safely.
Btw, in the answer above: "static const std::string RECTANGLE() const" , static functions cannot be const
because they cannot change the state if any object anyway (there is no this pointer).
HTML favicon won't show on google chrome
Note if you have so many tabs open that Google Chrome is only showing the favicons then Google Chrome won't show the favicon for the selected tab, so if you keep reloading the tab with your page loaded in order to see your new favicon you will only see the text of your page's title.
You will need to reload your page, and then select a different tab in order to see your favicon.
What is HTML5 ARIA?
What is ARIA?
ARIA emerged as a way to address the accessibility problem of using a markup language intended for documents, HTML, to build user interfaces (UI). HTML includes a great many features to deal with documents (P, h3,UL,TABLE) but only basic UI elements such as A, INPUT and BUTTON. Windows and other operating systems support APIs that allow (Assistive Technology) AT to access the functionality of UI controls. Internet Explorer and other browsers map the native HTML elements to the accessibility API, but the html controls are not as rich as the controls common on desktop operating systems, and are not enough for modern web applications Custom controls can extend html elements to provide the rich UI needed for modern web applications. Before ARIA, the browser had no way to expose this extra richness to the accessibility API or AT. The classic example of this issue is adding a click handler to an image. It creates what appears to be a clickable button to a mouse user, but is still just an image to a keyboard or AT user.
The solution was to create a set of attributes that allow developers to extend HTML with UI semantics. The ARIA term for a group of HTML elements that have custom functionality and use ARIA attributes to map these functions to accessibility APIs is a “Widget. ARIA also provides a means for authors to document the role of content itself, which in turn, allows AT to construct alternate navigation mechanisms for the content that are much easier to use than reading the full text or only iterating over a list of the links.
It is important to remember that in simple cases, it is much preferred to use native HTML controls and style them rather than using ARIA. That is don’t reinvent wheels, or checkboxes, if you don’t have to.
Fortunately, ARIA markup can be added to existing sites without changing the behavior for mainstream users. This greatly reduces the cost of modifying and testing the website or application.
How to see if a directory exists or not in Perl?
Use -d
(full list of file tests)
if (-d "cgi-bin") {
# directory called cgi-bin exists
}
elsif (-e "cgi-bin") {
# cgi-bin exists but is not a directory
}
else {
# nothing called cgi-bin exists
}
As a note, -e
doesn't distinguish between files and directories. To check if something exists and is a plain file, use -f
.
How to finish Activity when starting other activity in Android?
You need to intent
your current context
to another activity first with startActivity
. After that you can finish
your current activity
from where you redirect.
Intent intent = new Intent(this, FirstActivity.class);// New activity
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish(); // Call once you redirect to another activity
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
- Clears the activity stack. If you don't want to clear the activity stack. PLease don't use that flag then.
MVC 3: How to render a view without its layout page when loaded via ajax?
With ASP.NET 5 there is no Request variable available anymore. You can access it now with Context.Request
Also there is no IsAjaxRequest() Method anymore, you have to write it by yourself, for example in Extensions\HttpRequestExtensions.cs
using System;
using Microsoft.AspNetCore.Http;
namespace Microsoft.AspNetCore.Mvc
{
public static class HttpRequestExtensions
{
public static bool IsAjaxRequest(this HttpRequest request)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
return (request.Headers != null) && (request.Headers["X-Requested-With"] == "XMLHttpRequest");
}
}
}
I searched for a while now on this and hope that will help some others too ;)
Resource: https://github.com/aspnet/AspNetCore/issues/2729
How to check if my string is equal to null?
I'd do something like this:
( myString != null && myString.length() > 0 )
? doSomething() : System.out.println("Non valid String");
- Testing for null checks whether myString contains an instance of String.
- length() returns the length and is equivalent to equals("").
- Checking if myString is null first will avoid a NullPointerException.
Replace last occurrence of a string in a string
$string = 'this is my world, not my world';
$find = 'world';
$replace = 'farm';
$result = preg_replace(strrev("/$find/"),strrev($replace),strrev($string),1);
echo strrev($result); //output: this is my world, not my farm
How to call Base Class's __init__ method from the child class?
You could use super(ChildClass, self).__init__()
class BaseClass(object):
def __init__(self, *args, **kwargs):
pass
class ChildClass(BaseClass):
def __init__(self, *args, **kwargs):
super(ChildClass, self).__init__(*args, **kwargs)
Your indentation is incorrect, here's the modified code:
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
class ElectricCar(Car):
def __init__(self, battery_type, model, color, mpg):
self.battery_type=battery_type
super(ElectricCar, self).__init__(model, color, mpg)
car = ElectricCar('battery', 'ford', 'golden', 10)
print car.__dict__
Here's the output:
{'color': 'golden', 'mpg': 10, 'model': 'ford', 'battery_type': 'battery'}
Remove border from buttons
I was having the same problem and even though I was styling my button in CSS it would never pick up the border:none
but what worked was adding a style directly on the input button like so:
<div style="text-align:center;">
<input type="submit" class="SubmitButtonClass" style="border:none;" value="" />
</div>
Setting up maven dependency for SQL Server
It looks like Microsoft has published some their drivers to maven central:
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.1.0.jre8</version>
</dependency>
Setting onClickListener for the Drawable right of an EditText
You don't have access to the right image as far my knowledge, unless you override the onTouch
event. I suggest to use a RelativeLayout
, with one editText
and one imageView
, and set OnClickListener
over the image view as below:
<RelativeLayout
android:id="@+id/rlSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:drawable/edit_text"
android:padding="5dip" >
<EditText
android:id="@+id/txtSearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="@+id/imgSearch"
android:background="#00000000"
android:ems="10"/>
<ImageView
android:id="@+id/imgSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:src="@drawable/btnsearch" />
</RelativeLayout>
Running a simple shell script as a cronjob
The easiest way would be to use a GUI:
For Gnome use gnome-schedule (universe)
sudo apt-get install gnome-schedule
For KDE use kde-config-cron
It should be pre installed on Kubuntu
But if you use a headless linux or don´t want GUI´s you may use:
crontab -e
If you type it into Terminal you´ll get a table.
You have to insert your cronjobs now.
Format a job like this:
* * * * * YOURCOMMAND
- - - - -
| | | | |
| | | | +----- Day in Week (0 to 7) (Sunday is 0 and 7)
| | | +------- Month (1 to 12)
| | +--------- Day in Month (1 to 31)
| +----------- Hour (0 to 23)
+------------- Minute (0 to 59)
There are some shorts, too (if you don´t want the *):
@reboot --> only once at startup
@daily ---> once a day
@midnight --> once a day at midnight
@hourly --> once a hour
@weekly --> once a week
@monthly --> once a month
@annually --> once a year
@yearly --> once a year
If you want to use the shorts as cron (because they don´t work or so):
@daily --> 0 0 * * *
@midnight --> 0 0 * * *
@hourly --> 0 * * * *
@weekly --> 0 0 * * 0
@monthly --> 0 0 1 * *
@annually --> 0 0 1 1 *
@yearly --> 0 0 1 1 *
copy db file with adb pull results in 'permission denied' error
This generic solution should work on all rooted devices:
adb shell "su -c cat /data/data/com.android.providers.contacts/databases/contacts2.db" > contacts2.d
The command connects as shell, then executes cat
as root and collects the output into a local file.
In opposite to @guest-418 s solution, one does not have to dig for the user in question.
Plus If you get greedy and want all the db's at once (eg. for backup)
for i in `adb shell "su -c find /data -name '*.db'"`; do
mkdir -p ".`dirname $i`"
adb shell "su -c cat $i" > ".$i"
done
This adds a mysteryous question mark to the end of the filename, but it is still readable.
How to get size of mysql database?
Alternatively you can directly jump into data directory and check for combined size of v3.myd, v3. myi and v3. frm files (for myisam) or v3.idb & v3.frm (for innodb).
Using Python's ftplib to get a directory listing, portably
That helped me with my code.
When I tried feltering only a type of files and show them on screen by adding a condition that tests on each line.
Like this
elif command == 'ls':
print("directory of ", ftp.pwd())
data = []
ftp.dir(data.append)
for line in data:
x = line.split(".")
formats=["gz", "zip", "rar", "tar", "bz2", "xz"]
if x[-1] in formats:
print ("-", line)
Getting a Request.Headers value
The following code should allow you to check for the existance of the header you're after in Request.Headers
:
if (Request.Headers.AllKeys.Contains("XYZComponent"))
{
// Can now check if the value is true:
var value = Convert.ToBoolean(Request.Headers["XYZComponent"]);
}
Turn a number into star rating display using jQuery and CSS
DEMO
You can do it with 2 images only. 1 blank stars, 1 filled stars.
Overlay filled image on the top of the other one. and convert rating number into percentage and use it as width of fillter image.
.containerdiv {
border: 0;
float: left;
position: relative;
width: 300px;
}
.cornerimage {
border: 0;
position: absolute;
top: 0;
left: 0;
overflow: hidden;
}
img{
max-width: 300px;
}
Python function pointer
eval(compile(myvar,'<str>','eval'))(myargs)
compile(...,'eval') allows only a single statement, so that there can't be arbitrary commands after a call, or there will be a SyntaxError. Then a tiny bit of validation can at least constrain the expression to something in your power, like testing for 'mypackage' to start.
What is the best way to generate a unique and short file name in Java
I use the timestamp
i.e
new File( simpleDateFormat.format( new Date() ) );
And have the simpleDateFormat initialized to something like as:
new SimpleDateFormat("File-ddMMyy-hhmmss.SSS.txt");
EDIT
What about
new File(String.format("%s.%s", sdf.format( new Date() ),
random.nextInt(9)));
Unless the number of files created in the same second is too high.
If that's the case and the name doesn't matters
new File( "file."+count++ );
:P
combining results of two select statements
Probably you use Microsoft SQL Server which support Common Table Expressions (CTE) (see http://msdn.microsoft.com/en-us/library/ms190766.aspx) which are very friendly for query optimization. So I suggest you my favor construction:
WITH GetNumberOfPlans(Id,NumberOfPlans) AS (
SELECT tableA.Id, COUNT(tableC.Id)
FROM tableC
RIGHT OUTER JOIN tableA ON tableC.tableAId = tableA.Id
GROUP BY tableA.Id
),GetUserInformation(Id,Name,Owner,ImageUrl,
CompanyImageUrl,NumberOfUsers) AS (
SELECT tableA.Id, tableA.Name, tableB.Username AS Owner, tableB.ImageUrl,
tableB.CompanyImageUrl,COUNT(tableD.UserId),p.NumberOfPlans
FROM tableA
INNER JOIN tableB ON tableB.Id = tableA.Owner
RIGHT OUTER JOIN tableD ON tableD.tableAId = tableA.Id
GROUP BY tableA.Name, tableB.Username, tableB.ImageUrl, tableB.CompanyImageUrl
)
SELECT u.Id,u.Name,u.Owner,u.ImageUrl,u.CompanyImageUrl
,u.NumberOfUsers,p.NumberOfPlans
FROM GetUserInformation AS u
INNER JOIN GetNumberOfPlans AS p ON p.Id=u.Id
After some experiences with CTE you will be find very easy to write code using CTE and you will be happy with the performance.
Is it possible to define more than one function per file in MATLAB, and access them from outside that file?
The only way to have multiple, separately accessible functions in a single file is to define STATIC METHODS using object-oriented programming. You'd access the function as myClass.static1()
, myClass.static2()
etc.
OOP functionality is only officially supported since R2008a, so unless you want to use the old, undocumented OOP syntax, the answer for you is no, as explained by @gnovice.
EDIT
One more way to define multiple functions inside a file that are accessible from the outside is to create a function that returns multiple function handles. In other words, you'd call your defining function as [fun1,fun2,fun3]=defineMyFunctions
, after which you could use out1=fun1(inputs)
etc.
Java string split with "." (dot)
This is because .
is a reserved character in regular expression, representing any character.
Instead, we should use the following statement:
String extensionRemoved = filename.split("\\.")[0];
Custom "confirm" dialog in JavaScript?
To enable you to use the confirm box like the normal confirm dialog, I would use Promises which will enable you to await on the result of the outcome and then act on this, rather than having to use callbacks.
This will allow you to follow the same pattern you have in other parts of your code with code such as...
const confirm = await ui.confirm('Are you sure you want to do this?');
if(confirm){
alert('yes clicked');
} else{
alert('no clicked');
}
See codepen for example, or run the snippet below.
https://codepen.io/larnott/pen/rNNQoNp
_x000D_
_x000D_
const ui = {_x000D_
confirm: async (message) => createConfirm(message)_x000D_
}_x000D_
_x000D_
const createConfirm = (message) => {_x000D_
return new Promise((complete, failed)=>{_x000D_
$('#confirmMessage').text(message)_x000D_
_x000D_
$('#confirmYes').off('click');_x000D_
$('#confirmNo').off('click');_x000D_
_x000D_
$('#confirmYes').on('click', ()=> { $('.confirm').hide(); complete(true); });_x000D_
$('#confirmNo').on('click', ()=> { $('.confirm').hide(); complete(false); });_x000D_
_x000D_
$('.confirm').show();_x000D_
});_x000D_
}_x000D_
_x000D_
const saveForm = async () => {_x000D_
const confirm = await ui.confirm('Are you sure you want to do this?');_x000D_
_x000D_
if(confirm){_x000D_
alert('yes clicked');_x000D_
} else{_x000D_
alert('no clicked');_x000D_
}_x000D_
}
_x000D_
body {_x000D_
margin: 0px;_x000D_
font-family: "Arial";_x000D_
}_x000D_
_x000D_
.example {_x000D_
padding: 20px;_x000D_
}_x000D_
_x000D_
input[type=button] {_x000D_
padding: 5px 10px;_x000D_
margin: 10px 5px;_x000D_
border-radius: 5px;_x000D_
cursor: pointer;_x000D_
background: #ddd;_x000D_
border: 1px solid #ccc;_x000D_
}_x000D_
input[type=button]:hover {_x000D_
background: #ccc;_x000D_
}_x000D_
_x000D_
.confirm {_x000D_
display: none;_x000D_
}_x000D_
.confirm > div:first-of-type {_x000D_
position: fixed;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
background: rgba(0, 0, 0, 0.5);_x000D_
top: 0px;_x000D_
left: 0px;_x000D_
}_x000D_
.confirm > div:last-of-type {_x000D_
padding: 10px 20px;_x000D_
background: white;_x000D_
position: absolute;_x000D_
width: auto;_x000D_
height: auto;_x000D_
left: 50%;_x000D_
top: 50%;_x000D_
transform: translate(-50%, -50%);_x000D_
border-radius: 5px;_x000D_
border: 1px solid #333;_x000D_
}_x000D_
.confirm > div:last-of-type div:first-of-type {_x000D_
min-width: 150px;_x000D_
padding: 10px;_x000D_
}_x000D_
.confirm > div:last-of-type div:last-of-type {_x000D_
text-align: right;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="example">_x000D_
<input type="button" onclick="saveForm()" value="Save" />_x000D_
</div>_x000D_
_x000D_
<!-- Hidden confirm markup somewhere at the bottom of page -->_x000D_
_x000D_
<div class="confirm">_x000D_
<div></div>_x000D_
<div>_x000D_
<div id="confirmMessage"></div>_x000D_
<div>_x000D_
<input id="confirmYes" type="button" value="Yes" />_x000D_
<input id="confirmNo" type="button" value="No" />_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
problem with <select> and :after with CSS in WebKit
I haven't checked this extensively, but I'm under the impression that this isn't (yet?) possible, due to the way in which select
elements are generated by the OS on which the browser runs, rather than the browser itself.
Is it possible to pass a flag to Gulp to have it run tasks in different ways?
We wanted to pass a different config file for different environments -- one for production, dev and testing. This is the code in the gulp file:
_x000D_
_x000D_
//passing in flag to gulp to set environment_x000D_
//var env = gutil.env.env;_x000D_
_x000D_
if (typeof gutil.env.env === 'string') {_x000D_
process.env.NODE_ENV = gutil.env.env;_x000D_
}
_x000D_
_x000D_
_x000D_
This is the code in the app.js file:
_x000D_
_x000D_
if(env === 'testing'){_x000D_
var Config = require('./config.testing.js');_x000D_
var Api = require('./api/testing.js')(Config.web);_x000D_
}_x000D_
else if(env === 'dev'){_x000D_
Config = require('./config.dev.js');_x000D_
Api = require('./api/dev.js').Api;_x000D_
}_x000D_
else{_x000D_
Config = require('./config.production.js');_x000D_
Api = require('./api/production.js')(Config.web);_x000D_
}
_x000D_
_x000D_
_x000D_
And then to run it gulp --env=testing
How to improve Netbeans performance?
In order to improve Netbeans startup and build times one should (in this order):
- Make sure that one has enough free RAM memory (4GB Windows is enough on my 64-bit system)
- Buy an SSD, it makes all the difference in startup time and build time (my project build time wend from 60 seconds to 6 seconds!)
- Watch out for the virus scanner, they can slow down random file access considerably (make sure they don’t scan your .java and .class files!)
- Buy the fastest processor you can get your hands on.
Filtering by Multiple Specific Model Properties in AngularJS (in OR relationship)
Pretty straight forward approach using filterBy in angularJs
For working plnkr follow this link
http://plnkr.co/edit/US6xE4h0gD5CEYV0aMDf?p=preview
This has specially used a single property to search against multiple column but not all.
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script data-require="[email protected]" data-semver="1.4.1" src="https://code.angularjs.org/1.4.1/angular.js"></script>
<script data-require="[email protected]" data-semver="0.5.2" src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.2/angular-filter.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="myCtrl as vm">
<input type="text" placeholder="enter your search text" ng-model="vm.searchText" />
<table>
<tr ng-repeat="row in vm.tableData | filterBy: ['col1','col2']: vm.searchText">
<td>{{row.col1}}</td>
<td>{{row.col2}}</td>
<td>{{row.col3}}</td>
</tr>
</table>
<p>This will show filter from <b>two columns</b> only(col1 and col2) . Not from all. Whatever columns you add into filter array they
will be searched. all columns will be used by default if you use <b>filter: vm.searchText</b></p>
</body>
</html>
controller
// Code goes here
(function(){
var myApp = angular.module('myApp',['angular.filter']);
myApp.controller('myCtrl', function($scope){
var vm= this;
vm.x = 20;
vm.tableData = [
{
col1: 'Ashok',
col2: 'Tewatia',
col3: '12'
},{
col1: 'Babita',
col2: 'Malik',
col3: '34'
},{
col1: 'Dinesh',
col2: 'Tewatia',
col3: '56'
},{
col1: 'Sabita',
col2: 'Malik',
col3: '78'
}
];
})
})();
Difference between Java SE/EE/ME?
Here are some differences in terms of APIs
Java SE includes has the following APIs and many more
- applet
- awt
- rmi
- jdbc
- swing
- collections
- xml binding
- JavaFX (Merged to Java SE 8)
- Java 8 Collections Streaming API
- Java 9 Reactive Streams API
- Java 9 HTTP/2 API
Java EE includes the following APIs and many more
- servlet
- websocket
- java faces
- dependency injection
- ejb
- persistence
- transaction
- jms
- batch api
Java ME includes the following APIs and many more
- Wireless Messaging
- Java ME Web Services
- Security and Trust Services API
- Location
- Mobile XML API
Hope this helps.
Using Java 8's Optional with Stream::flatMap
As my previous answer appeared not to be very popular, I will give this another go.
A short answer:
You are mostly on a right track. The shortest code to get to your desired output I could come up with is this:
things.stream()
.map(this::resolve)
.filter(Optional::isPresent)
.findFirst()
.flatMap( Function.identity() );
This will fit all your requirements:
- It will find first response that resolves to a nonempty
Optional<Result>
- It calls
this::resolve
lazily as needed
this::resolve
will not be called after first non-empty result
- It will return
Optional<Result>
Longer answer
The only modification compared to OP initial version was that I removed .map(Optional::get)
before call to .findFirst()
and added .flatMap(o -> o)
as the last call in the chain.
This has a nice effect of getting rid of the double-Optional, whenever stream finds an actual result.
You can't really go any shorter than this in Java.
The alternative snippet of code using the more conventional for
loop technique is going to be about same number of lines of code and have more or less same order and number of operations you need to perform:
- Calling
this.resolve
,
- filtering based on
Optional.isPresent
- returning the result and
- some way of dealing with negative result (when nothing was found)
Just to prove that my solution works as advertised, I wrote a small test program:
public class StackOverflow {
public static void main( String... args ) {
try {
final int integer = Stream.of( args )
.peek( s -> System.out.println( "Looking at " + s ) )
.map( StackOverflow::resolve )
.filter( Optional::isPresent )
.findFirst()
.flatMap( o -> o )
.orElseThrow( NoSuchElementException::new )
.intValue();
System.out.println( "First integer found is " + integer );
}
catch ( NoSuchElementException e ) {
System.out.println( "No integers provided!" );
}
}
private static Optional<Integer> resolve( String string ) {
try {
return Optional.of( Integer.valueOf( string ) );
}
catch ( NumberFormatException e )
{
System.out.println( '"' + string + '"' + " is not an integer");
return Optional.empty();
}
}
}
(It does have few extra lines for debugging and verifying that only as many calls to resolve as needed...)
Executing this on a command line, I got the following results:
$ java StackOferflow a b 3 c 4
Looking at a
"a" is not an integer
Looking at b
"b" is not an integer
Looking at 3
First integer found is 3
CSS Outside Border
I think you've got your understanding of the two properties off a little. Border affects the outside edge of the element, making the element different in size. Outline will not change the size or position of the element (takes up no space) and goes outside the border. From your description you want to use the border property.
Look at the simple example below in your browser:
_x000D_
_x000D_
<div style="height: 100px; width: 100px; background: black; color: white; outline: thick solid #00ff00">SOME TEXT HERE</div>_x000D_
_x000D_
<div style="height: 100px; width: 100px; background: black; color: white; border-left: thick solid #00ff00">SOME TEXT HERE</div>
_x000D_
_x000D_
_x000D_
Notice how the border pushes the bottom div over, but the outline doesn't move the top div and the outline actually overlaps the bottom div.
You can read more about it here:
Border
Outline
Relative Paths in Javascript in an external file
A proper solution is using a css class instead of writing src in js file.
For example instead of using:
$(this).css("background", "url('../Images/filters_collapse.jpg')");
use:
$(this).addClass("xxx");
and in a css file that is loaded in the page write:
.xxx {
background-image:url('../Images/filters_collapse.jpg');
}
Select query to get data from SQL Server
you can use ExecuteScalar()
in place of ExecuteNonQuery()
to get a single result
use it like this
Int32 result= (Int32) command.ExecuteScalar();
Console.WriteLine(String.Format("{0}", result));
It will execute the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
As you want only one row in return, remove this use of SqlDataReader
from your code
using (SqlDataReader reader = command.ExecuteReader())
{
// iterate your results here
Console.WriteLine(String.Format("{0}",reader["id"]));
}
because it will again execute your command and effect your page performance.
Creating the checkbox dynamically using JavaScript?
You can create a function:
function changeInputType(oldObj, oTyp, nValue) {
var newObject = document.createElement('input');
newObject.type = oTyp;
if(oldObj.size) newObject.size = oldObj.size;
if(oldObj.value) newObject.value = nValue;
if(oldObj.name) newObject.name = oldObj.name;
if(oldObj.id) newObject.id = oldObj.id;
if(oldObj.className) newObject.className = oldObj.className;
oldObj.parentNode.replaceChild(newObject,oldObj);
return newObject;
}
And you do a call like:
changeInputType(document.getElementById('DATE_RANGE_VALUE'), 'checkbox', 7);
ASP.NET MVC get textbox input value
Simple ASP.NET MVC subscription form with email textbox would be implemented like that:
Model
The data from the form is mapped to this model
public class SubscribeModel
{
[Required]
public string Email { get; set; }
}
View
View name should match controller method name.
@model App.Models.SubscribeModel
@using (Html.BeginForm("Subscribe", "Home", FormMethod.Post))
{
@Html.TextBoxFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
<button type="submit">Subscribe</button>
}
Controller
Controller is responsible for request processing and returning proper response view.
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Subscribe(SubscribeModel model)
{
if (ModelState.IsValid)
{
//TODO: SubscribeUser(model.Email);
}
return View("Index", model);
}
}
Here is my project structure. Please notice, "Home" views folder matches HomeController name.
C++ Best way to get integer division and remainder
On x86 the remainder is a by-product of the division itself so any half-decent compiler should be able to just use it (and not perform a div
again). This is probably done on other architectures too.
Instruction: DIV
src
Note: Unsigned division. Divides accumulator (AX) by "src". If divisor
is a byte value, result is put to AL and remainder to AH. If divisor
is a word value, then DX:AX is divided by "src" and result is stored
in AX and remainder is stored in DX.
int c = (int)a / b;
int d = a % b; /* Likely uses the result of the division. */
How to configure PHP to send e-mail?
configure your php.ini like this
SMTP = smtp.gmail.com
[mail function]
; XAMPP: Comment out this if you want to work with an SMTP Server like Mercury
; SMTP = smtp.gmail.com
; smtp_port = 465
; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = postmaster@localhost
How to run multiple SQL commands in a single SQL connection?
This is likely to be attacked via SQL injection by the way. It'd be worth while reading up on that and adjusting your queries accordingly.
Maybe look at even creating a stored proc for this and using something like sp_executesql which can provide some protection against this when dynamic sql is a requirement (ie. unknown table names etc). For more info, check out this link.
What is a thread exit code?
what happened to me is that I have multiple projects in my solution. I meant to debug project 1, however, the project 2 was set as the default starting project. I fixed this by, right click on the project and select "Set as startup project", then running debugging is fine.
Execute Python script via crontab
Just use crontab -e
and follow the tutorial here.
Look at point 3 for a guide on how to specify the frequency.
Based on your requirement, it should effectively be:
*/10 * * * * /usr/bin/python script.py
How do I clone a Django model instance object and save it to the database?
This does an in-memory copy that you can mutate independently.
original = CheckoutItem(title="test", ...)
copy = CheckoutItem()
for f in CheckoutItem._meta.fields:
setattr(copy, f.attname, getattr(original, f.attname))
Or, as a method:
def clone(self):
"""Returns a clone of this instance."""
clone = self.__class__()
for f in self.__class__._meta.fields:
setattr(clone, f.attname, getattr(self, f.attname))
return clone
Convert base64 png data to javascript file objects
You can create a Blob
from your base64 data, and then read it asDataURL
:
var img_b64 = canvas.toDataURL('image/png');
var png = img_b64.split(',')[1];
var the_file = new Blob([window.atob(png)], {type: 'image/png', encoding: 'utf-8'});
var fr = new FileReader();
fr.onload = function ( oFREvent ) {
var v = oFREvent.target.result.split(',')[1]; // encoding is messed up here, so we fix it
v = atob(v);
var good_b64 = btoa(decodeURIComponent(escape(v)));
document.getElementById("uploadPreview").src = "data:image/png;base64," + good_b64;
};
fr.readAsDataURL(the_file);
Full example (includes junk code and console log): http://jsfiddle.net/tTYb8/
Alternatively, you can use .readAsText
, it works fine, and its more elegant.. but for some reason text does not sound right ;)
fr.onload = function ( oFREvent ) {
document.getElementById("uploadPreview").src = "data:image/png;base64,"
+ btoa(oFREvent.target.result);
};
fr.readAsText(the_file, "utf-8"); // its important to specify encoding here
Full example: http://jsfiddle.net/tTYb8/3/
Drop-down menu that opens up/upward with pure css
If we are use chosen dropdown list, then we can use below css(No JS/JQuery require)
<select chosen="{width: '100%'}" ng-
model="modelName" class="form-control input-
sm"
ng-
options="persons.persons as
persons.persons for persons in
jsonData"
ng-
change="anyFunction(anyParam)"
required>
<option value=""> </option>
</select>
<style>
.chosen-container .chosen-drop {
border-bottom: 0;
border-top: 1px solid #aaa;
top: auto;
bottom: 40px;
}
.chosen-container.chosen-with-drop .chosen-single {
border-top-left-radius: 0px;
border-top-right-radius: 0px;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
background-image: none;
}
.chosen-container.chosen-with-drop .chosen-drop {
border-bottom-left-radius: 0px;
border-bottom-right-radius: 0px;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
box-shadow: none;
margin-bottom: -16px;
}
</style>
How to list files in a directory in a C program?
Below code will only print files within directory and exclude directories within given directory while traversing.
#include <dirent.h>
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>
#include<string.h>
int main(void)
{
DIR *d;
struct dirent *dir;
char path[1000]="/home/joy/Downloads";
d = opendir(path);
char full_path[1000];
if (d)
{
while ((dir = readdir(d)) != NULL)
{
//Condition to check regular file.
if(dir->d_type==DT_REG){
full_path[0]='\0';
strcat(full_path,path);
strcat(full_path,"/");
strcat(full_path,dir->d_name);
printf("%s\n",full_path);
}
}
closedir(d);
}
return(0);
}
Convert a Map<String, String> to a POJO
The answers provided so far using Jackson are so good, but still you could have a util function to help you convert different POJO
s as follows:
public static <T> T convert(Map<String, Object> aMap, Class<T> t) {
try {
return objectMapper
.convertValue(aMap, objectMapper.getTypeFactory().constructType(t));
} catch (Exception e) {
log.error("converting failed! aMap: {}, class: {}", getJsonString(aMap), t.getClass().getSimpleName(), e);
}
return null;
}