how to save DOMPDF generated content to file?
I have just used dompdf and the code was a little different but it worked.
Here it is:
require_once("./pdf/dompdf_config.inc.php");
$files = glob("./pdf/include/*.php");
foreach($files as $file) include_once($file);
$html =
'<html><body>'.
'<p>Put your html here, or generate it with your favourite '.
'templating system.</p>'.
'</body></html>';
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$output = $dompdf->output();
file_put_contents('Brochure.pdf', $output);
Only difference here is that all of the files in the include directory are included.
Other than that my only suggestion would be to specify a full directory path for writing the file rather than just the filename.
Convert Word doc, docx and Excel xls, xlsx to PDF with PHP
Well my 2 cents when it comes to the topic word 2007 docx
, word 97-2004 doc
, pdf
and all other types of MS Office wishing to be "converted from y
to z
but in real they don't wanna be". In my experience so far, conversion with LibreOffice or OpenOffice can't be relied on. Though .doc
documents tend to be better supported than word 2007's .docx
. In general it's very hard to convert the .docx
to .doc
without breaking anything.
.docx
also tend to be extremely useful for templating where .doc
is not for being binary.
The conversion from .doc
to PDF was most of the time quite reliable. If you can still influence the design or content of the word document then this might be satisfying, but in my situation documents were supplied from foreign companies where even after generating the .docx
templates, in some scenario's, the generated .docx
had to be slightly modified with supplement text before it was generated to a PDF.
WINDOWS BASED!
All this hiccup made me come to the conclusion that the only true reliable conversion method I found was using the COM class in PHP and let the MS Word or Excel Application do all the work for you. I'll just give an example on converting .docx
to .doc
and/or PDF. If you do not have MS Office installed, you can download a trial version of 60 days which would give you enough room for testing purposes.
the COM.net extension is by default commented out in the php.ini
, just search for the line php_com_dotnet.dll
and uncomment it like so
extension=php_com_dotnet.dll
Restart the web server (IIS is not a pre, Apache will work just as well).
The code below is a demonstration on how easy it is.
$word = new COM("Word.Application") or die ("Could not initialise Object.");
// set it to 1 to see the MS Word window (the actual opening of the document)
$word->Visible = 0;
// recommend to set to 0, disables alerts like "Do you want MS Word to be the default .. etc"
$word->DisplayAlerts = 0;
// open the word 2007-2013 document
$word->Documents->Open('yourdocument.docx');
// save it as word 2003
$word->ActiveDocument->SaveAs('newdocument.doc');
// convert word 2007-2013 to PDF
$word->ActiveDocument->ExportAsFixedFormat('yourdocument.pdf', 17, false, 0, 0, 0, 0, 7, true, true, 2, true, true, false);
// quit the Word process
$word->Quit(false);
// clean up
unset($word);
This is just a small demonstration. I can just say that if it comes to conversion, this was the only real reliable option I could use and even recommend.
Convert canvas to PDF
So for today, jspdf-1.5.3.
To answer the question of having the pdf file page exactly same as the canvas. After many tries of different combinations, I figured you gotta do something like this.
We first need to set the height and width for the output pdf file with correct orientation, otherwise the sides might be cut off. Then we get the dimensions from the 'pdf' file itself, if you tried to use the canvas's dimensions, the sides might be cut off again. I am not sure why that happens, my best guess is the jsPDF convert the dimensions in other units in the library.
// Download button
$("#download-image").on('click', function () {
let width = __CANVAS.width;
let height = __CANVAS.height;
//set the orientation
if(width > height){
pdf = new jsPDF('l', 'px', [width, height]);
}
else{
pdf = new jsPDF('p', 'px', [height, width]);
}
//then we get the dimensions from the 'pdf' file itself
width = pdf.internal.pageSize.getWidth();
height = pdf.internal.pageSize.getHeight();
pdf.addImage(__CANVAS, 'PNG', 0, 0,width,height);
pdf.save("download.pdf");
});
Learnt about switching orientations from here:
https://github.com/MrRio/jsPDF/issues/476
Converting HTML to PDF using PHP?
If you wish to create a pdf from php, pdflib will help you (as some others suggested).
Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.
So, the options I know are:
DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.
HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.
Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:
wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.
htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.
Render HTML to PDF in Django site
Try the solution from Reportlab.
Download it and install it as usual with python setup.py install
You will also need to install the following modules: xhtml2pdf, html5lib, pypdf with easy_install.
Here is an usage example:
First define this function:
import cStringIO as StringIO
from xhtml2pdf import pisa
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
from cgi import escape
def render_to_pdf(template_src, context_dict):
template = get_template(template_src)
context = Context(context_dict)
html = template.render(context)
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))
Then you can use it like this:
def myview(request):
#Retrieve data or whatever you need
return render_to_pdf(
'mytemplate.html',
{
'pagesize':'A4',
'mylist': results,
}
)
The template:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>My Title</title>
<style type="text/css">
@page {
size: {{ pagesize }};
margin: 1cm;
@frame footer {
-pdf-frame-content: footerContent;
bottom: 0cm;
margin-left: 9cm;
margin-right: 9cm;
height: 1cm;
}
}
</style>
</head>
<body>
<div>
{% for item in mylist %}
RENDER MY CONTENT
{% endfor %}
</div>
<div id="footerContent">
{%block page_foot%}
Page <pdf:pagenumber>
{%endblock%}
</div>
</body>
</html>
Hope it helps.
Best C# API to create PDF
My work uses Winnovative's PDF generator (We've used it mainly to convert HTML to PDF, but you can generate it other ways as well)
Save multiple sheets to .pdf
Similar to Tim's answer - but with a check for 2007 (where the PDF export is not installed by default):
Public Sub subCreatePDF()
If Not IsPDFLibraryInstalled Then
'Better show this as a userform with a proper link:
MsgBox "Please install the Addin to export to PDF. You can find it at http://www.microsoft.com/downloads/details.aspx?familyid=4d951911-3e7e-4ae6-b059-a2e79ed87041".
Exit Sub
End If
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=ActiveWorkbook.Path & Application.PathSeparator & _
ActiveSheet.Name & " für " & Range("SelectedName").Value & ".pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
End Sub
Private Function IsPDFLibraryInstalled() As Boolean
'Credits go to Ron DeBruin (http://www.rondebruin.nl/pdf.htm)
IsPDFLibraryInstalled = _
(Dir(Environ("commonprogramfiles") & _
"\Microsoft Shared\OFFICE" & _
Format(Val(Application.Version), "00") & _
"\EXP_PDF.DLL") <> "")
End Function
ITextSharp insert text to an existing pdf
This worked for me and includes using OutputStream:
PdfReader reader = new PdfReader(new RandomAccessFileOrArray(Request.MapPath("Template.pdf")), null);
Rectangle size = reader.GetPageSizeWithRotation(1);
using (Stream outStream = Response.OutputStream)
{
Document document = new Document(size);
PdfWriter writer = PdfWriter.GetInstance(document, outStream);
document.Open();
try
{
PdfContentByte cb = writer.DirectContent;
cb.BeginText();
try
{
cb.SetFontAndSize(BaseFont.CreateFont(), 12);
cb.SetTextMatrix(110, 110);
cb.ShowText("aaa");
}
finally
{
cb.EndText();
}
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
}
finally
{
document.Close();
writer.Close();
reader.Close();
}
}
How to convert HTML to PDF using iTextSharp
First, HTML and PDF are not related although they were created around the same time. HTML is intended to convey higher level information such as paragraphs and tables. Although there are methods to control it, it is ultimately up to the browser to draw these higher level concepts. PDF is intended to convey documents and the documents must "look" the same wherever they are rendered.
In an HTML document you might have a paragraph that's 100% wide and depending on the width of your monitor it might take 2 lines or 10 lines and when you print it it might be 7 lines and when you look at it on your phone it might take 20 lines. A PDF file, however, must be independent of the rendering device, so regardless of your screen size it must always render exactly the same.
Because of the musts above, PDF doesn't support abstract things like "tables" or "paragraphs". There are three basic things that PDF supports: text, lines/shapes and images. (There are other things like annotations and movies but I'm trying to keep it simple here.) In a PDF you don't say "here's a paragraph, browser do your thing!". Instead you say, "draw this text at this exact X,Y location using this exact font and don't worry, I've previously calculated the width of the text so I know it will all fit on this line". You also don't say "here's a table" but instead you say "draw this text at this exact location and then draw a rectangle at this other exact location that I've previously calculated so I know it will appear to be around the text".
Second, iText and iTextSharp parse HTML and CSS. That's it. ASP.Net, MVC, Razor, Struts, Spring, etc, are all HTML frameworks but iText/iTextSharp is 100% unaware of them. Same with DataGridViews, Repeaters, Templates, Views, etc. which are all framework-specific abstractions. It is your responsibility to get the HTML from your choice of framework, iText won't help you. If you get an exception saying The document has no pages
or you think that "iText isn't parsing my HTML" it is almost definite that you don't actually have HTML, you only think you do.
Third, the built-in class that's been around for years is the HTMLWorker
however this has been replaced with XMLWorker
(Java / .Net). Zero work is being done on HTMLWorker
which doesn't support CSS files and has only limited support for the most basic CSS properties and actually breaks on certain tags. If you do not see the HTML attribute or CSS property and value in this file then it probably isn't supported by HTMLWorker
. XMLWorker
can be more complicated sometimes but those complications also make it more extensible.
Below is C# code that shows how to parse HTML tags into iText abstractions that get automatically added to the document that you are working on. C# and Java are very similar so it should be relatively easy to convert this. Example #1 uses the built-in HTMLWorker
to parse the HTML string. Since only inline styles are supported the class="headline"
gets ignored but everything else should actually work. Example #2 is the same as the first except it uses XMLWorker
instead. Example #3 also parses the simple CSS example.
//Create a byte array that will eventually hold our final PDF
Byte[] bytes;
//Boilerplate iTextSharp setup here
//Create a stream that we can write to, in this case a MemoryStream
using (var ms = new MemoryStream()) {
//Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
using (var doc = new Document()) {
//Create a writer that's bound to our PDF abstraction and our stream
using (var writer = PdfWriter.GetInstance(doc, ms)) {
//Open the document for writing
doc.Open();
//Our sample HTML and CSS
var example_html = @"<p>This <em>is </em><span class=""headline"" style=""text-decoration: underline;"">some</span> <strong>sample <em> text</em></strong><span style=""color: red;"">!!!</span></p>";
var example_css = @".headline{font-size:200%}";
/**************************************************
* Example #1 *
* *
* Use the built-in HTMLWorker to parse the HTML. *
* Only inline CSS is supported. *
* ************************************************/
//Create a new HTMLWorker bound to our document
using (var htmlWorker = new iTextSharp.text.html.simpleparser.HTMLWorker(doc)) {
//HTMLWorker doesn't read a string directly but instead needs a TextReader (which StringReader subclasses)
using (var sr = new StringReader(example_html)) {
//Parse the HTML
htmlWorker.Parse(sr);
}
}
/**************************************************
* Example #2 *
* *
* Use the XMLWorker to parse the HTML. *
* Only inline CSS and absolutely linked *
* CSS is supported *
* ************************************************/
//XMLWorker also reads from a TextReader and not directly from a string
using (var srHtml = new StringReader(example_html)) {
//Parse the HTML
iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
}
/**************************************************
* Example #3 *
* *
* Use the XMLWorker to parse HTML and CSS *
* ************************************************/
//In order to read CSS as a string we need to switch to a different constructor
//that takes Streams instead of TextReaders.
//Below we convert the strings into UTF8 byte array and wrap those in MemoryStreams
using (var msCss = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(example_css))) {
using (var msHtml = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(example_html))) {
//Parse the HTML
iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msHtml, msCss);
}
}
doc.Close();
}
}
//After all of the PDF "stuff" above is done and closed but **before** we
//close the MemoryStream, grab all of the active bytes from the stream
bytes = ms.ToArray();
}
//Now we just need to do something with those bytes.
//Here I'm writing them to disk but if you were in ASP.Net you might Response.BinaryWrite() them.
//You could also write the bytes to a database in a varbinary() column (but please don't) or you
//could pass them to another function for further PDF processing.
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");
System.IO.File.WriteAllBytes(testFile, bytes);
2017's update
There are good news for HTML-to-PDF demands. As this answer showed, the W3C standard css-break-3 will solve the problem... It is a Candidate Recommendation with plan to turn into definitive Recommendation this year, after tests.
As not-so-standard there are solutions, with plugins for C#, as showed by print-css.rocks.
Convert HTML + CSS to PDF
Try grabbing the latest nightly dompdf build - I was using an older version that was a terrible resource hog and took forever to render my pdf. After grabbing a nightly from here.
It only took a few seconds to generate the PDF - AND it was just as nicely rendered as with PrinceXML / Docraptor. Seems like they've seriously optimized the dompdf code since I last used it!
Convert PDF to PNG using ImageMagick
when you set the density to 96, doesn't it look good?
when i tried it i saw that saving as jpg resulted with better quality, but larger file size
How do I use regex in a SQLite query?
As others pointed out already, REGEXP calls a user defined function which must first be defined and loaded into the the database. Maybe some sqlite distributions or GUI tools include it by default, but my Ubuntu install did not. The solution was
sudo apt-get install sqlite3-pcre
which implements Perl regular expressions in a loadable module in /usr/lib/sqlite3/pcre.so
To be able to use it, you have to load it each time you open the database:
.load /usr/lib/sqlite3/pcre.so
Or you could put that line into your ~/.sqliterc
.
Now you can query like this:
SELECT fld FROM tbl WHERE fld REGEXP '\b3\b';
If you want to query directly from the command-line, you can use the -cmd
switch to load the library before your SQL:
sqlite3 "$filename" -cmd ".load /usr/lib/sqlite3/pcre.so" "SELECT fld FROM tbl WHERE fld REGEXP '\b3\b';"
If you are on Windows, I guess a similar .dll file should be available somewhere.
PHP error: "The zip extension and unzip command are both missing, skipping."
Not to belabor the point, but if you are working in a Dockerfile
, you would solve this particular issue with Composer by installing the unzip
utility. Below is an example using the official PHP image to install unzip
and the zip
PHP extension for good measure.
FROM php:7.4-apache
# Install Composer
COPY --from=composer /usr/bin/composer /usr/bin/composer
# Install unzip utility and libs needed by zip PHP extension
RUN apt-get update && apt-get install -y \
zlib1g-dev \
libzip-dev \
unzip
RUN docker-php-ext-install zip
This is a helpful GitHub issue where the above is lovingly lifted from.
postgreSQL - psql \i : how to execute script in a given path
Have you tried using Unix style slashes (/ instead of \)?
\ is often an escape or command character, and may be the source of confusion. I have never had issues with this, but I also do not have Windows, so I cannot test it.
Additionally, the permissions may be based on the user running psql, or maybe the user executing the postmaster service, check that both have read to that file in that directory.
Android SDK Manager Not Installing Components
In my case I was using Windows 7 with the 64-bit OS. We installed the 64-bit Java SE and 64-bit ADT Bundle. With that set up, we couldn't get the SDK manager to work correctly (specifically, no downloads allowed and it didn't show all the API download options). After trying all of the above answers and from other posts, we decided to look into the Java set up and realized it might the 64-bit configuration that's giving the ADT bundle grief (I vaguely recall seeing/reading this issue before).
So we uninstalled Java 64-bit and reinstalled the 32-bit, and then used the 32-bit ADT bundle, and it worked correctly. The system user was already an admin, so we didn't need to "Run as Administrator"
Using Javascript: How to create a 'Go Back' link that takes the user to a link if there's no history for the tab or window?
The following code did the trick for me.
html:
<div class="back" onclick="goBackOrGoHome()">
Back
</div>
js:
home_url = [YOUR BASE URL];
pathArray = document.referrer.split( '/' );
protocol = pathArray[0];
host = pathArray[2];
url_before = protocol + '//' + host;
url_now = window.location.protocol + "//" + window.location.host;
function goBackOrGoHome(){
if ( url_before == url_now) {
window.history.back();
}else{
window.location = home_url;
};
}
So, you use document.referrer
to set the domain of the page you come from. Then you compare that with your current url using window.location
.
If they are from the same domain, it means you are coming from your own site and you send them window.history.back()
. If they are not the same, you are coming from somewhere else and you should redirect home or do whatever you like.
Regex Match all characters between two strings
Here is how I did it:
This was easier for me than trying to figure out the specific regex necessary.
int indexPictureData = result.IndexOf("-PictureData:");
int indexIdentity = result.IndexOf("-Identity:");
string returnValue = result.Remove(indexPictureData + 13);
returnValue = returnValue + " [bytecoderemoved] " + result.Remove(0, indexIdentity); `
How to make google spreadsheet refresh itself every 1 minute?
If you're on the New Google Sheets, this is all you need to do, according to the docs:
change your recalculation setting to "On change and every minute" in your spreadsheet at File > Spreadsheet settings.
This will make the entire sheet update itself every minute, on the server side, regardless of whether you have the spreadsheet up in your browser or not.
If you're on the old Google Sheets, you'll want to add a cell with this formula to achieve the same functionality:
=GoogleClock()
EDIT to include old and new Google Sheets and change to =GoogleClock()
.
AttributeError: 'module' object has no attribute 'model'
As the error message says in the last line: the module models
in the file c:\projects\mysite..\mysite\polls\models.py
contains no class model
. This error occurs in the definition of the Poll
class:
class Poll(models.model):
Either the class model
is misspelled in the definition of the class Poll
or it is misspelled in the module models
. Another possibility is that it is completely missing from the module models
. Maybe it is in another module or it is not yet implemented in models
.
Convert string in base64 to image and save on filesystem in Python
Try this solution,
image file --> binary encoded string
binary encoded string --> image file
import base64
"""
1st step - convert image into binary
"""
with open("original_image.png", "rb") as original_file:
encoded_string = base64.b64encode(original_file.read())
print(encoded_string)
# xmzWowsfJbpGwCe0DTveqwvos7Mf0lcVNe/Q+G1hO/p+UNPd/stUse8AhP/3fDixf8HI3No67nvhlYAAAAASUVORK5CYII='
print(type(encoded_string))
# <class 'bytes'>
"""
2nd step - create new image using the encoded string
"""
with open("new_image.png", "wb") as new_file:
new_file.write(base64.decodebytes(encoded_string))
References:
CSS grid wrapping
Use either auto-fill
or auto-fit
as the first argument of the repeat()
notation.
<auto-repeat>
variant of the repeat()
notation:
repeat( [ auto-fill | auto-fit ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
auto-fill
When auto-fill
is given as the repetition number, if the grid
container has a definite size or max size in the relevant axis, then
the number of repetitions is the largest possible positive integer
that does not cause the grid to overflow its grid container.
https://www.w3.org/TR/css-grid-1/#valdef-repeat-auto-fill
_x000D_
_x000D_
.grid {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fill, 186px);
}
.grid>* {
background-color: green;
height: 200px;
}
_x000D_
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
_x000D_
_x000D_
_x000D_
The grid will repeat as many tracks as possible without overflowing its container.
In this case, given the example above (see image), only 5 tracks can fit the grid-container without overflowing. There are only 4 items in our grid, so a fifth one is created as an empty track within the remaining space.
The rest of the remaining space, track #6, ends the explicit grid. This means there was not enough space to place another track.
auto-fit
The auto-fit
keyword behaves the same as auto-fill
, except
that after grid item placement any empty repeated tracks are collapsed.
https://www.w3.org/TR/css-grid-1/#valdef-repeat-auto-fit
_x000D_
_x000D_
.grid {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fit, 186px);
}
.grid>* {
background-color: green;
height: 200px;
}
_x000D_
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
_x000D_
_x000D_
_x000D_
The grid will still repeat as many tracks as possible without overflowing its container, but the empty tracks will be collapsed to 0
.
A collapsed track is treated as having a fixed track sizing function of 0px
.
Unlike the auto-fill
image example, the empty fifth track is collapsed, ending the explicit grid right after the 4th item.
auto-fill
vs auto-fit
The difference between the two is noticeable when the minmax()
function is used.
Use minmax(186px, 1fr)
to range the items from 186px
to a fraction of the leftover space in the grid container.
When using auto-fill
, the items will grow once there is no space to place empty tracks.
_x000D_
_x000D_
.grid {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fill, minmax(186px, 1fr));
}
.grid>* {
background-color: green;
height: 200px;
}
_x000D_
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
_x000D_
_x000D_
_x000D_
When using auto-fit
, the items will grow to fill the remaining space because all the empty tracks will be collapsed to 0px
.
_x000D_
_x000D_
.grid {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fit, minmax(186px, 1fr));
}
.grid>* {
background-color: green;
height: 200px;
}
_x000D_
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
_x000D_
_x000D_
_x000D_
Playground:
Inspecting auto-fill tracks
Inspecting auto-fit tracks
How to create and write to a txt file using VBA
an easy way with out much redundancy.
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim Fileout As Object
Set Fileout = fso.CreateTextFile("C:\your_path\vba.txt", True, True)
Fileout.Write "your string goes here"
Fileout.Close
How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?
I was in the same situation as you, the half answers scattered throughout the Internet were quite annoying, since it seemed that many people had the same issue, but no one could be bothered to fully explain how they solved it.
The Sonar docs refer to a GitHub project with examples that are helpful. What I did to solve this was to apply the integration tests logic to regular unit tests (although proper unit tests should be submodule specific, this isn't always the case).
In the parent pom.xml, add these properties:
<properties>
<!-- Sonar -->
<sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
<sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
<sonar.jacoco.reportPath>${project.basedir}/../target/jacoco.exec</sonar.jacoco.reportPath>
<sonar.language>java</sonar.language>
</properties>
This will make Sonar pick up unit testing reports for all submodules in the same place (a target folder in the parent project). It also tells Sonar to reuse reports ran manually instead of rolling its own. We just need to make jacoco-maven-plugin run for all submodules by placing this in the parent pom, inside build/plugins:
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.6.0.201210061924</version>
<configuration>
<destFile>${sonar.jacoco.reportPath}</destFile>
<append>true</append>
</configuration>
<executions>
<execution>
<id>agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
</executions>
</plugin>
destFile
places the report file in the place where Sonar will look for it and append
makes it append to the file rather than overwriting it. This will combine all JaCoCo reports for all submodules in the same file.
Sonar will look at that file for each submodule, since that's what we pointed him at above, giving us combined unit testing results for multi module files in Sonar.
Can I set up HTML/Email Templates with ASP.NET?
Similar to Canavar's answer, but instead of NVelocity, I always use "StringTemplate"
which I load the template from a configuration file, or load an external file using File.ReadAllText() and set the values.
It's a Java project but the C# port is solid and I've used it in several projects (just used it for email templating using the template in an external file).
Alternatives are always good.
Skip a submodule during a Maven build
Sure, this can be done using profiles. You can do something like the following in your parent pom.xml.
...
<modules>
<module>module1</module>
<module>module2</module>
...
</modules>
...
<profiles>
<profile>
<id>ci</id>
<modules>
<module>module1</module>
<module>module2</module>
...
<module>module-integration-test</module>
</modules>
</profile>
</profiles>
...
In your CI, you would run maven with the ci
profile, i.e. mvn -P ci clean install
Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?
This thread is a bit older but here something I just came across:
Try this code:
$date = new DateTime();
$arr = ['date' => $date];
echo $date->format('Ymd') . '<br>';
mytest($arr);
echo $date->format('Ymd') . '<br>';
function mytest($params = []) {
if (isset($params['date'])) {
$params['date']->add(new DateInterval('P1D'));
}
}
http://codepad.viper-7.com/gwPYMw
Note there is no amp for the $params parameter and still it changes the value of $arr['date']. This doesn't really match with all the other explanations here and what I thought until now.
If I clone the $params['date'] object, the 2nd outputted date stays the same. If I just set it to a string it doesn't effect the output either.
Regex (grep) for multi-line search needed
Your fundamental problem is that grep
works one line at a time - so it cannot find a SELECT statement spread across lines.
Your second problem is that the regex you are using doesn't deal with the complexity of what can appear between SELECT and FROM - in particular, it omits commas, full stops (periods) and blanks, but also quotes and anything that can be inside a quoted string.
I would likely go with a Perl-based solution, having Perl read 'paragraphs' at a time and applying a regex to that. The downside is having to deal with the recursive search - there are modules to do that, of course, including the core module File::Find.
In outline, for a single file:
$/ = "\n\n"; # Paragraphs
while (<>)
{
if ($_ =~ m/SELECT.*customerName.*FROM/mi)
{
printf file name
go to next file
}
}
That needs to be wrapped into a sub that is then invoked by the methods of File::Find.
Android fade in and fade out with ImageView
This is probably the best solution you'll get. Simple and Easy. I learned it on udemy.
Suppose you have two images having image id's id1 and id2 respectively and currently the image view is set as id1 and you want to change it to the other image everytime someone clicks in. So this is the basic code in MainActivity.java
File
int clickNum=0;
public void click(View view){
clickNum++;
ImageView a=(ImageView)findViewById(R.id.id1);
ImageView b=(ImageView)findViewById(R.id.id2);
if(clickNum%2==1){
a.animate().alpha(0f).setDuration(2000); //alpha controls the transpiracy
}
else if(clickNum%2==0){
b.animate().alpha(0f).setDuration(2000); //alpha controls the transpiracy
}
}
I hope this will surely help
How to append multiple values to a list in Python
letter = ["a", "b", "c", "d"]
letter.extend(["e", "f", "g", "h"])
letter.extend(("e", "f", "g", "h"))
print(letter)
...
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'e', 'f', 'g', 'h']
Visual Studio displaying errors even if projects build
If you have ReSharper, try emptying the ReSharper cache:
In menu, ReSharper > Options > Environment > General > Clear Caches
and disabling and re-enabling ReSharper:
In menu, Tools > Options > ReSharper > General > Suspend / Restore
bootstrap initially collapsed element
If removing the in
class doesn't work for you, such was my case, you can force the collapsed initial state using the CSS display property:
...
<div id="collapseOne" class="accordion-body collapse" style="display: none;">
...
MySQL: Check if the user exists and drop it
In case you have a school server where the pupils worked a lot. You can just clean up the mess by:
delete from user where User != 'root' and User != 'admin';
delete from db where User != 'root' and User != 'admin';
delete from tables_priv;
delete from columns_priv;
flush privileges;
How can I use a JavaScript variable as a PHP variable?
PHP runs on the server. It outputs some text (usually). This is then parsed by the client.
During and after the parsing on the client, JavaScript runs. At this stage it is too late for the PHP script to do anything.
If you want to get anything back to PHP you need to make a new HTTP request and include the data in it (either in the query string (GET data) or message body (POST data).
You can do this by:
- Setting location (GET only)
- Submitting a form (with the
FormElement.submit()
method)
- Using the XMLHttpRequest object (the technique commonly known as Ajax). Various libraries do some of the heavy lifting for you here, e.g. YUI or jQuery.
Which ever option you choose, the PHP is essentially the same. Read from $_GET
or $_POST
, run your database code, then return some data to the client.
Can I automatically increment the file build version when using Visual Studio?
open up the AssemblyInfo.cs file and change
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
to
[assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
you can do this in IDE by going to project -> properties -> assembly information
This however will only allow you to auto increment the Assembly version and will give you the
Assembly File Version: A wildcard ("*") is not allowed in this field
message box if you try place a * in the file version field.
So just open up the assemblyinfo.cs and do it manually.
Put buttons at bottom of screen with LinearLayout?
You can do this by taking a Frame layout as parent Layout and then put linear layout inside it. Here is a example:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:textSize="16sp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:textSize="16sp"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:textSize="16sp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:textSize="16sp"/>
</LinearLayout>
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_gravity="bottom"
/>
</FrameLayout>
Failed to load resource: net::ERR_FILE_NOT_FOUND loading json.js
Same thing happened to me. Eventually my solution was to navigate to the repository using terminal (on mac) and create a new js file with a slightly different name. It linked immediately so i copied contents of original file to new one. You also might want to lose the first /
after src=
and use ""
.
TypeError: 'list' object is not callable in python
Seems like you've shadowed the builtin name list
pointing at a class by the same name pointing at its instance. Here is an example:
>>> example = list('easyhoss') # here `list` refers to the builtin class
>>> list = list('abc') # we create a variable `list` referencing an instance of `list`
>>> example = list('easyhoss') # here `list` refers to the instance
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: 'list' object is not callable
I believe this is fairly obvious. Python stores object names (functions and classes are objects, too) in namespaces (which are implemented as dictionaries), hence you can rewrite pretty much any name in any scope. It won't show up as an error of some sort. As you might know, Python emphasizes that "special cases aren't special enough to break the rules". And there are two major rules behind the problem you've faced:
Namespaces. Python supports nested namespaces. Theoretically you can endlessly nest namespaces. As I've already mentioned, namespaces are basically dictionaries of names and references to corresponding objects. Any module you create gets its own "global" namespace. In fact it's just a local namespace with respect to that particular module.
Scoping. When you reference a name, the Python runtime looks it up in the local namespace (with respect to the reference) and, if such name does not exist, it repeats the attempt in a higher-level namespace. This process continues until there are no higher namespaces left. In that case you get a NameError
. Builtin functions and classes reside in a special high-order namespace __builtins__
. If you declare a variable named list
in your module's global namespace, the interpreter will never search for that name in a higher-level namespace (that is __builtins__
). Similarly, suppose you create a variable var
inside a function in your module, and another variable var
in the module. Then, if you reference var
inside the function, you will never get the global var
, because there is a var
in the local namespace - the interpreter has no need to search it elsewhere.
Here is a simple illustration.
>>> example = list("abc") # Works fine
>>>
>>> # Creating name "list" in the global namespace of the module
>>> list = list("abc")
>>>
>>> example = list("abc")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
>>> # Python looks for "list" and finds it in the global namespace,
>>> # but it's not the proper "list".
>>>
>>> # Let's remove "list" from the global namespace
>>> del list
>>> # Since there is no "list" in the global namespace of the module,
>>> # Python goes to a higher-level namespace to find the name.
>>> example = list("abc") # It works.
So, as you see there is nothing special about Python builtins. And your case is a mere example of universal rules. You'd better use an IDE (e.g. a free version of PyCharm, or Atom with Python plugins) that highlights name shadowing to avoid such errors.
You might as well be wondering what is a "callable", in which case you can read this post. list
, being a class, is callable. Calling a class triggers instance construction and initialisation. An instance might as well be callable, but list
instances are not. If you are even more puzzled by the distinction between classes and instances, then you might want to read the documentation (quite conveniently, the same page covers namespaces and scoping).
If you want to know more about builtins, please read the answer by Christian Dean.
P.S. When you start an interactive Python session, you create a temporary module.
Databound drop down list - initial value
To select a value from the dropdown use the index like this:
if we have the
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true"></asp:DropDownList>
you would use :
DropDownList1.Items[DropDownList1.SelectedIndex].Value
this would return the value for the selected index.
How do I combine two lists into a dictionary in Python?
dict(zip([1,2,3,4], [a,b,c,d]))
If the lists are big you should use itertools.izip
.
If you have more keys than values, and you want to fill in values for the extra keys, you can use itertools.izip_longest
.
Here, a
, b
, c
, and d
are variables -- it will work fine (so long as they are defined), but you probably meant ['a','b','c','d']
if you want them as strings.
zip
takes the first item from each iterable and makes a tuple, then the second item from each, etc. etc.
dict
can take an iterable of iterables, where each inner iterable has two items -- it then uses the first as the key and the second as the value for each item.
How to drop a PostgreSQL database if there are active connections to it?
PostgreSQL 13 introduced FORCE
option.
DROP DATABASE
DROP DATABASE drops a database ... Also, if anyone else is connected to the target database, this command will fail unless you use the FORCE option described below.
FORCE
Attempt to terminate all existing connections to the target database. It doesn't terminate if prepared transactions, active logical replication slots or subscriptions are present in the target database.
DROP DATABASE db_name WITH (FORCE);
How to create roles in ASP.NET Core and assign them to users?
I use this (DI):
public class IdentitySeed
{
private readonly ApplicationDbContext _context;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<ApplicationRole> _rolesManager;
private readonly ILogger _logger;
public IdentitySeed(
ApplicationDbContext context,
UserManager<ApplicationUser> userManager,
RoleManager<ApplicationRole> roleManager,
ILoggerFactory loggerFactory) {
_context = context;
_userManager = userManager;
_rolesManager = roleManager;
_logger = loggerFactory.CreateLogger<IdentitySeed>();
}
public async Task CreateRoles() {
if (await _context.Roles.AnyAsync()) {// not waste time
_logger.LogInformation("Exists Roles.");
return;
}
var adminRole = "Admin";
var roleNames = new String[] { adminRole, "Manager", "Crew", "Guest", "Designer" };
foreach (var roleName in roleNames) {
var role = await _rolesManager.RoleExistsAsync(roleName);
if (!role) {
var result = await _rolesManager.CreateAsync(new ApplicationRole { Name = roleName });
//
_logger.LogInformation("Create {0}: {1}", roleName, result.Succeeded);
}
}
// administrator
var user = new ApplicationUser {
UserName = "Administrator",
Email = "[email protected]",
EmailConfirmed = true
};
var i = await _userManager.FindByEmailAsync(user.Email);
if (i == null) {
var adminUser = await _userManager.CreateAsync(user, "Something*");
if (adminUser.Succeeded) {
await _userManager.AddToRoleAsync(user, adminRole);
//
_logger.LogInformation("Create {0}", user.UserName);
}
}
}
//! By: Luis Harvey Triana Vega
}
Insert into C# with SQLCommand
Use AddWithValue()
, but be aware of the possibility of the wrong implicit type conversion
.
like this:
cmd.Parameters.AddWithValue("@param1", klantId);
cmd.Parameters.AddWithValue("@param2", klantNaam);
cmd.Parameters.AddWithValue("@param3", klantVoornaam);
JVM option -Xss - What does it do exactly?
Each thread has a stack which used for local variables and internal values. The stack size limits how deep your calls can be. Generally this is not something you need to change.
SQL update query using joins
It is very simple to update using join query in SQL .You can do it without using FROM
clause. Here is an example :
UPDATE customer_table c
JOIN
employee_table e
ON c.city_id = e.city_id
JOIN
anyother_ table a
ON a.someID = e.someID
SET c.active = "Yes"
WHERE c.city = "New york";
How to force remounting on React components?
Use setState
in your view to change employed
property of state. This is example of React render engine.
someFunctionWhichChangeParamEmployed(isEmployed) {
this.setState({
employed: isEmployed
});
}
getInitialState() {
return {
employed: true
}
},
render(){
if (this.state.employed) {
return (
<div>
<MyInput ref="job-title" name="job-title" />
</div>
);
} else {
return (
<div>
<span>Diff me!</span>
<MyInput ref="unemployment-reason" name="unemployment-reason" />
<MyInput ref="unemployment-duration" name="unemployment-duration" />
</div>
);
}
}
Update a dataframe in pandas while iterating row by row
You can assign values in the loop using df.set_value:
for i, row in df.iterrows():
ifor_val = something
if <condition>:
ifor_val = something_else
df.set_value(i,'ifor',ifor_val)
If you don't need the row values you could simply iterate over the indices of df, but I kept the original for-loop in case you need the row value for something not shown here.
update
df.set_value() has been deprecated since version 0.21.0
you can use df.at() instead:
for i, row in df.iterrows():
ifor_val = something
if <condition>:
ifor_val = something_else
df.at[i,'ifor'] = ifor_val
"405 method not allowed" in IIS7.5 for "PUT" method
I was using Angular 8 and was .NET core API.
I add the following in my service web.config file. That resolve my error.
<system.webServer>
<modules runAllManagedModulesForAllRequests="false">
<remove name="WebDAVModule" />
</modules>
</system.webServer>
What is an unsigned char?
An unsigned char
is an unsigned byte value (0 to 255). You may be thinking of char
in terms of being a "character" but it is really a numerical value. The regular char
is signed, so you have 128 values, and these values map to characters using ASCII encoding. But in either case, what you are storing in memory is a byte value.
How to print a linebreak in a python function?
>>> A = ['a1', 'a2', 'a3']
>>> B = ['b1', 'b2', 'b3']
>>> for x in A:
for i in B:
print ">" + x + "\n" + i
Outputs:
>a1
b1
>a1
b2
>a1
b3
>a2
b1
>a2
b2
>a2
b3
>a3
b1
>a3
b2
>a3
b3
Notice that you are using /n
which is not correct!
What are the rules for calling the superclass constructor?
If you have default parameters in your base constructor the base class will be called automatically.
using namespace std;
class Base
{
public:
Base(int a=1) : _a(a) {}
protected:
int _a;
};
class Derived : public Base
{
public:
Derived() {}
void printit() { cout << _a << endl; }
};
int main()
{
Derived d;
d.printit();
return 0;
}
Output is: 1
How to execute raw queries with Laravel 5.1?
I found the solution in this topic and I code this:
$cards = DB::select("SELECT
cards.id_card,
cards.hash_card,
cards.`table`,
users.name,
0 as total,
cards.card_status,
cards.created_at as last_update
FROM cards
LEFT JOIN users
ON users.id_user = cards.id_user
WHERE hash_card NOT IN ( SELECT orders.hash_card FROM orders )
UNION
SELECT
cards.id_card,
orders.hash_card,
cards.`table`,
users.name,
sum(orders.quantity*orders.product_price) as total,
cards.card_status,
max(orders.created_at) last_update
FROM menu.orders
LEFT JOIN cards
ON cards.hash_card = orders.hash_card
LEFT JOIN users
ON users.id_user = cards.id_user
GROUP BY hash_card
ORDER BY id_card ASC");
How do you automatically set text box to Uppercase?
try
<input type="text" class="normal"
style="text-transform:uppercase"
name="Name" size="20" maxlength="20">
<img src="../images/tickmark.gif" border="0"/>
Instead of image put style tag on input because you are writing on input not on image
jQuery get mouse position within an element
One way is to use the jQuery offset
method to translate the event.pageX
and event.pageY
coordinates from the event into a mouse position relative to the parent. Here's an example for future reference:
$("#something").click(function(e){
var parentOffset = $(this).parent().offset();
//or $(this).offset(); if you really just want the current element's offset
var relX = e.pageX - parentOffset.left;
var relY = e.pageY - parentOffset.top;
});
Why doesn't Mockito mock static methods?
Mockito [3.4.0] can mock static methods!
Replace mockito-core
dependency with mockito-inline:3.4.0
.
Class with static method:
class Buddy {
static String name() {
return "John";
}
}
Use new method Mockito.mockStatic()
:
@Test
void lookMomICanMockStaticMethods() {
assertThat(Buddy.name()).isEqualTo("John");
try (MockedStatic<Buddy> theMock = Mockito.mockStatic(Buddy.class)) {
theMock.when(Buddy::name).thenReturn("Rafael");
assertThat(Buddy.name()).isEqualTo("Rafael");
}
assertThat(Buddy.name()).isEqualTo("John");
}
Mockito replaces the static method within the try
block only.
How to show imageView full screen on imageView click?
Use this property for an Image view such as,
1) android:scaleType="fitXY"
- It means the Images will be stretched to fit all the sides of the parent that is based on your ImageView
!
2) By using above property, it will affect your Image resolution so if you want to maintain the resolution then add a property such as android:scaleType="centerInside"
.
How to split a string in Java
An alternative to processing the string directly would be to use a regular expression with capturing groups. This has the advantage that it makes it straightforward to imply more sophisticated constraints on the input. For example, the following splits the string into two parts, and ensures that both consist only of digits:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
class SplitExample
{
private static Pattern twopart = Pattern.compile("(\\d+)-(\\d+)");
public static void checkString(String s)
{
Matcher m = twopart.matcher(s);
if (m.matches()) {
System.out.println(s + " matches; first part is " + m.group(1) +
", second part is " + m.group(2) + ".");
} else {
System.out.println(s + " does not match.");
}
}
public static void main(String[] args) {
checkString("123-4567");
checkString("foo-bar");
checkString("123-");
checkString("-4567");
checkString("123-4567-890");
}
}
As the pattern is fixed in this instance, it can be compiled in advance and stored as a static member (initialised at class load time in the example). The regular expression is:
(\d+)-(\d+)
The parentheses denote the capturing groups; the string that matched that part of the regexp can be accessed by the Match.group() method, as shown. The \d matches and single decimal digit, and the + means "match one or more of the previous expression). The - has no special meaning, so just matches that character in the input. Note that you need to double-escape the backslashes when writing this as a Java string. Some other examples:
([A-Z]+)-([A-Z]+) // Each part consists of only capital letters
([^-]+)-([^-]+) // Each part consists of characters other than -
([A-Z]{2})-(\d+) // The first part is exactly two capital letters,
// the second consists of digits
Difference between size and length methods?
size()
is a method specified in java.util.Collection
, which is then inherited by every data structure in the standard library. length
is a field on any array (arrays are objects, you just don't see the class normally), and length()
is a method on java.lang.String
, which is just a thin wrapper on a char[]
anyway.
Perhaps by design, Strings are immutable, and all of the top-level Collection subclasses are mutable. So where you see "length" you know that's constant, and where you see "size" it isn't.
jQuery Mobile Page refresh mechanism
I posted that in jQuery forums (I hope it can help):
Diving into the jQM code i've found this solution. I hope it can help other people:
To refresh a dynamically modified page:
function refreshPage(page){
// Page refresh
page.trigger('pagecreate');
page.listview('refresh');
}
It works even if you create new headers, navbars or footers. I've tested it with jQM 1.0.1.
Oracle get previous day records
this
SELECT field,datetime_field
FROM database
WHERE datetime_field > (sysdate-1)
will work. The question is: is the 'datetime_field' has the same format as sysdate ?
My way to handle that: use 'to_char()' function (only works in Oracle).
samples:
previous day:
select your_column
from your_table
where to_char(sysdate-1, 'dd.mm.yyyy')
or
select extract(day from date_field)||'/'||
extract(month from date_field)||'/'||
extract(year from date_field)||'/'||
as mydate
from dual(or a_table)
where extract(day from date_field) = an_int_number and
extract(month from date_field) = an_int_number and so on..
comparing date:
select your_column
from your_table
where
to_char(a_datetime_column, 'dd.mm.yyyy') > or < or >= or <= to_char(sysdate, 'dd.mm.yyyy')
time range between yesterday and a day before yesterday:
select your_column
from your_table
where
to_char(a_datetime_column, 'dd.mm.yyyy') > or < or >= or <= to_char(sysdate-1, 'dd.mm.yyyy') and
to_char(a_datetime_column, 'dd.mm.yyyy') > or < or >= or <= to_char(sysdate-2, 'dd.mm.yyyy')
other time range variation
select your_column
from your_table
where
to_char(a_datetime_column, 'dd.mm.yyyy') is between to_char(sysdate-1, 'dd.mm.yyyy')
and to_char(sysdate-2, 'dd.mm.yyyy')
Delete from two tables in one query
there's another way which is not mentioned here (I didn't fully test it's performance yet), you could set array for all tables -> rows you want to delete as below
// set your tables array
$array = ['table1', 'table2', 'table3'];
// loop through each table
for($i = 0; $i < count($array); $i++){
// get each single array
$single_array = $array[$i];
// build your query
$query = "DELETE FROM $single_array WHERE id = 'id'";
// prepare the query and get the connection
$data = con::GetCon()->prepare($query);
// execute the action
$data->execute();
}
then you could redirect the user to the home page.
header('LOCATION:' . $home_page);
hope this will help someone :)
Thanks
Use JAXB to create Object from XML String
If you already have the xml, and comes more than one attribute, you can handle it as follows:
String output = "<ciudads><ciudad><idCiudad>1</idCiudad>
<nomCiudad>BOGOTA</nomCiudad></ciudad><ciudad><idCiudad>6</idCiudad>
<nomCiudad>Pereira</nomCiudad></ciudads>";
DocumentBuilder db = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(output));
Document doc = db.parse(is);
NodeList nodes = ((org.w3c.dom.Document) doc)
.getElementsByTagName("ciudad");
for (int i = 0; i < nodes.getLength(); i++) {
Ciudad ciudad = new Ciudad();
Element element = (Element) nodes.item(i);
NodeList name = element.getElementsByTagName("idCiudad");
Element element2 = (Element) name.item(0);
ciudad.setIdCiudad(Integer
.valueOf(getCharacterDataFromElement(element2)));
NodeList title = element.getElementsByTagName("nomCiudad");
element2 = (Element) title.item(0);
ciudad.setNombre(getCharacterDataFromElement(element2));
ciudades.getPartnerAccount().add(ciudad);
}
}
for (Ciudad ciudad1 : ciudades.getPartnerAccount()) {
System.out.println(ciudad1.getIdCiudad());
System.out.println(ciudad1.getNombre());
}
the method getCharacterDataFromElement is
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
Datetime in C# add days
Its because the AddDays()
method returns a new DateTime
, that you are not assigning or using anywhere.
Example of use:
DateTime newDate = endDate.AddDays(2);
Laravel Mail::send() sending to multiple to or bcc addresses
the accepted answer does not work any longer with laravel 5.3 because mailable tries to access ->email
and results in
ErrorException in Mailable.php line 376: Trying to get property of
non-object
a working code for laravel 5.3 is this:
$users_temp = explode(',', '[email protected],[email protected]');
$users = [];
foreach($users_temp as $key => $ut){
$ua = [];
$ua['email'] = $ut;
$ua['name'] = 'test';
$users[$key] = (object)$ua;
}
Mail::to($users)->send(new OrderAdminSendInvoice($o));
How to execute the start script with Nodemon
To avoid a global install, add Nodemon as a dependency, then...
package.json
"scripts": {
"start": "node ./bin/www",
"start-dev": "./node_modules/nodemon/bin/nodemon.js ./bin/www"
},
Load CSV file with Spark
When using spark.read.csv
, I find that using the options escape='"'
and multiLine=True
provide the most consistent solution to the CSV standard, and in my experience works the best with CSV files exported from Google Sheets.
That is,
#set inferSchema=False to read everything as string
df = spark.read.csv("myData.csv", escape='"', multiLine=True,
inferSchema=False, header=True)
Basic HTTP and Bearer Token Authentication
There is another solution for testing APIs on development server.
- Set
HTTP Basic Authentication
only for web routes
- Leave all API routes free from authentication
Web server configuration for nginx
and Laravel
would be like this:
location /api {
try_files $uri $uri/ /index.php?$query_string;
}
location / {
try_files $uri $uri/ /index.php?$query_string;
auth_basic "Enter password";
auth_basic_user_file /path/to/.htpasswd;
}
Authorization: Bearer
will do the job of defending the development server against web crawlers and other unwanted visitors.
@Media min-width & max-width
The underlying issue is using max-device-width
vs plain old max-width
.
Using the "device" keyword targets physical dimension of the screen, not the width of the browser window.
For example:
@media only screen and (max-device-width: 480px) {
/* STYLES HERE for DEVICES with physical max-screen width of 480px */
}
Versus
@media only screen and (max-width: 480px) {
/* STYLES HERE for BROWSER WINDOWS with a max-width of 480px.
This will work on desktops when the window is narrowed. */
}
How can I temporarily disable a foreign key constraint in MySQL?
It's not a good idea to set a foreign key constraint to 0, because if you do, your database would not ensure it is not violating referential integrity. This could lead to inaccurate, misleading, or incomplete data.
You make a foreign key for a reason: because all the values in the child column shall be the same as a value in the parent column. If there are no foreign key constraints, a child row can have a value that is not in the parent row, which would lead to inaccurate data.
For instance, let's say you have a website for students to login and every student must register for an account as a user. You have one table for user ids, with user id as a primary key; and another table for student accounts, with student id as a column. Since every student must have a user id, it would make sense to make the student id from the student accounts table a foreign key that references the primary key user id in the user ids table. If there are no foreign key checks, a student could end up having a student id and no user id, which means a student can get an account without being a user, which is wrong.
Imagine if it happens to a large amount of data. That's why you need the foreign key check.
It's best to figure out what is causing the error. Most likely, you are trying to delete from a parent row without deleting from a child row. Try deleting from the child row before deleting from the parent row.
How do I find out what keystore my JVM is using?
This works for me:
#! /bin/bash
CACERTS=$(readlink -e $(dirname $(readlink -e $(which keytool)))/../lib/security/cacerts)
if keytool -list -keystore $CACERTS -storepass changeit > /dev/null ; then
echo $CACERTS
else
echo 'Can not find cacerts file.' >&2
exit 1
fi
Only for Linux. My Solaris has no readlink. In the end I used this Perl-Script:
#! /usr/bin/env perl
use strict;
use warnings;
use Cwd qw(realpath);
$_ = realpath((grep {-x && -f} map {"$_/keytool"} split(':', $ENV{PATH}))[0]);
die "Can not find keytool" unless defined $_;
my $keytool = $_;
print "Using '$keytool'.\n";
s/keytool$//;
$_ = realpath($_ . '../lib/security/cacerts');
die "Can not find cacerts" unless -f $_;
my $cacerts = $_;
print "Importing into '$cacerts'.\n";
`$keytool -list -keystore "$cacerts" -storepass changeit`;
die "Can not read key container" unless $? == 0;
exit if $ARGV[0] eq '-d';
foreach (@ARGV) {
my $cert = $_;
s/\.[^.]+$//;
my $alias = $_;
print "Importing '$cert' as '$alias'.\n";
`keytool -importcert -file "$cert" -alias "$alias" -keystore "$cacerts" -storepass changeit`;
warn "Can not import certificate: $?" unless $? == 0;
}
How to force deletion of a python object?
Perhaps you are looking for a context manager?
>>> class Foo(object):
... def __init__(self):
... self.bar = None
... def __enter__(self):
... if self.bar != 'open':
... print 'opening the bar'
... self.bar = 'open'
... def __exit__(self, type_, value, traceback):
... if self.bar != 'closed':
... print 'closing the bar', type_, value, traceback
... self.bar = 'close'
...
>>>
>>> with Foo() as f:
... # oh no something crashes the program
... sys.exit(0)
...
opening the bar
closing the bar <type 'exceptions.SystemExit'> 0 <traceback object at 0xb7720cfc>
How can an html element fill out 100% of the remaining screen height, using css only?
The trick to this is specifying 100% height on the html and body elements.
Some browsers look to the parent elements (html, body) to calculate the height.
<html>
<body>
<div id="Header">
</div>
<div id="Content">
</div>
</body>
</html>
html, body
{
height: 100%;
}
#Header
{
width: 960px;
height: 150px;
}
#Content
{
height: 100%;
width: 960px;
}
How do I make the return type of a method generic?
There are many ways of doing this(listed by priority, specific to the OP's problem)
Option 1: Straight approach - Create multiple functions for each type you expect rather than having one generic function.
public static bool ConfigSettingInt(string settingName)
{
return Convert.ToBoolean(ConfigurationManager.AppSettings[settingName]);
}
Option 2: When you don't want to use fancy methods of conversion - Cast the value to object and then to generic type.
public static T ConfigSetting<T>(string settingName)
{
return (T)(object)ConfigurationManager.AppSettings[settingName];
}
Note - This will throw an error if the cast is not valid(your case). I would not recommend doing this if you are not sure about the type casting, rather go for option 3.
Option 3: Generic with type safety - Create a generic function to handle type conversion.
public static T ConvertValue<T,U>(U value) where U : IConvertible
{
return (T)Convert.ChangeType(value, typeof(T));
}
Note - T is the expected type, note the where constraint here(type of U must be IConvertible to save us from the errors)
How do I print colored output with Python 3?
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def colour_print(text,colour):
if colour == 'OKBLUE':
string = bcolors.OKBLUE + text + bcolors.ENDC
print(string)
elif colour == 'HEADER':
string = bcolors.HEADER + text + bcolors.ENDC
print(string)
elif colour == 'OKCYAN':
string = bcolors.OKCYAN + text + bcolors.ENDC
print(string)
elif colour == 'OKGREEN':
string = bcolors.OKGREEN + text + bcolors.ENDC
print(string)
elif colour == 'WARNING':
string = bcolors.WARNING + text + bcolors.ENDC
print(string)
elif colour == 'FAIL':
string = bcolors.HEADER + text + bcolors.ENDC
print(string)
elif colour == 'BOLD':
string = bcolors.BOLD + text + bcolors.ENDC
print(string)
elif colour == 'UNDERLINE':
string = bcolors.UNDERLINE + text + bcolors.ENDC
print(string)
just copy the above code.
just call them easily
colour_print('Hello world','OKBLUE')
colour_print('easy one','OKCYAN')
colour_print('copy and paste','OKGREEN')
colour_print('done','OKBLUE')
Hope it would help
Solving "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection" InvalidOperationException
In my case, I was passsing all models 'Users' to column and it wasn't mapped correctly, so I just passed 'Users.Name' and it fixed it.
var data = db.ApplicationTranceLogs
.Include(q=>q.Users)
.Include(q => q.LookupItems)
.Select(q => new { Id = q.Id, FormatDate = q.Date.ToString("yyyy/MM/dd"), ***Users = q.Users,*** ProcessType = q.ProcessType, CoreProcessId = q.CoreProcessId, Data = q.Data })
.ToList();
var data = db.ApplicationTranceLogs
.Include(q=>q.Users).Include(q => q.LookupItems)
.Select(q => new { Id = q.Id, FormatDate = q.Date.ToString("yyyy/MM/dd"), ***Users = q.Users.Name***, ProcessType = q.ProcessType, CoreProcessId = q.CoreProcessId, Data = q.Data })
.ToList();
getting the last item in a javascript object
No. Order is not guaranteed in JSON and most other key-value data structures, so therefore the last item could sometimes be carrot
and at other times be banana
and so on. If you need to rely on ordering, your best bet is to go with arrays. The power of key-value data structures lies in accessing values by their keys
, not in being able to get the nth
item of the object.
How can I list ALL DNS records?
When you query for ANY you will get a list of all records at that level but not below.
# try this
dig google.com any
This may return A records, TXT records, NS records, MX records, etc if the domain name is exactly "google.com". However, it will not return child records (e.g., www.google.com). More precisely, you MAY get these records if they exist. The name server does not have to return these records if it chooses not to do so (for example, to reduce the size of the response).
An AXFR is a zone transfer and is likely what you want. However, these are typically restricted and not available unless you control the zone. You'll usually conduct a zone transfer directly from the authoritative server (the @ns1.google.com below) and often from a name server that may not be published (a stealth name server).
# This will return "Transfer failed"
dig @ns1.google.com google.com axfr
If you have control of the zone, you can set it up to get transfers that are protected with a TSIG key. This is a shared secret the the client can send to the server to authorize the transfer.
Convert a binary NodeJS Buffer to JavaScript ArrayBuffer
1. A Buffer
is just a view for looking into an ArrayBuffer
.
A Buffer
, in fact, is a FastBuffer
, which extends
(inherits from) Uint8Array
, which is an octet-unit view (“partial accessor”) of the actual memory, an ArrayBuffer
.
/lib/buffer.js#L65-L73
Node.js 9.4.0
class FastBuffer extends Uint8Array {
constructor(arg1, arg2, arg3) {
super(arg1, arg2, arg3);
}
}
FastBuffer.prototype.constructor = Buffer;
internalBuffer.FastBuffer = FastBuffer;
Buffer.prototype = FastBuffer.prototype;
2. The size of an ArrayBuffer
and the size of its view may vary.
Reason #1: Buffer.from(arrayBuffer[, byteOffset[, length]])
.
With Buffer.from(arrayBuffer[, byteOffset[, length]])
, you can create a Buffer
with specifying its underlying ArrayBuffer
and the view's position and size.
const test_buffer = Buffer.from(new ArrayBuffer(50), 40, 10);
console.info(test_buffer.buffer.byteLength); // 50; the size of the memory.
console.info(test_buffer.length); // 10; the size of the view.
Reason #2: FastBuffer
's memory allocation.
It allocates the memory in two different ways depending on the size.
- If the size is less than the half of the size of a memory pool and is not 0 (“small”): it makes use of a memory pool to prepare the required memory.
- Else: it creates a dedicated
ArrayBuffer
that exactly fits the required memory.
/lib/buffer.js#L306-L320
Node.js 9.4.0
function allocate(size) {
if (size <= 0) {
return new FastBuffer();
}
if (size < (Buffer.poolSize >>> 1)) {
if (size > (poolSize - poolOffset))
createPool();
var b = new FastBuffer(allocPool, poolOffset, size);
poolOffset += size;
alignPool();
return b;
} else {
return createUnsafeBuffer(size);
}
}
/lib/buffer.js#L98-L100
Node.js 9.4.0
function createUnsafeBuffer(size) {
return new FastBuffer(createUnsafeArrayBuffer(size));
}
What do you mean by a “memory pool?”
A memory pool is a fixed-size pre-allocated memory block for keeping small-size memory chunks for Buffer
s. Using it keeps the small-size memory chunks tightly together, so prevents fragmentation caused by separate management (allocation and deallocation) of small-size memory chunks.
In this case, the memory pools are ArrayBuffer
s whose size is 8 KiB by default, which is specified in Buffer.poolSize
. When it is to provide a small-size memory chunk for a Buffer
, it checks if the last memory pool has enough available memory to handle this; if so, it creates a Buffer
that “views” the given partial chunk of the memory pool, otherwise, it creates a new memory pool and so on.
You can access the underlying ArrayBuffer
of a Buffer
. The Buffer
's buffer
property (that is, inherited from Uint8Array
) holds it. A “small” Buffer
's buffer
property is an ArrayBuffer
that represents the entire memory pool. So in this case, the ArrayBuffer
and the Buffer
varies in size.
const zero_sized_buffer = Buffer.allocUnsafe(0);
const small_buffer = Buffer.from([0xC0, 0xFF, 0xEE]);
const big_buffer = Buffer.allocUnsafe(Buffer.poolSize >>> 1);
// A `Buffer`'s `length` property holds the size, in octets, of the view.
// An `ArrayBuffer`'s `byteLength` property holds the size, in octets, of its data.
console.info(zero_sized_buffer.length); /// 0; the view's size.
console.info(zero_sized_buffer.buffer.byteLength); /// 0; the memory..'s size.
console.info(Buffer.poolSize); /// 8192; a memory pool's size.
console.info(small_buffer.length); /// 3; the view's size.
console.info(small_buffer.buffer.byteLength); /// 8192; the memory pool's size.
console.info(Buffer.poolSize); /// 8192; a memory pool's size.
console.info(big_buffer.length); /// 4096; the view's size.
console.info(big_buffer.buffer.byteLength); /// 4096; the memory's size.
console.info(Buffer.poolSize); /// 8192; a memory pool's size.
3. So we need to extract the memory it “views.”
An ArrayBuffer
is fixed in size, so we need to extract it out by making a copy of the part. To do this, we use Buffer
's byteOffset
property and length
property, which are inherited from Uint8Array
, and the ArrayBuffer.prototype.slice
method, which makes a copy of a part of an ArrayBuffer
. The slice()
-ing method herein was inspired by @ZachB.
const test_buffer = Buffer.from(new ArrayBuffer(10));
const zero_sized_buffer = Buffer.allocUnsafe(0);
const small_buffer = Buffer.from([0xC0, 0xFF, 0xEE]);
const big_buffer = Buffer.allocUnsafe(Buffer.poolSize >>> 1);
function extract_arraybuffer(buf)
{
// You may use the `byteLength` property instead of the `length` one.
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
}
// A copy -
const test_arraybuffer = extract_arraybuffer(test_buffer); // of the memory.
const zero_sized_arraybuffer = extract_arraybuffer(zero_sized_buffer); // of the... void.
const small_arraybuffer = extract_arraybuffer(small_buffer); // of the part of the memory.
const big_arraybuffer = extract_arraybuffer(big_buffer); // of the memory.
console.info(test_arraybuffer.byteLength); // 10
console.info(zero_sized_arraybuffer.byteLength); // 0
console.info(small_arraybuffer.byteLength); // 3
console.info(big_arraybuffer.byteLength); // 4096
4. Performance improvement
If you're to use the results as read-only, or it is okay to modify the input Buffer
s' contents, you can avoid unnecessary memory copying.
const test_buffer = Buffer.from(new ArrayBuffer(10));
const zero_sized_buffer = Buffer.allocUnsafe(0);
const small_buffer = Buffer.from([0xC0, 0xFF, 0xEE]);
const big_buffer = Buffer.allocUnsafe(Buffer.poolSize >>> 1);
function obtain_arraybuffer(buf)
{
if(buf.length === buf.buffer.byteLength)
{
return buf.buffer;
} // else:
// You may use the `byteLength` property instead of the `length` one.
return buf.subarray(0, buf.length);
}
// Its underlying `ArrayBuffer`.
const test_arraybuffer = obtain_arraybuffer(test_buffer);
// Just a zero-sized `ArrayBuffer`.
const zero_sized_arraybuffer = obtain_arraybuffer(zero_sized_buffer);
// A copy of the part of the memory.
const small_arraybuffer = obtain_arraybuffer(small_buffer);
// Its underlying `ArrayBuffer`.
const big_arraybuffer = obtain_arraybuffer(big_buffer);
console.info(test_arraybuffer.byteLength); // 10
console.info(zero_sized_arraybuffer.byteLength); // 0
console.info(small_arraybuffer.byteLength); // 3
console.info(big_arraybuffer.byteLength); // 4096
No notification sound when sending notification from firebase in android
try this....
public void buildPushNotification(Context ctx, String content, int icon, CharSequence text, boolean silent) {
Intent intent = new Intent(ctx, Activity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 1410, intent, PendingIntent.FLAG_ONE_SHOT);
Bitmap bm = BitmapFactory.decodeResource(ctx.getResources(), //large drawable);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(ctx)
.setSmallIcon(icon)
.setLargeIcon(bm)
.setContentTitle(content)
.setContentText(text)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
if(!silent)
notificationBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1410, notificationBuilder.build());
}
and in onMessageReceived, call it
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d("Msg", "Message received [" + remoteMessage.getNotification().getBody() + "]");
buildPushNotification(/*your param*/);
}
or follow KongJing, Is also correct as he says, but you can use a Firebase Console.
How do I request a file but not save it with Wget?
You can use -O-
(uppercase o) to redirect content to the stdout (standard output) or to a file (even special files like /dev/null
/dev/stderr
/dev/stdout
)
wget -O- http://yourdomain.com
Or:
wget -O- http://yourdomain.com > /dev/null
Or: (same result as last command)
wget -O/dev/null http://yourdomain.com
How to display HTML <FORM> as inline element?
<form>
cannot go inside <p>
, no. The browser is going to abruptly close your <p>
element when it hits the opening <form>
tag as it tries to handle what it thinks is an unclosed paragraph element:
<p>Read this sentence
</p><form style='display:inline;'>
Renaming column names of a DataFrame in Spark Scala
Sometime we have the column name is below format in SQLServer or MySQL table
Ex : Account Number,customer number
But Hive tables do not support column name containing spaces, so please use below solution to rename your old column names.
Solution:
val renamedColumns = df.columns.map(c => df(c).as(c.replaceAll(" ", "_").toLowerCase()))
df = df.select(renamedColumns: _*)
How to scale images to screen size in Pygame
You can scale the image with pygame.transform.scale
:
import pygame
picture = pygame.image.load(filename)
picture = pygame.transform.scale(picture, (1280, 720))
You can then get the bounding rectangle of picture
with
rect = picture.get_rect()
and move the picture with
rect = rect.move((x, y))
screen.blit(picture, rect)
where screen
was set with something like
screen = pygame.display.set_mode((1600, 900))
To allow your widgets to adjust to various screen sizes,
you could make the display
resizable:
import os
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((500, 500), HWSURFACE | DOUBLEBUF | RESIZABLE)
pic = pygame.image.load("image.png")
screen.blit(pygame.transform.scale(pic, (500, 500)), (0, 0))
pygame.display.flip()
while True:
pygame.event.pump()
event = pygame.event.wait()
if event.type == QUIT:
pygame.display.quit()
elif event.type == VIDEORESIZE:
screen = pygame.display.set_mode(
event.dict['size'], HWSURFACE | DOUBLEBUF | RESIZABLE)
screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0))
pygame.display.flip()
Operator overloading in Java
No, Java doesn't support user-defined operator overloading. The only aspect of Java which comes close to "custom" operator overloading is the handling of + for strings, which either results in compile-time concatenation of constants or execution-time concatenation using StringBuilder/StringBuffer. You can't define your own operators which act in the same way though.
For a Java-like (and JVM-based) language which does support operator overloading, you could look at Kotlin or Groovy. Alternatively, you might find luck with a Java compiler plugin solution.
How to start mongodb shell?
bat command to start mongodb
create one folder for database like in this example r0
start /d "{path}\bin" mongod.exe --replSet foo --port 27017 --dbpath {path}mongoDataBase\r0
start /d "{path}\bin" mongo.exe 127.0.0.1:27017
Getting DOM node from React child element
this.props.children
should either be a ReactElement or an array of ReactElement, but not components.
To get the DOM nodes of the children elements, you need to clone them and assign them a new ref.
render() {
return (
<div>
{React.Children.map(this.props.children, (element, idx) => {
return React.cloneElement(element, { ref: idx });
})}
</div>
);
}
You can then access the child components via this.refs[childIdx]
, and retrieve their DOM nodes via ReactDOM.findDOMNode(this.refs[childIdx])
.
Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"
I suspect the problem is the slashes in the format string versus the ones in the data. That's a culture-sensitive date separator character in the format string, and the final argument being null
means "use the current culture". If you either escape the slashes ("M'/'d'/'yyyy") or you specify CultureInfo.InvariantCulture
, it will be okay.
If anyone's interested in reproducing this:
// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M'/'d'/'yyyy",
new CultureInfo("de-DE"));
// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy",
new CultureInfo("en-US"));
// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy",
CultureInfo.InvariantCulture);
// Fails
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy",
new CultureInfo("de-DE"));
Asp Net Web API 2.1 get client IP address
It's better to cast it to HttpContextBase
, this way you can mock and test it more easily
public string GetUserIp(HttpRequestMessage request)
{
if (request.Properties.ContainsKey("MS_HttpContext"))
{
var ctx = request.Properties["MS_HttpContext"] as HttpContextBase;
if (ctx != null)
{
return ctx.Request.UserHostAddress;
}
}
return null;
}
VBA using ubound on a multidimensional array
Looping D3 ways;
Sub SearchArray()
Dim arr(3, 2) As Variant
arr(0, 0) = "A"
arr(0, 1) = "1"
arr(0, 2) = "w"
arr(1, 0) = "B"
arr(1, 1) = "2"
arr(1, 2) = "x"
arr(2, 0) = "C"
arr(2, 1) = "3"
arr(2, 2) = "y"
arr(3, 0) = "D"
arr(3, 1) = "4"
arr(3, 2) = "z"
Debug.Print "Loop Dimension 1"
For i = 0 To UBound(arr, 1)
Debug.Print "arr(" & i & ", 0) is " & arr(i, 0)
Next i
Debug.Print ""
Debug.Print "Loop Dimension 2"
For j = 0 To UBound(arr, 2)
Debug.Print "arr(0, " & j & ") is " & arr(0, j)
Next j
Debug.Print ""
Debug.Print "Loop Dimension 1 and 2"
For i = 0 To UBound(arr, 1)
For j = 0 To UBound(arr, 2)
Debug.Print "arr(" & i & ", " & j & ") is " & arr(i, j)
Next j
Next i
Debug.Print ""
End Sub
PostgreSQL delete with inner join
This worked for me:
DELETE from m_productprice
WHERE m_pricelist_version_id='1000020'
AND m_product_id IN (SELECT m_product_id
FROM m_product
WHERE upc = '7094');
Create numpy matrix filled with NaNs
You rarely need loops for vector operations in numpy.
You can create an uninitialized array and assign to all entries at once:
>>> a = numpy.empty((3,3,))
>>> a[:] = numpy.nan
>>> a
array([[ NaN, NaN, NaN],
[ NaN, NaN, NaN],
[ NaN, NaN, NaN]])
I have timed the alternatives a[:] = numpy.nan
here and a.fill(numpy.nan)
as posted by Blaenk:
$ python -mtimeit "import numpy as np; a = np.empty((100,100));" "a.fill(np.nan)"
10000 loops, best of 3: 54.3 usec per loop
$ python -mtimeit "import numpy as np; a = np.empty((100,100));" "a[:] = np.nan"
10000 loops, best of 3: 88.8 usec per loop
The timings show a preference for ndarray.fill(..)
as the faster alternative. OTOH, I like numpy's convenience implementation where you can assign values to whole slices at the time, the code's intention is very clear.
Note that ndarray.fill
performs its operation in-place, so numpy.empty((3,3,)).fill(numpy.nan)
will instead return None
.
Int division: Why is the result of 1/3 == 0?
The conversion in JAVA is quite simple but need some understanding. As explain in the JLS for integer operations:
If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.5) to type long by numeric promotion (§5.6).
And an example is always the best way to translate the JLS ;)
int + long -> long
int(1) + long(2) + int(3) -> long(1+2) + long(3)
Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion.
short + int -> int + int -> int
A small example using Eclipse to show that even an addition of two short
s will not be that easy :
short s = 1;
s = s + s; <- Compiling error
//possible loss of precision
// required: short
// found: int
This will required a casting with a possible loss of precision.
The same is true for the floating point operators
If at least one of the operands to a numerical operator is of type double, then the operation is carried out using 64-bit floating-point arithmetic, and the result of the numerical operator is a value of type double. If the other operand is not a double, it is first widened (§5.1.5) to type double by numeric promotion (§5.6).
So the promotion is done on the float into double.
And the mix of both integer and floating value result in floating values as said
If at least one of the operands to a binary operator is of floating-point type, then the operation is a floating-point operation, even if the other is integral.
This is true for binary operators but not for "Assignment Operators" like +=
A simple working example is enough to prove this
int i = 1;
i += 1.5f;
The reason is that there is an implicit cast done here, this will be execute like
i = (int) i + 1.5f
i = (int) 2.5f
i = 2
How do you detect where two line segments intersect?
I have tried to implement the algorithm so elegantly described by Jason above; unfortunately while working though the mathematics in the debugging I found many cases for which it doesn't work.
For example consider the points A(10,10) B(20,20) C(10,1) D(1,10) gives h=.5 and yet it is clear by examination that these segments are no-where near each other.
Graphing this makes it clear that 0 < h < 1 criteria only indicates that the intercept point would lie on CD if it existed but tells one nothing of whether that point lies on AB.
To ensure that there is a cross point you must do the symmetrical calculation for the variable g and the requirement for interception is:
0 < g < 1 AND 0 < h < 1
How to replace case-insensitive literal substrings in Java
Just make it simple without third party libraries:
final String source = "FooBar";
final String target = "Foo";
final String replacement = "";
final String result = Pattern.compile(target, Pattern.LITERAL | Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE).matcher(source)
.replaceAll(Matcher.quoteReplacement(replacement));
How do you make an anchor link non-clickable or disabled?
Jason MacDonald comments worked for me, tested in Chrome, Mozila and IE.
Added gray color to show disable effect.
.disable_a_href{
pointer-events: none;
**color:#c0c0c0 !important;**
}
Jquery was selecting only first element in the anchor list, added meta character (*) to select and disable all element with id #ThisLink
.
$("#ThisLink*").addClass("disable_a_href");
how to zip a folder itself using java
Try this:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Zip {
public static void main(String[] a) throws Exception {
zipFolder("D:\\reports\\january", "D:\\reports\\january.zip");
}
static public void zipFolder(String srcFolder, String destZipFile) throws Exception {
ZipOutputStream zip = null;
FileOutputStream fileWriter = null;
fileWriter = new FileOutputStream(destZipFile);
zip = new ZipOutputStream(fileWriter);
addFolderToZip("", srcFolder, zip);
zip.flush();
zip.close();
}
static private void addFileToZip(String path, String srcFile, ZipOutputStream zip)
throws Exception {
File folder = new File(srcFile);
if (folder.isDirectory()) {
addFolderToZip(path, srcFile, zip);
} else {
byte[] buf = new byte[1024];
int len;
FileInputStream in = new FileInputStream(srcFile);
zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len);
}
}
}
static private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip)
throws Exception {
File folder = new File(srcFolder);
for (String fileName : folder.list()) {
if (path.equals("")) {
addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip);
} else {
addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip);
}
}
}
}
Nginx location priority
Locations are evaluated in this order:
location = /path/file.ext {}
Exact match
location ^~ /path/ {}
Priority prefix match -> longest first
location ~ /Paths?/ {}
(case-sensitive regexp) and location ~* /paths?/ {}
(case-insensitive regexp) -> first match
location /path/ {}
Prefix match -> longest first
The priority prefix match (number 2) is exactly as the common prefix match (number 4), but has priority over any regexp.
For both prefix matche types the longest match wins.
Case-sensitive and case-insensitive have the same priority. Evaluation stops at the first matching rule.
Documentation says that all prefix rules are evaluated before any regexp, but if one regexp matches then no standard prefix rule is used. That's a little bit confusing and does not change anything for the priority order reported above.
jquery/javascript convert date string to date
If you're running with jQuery you can use the datepicker UI library's parseDate function to convert your string to a date:
var d = $.datepicker.parseDate("DD, MM dd, yy", "Sunday, February 28, 2010");
and then follow it up with the formatDate method to get it to the string format you want
var datestrInNewFormat = $.datepicker.formatDate( "mm/dd/yy", d);
If you're not running with jQuery of course its probably not the best plan given you'd need jQuery core as well as the datepicker UI module... best to go with the suggestion from Segfault above to use date.js.
HTH
PostgreSQL - query from bash script as database user 'postgres'
The safest way to pass commands to psql
in a script is by piping a string or passing a here-doc.
The man docs for the -c/--command
option goes into more detail when it should be avoided.
-c command
--command=command
Specifies that psql is to execute one command string, command, and then exit. This is useful in shell scripts. Start-up files (psqlrc and ~/.psqlrc)
are ignored with this option.
command must be either a command string that is completely parsable by the server (i.e., it contains no psql-specific features), or a single
backslash command. Thus you cannot mix SQL and psql meta-commands with this option. To achieve that, you could pipe the string into psql, for
example: echo '\x \\ SELECT * FROM foo;' | psql. (\\ is the separator meta-command.)
If the command string contains multiple SQL commands, they are processed in a single transaction, unless there are explicit BEGIN/COMMIT commands
included in the string to divide it into multiple transactions. This is different from the behavior when the same string is fed to psql's standard
input. Also, only the result of the last SQL command is returned.
Because of these legacy behaviors, putting more than one command in the -c string often has unexpected results. It's better to feed multiple
commands to psql's standard input, either using echo as illustrated above, or via a shell here-document, for example:
psql <<EOF
\x
SELECT * FROM foo;
EOF
Setting up JUnit with IntelliJ IDEA
I needed to enable the JUnit plugin, after I linked my project with the jar files.
To enable the JUnit plugin, go to File->Settings, type "JUnit" in the search bar, and under "Plugins," check "JUnit.
vikingsteve's advice above will probably get the libraries linked right. Otherwise, open File->Project Structure, go to Libraries, hit the plus, and then browse to
C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 14.1.1\lib\
and add these jar files:
hamcrest-core-1.3.jar
junit-4.11.jar
junit.jar
TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable
In your example code, you have your map
operator receiving two callbacks, when it should only be receiving one. You can move your error handling code to your catch callback.
checkLogin():Observable<boolean>{
return this.service.getData()
.map(response => {
this.data = response;
this.checkservice=true;
return true;
})
.catch(error => {
this.router.navigate(['newpage']);
console.log(error);
return Observable.throw(error);
})
}
You'll need to also import the catch
and throw
operators.
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
EDIT:
Note that by returning Observable.throw
in your catch handler, you won't actually capture the error - it will still surface to the console.
Include CSS and Javascript in my django template
Refer django docs on static files.
In settings.py:
import os
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__).decode('utf-8'))
MEDIA_ROOT = os.path.join(CURRENT_PATH, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = 'static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(CURRENT_PATH, 'static'),
)
Then place your js and css files static folder in your project. Not in media folder.
In views.py:
from django.shortcuts import render_to_response, RequestContext
def view_name(request):
#your stuff goes here
return render_to_response('template.html', locals(), context_instance = RequestContext(request))
In template.html:
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/style.css" />
<script type="text/javascript" src="{{ STATIC_URL }}js/jquery-1.8.3.min.js"></script>
In urls.py:
from django.conf import settings
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
)
Project file structure can be found here in imgbin.
how to change listen port from default 7001 to something different?
You can change the listen port as per your requirement.
This task can be accomplished in two diffrent ways.
By changing config.xml file
By changing in admin console
Change the listen port in config.xml as per your requirement and bounce the domain.
Admin Console
Login to AdminConsole->Server->Configuration->ListenPort (Change it)
Note:
It is a bad practice to edit config.xml and try to edit in admin console(It's a good practise as well)
Difference between DOM parentNode and parentElement
Just like with nextSibling and nextElementSibling, just remember that, properties with "element" in their name always returns Element
or null
. Properties without can return any other kind of node.
console.log(document.body.parentNode, "is body's parent node"); // returns <html>
console.log(document.body.parentElement, "is body's parent element"); // returns <html>
var html = document.body.parentElement;
console.log(html.parentNode, "is html's parent node"); // returns document
console.log(html.parentElement, "is html's parent element"); // returns null
Set default option in mat-select
HTML
<mat-form-field>
<mat-select [(ngModel)]="modeSelect" placeholder="Mode">
<mat-option *ngFor="let obj of Array" [value]="obj.value">{{obj.value}}</mat-option>
</mat-select>
Now set your default value to
modeSelect
, where you are getting the values in Array variable.
How to set layout_gravity programmatically?
Perfectly Working!!! None of the above answer works for me. In Xml file setting gravity and setting layout_gravity is different. Check out the below code
// here messageLL is the linear layout in the xml file
// Before adding any view just remove all views
messageLL.removeAllViews();
// FrameLayout is the parent for LinearLayout
FrameLayout.LayoutParams params = new
FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
params.gravity = Gravity.CENTER|Gravity.CENTER_VERTICAL;
messageLL.setLayoutParams(params);
messageText.setVisibility(View.GONE);
messageNoText.setVisibility(View.VISIBLE);
messageLL.addView(messageNoText);
Also check This,where you can find clear explanation about gravity and layout_gravity .
How to ftp with a batch file?
Here's what I use. In my case, certain ftp servers (pure-ftpd for one) will always prompt for the username even with the -i parameter, and catch the "user username" command as the interactive password. What I do it enter a few NOOP (no operation) commands until the ftp server times out, and then login:
open ftp.example.com
noop
noop
noop
noop
noop
noop
noop
noop
user username password
...
quit
How to test abstract class in Java with JUnit?
As an option, you can create abstract test class covering logic inside abstract class and extend it for each subclass test. So that in this way you can ensure this logic will be tested for each child separately.
Emulating a do-while loop in Bash
We can emulate a do-while loop in Bash with while [[condition]]; do true; done
like this:
while [[ current_time <= $cutoff ]]
check_if_file_present
#do other stuff
do true; done
For an example. Here is my implementation on getting ssh connection in bash script:
#!/bin/bash
while [[ $STATUS != 0 ]]
ssh-add -l &>/dev/null; STATUS="$?"
if [[ $STATUS == 127 ]]; then echo "ssh not instaled" && exit 0;
elif [[ $STATUS == 2 ]]; then echo "running ssh-agent.." && eval `ssh-agent` > /dev/null;
elif [[ $STATUS == 1 ]]; then echo "get session identity.." && expect $HOME/agent &> /dev/null;
else ssh-add -l && git submodule update --init --recursive --remote --merge && return 0; fi
do true; done
It will give the output in sequence as below:
Step #0 - "gcloud": intalling expect..
Step #0 - "gcloud": running ssh-agent..
Step #0 - "gcloud": get session identity..
Step #0 - "gcloud": 4096 SHA256:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX /builder/home/.ssh/id_rsa (RSA)
Step #0 - "gcloud": Submodule '.google/cloud/compute/home/chetabahana/.docker/compose' ([email protected]:chetabahana/compose) registered for path '.google/cloud/compute/home/chetabahana/.docker/compose'
Step #0 - "gcloud": Cloning into '/workspace/.io/.google/cloud/compute/home/chetabahana/.docker/compose'...
Step #0 - "gcloud": Warning: Permanently added the RSA host key for IP address 'XXX.XX.XXX.XXX' to the list of known hosts.
Step #0 - "gcloud": Submodule path '.google/cloud/compute/home/chetabahana/.docker/compose': checked out '24a28a7a306a671bbc430aa27b83c09cc5f1c62d'
Finished Step #0 - "gcloud"
How do I remove all .pyc files from a project?
If you want remove all *.pyc
files and __pycache__
directories recursively in the current directory:
import os
os.popen('find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf')
- or manually with terminal or cmd:
find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf
How to check for empty array in vba macro
Public Function IsEmptyArray(InputArray As Variant) As Boolean
On Error GoTo ErrHandler:
IsEmptyArray = Not (UBound(InputArray) >= 0)
Exit Function
ErrHandler:
IsEmptyArray = True
End Function
Automatically create an Enum based on values in a database lookup table?
Just showing the answer of Pandincus with "of the shelf" code and some explanation:
You need two solutions for this example ( I know it could be done via one also ; ), let the advanced students present it ...
So here is the DDL SQL for the table :
USE [ocms_dev]
GO
CREATE TABLE [dbo].[Role](
[RoleId] [int] IDENTITY(1,1) NOT NULL,
[RoleName] [varchar](50) NULL
) ON [PRIMARY]
So here is the console program producing the dll:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
using System.Data.Common;
using System.Data;
using System.Data.SqlClient;
namespace DynamicEnums
{
class EnumCreator
{
// after running for first time rename this method to Main1
static void Main ()
{
string strAssemblyName = "MyEnums";
bool flagFileExists = System.IO.File.Exists (
AppDomain.CurrentDomain.SetupInformation.ApplicationBase +
strAssemblyName + ".dll"
);
// Get the current application domain for the current thread
AppDomain currentDomain = AppDomain.CurrentDomain;
// Create a dynamic assembly in the current application domain,
// and allow it to be executed and saved to disk.
AssemblyName name = new AssemblyName ( strAssemblyName );
AssemblyBuilder assemblyBuilder =
currentDomain.DefineDynamicAssembly ( name,
AssemblyBuilderAccess.RunAndSave );
// Define a dynamic module in "MyEnums" assembly.
// For a single-module assembly, the module has the same name as
// the assembly.
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule (
name.Name, name.Name + ".dll" );
// Define a public enumeration with the name "MyEnum" and
// an underlying type of Integer.
EnumBuilder myEnum = moduleBuilder.DefineEnum (
"EnumeratedTypes.MyEnum",
TypeAttributes.Public,
typeof ( int )
);
#region GetTheDataFromTheDatabase
DataTable tableData = new DataTable ( "enumSourceDataTable" );
string connectionString = "Integrated Security=SSPI;Persist " +
"Security Info=False;Initial Catalog=ocms_dev;Data " +
"Source=ysg";
using (SqlConnection connection =
new SqlConnection ( connectionString ))
{
SqlCommand command = connection.CreateCommand ();
command.CommandText = string.Format ( "SELECT [RoleId], " +
"[RoleName] FROM [ocms_dev].[dbo].[Role]" );
Console.WriteLine ( "command.CommandText is " +
command.CommandText );
connection.Open ();
tableData.Load ( command.ExecuteReader (
CommandBehavior.CloseConnection
) );
} //eof using
foreach (DataRow dr in tableData.Rows)
{
myEnum.DefineLiteral ( dr[1].ToString (),
Convert.ToInt32 ( dr[0].ToString () ) );
}
#endregion GetTheDataFromTheDatabase
// Create the enum
myEnum.CreateType ();
// Finally, save the assembly
assemblyBuilder.Save ( name.Name + ".dll" );
} //eof Main
} //eof Program
} //eof namespace
Here is the Console programming printing the output ( remember that it has to reference the dll ). Let the advance students present the solution for combining everything in one solution with dynamic loading and checking if there is already build dll.
// add the reference to the newly generated dll
use MyEnums ;
class Program
{
static void Main ()
{
Array values = Enum.GetValues ( typeof ( EnumeratedTypes.MyEnum ) );
foreach (EnumeratedTypes.MyEnum val in values)
{
Console.WriteLine ( String.Format ( "{0}: {1}",
Enum.GetName ( typeof ( EnumeratedTypes.MyEnum ), val ),
val ) );
}
Console.WriteLine ( "Hit enter to exit " );
Console.ReadLine ();
} //eof Main
} //eof Program
OracleCommand SQL Parameters Binding
Oracle has a different syntax for parameters than Sql-Server. So use :
instead of @
using(var con=new OracleConnection(connectionString))
{
con.open();
var sql = "insert into users values (:id,:name,:surname,:username)";
using(var cmd = new OracleCommand(sql,con)
{
OracleParameter[] parameters = new OracleParameter[] {
new OracleParameter("id",1234),
new OracleParameter("name","John"),
new OracleParameter("surname","Doe"),
new OracleParameter("username","johnd")
};
cmd.Parameters.AddRange(parameters);
cmd.ExecuteNonQuery();
}
}
When using named parameters in an OracleCommand you must precede the parameter name with a colon (:).
http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oraclecommand.parameters.aspx
Angular 1 - get current URL parameters
Better would have been generate url like
app.dev/backend?type=surveys&id=2
and then use
var type=$location.search().type;
var id=$location.search().id;
and inject $location in controller.
How to get a password from a shell script without echoing
One liner:
read -s -p "Password: " password
Under Linux (and cygwin) this form works in bash and sh. It may not be standard Unix sh, though.
For more info and options, in bash, type "help read".
$ help read
read: read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]
Read a line from the standard input and split it into fields.
...
-p prompt output the string PROMPT without a trailing newline before
attempting to read
...
-s do not echo input coming from a terminal
Unsuccessful append to an empty NumPy array
I might understand the question incorrectly, but if you want to declare an array of a certain shape but with nothing inside, the following might be helpful:
Initialise empty array:
>>> a = np.zeros((0,3)) #or np.empty((0,3)) or np.array([]).reshape(0,3)
>>> a
array([], shape=(0, 3), dtype=float64)
Now you can use this array to append rows of similar shape to it. Remember that a numpy array is immutable, so a new array is created for each iteration:
>>> for i in range(3):
... a = np.vstack([a, [i,i,i]])
...
>>> a
array([[ 0., 0., 0.],
[ 1., 1., 1.],
[ 2., 2., 2.]])
np.vstack and np.hstack is the most common method for combining numpy arrays, but coming from Matlab I prefer np.r_ and np.c_:
Concatenate 1d:
>>> a = np.zeros(0)
>>> for i in range(3):
... a = np.r_[a, [i, i, i]]
...
>>> a
array([ 0., 0., 0., 1., 1., 1., 2., 2., 2.])
Concatenate rows:
>>> a = np.zeros((0,3))
>>> for i in range(3):
... a = np.r_[a, [[i,i,i]]]
...
>>> a
array([[ 0., 0., 0.],
[ 1., 1., 1.],
[ 2., 2., 2.]])
Concatenate columns:
>>> a = np.zeros((3,0))
>>> for i in range(3):
... a = np.c_[a, [[i],[i],[i]]]
...
>>> a
array([[ 0., 1., 2.],
[ 0., 1., 2.],
[ 0., 1., 2.]])
How do I disable directory browsing?
If you choose to modify your httpd.conf file to solve this and you have multiple Options directives, then you must add a - or a + before each directive. Example:
Options -Indexes +FollowSymLinks
COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'
Firstly run this query
SHOW VARIABLES LIKE '%char%';
You have character_set_server='latin1'
If so,go into your config file,my.cnf and add or uncomment these lines:
character-set-server = utf8
collation-server = utf8_unicode_ci
Restart the server.
Yes late to the party,just encountered the same issue.
Maven Jacoco Configuration - Exclude classes/packages from report not working
Your XML is slightly wrong, you need to add any class exclusions within an excludes parent field, so your above configuration should look like the following as per the Jacoco docs
<configuration>
<excludes>
<exclude>**/*Config.*</exclude>
<exclude>**/*Dev.*</exclude>
</excludes>
</configuration>
The values of the exclude fields should be class paths (not package names) of the compiled classes relative to the directory target/classes/ using the standard wildcard syntax
* Match zero or more characters
** Match zero or more directories
? Match a single character
You may also exclude a package and all of its children/subpackages this way:
<exclude>some/package/**/*</exclude>
This will exclude every class in some.package
, as well as any children. For example, some.package.child
wouldn't be included in the reports either.
I have tested and my report goal reports on a reduced number of classes using the above.
If you are then pushing this report into Sonar, you will then need to tell Sonar to exclude these classes in the display which can be done in the Sonar settings
Settings > General Settings > Exclusions > Code Coverage
Sonar Docs explains it a bit more
Running your command above
mvn clean verify
Will show the classes have been excluded
No exclusions
[INFO] --- jacoco-maven-plugin:0.7.4.201502262128:report (post-test) @ ** ---
[INFO] Analyzed bundle '**' with 37 classes
With exclusions
[INFO] --- jacoco-maven-plugin:0.7.4.201502262128:report (post-test) @ ** ---
[INFO] Analyzed bundle '**' with 34 classes
Hope this helps
Entity Framework Timeouts
Usually I handle my operations within a transaction. As I've experienced, it is not enough to set the context command timeout, but the transaction needs a constructor with a timeout parameter. I had to set both time out values for it to work properly.
int? prevto = uow.Context.Database.CommandTimeout;
uow.Context.Database.CommandTimeout = 900;
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromSeconds(900))) {
...
}
At the end of the function I set back the command timeout to the previous value in prevto.
Using EF6
Converting JavaScript object with numeric keys into array
There is nothing like a "JSON object" - JSON is a serialization notation.
If you want to transform your javascript object to a javascript array, either you write your own loop [which would not be that complex!], or you rely on underscore.js _.toArray()
method:
var obj = {"0":"1","1":"2","2":"3","3":"4"};
var yourArray = _(obj).toArray();
ssh-copy-id no identities found error
Run following command
# ssh-add
If it gives following error:
Could not open a connection to your authentication agent
To remove this error, Run following command:
# eval `ssh-agent`
HikariCP - connection is not available
I managed to fix it finally. The problem is not related to HikariCP.
The problem persisted because of some complex methods in REST controllers executing multiple changes in DB through JPA repositories. For some reasons calls to these interfaces resulted in a growing number of "freezed" active connections, exhausting the pool. Either annotating these methods as @Transactional
or enveloping all the logic in a single call to transactional service method seem to solve the problem.
APT command line interface-like yes/no input?
A very simple (but not very sophisticated) way of doing this for a single choice would be:
msg = 'Shall I?'
shall = input("%s (y/N) " % msg).lower() == 'y'
You could also write a simple (slightly improved) function around this:
def yn_choice(message, default='y'):
choices = 'Y/n' if default.lower() in ('y', 'yes') else 'y/N'
choice = input("%s (%s) " % (message, choices))
values = ('y', 'yes', '') if choices == 'Y/n' else ('y', 'yes')
return choice.strip().lower() in values
Note: On Python 2, use raw_input
instead of input
.
How exactly does <script defer="defer"> work?
This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed. Since this feature hasn't yet been implemented by all other major browsers, authors should not assume that the script’s execution will actually be deferred. Never call document.write() from a defer script (since Gecko 1.9.2, this will blow away the document). The defer attribute shouldn't be used on scripts that don't have the src attribute. Since Gecko 1.9.2, the defer attribute is ignored on scripts that don't have the src attribute. However, in Gecko 1.9.1 even inline scripts are deferred if the defer attribute is set.
defer works with chrome , firefox , ie > 7 and Safari
ref: https://developer.mozilla.org/en-US/docs/HTML/Element/script
How do I find the number of arguments passed to a Bash script?
#!/bin/bash
echo "The number of arguments is: $#"
a=${@}
echo "The total length of all arguments is: ${#a}: "
count=0
for var in "$@"
do
echo "The length of argument '$var' is: ${#var}"
(( count++ ))
(( accum += ${#var} ))
done
echo "The counted number of arguments is: $count"
echo "The accumulated length of all arguments is: $accum"
How can I roll back my last delete command in MySQL?
I also had deleted some values from my development database, but I had the same copy in QA database, so I did a generate script and selected option "type of data to script" to "data only" and selected my table.
Then I got the insert statements with same data, and then I run the script on my development database.
C# refresh DataGridView when updating or inserted on another form
// Form A
public void loaddata()
{
//do what you do in load data in order to update data in datagrid
}
then on Form B define:
// Form B
FormA obj = (FormA)Application.OpenForms["FormA"];
private void button1_Click(object sender, EventArgs e)
{
obj.loaddata();
datagridview1.Update();
datagridview1.Refresh();
}
Export to csv in jQuery
You can't avoid a server call here, JavaScript simply cannot (for security reasons) save a file to the user's file system. You'll have to submit your data to the server and have it send the .csv
as a link or an attachment directly.
HTML5 has some ability to do this (though saving really isn't specified - just a use case, you can read the file if you want), but there's no cross-browser solution in place now.
In log4j, does checking isDebugEnabled before logging improve performance?
Since in option 1 the message string is a constant, there is absolutely no gain in wrapping the logging statement with a condition, on the contrary, if the log statement is debug enabled, you will be evaluating twice, once in the isDebugEnabled()
method and once in debug()
method. The cost of invoking isDebugEnabled()
is in the order of 5 to 30 nanoseconds which should be negligible for most practical purposes. Thus, option 2 is not desirable because it pollutes your code and provides no other gain.
Removing spaces from string
I also had this problem. To sort out the problem of spaces in the middle of the string this line of code always works:
String field = field.replaceAll("\\s+", "");
pass post data with window.location.href
I use a very different approach to this. I set browser cookies in the client that expire a second after I set window.location.href
.
This is way more secure than embedding your parameters in the URL.
The server receives the parameters as cookies, and the browser deletes the cookies right after they are sent.
const expires = new Date(Date.now() + 1000).toUTCString()
document.cookie = `oauth-username=user123; expires=${expires}`
window.location.href = `https:foo.com/oauth/google/link`
How to prevent the "Confirm Form Resubmission" dialog?
Quick Answer
Use different methods to load the form and save/process form.
Example.
Login.php
Load login form at Login/index
Validate login at Login/validate
On Success
Redirect the user to User/dashboard
On failure
Redirect the user to login/index
Reading HTML content from a UIWebView
Note that the NSString stringWithContentsOfURL will report a totally different user-agent string than the UIWebView making the same request. So if your server is user-agent aware, and sending back different html depending on who is asking for it, you may not get correct results this way.
Also note that the @"document.body.innerHTML"
mentioned above will only display what is in the body tag. If you use @"document.all[0].innerHTML"
you will get both head and body. Which is still not the complete contents of the UIWebView, since it will not get back the !doctype or html tags, but it is a lot closer.
How to set base url for rest in spring boot?
server.servlet.context-path=/api
would be the solution I guess. I had the same issue and this got me solved. I used server.context-path. However, that seemed to be deprecated and I found that server.servlet.context-path
solves the issue now. Another workaround I found was adding a base tag to my front end (H5) pages. I hope this helps someone out there.
Cheers
What is ModelState.IsValid valid for in ASP.NET MVC in NerdDinner?
ModelState.IsValid
tells you if any model errors have been added to ModelState
.
The default model binder will add some errors for basic type conversion issues (for example, passing a non-number for something which is an "int"). You can populate ModelState more fully based on whatever validation system you're using.
The sample DataAnnotations
model binder will fill model state with validation errors taken from the DataAnnotations
attributes on your model.
Jasmine.js comparing arrays
Just did the test and it works with toEqual
please find my test:
http://jsfiddle.net/7q9N7/3/
describe('toEqual', function() {
it('passes if arrays are equal', function() {
var arr = [1, 2, 3];
expect(arr).toEqual([1, 2, 3]);
});
});
Just for information:
toBe() versus toEqual(): toEqual() checks equivalence. toBe(), on the
other hand, makes sure that they're the exact same object.
How to hide only the Close (x) button?
We can hide close button on form by setting this.ControlBox=false;
Note that this hides all of those sizing buttons. Not just the X. In some cases that may be fine.
How to count TRUE values in a logical vector
Another way is
> length(z[z==TRUE])
[1] 498
While sum(z)
is nice and short, for me length(z[z==TRUE])
is more self explaining. Though, I think with a simple task like this it does not really make a difference...
If it is a large vector, you probably should go with the fastest solution, which is sum(z)
. length(z[z==TRUE])
is about 10x slower and table(z)[TRUE]
is about 200x slower than sum(z)
.
Summing up, sum(z)
is the fastest to type and to execute.
Spring JDBC Template for calling Stored Procedures
There are a number of ways to call stored procedures in Spring.
If you use CallableStatementCreator
to declare parameters, you will be using Java's standard interface of CallableStatement
, i.e register out parameters and set them separately. Using SqlParameter
abstraction will make your code cleaner.
I recommend you looking at SimpleJdbcCall
. It may be used like this:
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(package)
.withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);
For simple procedures you may use jdbcTemplate
's update
method:
jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);
The type initializer for 'MyClass' threw an exception
Had a case like this in a WPF project. My issue was on a line that went like this:
DataTable myTable = FillTable(strMySqlQuery);
Where FillTable()
returned a DataTable based on a SQL query string. If I did the "copy exception to clipboard" option, I think it was, and pasted into Notepad, I could see the message. For me, it was The input is not a valid Base-64 string as it contains a non-base 64 character
.
My actual problem wasn't that the query string had something that shouldn't be there, like I was thinking, because string strMySqlQuery = "SELECT * FROM My_Table"
was my string and thought it could be the *
or _
, but the actual problem was in FillTable()
, where I had a call to another function, GetConnection()
that returned an OracleConnection
object, in order to open it and retrieve and return the DataTable. Inside GetConnection()
I was getting the app.config
parameters for my connection string, and I had one of them misnamed, so it was setting a null value for the service account's password and not making the DB connection. So it's not always where the error is exactly correct for all circumstances. Best to dive into the function where the error is and debug step-by-step and ensure all values are getting filled with what you expect.
Is there a function to round a float in C or do I need to write my own?
To print a rounded value, @Matt J well answers the question.
float x = 45.592346543;
printf("%0.1f\n", x); // 45.6
As most floating point (FP) is binary based, exact rounding to one decimal place is not possible when the mathematically correct answer is x.1, x.2, ...
.
To convert the FP number to the nearest 0.1
is another matter.
Overflow: Approaches that first scale by 10 (or 100, 1000, etc) may overflow for large x
.
float round_tenth1(float x) {
x = x * 10.0f;
...
}
Double rounding: Adding 0.5f and then using floorf(x*10.0f + 0.5f)/10.0
returns the wrong result when the intermediate sum x*10.0f + 0.5f
rounds up to a new integer.
// Fails to round 838860.4375 correctly, comes up with 838860.5
// 0.4499999880790710449 fails as it rounds to 0.5
float round_tenth2(float x) {
if (x < 0.0) {
return ceilf(x*10.0f + 0.5f)/10.0f;
}
return floorf(x*10.0f + 0.5f)/10.0f;
}
Casting to int
has the obvious problem when float x
is much greater than INT_MAX
.
Using roundf()
and family, available in <math.h>
is the best approach.
float round_tenthA(float x) {
double x10 = 10.0 * x;
return (float) (round(x10)/10.0);
}
To avoid using double
, simply test if the number needs rounding.
float round_tenthB(float x) {
const float limit = 1.0/FLT_EPSILON;
if (fabsf(x) < limit) {
return roundf(x*10.0f)/10.0f;
}
return x;
}
Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support
This happened to me after I ran a script with cProfile a la python3 -m cProfile script.py
even though xlrd was already installed and had never thrown this error before. it persisted even under python3 script.py
. (Granted, I agree this wasn't what happened to OP, given the obvious import error)
However, for cases like mine, the following fixed the issue, despite being told "requirement already met" in every case.
pip install --upgrade pandas
pip install --upgrade xlrd
Pretty confounding stuff; not sure if cProfile was the cause or just a coincidence
The following should work, assuming your pip install
operated on python2.
python3 -m pip install xlrd
Check if event exists on element
This work for me it is showing the objects and type of event which has occurred.
var foo = $._data( $('body').get(0), 'events' );
$.each( foo, function(i,o) {
console.log(i); // guide of the event
console.log(o); // the function definition of the event handler
});
Forcing Internet Explorer 9 to use standards document mode
Make sure you use the right doctype.
eg.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
or just
<!doctype html>
and also read and understand how compatibility modes and developer toolbar for IE work and set modes for IE:
How to convert string to char array in C++?
Ok, i am shocked that no one really gave a good answer, now my turn. There are two cases;
A constant char array is good enough for you so you go with,
const char *array = tmp.c_str();
Or you need to modify the char array so constant is not ok, then just go with this
char *array = &tmp[0];
Both of them are just assignment operations and most of the time that is just what you need, if you really need a new copy then follow other fellows answers.
Java; String replace (using regular expressions)?
import java.util.regex.PatternSyntaxException;
// (:?\d+) \* x\^(:?\d+)
//
// Options: ^ and $ match at line breaks
//
// Match the regular expression below and capture its match into backreference number 1 «(:?\d+)»
// Match the character “:” literally «:?»
// Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
// Match a single digit 0..9 «\d+»
// Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
// Match the character “ ” literally « »
// Match the character “*” literally «\*»
// Match the characters “ x” literally « x»
// Match the character “^” literally «\^»
// Match the regular expression below and capture its match into backreference number 2 «(:?\d+)»
// Match the character “:” literally «:?»
// Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
// Match a single digit 0..9 «\d+»
// Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
try {
String resultString = subjectString.replaceAll("(?m)(:?\\d+) \\* x\\^(:?\\d+)", "$1x<sup>$2</sup>");
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
} catch (IllegalArgumentException ex) {
// Syntax error in the replacement text (unescaped $ signs?)
} catch (IndexOutOfBoundsException ex) {
// Non-existent backreference used the replacement text
}
Is it better to use NOT or <> when comparing values?
The second example would be the one to go with, not just for readability, but because of the fact that in the first example, If NOT value1 would return a boolean value to be compared against value2. IOW, you need to rewrite that example as
If NOT (value1 = value2)
which just makes the use of the NOT keyword pointless.
gnuplot - adjust size of key/legend
To adjust the length of the samples:
set key samplen X
(default is 4)
To adjust the vertical spacing of the samples:
set key spacing X
(default is 1.25)
and (for completeness), to adjust the fontsize:
set key font "<face>,<size>"
(default depends on the terminal)
And of course, all these can be combined into one line:
set key samplen 2 spacing .5 font ",8"
Note that you can also change the position of the key using set key at <position>
or any one of the pre-defined positions (which I'll just defer to help key
at this point)