How can I make git accept a self signed certificate?
It’s not a good practice to set http.sslVerify false.
Instead we can use SSL certificate.
So, build agent will use https with SSL certificate and PAT for authentication.
Copy the content of cer file including –begin—and –end--.
git bash on build agent =>
git config –global http.sslcainfo “C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt”
Go to this file and append the .cer content.
Thus, build agent can access the SSL certificate
Getting Chrome to accept self-signed localhost certificate
This worked for me:
- Using Chrome, hit a page on your server via HTTPS and continue past the red warning page (assuming you haven't done this already).
- Open up
Chrome Settings > Show advanced settings > HTTPS/SSL > Manage Certificates
.
- Click the
Authorities
tab and scroll down to find your certificate under the Organization Name that you gave to the certificate.
- Select it, click Edit (NOTE: in recent versions of Chrome, the button is now "Advanced" instead of "Edit"), check all the boxes and click OK. You may have to restart Chrome.
You should get the nice green lock on your pages now.
EDIT: I tried this again on a new machine and the certificate did not appear on the Manage Certificates window just by continuing from the red untrusted certificate page. I had to do the following:
- On the page with the untrusted certificate (
https://
is crossed out in red), click the lock > Certificate Information. NOTE: on newer versions of chrome, you have to open Developer Tools > Security
, and select View certificate
.
- Click the
Details tab > Export
. Choose PKCS #7, single certificate
as the file format.
- Then follow my original instructions to get to the Manage Certificates page. Click the
Authorities tab > Import
and choose the file to which you exported the certificate, and make sure to choose PKCS #7, single certificate
as the file type.
- If prompted certification store, choose Trusted Root Certificate Authorities
- Check all boxes and click OK. Restart Chrome.
How to export private key from a keystore of self-signed certificate
public static void main(String[] args) {
try {
String keystorePass = "20174";
String keyPass = "rav@789";
String alias = "TyaGi!";
InputStream keystoreStream = new FileInputStream("D:/keyFile.jks");
KeyStore keystore = KeyStore.getInstance("JCEKS");
keystore.load(keystoreStream, keystorePass.toCharArray());
Key key = keystore.getKey(alias, keyPass.toCharArray());
byte[] bt = key.getEncoded();
String s = new String(bt);
System.out.println("------>"+s);
String str12 = Base64.encodeBase64String(bt);
System.out.println("Fetched Key From JKS : " + str12);
} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException ex) {
System.out.println(ex);
}
}
Failed to load resource: net::ERR_INSECURE_RESPONSE
If you're developing, and you're developing with a Windows machine, simply add localhost
as a Trusted Site.
And yes, per DarrylGriffiths' comment, although it may look like you're adding an Internet Explorer setting...
I believe those are Windows rather than IE settings. Although MS tend to assume that they're only IE (hence the alert next to "Enable Protected Mode" that it requries restarted IE)...
unsigned APK can not be installed
You could also send your testers the apk that is signed with your debug key. You can find that in the bin folder of your project after building in debug mode.
How to create a self-signed certificate for a domain name for development?
With IIS's self-signed certificate feature, you cannot set the common name (CN) for the certificate, and therefore cannot create a certificate bound to your choice of subdomain.
One way around the problem is to use makecert.exe, which is bundled with the .Net 2.0 SDK. On my server it's at:
C:\Program Files\Microsoft.Net\SDK\v2.0 64bit\Bin\makecert.exe
You can create a signing authority and store it in the LocalMachine certificates repository as follows (these commands must be run from an Administrator account or within an elevated command prompt):
makecert.exe -n "CN=My Company Development Root CA,O=My Company,
OU=Development,L=Wallkill,S=NY,C=US" -pe -ss Root -sr LocalMachine
-sky exchange -m 120 -a sha1 -len 2048 -r
You can then create a certificate bound to your subdomain and signed by your new authority:
(Note that the the value of the -in parameter must be the same as the CN value used to generate your authority above.)
makecert.exe -n "CN=subdomain.example.com" -pe -ss My -sr LocalMachine
-sky exchange -m 120 -in "My Company Development Root CA" -is Root
-ir LocalMachine -a sha1 -eku 1.3.6.1.5.5.7.3.1
Your certificate should then appear in IIS Manager to be bound to your site as explained in Tom Hall's post.
All kudos for this solution to Mike O'Brien for his excellent blog post at http://www.mikeobrien.net/blog/creating-self-signed-wildcard
jQuery onclick toggle class name
jQuery has a toggleClass function:
<button class="switch">Click me</button>
<div class="text-block collapsed pressed">some text</div>
<script>
$('.switch').on('click', function(e) {
$('.text-block').toggleClass("collapsed pressed"); //you can list several class names
e.preventDefault();
});
</script>
Redirect HTTP to HTTPS on default virtual host without ServerName
I have use mkcert to create infinites *.dev.net subdomains & localhost with valid HTTPS/SSL certs (Windows 10 XAMPP & Linux Debian 10 Apache2)
I create the certs on Windows with mkcert v1.4.0 (execute CMD as Administrator):
mkcert -install
mkcert localhost "*.dev.net"
This create in Windows 10 this files (I will install it first in Windows 10 XAMPP)
localhost+1.pem
localhost+1-key.pem
Overwrite the XAMPP default certs:
copy "localhost+1.pem" C:\xampp\apache\conf\ssl.crt\server.crt
copy "localhost+1-key.pem" C:\xampp\apache\conf\ssl.key\server.key
Now, in Apache2 for Debian 10, activate SSL & vhost_alias
a2enmod vhosts_alias
a2enmod ssl
a2ensite default-ssl
systemctl restart apache2
For vhost_alias add this Apache2 config:
nano /etc/apache2/sites-available/999-vhosts_alias.conf
With this content:
<VirtualHost *:80>
UseCanonicalName Off
ServerAlias *.dev.net
VirtualDocumentRoot "/var/www/html/%0/"
</VirtualHost>
Add the site:
a2ensite 999-vhosts_alias
Copy the certs to /root/mkcert by SSH and let overwrite the Debian ones:
systemctl stop apache2
mv /etc/ssl/certs/ssl-cert-snakeoil.pem /etc/ssl/certs/ssl-cert-snakeoil.pem.bak
mv /etc/ssl/private/ssl-cert-snakeoil.key /etc/ssl/private/ssl-cert-snakeoil.key.bak
cp "localhost+1.pem" /etc/ssl/certs/ssl-cert-snakeoil.pem
cp "localhost+1-key.pem" /etc/ssl/private/ssl-cert-snakeoil.key
chown root:ssl-cert /etc/ssl/private/ssl-cert-snakeoil.key
chmod 640 /etc/ssl/private/ssl-cert-snakeoil.key
systemctl start apache2
Edit the SSL config
nano /etc/apache2/sites-enabled/default-ssl.conf
At the start edit the file with this content:
<IfModule mod_ssl.c>
<VirtualHost *:443>
UseCanonicalName Off
ServerAlias *.dev.net
ServerAdmin webmaster@localhost
# DocumentRoot /var/www/html/
VirtualDocumentRoot /var/www/html/%0/
...
Last restart:
systemctl restart apache2
NOTE: don´t forget to create the folders for your subdomains in /var/www/html/
/var/www/html/subdomain1.dev.net
/var/www/html/subdomain2.dev.net
/var/www/html/subdomain3.dev.net
Get MIME type from filename extension
Most of the solutions are working but why take so efforts while we also can get mime type very easily.
In System.Web assembly, there is method for getting the mime type from file name.
eg:
string mimeType = MimeMapping.GetMimeMapping(filename);
How to vertically center <div> inside the parent element with CSS?
I found a way that works great for me. The next script inserts an invisible image (same as bgcolor or a transparant gif) with height equal to half the size of the white-space on the screen. The effect is a perfect vertical-alignment.
Say you have a header div (height=100) and a footer div (height=50) and the content in the main div that you would like to align has a height of 300:
<script type="text/javascript" charset="utf-8">
var screen = window.innerHeight;
var content = 150 + 300;
var imgheight = ( screen - content) / 2 ;
document.write("<img src='empty.jpg' height='" + imgheight + "'>");
</script>
You place the script just before the content that you want to align!
In my case the content I liked to align was an image (width=95%) with an aspect ratio of 100:85 (width:height).Meaning the height of the image is 85% of it's width. And the Width being 95% of the screenwidth.
I therefore used:
var content = 150 + ( 0.85 * ( 0.95 * window.innerWidth ));
Combine this script with
<body onResize="window.location.href = window.location.href;">
and you have a smooth vertical alignment.
Hope this works for you too!
'do...while' vs. 'while'
do-while is better if the compiler isn't competent at optimization. do-while has only a single conditional jump, as opposed to for and while which have a conditional jump and an unconditional jump. For CPUs which are pipelined and don't do branch prediction, this can make a big difference in the performance of a tight loop.
Also, since most compilers are smart enough to perform this optimization, all loops found in decompiled code will usually be do-while (if the decompiler even bothers to reconstruct loops from backward local gotos at all).
Sort a list of numerical strings in ascending order
The recommended approach in this case is to sort the data in the database, adding an ORDER BY
at the end of the query that fetches the results, something like this:
SELECT temperature FROM temperatures ORDER BY temperature ASC; -- ascending order
SELECT temperature FROM temperatures ORDER BY temperature DESC; -- descending order
If for some reason that is not an option, you can change the sorting order like this in Python:
templist = [25, 50, 100, 150, 200, 250, 300, 33]
sorted(templist, key=int) # ascending order
> [25, 33, 50, 100, 150, 200, 250, 300]
sorted(templist, key=int, reverse=True) # descending order
> [300, 250, 200, 150, 100, 50, 33, 25]
As has been pointed in the comments, the int
key (or float
if values with decimals are being stored) is required for correctly sorting the data if the data received is of type string
, but it'd be very strange to store temperature values as strings, if that is the case, go back and fix the problem at the root, and make sure that the temperatures being stored are numbers.
HTML/CSS: how to put text both right and left aligned in a paragraph
The only half-way proper way to do this is
<p>
<span style="float: right">Text on the right</span>
<span style="float: left">Text on the left</span>
</p>
however, this will get you into trouble if the text overflows. If you can, use div
s (block level elements) and give them a fixed width
.
A table (or a number of div
s with the according display: table / table-row / table-cell
properties) would in fact be the safest solution for this - it will be impossible to break, even if you have lots of difficult content.
Input and Output binary streams using JERSEY?
I managed to get a ZIP file or a PDF file by extending the StreamingOutput
object. Here is some sample code:
@Path("PDF-file.pdf/")
@GET
@Produces({"application/pdf"})
public StreamingOutput getPDF() throws Exception {
return new StreamingOutput() {
public void write(OutputStream output) throws IOException, WebApplicationException {
try {
PDFGenerator generator = new PDFGenerator(getEntity());
generator.generatePDF(output);
} catch (Exception e) {
throw new WebApplicationException(e);
}
}
};
}
The PDFGenerator class (my own class for creating the PDF) takes the output stream from the write method and writes to that instead of a newly created output stream.
Don't know if it's the best way to do it, but it works.
Load local javascript file in chrome for testing?
Use Chrome browser and with the Web Server for Chrome extension, set a default folder and put your linked html/js files in there, browse to 127.0.0.1:8887 (0r whatever the port is set at) in Chrome and open the developers panel & console. You can then interact with your html/js scripts in the console.
Jquery change <p> text programmatically
It seems you have the click event wrapped around a custom event name "pageinit", are you sure you're triggered the event before you click the button?
something like this:
$("#gender").trigger("pageinit");
How to read a configuration file in Java
Create a configuration file and put your entries there.
SERVER_PORT=10000
THREAD_POOL_COUNT=3
ROOT_DIR=/home/
You can load this file using Properties.load(fileName)
and retrieved values you get(key)
;
Received fatal alert: handshake_failure through SSLHandshakeException
I don't think this solves the problem to the first questioner, but for googlers coming here for answers:
On update 51, java 1.8 prohibited[1] RC4 ciphers by default, as we can see on the Release Notes page:
Bug Fix: Prohibit RC4 cipher suites
RC4 is now considered as a compromised cipher.
RC4 cipher suites have been removed from both client and server default enabled cipher suite list in Oracle JSSE implementation. These cipher suites can still be enabled by SSLEngine.setEnabledCipherSuites()
and SSLSocket.setEnabledCipherSuites()
methods. See JDK-8077109 (not public).
If your server has a strong preference for this cipher (or use only this cipher) this can trigger a handshake_failure
on java.
You can test connecting to the server enabling RC4 ciphers (first, try without enabled
argument to see if triggers a handshake_failure
, then set enabled
:
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.*;
import java.util.Arrays;
/** Establish a SSL connection to a host and port, writes a byte and
* prints the response. See
* http://confluence.atlassian.com/display/JIRA/Connecting+to+SSL+services
*/
public class SSLRC4Poke {
public static void main(String[] args) {
String[] cyphers;
if (args.length < 2) {
System.out.println("Usage: "+SSLRC4Poke.class.getName()+" <host> <port> enable");
System.exit(1);
}
try {
SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket(args[0], Integer.parseInt(args[1]));
cyphers = sslsocketfactory.getSupportedCipherSuites();
if (args.length ==3){
sslsocket.setEnabledCipherSuites(new String[]{
"SSL_DH_anon_EXPORT_WITH_RC4_40_MD5",
"SSL_DH_anon_WITH_RC4_128_MD5",
"SSL_RSA_EXPORT_WITH_RC4_40_MD5",
"SSL_RSA_WITH_RC4_128_MD5",
"SSL_RSA_WITH_RC4_128_SHA",
"TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",
"TLS_ECDHE_RSA_WITH_RC4_128_SHA",
"TLS_ECDH_ECDSA_WITH_RC4_128_SHA",
"TLS_ECDH_RSA_WITH_RC4_128_SHA",
"TLS_ECDH_anon_WITH_RC4_128_SHA",
"TLS_KRB5_EXPORT_WITH_RC4_40_MD5",
"TLS_KRB5_EXPORT_WITH_RC4_40_SHA",
"TLS_KRB5_WITH_RC4_128_MD5",
"TLS_KRB5_WITH_RC4_128_SHA"
});
}
InputStream in = sslsocket.getInputStream();
OutputStream out = sslsocket.getOutputStream();
// Write a test byte to get a reaction :)
out.write(1);
while (in.available() > 0) {
System.out.print(in.read());
}
System.out.println("Successfully connected");
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
1 - https://www.java.com/en/download/faq/release_changes.xml
AngularJS format JSON string output
In addition to the angular json
filter already mentioned, there is also the angular toJson()
function.
angular.toJson(obj, pretty);
The second param of this function lets you switch on pretty printing and set the number of spaces to use.
If set to true, the JSON output will contain newlines and whitespace. If set to an integer, the JSON output will contain that many spaces per indentation.
(default: 2)
Change text (html) with .animate
For fadeOut => change text => fadeIn effect
We need to animate the wrapper of texts we would like change.
Example below:
HTML
<div class="timeline-yeardata">
<div class="anime">
<div class="ilosc-sklepow-sticker">
<span id="amount">1400</span><br>
sklepów
</div>
<div class="txts-wrap">
<h3 class="title">Some text</h3>
<span class="desc">Lorem ipsum description</span>
</div>
<div class="year-bg" id="current-year">2018</div>
</div>
</div>
<div class="ch-timeline-wrap">
<div class="ch-timeline">
<div class="line"></div>
<div class="row no-gutters">
<div class="col">
<a href="#2009" data-amount="9" data-y="2009" class="el current">
<span class="yr">2009</span>
<span class="dot"></span>
<span class="title">Lorem asdf asdf asdf a</span>
<span class="desc">Ww wae awer awe rawer aser as</span>
</a>
</div>
<div class="col">
<a href="#2010" data-amount="19" data-y="2010" class="el">
<span class="yr">2010</span>
<span class="dot"></span>
<span class="title">Lorem brernern</span>
<span class="desc">A sd asdkj aksjdkajskd jaksjd kajskd jaksjd akjsdk jaskjd akjsdkajskdj akjsd k</span>
</a>
</div>
</div>
</div>
</div>
JQuery JS
$(document).ready(function(){
$('.ch-timeline .el').on('click', function(){
$('.ch-timeline .el').removeClass('current');
$(this).addClass('current');
var ilosc = $(this).data('ilosc');
var y = $(this).data('y');
var title = $(this).find('.title').html();
var desc = $(this).find('desc').html();
$('.timeline-yeardata .anime').fadeOut(400, function(){
$('#ilosc-sklepow').html(ilosc);
$('#current-year').html(y);
$('.timeline-yeardata .title').html(title);
$('.timeline-yeardata .desc').html(desc);
$(this).fadeIn(300);
})
});
});
Hope this will help someone.
Check if DataRow exists by column name in c#?
if (drMyRow.Table.Columns["ColNameToCheck"] != null)
{
doSomethingUseful;
{
else { return; }
Although the DataRow does not have a Columns property, it does have a Table that the column can be checked for.
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
Python - List of unique dictionaries
A quick-and-dirty solution is just by generating a new list.
sortedlist = []
for item in listwhichneedssorting:
if item not in sortedlist:
sortedlist.append(item)
How to prevent a browser from storing passwords
I did it by setting the input field as "text", and catching and manipulating the input keys
first activate a function to catch keys
yourInputElement.addEventListener('keydown', onInputPassword);
the onInputPassword function is like this:
(assuming that you have the "password" variable defined somewhere)
onInputPassword( event ) {
let key = event.key;
event.preventDefault(); // this is to prevent the key to reach the input field
if( key == "Enter" ) {
// here you put a call to the function that will do something with the password
}
else if( key == "Backspace" ) {
if( password ) {
// remove the last character if any
yourInputElement.value = yourInputElement.value.slice(0, -1);
password = password.slice(0, -1);
}
}
else if( (key >= '0' && key <= '9') || (key >= 'A' && key <= 'Z') || (key >= 'a' && key <= 'z') ) {
// show a fake '*' on input field and store the real password
yourInputElement.value = yourInputElement.value + "*";
password += key;
}
}
so all alphanumeric keys will be added to the password, the 'backspace' key will erase one character, the 'enter' key will terminate, and any other keys will be ignored
don't forget to call removeEventListener('keydown', onInputPassword) somewhere at the end
SSL error : routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
The server certificate is invalid, either because it is signed by an invalid CA (internal CA, self signed,...), doesn't match the server's name or because it is expired.
Either way, you need to find how to tell to the Python library that you are using that it must not stop at an invalid certificate if you really want to download files from this server.
How can I truncate a string to the first 20 words in PHP?
Change the number 3
to the number 20
below to get the first 20 words, or pass it as parameter. The following demonstrates how to get the first 3 words: (so change the 3
to 20
to change the default value):
function first3words($s, $limit=3) {
return preg_replace('/((\w+\W*){'.($limit-1).'}(\w+))(.*)/', '${1}', $s);
}
var_dump(first3words("hello yes, world wah ha ha")); # => "hello yes, world"
var_dump(first3words("hello yes,world wah ha ha")); # => "hello yes,world"
var_dump(first3words("hello yes world wah ha ha")); # => "hello yes world"
var_dump(first3words("hello yes world")); # => "hello yes world"
var_dump(first3words("hello yes world.")); # => "hello yes world"
var_dump(first3words("hello yes")); # => "hello yes"
var_dump(first3words("hello")); # => "hello"
var_dump(first3words("a")); # => "a"
var_dump(first3words("")); # => ""
What does '--set-upstream' do?
When you push to a remote and you use the --set-upstream
flag git sets the branch you are pushing to as the remote tracking branch of the branch you are pushing.
Adding a remote tracking branch means that git then knows what you want to do when you git fetch
, git pull
or git push
in future. It assumes that you want to keep the local branch and the remote branch it is tracking in sync and does the appropriate thing to achieve this.
You could achieve the same thing with git branch --set-upstream-to
or git checkout --track
. See the git help pages on tracking branches for more information.
Easily measure elapsed time
As others have already noted, the time() function in the C standard library does not have a resolution better than one second. The only fully portable C function that may provide better resolution appears to be clock(), but that measures processor time rather than wallclock time. If one is content to limit oneself to POSIX platforms (e.g. Linux), then the clock_gettime() function is a good choice.
Since C++11, there are much better timing facilities available that offer better resolution in a form that should be very portable across different compilers and operating systems. Similarly, the boost::datetime library provides good high-resolution timing classes that should be highly portable.
One challenge in using any of these facilities is the time-delay introduced by querying the system clock. From experimenting with clock_gettime(), boost::datetime and std::chrono, this delay can easily be a matter of microseconds. So, when measuring the duration of any part of your code, you need to allow for there being a measurement error of around this size, or try to correct for that zero-error in some way. Ideally, you may well want to gather multiple measurements of the time taken by your function, and compute the average, or maximum/minimum time taken across many runs.
To help with all these portability and statistics-gathering issues, I've been developing the cxx-rtimers library available on Github which tries to provide a simple API for timing blocks of C++ code, computing zero errors, and reporting stats from multiple timers embedded in your code. If you have a C++11 compiler, you simply #include <rtimers/cxx11.hpp>
, and use something like:
void expensiveFunction() {
static rtimers::cxx11::DefaultTimer timer("expensiveFunc");
auto scopedStartStop = timer.scopedStart();
// Do something costly...
}
On program exit, you'll get a summary of timing stats written to std::cerr such as:
Timer(expensiveFunc): <t> = 6.65289us, std = 3.91685us, 3.842us <= t <= 63.257us (n=731)
which shows the mean time, its standard-deviation, the upper and lower limits, and the number of times this function was called.
If you want to use Linux-specific timing functions, you can #include <rtimers/posix.hpp>
, or if you have the Boost libraries but an older C++ compiler, you can #include <rtimers/boost.hpp>
. There are also versions of these timer classes that can gather statistical timing information from across multiple threads. There are also methods that allow you to estimate the zero-error associated with two immediately consecutive queries of the system clock.
How do you round a floating point number in Perl?
See perldoc/perlfaq:
Remember that int()
merely truncates toward 0. For rounding to a
certain number of digits, sprintf()
or printf()
is usually the
easiest route.
printf("%.3f",3.1415926535);
# prints 3.142
The POSIX
module (part of the standard Perl distribution)
implements ceil()
, floor()
, and a number of other mathematical
and trigonometric functions.
use POSIX;
$ceil = ceil(3.5); # 4
$floor = floor(3.5); # 3
In 5.000 to 5.003 perls, trigonometry was done in the Math::Complex
module.
With 5.004, the Math::Trig
module (part of the standard Perl distribution) > implements the trigonometric functions.
Internally it uses the Math::Complex
module and some functions can break
out from the real axis into the complex plane, for example the inverse sine of 2.
Rounding in financial applications can have serious implications, and the rounding
method used should be specified precisely. In these cases, it probably pays not to
trust whichever system rounding is being used by Perl, but to instead implement the
rounding function you need yourself.
To see why, notice how you'll still have an issue on half-way-point alternation:
for ($i = 0; $i < 1.01; $i += 0.05)
{
printf "%.1f ",$i
}
0.0 0.1 0.1 0.2 0.2 0.2 0.3 0.3 0.4 0.4 0.5 0.5 0.6 0.7 0.7 0.8 0.8 0.9 0.9 1.0 1.0
Don't blame Perl. It's the same as in C. IEEE says we have to do
this. Perl numbers whose absolute values are integers under 2**31 (on
32 bit machines) will work pretty much like mathematical integers.
Other numbers are not guaranteed.
Created Button Click Event c#
public MainWindow()
{
// This button needs to exist on your form.
myButton.Click += myButton_Click;
}
void myButton_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Message here");
this.Close();
}
How to install PyQt4 on Windows using pip?
Here are Windows wheel packages built by Chris Golke - Python Windows Binary packages - PyQt
In the filenames cp27
means C-python version 2.7, cp35
means python 3.5, etc.
Since Qt is a more complicated system with a compiled C++ codebase underlying the python interface it provides you, it can be more complex to build than just a pure python code package, which means it can be hard to install it from source.
Make sure you grab the correct Windows wheel file (python version, 32/64 bit), and then use pip to install it - e.g:
C:\path\where\wheel\is\> pip install PyQt4-4.11.4-cp35-none-win_amd64.whl
Should properly install if you are running an x64 build of Python 3.5.
Using ffmpeg to encode a high quality video
Unless you do some kind of post-processing work, the video will never be better than the original frames. Also just like a flip-book, if you have a big "jump" between keyframes it will look funny. You generally need enough "tweens" in between the keyframes to give smooth animation. HTH
How can I debug a .BAT script?
you can use cmd \k
at the end of your script to see the error. it won't close your command prompt after the execution is done
Get timezone from DateTime
You could use TimeZoneInfo class
The TimeZone class recognizes local time zone, and can convert times between Coordinated Universal Time (UTC) and local time. A TimeZoneInfo object can represent any time zone, and methods of the TimeZoneInfo class can be used to convert the time in one time zone to the corresponding time in any other time zone. The members of the TimeZoneInfo class support the following operations:
Retrieving a time zone that is already defined by the operating
system.
Enumerating the time zones that are available on a system.
Converting times between different time zones.
Creating a new time zone that is not already defined by the
operating system.
Serializing a time zone for later retrieval.
cout is not a member of std
I had a similar issue and it turned out that i had to add an extra entry in cmake
to include the files.
Since i was also using the zmq library I had to add this to the included libraries as well.
Is it ok to scrape data from Google results?
Google thrives on scraping websites of the world...so if it was "so illegal" then even Google won't survive ..of course other answers mention ways of mitigating IP blocks by Google. One more way to explore avoiding captcha could be scraping at random times (dint try) ..Moreover, I have a feeling, that if we provide novelty or some significant processing of data then it sounds fine at least to me...if we are simply copying a website.. or hampering its business/brand in some way...then it is bad and should be avoided..on top of it all...if you are a startup then no one will fight you as there is no benefit.. but if your entire premise is on scraping even when you are funded then you should think of more sophisticated ways...alternative APIs..eventually..Also Google keeps releasing (or depricating) fields for its API so what you want to scrap now may be in roadmap of new Google API releases..
Python - Create list with numbers between 2 values?
Use range
. In Python 2.x it returns a list so all you need is:
>>> range(11, 17)
[11, 12, 13, 14, 15, 16]
In Python 3.x range
is a iterator. So, you need to convert it to a list:
>>> list(range(11, 17))
[11, 12, 13, 14, 15, 16]
Note: The second number is exclusive. So, here it needs to be 16+1
= 17
EDIT:
To respond to the question about incrementing by 0.5
, the easiest option would probably be to use numpy's arange()
and .tolist()
:
>>> import numpy as np
>>> np.arange(11, 17, 0.5).tolist()
[11.0, 11.5, 12.0, 12.5, 13.0, 13.5,
14.0, 14.5, 15.0, 15.5, 16.0, 16.5]
How to convert float to varchar in SQL Server
this is the solution I ended up using in sqlserver 2012 (since all the other suggestions had the drawback of truncating fractional part or some other drawback).
declare @float float = 1000000000.1234;
select format(@float, N'#.##############################');
output:
1000000000.1234
this has the further advantage (in my case) to make thousands separator and localization easy:
select format(@float, N'#,##0.##########', 'de-DE');
output:
1.000.000.000,1234
How to get a variable name as a string in PHP?
Adapted from answers above for many variables, with good performance, just one $GLOBALS scan for many
function compact_assoc(&$v1='__undefined__', &$v2='__undefined__',&$v3='__undefined__',&$v4='__undefined__',&$v5='__undefined__',&$v6='__undefined__',&$v7='__undefined__',&$v8='__undefined__',&$v9='__undefined__',&$v10='__undefined__',&$v11='__undefined__',&$v12='__undefined__',&$v13='__undefined__',&$v14='__undefined__',&$v15='__undefined__',&$v16='__undefined__',&$v17='__undefined__',&$v18='__undefined__',&$v19='__undefined__'
) {
$defined_vars=get_defined_vars();
$result=Array();
$reverse_key=Array();
$original_value=Array();
foreach( $defined_vars as $source_key => $source_value){
if($source_value==='__undefined__') break;
$original_value[$source_key]=$$source_key;
$new_test_value="PREFIX".rand()."SUFIX";
$reverse_key[$new_test_value]=$source_key;
$$source_key=$new_test_value;
}
foreach($GLOBALS as $key => &$value){
if( is_string($value) && isset($reverse_key[$value]) ) {
$result[$key]=&$value;
}
}
foreach( $original_value as $source_key => $original_value){
$$source_key=$original_value;
}
return $result;
}
$a = 'A';
$b = 'B';
$c = '999';
$myArray=Array ('id'=>'id123','name'=>'Foo');
print_r(compact_assoc($a,$b,$c,$myArray) );
//print
Array
(
[a] => A
[b] => B
[c] => 999
[myArray] => Array
(
[id] => id123
[name] => Foo
)
)
Capturing multiple line output into a Bash variable
How about this, it will read each line to a variable and that can be used subsequently !
say myscript output is redirected to a file called myscript_output
awk '{while ( (getline var < "myscript_output") >0){print var;} close ("myscript_output");}'
Python: Best way to add to sys.path relative to the current running script
I use:
from site import addsitedir
Then, can use any relative directory !
addsitedir('..\lib')
; the two dots implies move (up) one directory first.
Remember that it all depends on what your current working directory your starting from.
If C:\Joe\Jen\Becky, then
addsitedir('..\lib') imports to your path C:\Joe\Jen\lib
C:\
|__Joe
|_ Jen
| |_ Becky
|_ lib
Angular Material: mat-select not selecting default
You should be binding it as [value]
in the mat-option
as below,
<mat-select placeholder="Panel color" [(value)]="selected2">
<mat-option *ngFor="let option of options2" [value]="option.id">
{{ option.name }}
</mat-option>
</mat-select>
LIVE DEMO
Qt - reading from a text file
You have to replace string line
QString line = in.readLine();
into while:
QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
QMessageBox::information(0, "error", file.errorString());
}
QTextStream in(&file);
while(!in.atEnd()) {
QString line = in.readLine();
QStringList fields = line.split(",");
model->appendRow(fields);
}
file.close();
How to dockerize maven project? and how many ways to accomplish it?
Create a Dockerfile
#
# Build stage
#
FROM maven:3.6.3-jdk-11-slim AS build
WORKDIR usr/src/app
COPY . ./
RUN mvn clean package
#
# Package stage
#
FROM openjdk:11-jre-slim
ARG JAR_NAME="project-name"
WORKDIR /usr/src/app
EXPOSE ${HTTP_PORT}
COPY --from=build /usr/src/app/target/${JAR_NAME}.jar ./app.jar
CMD ["java","-jar", "./app.jar"]
jQuery UI dialog box not positioned center screen
This is how I solved the issue, I added this open function of the dialog:
open: function () {
$('.ui-dialog').css("top","0px");
}
This now opens the dialog at the top of the screen, no matter where the page is scrolled to and in all browsers.
Bootstrap carousel multiple frames at once
_x000D_
_x000D_
$('#carousel-example-generic').on('slid.bs.carousel', function () {_x000D_
$(".item.active:nth-child(" + ($(".carousel-inner .item").length -1) + ") + .item").insertBefore($(".item:first-child"));_x000D_
$(".item.active:last-child").insertBefore($(".item:first-child"));_x000D_
});
_x000D_
.item.active,_x000D_
.item.active + .item,_x000D_
.item.active + .item + .item {_x000D_
width: 33.3%;_x000D_
display: block;_x000D_
float:left;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">_x000D_
_x000D_
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel" style="max-width:800px;">_x000D_
<!-- Indicators -->_x000D_
<ol class="carousel-indicators">_x000D_
<li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>_x000D_
<li data-target="#carousel-example-generic" data-slide-to="1"></li>_x000D_
<li data-target="#carousel-example-generic" data-slide-to="2"></li>_x000D_
</ol>_x000D_
_x000D_
<!-- Wrapper for slides -->_x000D_
<div class="carousel-inner" role="listbox">_x000D_
<div class="item active">_x000D_
<img data-src="holder.js/300x200?text=1">_x000D_
</div>_x000D_
<div class="item">_x000D_
<img data-src="holder.js/300x200?text=2">_x000D_
</div>_x000D_
<div class="item">_x000D_
<img data-src="holder.js/300x200?text=3">_x000D_
</div>_x000D_
<div class="item">_x000D_
<img data-src="holder.js/300x200?text=4">_x000D_
</div>_x000D_
<div class="item">_x000D_
<img data-src="holder.js/300x200?text=5">_x000D_
</div>_x000D_
<div class="item">_x000D_
<img data-src="holder.js/300x200?text=6">_x000D_
</div>_x000D_
<div class="item">_x000D_
<img data-src="holder.js/300x200?text=7">_x000D_
</div> _x000D_
</div>_x000D_
_x000D_
<!-- Controls -->_x000D_
<a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">_x000D_
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>_x000D_
<span class="sr-only">Previous</span>_x000D_
</a>_x000D_
<a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">_x000D_
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>_x000D_
<span class="sr-only">Next</span>_x000D_
</a>_x000D_
</div>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/holder/2.9.1/holder.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
How can I measure the actual memory usage of an application or process?
Valgrind can show detailed information, but it slows down the target application significantly, and most of the time it changes the behavior of the application.
Exmap was something I didn't know yet, but it seems that you need a kernel module to get the information, which can be an obstacle.
I assume what everyone wants to know with respect to "memory usage" is the following...
In Linux, the amount of physical memory a single process might use can be roughly divided into following categories.
Utility included in Android called showmap is quite useful
virtual shared shared private private
size RSS PSS clean dirty clean dirty object
-------- -------- -------- -------- -------- -------- -------- ------------------------------
4 0 0 0 0 0 0 0:00 0 [vsyscall]
4 4 0 4 0 0 0 [vdso]
88 28 28 0 0 4 24 [stack]
12 12 12 0 0 0 12 7909 /lib/ld-2.11.1.so
12 4 4 0 0 0 4 89529 /usr/lib/locale/en_US.utf8/LC_IDENTIFICATION
28 0 0 0 0 0 0 86661 /usr/lib/gconv/gconv-modules.cache
4 0 0 0 0 0 0 87660 /usr/lib/locale/en_US.utf8/LC_MEASUREMENT
4 0 0 0 0 0 0 89528 /usr/lib/locale/en_US.utf8/LC_TELEPHONE
4 0 0 0 0 0 0 89527 /usr/lib/locale/en_US.utf8/LC_ADDRESS
4 0 0 0 0 0 0 87717 /usr/lib/locale/en_US.utf8/LC_NAME
4 0 0 0 0 0 0 87873 /usr/lib/locale/en_US.utf8/LC_PAPER
4 0 0 0 0 0 0 13879 /usr/lib/locale/en_US.utf8/LC_MESSAGES/SYS_LC_MESSAGES
4 0 0 0 0 0 0 89526 /usr/lib/locale/en_US.utf8/LC_MONETARY
4 0 0 0 0 0 0 89525 /usr/lib/locale/en_US.utf8/LC_TIME
4 0 0 0 0 0 0 11378 /usr/lib/locale/en_US.utf8/LC_NUMERIC
1156 8 8 0 0 4 4 11372 /usr/lib/locale/en_US.utf8/LC_COLLATE
252 0 0 0 0 0 0 11321 /usr/lib/locale/en_US.utf8/LC_CTYPE
128 52 1 52 0 0 0 7909 /lib/ld-2.11.1.so
2316 32 11 24 0 0 8 7986 /lib/libncurses.so.5.7
2064 8 4 4 0 0 4 7947 /lib/libdl-2.11.1.so
3596 472 46 440 0 4 28 7933 /lib/libc-2.11.1.so
2084 4 0 4 0 0 0 7995 /lib/libnss_compat-2.11.1.so
2152 4 0 4 0 0 0 7993 /lib/libnsl-2.11.1.so
2092 0 0 0 0 0 0 8009 /lib/libnss_nis-2.11.1.so
2100 0 0 0 0 0 0 7999 /lib/libnss_files-2.11.1.so
3752 2736 2736 0 0 864 1872 [heap]
24 24 24 0 0 0 24 [anon]
916 616 131 584 0 0 32 /bin/bash
-------- -------- -------- -------- -------- -------- -------- ------------------------------
22816 4004 3005 1116 0 876 2012 TOTAL
Convert Swift string to array
An easy way to do this is to map
the variable and return each Character
as a String
:
let someText = "hello"
let array = someText.map({ String($0) }) // [String]
The output should be ["h", "e", "l", "l", "o"]
.
Android: Quit application when press back button
When you press back and then you finish your current activity(say A), you see a blank activity with your app logo(say B), this simply means that activity B which is shown after finishing A is still in backstack, and also activity A was started from activity B, so in activity, You should start activity A with flags as
Intent launchNextActivity;
launchNextActivity = new Intent(B.class, A.class);
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(launchNextActivity);
Now your activity A is top on stack with no other activities of your application on the backstack.
Now in the activity A where you want to implement onBackPressed to close the app, you may do something like this,
private Boolean exit = false;
@Override
public void onBackPressed() {
if (exit) {
finish(); // finish activity
} else {
Toast.makeText(this, "Press Back again to Exit.",
Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
exit = false;
}
}, 3 * 1000);
}
}
The Handler here handles accidental back presses, it simply shows a Toast
, and if there is another back press within 3 seconds, it closes the application.
Best Practice: Software Versioning
Yet another example for the A.B.C
approach is the Eclipse Bundle Versioning. Eclipse bundles rather have a fourth segment:
In Eclipse, version numbers are composed of four (4) segments: 3 integers and a string respectively named major.minor.service.qualifier
. Each segment captures a different intent:
- the major segment indicates breakage in the API
- the minor segment indicates "externally visible" changes
- the service segment indicates bug fixes and the change of development stream
- the qualifier segment indicates a particular build
Convert an NSURL to an NSString
You can use any one way
NSString *string=[NSString stringWithFormat:@"%@",url1];
or
NSString *str=[url1 absoluteString];
NSLog(@"string :: %@",string);
string :: file:///var/containers/Bundle/Application/E2D7570B-D5A6-45A0-8EAAA1F7476071FE/RemoDuplicateMedia.app/loading_circle_animation.gif
NSLog(@"str :: %@", str);
str :: file:///var/containers/Bundle/Application/E2D7570B-D5A6-45A0-8EAA-A1F7476071FE/RemoDuplicateMedia.app/loading_circle_animation.gif
Toolbar overlapping below status bar
Remove below lines from style or style(21)
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@color/colorPrimaryDark</item>
<item name="android:windowTranslucentStatus">false</item>
Responsive css styles on mobile devices ONLY
What's you've got there should be fine to work, but there is no actual "Is Mobile/Tablet" media query so you're always going to be stuck.
There are media queries for common breakpoints , but with the ever changing range of devices they're not guaranteed to work moving forwards.
The idea is that your site maintains the same brand across all sizes, so you should want the styles to cascade across the breakpoints and only update the widths and positioning to best suit that viewport.
To further the answer above, using Modernizr with a no-touch test will allow you to target touch devices which are most likely tablets and smart phones, however with the new releases of touch based screens that is not as good an option as it once was.
Pattern matching using a wildcard
glob2rx()
converts a pattern including a wildcard into the equivalent regular expression. You then need to pass this regular expression onto one of R's pattern matching tools.
If you want to match "blue*"
where *
has the usual wildcard, not regular expression, meaning we use glob2rx()
to convert the wildcard pattern into a useful regular expression:
> glob2rx("blue*")
[1] "^blue"
The returned object is a regular expression.
Given your data:
x <- c('red','blue1','blue2', 'red2')
we can pattern match using grep()
or similar tools:
> grx <- glob2rx("blue*")
> grep(grx, x)
[1] 2 3
> grep(grx, x, value = TRUE)
[1] "blue1" "blue2"
> grepl(grx, x)
[1] FALSE TRUE TRUE FALSE
As for the selecting rows problem you posted
> a <- data.frame(x = c('red','blue1','blue2', 'red2'))
> with(a, a[grepl(grx, x), ])
[1] blue1 blue2
Levels: blue1 blue2 red red2
> with(a, a[grep(grx, x), ])
[1] blue1 blue2
Levels: blue1 blue2 red red2
or via subset()
:
> with(a, subset(a, subset = grepl(grx, x)))
x
2 blue1
3 blue2
Hope that explains what grob2rx()
does and how to use it?
Focus Input Box On Load
If you can't add to the BODY tag for some reason, you can add this AFTER the Form:
<SCRIPT type="text/javascript">
document.yourFormName.yourFieldName.focus();
</SCRIPT>
Using Panel or PlaceHolder
Use the PlaceHolder control as a container to store server controls that are dynamically added to the Web page. The PlaceHolder control does not produce any visible output and is used only as a container for other controls on the Web page. You can use the Control.Controls
collection to add, insert, or remove a control in the PlaceHolder control.
The Panel control is a container for other controls. It is especially useful when you want to generate controls programmatically, hide/show a group of controls, or localize a group of controls.
The Direction
property is useful for localizing a Panel control's content to display text for languages that are written from right to left, such as Arabic or Hebrew.
The Panel control provides several properties that allow you to customize the behavior and display of its contents. Use the BackImageUr
l property to display a custom image for the Panel control. Use the ScrollBars
property to specify scroll bars for the control.
Small differences when rendering HTML: a PlaceHolder control will render nothing, but Panel control will render as a <div>
.
More information at ASP.NET Forums
Easiest way to make lua script wait/pause/sleep/block for a few seconds?
cy = function()
local T = os.time()
coroutine.yield(coroutine.resume(coroutine.create(function()
end)))
return os.time()-T
end
sleep = function(time)
if not time or time == 0 then
time = cy()
end
local t = 0
repeat
local T = os.time()
coroutine.yield(coroutine.resume(coroutine.create(function() end)))
t = t + (os.time()-T)
until t >= time
end
What is the bower (and npm) version syntax?
Bower uses semver syntax, but here are a few quick examples:
You can install a specific version:
$ bower install jquery#1.11.1
You can use ~ to specify 'any version that starts with this':
$ bower install jquery#~1.11
You can specify multiple version requirements together:
$ bower install "jquery#<2.0 >1.10"
Draw a curve with css
You could use an asymmetrical border to make curves with CSS.
border-radius: 50%/100px 100px 0 0;
VIEW DEMO
_x000D_
_x000D_
.box {_x000D_
width: 500px; _x000D_
height: 100px; _x000D_
border: solid 5px #000;_x000D_
border-color: #000 transparent transparent transparent;_x000D_
border-radius: 50%/100px 100px 0 0;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
_x000D_
_x000D_
php: check if an array has duplicates
I'm using this:
if(count($array)==count(array_count_values($array))){
echo("all values are unique");
}else{
echo("there's dupe values");
}
I don't know if it's the fastest but works pretty good so far
PHP: Count a stdClass object
count()
function works with array. But if you want to count object's length then you can use this method.
$total = $obj->length;
What are all the different ways to create an object in Java?
There are five different ways to create an object in Java,
1. Using new
keyword ? constructor get called
Employee emp1 = new Employee();
2. Using newInstance()
method of Class
? constructor get called
Employee emp2 = (Employee) Class.forName("org.programming.mitra.exercises.Employee")
.newInstance();
It can also be written as
Employee emp2 = Employee.class.newInstance();
3. Using newInstance()
method of Constructor
? constructor get called
Constructor<Employee> constructor = Employee.class.getConstructor();
Employee emp3 = constructor.newInstance();
4. Using clone()
method ? no constructor call
Employee emp4 = (Employee) emp3.clone();
5. Using deserialization ? no constructor call
ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));
Employee emp5 = (Employee) in.readObject();
First three methods new
keyword and both newInstance()
include a constructor call but later two clone and deserialization methods create objects without calling the constructor.
All above methods have different bytecode associated with them, Read Different ways to create objects in Java with Example for examples and more detailed description e.g. bytecode conversion of all these methods.
However one can argue that creating an array or string object is also a way of creating the object but these things are more specific to some classes only and handled directly by JVM, while we can create an object of any class by using these 5 ways.
What is Bootstrap?
Bootstrap is an open-source CSS, JavaScript framework that was originally developed for twitter application by twitter's team of designers and developers. Then they released it for open-source. Being a longtime user of twitter bootstrap I find that its one of the best for designing mobile ready responsive websites. Many CSS and Javascript plugins are available for designing your website in no time. It's kind of rapid template design framework. Some people complain that the bootstrap CSS files are heavy and take time to load but these claims are made by lazy people. You don't have to keep the complete bootstrap.css in your website. You always have the option to remove the styles for components that you do not need for your website. For example, if you are only using basic components like forms and buttons then you can remove other components like accordions etc from the main CSS file. To start dabbling in bootstrap you can download the basic templates and components from getbootstrap site and let the magic happen.
Posting form to different MVC post action depending on the clicked submit button
You can choose the url where the form must be posted (and thus, the invoked action) in different ways, depending on the browser support:
In this way you don't need to do anything special on the server side.
Of course, you can use Url
extensions methods in your Razor to specify the form action.
For browsers supporting HMTL5: simply define your submit buttons like this:
<input type='submit' value='...' formaction='@Url.Action(...)' />
For older browsers I recommend using an unobtrusive script like this (include it in your "master layout"):
$(document).on('click', '[type="submit"][data-form-action]', function (event) {
var $this = $(this);
var formAction = $this.attr('data-form-action');
$this.closest('form').attr('action', formAction);
});
NOTE: This script will handle the click for any element in the page that has type=submit
and data-form-action
attributes. When this happens, it takes the value of data-form-action
attribute and set the containing form's action to the value of this attribute. As it's a delegated event, it will work even for HTML loaded using AJAX, without taking extra steps.
Then you simply have to add a data-form-action
attribute with the desired action URL to your button, like this:
<input type='submit' data-form-action='@Url.Action(...)' value='...'/>
Note that clicking the button changes the form's action, and, right after that, the browser posts the form to the desired action.
As you can see, this requires no custom routing, you can use the standard Url
extension methods, and you have nothing special to do in modern browsers.
Root element is missing
Just in case anybody else lands here from Google, I was bitten by this error message when using XDocument.Load(Stream) method.
XDocument xDoc = XDocument.Load(xmlStream);
Make sure the stream position is set to 0 (zero) before you try and load the Stream, its an easy mistake I always overlook!
if (xmlStream.Position > 0)
{
xmlStream.Position = 0;
}
XDocument xDoc = XDocument.Load(xmlStream);
jQuery click events not working in iOS
Recently when working on a web app for a client, I noticed that any click events added to a non-anchor element didn't work on the iPad or iPhone. All desktop and other mobile devices worked fine - but as the Apple products are the most popular mobile devices, it was important to get it fixed.
Turns out that any non-anchor element assigned a click handler in jQuery must either have an onClick attribute (can be empty like below):
onClick=""
OR
The element css needs to have the following declaration:
cursor:pointer
Strange, but that's what it took to get things working again!
source:http://www.mitch-solutions.com/blog/17-ipad-jquery-live-click-events-not-working
eval command in Bash and its typical uses
I like the "evaluating your expression one additional time before execution" answer, and would like to clarify with another example.
var="\"par1 par2\""
echo $var # prints nicely "par1 par2"
function cntpars() {
echo " > Count: $#"
echo " > Pars : $*"
echo " > par1 : $1"
echo " > par2 : $2"
if [[ $# = 1 && $1 = "par1 par2" ]]; then
echo " > PASS"
else
echo " > FAIL"
return 1
fi
}
# Option 1: Will Pass
echo "eval \"cntpars \$var\""
eval "cntpars $var"
# Option 2: Will Fail, with curious results
echo "cntpars \$var"
cntpars $var
The Curious results in Option 2 are that we would have passed 2 parameters as follows:
- First Parameter:
"value
- Second Parameter:
content"
How is that for counter intuitive? The additional eval
will fix that.
Adapted from https://stackoverflow.com/a/40646371/744133
What is the correct way to read from NetworkStream in .NET
Networking code is notoriously difficult to write, test and debug.
You often have lots of things to consider such as:
what "endian" will you use for the data that is exchanged (Intel x86/x64 is based on little-endian) - systems that use big-endian can still read data that is in little-endian (and vice versa), but they have to rearrange the data. When documenting your "protocol" just make it clear which one you are using.
are there any "settings" that have been set on the sockets which can affect how the "stream" behaves (e.g. SO_LINGER) - you might need to turn certain ones on or off if your code is very sensitive
how does congestion in the real world which causes delays in the stream affect your reading/writing logic
If the "message" being exchanged between a client and server (in either direction) can vary in size then often you need to use a strategy in order for that "message" to be exchanged in a reliable manner (aka Protocol).
Here are several different ways to handle the exchange:
have the message size encoded in a header that precedes the data - this could simply be a "number" in the first 2/4/8 bytes sent (dependent on your max message size), or could be a more exotic "header"
use a special "end of message" marker (sentinel), with the real data encoded/escaped if there is the possibility of real data being confused with an "end of marker"
use a timeout....i.e. a certain period of receiving no bytes means there is no more data for the message - however, this can be error prone with short timeouts, which can easily be hit on congested streams.
have a "command" and "data" channel on separate "connections"....this is the approach the FTP protocol uses (the advantage is clear separation of data from commands...at the expense of a 2nd connection)
Each approach has its pros and cons for "correctness".
The code below uses the "timeout" method, as that seems to be the one you want.
See http://msdn.microsoft.com/en-us/library/bk6w7hs8.aspx. You can get access to the NetworkStream
on the TCPClient
so you can change the ReadTimeout
.
string SendCmd(string cmd, string ip, int port)
{
var client = new TcpClient(ip, port);
var data = Encoding.GetEncoding(1252).GetBytes(cmd);
var stm = client.GetStream();
// Set a 250 millisecond timeout for reading (instead of Infinite the default)
stm.ReadTimeout = 250;
stm.Write(data, 0, data.Length);
byte[] resp = new byte[2048];
var memStream = new MemoryStream();
int bytesread = stm.Read(resp, 0, resp.Length);
while (bytesread > 0)
{
memStream.Write(resp, 0, bytesread);
bytesread = stm.Read(resp, 0, resp.Length);
}
return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}
As a footnote for other variations on this writing network code...when doing a Read
where you want to avoid a "block", you can check the DataAvailable
flag and then ONLY read what is in the buffer checking the .Length
property e.g. stm.Read(resp, 0, stm.Length);
Why is Git better than Subversion?
One of the things about SubVersion that irks me is that it puts its own folder in each directory of a project, whereas git only puts one in the root directory. It's not that big of a deal, but little things like that add up.
Of course, SubVersion has Tortoise, which is [usually] very nice.
Best way to copy a database (SQL Server 2008)
If you want to take a copy of a live database, do the Backup/Restore method.
[In SQLS2000, not sure about 2008:] Just keep in mind that if you are using SQL Server accounts in this database, as opposed to Windows accounts, if the master DB is different or out of sync on the development server, the user accounts will not translate when you do the restore. I've heard about an SP to remap them, but I can't remember which one it was.
Is there a label/goto in Python?
no there is an alternative way to implement goto statement
class id:
def data1(self):
name=[]
age=[]
n=1
while n>0:
print("1. for enter data")
print("2. update list")
print("3. show data")
print("choose what you want to do ?")
ch=int(input("enter your choice"))
if ch==1:
n=int(input("how many elemet you want to enter="))
for i in range(n):
name.append(input("NAME "))
age.append(int(input("age ")))
elif ch==2:
name.append(input("NAME "))
age.append(int(input("age ")))
elif ch==3:
try:
if name==None:
print("empty list")
else:
print("name \t age")
for i in range(n):
print(name[i]," \t ",age[i])
break
except:
print("list is empty")
print("do want to continue y or n")
ch1=input()
if ch1=="y":
n=n+1
else:
print("name \t age")
for i in range(n):
print(name[i]," \t ",age[i])
n=-1
p1=id()
p1.data1()
How to make --no-ri --no-rdoc the default for gem install?
Step by steps:
To create/edit the .gemrc file from the terminal:
vi ~/.gemrc
You will open a editor called vi.
paste in:
gem: --no-ri --no-rdoc
click 'esc'-button.
type in:
:exit
You can check if everything is correct with this command:
sudo /Applications/TextEdit.app/Contents/MacOS/TextEdit ~/.gemrc
Creating a Shopping Cart using only HTML/JavaScript
Here's a one page cart written in Javascript with localStorage. Here's a full working pen. Previously found on Codebox
cart.js
var cart = {
// (A) PROPERTIES
hPdt : null, // HTML products list
hItems : null, // HTML current cart
items : {}, // Current items in cart
// (B) LOCALSTORAGE CART
// (B1) SAVE CURRENT CART INTO LOCALSTORAGE
save : function () {
localStorage.setItem("cart", JSON.stringify(cart.items));
},
// (B2) LOAD CART FROM LOCALSTORAGE
load : function () {
cart.items = localStorage.getItem("cart");
if (cart.items == null) { cart.items = {}; }
else { cart.items = JSON.parse(cart.items); }
},
// (B3) EMPTY ENTIRE CART
nuke : function () {
if (confirm("Empty cart?")) {
cart.items = {};
localStorage.removeItem("cart");
cart.list();
}
},
// (C) INITIALIZE
init : function () {
// (C1) GET HTML ELEMENTS
cart.hPdt = document.getElementById("cart-products");
cart.hItems = document.getElementById("cart-items");
// (C2) DRAW PRODUCTS LIST
cart.hPdt.innerHTML = "";
let p, item, part;
for (let id in products) {
// WRAPPER
p = products[id];
item = document.createElement("div");
item.className = "p-item";
cart.hPdt.appendChild(item);
// PRODUCT IMAGE
part = document.createElement("img");
part.src = "images/" +p.img;
part.className = "p-img";
item.appendChild(part);
// PRODUCT NAME
part = document.createElement("div");
part.innerHTML = p.name;
part.className = "p-name";
item.appendChild(part);
// PRODUCT DESCRIPTION
part = document.createElement("div");
part.innerHTML = p.desc;
part.className = "p-desc";
item.appendChild(part);
// PRODUCT PRICE
part = document.createElement("div");
part.innerHTML = "$" + p.price;
part.className = "p-price";
item.appendChild(part);
// ADD TO CART
part = document.createElement("input");
part.type = "button";
part.value = "Add to Cart";
part.className = "cart p-add";
part.onclick = cart.add;
part.dataset.id = id;
item.appendChild(part);
}
// (C3) LOAD CART FROM PREVIOUS SESSION
cart.load();
// (C4) LIST CURRENT CART ITEMS
cart.list();
},
// (D) LIST CURRENT CART ITEMS (IN HTML)
list : function () {
// (D1) RESET
cart.hItems.innerHTML = "";
let item, part, pdt;
let empty = true;
for (let key in cart.items) {
if(cart.items.hasOwnProperty(key)) { empty = false; break; }
}
// (D2) CART IS EMPTY
if (empty) {
item = document.createElement("div");
item.innerHTML = "Cart is empty";
cart.hItems.appendChild(item);
}
// (D3) CART IS NOT EMPTY - LIST ITEMS
else {
let p, total = 0, subtotal = 0;
for (let id in cart.items) {
// ITEM
p = products[id];
item = document.createElement("div");
item.className = "c-item";
cart.hItems.appendChild(item);
// NAME
part = document.createElement("div");
part.innerHTML = p.name;
part.className = "c-name";
item.appendChild(part);
// REMOVE
part = document.createElement("input");
part.type = "button";
part.value = "X";
part.dataset.id = id;
part.className = "c-del cart";
part.addEventListener("click", cart.remove);
item.appendChild(part);
// QUANTITY
part = document.createElement("input");
part.type = "number";
part.value = cart.items[id];
part.dataset.id = id;
part.className = "c-qty";
part.addEventListener("change", cart.change);
item.appendChild(part);
// SUBTOTAL
subtotal = cart.items[id] * p.price;
total += subtotal;
}
// EMPTY BUTTONS
item = document.createElement("input");
item.type = "button";
item.value = "Empty";
item.addEventListener("click", cart.nuke);
item.className = "c-empty cart";
cart.hItems.appendChild(item);
// CHECKOUT BUTTONS
item = document.createElement("input");
item.type = "button";
item.value = "Checkout - " + "$" + total;
item.addEventListener("click", cart.checkout);
item.className = "c-checkout cart";
cart.hItems.appendChild(item);
}
},
// (E) ADD ITEM INTO CART
add : function () {
if (cart.items[this.dataset.id] == undefined) {
cart.items[this.dataset.id] = 1;
} else {
cart.items[this.dataset.id]++;
}
cart.save();
cart.list();
},
// (F) CHANGE QUANTITY
change : function () {
if (this.value == 0) {
delete cart.items[this.dataset.id];
} else {
cart.items[this.dataset.id] = this.value;
}
cart.save();
cart.list();
},
// (G) REMOVE ITEM FROM CART
remove : function () {
delete cart.items[this.dataset.id];
cart.save();
cart.list();
},
// (H) CHECKOUT
checkout : function () {
// SEND DATA TO SERVER
// CHECKS
// SEND AN EMAIL
// RECORD TO DATABASE
// PAYMENT
// WHATEVER IS REQUIRED
alert("TO DO");
/*
var data = new FormData();
data.append('cart', JSON.stringify(cart.items));
data.append('products', JSON.stringify(products));
var xhr = new XMLHttpRequest();
xhr.open("POST", "SERVER-SCRIPT");
xhr.onload = function(){ ... };
xhr.send(data);
*/
}
};
window.addEventListener("DOMContentLoaded", cart.init);
How to check if String is null
You can check with null or Number.
First, add a reference to Microsoft.VisualBasic
in your application.
Then, use the following code:
bool b = Microsoft.VisualBasic.Information.IsNumeric("null");
bool c = Microsoft.VisualBasic.Information.IsNumeric("abc");
In the above, b
and c
should both be false
.
PHP Session timeout
session_cache_expire( 20 );
session_start(); // NEVER FORGET TO START THE SESSION!!!
$inactive = 1200; //20 minutes *60
if(isset($_SESSION['start']) ) {
$session_life = time() - $_SESSION['start'];
if($session_life > $inactive){
header("Location: user_logout.php");
}
}
$_SESSION['start'] = time();
if($_SESSION['valid_user'] != true){
header('Location: ../....php');
}else{
source: http://www.daniweb.com/web-development/php/threads/124500
How to set underline text on textview?
You have to use SpannableString for that :
String mystring=new String("Hello.....");
SpannableString content = new SpannableString(mystring);
content.setSpan(new UnderlineSpan(), 0, mystring.length(), 0);
yourtextview.setText(content);
Update : You can refer my answer on Underling TextView's here in all possible ways.
How can I display a JavaScript object?
A little helper function I always use in my projects for simple, speedy debugging via the console.
Inspiration taken from Laravel.
/**
* @param variable mixed The var to log to the console
* @param varName string Optional, will appear as a label before the var
*/
function dd(variable, varName) {
var varNameOutput;
varName = varName || '';
varNameOutput = varName ? varName + ':' : '';
console.warn(varNameOutput, variable, ' (' + (typeof variable) + ')');
}
Usage
dd(123.55);
outputs:
var obj = {field1: 'xyz', field2: 2016};
dd(obj, 'My Cool Obj');
Create File If File Does Not Exist
You can simply call
using (StreamWriter w = File.AppendText("log.txt"))
It will create the file if it doesn't exist and open the file for appending.
Edit:
This is sufficient:
string path = txtFilePath.Text;
using(StreamWriter sw = File.AppendText(path))
{
foreach (var line in employeeList.Items)
{
Employee e = (Employee)line; // unbox once
sw.WriteLine(e.FirstName);
sw.WriteLine(e.LastName);
sw.WriteLine(e.JobTitle);
}
}
But if you insist on checking first, you can do something like this, but I don't see the point.
string path = txtFilePath.Text;
using (StreamWriter sw = (File.Exists(path)) ? File.AppendText(path) : File.CreateText(path))
{
foreach (var line in employeeList.Items)
{
sw.WriteLine(((Employee)line).FirstName);
sw.WriteLine(((Employee)line).LastName);
sw.WriteLine(((Employee)line).JobTitle);
}
}
Also, one thing to point out with your code is that you're doing a lot of unnecessary unboxing. If you have to use a plain (non-generic) collection like ArrayList
, then unbox the object once and use the reference.
However, I perfer to use List<>
for my collections:
public class EmployeeList : List<Employee>
How to insert an element after another element in JavaScript without using a library?
2018 Solution (Bad Practice, go to 2020)
I know this question is Ancient, but for any future users, heres a modified prototype
this is just a micro polyfill for the .insertAfter function that doesnt exist
this prototype directly adds a new function baseElement.insertAfter(element);
to the Element prototype:
Element.prototype.insertAfter = function(new) {
this.parentNode.insertBefore(new, this.nextSibling);
}
Once youve placed the polyfill in a library, gist, or just in your code (or anywhere else where it can be referenced)
Just write document.getElementById('foo').insertAfter(document.createElement('bar'));
2019 Solution (Ugly, go to 2020)
You SHOULD NOT USE PROTOTYPES. They overwrite the default codebase and arent very efficient or safe and can cause compatibility errors, but if its for non-commercial projects, it shouldnt matter.
if you want a safe function for commercial use, just use a default function. its not pretty but it works:
function insertAfter(el, newEl) {
el.parentNode.insertBefore(newEl, this.nextSibling);
}
// use
const el = document.body || document.querySelector("body");
// the || means "this OR that"
el.insertBefore(document.createElement("div"), el.nextSibling);
// Insert Before
insertAfter(el, document.createElement("div"));
// Insert After
2020 Solution
Current Web Standards for ChildNode: https://developer.mozilla.org/en-US/docs/Web/API/ChildNode
Its currently in the Living Standards and is SAFE.
For Unsupported Browsers, use this Polyfill: https://github.com/seznam/JAK/blob/master/lib/polyfills/childNode.js
Someone mentioned that the Polyfill uses Protos, when I said they were bad practice. They are, especially when they are used blindly and overwrited, like with my 2018 solution. However, that polyfill is on the MDN Documentation and uses a kind of initialization and execution that is safer.
How to use the 2020 Solution:
// Parent Element
const el = document.querySelector(".class");
// Create New Element
const newEl = document.createElement("div");
newEl.id = "foo";
// Insert New Element BEFORE an Element
el.before(newEl);
// Insert New Element AFTER an Element
el.after(newEl);
// Remove an Element
el.remove();
// Even though it’s a created element,
// newEl is still a reference to the HTML,
// so using .remove() on it should work
// if you have already appended it somewhere
newEl.remove();
MySQL load NULL values from CSV data
This will do what you want. It reads the fourth field into a local variable, and then sets the actual field value to NULL, if the local variable ends up containing an empty string:
LOAD DATA INFILE '/tmp/testdata.txt'
INTO TABLE moo
FIELDS TERMINATED BY ","
LINES TERMINATED BY "\n"
(one, two, three, @vfour, five)
SET four = NULLIF(@vfour,'')
;
If they're all possibly empty, then you'd read them all into variables and have multiple SET statements, like this:
LOAD DATA INFILE '/tmp/testdata.txt'
INTO TABLE moo
FIELDS TERMINATED BY ","
LINES TERMINATED BY "\n"
(@vone, @vtwo, @vthree, @vfour, @vfive)
SET
one = NULLIF(@vone,''),
two = NULLIF(@vtwo,''),
three = NULLIF(@vthree,''),
four = NULLIF(@vfour,'')
;
javascript, is there an isObject function like isArray?
You can use typeof operator.
if( (typeof A === "object" || typeof A === 'function') && (A !== null) )
{
alert("A is object");
}
Note that because typeof new Number(1) === 'object'
while typeof Number(1) === 'number';
the first syntax should be avoided.
Media query to detect if device is touchscreen
The CSS solutions don't appear to be widely available as of mid-2013. Instead...
Nicholas Zakas explains that Modernizr applies a no-touch
CSS class when the browser doesn’t support touch.
Or detect in JavaScript with a simple piece of code, allowing you to implement your own Modernizr-like solution:
<script>
document.documentElement.className +=
(("ontouchstart" in document.documentElement) ? ' touch' : ' no-touch');
</script>
Then you can write your CSS as:
.no-touch .myClass {
...
}
.touch .myClass {
...
}
ASP.NET Display "Loading..." message while update panel is updating
You can use code as below when
using Image as Loading
<asp:UpdateProgress id="updateProgress" runat="server">
<ProgressTemplate>
<div style="position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;">
<asp:Image ID="imgUpdateProgress" runat="server" ImageUrl="~/images/ajax-loader.gif" AlternateText="Loading ..." ToolTip="Loading ..." style="padding: 10px;position:fixed;top:45%;left:50%;" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
using Text as Loading
<asp:UpdateProgress id="updateProgress" runat="server">
<ProgressTemplate>
<div style="position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;">
<span style="border-width: 0px; position: fixed; padding: 50px; background-color: #FFFFFF; font-size: 36px; left: 40%; top: 40%;">Loading ...</span>
</div>
</ProgressTemplate>
</asp:UpdateProgress>
What is Java Servlet?
In addition to the above, and just to point out the bleedin' obvious...
To many this is hyper obvious, but to someone used to writing apps which are just run and then end: a servlet spends most of its time hanging around doing nothing... waiting to be sent something, a request, and then responding to it. For this reason a servlet has a lifetime: it is initalised and then waits around, responding to anything thrown at it, and is then destroyed. Which implies that it has to be created (and later destroyed) by something else (a framework), that it runs in its own thread or process, and that it does nothing unless asked to. And also that, by some means or other, a mechanism must be implemented whereby this "entity" can "listen" for requests.
I suggest that reading about threads, processes and sockets will throw some light on this: it's quite different to the way a basic "hello world" app functions.
It could be argued that the term "server" or "servlet" is a bit of an overkill. A more rational and simpler name might be "responder". The reason for the choice of the term "server" is historical: the first such arrangements were "file servers", where multiple user/client terminals would ask for a specific file from a central machine, and this file would then be "served up" like a book or a plate of fish and chips.
Changing tab bar item image and text color iOS
Swift
For Image:
custom.tabBarItem = UITabBarItem(title: "Home", image: UIImage(named: "tab_icon_normal"), selectedImage: UIImage(named: "tab_icon_selected"))
For Text:
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.gray], for: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red], for: .selected)
printf a variable in C
As Shafik already wrote you need to use the right format because scanf
gets you a char.
Don't hesitate to look here if u aren't sure about the usage: http://www.cplusplus.com/reference/cstdio/printf/
Hint: It's faster/nicer to write x=x+1
; the shorter way: x++;
Sorry for answering what's answered just wanted to give him the link - the site was really useful to me all the time dealing with C.
How can I find a specific element in a List<T>?
var list = new List<MyClass>();
var item = list.Find( x => x.GetId() == "TARGET_ID" );
or if there is only one and you want to enforce that something like SingleOrDefault
may be what you want
var item = list.SingleOrDefault( x => x.GetId() == "TARGET" );
if ( item == null )
throw new Exception();
SELECT COUNT in LINQ to SQL C#
You should be able to do the count on the purch variable:
purch.Count();
e.g.
var purch = from purchase in myBlaContext.purchases
select purchase;
purch.Count();
How to play an android notification sound
If anyone's still looking for a solution to this, I found an answer at How to play ringtone/alarm sound in Android
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
You can change TYPE_NOTIFICATION to TYPE_ALARM, but you'll want to keep track of your Ringtone r in order to stop playing it... say, when the user clicks a button or something.
length and length() in Java
I was taught that for arrays, length is not retrieved through a method due to the following fear: programmers would just assign the length to a local variable before entering a loop (think a for loop where the conditional uses the array's length.) The programmer would supposedly do so to trim down on function calls (and thereby improve performance.) The problem is that the length might change during the loop, and the variable wouldn't.
Aesthetics must either be length one, or the same length as the dataProblems
Similar to @joran's answer. Reshape the df so that the prices for each product are in different columns:
xx <- reshape(df, idvar=c("skew","version","color"),
v.names="price", timevar="product", direction="wide")
xx will have columns price.p1, ... price.p4, so:
ggp <- ggplot(xx,aes(x=price.p1, y=price.p3, color=factor(skew))) +
geom_point(shape=19, size=5)
ggp + facet_grid(color~version)
gives the result from your image.
JavaScript/jQuery - "$ is not defined- $function()" error
if you are trying to use jquery in your electron app before adding jquery you should add it to your modules:
<script>
if (typeof module === 'object') {
window.module = module;
module = undefined;
}
</script>
<script src="js/jquery-3.5.1.min.js"></script>
CSS vertical alignment of inline/inline-block elements
vertical-align
applies to the elements being aligned, not their parent element. To vertically align the div's children, do this instead:
div > * {
vertical-align:middle; // Align children to middle of line
}
See: http://jsfiddle.net/dfmx123/TFPx8/1186/
NOTE: vertical-align
is relative to the current text line, not the full height of the parent div
. If you wanted the parent div
to be taller and still have the elements vertically centered, set the div
's line-height
property instead of its height
. Follow jsfiddle link above for an example.
Compare two List<T> objects for equality, ignoring order
As written, this question is ambigous. The statement:
... they both have the same elements, regardless of their position within the list.
Each MyType object may appear multiple times on a list.
does not indicate whether you want to ensure that the two lists have the same set of objects or the same distinct set.
If you want to ensure to collections have exactly the same set of members regardless of order, you can use:
// lists should have same count of items, and set difference must be empty
var areEquivalent = (list1.Count == list2.Count) && !list1.Except(list2).Any();
If you want to ensure two collections have the same distinct set of members (where duplicates in either are ignored), you can use:
// check that [(A-B) Union (B-A)] is empty
var areEquivalent = !list1.Except(list2).Union( list2.Except(list1) ).Any();
Using the set operations (Intersect
, Union
, Except
) is more efficient than using methods like Contains
. In my opinion, it also better expresses the expectations of your query.
EDIT: Now that you've clarified your question, I can say that you want to use the first form - since duplicates matter. Here's a simple example to demonstrate that you get the result you want:
var a = new[] {1, 2, 3, 4, 4, 3, 1, 1, 2};
var b = new[] { 4, 3, 2, 3, 1, 1, 1, 4, 2 };
// result below should be true, since the two sets are equivalent...
var areEquivalent = (a.Count() == b.Count()) && !a.Except(b).Any();
Android - Best and safe way to stop thread
Currently and unfortunately we can't do anything to stop the thread....
Adding something to Matt's answer we can call interrupt()
but that doesn't stop thread... Just tells the system to stop the thread when system wants to kill some threads. Rest is done by system, and we can check it by calling interrupted()
.
[p.s. : If you are really going with interrupt()
I would ask you to do some experiments with a short sleep after calling interrupt()
]
Clone private git repo with dockerfile
My key was password protected which was causing the problem, a working file is now listed below (for help of future googlers)
FROM ubuntu
MAINTAINER Luke Crooks "[email protected]"
# Update aptitude with new repo
RUN apt-get update
# Install software
RUN apt-get install -y git
# Make ssh dir
RUN mkdir /root/.ssh/
# Copy over private key, and set permissions
# Warning! Anyone who gets their hands on this image will be able
# to retrieve this private key file from the corresponding image layer
ADD id_rsa /root/.ssh/id_rsa
# Create known_hosts
RUN touch /root/.ssh/known_hosts
# Add bitbuckets key
RUN ssh-keyscan bitbucket.org >> /root/.ssh/known_hosts
# Clone the conf files into the docker container
RUN git clone [email protected]:User/repo.git
Django URL Redirect
If you are stuck on django 1.2 like I am and RedirectView doesn't exist, another route-centric way to add the redirect mapping is using:
(r'^match_rules/$', 'django.views.generic.simple.redirect_to', {'url': '/new_url'}),
You can also re-route everything on a match. This is useful when changing the folder of an app but wanting to preserve bookmarks:
(r'^match_folder/(?P<path>.*)', 'django.views.generic.simple.redirect_to', {'url': '/new_folder/%(path)s'}),
This is preferable to django.shortcuts.redirect if you are only trying to modify your url routing and do not have access to .htaccess, etc (I'm on Appengine and app.yaml doesn't allow url redirection at that level like an .htaccess).
How to change RGB color to HSV?
FIRST: make sure you have a color as a bitmap, like this:
Bitmap bmp = (Bitmap)pictureBox1.Image.Clone();
paintcolor = bmp.GetPixel(e.X, e.Y);
(e is from the event handler wich picked my color!)
What I did when I had this problem a whilke ago, I first got the rgba (red, green, blue and alpha) values.
Next I created 3 floats: float hue, float saturation, float brightness. Then you simply do:
hue = yourcolor.Gethue;
saturation = yourcolor.GetSaturation;
brightness = yourcolor.GetBrightness;
The whole lot looks like this:
Bitmap bmp = (Bitmap)pictureBox1.Image.Clone();
paintcolor = bmp.GetPixel(e.X, e.Y);
float hue;
float saturation;
float brightness;
hue = paintcolor.GetHue();
saturation = paintcolor.GetSaturation();
brightness = paintcolor.GetBrightness();
If you now want to display them in a label, just do:
yourlabelname.Text = hue.ToString;
yourlabelname.Text = saturation.ToString;
yourlabelname.Text = brightness.ToString;
Here you go, you now have RGB Values into HSV values :)
Hope this helps
How can I create a copy of an Oracle table without copying the data?
The task above can be completed in two simple steps.
STEP 1:
CREATE table new_table_name AS(Select * from old_table_name);
The query
above creates a duplicate of a table (with contents as well).
To get the structure, delete the contents of the table using.
STEP 2:
DELETE * FROM new_table_name.
Hope this solves your problem. And thanks to the earlier posts. Gave me a lot of insight.
Getting files by creation date in .NET
@jing: "The DirectoryInfo solution is much faster then this (especially for network path)"
I cant confirm this.
It seems as if Directory.GetFiles triggers a filesystem or network cache.
The first request takes a while, but the following requests are much faster, even if new files were added.
In my test I did a Directory.getfiles and a info.GetFiles with the same patterns and both run equally
GetFiles done 437834 in00:00:20.4812480
process files done 437834 in00:00:00.9300573
GetFiles by Dirinfo(2) done 437834 in00:00:20.7412646
Why doesn't indexOf work on an array IE8?
If you're using jQuery and want to keep using indexOf without worrying about compatibility issues, you can do this :
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(val) {
return jQuery.inArray(val, this);
};
}
This is helpful when you want to keep using indexOf
but provide a fallback when it's not available.
AngularJS HTTP post to PHP and undefined
You need to deserialize your form data before passing it as the second parameter to .post (). You can achieve this using jQuery's $.param (data) method.
Then you will be able to on server side to reference it like $.POST ['email'];
Changing project port number in Visual Studio 2013
The Visual Studio Development Server option applies only when you are
running (testing) the Web project in Visual Studio. Production Web
applications always run under IIS.
To specify the Web server for a Web site project
- In Solution Explorer, right-click the name of the Web site project for which you want to specify a Web server, and then click Property
Pages.
- In the Property Pages dialog box, click the Start Options tab.
- Under Server, click Use custom server.
- In the Base URL box, type the URL that Visual Studio should start when running the current project.
Note: If you specify the URL of a remote server (for example, an IIS Web application on another computer), be sure that the remote server is running at least the .NET Framework version 2.0.
To specify the Web server for a Web application project
- In Solution Explorer, right-click the name of the Web application project for which you want to specify a Web server, and then click
Properties.
- In the Properties window, click the Web tab.
- Under Servers, click Use Visual Studio Development Server or Use Local IIS Web server or Use Custom Web server.
- If you clicked Local IIS Web server or Use Custom Web Server, in the Base URL box, type the URL that Visual Studio should start when
running the current project.
Note: If you clicked Use Custom Web Server and specify the URL of a remote server (for example, an IIS Web application on another computer), be sure that the remote server is running at least the .NET Framework version 2.0.
(Source: https://msdn.microsoft.com/en-us/library/ms178108.aspx)
Getting the encoding of a Postgres database
Method 1:
If you're already logged in to the db server, just copy and paste this.
SHOW SERVER_ENCODING;
Result:
server_encoding
-----------------
UTF8
For Client encoding :
SHOW CLIENT_ENCODING;
Method 2:
Again if you are already logged in, use this to get the list based result
\l
Cassandra "no viable alternative at input"
Wrong syntax. Here you are:
insert into user_by_category (game_category,customer_id) VALUES
('Goku','12');
or:
insert into user_by_category ("game_category","customer_id") VALUES
('Kakarot','12');
The second one is normally used for case-sensitive column names.
Shortcut for changing font size
You'll probably find these shortcuts useful:
Ctrl+Shift+. to zoom in.
Ctrl+Shift+, to zoom out.
Those characters are period and comma, respectively.
How do I put the image on the right side of the text in a UIButton?
Just update the insets when the title is changed. You need to compensate for the inset with an equal and opposite inset on the other side.
[thebutton setTitle:title forState:UIControlStateNormal];
thebutton.titleEdgeInsets = UIEdgeInsetsMake(0, -thebutton.imageView.frame.size.width, 0, thebutton.imageView.frame.size.width);
thebutton.imageEdgeInsets = UIEdgeInsetsMake(0, thebutton.titleLabel.frame.size.width, 0, -thebutton.titleLabel.frame.size.width);
TypeError: Cannot read property "0" from undefined
For me, the problem was I was using a package that isn't included in package.json
nor installed.
import { ToastrService } from 'ngx-toastr';
So when the compiler tried to compile this, it threw an error.
(I installed it locally, and when running a build on an external server the error was thrown)
How to get text of an input text box during onKeyPress?
keep it Compact.
Each time you press a key, the function edValueKeyPress()
is called.
You've also declared and initialized some variables in that function - which slow down the process and requires more CPU and memory as well.
You can simply use this code - derived from simple substitution.
function edValueKeyPress()
{
document.getElementById("lblValue").innerText =""+document.getElementById("edValue").value;
}
That's all you want, and it's faster!
Best way to repeat a character in C#
You can create an extension method
static class MyExtensions
{
internal static string Repeat(this char c, int n)
{
return new string(c, n);
}
}
Then you can use it like this
Console.WriteLine('\t'.Repeat(10));
How to properly highlight selected item on RecyclerView?
UPDATE [26/Jul/2017]:
As the Pawan mentioned in the comment about that IDE warning about not to using that
fixed position, I have just modified my code as below. The click
listener is moved to ViewHolder
, and there I am getting the position
using getAdapterPosition()
method
int selected_position = 0; // You have to set this globally in the Adapter class
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Item item = items.get(position);
// Here I am just highlighting the background
holder.itemView.setBackgroundColor(selected_position == position ? Color.GREEN : Color.TRANSPARENT);
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// Below line is just like a safety check, because sometimes holder could be null,
// in that case, getAdapterPosition() will return RecyclerView.NO_POSITION
if (getAdapterPosition() == RecyclerView.NO_POSITION) return;
// Updating old as well as new positions
notifyItemChanged(selected_position);
selected_position = getAdapterPosition();
notifyItemChanged(selected_position);
// Do your another stuff for your onClick
}
}
hope this'll help.
How to enable Google Play App Signing
While Migrating Android application package file (APK) to Android App Bundle (AAB), publishing app into Play Store i faced this issue and got resolved like this below...
When building .aab
file you get prompted for the location to store key export path as below:
In second image you find Encrypted key export path Location where our .pepk will store in the specific folder while generating .aab file.
Once you log in to the Google Play Console with play store credential:
select your project from left side choose App Signing option Release Management>>App Signing
you will find the Google App Signing Certification window ACCEPT it.
After that you will find three radio button select
**
Upload a key exported from Android Studio radio button
**, it will expand you
APP SIGNING PRIVATE KEY button as below
click on the button and choose the .pepk
file (We Stored while generating .aab
file as above)
Read the all other option and submit.
Once Successfully you can go back to app release and browse the .aab file and complete RollOut...
@Ambilpura
How to set default text for a Tkinter Entry widget
Use Entry.insert
. For example:
try:
from tkinter import * # Python 3.x
except Import Error:
from Tkinter import * # Python 2.x
root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()
Or use textvariable
option:
try:
from tkinter import * # Python 3.x
except Import Error:
from Tkinter import * # Python 2.x
root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()
How is Java platform-independent when it needs a JVM to run?
When we compile C source data, it generate native code which can be understood by current operating system.
When we move this source code to the other operating system, it can't be understood by operating system because of native code that means representation is change from O.S to O.S.
So C or C++ are platform dependent .
Now in case of java, after compilation we get byte code instead of native code. When we will run the byte code,
it is converted into native code with the help of JVM and then it will be executed.
So Java is platform independent and C or C++ is not platform independent.
Python dictionary replace values
via dict.update() function
In case you need a declarative solution, you can use dict.update()
to change values in a dict.
Either like this:
my_dict.update({'key1': 'value1', 'key2': 'value2'})
or like this:
my_dict.update(key1='value1', key2='value2')
via dictionary unpacking
Since Python 3.5 you can also use dictionary unpacking for this:
my_dict = { **my_dict, 'key1': 'value1', 'key2': 'value2'}
Note: This creates a new dictionary.
via merge operator or update operator
Since Python 3.9 you can also use the merge operator on dictionaries:
my_dict = my_dict | {'key1': 'value1', 'key2': 'value2'}
Note: This creates a new dictionary.
Or you can use the update operator:
my_dict |= {'key1': 'value1', 'key2': 'value2'}
Inner text shadow with CSS
For normal-sized text on small-ish buttons
I found the other ideas on this page to lose their efficacy when used on small buttons with small text lettering. This answer expands on RobertPitt's answer.
Here is the minor tweak:
text-shadow: 1px 1px transparent, -1px -1px black;
_x000D_
_x000D_
$('button').click(function(){
$('button').removeClass('btnActive');
$(this).addClass('btnActive');
});
_x000D_
body{background:#666;}
.btnActive{
border: 1px solid #aaa;
border-top: 1px solid #333;
border-left: 1px solid #333;
color: #ecf0f8;
background-color: #293d70;
background-image: none;
text-shadow: 1px 1px transparent, -1px -1px black;
outline:none;
}
button{
border: 1px solid #446;
border-radius: 3px;
color: white;
background-color: #385499;
background-image: linear-gradient(-180deg,##7d94cf,#1c294a 90%);
cursor: pointer;
font-size: 14px;
font-weight: 600;
padding: 6px 12px;
xxtext-shadow: 1px 1px 2px navy;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btnActive">Option One</button>
<button>Option Two</button>
_x000D_
_x000D_
_x000D_
Note:
I used this site to finesse the color shades.
Button inside of anchor link works in Firefox but not in Internet Explorer?
If you're using a framework like Twitter bootstrap you could simply add class "btn" to an a tag -- I just had a user call in about this problem apparently my checkout button wasn't working because I had a button inside an a tag... instead I just added the btn class to it and it works perfectly now.. Big mistake, one that probably cost customers -- and I sometimes forget to code check everything works in IE..
E.g.
<a href="link.com" class="btn" >Checkout</a>
random.seed(): What does it do?
A random number is generated by some operation on previous value.
If there is no previous value then the current time is taken as previous value automatically. We can provide this previous value by own using random.seed(x)
where x
could be any number or string etc.
Hence random.random()
is not actually perfect random number, it could be predicted via random.seed(x)
.
import random
random.seed(45) #seed=45
random.random() #1st rand value=0.2718754143840908
0.2718754143840908
random.random() #2nd rand value=0.48802820785090784
0.48802820785090784
random.seed(45) # again reasign seed=45
random.random()
0.2718754143840908 #matching with 1st rand value
random.random()
0.48802820785090784 #matching with 2nd rand value
Hence, generating a random number is not actually random, because it runs on algorithms. Algorithms always give the same output based on the same input. This means, it depends on the value of the seed. So, in order to make it more random, time is automatically assigned to seed()
.
How to install PyQt5 on Windows?
One of the most (probably the most) easiest way to install site-packages like PyQt5 is installing one of the versions of Anaconda. You can just install many of site-packages by installing it. List of avaliable site-packages with Anaconda versions can be checked here.
- Dowload Anaconda3 or Anaconda2
- Install it.
- Add PyQt5's path inside Anaconda installation to your System Environment Variables.
For example:
PATH: ....; C:\Anaconda3\Lib\site-packages\PyQt5; ...
- It is ready to use.
Python: Figure out local timezone
First get pytz and tzlocal modules
pip install pytz tzlocal
then
from tzlocal import get_localzone
local = get_localzone()
then you can do things like
from datetime import datetime
print(datetime.now(local))
LaTeX Optional Arguments
Here's my attempt, it doesn't follow your specs exactly though. Not fully tested, so be cautious.
\newcount\seccount
\def\sec{%
\seccount0%
\let\go\secnext\go
}
\def\secnext#1{%
\def\last{#1}%
\futurelet\next\secparse
}
\def\secparse{%
\ifx\next\bgroup
\let\go\secparseii
\else
\let\go\seclast
\fi
\go
}
\def\secparseii#1{%
\ifnum\seccount>0, \fi
\advance\seccount1\relax
\last
\def\last{#1}%
\futurelet\next\secparse
}
\def\seclast{\ifnum\seccount>0{} and \fi\last}%
\sec{a}{b}{c}{d}{e}
% outputs "a, b, c, d and e"
\sec{a}
% outputs "a"
\sec{a}{b}
% outputs "a and b"
How to right-align and justify-align in Markdown?
Specific to your usage of a Jupyter Notebook: the ability to specify table column alignment should return in a future release. (Current releases default to right-aligned everywhere.)
From PR #4130:
Allow markdown tables to specify their alignment with the :--, :--:, --: syntax while still allowing --- to default to right alignment.
This reverts a previous change (part of #2534) that stripped the alignment information from the rendered HTML coming out of the marked renderer. To be clear this does not change the right alignment default but does bring back support for overriding this alignment per column by using the gfm table alignment syntax.
...
select data up to a space?
You can use a combiation of LEFT
and CHARINDEX
to find the index of the first space, and then grab everything to the left of that.
SELECT LEFT(YourColumn, charindex(' ', YourColumn) - 1)
And in case any of your columns don't have a space in them:
SELECT LEFT(YourColumn, CASE WHEN charindex(' ', YourColumn) = 0 THEN
LEN(YourColumn) ELSE charindex(' ', YourColumn) - 1 END)
How to make HTML code inactive with comments
If you are using Eclipse then the keyboard shortcut is Ctrl + Shift + / to add a group of code. To make a comment line or select the code, right click -> Source -> Add Block Comment.
To remove the block comment, Ctrl + Shift + \ or right click -> Source -> Remove Block comment.
error: passing xxx as 'this' argument of xxx discards qualifiers
Let's me give a more detail example. As to the below struct:
struct Count{
uint32_t c;
Count(uint32_t i=0):c(i){}
uint32_t getCount(){
return c;
}
uint32_t add(const Count& count){
uint32_t total = c + count.getCount();
return total;
}
};
As you see the above, the IDE(CLion), will give tips Non-const function 'getCount' is called on the const object
. In the method add
count
is declared as const object, but the method getCount
is not const method, so count.getCount()
may change the members in count
.
Compile error as below(core message in my compiler):
error: passing 'const xy_stl::Count' as 'this' argument discards qualifiers [-fpermissive]
To solve the above problem, you can:
- change the method
uint32_t getCount(){...}
to uint32_t getCount() const {...}
. So count.getCount()
won't change the members in count
.
or
- change
uint32_t add(const Count& count){...}
to uint32_t add(Count& count){...}
. So count
don't care about changing members in it.
As to you problem, objects in the std::set are stored as const StudentT, but the method getId
and getName
are not const, so you give the above error.
You can also see this question Meaning of 'const' last in a function declaration of a class? for more detail.
nodejs get file name from absolute path?
var path = require("path");
var filepath = "C:\\Python27\\ArcGIS10.2\\python.exe";
var name = path.parse(filepath).name;
// returns
'python'
Above code returns the name of the file without extension, if you need the name with extention use
var path = require("path");
var filepath = "C:\\Python27\\ArcGIS10.2\\python.exe";
var name = path.basename(filepath);
// returns
'python.exe'
Yahoo Finance API
You may use YQL however yahoo.finance.* tables are not the core yahoo tables. It is an open data table which uses the 'csv api' and converts it to json or xml format. It is more convenient to use but it's not always reliable. I could not use it just a while ago because it the table hits its storage limit or something...
You may use this php library to get historical data / quotes using YQL
https://github.com/aygee/php-yql-finance
Write to custom log file from a Bash script
logger
logs to syslog facilities. If you want the message to go to a particular file you have to modify the syslog configuration accordingly. You could add a line like this:
local7.* -/var/log/mycustomlog
and restart syslog. Then you can log like this:
logger -p local7.info "information message"
logger -p local7.err "error message"
and the messages will appear in the desired logfile with the correct log level.
Without making changes to the syslog configuration you could use logger
like this:
logger -s "foo bar" >> /var/log/mycustomlog
That would instruct logger
to print the message to STDERR as well (in addition to logging it to syslog), so you could redirect STDERR to a file. However, it would be utterly pointless, because the message is already logged via syslog anyway (with the default priority user.notice
).
Converting a datetime string to timestamp in Javascript
Parsing dates is a pain in JavaScript as there's no extensive native support. However you could do something like the following by relying on the Date(year, month, day [, hour, minute, second, millisecond])
constructor signature of the Date
object.
var dateString = '17-09-2013 10:08',
dateTimeParts = dateString.split(' '),
timeParts = dateTimeParts[1].split(':'),
dateParts = dateTimeParts[0].split('-'),
date;
date = new Date(dateParts[2], parseInt(dateParts[1], 10) - 1, dateParts[0], timeParts[0], timeParts[1]);
console.log(date.getTime()); //1379426880000
console.log(date); //Tue Sep 17 2013 10:08:00 GMT-0400
You could also use a regular expression with capturing groups to parse the date string in one line.
var dateParts = '17-09-2013 10:08'.match(/(\d+)-(\d+)-(\d+) (\d+):(\d+)/);
console.log(dateParts); // ["17-09-2013 10:08", "17", "09", "2013", "10", "08"]
How to make layout with View fill the remaining space?
In case if < TEXT VIEW > is placed in LinearLayout, set the Layout_weight proprty of < and > to 0 and 1 for TextView.
In case of RelativeLayout align < and > to left and right and set "Layout to left of" and "Layout to right of" property of TextView to ids of < and >
Sending a mail from a linux shell script
On linux, mail utility can be used to send attachment with option "-a". Go through man pages to read about the option. For eg following code will send an attachment :
mail -s "THIS IS SUBJECT" -a attachment.txt [email protected] <<< "Hi Buddy, Please find failure reports."
Error - is not marked as serializable
Leaving my specific solution of this for prosperity, as it's a tricky version of this problem:
Type 'System.Linq.Enumerable+WhereSelectArrayIterator[T...] was not marked as serializable
Due to a class with an attribute IEnumerable<int>
eg:
[Serializable]
class MySessionData{
public int ID;
public IEnumerable<int> RelatedIDs; //This can be an issue
}
Originally the problem instance of MySessionData
was set from a non-serializable list:
MySessionData instance = new MySessionData(){
ID = 123,
RelatedIDs = nonSerizableList.Select<int>(item => item.ID)
};
The cause here is the concrete class that the Select<int>(...)
returns, has type data that's not serializable, and you need to copy the id's to a fresh List<int>
to resolve it.
RelatedIDs = nonSerizableList.Select<int>(item => item.ID).ToList();
How do I create a file AND any folders, if the folders don't exist?
You will need to check both parts of the path (directory and filename) and create each if it does not exist.
Use File.Exists
and Directory.Exists
to find out whether they exist. Directory.CreateDirectory
will create the whole path for you, so you only ever need to call that once if the directory does not exist, then simply create the file.
How to read from a file or STDIN in Bash?
I don't find any of these answers acceptable. In particular, the accepted answer only handles the first command line parameter and ignores the rest. The Perl program that it is trying to emulate handles all the command line parameters. So the accepted answer doesn't even answer the question. Other answers use bash extensions, add unnecessary 'cat' commands, only work for the simple case of echoing input to output, or are just unnecessarily complicated.
However, I have to give them some credit because they gave me some ideas. Here is the complete answer:
#!/bin/sh
if [ $# = 0 ]
then
DEFAULT_INPUT_FILE=/dev/stdin
else
DEFAULT_INPUT_FILE=
fi
# Iterates over all parameters or /dev/stdin
for FILE in "$@" $DEFAULT_INPUT_FILE
do
while IFS= read -r LINE
do
# Do whatever you want with LINE here.
echo $LINE
done < "$FILE"
done
OS specific instructions in CMAKE: How to?
Use some preprocessor macro to check if it's in windows or linux.
For example
#ifdef WIN32
LIB=
#elif __GNUC__
LIB=wsock32
#endif
include -l$(LIB) in you build command.
You can also specify some command line argument to differentiate both.
Send Outlook Email Via Python?
This was one I tried using Win32:
import win32com.client as win32
import psutil
import os
import subprocess
import sys
# Drafting and sending email notification to senders. You can add other senders' email in the list
def send_notification():
outlook = win32.Dispatch('outlook.application')
olFormatHTML = 2
olFormatPlain = 1
olFormatRichText = 3
olFormatUnspecified = 0
olMailItem = 0x0
newMail = outlook.CreateItem(olMailItem)
newMail.Subject = sys.argv[1]
#newMail.Subject = "check"
newMail.BodyFormat = olFormatHTML #or olFormatRichText or olFormatPlain
#newMail.HTMLBody = "test"
newMail.HTMLBody = sys.argv[2]
newMail.To = "[email protected]"
attachment1 = sys.argv[3]
attachment2 = sys.argv[4]
newMail.Attachments.Add(attachment1)
newMail.Attachments.Add(attachment2)
newMail.display()
# or just use this instead of .display() if you want to send immediately
newMail.Send()
# Open Outlook.exe. Path may vary according to system config
# Please check the path to .exe file and update below
def open_outlook():
try:
subprocess.call(['C:\Program Files\Microsoft Office\Office15\Outlook.exe'])
os.system("C:\Program Files\Microsoft Office\Office15\Outlook.exe");
except:
print("Outlook didn't open successfully")
#
# Checking if outlook is already opened. If not, open Outlook.exe and send email
for item in psutil.pids():
p = psutil.Process(item)
if p.name() == "OUTLOOK.EXE":
flag = 1
break
else:
flag = 0
if (flag == 1):
send_notification()
else:
open_outlook()
send_notification()
Hive load CSV with commas in quoted fields
The problem is that Hive
doesn't handle quoted texts. You either need to pre-process the data by changing the delimiter between the fields (e.g: with a Hadoop-streaming job) or you can also give a try to use a custom CSV SerDe which uses OpenCSV to parse the files.
Reactjs: Unexpected token '<' Error
The issue Unexpected token '<' is because of missing the babel preset.
Solution : You have to configure your webpack configuration as follows
{
test : /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader : 'babel',
query : {
presets:[ 'react', 'es2015' ]
}
}
here .jsx checks both .js and .jsx formats.
you can simply install the babel dependency using node as follows
npm install babel-preset-react
Thank you
how to get the last character of a string?
Use charAt
:
The charAt() method returns the character at the specified index in a string.
You can use this method in conjunction with the length
property of a string to get the last character in that string.
For example:
_x000D_
_x000D_
const myString = "linto.yahoo.com.";_x000D_
const stringLength = myString.length; // this will be 16_x000D_
console.log('lastChar: ', myString.charAt(stringLength - 1)); // this will be the string
_x000D_
_x000D_
_x000D_