How do I remove link underlining in my HTML email?
Windows Mail seemed to outright ignore inline text-decoration
tag but what fixed it for me was by adding this to the head:
<!--[if (mso)|(mso 16)]>
<style type="text/css">
body, table, td, a, span { font-family: Arial, Helvetica, sans-serif !important; }
a {text-decoration: none;}
</style>
<![endif]-->
What is the difference between ports 465 and 587?
I use port 465 all the time.
The answer by danorton is outdated. As he and Wikipedia say, port 465 was initially planned for the SMTPS encryption and quickly deprecated 15 years ago. But a lot of ISPs are still using port 465, especially to be in compliance with the current recommendations of RFC 8314, which encourages the use of implicit TLS instead of the use of the STARTTLS command with port 587. (See section 3.3). Using port 465 is the only way to begin an implicitly secure session with an SMTP server that is acting as a mail submission agent (MSA).
Basically, what RFC 8314 recommends is that cleartext email exchanges be abandoned and that all three common IETF mail protocols be used only in implicit TLS sessions for consistency when possible. The recommended secure ports, then, are 465, 993, and 995 for SMTPS, IMAP4S, and POP3S, respectively.
Although RFC 8314 certainly allows the continued use of explicit TLS with port 587 and the STARTTLS command, doing so opens up the mail user agent (MUA, the mail client) to a downgrade attack where a man-in-the-middle intercepts the STARTTLS request to upgrade to TLS security but denies it, thus forcing the session to remain in cleartext.
What is the behavior difference between return-path, reply-to and from?
I had to add a Return-Path header in emails send by a Redmine instance.
I agree with greatwolf only the sender can determine a correct (non default) Return-Path.
The case is the following :
E-mails are send with the default email address : [email protected]
But we want that the real user initiating the action receives the bounce emails, because he will be the one knowing how to fix wrong recipients emails (and not the application adminstrators that have other cats to whip :-) ).
We use this and it works perfectly well with exim on the application server and zimbra as the final company mail server.
Error - Unable to access the IIS metabase
Navigating to folder: %systemroot%\System32\inetsrv\config
presents a security dialog. Click continue and this may resolve the issue. This has worked on two separate Win 10/VS 2017/IIS machines.
What is the maximum characters for the NVARCHAR(MAX)?
From MSDN Documentation
nvarchar [ ( n | max ) ]
Variable-length Unicode string data. n defines the string length and can be a value from 1 through 4,000. max indicates that the maximum storage size is 2^31-1 bytes (2 GB).
The storage size, in bytes, is two times the actual length of data entered + 2 bytes
AttributeError: 'datetime' module has no attribute 'strptime'
If I had to guess, you did this:
import datetime
at the top of your code. This means that you have to do this:
datetime.datetime.strptime(date, "%Y-%m-%d")
to access the strptime
method. Or, you could change the import statement to this:
from datetime import datetime
and access it as you are.
The people who made the datetime
module also named their class datetime
:
#module class method
datetime.datetime.strptime(date, "%Y-%m-%d")
insert echo into the specific html element like div which has an id or class
Well from your code its clear that $row['name'] is the location of the image on the file, try including the div tag like this
echo '<div>' .$row['name']. '</div>' ;
and do the same for others, let me know if it works because you said that one snippet of your code is giving the desired result so try this and if the div has some class specifier then do this
echo '<div class="whatever_it_is">' . $row['name'] . '</div'> ;
How does the keyword "use" work in PHP and can I import classes with it?
The issue is most likely you will need to use an auto loader that will take the name of the class (break by '\' in this case) and map it to a directory structure.
You can check out this article on the autoloading functionality of PHP. There are many implementations of this type of functionality in frameworks already.
I've actually implemented one before. Here's a link.
How to get first character of a string in SQL?
It is simple to achieve by the following
DECLARE @SomeString NVARCHAR(20) = 'This is some string'
DECLARE @Result NVARCHAR(20)
Either
SET @Result = SUBSTRING(@SomeString, 2, 3)
SELECT @Result
@Result = his
or
SET @Result = LEFT(@SomeString, 6)
SELECT @Result
@Result = This i
Call break in nested if statements
To make multiple checking statements more readable (and avoid nested ifs):
var tmp = 'Test[[email protected]]';
var posStartEmail = undefined;
var posEndEmail = undefined;
var email = undefined;
do {
if (tmp.toLowerCase().substring(0,4) !== 'test') { break; }
posStartEmail = tmp.toLowerCase().substring(4).indexOf('[');
posEndEmail = tmp.toLowerCase().substring(4).indexOf(']');
if (posStartEmail === -1 || posEndEmail === -1) { break; }
email = tmp.substring(posStartEmail+1+4,posEndEmail);
if (email.indexOf('@') === -1) { break; }
// all checks are done - do what you intend to do
alert ('All checks are ok')
break; // the most important break of them all
} while(true);
How to get PID by process name?
Since Python 3.5, subprocess.run() is recommended over subprocess.check_output():
>>> int(subprocess.run(["pidof", "-s", "your_process"], stdout=subprocess.PIPE).stdout)
Also, since Python 3.7, you can use the capture_output=true
parameter to capture stdout and stderr:
>>> int(subprocess.run(["pidof", "-s", "your process"], capture_output=True).stdout)
How to cast Object to its actual type?
If your MyFunction()
method is defined only in one class (and its descendants), try
void MyMethod(Object obj)
{
var o = obj as MyClass;
if (o != null)
o.MyFunction();
}
If you have a large number in unrelated classes defining the function you want to call, you should define an interface and make your classes define that interface:
interface IMyInterface
{
void MyFunction();
}
void MyMethod(Object obj)
{
var o = obj as IMyInterface;
if (o != null)
o.MyFunction();
}
Is there any kind of hash code function in JavaScript?
If you want a hashCode() function like Java's in JavaScript, that is yours:
String.prototype.hashCode = function(){
var hash = 0;
for (var i = 0; i < this.length; i++) {
var character = this.charCodeAt(i);
hash = ((hash<<5)-hash)+character;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
That is the way of implementation in Java (bitwise operator).
Please note that hashCode could be positive and negative, and that's normal, see HashCode giving negative values. So, you could consider to use Math.abs()
along with this function.
Boxplot in R showing the mean
I also think chart.Boxplot is the best option, it gives you the position of the mean but if you have a matrix with returns all you need is one line of code to get all the boxplots in one graph.
Here is a small ETF portfolio example.
library(zoo)
library(PerformanceAnalytics)
library(tseries)
library(xts)
VTI.prices = get.hist.quote(instrument = "VTI", start= "2007-03-01", end="2013-03-01",
quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
compression = "m", retclass = c("zoo"))
VEU.prices = get.hist.quote(instrument = "VEU", start= "2007-03-01", end="2013-03-01",
quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
compression = "m", retclass = c("zoo"))
VWO.prices = get.hist.quote(instrument = "VWO", start= "2007-03-01", end="2013-03-01",
quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
compression = "m", retclass = c("zoo"))
VNQ.prices = get.hist.quote(instrument = "VNQ", start= "2007-03-01", end="2013-03-01",
quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
compression = "m", retclass = c("zoo"))
TLT.prices = get.hist.quote(instrument = "TLT", start= "2007-03-01", end="2013-03-01",
quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
compression = "m", retclass = c("zoo"))
TIP.prices = get.hist.quote(instrument = "TIP", start= "2007-03-01", end="2013-03-01",
quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
compression = "m", retclass = c("zoo"))
index(VTI.prices) = as.yearmon(index(VTI.prices))
index(VEU.prices) = as.yearmon(index(VEU.prices))
index(VWO.prices) = as.yearmon(index(VWO.prices))
index(VNQ.prices) = as.yearmon(index(VNQ.prices))
index(TLT.prices) = as.yearmon(index(TLT.prices))
index(TIP.prices) = as.yearmon(index(TIP.prices))
Prices.z=merge(VTI.prices, VEU.prices, VWO.prices, VNQ.prices,
TLT.prices, TIP.prices)
colnames(Prices.z) = c("VTI", "VEU", "VWO" , "VNQ", "TLT", "TIP")
returnscc.z = diff(log(Prices.z))
start(returnscc.z)
end(returnscc.z)
colnames(returnscc.z)
head(returnscc.z)
Return Matrix
ret.mat = coredata(returnscc.z)
class(ret.mat)
colnames(ret.mat)
head(ret.mat)
Box Plot of Return Matrix
chart.Boxplot(returnscc.z, names=T, horizontal=TRUE, colorset="darkgreen", as.Tufte =F,
mean.symbol = 20, median.symbol="|", main="Return Distributions Comparison",
element.color = "darkgray", outlier.symbol = 20,
xlab="Continuously Compounded Returns", sort.ascending=F)
You can try changing the mean.symbol, and remove or change the median.symbol.
Hope it helped. :)
Accessing Session Using ASP.NET Web API
Why to avoid using Session in WebAPI?
Performance, performance, performance!
There's a very good, and often overlooked reason why you shouldn't be using Session in WebAPI at all.
The way ASP.NET works when Session is in use is to serialize all requests received from a single client. Now I'm not talking about object serialization - but running them in the order received and waiting for each to complete before running the next. This is to avoid nasty thread / race conditions if two requests each try to access Session simultaneously.
Access to ASP.NET session state
is exclusive per session, which means that if two different users make
concurrent requests, access to each separate session is granted
concurrently. However, if two concurrent requests are made for the
same session (by using the same SessionID value), the first request
gets exclusive access to the session information. The second request
executes only after the first request is finished. (The second session
can also get access if the exclusive lock on the information is freed
because the first request exceeds the lock time-out.) If the
EnableSessionState value in the @ Page directive is set to ReadOnly, a
request for the read-only session information does not result in an
exclusive lock on the session data. However, read-only requests for
session data might still have to wait for a lock set by a read-write
request for session data to clear.
So what does this mean for Web API? If you have an application running many AJAX requests then only ONE is going to be able to run at a time. If you have a slower request then it will block all others from that client until it is complete. In some applications this could lead to very noticeably sluggish performance.
So you should probably use an MVC controller if you absolutely need something from the users session and avoid the unncesessary performance penalty of enabling it for WebApi.
You can easily test this out for yourself by just putting Thread.Sleep(5000)
in a WebAPI method and enable Session. Run 5 requests to it and they will take a total of 25 seconds to complete. Without Session they'll take a total of just over 5 seconds.
(This same reasoning applies to SignalR).
Clang vs GCC - which produces faster binaries?
The only way to determine this is to try it. FWIW I have seen some really good improvements using Apple's LLVM gcc 4.2 compared to the regular gcc 4.2 (for x86-64 code with quite a lot of SSE), but YMMV for different code bases. Assuming you're working with x86/x86-64 and that you really do care about the last few percent then you ought to try Intel's ICC too, as this can often beat gcc - you can get a 30 day evaluation license from intel.com and try it.
When should we implement Serializable interface?
The answer to this question is, perhaps surprisingly, never, or more realistically, only when you are forced to for interoperability with legacy code. This is the recommendation in Effective Java, 3rd Edition by Joshua Bloch:
There is no reason to use Java serialization in any new system you write
Oracle's chief architect, Mark Reinhold, is on record as saying removing the current Java serialization mechanism is a long-term goal.
Why Java serialization is flawed
Java provides as part of the language a serialization scheme you can opt in to, by using the Serializable
interface. This scheme however has several intractable flaws and should be treated as a failed experiment by the Java language designers.
- It fundamentally pretends that one can talk about the serialized form of an object. But there are infinitely many serialization schemes, resulting in infinitely many serialized forms. By imposing one scheme, without any way of changing the scheme, applications can not use a scheme most appropriate for them.
- It is implemented as an additional means of constructing objects, which bypasses any precondition checks your constructors or factory methods perform. Unless tricky, error prone, and difficult to test extra deserialization code is written, your code probably has a gaping security weakness.
- Testing interoperability of different versions of the serialized form is very difficult.
- Handling of immutable objects is troublesome.
What to do instead
Instead, use a serialization scheme that you can explicitly control. Such as Protocol Buffers, JSON, XML, or your own custom scheme.
How to access a DOM element in React? What is the equilvalent of document.getElementById() in React
Disclaimer: While the top answer is probably a better solution, as a beginner it's a lot to take in when all you want is something very simple. This is intended as a more direct answer to your original question "How can I select certain elements in React"
I think the confusion in your question is because you have React components which you are being passed the id "Progress1", "Progress2" etc. I believe this is not setting the html attribute 'id', but the React component property. e.g.
class ProgressBar extends React.Component {
constructor(props) {
super(props)
this.state = {
id: this.props.id <--- ID set from <ProgressBar id="Progress1"/>
}
}
}
As mentioned in some of the answers above you absolutely can use document.querySelector
inside of your React app, but you have to be clear that it is selecting the html output of your components' render methods. So assuming your render output looks like this:
render () {
const id = this.state.id
return (<div id={"progress-bar-" + id}></div>)
}
Then you can elsewhere do a normal javascript querySelector call like this:
let element = document.querySelector('#progress-bar-Progress1')
How to convert char to int?
how about (for char c
)
int i = (int)(c - '0');
which does substraction of the char value?
Re the API question (comments), perhaps an extension method?
public static class CharExtensions {
public static int ParseInt32(this char value) {
int i = (int)(value - '0');
if (i < 0 || i > 9) throw new ArgumentOutOfRangeException("value");
return i;
}
}
then use int x = c.ParseInt32();
In CSS how do you change font size of h1 and h2
h1 {
font-weight: bold;
color: #fff;
font-size: 32px;
}
h2 {
font-weight: bold;
color: #fff;
font-size: 24px;
}
Note that after color you can use a word (e.g. white
), a hex code (e.g. #fff
) or RGB (e.g. rgb(255,255,255)
) or RGBA (e.g. rgba(255,255,255,0.3)
).
How to render a PDF file in Android
To add a little light to this, I would have to go with the pdf.js solution from Mozilla. Here is the link to an already well written implementation of this: https://bitbucket.org/butelo/pdfviewer/.
Here are the edits that I added in my Android Activity:
private String getInternalPDFURL(String interalPDFName){
return "file:///android_asset/pdfviewer/index.html?pdf=" + interalPDFName + ".pdf";
}
Here are the edits I made in pdffile.js
:
var url = '../' + getPDFURL();
function getPDFURL(){
var query = window.location.search.substring(1);
var vars = query.split("=");
var pdfPage = vars[1];
return pdfPage;
}
How do I read and parse an XML file in C#?
You could use a DataSet to read XML strings.
var xmlString = File.ReadAllText(FILE_PATH);
var stringReader = new StringReader(xmlString);
var dsSet = new DataSet();
dsSet.ReadXml(stringReader);
Posting this for the sake of information.
Returning http status code from Web Api controller
If you need to return an IHttpActionResult and want to return the error code plus a message, use:
return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NotModified, "Error message here"));
jQuery-- Populate select from json
I would do something like this:
$.each(temp,function(key, value)
{
$select.append('<option value=' + key + '>' + value + '</option>');
});
JSON structure would be appreciated. At first you can experiment with find('element')
- it depends on JSON.
MySQL 'Order By' - sorting alphanumeric correctly
I know this post is closed but I think my way could help some people. So there it is :
My dataset is very similar but is a bit more complex. It has numbers, alphanumeric data :
1
2
Chair
3
0
4
5
-
Table
10
13
19
Windows
99
102
Dog
I would like to have the '-' symbol at first, then the numbers, then the text.
So I go like this :
SELECT name, (name = '-') boolDash, (name = '0') boolZero, (name+0 > 0) boolNum
FROM table
ORDER BY boolDash DESC, boolZero DESC, boolNum DESC, (name+0), name
The result should be something :
-
0
1
2
3
4
5
10
13
99
102
Chair
Dog
Table
Windows
The whole idea is doing some simple check into the SELECT and sorting with the result.
How to change the default GCC compiler in Ubuntu?
I used just the lines below and it worked. I just wanted to compile VirtualBox
and VMWare WorkStation
using kernel 4.8.10
on Ubuntu 14.04
. Initially, most things were not working for example graphics and networking. I was lucky that VMWare workstation
requested for gcc 6.2.0
. I couldn't start my Genymotion Android emulators
because virtualbox was down. Will post results later if necessary.
VER=4.6 ; PRIO=60
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER
VER=6 ; PRIO=50
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER
VER=4.8 ; PRIO=40
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER
Copy all values from fields in one class to another through reflection
Without using BeanUtils or Apache Commons
public static <T1 extends Object, T2 extends Object> void copy(T1
origEntity, T2 destEntity) throws IllegalAccessException, NoSuchFieldException {
Field[] fields = origEntity.getClass().getDeclaredFields();
for (Field field : fields){
origFields.set(destEntity, field.get(origEntity));
}
}
importing pyspark in python shell
export PYSPARK_PYTHON=/home/user/anaconda3/bin/python
export PYSPARK_DRIVER_PYTHON=jupyter
export PYSPARK_DRIVER_PYTHON_OPTS='notebook'
This is what I did for using my Anaconda distribution with Spark.
This is Spark version independent.
You can change the first line to your users' python bin.
Also, as of Spark 2.2.0 PySpark is available as a Stand-alone package on PyPi
but I am yet to test it out.
What is the minimum length of a valid international phone number?
As per different sources, I think the minimum length in E-164 format depends on country to country. For eg:
... and so on.
So including country code, the minimum length is 9 digits for Sweden and 11 for Israel and 8 for Solomon Islands.
Edit (Clean Solution): Actually, Instead of validating an international phone number by having different checks like length etc, you can use the Google's libphonenumber library. It can validate a phone number in E164 format directly. It will take into account everything and you don't even need to give the country if the number is in valid E164 format. Its pretty good!
Taking an example:
String phoneNumberE164Format = "+14167129018"
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
PhoneNumber phoneNumberProto = phoneUtil.parse(phoneNumberE164Format, null);
boolean isValid = phoneUtil.isValidNumber(phoneNumberProto); // returns true if valid
if (isValid) {
// Actions to perform if the number is valid
} else {
// Do necessary actions if its not valid
}
} catch (NumberParseException e) {
System.err.println("NumberParseException was thrown: " + e.toString());
}
If you know the country for which you are validating the numbers, you don;t even need the E164 format and can specify the country in .parse
function instead of passing null
.
form action with javascript
A form action set to a JavaScript function is not widely supported, I'm surprised it works in FireFox.
The best is to just set form action
to your PHP script; if you need to do anything before submission you can just add to onsubmit
Edit turned out you didn't need any extra function, just a small change here:
function validateFormOnSubmit(theForm) {
var reason = "";
reason += validateName(theForm.name);
reason += validatePhone(theForm.phone);
reason += validateEmail(theForm.emaile);
if (reason != "") {
alert("Some fields need correction:\n" + reason);
} else {
simpleCart.checkout();
}
return false;
}
Then in your form:
<form action="#" onsubmit="return validateFormOnSubmit(this);">
How to initialize private static members in C++?
For a variable:
foo.h:
class foo
{
private:
static int i;
};
foo.cpp:
int foo::i = 0;
This is because there can only be one instance of foo::i
in your program. It's sort of the equivalent of extern int i
in a header file and int i
in a source file.
For a constant you can put the value straight in the class declaration:
class foo
{
private:
static int i;
const static int a = 42;
};
How to read data of an Excel file using C#?
Here's a 2020 answer - if you don't need to support the older .xls format (so pre 2003) you could use either:
or
Pros :
Cons:
- Neither LightweightExcelReader nor ExcelToEnumerable support .xls files.
Disclaimer: I am the author of LightweightExcelReader and ExcelToEnumerable
Creating a Plot Window of a Particular Size
As the accepted solution of @Shane is not supported in RStudio (see here) as of now (Sep 2015), I would like to add an advice to @James Thompson answer regarding workflow:
If you use SumatraPDF as viewer you do not need to close the PDF file before making changes to it. Sumatra does not put a opened file in read-only and thus does not prevent it from being overwritten. Therefore, once you opened your PDF file with Sumatra, changes out of RStudio (or any other R IDE) are immediately displayed in Sumatra.
how to re-format datetime string in php?
try this
$datetime = "20130409163705";
print_r(date_parse_from_format("Y-m-d H-i-s", $datetime));
the output:
[year] => 2013
[month] => 4
[day] => 9
[hour] => 16
[minute] => 37
[second] => 5
DateTime and CultureInfo
You may try the following:
System.Globalization.CultureInfo cultureinfo =
new System.Globalization.CultureInfo("nl-NL");
DateTime dt = DateTime.Parse(date, cultureinfo);
Waiting until the task finishes
Swift 5 version of the solution
func myCriticalFunction() {
var value1: String?
var value2: String?
let group = DispatchGroup()
group.enter()
//async operation 1
DispatchQueue.global(qos: .default).async {
// Network calls or some other async task
value1 = //out of async task
group.leave()
}
group.enter()
//async operation 2
DispatchQueue.global(qos: .default).async {
// Network calls or some other async task
value2 = //out of async task
group.leave()
}
group.wait()
print("Value1 \(value1) , Value2 \(value2)")
}
How to stop an animation (cancel() does not work)
Use the method setAnimation(null) to stop an animation, it exposed as public method in
View.java, it is the base class for all widgets, which are used to create interactive UI components (buttons, text fields, etc.).
/**
* Sets the next animation to play for this view.
* If you want the animation to play immediately, use
* {@link #startAnimation(android.view.animation.Animation)} instead.
* This method provides allows fine-grained
* control over the start time and invalidation, but you
* must make sure that 1) the animation has a start time set, and
* 2) the view's parent (which controls animations on its children)
* will be invalidated when the animation is supposed to
* start.
*
* @param animation The next animation, or null.
*/
public void setAnimation(Animation animation)
Django Template Variables and Javascript
A solution that worked for me is using the hidden input field in the template
<input type="hidden" id="myVar" name="variable" value="{{ variable }}">
Then getting the value in javascript this way,
var myVar = document.getElementById("myVar").value;
Creating a SOAP call using PHP with an XML body
First off, you have to specify you wish to use Document Literal style:
$client = new SoapClient(NULL, array(
'location' => 'https://example.com/path/to/service',
'uri' => 'http://example.com/wsdl',
'trace' => 1,
'use' => SOAP_LITERAL)
);
Then, you need to transform your data into a SoapVar; I've written a simple transform function:
function soapify(array $data)
{
foreach ($data as &$value) {
if (is_array($value)) {
$value = soapify($value);
}
}
return new SoapVar($data, SOAP_ENC_OBJECT);
}
Then, you apply this transform function onto your data:
$data = soapify(array(
'Acquirer' => array(
'Id' => 'MyId',
'UserId' => 'MyUserId',
'Password' => 'MyPassword',
),
));
Finally, you call the service passing the Data parameter:
$method = 'Echo';
$result = $client->$method(new SoapParam($data, 'Data'));
Encode a FileStream to base64 with c#
When dealing with large streams, like a file sized over 4GB - you don't want to load the file into memory (as a Byte[]
) because not only is it very slow, but also may cause a crash as even in 64-bit processes a Byte[]
cannot exceed 2GB (or 4GB with gcAllowVeryLargeObjects
).
Fortunately there's a neat helper in .NET called ToBase64Transform
which processes a stream in chunks. For some reason Microsoft put it in System.Security.Cryptography
and it implements ICryptoTransform
(for use with CryptoStream
), but disregard that ("a rose by any other name...") just because you aren't performing any cryprographic tasks.
You use it with CryptoStream
like so:
using System.Security.Cryptography;
using System.IO;
//
using( FileStream inputFile = new FileStream( @"C:\VeryLargeFile.bin", FileMode.Open, FileAccess.Read, FileShare.None, bufferSize: 1024 * 1024, useAsync: true ) ) // When using `useAsync: true` you get better performance with buffers much larger than the default 4096 bytes.
using( CryptoStream base64Stream = new CryptoStream( inputFile, new ToBase64Transform(), CryptoStreamMode.Read ) )
using( FileStream outputFile = new FileStream( @"C:\VeryLargeBase64File.txt", FileMode.CreateNew, FileAccess.Write, FileShare.None, bufferSize: 1024 * 1024, useAsync: true ) )
{
await base64Stream.CopyToAsync( outputFile ).ConfigureAwait(false);
}
How to sum all values in a column in Jaspersoft iReport Designer?
It is quite easy to solve your task. You should create and use a new variable for summing values of the "Doctor Payment" column.
In your case the variable can be declared like this:
<variable name="total" class="java.lang.Integer" calculation="Sum">
<variableExpression><![CDATA[$F{payment}]]></variableExpression>
</variable>
- the Calculation type is Sum;
- the Reset type is Report;
- the Variable expression is $F{payment}, where $F{payment} is the name of a field contains sum (Doctor Payment).
The working example.
CSV datasource:
doctor_id,payment
A1,123
B1,223
C2,234
D3,678
D1,343
The template:
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport ...>
<queryString>
<![CDATA[]]>
</queryString>
<field name="doctor_id" class="java.lang.String"/>
<field name="payment" class="java.lang.Integer"/>
<variable name="total" class="java.lang.Integer" calculation="Sum">
<variableExpression><![CDATA[$F{payment}]]></variableExpression>
</variable>
<columnHeader>
<band height="20" splitType="Stretch">
<staticText>
<reportElement x="0" y="0" width="100" height="20"/>
<box leftPadding="10"/>
<textElement textAlignment="Center" verticalAlignment="Middle">
<font size="10" isBold="true" isItalic="true"/>
</textElement>
<text><![CDATA[Doctor ID]]></text>
</staticText>
<staticText>
<reportElement x="100" y="0" width="100" height="20"/>
<box leftPadding="10"/>
<textElement textAlignment="Center" verticalAlignment="Middle">
<font size="10" isBold="true" isItalic="true"/>
</textElement>
<text><![CDATA[Doctor Payment]]></text>
</staticText>
</band>
</columnHeader>
<detail>
<band height="20" splitType="Stretch">
<textField>
<reportElement x="0" y="0" width="100" height="20"/>
<box leftPadding="10"/>
<textElement/>
<textFieldExpression><![CDATA[$F{doctor_id}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="100" y="0" width="100" height="20"/>
<box leftPadding="10"/>
<textElement/>
<textFieldExpression><![CDATA[$F{payment}]]></textFieldExpression>
</textField>
</band>
</detail>
<summary>
<band height="20">
<staticText>
<reportElement x="0" y="0" width="100" height="20"/>
<box leftPadding="10"/>
<textElement>
<font isBold="true"/>
</textElement>
<text><![CDATA[Total]]></text>
</staticText>
<textField>
<reportElement x="100" y="0" width="100" height="20"/>
<box leftPadding="10"/>
<textElement>
<font isBold="true" isItalic="true"/>
</textElement>
<textFieldExpression><![CDATA[$V{total}]]></textFieldExpression>
</textField>
</band>
</summary>
</jasperReport>
The result will be:
You can find a lot of info in the JasperReports Ultimate Guide.
Insert an item into sorted list in Python
# function to insert a number in an sorted list
def pstatement(value_returned):
return print('new sorted list =', value_returned)
def insert(input, n):
print('input list = ', input)
print('number to insert = ', n)
print('range to iterate is =', len(input))
first = input[0]
print('first element =', first)
last = input[-1]
print('last element =', last)
if first > n:
list = [n] + input[:]
return pstatement(list)
elif last < n:
list = input[:] + [n]
return pstatement(list)
else:
for i in range(len(input)):
if input[i] > n:
break
list = input[:i] + [n] + input[i:]
return pstatement(list)
# Input values
listq = [2, 4, 5]
n = 1
insert(listq, n)
How to format dateTime in django template?
I suspect wpis.entry.lastChangeDate
has been somehow transformed into a string in the view, before arriving to the template.
In order to verify this hypothesis, you may just check in the view if it has some property/method that only strings have - like for instance wpis.entry.lastChangeDate.upper
, and then see if the template crashes.
You could also create your own custom filter, and use it for debugging purposes, letting it inspect the object, and writing the results of the inspection on the page, or simply on the console. It would be able to inspect the object, and check if it is really a DateTimeField.
On an unrelated notice, why don't you use models.DateTimeField(
auto_now_add
=True)
to set the datetime on creation?
Bootstrap 3 Navbar with Logo
Another approach is to implement Bootstrap's built-in .text-hide
class alongside of .navbar-brand
to replace the brand text/content with a background image.
CSS:
.navbar-brand{
background: url(http://example.com/your-logo-here.png) center / contain no-repeat;
width: 200px;
}
HTML:
<a class="navbar-brand text-hide" href="#">Navbar Brand</a>
This is a very consistent method and keeps your image centered. To adjust the size of the image all you need to do is adjust .navbar-brand
width since the height is already set.
Here's a live demo
How to set up Android emulator proxy settings
In case if you are under proxy environment and internet is not running in your emulator, then please don't change any setting in emulator. Go to your eclipse project, right click , click on "Run as" then click on "Run Configuration".
In pop up window choose "Target" and scroll down a little,
you will find "Additional Emulator Command Line Options"
Enter your proxy setting here in "Additional Emulator Command Line Options" as i entered
-http-proxy http://ee11s040:[email protected]:3128
Then start a new Emulator.
Python: how to print range a-z?
myList = [chr(chNum) for chNum in list(range(ord('a'),ord('z')+1))]
print(myList)
Output
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
How to implement private method in ES6 class with Traceur
I hope this can be helpful. :)
I. Declaring vars, functions inside IIFE(Immediately-invoked function expression), those can be used only in the anonymous function. (It can be good to use "let, const" keywords without using 'var' when you need to change code for ES6.)
let Name = (function() {
const _privateHello = function() {
}
class Name {
constructor() {
}
publicMethod() {
_privateHello()
}
}
return Name;
})();
II. WeakMap object can be good for memoryleak trouble.
Stored variables in the WeakMap will be removed when the instance will be removed. Check this article. (Managing the private data of ES6 classes)
let Name = (function() {
const _privateName = new WeakMap();
})();
III. Let's put all together.
let Name = (function() {
const _privateName = new WeakMap();
const _privateHello = function(fullName) {
console.log("Hello, " + fullName);
}
class Name {
constructor(firstName, lastName) {
_privateName.set(this, {firstName: firstName, lastName: lastName});
}
static printName(name) {
let privateName = _privateName.get(name);
let _fullname = privateName.firstName + " " + privateName.lastName;
_privateHello(_fullname);
}
printName() {
let privateName = _privateName.get(this);
let _fullname = privateName.firstName + " " + privateName.lastName;
_privateHello(_fullname);
}
}
return Name;
})();
var aMan = new Name("JH", "Son");
aMan.printName(); // "Hello, JH Son"
Name.printName(aMan); // "Hello, JH Son"
TOMCAT - HTTP Status 404
You don't have to use Tomcat installation as a server location. It is much easier just to copy the files in the ROOT folder.
Eclipse forgets to copy the default apps (ROOT, examples, etc.) when
it creates a Tomcat folder inside the Eclipse workspace. Go to
C:\apache-tomcat-7.0.8\webapps
, R-click on the ROOT folder and copy
it. Then go to your Eclipse workspace, go to the .metadata
folder, and
search for "wtpwebapps". You should find something like
your-eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
(or ../tmp1/wtpwebapps
if you already had another server registered
in Eclipse). Go to the wtpwebapps
folder, R-click, and paste ROOT (say
"yes" if asked if you want to merge/replace folders/files). Then
reload http://localhost/
to see the Tomcat welcome page.
Source: HTTP Status 404 error in tomcat
Find and extract a number from a string
An interesting approach is provided here by Ahmad Mageed, uses Regex and StringBuilder
to extract the integers in the order in which they appear in the string.
An example using Regex.Split
based on the post by Ahmad Mageed is as follows:
var dateText = "MARCH-14-Tue";
string splitPattern = @"[^\d]";
string[] result = Regex.Split(dateText, splitPattern);
var finalresult = string.Join("", result.Where(e => !String.IsNullOrEmpty(e)));
int DayDateInt = 0;
int.TryParse(finalresult, out DayDateInt);
How to maintain state after a page refresh in React.js?
We have an application that allows the user to set "parameters" in the page. What we do is set those params on the URL, using React Router (in conjunction with History) and a library that URI-encodes JavaScript objects into a format that can be used as your query string.
When the user selects an option, we can push the value of that onto the current route with:
history.push({pathname: 'path/', search: '?' + Qs.stringify(params)});
pathname
can be the current path. In your case params
would look something like:
{
selectedOption: 5
}
Then at the top level of the React tree, React Router will update the props
of that component with a prop of location.search
which is the encoded value we set earlier, so there will be something in componentWillReceiveProps
like:
params = Qs.parse(nextProps.location.search.substring(1));
this.setState({selectedOption: params.selectedOption});
Then that component and its children will re-render with the updated setting. As the information is on the URL it can be bookmarked (or emailed around - this was our use case) and a refresh will leave the app in the same state.
This has been working really well for our application.
React Router: https://github.com/reactjs/react-router
History: https://github.com/ReactTraining/history
The query string library: https://github.com/ljharb/qs
Python data structure sort list alphabetically
[]
denotes a list, ()
denotes a tuple and {}
denotes a dictionary. You should take a look at the official Python tutorial as these are the very basics of programming in Python.
What you have is a list of strings. You can sort it like this:
In [1]: lst = ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']
In [2]: sorted(lst)
Out[2]: ['Eflux', 'Intrigue', 'Sedge', 'Stem', 'Whim', 'constitute']
As you can see, words that start with an uppercase letter get preference over those starting with a lowercase letter. If you want to sort them independently, do this:
In [4]: sorted(lst, key=str.lower)
Out[4]: ['constitute', 'Eflux', 'Intrigue', 'Sedge', 'Stem', 'Whim']
You can also sort the list in reverse order by doing this:
In [12]: sorted(lst, reverse=True)
Out[12]: ['constitute', 'Whim', 'Stem', 'Sedge', 'Intrigue', 'Eflux']
In [13]: sorted(lst, key=str.lower, reverse=True)
Out[13]: ['Whim', 'Stem', 'Sedge', 'Intrigue', 'Eflux', 'constitute']
Please note: If you work with Python 3, then str
is the correct data type for every string that contains human-readable text. However, if you still need to work with Python 2, then you might deal with unicode strings which have the data type unicode
in Python 2, and not str
. In such a case, if you have a list of unicode strings, you must write key=unicode.lower
instead of key=str.lower
.
Working with INTERVAL and CURDATE in MySQL
As suggested by A Star, I always use something along the lines of:
DATE(NOW()) - INTERVAL 1 MONTH
Similarly you can do:
NOW() + INTERVAL 5 MINUTE
"2013-01-01 00:00:00" + INTERVAL 10 DAY
and so on. Much easier than typing DATE_ADD
or DATE_SUB
all the time :)!
How to split a list by comma not space
Using a subshell substitution to parse the words undoes all the work you are doing to put spaces together.
Try instead:
cat CSV_file | sed -n 1'p' | tr ',' '\n' | while read word; do
echo $word
done
That also increases parallelism. Using a subshell as in your question forces the entire subshell process to finish before you can start iterating over the answers. Piping to a subshell (as in my answer) lets them work in parallel. This matters only if you have many lines in the file, of course.
Eclipse DDMS error "Can't bind to local 8600 for debugger"
Based on an Aptana Studio support response, it was confirmed that the Aptana plugin and Android Development Tools collide on this port (i.e. Aptana's Comet server overlapped on this port). Aptana opened a ticket back in 2010.
Unfortunately, it does not appear that Aptana has fixed it yet or made their Comet server port configurable. Changing the port number in eclipse and restarting adb did NOT fix it for me. I finally was forced to uninstall the Aptana plugin.
how to call a variable in code behind to aspx page
First you have to make sure the access level of the variable is protected or public. If the variable or property is private the page won't have access to it.
Code Behind
protected String Clients { get; set; }
Aspx
<span><%=Clients %> </span>
Adding a HTTP header to the Angular HttpClient doesn't send the header, why?
To add multiples params or headers you can do the following:
constructor(private _http: HttpClient) {}
//....
const url = `${environment.APP_API}/api/request`;
let headers = new HttpHeaders().set('header1', hvalue1); // create header object
headers = headers.append('header2', hvalue2); // add a new header, creating a new object
headers = headers.append('header3', hvalue3); // add another header
let params = new HttpParams().set('param1', value1); // create params object
params = params.append('param2', value2); // add a new param, creating a new object
params = params.append('param3', value3); // add another param
return this._http.get<any[]>(url, { headers: headers, params: params })
Set colspan dynamically with jquery
How about
$([your selector]).attr('colspan',3);
I would imagine that to work but have no way to test at the moment. Using .attr()
would be the usual jQuery way of setting attributes of elements in the wrapped set.
As has been mentioned in another answer, in order to get this to work would require removing the td elements that have no text in them from the DOM. It may be easier to do this all server side
EDIT:
As was mentioned in the comments, there is a bug in attempting to set colspan using attr() in IE, but the following works in IE6 and FireFox 3.0.13.
Working Demo
notice the use of the attribute colSpan
and not colspan
- the former works in both IE and Firefox, but the latter does not work in IE. Looking at jQuery 1.3.2 source, it would appear that attr()
attempts to set the attribute as a property of the element if
- it exists as a property on the element (
colSpan
exists as a property and defaults to 1 on <td>
HTMLElements in IE and FireFox)
- the document is not xml and
- the attribute is none of href, src or style
using colSpan
as opposed to colspan
works with attr()
because the former is a property defined on the element whereas the latter is not.
the fall-through for attr()
is to attempt to use setAttribute()
on the element in question, setting the value to a string, but this causes problems in IE (bug #1070 in jQuery)
// convert the value to a string (all browsers do this but IE) see #1070
elem.setAttribute( name, "" + value );
In the demo, for each row, the text in each cell is evaluated. If the text is a blank string, then the cell is removed and a counter incremented. The first cell in the row that does not have class="colTime"
has a colspan attribute set to the value of the counter + 1 (for the span it occupies itself).
After this, for each row, the text in the cell with class="colspans"
is set to the colspan attribute values of each cell in the row from left to right.
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Sandbox</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body { background-color: #000; font: 16px Helvetica, Arial; color: #fff; }
td { text-align: center; }
</style>
</head>
<body>
<table class="tblSimpleAgenda" cellpadding="5" cellspacing="0">
<tbody>
<tr>
<th align="left">Time</th>
<th align="left">Room 1</th>
<th align="left">Room 2</th>
<th align="left">Room 3</th>
<th align="left">Colspans (L -> R)</th>
</tr>
<tr valign="top">
<td class="colTime">09:00 – 10:00</td>
<td class="col1"></td>
<td class="col2">Meeting 2</td>
<td class="col3"></td>
<td class="colspans">holder</td>
</tr>
<tr valign="top">
<td class="colTime">10:00 – 10:45</td>
<td class="col1">Meeting 1</td>
<td class="col2">Meeting 2</td>
<td class="col3">Meeting 3</td>
<td class="colspans">holder</td>
</tr>
<tr valign="top">
<td class="colTime">11:00 – 11:45</td>
<td class="col1">Meeting 1</td>
<td class="col2">Meeting 2</td>
<td class="col3">Meeting 3</td>
<td class="colspans">holder</td>
</tr>
<tr valign="top">
<td class="colTime">11:00 – 11:45</td>
<td class="col1">Meeting 1</td>
<td class="col2">Meeting 2</td>
<td class="col3"></td>
<td class="colspans">holder</td>
</tr>
</tbody>
</table>
</body>
</html>
jQuery code
$(function() {
$('table.tblSimpleAgenda tr').each(function() {
var tr = this;
var counter = 0;
$('td', tr).each(function(index, value) {
var td = $(this);
if (td.text() == "") {
counter++;
td.remove();
}
});
if (counter !== 0) {
$('td:not(.colTime):first', tr)
.attr('colSpan', '' + parseInt(counter + 1,10) + '');
}
});
$('td.colspans').each(function(){
var td = $(this);
var colspans = [];
td.siblings().each(function() {
colspans.push(($(this).attr('colSpan')) == null ? 1 : $(this).attr('colSpan'));
});
td.text(colspans.join(','));
});
});
This is just a demonstration to show that attr()
can be used, but to be aware of it's implementation and the cross-browser quirks that come with it. I've also made some assumptions about your table layout in the demo (i.e. apply the colspan to the first "non-Time" cell in each row), but hopefully you get the idea.
Exploring Docker container's file system
Before Container Creation :
If you to explore the structure of the image that is mounted inside the container you can do
sudo docker image save image_name > image.tar
tar -xvf image.tar
This would give you the visibility of all the layers of an image and its configuration which is present in json files.
After container creation :
For this there are already lot of answers above. my preferred way to do
this would be -
docker exec -t -i container /bin/bash
Declare a variable in DB2 SQL
I imagine this forum posting, which I quote fully below, should answer the question.
Inside a procedure, function, or trigger definition, or in a dynamic SQL statement (embedded in a host program):
BEGIN ATOMIC
DECLARE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM tablename
WHERE column1 = example ;
END
or (in any environment):
WITH t(example) AS (VALUES('welcome'))
SELECT *
FROM tablename, t
WHERE column1 = example
or (although this is probably not what you want, since the variable needs to be created just once, but can be used thereafter by everybody although its content will be private on a per-user basis):
CREATE VARIABLE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM tablename
WHERE column1 = example ;
How to send characters in PuTTY serial communication only when pressing enter?
The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.
To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".
To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".
Explanation:
From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):
4.3.8 ‘Local echo’
With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)
Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.
4.3.9 ‘Local line editing’
Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.
If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.
Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)
Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.
Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.
Sum across multiple columns with dplyr
If you want to sum certain columns only, I'd use something like this:
library(dplyr)
df=data.frame(
x1=c(1,0,0,NA,0,1,1,NA,0,1),
x2=c(1,1,NA,1,1,0,NA,NA,0,1),
x3=c(0,1,0,1,1,0,NA,NA,0,1),
x4=c(1,0,NA,1,0,0,NA,0,0,1),
x5=c(1,1,NA,1,1,1,NA,1,0,1))
df %>% select(x3:x5) %>% rowSums(na.rm=TRUE) -> df$x3x5.total
head(df)
This way you can use dplyr::select
's syntax.
Abstract methods in Java
If you use the java keyword abstract
you cannot provide an implementation.
Sometimes this idea comes from having a background in C++ and mistaking the virtual
keyword in C++ as being "almost the same" as the abstract
keyword in Java.
In C++ virtual
indicates that a method can be overridden and polymorphism will follow, but abstract
in Java is not the same thing. In Java abstract
is more like a pure virtual
method, or one where the implementation must be provided by a subclass. Since Java supports polymorphism without the need to declare it, all methods are virtual
from a C++ point of view. So if you want to provide a method that might be overridden, just write it as a "normal" method.
Now to protect a method from being overridden, Java uses the keyword final
in coordination with the method declaration to indicate that subclasses cannot override the method.
how to get current datetime in SQL?
GETDATE()
or GETUTCDATE()
are now superseded by the richer SYSDATETIME
, SYSUTCDATETIME
, and SYSDATETIMEOFFSET
(in SQL 2008)
- Yes, I don't think
ANSI
has ever declared anything, and so each manufacturer has their own.
- That would be
NOW()
Hope this helps...
Rob
Combine two or more columns in a dataframe into a new column with a new name
Some examples with NAs and their removal using apply
n = c(2, NA, NA)
s = c("aa", "bb", NA)
b = c(TRUE, FALSE, NA)
c = c(2, 3, 5)
d = c("aa", NA, "cc")
e = c(TRUE, NA, TRUE)
df = data.frame(n, s, b, c, d, e)
paste_noNA <- function(x,sep=", ") {
gsub(", " ,sep, toString(x[!is.na(x) & x!="" & x!="NA"] ) ) }
sep=" "
df$x <- apply( df[ , c(1:6) ] , 1 , paste_noNA , sep=sep)
df
Making TextView scrollable on Android
Use it like this
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:maxLines = "AN_INTEGER"
android:scrollbars = "vertical"
/>
USB Debugging option greyed out
I had an LG Android phone, and could not get USB to work with Windows, even after trying the following:
- Settings > About phone > Software info
- Tap 'Build number' 7x, and Activate Developer mode
- Settings > Developer options > USB debugging [ON]
- Settings > Developer options > Select USB Configuration > MTP
- Plug into Windows PC with USB cable.
It DOES show the phone as charging via USB (so the plug must be OK), but it does not show up under 'This PC' in Windows File Explorer as a Device/Drive.. grrr.
Turns out that not all USB cables are the same — some USB cable manufacturers only make their cable with 2wires instead of 4wires, so that they will charge, but not pass data through the cable — so if software solutions do not appear to be working, try changing the USB cable (!).
im writing this here so that maybe someone else doesnt have to waste half an hour figuring out that some USB cable manufacturer doesnt include all 4 wires in their USB cables... grrr.
jQuery: get parent tr for selected radio button
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.
What does the "undefined reference to varName" in C mean?
An initial reaction to this would be to ask and ensure that the two object files are being linked together. This is done at the compile stage by compiling both files at the same time:
gcc -o programName a.c b.c
Or if you want to compile separately, it would be:
gcc -c a.c
gcc -c b.c
gcc -o programName a.o b.o
Clicking at coordinates without identifying element
In Selenium Java, you can try it using Javascript:
_x000D_
_x000D_
WebDriver driver = new ChromeDriver();_x000D_
_x000D_
if (driver instanceof JavascriptExecutor) {_x000D_
((JavascriptExecutor) driver).executeScript("el = document.elementFromPoint(x-cordinate, y-cordinate); el.click();");_x000D_
}
_x000D_
_x000D_
_x000D_
Read file from resources folder in Spring Boot
i think the problem lies within the space in the folder-name where your project is placed.
/home/user/Dev/Java/Java%20Programs/SystemRoutines/target/classes/jsonschema.json
there is space between Java Programs.Renaming the folder name should make it work
What should a JSON service return on failure / error
Yes, you should use HTTP status codes. And also preferably return error descriptions in a somewhat standardized JSON format, like Nottingham’s proposal, see apigility Error Reporting:
The payload of an API Problem has the following structure:
-
type: a URL to a document describing the error condition (optional, and "about:blank" is
assumed if none is provided; should resolve to a human-readable document; Apigility always
provides this).
-
title: a brief title for the error condition (required; and should be the same for every
problem of the same type; Apigility always provides this).
-
status: the HTTP status code for the current request (optional; Apigility always provides this).
-
detail: error details specific to this request (optional; Apigility requires it for each
problem).
-
instance: URI identifying the specific instance of this problem (optional; Apigility currently
does not provide this).
List comprehension vs map
Here is one possible case:
map(lambda op1,op2: op1*op2, list1, list2)
versus:
[op1*op2 for op1,op2 in zip(list1,list2)]
I am guessing the zip() is an unfortunate and unnecessary overhead you need to indulge in if you insist on using list comprehensions instead of the map. Would be great if someone clarifies this whether affirmatively or negatively.
MySQL ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)
I had the same problem, but in my case the solution was solved by the comment by eggyal. I had an anonymous user as well, but removing it didn't solve the problem. The 'FLUSH PRIVILEGES' command worked though.
The surprising thing to me about this was that I created the user with MySQL Workbench and I would have expected that to perform all of the necessary functions to complete the task.
pip install from git repo branch
You used the egg files install procedure.
This procedure supports installing over git
, git+http
, git+https
, git+ssh
, git+git
and git+file
. Some of these are mentioned.
It's good you can use branches, tags, or hashes to install.
@Steve_K noted it can be slow to install with "git+" and proposed installing via zip file:
pip install https://github.com/user/repository/archive/branch.zip
Alternatively, I suggest you may install using the .whl
file if this exists.
pip install https://github.com/user/repository/archive/branch.whl
It's pretty new format, newer than egg files. It requires wheel and setuptools>=0.8 packages. You can find more in here.
What is the difference between git clone and checkout?
One thing to notice is the lack of any "Copyout" within git. That's because you already have a full copy in your local repo - your local repo being a clone
of your chosen upstream repo. So you have effectively a personal checkout
of everything, without putting some 'lock' on those files in the reference repo.
Git provides the SHA1 hash values as the mechanism for verifying that the copy you have of a file / directory tree / commit / repo is exactly the same as that used by whoever is able to declare things as "Master" within the hierarchy of trust. This avoids all those 'locks' that cause most SCM systems to choke (with the usual problems of private copies, big merges, and no real control or management of source code ;-) !
How to save SELECT sql query results in an array in C# Asp.net
Normally i use a class for this:
public class ClassName
{
public string Col1 { get; set; }
public int Col2 { get; set; }
}
Now you can use a loop to fill a list and ToArray
if you really need an array:
ClassName[] allRecords = null;
string sql = @"SELECT col1,col2
FROM some table";
using (var command = new SqlCommand(sql, con))
{
con.Open();
using (var reader = command.ExecuteReader())
{
var list = new List<ClassName>();
while (reader.Read())
list.Add(new ClassName { Col1 = reader.GetString(0), Col2 = reader.GetInt32(1) });
allRecords = list.ToArray();
}
}
Note that i've presumed that the first column is a string
and the second an integer
. Just to demonstrate that C# is typesafe and how you use the DataReader.GetXY
methods.
Regular expression replace in C#
Try this::
sb_trim = Regex.Replace(stw, @"(\D+)\s+\$([\d,]+)\.\d+\s+(.)",
m => string.Format(
"{0},{1},{2}",
m.Groups[1].Value,
m.Groups[2].Value.Replace(",", string.Empty),
m.Groups[3].Value));
This is about as clean an answer as you'll get, at least with regexes.
(\D+)
: First capture group. One or more non-digit characters.
\s+\$
: One or more spacing characters, then a literal dollar sign ($).
([\d,]+)
: Second capture group. One or more digits and/or commas.
\.\d+
: Decimal point, then at least one digit.
\s+
: One or more spacing characters.
(.)
: Third capture group. Any non-line-breaking character.
The second capture group additionally needs to have its commas stripped. You could do this with another regex, but it's really unnecessary and bad for performance. This is why we need to use a lambda expression and string format to piece together the replacement. If it weren't for that, we could just use this as the replacement, in place of the lambda expression:
"$1,$2,$3"
How to do something before on submit?
make sure the submit button is not of type "submit", make it a button. Then use the onclick event to trigger some javascript. There you can do whatever you want before you actually post your data.
How do we count rows using older versions of Hibernate (~2009)?
This works in Hibernate 4(Tested).
String hql="select count(*) from Book";
Query query= getCurrentSession().createQuery(hql);
Long count=(Long) query.uniqueResult();
return count;
Where getCurrentSession() is:
@Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}
How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?
The linked list holds operations on the shared data structure.
For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).
In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.
In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.
How to prevent page from reloading after form submit - JQuery
The <button>
element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:
- Use
<button type="button">
to override default submission behavior
- Use
event.preventDefault()
in the onSubmit event to prevent form submission
Solution 1:
- Advantage: simple change to markup
- Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?
Insert extra type
attribute to your button markup:
<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>
Solution 2:
- Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission
Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:
$(document).ready(function () {
// Listen to click event on the submit button
$('#button').click(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
Better variant:
In this improvement, we listen to the submit event emitted from the <form>
element:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
Even better variant: use .serialize()
to serialize your form, but remember to add name
attributes to your input:
The name
attribute is required for .serialize()
to work, as per jQuery's documentation:
For a form element's value to be included in the serialized string, the element must have a name attribute.
<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">
And then in your JS:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
// Prevent form submission which refreshes page
e.preventDefault();
// Serialize data
var formData = $(this).serialize();
// Make AJAX request
$.post("process.php", formData).complete(function() {
console.log("Success");
});
});
});
What is the difference between document.location.href and document.location?
document.location
is an object, while document.location.href
is a string. But the former has a toString
method, so you can read from it as if it was a string and get the same value as document.location.href
.
In some browsers - most modern ones, I think - you can also assign to document.location
as if it were a string. According to the Mozilla documentation however, it is better to use window.location
for this purpose as document.location
was originally read-only and so may not be as widely supported.
SpringMVC RequestMapping for GET parameters
This works in my case:
@RequestMapping(value = "/savedata",
params = {"textArea", "localKey", "localFile"})
@ResponseBody
public void saveData(@RequestParam(value = "textArea") String textArea,
@RequestParam(value = "localKey") String localKey,
@RequestParam(value = "localFile") String localFile) {
}
Python: subplot within a loop: first panel appears in wrong position
Using your code with some random data, this would work:
fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)
axs = axs.ravel()
for i in range(10):
axs[i].contourf(np.random.rand(10,10),5,cmap=plt.cm.Oranges)
axs[i].set_title(str(250+i))
The layout is off course a bit messy, but that's because of your current settings (the figsize, wspace etc).
Matching a space in regex
It seems to me like using a REGEX in this case would just be overkill. Why not just just strpos to find the space character. Also, there's nothing special about the space character in regular expressions, you should be able to search for it the same as you would search for any other character. That is, unless you disabled pattern whitespace, which would hardly be necessary in this case.
How do I get the picture size with PIL?
Note that PIL will not apply the EXIF rotation information (at least up to v7.1.1; used in many jpgs). A quick fix to accomodate this:
def get_image_dims(file_path):
from PIL import Image as pilim
im = pilim.open(file_path)
# returns (w,h) after rotation-correction
return im.size if im._getexif().get(274,0) < 5 else im.size[::-1]
Is it better to use std::memcpy() or std::copy() in terms to performance?
Just a minor addition: The speed difference between memcpy()
and std::copy()
can vary quite a bit depending on if optimizations are enabled or disabled. With g++ 6.2.0 and without optimizations memcpy()
clearly wins:
Benchmark Time CPU Iterations
---------------------------------------------------
bm_memcpy 17 ns 17 ns 40867738
bm_stdcopy 62 ns 62 ns 11176219
bm_stdcopy_n 72 ns 72 ns 9481749
When optimizations are enabled (-O3
), everything looks pretty much the same again:
Benchmark Time CPU Iterations
---------------------------------------------------
bm_memcpy 3 ns 3 ns 274527617
bm_stdcopy 3 ns 3 ns 272663990
bm_stdcopy_n 3 ns 3 ns 274732792
The bigger the array the less noticeable the effect gets, but even at N=1000
memcpy()
is about twice as fast when optimizations aren't enabled.
Source code (requires Google Benchmark):
#include <string.h>
#include <algorithm>
#include <vector>
#include <benchmark/benchmark.h>
constexpr int N = 10;
void bm_memcpy(benchmark::State& state)
{
std::vector<int> a(N);
std::vector<int> r(N);
while (state.KeepRunning())
{
memcpy(r.data(), a.data(), N * sizeof(int));
}
}
void bm_stdcopy(benchmark::State& state)
{
std::vector<int> a(N);
std::vector<int> r(N);
while (state.KeepRunning())
{
std::copy(a.begin(), a.end(), r.begin());
}
}
void bm_stdcopy_n(benchmark::State& state)
{
std::vector<int> a(N);
std::vector<int> r(N);
while (state.KeepRunning())
{
std::copy_n(a.begin(), N, r.begin());
}
}
BENCHMARK(bm_memcpy);
BENCHMARK(bm_stdcopy);
BENCHMARK(bm_stdcopy_n);
BENCHMARK_MAIN()
/* EOF */
Parsing XML with namespace in Python via 'ElementTree'
My solution is based on @Martijn Pieters' comment:
register_namespace
only influences serialisation, not search.
So the trick here is to use different dictionaries for serialization and for searching.
namespaces = {
'': 'http://www.example.com/default-schema',
'spec': 'http://www.example.com/specialized-schema',
}
Now, register all namespaces for parsing and writing:
for name, value in namespaces.iteritems():
ET.register_namespace(name, value)
For searching (find()
, findall()
, iterfind()
) we need a non-empty prefix. Pass these functions a modified dictionary (here I modify the original dictionary, but this must be made only after the namespaces are registered).
self.namespaces['default'] = self.namespaces['']
Now, the functions from the find()
family can be used with the default
prefix:
print root.find('default:myelem', namespaces)
but
tree.write(destination)
does not use any prefixes for elements in the default namespace.
How to get file name when user select a file via <input type="file" />?
You can use the next code:
JS
function showname () {
var name = document.getElementById('fileInput');
alert('Selected file: ' + name.files.item(0).name);
alert('Selected file: ' + name.files.item(0).size);
alert('Selected file: ' + name.files.item(0).type);
};
HTML
<body>
<p>
<input type="file" id="fileInput" multiple onchange="showname()"/>
</p>
</body>
Display a tooltip over a button using Windows Forms
Lazy and compact storing text in the Tag property
If you are a bit lazy and do not use the Tag property of the controls for anything else you can use it to store the tooltip text and assign MouseHover event handlers to all such controls in one go like this:
private System.Windows.Forms.ToolTip ToolTip1;
private void PrepareTooltips()
{
ToolTip1 = new System.Windows.Forms.ToolTip();
foreach(Control ctrl in this.Controls)
{
if (ctrl is Button && ctrl.Tag is string)
{
ctrl.MouseHover += new EventHandler(delegate(Object o, EventArgs a)
{
var btn = (Control)o;
ToolTip1.SetToolTip(btn, btn.Tag.ToString());
});
}
}
}
In this case all buttons having a string in the Tag property is assigned a MouseHover event. To keep it compact the MouseHover event is defined inline using a lambda expression. In the event any button hovered will have its Tag text assigned to the Tooltip and shown.
No Access-Control-Allow-Origin header is present on the requested resource
Solution:
Instead of using setHeader
method I have used addHeader
.
response.addHeader("Access-Control-Allow-Origin", "*");
*
in above line will allow access to all domains, For allowing access to specific domain only:
response.addHeader("Access-Control-Allow-Origin", "http://www.example.com");
For issues related to IE<=9, Please see here.
Is there StartsWith or Contains in t sql with variables?
StartsWith
a) left(@edition, 15) = 'Express Edition'
b) charindex('Express Edition', @edition) = 1
Contains
charindex('Express Edition', @edition) >= 1
Examples
left
function
set @isExpress = case when left(@edition, 15) = 'Express Edition' then 1 else 0 end
iif
function (starting with SQL Server 2012)
set @isExpress = iif(left(@edition, 15) = 'Express Edition', 1, 0);
charindex
function
set @isExpress = iif(charindex('Express Edition', @edition) = 1, 1, 0);
Doing HTTP requests FROM Laravel to an external API
Updated on March 21 2019
Add GuzzleHttp
package using composer require guzzlehttp/guzzle:~6.3.3
Or you can specify Guzzle as a dependency in your project's composer.json
{
"require": {
"guzzlehttp/guzzle": "~6.3.3"
}
}
Include below line in the top of the class where you are calling the API
use GuzzleHttp\Client;
Add below code for making the request
$client = new Client();
$res = $client->request('POST', 'http://www.exmple.com/mydetails', [
'form_params' => [
'name' => 'george',
]
]);
if ($res->getStatusCode() == 200) { // 200 OK
$response_data = $res->getBody()->getContents();
}
Why is IoC / DI not common in Python?
In my opinion, things like dependency injection are symptoms of a rigid and over-complex framework. When the main body of code becomes much too weighty to change easily, you find yourself having to pick small parts of it, define interfaces for them, and then allowing people to change behaviour via the objects that plug into those interfaces. That's all well and good, but it's better to avoid that sort of complexity in the first place.
It's also the symptom of a statically-typed language. When the only tool you have to express abstraction is inheritance, then that's pretty much what you use everywhere. Having said that, C++ is pretty similar but never picked up the fascination with Builders and Interfaces everywhere that Java developers did. It is easy to get over-exuberant with the dream of being flexible and extensible at the cost of writing far too much generic code with little real benefit. I think it's a cultural thing.
Typically I think Python people are used to picking the right tool for the job, which is a coherent and simple whole, rather than the One True Tool (With A Thousand Possible Plugins) that can do anything but offers a bewildering array of possible configuration permutations. There are still interchangeable parts where necessary, but with no need for the big formalism of defining fixed interfaces, due to the flexibility of duck-typing and the relative simplicity of the language.
How to pass command line arguments to a shell alias?
You found the way: create a function instead of an alias. The C shell has a mechanism for doing arguments to aliases, but bash and the Korn shell don't, because the function mechanism is more flexible and offers the same capability.
Close/kill the session when the browser or tab is closed
I do it like this:
$(window).bind('unload', function () {
if(event.clientY < 0) {
alert('Thank you for using this app.');
endSession(); // here you can do what you want ...
}
});
window.onbeforeunload = function () {
$(window).unbind('unload');
//If a string is returned, you automatically ask the
//user if he wants to logout or not...
//return ''; //'beforeunload event';
if (event.clientY < 0) {
alert('Thank you for using this service.');
endSession();
}
}
What is a Python egg?
Python eggs are a way of bundling additional information with a Python project, that allows the project's dependencies to be checked and satisfied at runtime, as well as allowing projects to provide plugins for other projects. There are several binary formats that embody eggs, but the most common is '.egg' zipfile format, because it's a convenient one for distributing projects. All of the formats support including package-specific data, project-wide metadata, C extensions, and Python code.
The easiest way to install and use Python eggs is to use the "Easy Install" Python package manager, which will find, download, build, and install eggs for you; all you do is tell it the name (and optionally, version) of the Python project(s) you want to use.
Python eggs can be used with Python 2.3 and up, and can be built using the setuptools package (see the Python Subversion sandbox for source code, or the EasyInstall page for current installation instructions).
The primary benefits of Python Eggs are:
They enable tools like the "Easy Install" Python package manager
.egg files are a "zero installation" format for a Python package; no build or install step is required, just put them on PYTHONPATH or sys.path and use them (may require the runtime installed if C extensions or data files are used)
They can include package metadata, such as the other eggs they depend on
They allow "namespace packages" (packages that just contain other packages) to be split into separate distributions (e.g. zope., twisted., peak.* packages can be distributed as separate eggs, unlike normal packages which must always be placed under the same parent directory. This allows what are now huge monolithic packages to be distributed as separate components.)
They allow applications or libraries to specify the needed version of a library, so that you can e.g. require("Twisted-Internet>=2.0") before doing an import twisted.internet.
They're a great format for distributing extensions or plugins to extensible applications and frameworks (such as Trac, which uses eggs for plugins as of 0.9b1), because the egg runtime provides simple APIs to locate eggs and find their advertised entry points (similar to Eclipse's "extension point" concept).
There are also other benefits that may come from having a standardized format, similar to the benefits of Java's "jar" format.
How to use RecyclerView inside NestedScrollView?
For my case the child of NestedScrollview is ConstraintLayout. It is not working as expected i replaced it to LinearLayout. Maybe it helps someone.
<androidx.core.widget.NestedScrollView
android:id="@+id/nestedScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:nestedScrollingEnabled="false" />
</LinearLayout>
</androidx.core.widget.NestedScrollView>
How to find elements by class
This works for me to access the class attribute (on beautifulsoup 4, contrary to what the documentation says). The KeyError comes a list being returned not a dictionary.
for hit in soup.findAll(name='span'):
print hit.contents[1]['class']
Using C# to read/write Excel files (.xls/.xlsx)
If you are doing simple manipulation and can tie yourself to xlsx then you can look into manipulating the XML yourself. I have done it and found it to be faster than grokking the excel libs.
There are also 3rd party libs that can be easier to use... and can be used on the server which MS's can't.
Convert data.frame column format from character to factor
If you want to change all character variables in your data.frame to factors after you've already loaded your data, you can do it like this, to a data.frame called dat
:
character_vars <- lapply(dat, class) == "character"
dat[, character_vars] <- lapply(dat[, character_vars], as.factor)
This creates a vector identifying which columns are of class character
, then applies as.factor
to those columns.
Sample data:
dat <- data.frame(var1 = c("a", "b"),
var2 = c("hi", "low"),
var3 = c(0, 0.1),
stringsAsFactors = FALSE
)
How do I disable the resizable property of a textarea?
The following CSS rule disables resizing behavior for textarea
elements:
textarea {
resize: none;
}
To disable it for some (but not all) textarea
s, there are a couple of options.
To disable a specific textarea
with the name
attribute set to foo
(i.e., <textarea name="foo"></textarea>
):
textarea[name=foo] {
resize: none;
}
Or, using an id
attribute (i.e., <textarea id="foo"></textarea>
):
#foo {
resize: none;
}
The W3C page lists possible values for resizing restrictions: none, both, horizontal, vertical, and inherit:
textarea {
resize: vertical; /* user can resize vertically, but width is fixed */
}
Review a decent compatibility page to see what browsers currently support this feature. As Jon Hulka has commented, the dimensions can be further restrained in CSS using max-width, max-height, min-width, and min-height.
Super important to know:
This property does nothing unless the overflow property is something other than visible, which is the default for most elements. So generally to use this, you'll have to set something like overflow: scroll;
Quote by Sara Cope,
http://css-tricks.com/almanac/properties/r/resize/
How to check if a line is blank using regex
The pattern you want is something like this in multiline mode:
^\s*$
Explanation:
^
is the beginning of string anchor.
$
is the end of string anchor.
\s
is the whitespace character class.
*
is zero-or-more repetition of.
In multiline mode, ^
and $
also match the beginning and end of the line.
References:
A non-regex alternative:
You can also check if a given string line
is "blank" (i.e. containing only whitespaces) by trim()
-ing it, then checking if the resulting string isEmpty()
.
In Java, this would be something like this:
if (line.trim().isEmpty()) {
// line is "blank"
}
The regex solution can also be simplified without anchors (because of how matches
is defined in Java) as follows:
if (line.matches("\\s*")) {
// line is "blank"
}
API references
Intellij JAVA_HOME variable
In my case I needed a lower JRE, so I had to tell IntelliJ to use a different one in "Platform Settings"
- Platform Settings > SDKs ( ⌘+; )
- Click the + button to add a new SDK (or rename and load an existing one)
- Choose the /Contents/Home directory from the appropriate SDK
(i.e. /Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home)
Google Maps API v3 marker with label
I can't guarantee it's the simplest, but I like MarkerWithLabel. As shown in the basic example, CSS styles define the label's appearance and options in the JavaScript define the content and placement.
.labels {
color: red;
background-color: white;
font-family: "Lucida Grande", "Arial", sans-serif;
font-size: 10px;
font-weight: bold;
text-align: center;
width: 60px;
border: 2px solid black;
white-space: nowrap;
}
JavaScript:
var marker = new MarkerWithLabel({
position: homeLatLng,
draggable: true,
map: map,
labelContent: "$425K",
labelAnchor: new google.maps.Point(22, 0),
labelClass: "labels", // the CSS class for the label
labelStyle: {opacity: 0.75}
});
The only part that may be confusing is the labelAnchor. By default, the label's top left corner will line up to the marker pushpin's endpoint. Setting the labelAnchor's x-value to half the width defined in the CSS width property will center the label. You can make the label float above the marker pushpin with an anchor point like new google.maps.Point(22, 50)
.
In case access to the links above are blocked, I copied and pasted the packed source of MarkerWithLabel into this JSFiddle demo. I hope JSFiddle is allowed in China :|
SQL Server Group By Month
Now your query is explicitly looking at only payments for year = 2010, however, I think you meant to have your Jan/Feb/Mar actually represent 2009. If so, you'll need to adjust this a bit for that case. Don't keep requerying the sum values for every column, just the condition of the date difference in months. Put the rest in the WHERE clause.
SELECT
SUM( case when DateDiff(m, PaymentDate, @start) = 0
then Amount else 0 end ) AS "Apr",
SUM( case when DateDiff(m, PaymentDate, @start) = 1
then Amount else 0 end ) AS "May",
SUM( case when DateDiff(m, PaymentDate, @start) = 2
then Amount else 0 end ) AS "June",
SUM( case when DateDiff(m, PaymentDate, @start) = 3
then Amount else 0 end ) AS "July",
SUM( case when DateDiff(m, PaymentDate, @start) = 4
then Amount else 0 end ) AS "Aug",
SUM( case when DateDiff(m, PaymentDate, @start) = 5
then Amount else 0 end ) AS "Sep",
SUM( case when DateDiff(m, PaymentDate, @start) = 6
then Amount else 0 end ) AS "Oct",
SUM( case when DateDiff(m, PaymentDate, @start) = 7
then Amount else 0 end ) AS "Nov",
SUM( case when DateDiff(m, PaymentDate, @start) = 8
then Amount else 0 end ) AS "Dec",
SUM( case when DateDiff(m, PaymentDate, @start) = 9
then Amount else 0 end ) AS "Jan",
SUM( case when DateDiff(m, PaymentDate, @start) = 10
then Amount else 0 end ) AS "Feb",
SUM( case when DateDiff(m, PaymentDate, @start) = 11
then Amount else 0 end ) AS "Mar"
FROM
Payments I
JOIN Live L
on I.LiveID = L.Record_Key
WHERE
Year = 2010
AND UserID = 100
How to generate entire DDL of an Oracle schema (scriptable)?
The get_ddl procedure for a PACKAGE will return both spec AND body, so it will be better to change the query on the all_objects so the package bodies are not returned on the select.
So far I changed the query to this:
SELECT DBMS_METADATA.GET_DDL(REPLACE(object_type, ' ', '_'), object_name, owner)
FROM all_OBJECTS
WHERE (OWNER = 'OWNER1')
and object_type not like '%PARTITION'
and object_type not like '%BODY'
order by object_type, object_name;
Although other changes might be needed depending on the object types you are getting...
how to replace an entire column on Pandas.DataFrame
For those that struggle with the "SettingWithCopy" warning, here's a workaround which may not be so efficient, but still gets the job done.
Suppose you with to overwrite column_1 and column_3, but retain column_2 and column_4
columns_to_overwrite = ["column_1", "column_3"]
First delete the columns that you intend to replace...
original_df.drop(labels=columns_to_overwrite, axis="columns", inplace=True)
... then re-insert the columns, but using the values that you intended to overwrite
original_df[columns_to_overwrite] = other_data_frame[columns_to_overwrite]
Correct MIME Type for favicon.ico?
I have noticed that when using type="image/vnd.microsoft.icon"
, the favicon fails to appear when the browser is not connected to the internet.
But type="image/x-icon"
works whether the browser can connect to the internet, or not.
When developing, at times I am not connected to the internet.
Multiple files upload (Array) with CodeIgniter 2.0
You should use this library for multi upload in CI https://github.com/stvnthomas/CodeIgniter-Multi-Upload
Installation Simply copy the MY_Upload.php file to your applications library directory.
Use: function test_up in controller
public function test_up(){
if($this->input->post('submit')){
$path = './public/test_upload/';
$this->load->library('upload');
$this->upload->initialize(array(
"upload_path"=>$path,
"allowed_types"=>"*"
));
if($this->upload->do_multi_upload("myfile")){
echo '<pre>';
print_r($this->upload->get_multi_upload_data());
echo '</pre>';
}
}else{
$this->load->view('test/upload_view');
}
}
upload_view.php in applications/view/test folder
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="myfile[]" id="myfile" multiple>
<input type="submit" name="submit" id="submit" value="submit"/>
How can I pipe stderr, and not stdout?
You can use the rc shell.
First install the package (it's less than 1 MB).
This an example of how you would discard standard output and pipe standard error to grep in rc
:
find /proc/ >[1] /dev/null |[2] grep task
You can do it without leaving Bash:
rc -c 'find /proc/ >[1] /dev/null |[2] grep task'
As you may have noticed, you can specify which file descriptor you want piped by using brackets after the pipe.
Standard file descriptors are numerated as such:
- 0 : Standard input
- 1 : Standard output
- 2 : Standard error
How to use Tomcat 8 in Eclipse?
The only thing the eclipse plugin is checking is the tomcat version inside:
catalina.jar!/org/apache/catalina/util/ServerInfo.properties
I replaced the properties file with the one in tomcat7 and that fixed the issue for eclipse
In order to be able to deploy the spring-websockets sample app you need to edit the following file in eclipse:
.settings/org.eclipse.wst.common.project.facet.core.xml
And change the web version to 2.5
<installed facet="jst.web" version="2.5"/>
header('HTTP/1.0 404 Not Found'); not doing anything
i think this will help you
content of .htaccess
ErrorDocument 404 /error.php
ErrorDocument 400 /error.php
ErrorDocument 401 /error.php
ErrorDocument 403 /error.php
ErrorDocument 405 /error.php
ErrorDocument 406 /error.php
ErrorDocument 409 /error.php
ErrorDocument 413 /error.php
ErrorDocument 414 /error.php
ErrorDocument 500 /error.php
ErrorDocument 501 /error.php
error.php and .htaccess should be put in the same directory [in this case]
angularjs directive call function specified in attribute and pass an argument to it
Here's what worked for me.
Html using the directive
<tr orderitemdirective remove="vm.removeOrderItem(orderItem)" order-item="orderitem"></tr>
Html of the directive: orderitem.directive.html
<md-button type="submit" ng-click="remove({orderItem:orderItem})">
(...)
</md-button>
Directive's scope:
scope: {
orderItem: '=',
remove: "&",
How do you overcome the svn 'out of date' error?
I believe this problem is coming from the .svn file. It's either incorrect in the old parent, the new parent or the old one. I would try reverting back to your starting point. Use an export to get a clean copy of the folder. Move the clean copy to the new location, and use an add and delete to do the move. That's manually doing what SVN does, but it might work.
Hide/Show components in react native
I needed to switch between two images. With conditional switching between them there was 5sec delay with no image displayed.
I'm using approach from downvoted amos answer. Posting as new answer because it's hard to put code into comment with proper formatting.
Render function:
<View style={styles.logoWrapper}>
<Image
style={[styles.logo, loading ? styles.hidden : {}]}
source={require('./logo.png')} />
<Image
style={[styles.logo, loading ? {} : styles.hidden]}
source={require('./logo_spin.gif')} />
</View>
Styles:
var styles = StyleSheet.create({
logo: {
width: 200,
height: 200,
},
hidden: {
width: 0,
height: 0,
},
});
Get list of JSON objects with Spring RestTemplate
You can create POJO for each entry like,
class BitPay{
private String code;
private String name;
private double rate;
}
then using ParameterizedTypeReference of List of BitPay you can use as:
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<List<Employee>> response = restTemplate.exchange(
"https://bitpay.com/api/rates",
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<BitPay>>(){});
List<Employee> employees = response.getBody();
How to store Configuration file and read it using React
You can use the dotenv package no matter what setup you use. It allows you to create a .env in your project root and specify your keys like so
REACT_APP_SERVER_PORT=8000
In your applications entry file your just call dotenv(); before accessing the keys like so
process.env.REACT_APP_SERVER_PORT
How to easily resize/optimize an image size with iOS?
Adding to the slew of answers here, but I have gone for a solution which resizes by file size, rather than dimensions.
This will both reduce the dimensions and quality of the image until it reaches your given size.
func compressTo(toSizeInMB size: Double) -> UIImage? {
let bytes = size * 1024 * 1024
let sizeInBytes = Int(bytes)
var needCompress:Bool = true
var imgData:Data?
var compressingValue:CGFloat = 1.0
while (needCompress) {
if let resizedImage = scaleImage(byMultiplicationFactorOf: compressingValue), let data: Data = UIImageJPEGRepresentation(resizedImage, compressingValue) {
if data.count < sizeInBytes || compressingValue < 0.1 {
needCompress = false
imgData = data
} else {
compressingValue -= 0.1
}
}
}
if let data = imgData {
print("Finished with compression value of: \(compressingValue)")
return UIImage(data: data)
}
return nil
}
private func scaleImage(byMultiplicationFactorOf factor: CGFloat) -> UIImage? {
let size = CGSize(width: self.size.width*factor, height: self.size.height*factor)
UIGraphicsBeginImageContext(size)
draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
if let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext() {
UIGraphicsEndImageContext()
return newImage;
}
return nil
}
Credit for scaling by size answer
How to make a movie out of images in python
You could consider using an external tool like ffmpeg to merge the images into a movie (see answer here) or you could try to use OpenCv to combine the images into a movie like the example here.
I'm attaching below a code snipped I used to combine all png files from a folder called "images" into a video.
import cv2
import os
image_folder = 'images'
video_name = 'video.avi'
images = [img for img in os.listdir(image_folder) if img.endswith(".png")]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape
video = cv2.VideoWriter(video_name, 0, 1, (width,height))
for image in images:
video.write(cv2.imread(os.path.join(image_folder, image)))
cv2.destroyAllWindows()
video.release()
What are the differences between 'call-template' and 'apply-templates' in XSL?
To add to the good answer by @Tomalak:
Here are some unmentioned and important differences:
xsl:apply-templates
is much richer and deeper than xsl:call-templates
and even from xsl:for-each
, simply because we don't know what code will be applied on the nodes of
the selection -- in the general case this code will be different for
different nodes of the node-list.
The code that will be applied
can be written way after the xsl:apply template
s was written and by
people that do not know the original author.
The FXSL library's implementation of higher-order functions (HOF) in XSLT wouldn't be possible if XSLT didn't have the <xsl:apply-templates>
instruction.
Summary: Templates and the <xsl:apply-templates>
instruction is how XSLT implements and deals with polymorphism.
Reference: See this whole thread: http://www.biglist.com/lists/lists.mulberrytech.com/xsl-list/archives/200411/msg00546.html
How to pass extra variables in URL with WordPress
to add parameter to post urls (to perma-links), i use this:
add_filter( 'post_type_link', 'append_query_string', 10, 2 );
function append_query_string( $url, $post )
{
return add_query_arg('my_pid',$post->ID, $url);
}
output:
http://yoursite.com/pagename?my_pid=12345678
tqdm in Jupyter Notebook prints new progress bars repeatedly
None of the above works for me. I find that running the following sorts this issue after error (It just clears all the instances of progress bars in the background):
from tqdm import tqdm
# blah blah your code errored
tqdm._instances.clear()
How to completely uninstall python 2.7.13 on Ubuntu 16.04
How I do:
# Remove python2
sudo apt purge -y python2.7-minimal
# You already have Python3 but
# don't care about the version
sudo ln -s /usr/bin/python3 /usr/bin/python
# Same for pip
sudo apt install -y python3-pip
sudo ln -s /usr/bin/pip3 /usr/bin/pip
# Confirm the new version of Python: 3
python --version
Automatically plot different colored lines
Actually, a decent shortcut method for getting the colors to cycle is to use hold all;
in place of hold on;
. Each successive plot
will rotate (automatically for you) through MATLAB's default colormap.
From the MATLAB site on hold
:
hold all
holds the plot and the current line color and line style so that subsequent plotting commands do not reset the ColorOrder and LineStyleOrder property values to the beginning of the list. Plotting commands continue cycling through the predefined colors and linestyles from where the last plot stopped in the list.
How to convert wstring into string?
You might as well just use the ctype facet's narrow method directly:
#include <clocale>
#include <locale>
#include <string>
#include <vector>
inline std::string narrow(std::wstring const& text)
{
std::locale const loc("");
wchar_t const* from = text.c_str();
std::size_t const len = text.size();
std::vector<char> buffer(len + 1);
std::use_facet<std::ctype<wchar_t> >(loc).narrow(from, from + len, '_', &buffer[0]);
return std::string(&buffer[0], &buffer[len]);
}
MongoDB: How to find out if an array field contains an element?
[edit based on this now being possible in recent versions]
[Updated Answer] You can query the following way to get back the name of class and the student id only if they are already enrolled.
db.student.find({},
{_id:0, name:1, students:{$elemMatch:{$eq:ObjectId("51780f796ec4051a536015cf")}}})
and you will get back what you expected:
{ "name" : "CS 101", "students" : [ ObjectId("51780f796ec4051a536015cf") ] }
{ "name" : "Literature" }
{ "name" : "Physics", "students" : [ ObjectId("51780f796ec4051a536015cf") ] }
[Original Answer] It's not possible to do what you want to do currently. This is unfortunate because you would be able to do this if the student was stored in the array as an object. In fact, I'm a little surprised you are using just ObjectId() as that will always require you to look up the students if you want to display a list of students enrolled in a particular course (look up list of Id's first then look up names in the students collection - two queries instead of one!)
If you were storing (as an example) an Id and name in the course array like this:
{
"_id" : ObjectId("51780fb5c9c41825e3e21fc6"),
"name" : "Physics",
"students" : [
{id: ObjectId("51780f796ec4051a536015cf"), name: "John"},
{id: ObjectId("51780f796ec4051a536015d0"), name: "Sam"}
]
}
Your query then would simply be:
db.course.find( { },
{ students :
{ $elemMatch :
{ id : ObjectId("51780f796ec4051a536015d0"),
name : "Sam"
}
}
}
);
If that student was only enrolled in CS 101 you'd get back:
{ "name" : "Literature" }
{ "name" : "Physics" }
{
"name" : "CS 101",
"students" : [
{
"id" : ObjectId("51780f796ec4051a536015cf"),
"name" : "John"
}
]
}
Spring cannot find bean xml configuration file when it does exist
Gradle : v4.10.3
IDE : IntelliJ
I was facing this issue when using gradle to run my build and test. Copying the applicationContext.xml all over the place did not help. Even specifying the complete path as below did not help !
context = new ClassPathXmlApplicationContext("C:\\...\\applicationContext.xml");
The solution (for gradle at least) lies in the way gradle processes resources. For my gradle project I had laid out the workspace as defined at https://docs.gradle.org/current/userguide/java_plugin.html#sec:java_project_layout
When running a test using default gradle set of tasks includes a "processTestResources" step, which looks for test resources at C:\.....\src\test\resources (Gradle helpfully provides the complete path).
Your .properties file and applicationContext.xml need to be in this directory. If the resources directory is not present (as it was in my case), you need to create it copy the file(s) there. After this, simply specifying the file name worked just fine.
context = new ClassPathXmlApplicationContext("applicationContext.xml");
Installing PDO driver on MySQL Linux server
On Ubuntu you should be able to install the necessary PDO parts from apt using sudo apt-get install php5-mysql
There is no limitation between using PDO and mysql_ simultaneously. You will however need to create two connections to your DB, one with mysql_ and one using PDO.
Focus Input Box On Load
very simple one line solution:
<body onLoad="document.getElementById('myinputbox').focus();">
if (boolean condition) in Java
The syntax of if block is as below,
if(condition){
// Executes when condition evaluates to true.
}
else{
// Executes when condition evaluates to false.
}
In your case you are directly passing a boolean value so no evaluation is required.
CodeIgniter 404 Page Not Found, but why?
The cause of the problem was that the server was running PHP using FastCGI.
After changing the config.php to
$config['uri_protocol'] = "REQUEST_URI";
everything worked.
Is there a NumPy function to return the first index of something in an array?
To index on any criteria, you can so something like the following:
In [1]: from numpy import *
In [2]: x = arange(125).reshape((5,5,5))
In [3]: y = indices(x.shape)
In [4]: locs = y[:,x >= 120] # put whatever you want in place of x >= 120
In [5]: pts = hsplit(locs, len(locs[0]))
In [6]: for pt in pts:
.....: print(', '.join(str(p[0]) for p in pt))
4, 4, 0
4, 4, 1
4, 4, 2
4, 4, 3
4, 4, 4
And here's a quick function to do what list.index() does, except doesn't raise an exception if it's not found. Beware -- this is probably very slow on large arrays. You can probably monkey patch this on to arrays if you'd rather use it as a method.
def ndindex(ndarray, item):
if len(ndarray.shape) == 1:
try:
return [ndarray.tolist().index(item)]
except:
pass
else:
for i, subarray in enumerate(ndarray):
try:
return [i] + ndindex(subarray, item)
except:
pass
In [1]: ndindex(x, 103)
Out[1]: [4, 0, 3]
Example of multipart/form-data
EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245
To see exactly what is happening, use nc -l
or an ECHO server and an user agent like a browser or cURL.
Save the form to an .html
file:
<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
<p><input type="text" name="text" value="text default">
<p><input type="file" name="file1">
<p><input type="file" name="file2">
<p><button type="submit">Submit</button>
</form>
Create files to upload:
echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html
Run:
nc -l localhost 8000
Open the HTML on your browser, select the files and click on submit and check the terminal.
nc
prints the request received. Firefox sent:
POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"
text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain
Content of a.txt.
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html
<!DOCTYPE html><title>Content of a.html.</title>
-----------------------------9051914041544843365972754266--
Aternativelly, cURL should send the same POST request as your a browser form:
nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000
You can do multiple tests with:
while true; do printf '' | nc -l localhost 8000; done
Persist javascript variables across pages?
You can use http://rhaboo.org as a wrapper around localStorage. It stores complex objects but doesn't merely stringify and parse the whole thing like most such libraries do. That's really inefficient if you want to store a lot of data and add to it or change it in small chunks. Also, JSON discards a lot of important stuff like non-numerical properties of arrays.
In rhaboo you can write things like this:
var store = Rhaboo.persistent('Some name');
store.write('count', store.count ? store.count+1 : 1);
var laststamp = store.stamp ? store.stamp.toString() : "never";
store.write('stamp', new Date());
store.write('somethingfancy', {
one: ['man', 'went'],
2: 'mow',
went: [ 2, { mow: ['a', 'meadow' ] }, {} ]
});
store.somethingfancy.went[1].mow.write(1, 'lawn');
console.log( store.somethingfancy.went[1].mow[1] ); //says lawn
BTW, I wrote rhaboo
Notice: Array to string conversion in
Store the Value of $_SESSION['username'] into a variable such as $username
$username=$_SESSION['username'];
$get = @mysql_query("SELECT money FROM players WHERE username =
'$username'");
it should work!