You can grab eng.traineddata
Github:
wget https://github.com/tesseract-ocr/tessdata/raw/master/eng.traineddata
Check https://github.com/tesseract-ocr/tessdata for a full list of trained language data.
When you grab the file(s), move them to the /usr/local/share/tessdata
folder. Warning: some Linux distributions (such as openSUSE and Ubuntu) may be expecting it in /usr/share/tessdata
instead.
# If you got the data from Google, unzip it first!
gunzip eng.traineddata.gz
# Move the data
sudo mv -v eng.traineddata /usr/local/share/tessdata/
custom_oem=r'digits --oem 1 --psm 7 -c tessedit_char_whitelist=0123456789'
text = tess.image_to_string(croped,config=custom_oem)
I am using tesseract 4.1.1.
For better result you might want to consider Image processing techniques.
Java version for Sathyaraj's code above:
// Resize
public Bitmap resize(Bitmap img, int newWidth, int newHeight) {
Bitmap bmap = img.copy(img.getConfig(), true);
double nWidthFactor = (double) img.getWidth() / (double) newWidth;
double nHeightFactor = (double) img.getHeight() / (double) newHeight;
double fx, fy, nx, ny;
int cx, cy, fr_x, fr_y;
int color1;
int color2;
int color3;
int color4;
byte nRed, nGreen, nBlue;
byte bp1, bp2;
for (int x = 0; x < bmap.getWidth(); ++x) {
for (int y = 0; y < bmap.getHeight(); ++y) {
fr_x = (int) Math.floor(x * nWidthFactor);
fr_y = (int) Math.floor(y * nHeightFactor);
cx = fr_x + 1;
if (cx >= img.getWidth())
cx = fr_x;
cy = fr_y + 1;
if (cy >= img.getHeight())
cy = fr_y;
fx = x * nWidthFactor - fr_x;
fy = y * nHeightFactor - fr_y;
nx = 1.0 - fx;
ny = 1.0 - fy;
color1 = img.getPixel(fr_x, fr_y);
color2 = img.getPixel(cx, fr_y);
color3 = img.getPixel(fr_x, cy);
color4 = img.getPixel(cx, cy);
// Blue
bp1 = (byte) (nx * Color.blue(color1) + fx * Color.blue(color2));
bp2 = (byte) (nx * Color.blue(color3) + fx * Color.blue(color4));
nBlue = (byte) (ny * (double) (bp1) + fy * (double) (bp2));
// Green
bp1 = (byte) (nx * Color.green(color1) + fx * Color.green(color2));
bp2 = (byte) (nx * Color.green(color3) + fx * Color.green(color4));
nGreen = (byte) (ny * (double) (bp1) + fy * (double) (bp2));
// Red
bp1 = (byte) (nx * Color.red(color1) + fx * Color.red(color2));
bp2 = (byte) (nx * Color.red(color3) + fx * Color.red(color4));
nRed = (byte) (ny * (double) (bp1) + fy * (double) (bp2));
bmap.setPixel(x, y, Color.argb(255, nRed, nGreen, nBlue));
}
}
bmap = setGrayscale(bmap);
bmap = removeNoise(bmap);
return bmap;
}
// SetGrayscale
private Bitmap setGrayscale(Bitmap img) {
Bitmap bmap = img.copy(img.getConfig(), true);
int c;
for (int i = 0; i < bmap.getWidth(); i++) {
for (int j = 0; j < bmap.getHeight(); j++) {
c = bmap.getPixel(i, j);
byte gray = (byte) (.299 * Color.red(c) + .587 * Color.green(c)
+ .114 * Color.blue(c));
bmap.setPixel(i, j, Color.argb(255, gray, gray, gray));
}
}
return bmap;
}
// RemoveNoise
private Bitmap removeNoise(Bitmap bmap) {
for (int x = 0; x < bmap.getWidth(); x++) {
for (int y = 0; y < bmap.getHeight(); y++) {
int pixel = bmap.getPixel(x, y);
if (Color.red(pixel) < 162 && Color.green(pixel) < 162 && Color.blue(pixel) < 162) {
bmap.setPixel(x, y, Color.BLACK);
}
}
}
for (int x = 0; x < bmap.getWidth(); x++) {
for (int y = 0; y < bmap.getHeight(); y++) {
int pixel = bmap.getPixel(x, y);
if (Color.red(pixel) > 162 && Color.green(pixel) > 162 && Color.blue(pixel) > 162) {
bmap.setPixel(x, y, Color.WHITE);
}
}
}
return bmap;
}
Use the following command to install tesseract
pip install tesseract
There Are few steps to set the path
1:goto this "https://github.com/UB-Mannheim/tesseract/wiki"
2:download the latest installers
3:install it
4: set the path in system variables such as "C:\Program Files\Tesseract-OCR" or "C:\ProgramFiles (x86)\Tesseract-OCR"
5 : open CMD type "tesseract" and some output except "not regonized type errors"
Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.
Let me explain using step-by-step guidance.
First, download the source code from https://github.com/rmtheis/tess-two.
Import all three projects. After importing you will get an error.
To solve the error you have to create a res
folder in the tess-two project
First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"
After doing this in all three project the error should be gone.
Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.
Now you just need to import it into your workspace, but first you have to download android-ndk from this site:
http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file
Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable
Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture
done it
Now open cmd and go to on D:\Android Workspace\tess-two like below
If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:
Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest
Import test-two in this and run OCRTest and run it; you will get the best example of OCR.
In my case I had all these worked except for the correct character recognition.
But you need to consider these few things:
ocr.Init(@"c:\tessdata", "eng", true);
hope that this helps
Try setting a height on your td elements.
vertical-align: middle;
means the element the style is applied to will be aligned within the parent element. The height of the td may be only as high as the text inside.
<! DOCTYPE html>
<html>
<head></head>
<body>
<input type="text" id="subEmail">
<script type="text/javascript">
window.onload = function(){
var subEmail = document.getElementById("subEmail");
subEmail.onchange = function(){
if(subEmail.value == "")
{
subEmail.style.backgroundColor = "red";
}
else
{
subEmail.style.backgroundColor = "yellow";
}
};
};
</script>
</body>
The previous answers relied on doubling up text and lacked sufficient whitespace.
By using atop
and
I was able to get the results I wanted.
This example also includes arrows, a common use case for SVG text labels:
<svg viewBox="-105 -40 210 234">
<title>Size Guide</title>
<defs>
<filter x="0" y="0" width="1" height="1" id="solid">
<feFlood flood-color="white"></feFlood>
<feComposite in="SourceGraphic" operator="atop"></feComposite>
</filter>
<marker id="arrow" viewBox="0 0 10 10" refX="5" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
<path d="M 0 0 L 10 5 L 0 10 z"></path>
</marker>
</defs>
<g id="garment">
<path id="right-body" fill="none" stroke="black" stroke-width="1" stroke-linejoin="round" d="M0 0 l30 0 l0 154 l-30 0"></path>
<path id="right-sleeve" d="M30 0 l35 0 l0 120 l-35 0" fill="none" stroke-linejoin="round" stroke="black" stroke-width="1"></path>
<use id="left-body" href="#right-body" transform="scale(-1,1)"></use>
<use id="left-sleeve" href="#right-sleeve" transform="scale(-1,1)"></use>
<path id="collar-right-top" fill="none" stroke="black" stroke-width="1" stroke-linejoin="round" d="M0 -6.5 l11.75 0 l6.5 6.5"></path>
<use id="collar-left-top" href="#collar-right-top" transform="scale(-1,1)"></use>
<path id="collar-left" fill="white" stroke="black" stroke-width="1" stroke-linejoin="round" d="M-11.75 -6.5 l-6.5 6.5 l30 77 l6.5 -6.5 Z"></path>
<path id="front-right" fill="white" stroke="black" stroke-width="1" d="M18.25 0 L30 0 l0 154 l-41.75 0 l0 -77 Z"></path>
<line x1="0" y1="0" x2="0" y2="154" stroke="black" stroke-width="1" stroke-dasharray="1 3"></line>
<use id="collar-right" href="#collar-left" transform="scale(-1,1)"></use>
</g>
<g id="dimension-labels">
<g id="dimension-sleeve-length">
<line marker-start="url(#arrow)" marker-end="url(#arrow)" x1="85" y1="0" x2="85" y2="120" stroke="black" stroke-width="1"></line>
<text font-size="10" filter="url(#solid)" fill="black" x="85" y="60" class="dimension" text-anchor="middle" dominant-baseline="middle"> 120 cm</text>
</g>
<g id="dimension-length">
<line marker-start="url(#arrow)" marker-end="url(#arrow)" x1="-85" y1="0" x2="-85" y2="154" stroke="black" stroke-width="1"></line>
<text font-size="10" filter="url(#solid)" fill="black" x="-85" y="77" text-anchor="middle" dominant-baseline="middle" class="dimension"> 154 cm</text>
</g>
<g id="dimension-sleeve-to-sleeve">
<line marker-start="url(#arrow)" marker-end="url(#arrow)" x1="-65" y1="-20" x2="65" y2="-20" stroke="black" stroke-width="1"></line>
<text font-size="10" filter="url(#solid)" fill="black" x="0" y="-20" text-anchor="middle" dominant-baseline="middle" class="dimension"> 130 cm </text>
</g>
<g title="Back Width" id="dimension-back-width">
<line marker-start="url(#arrow)" marker-end="url(#arrow)" x1="-30" y1="174" x2="30" y2="174" stroke="black" stroke-width="1"></line>
<text font-size="10" filter="url(#solid)" fill="black" x="0" y="174" text-anchor="middle" dominant-baseline="middle" class="dimension"> 60 cm </text>
</g>
</g>
</svg>
If you wrote it like this then it would matter :
for(i=0; i<5; i=j++) {
printf("%d",i);
}
Would iterate once more than if written like this :
for(i=0; i<5; i=++j) {
printf("%d",i);
}
You will get all the class in below array
event.target.classList
For developers who cannot change php configuration because of the webhosting. (My settings 256MB max size, 1000 max variables)
I got the same issue that just 2 out of 5 big data objects (associative arrays) with substructures were received on the server side.
I find out that the whole substructure is being "flattened" in the post request. So, one object becomes a hundreds of literal variables. At the end, instead of 5 Object variables it is in reality sending dozens of hundreds elementar variables.
Solution in this case is to serialize each of the substructures into String. Then it is received on the server as 5 String variables.
Example:
{variable1:JSON.stringify(myDataObject1),variable2:JSON.stringify(myDataObject2)...}
Yeah. Just use binary serialization. You have to have each object use implements Serializable
but it's straightforward from there.
Your other option, if you want to avoid implementing the Serializable interface, is to use reflection and read and write data to/from a buffer using a process this one below:
/**
* Sets all int fields in an object to 0.
*
* @param obj The object to operate on.
*
* @throws RuntimeException If there is a reflection problem.
*/
public static void initPublicIntFields(final Object obj) {
try {
Field[] fields = obj.getClass().getFields();
for (int idx = 0; idx < fields.length; idx++) {
if (fields[idx].getType() == int.class) {
fields[idx].setInt(obj, 0);
}
}
} catch (final IllegalAccessException ex) {
throw new RuntimeException(ex);
}
}
A better approach would be to delegate the event, which means catching it as it bubbles to the parent node.
This solution is both more robust and efficient.
It allows the event to be handled even if more rows are dynamically added to the table later, and also results in attaching a single event handler to the parent node (table
element), instead of one for each child node (tr
element).
Assuming that the OP's example is a simplified one, the table's structure can be more complex, for example:
<table id="indexedTable">
...
<tr>
<td><p>1</p></td>
<td>2</td>
<td><p>3</p></td>
</tr>
</table>
Therefore, a simplistic approach such as getting e.target.parentElement
will not work, as clicking the internal <p>
and clicking the center <td>
will produce different results.
Using delegation normalizes the event handling, only assuming that there are no nested tables.
Both of the following snippets are equivalent:
$("#indexedTable").delegate("tr", "click", function(e) {
console.log($(e.currentTarget).index() + 1);
});
$("#indexedTable").on("click", "tr", function(e) {
console.log($(e.currentTarget).index() + 1);
});
They attach a listener to table
element and handle any event that bubbles from the table rows. The current API is the on
method and the delegate
method is legacy API (and actually calls on
behind the scenes).
Note that the order of parameters to both functions is different.
A comparison between direct handler attachment and delegation is available below or on jsFiddle:
$("#table-delegate").on("click", "tr", function(e) {_x000D_
var idx = $(e.currentTarget).index() + 1;_x000D_
$("#delegation-idx").text(idx); _x000D_
console.log('delegated', idx);_x000D_
});_x000D_
_x000D_
$("#table-direct tr").on("click", function(e) {_x000D_
var idx = $(e.currentTarget).index() + 1;_x000D_
$("#direct-idx").text(idx);_x000D_
console.log('direct', idx);_x000D_
});_x000D_
_x000D_
$('[data-action=add-row]').click(function(e) {_x000D_
var id = e.target.dataset.table;_x000D_
$('#' + id + ' tbody')_x000D_
.append($('<tr><td>extra</td><td>extra</td><td>extra</td></tr>')[0])_x000D_
});
_x000D_
tr:hover{_x000D_
background:#ddd;_x000D_
}_x000D_
_x000D_
button.add-row {_x000D_
margin-bottom: 5px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
<h1>Event handling test</h1>_x000D_
<p>Add rows to both tables and see the difference in handling.</p>_x000D_
<p>Event delegation attaches a single event listener and events related to newly added children are caught.</p>_x000D_
<p>Direct event handling attaches an event handler to each child, where children added after the inital handler attachment don't have a handler attached to them, and therefore their indices won't be logged to console.</p>_x000D_
<h2>Delegation</h2>_x000D_
<p><span>row index: </span><span id="delegation-idx">unknown</span></p>_x000D_
<button class="add-row" data-action="add-row" data-table="table-delegate">Add row to delegation</button>_x000D_
<table id="table-delegate" class="table">_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>normal</td>_x000D_
<td>normal</td>_x000D_
<td>normal</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><p>nested</p></td>_x000D_
<td><p>nested</p></td>_x000D_
<td><p>nested</p></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>normal</td>_x000D_
<td>normal</td>_x000D_
<td><p>nested</p></td>_x000D_
</tr>_x000D_
_x000D_
</table>_x000D_
_x000D_
<h2>Direct attachment</h2>_x000D_
<p><span>row index: </span><span id="direct-idx">unknown</span></p>_x000D_
<button class="add-row" data-action="add-row" data-table="table-direct">Add row to direct</button>_x000D_
<table id="table-direct" class="table">_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>normal</td>_x000D_
<td>normal</td>_x000D_
<td>normal</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><p>nested</p></td>_x000D_
<td><p>nested</p></td>_x000D_
<td><p>nested</p></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>normal</td>_x000D_
<td>normal</td>_x000D_
<td><p>nested</p></td>_x000D_
</tr>_x000D_
_x000D_
</tbody>_x000D_
</table>
_x000D_
Here's the demo on jsFiddle.
P.S:
If you do have nested tables (or, in the general case, wish to delegate to elements with specific depth), you can use this suggestion from the jQuery bug report.
I have the same issue, when I try to export the content of email to csv and still keep it break line when importing to excel.
I export the conent as this: ="Line 1"&CHAR(10)&"Line 2"
When I import it to excel(google), excel understand it as string. It still not break new line.
We need to trigger excel to treat it as formula by: Format -> Number | Scientific.
This is not the good way but it resolve my issue.
Try it this way in a simple manner it will work
$userset = User::where('name',$data['name'])->first();
if(!$userset) echo "no user found";
This could be a little tricky thing but the secure way is to set a javascript cookie, then picking it up by php cookie variable.Then Assign this php variable to an php session that will hold the data more securely than cookie.Then delete the cookie using javascript and redirect the page to itself. Given that you have added an php command to catch the variable, you will get it.
I managed to download the file generated by the rest API URL much easier with this kind of code which worked just fine on my local:
import React, {Component} from "react";
import {saveAs} from "file-saver";
class MyForm extends Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
const form = event.target;
let queryParam = buildQueryParams(form.elements);
let url = 'http://localhost:8080/...whatever?' + queryParam;
fetch(url, {
method: 'GET',
headers: {
// whatever
},
})
.then(function (response) {
return response.blob();
}
)
.then(function(blob) {
saveAs(blob, "yourFilename.xlsx");
})
.catch(error => {
//whatever
})
}
render() {
return (
<form onSubmit={this.handleSubmit} id="whateverFormId">
<table>
<tbody>
<tr>
<td>
<input type="text" key="myText" name="myText" id="myText"/>
</td>
<td><input key="startDate" name="from" id="startDate" type="date"/></td>
<td><input key="endDate" name="to" id="endDate" type="date"/></td>
</tr>
<tr>
<td colSpan="3" align="right">
<button>Export</button>
</td>
</tr>
</tbody>
</table>
</form>
);
}
}
function buildQueryParams(formElements) {
let queryParam = "";
//do code here
return queryParam;
}
export default MyForm;
Here is a good starting point.
HTML:
<div class="containing-table">
<div class="centre-align">
<div class="content"></div>
</div>
</div>
CSS:
.containing-table {
display: table;
width: 100%;
height: 400px; /* for demo only */
border: 1px dotted blue;
}
.centre-align {
padding: 10px;
border: 1px dashed gray;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.content {
width: 50px;
height: 50px;
background-color: red;
display: inline-block;
vertical-align: top; /* Removes the extra white space below the baseline */
}
See demo at: http://jsfiddle.net/audetwebdesign/jSVyY/
.containing-table
establishes the width and height context for .centre-align
(the table-cell).
You can apply text-align
and vertical-align
to alter .centre-align
as needed.
Note that .content
needs to use display: inline-block
if it is to be centered horizontally using the text-align property.
The macro ways !
press q and q for recording into q register (we use "q" as shortcut to remember "quotes").
press shift + b move cursor to front of current word
press i type ' (a single quotes)
press esc then press e to move to end of word
press a then press ' again to surround the word with quotes.
press esc to get into normal mode.
finally press q to record it into q
register.
How to use
You can alter step 4
with anything you like {a line, a word until found some character, etc}.
Make recorded macro persistent
let @q='ctrl + r ctrl + r q'
save and quit
open your files, go to some words
now press @q
if you do it correctly, magic things should appear in your words.
You can apply this to other macros you loved.
I use a slightly more concise version:
expect(() => {
// Code block that should throw error
}).toThrow(TypeError) // Or .toThrow('expectedErrorMessage')
mysql -uroot -psecret mysql < mydatabase.sql
It has the last status code (exit value) of a command.
I wanted to hide the waiting spinner div when the i frame content is fully loaded on IE, i tried literally every solution mentioned in Stackoverflow.Com, but with nothing worked as i wanted.
Then i had an idea, that when the i frame content is fully loaded, the $(Window ) load event might be fired. And that exactly what happened. So, i wrote this small script, and worked like magic:
$(window).load(function () {
//alert("Done window ready ");
var lblWait = document.getElementById("lblWait");
if (lblWait != null ) {
lblWait.style.visibility = "false";
document.getElementById("divWait").style.display = "none";
}
});
Hope this helps.
Here is the function which will print all permutaion. This function implements logic Explained by peter.
public class Permutation
{
//http://www.java2s.com/Tutorial/Java/0100__Class-Definition/RecursivemethodtofindallpermutationsofaString.htm
public static void permuteString(String beginningString, String endingString)
{
if (endingString.Length <= 1)
Console.WriteLine(beginningString + endingString);
else
for (int i = 0; i < endingString.Length; i++)
{
String newString = endingString.Substring(0, i) + endingString.Substring(i + 1);
permuteString(beginningString + endingString.ElementAt(i), newString);
}
}
}
static void Main(string[] args)
{
Permutation.permuteString(String.Empty, "abc");
Console.ReadLine();
}
Just delete the files or rename them.
e.g.
$ git pull
Enter passphrase for key '/c/Users/PC983/.ssh/id_rsa':
error: Your local changes to the following files would be overwritten by merge:
ajax/productPrice.php
Please commit your changes or stash them before you merge.
error: The following untracked working tree files would be overwritten by merge:
ajax/product.php
Please move or remove them before you merge.
Aborting
Updating a04cbe7a..6aa8ead5
I had to rename/delete ajax/product.php and ajax/produtPrice.php.
Don't worry, git pull will bring them back. I suggest you to rename them instead of deleting, because you might loose some changes.
If this does not help, then you have to delete the whole Branch and create it again and then do git pull origin remotebranch
The unload() method was deprecated in jQuery version 1.8.
so if you are using versions older than 1.8
then use -
$(window).unload(function(){
alert("Goodbye!");
});
and if you are using 1.8 and higher
then use -
window.onbeforeunload = function() {
return "Bye now!";
};
hope this will work :-)
A jQuery plugin based on M4N's answer
jQuery.fn.cssNumber = function(prop){
var v = parseInt(this.css(prop),10);
return isNaN(v) ? 0 : v;
};
So then you just use this method to get number values
$("#logo").cssNumber("top")
default_data['item3'] = 3
Easy as py.
Another possible solution:
default_data.update({'item3': 3})
which is nice if you want to insert multiple items at once.
Well I'm not exactly sure why your code is not working because I usually follow a different approach when trying to accomplish something similar.
But your code is erroring out.. There seems to be an issue with the way you are using scale
I got the jQuery to actually execute by changing your code to the following.
$(document).ready(function(){
$('img').hover(function() {
$(this).css("cursor", "pointer");
$(this).toggle({
effect: "scale",
percent: "90%"
},200);
}, function() {
$(this).toggle({
effect: "scale",
percent: "80%"
},200);
});
});
But I have always done it by using CSS
to setup my scaling and transition..
Here is an example, hopefully it helps.
$(document).ready(function(){
$('#content').hover(function() {
$("#content").addClass('transition');
}, function() {
$("#content").removeClass('transition');
});
});
A more complete, albeit more verbose, way of doing this would be to use the Character.codePointAt method. This will handle 'high surrogate' characters, that cannot be represented by a single integer within the range that a char
can represent.
In the example you've given this is not strictly necessary - if the (Unicode) character can fit inside a single (Java) char
(such as the registered
local variable) then it must fall within the \u0000
to \uffff
range, and you won't need to worry about surrogate pairs. But if you're looking at potentially higher code points, from within a String/char array, then calling this method is wise in order to cover the edge cases.
For example, instead of
String input = ...;
char fifthChar = input.charAt(4);
int codePoint = (int)fifthChar;
use
String input = ...;
int codePoint = Character.codePointAt(input, 4);
Not only is this slightly less code in this instance, but it will handle detection of surrogate pairs for you.
Based on the discussion in the comments (particularly from BalusC), it's probably not worth doing anything more complicated than this:
<script>var ctx = "${pageContext.request.contextPath}"</script>
This is an old question, but because this might help a lot of c# coders out there, there is an easy way to solve this right now as follows:
if ((dataTableName?.Rows?.Count ?? 0) > 0)
You can use jQuery’s show()
and hide()
methods. Like below:
JQuery:
$(document).ready(function(){
$('input[type="radio"]').click(function(){
var val = $(this).attr("value");
var target = $("." + val);
$(".msg").not(target).hide();
$(target).show();
});
});
HTML:
<input type="radio" name="color" value="yellow"> Yellow
<input type="radio" name="color" value="red"> Red
<input type="radio" name="color" value="green"> Green
<div class="yellow msg">You have selected Yellow</div>
<div class="red msg">You have selected Red</div>
<div class="green msg">You have selected Green</div>
Here is an example: Show/hide DIV based on Radio Button click
I faced the same issue, I tried the below solution and it worked for me
In Android SDK Manager Window, click on Tools->Options-> under "Others", check "Force https://... sources to be fetched using http://..."
Just include following in your code
<body background="C:\Users\Desktop\images.jpg">
if you want to specify the size and opacity you can use following
<p><img style="opacity:0.9;" src="C:\Users\Desktop\images.jpg" width="300" height="231" alt="Image" /></p>
No jQuery needed.
Some people say using onclick
is bad practice...
This example uses pure browser javascript. By default, it appears that the click handler will evaluate before the navigation, so you can cancel the navigation and do your own if you wish.
<a id="myButton" href="http://google.com">Click me!</a>
<script>
window.addEventListener("load", () => {
document.querySelector("#myButton").addEventListener("click", e => {
alert("Clicked!");
// Can also cancel the event and manually navigate
// e.preventDefault();
// window.location = e.target.href;
});
});
</script>
Also pass the --execute
flag to generate the output cells
jupyter nbconvert --execute --to html notebook.ipynb
jupyter nbconvert --execute --to pdf notebook.ipynb
The best practice is to keep the output out of the notebook for version control, see: Using IPython notebooks under version control
But then, if you don't pass --execute
, the output won't be present in the HTML, see also: How to run an .ipynb Jupyter Notebook from terminal?
For an HTML fragment without header: How to export an IPython notebook to HTML for a blog post?
Tested in Jupyter 4.4.0.
In order to accomplish this, all that we need is two annotations:
@JsonIgnore
@JsonProperty
Use @JsonIgnore
on the class member and its getter, and @JsonProperty
on its setter. A sample illustration would help to do this:
class User {
// More fields here
@JsonIgnore
private String password;
@JsonIgnore
public String getPassword() {
return password;
}
@JsonProperty
public void setPassword(final String password) {
this.password = password;
}
}
This is a FAQ:
//somexpression[$N]
means "Find every node selected by //somexpression
that is the $N
th child of its parent".
What you want is:
(//input[@id="search_query"])[2]
Remember: The []
operator has higher precedence (priority) than the //
abbreviation.
Since Python 3.9 you can use the merge operator |
to merge two dictionaries. The dict on the right takes precedence:
new_dict = old_dict | { key: val }
For example:
new_dict = { 'a': 1, 'b': 2 } | { 'b': 42 }
print(new_dict} # {'a': 1, 'b': 42}
Note: this creates a new dictionary with the updated values.
To show the values from 2 tables in a pre-defined way, use a VIEW
set the "Dock" property of datagridview in layoutto one of these properties : top, left, bottom, right. ok?
If you don't want to use any additional package, you can call the following function before creating your file:
var path = require('path'),
fs = require('fs');
function ensureDirectoryExistence(filePath) {
var dirname = path.dirname(filePath);
if (fs.existsSync(dirname)) {
return true;
}
ensureDirectoryExistence(dirname);
fs.mkdirSync(dirname);
}
Try this in your .htaccess:
.htaccess
ErrorDocument 404 http://example.com/404/
ErrorDocument 500 http://example.com/500/
# or map them to one error document:
# ErrorDocument 404 /pages/errors/error_redirect.php
# ErrorDocument 500 /pages/errors/error_redirect.php
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} ^/404/$
RewriteRule ^(.*)$ /pages/errors/404.php [L]
RewriteCond %{REQUEST_URI} ^/500/$
RewriteRule ^(.*)$ /pages/errors/500.php [L]
# or map them to one error document:
#RewriteCond %{REQUEST_URI} ^/404/$ [OR]
#RewriteCond %{REQUEST_URI} ^/500/$
#RewriteRule ^(.*)$ /pages/errors/error_redirect.php [L]
The ErrorDocument
redirects all 404s to a specific URL, all 500s to another url (replace with your domain).
The Rewrite rules map that URL to your actual 404.php script. The RewriteCond regular expressions can be made more generic if you want, but I think you have to explicitly define all ErrorDocument codes you want to override.
Local Redirect:
Change .htaccess ErrorDocument to a file that exists (must exist, or you'll get an error):
ErrorDocument 404 /pages/errors/404_redirect.php
404_redirect.php
<?php
header('Location: /404/');
exit;
?>
Redirect based on error number
Looks like you'll need to specify an ErrorDocument
line in .htaccess for every error you want to redirect (see: Apache ErrorDocument and Apache Custom Error). The .htaccess example above has multiple examples in it. You can use the following as the generic redirect script to replace 404_redirect.php above.
error_redirect.php
<?php
$error_url = $_SERVER["REDIRECT_STATUS"] . '/';
$error_path = $error_url . '.php';
if ( ! file_exists($error_path)) {
// this is the default error if a specific error page is not found
$error_url = '404/';
}
header('Location: ' . $error_url);
exit;
?>
Since we need ellipsis only when the string length is over the limit, it seems more appropriate to add ellipsis by using ng-if
than binding.
{{ longString | limitTo: 20 }}<span ng-if="longString.length > 20">…</span>
The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5
. From the comment you put this needed to be declared elsewhere in your code
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
The error was because you are trying to execute a method that does not exist.
PS C:\Users\Matt> $md5 | gm
TypeName: System.Security.Cryptography.MD5CryptoServiceProvider
Name MemberType Definition
---- ---------- ----------
Clear Method void Clear()
ComputeHash Method byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...
The .ComputeHash()
of $md5.ComputeHash()
was the null valued expression. Typing in gibberish would create the same effect.
PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PowerShell by default allows this to happen as defined its StrictMode
When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.
I find the -e
flag elegant and straight forward
bash$ STR="Hello\nWorld"
bash$ echo -e $STR
Hello
World
If the string is the output of another command, I just use quotes
indexes_diff=$(git diff index.yaml)
echo "$indexes_diff"
Regarding how you log messages within code, I would opt for the second approach:
ILog log = LogManager.GetLogger(typeof(Bar));
log.Info("message");
Where messages sent to the log above will be 'named' using the fully-qualifed type Bar
, e.g.
MyNamespace.Foo.Bar [INFO] message
The advantage of this approach is that it is the de-facto standard for organising logging, it also allows you to filter your log messages by namespace. For example, you can specify that you want to log INFO level message, but raise the logging level for Bar
specifically to DEBUG:
<log4net>
<!-- appenders go here -->
<root>
<level value="INFO" />
<appender-ref ref="myLogAppender" />
</root>
<logger name="MyNamespace.Foo.Bar">
<level value="DEBUG" />
</logger>
</log4net>
The ability to filter your logging via name is a powerful feature of log4net, if you simply log all your messages to "myLog"
, you loose much of this power!
Regarding the EPiServer CMS, you should be able to use the above approach to specify a different logging level for the CMS and your own code.
For further reading, here is a codeproject article I wrote on logging:
In case of exporting lll
list of lists of lists to .csv, this will work in Python3:
import csv
with open("output.csv", "w") as f:
writer = csv.writer(f)
for element in lll:
writer.writerows(element)
Set the XML as:
<ToggleButton
android:id="@+id/flashlightButton"
style="@style/Button"
android:layout_above="@+id/buttonStrobeLight"
android:layout_marginBottom="20dp"
android:onClick="onToggleClicked"
android:text="ToggleButton"
android:textOn="Light ON"
android:textOff="Light OFF" />
Removing double-quotes
solve my problem, now its:
DEBUG_STORE_PASSWORD=androiddebug
DEBUG_KEY_ALIAS=androiddebug
DEBUG_KEY_PASSWORD=androiddebug
Full Example (Python 3):
For Python 2.x look into Note below
import re
mylist = ["dog", "cat", "wildcat", "thundercat", "cow", "hooo"]
r = re.compile(".*cat")
newlist = list(filter(r.match, mylist)) # Read Note
print(newlist)
Prints:
['cat', 'wildcat', 'thundercat']
Note:
For Python 2.x developers, filter
returns a list already. In Python 3.x filter
was changed to return an iterator so it has to be converted to list
(in order to see it printed out nicely).
I had a similar problem. I solved it using:
find dir_name '*.mp3' -exec cp -vuni '{}' "../dest_dir" ";"
The '{}'
and ";"
executes the copy on each file.
The simplest way is to interrupt()
it, which will cause Thread.currentThread().isInterrupted()
to return true
, and may also throw an InterruptedException
under certain circumstances where the Thread is waiting, for example Thread.sleep()
, otherThread.join()
, object.wait()
etc.
Inside the run()
method you would need catch that exception and/or regularly check the Thread.currentThread().isInterrupted()
value and do something (for example, break out).
Note: Although Thread.interrupted()
seems the same as isInterrupted()
, it has a nasty side effect: Calling interrupted()
clears the interrupted
flag, whereas calling isInterrupted()
does not.
Other non-interrupting methods involve the use of "stop" (volatile
) flags that the running Thread monitors.
In pack explorer of eclipse> Single Click on the name of Package> click F2 keyboard key >type new name> click finish.
Eclipse will do the rest of job. It will rename old package name to new in code files also.
Chris Stewart wrote there:
Splash screens just waste your time, right? As an Android developer, when I see a splash screen, I know that some poor dev had to add a three-second delay to the code.
Then, I have to stare at some picture for three seconds until I can use the app. And I have to do this every time it’s launched. I know which app I opened. I know what it does. Just let me use it!
Splash Screens the Right Way
I believe that Google isn’t contradicting itself; the old advice and the new stand together. (That said, it’s still not a good idea to use a splash screen that wastes a user’s time. Please don’t do that.)
However, Android apps do take some amount of time to start up, especially on a cold start. There is a delay there that you may not be able to avoid. Instead of leaving a blank screen during this time, why not show the user something nice? This is the approach Google is advocating. Don’t waste the user’s time, but don’t show them a blank, unconfigured section of the app the first time they launch it, either.
If you look at recent updates to Google apps, you’ll see appropriate uses of the splash screen. Take a look at the YouTube app, for example.
According to Opera the CSS3 standard does not define the use of border-radius
on TDs. My experience is that Firefox and Chrome support it but Opera does not (don't know about IE). The workaround is to wrap the td content in a div and then apply the border-radius
to the div.
There might be a JSON object for Java coding convenience. But at last the data structure will be serialized to string. Setting a proper MIME type would be nice.
One way is by creating a soft link to whichever directory you want to list in the /var/www/html/ directory.
sudo ln -s /home/ /var/www/html/
Keep in mind the security.
If ayman's solution doesn't work, try naming your file .profile
instead of .bash_profile
. That worked for me.
# coding=utf-8
def my_function_get_list():
my_list = [0, 1, 2, 3, 4, 5]
# You may use map() to convert each item in the list to a string,
# and then join them to print my_list
print("Affichage de my_list [{0}]".format(', '.join(map(str, my_list))))
return my_list
my_result_list = [
(
number_in_my_list + 4, # Condition is False : append number_in_my_list + 4 in my_result_list
number_in_my_list * 2 # Condition is True : append number_in_my_list * 2 in my_result_list
)
[number_in_my_list % 2 == 0] # [Condition] If the number in my list is even
for number_in_my_list in my_function_get_list() # For each number in my list
]
print("Affichage de my_result_list [{0}]".format(', '.join(map(str, my_result_list))))
(venv) $ python list_comp.py
Affichage de my_list [0, 1, 2, 3, 4, 5]
Affichage de my_result_list [0, 5, 4, 7, 8, 9]
So, for you:
row = [('', unicode(x.strip()))[x is not None] for x in row]
I do not think that every database has auto-update timestamps (e.g. Postgres). So I've decided to update this field manually everywhere in my code. This will work with every database:
thingy.setLastTouched(new Date());
HibernateUtil.save(thingy);
There are reasons to use triggers, but for most projects, this is not one of them. Triggers dig you even deeper into a specific database implementation.
MySQL 5.6.28 (Ubuntu 15.10, OpenJDK 64-Bit 1.8.0_66) seems to be very forgiving, not requiring anything beyond
@Column(name="LastTouched")
MySQL 5.7.9 (CentOS 6, OpenJDK 64-Bit 1.8.0_72) only works with
@Column(name="LastTouched", insertable=false, updatable=false)
not:
FAILED: removing @Temporal
FAILED: @Column(name="LastTouched", nullable=true)
FAILED: @Column(name="LastTouched", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
My other system info (identical in both environments)
Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity
).
Make sure you refer to the property as fileName
in the Criteria query, not filename
.
Specifically, Hibernate will call the getter method of the filename
property when executing that Criteria query, so it will look for a method called getFilename()
. But the property is called FileName
and the getter getFileName()
.
So, change the projection like so:
criteria.setProjection(Projections.property("fileName"));
Quick Answer:
foreach (var process in Process.GetProcessesByName("whatever"))
{
process.Kill();
}
(leave off .exe from process name)
First you should read an explanation on the output of free
. Bottom line: you have at least 10.7 GB of memory readily usable by processes.
Then you should define what "memory usage" is for a process (it's not easy or unambiguous, trust me).
Then we might be able to help more :-)
I found that if you add the command to unload, he keeps down the page, ie the page that move! Hope it works with you too!
window.addEventListener("load", function() { window.scrollTo(0, 1); });
window.addEventListener("unload", function() { window.scrollTo(0, 1); });
Using a 7-inch tablet with android, www.kupsoft.com visit my website and check how it behaves page, I use this command in my portal.
The official package for behaviors is Microsoft.Xaml.Behaviors.Wpf
.
It used to be in the Blend SDK (deprecated).
See Jan's answer for more details if you need to migrate.
All Methods and constructors are same but only one difference is LinkedHashset will maintain insertion order but it will not allow duplicates.
Hashset will not maintain any insertion order. It is combination of List and Set simple :)
Keep your scripts right before </body>
. Async can be used with scripts located there in a few circumstances (see discussion below). Defer won't make much of a difference for scripts located there because the DOM parsing work has pretty much already been done anyway.
Here's an article that explains the difference between async and defer: http://peter.sh/experiments/asynchronous-and-deferred-javascript-execution-explained/.
Your HTML will display quicker in older browsers if you keep the scripts at the end of the body right before </body>
. So, to preserve the load speed in older browsers, you don't want to put them anywhere else.
If your second script depends upon the first script (e.g. your second script uses the jQuery loaded in the first script), then you can't make them async without additional code to control execution order, but you can make them defer because defer scripts will still be executed in order, just not until after the document has been parsed. If you have that code and you don't need the scripts to run right away, you can make them async or defer.
You could put the scripts in the <head>
tag and set them to defer
and the loading of the scripts will be deferred until the DOM has been parsed and that will get fast page display in new browsers that support defer, but it won't help you at all in older browsers and it isn't really any faster than just putting the scripts right before </body>
which works in all browsers. So, you can see why it's just best to put them right before </body>
.
Async is more useful when you really don't care when the script loads and nothing else that is user dependent depends upon that script loading. The most often cited example for using async is an analytics script like Google Analytics that you don't want anything to wait for and it's not urgent to run soon and it stands alone so nothing else depends upon it.
Usually the jQuery library is not a good candidate for async because other scripts depend upon it and you want to install event handlers so your page can start responding to user events and you may need to run some jQuery-based initialization code to establish the initial state of the page. It can be used async, but other scripts will have to be coded to not execute until jQuery is loaded.
First step is to load your xml string into an XmlDocument, using powershell's unique ability to cast strings to [xml]
$doc = [xml]@'
<xml>
<Section name="BackendStatus">
<BEName BE="crust" Status="1" />
<BEName BE="pizza" Status="1" />
<BEName BE="pie" Status="1" />
<BEName BE="bread" Status="1" />
<BEName BE="Kulcha" Status="1" />
<BEName BE="kulfi" Status="1" />
<BEName BE="cheese" Status="1" />
</Section>
</xml>
'@
Powershell makes it really easy to parse xml with the dot notation. This statement will produce a sequence of XmlElements for your BEName elements:
$doc.xml.Section.BEName
Then you can pipe these objects into the where-object cmdlet to filter down the results. You can use ? as a shortcut for where
$doc.xml.Section.BEName | ? { $_.Status -eq 1 }
The expression inside the braces will be evaluated for each XmlElement in the pipeline, and only those that have a Status of 1 will be returned. The $_ operator refers to the current object in the pipeline (an XmlElement).
If you need to do something for every object in your pipeline, you can pipe the objects into the foreach-object cmdlet, which executes a block for every object in the pipeline. % is a shortcut for foreach:
$doc.xml.Section.BEName | ? { $_.Status -eq 1 } | % { $_.BE + " is delicious" }
Powershell is great at this stuff. It's really easy to assemble pipelines of objects, filter pipelines, and do operations on each object in the pipeline.
Trace.WriteLine
should work provided you select the correct output (the dropdown labeled with "Show output from" found in the Output window).
I just created some directories, shared them and mapped using:
net use y: "\\mycomputername\folder with spaces"
So this solution gets "works on my machine" certificate. What error code do you get?
Update: As of SQL Server 2016 parsing JSON in TSQL is now possible.
Natively, there is no support. You'll have to use CLR. It is as simple as that, unless you have a huge masochistic streak and want to write a JSON parser in SQL
Normally, folk ask for JSON output from the DB and there are examples on the internet. But into a DB?
Another quicker option to call things (like DialogBoxes and MessageBoxes and creating separate threads for not-thread safe methods) would be to use the Lamba Expression
new Thread(() -> {
"code here"
}).start();
I found this in the navbar example, and simplified it.
<ul class="nav">
<li><a>Default</a></li>
<li><a>Static top</a></li>
<li><b><a>Fixed top <span class="sr-only">(current)</span></a></b></li>
</ul>
You see which one is selected (sr-only
part is hidden):
You hear which one is selected if you use screen reader:
As a result of this technique blind people supposed to navigate easier on your website.
I had the same problem and found out that I had forgotten to include the script in the file which I want to include in the live site.
Also, you should try this:
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
Below query seems to work good for me in SQL Server database:
select column, COUNT(column) AS MOST_FREQUENT
from TABLE_NAME
GROUP BY column
ORDER BY COUNT(column) DESC
Result:
column MOST_FREQUENT
item1 highest count
item2 second highest
item3 third higest
..
..
This is the resolution of the screen that the given component is currently assigned (something like most part of the root window is visible on that screen).
public Rectangle getCurrentScreenBounds(Component component) {
return component.getGraphicsConfiguration().getBounds();
}
Usage:
Rectangle currentScreen = getCurrentScreenBounds(frameOrWhateverComponent);
int currentScreenWidth = currentScreen.width // current screen width
int currentScreenHeight = currentScreen.height // current screen height
// absolute coordinate of current screen > 0 if left of this screen are further screens
int xOfCurrentScreen = currentScreen.x
If you want to respect toolbars, etc. you'll need to calculate with this, too:
GraphicsConfiguration gc = component.getGraphicsConfiguration();
Insets screenInsets = Toolkit.getDefaultToolkit().getScreenInsets(gc);
For any CSS3-enabled browser you can use an adjacent sibling selector for styling your labels
input:checked + label {
color: white;
}
MDN's browser compatibility table says essentially all of the current, popular browsers (Chrome, IE, Firefox, Safari), on both desktop and mobile, are compatible.
you can use too:
val frases = arrayOf("texto01","texto02 ","anotherText","and ")
for example.
Typical error on Windows because the default user directory is C:\user\<your_user>
, so when you want to use this path as an string parameter into a Python function, you get a Unicode error, just because the \u
is a Unicode escape. Any character not numeric after this produces an error.
To solve it, just double the backslashes: C:\\user\\<\your_user>...
Bash one-liner
echo -n "5a" | while read -N2 code; do printf "\x$code"; done
Another reason for the error (amongst many others that cropped up when changing the target build of a Win32 project to X64) was not having the C++ 64 bit compilers installed as noted at the top of this page.
Further to philipvr's comment on child headers, (in my case) an explicit include of winnt.h being unnecessary when windows.h was being used.
I know I'm kinda late to the party but I made a little method others might find cool/useful.
public static JLabel linkify(final String text, String URL, String toolTip)
{
URI temp = null;
try
{
temp = new URI(URL);
}
catch (Exception e)
{
e.printStackTrace();
}
final URI uri = temp;
final JLabel link = new JLabel();
link.setText("<HTML><FONT color=\"#000099\">"+text+"</FONT></HTML>");
if(!toolTip.equals(""))
link.setToolTipText(toolTip);
link.setCursor(new Cursor(Cursor.HAND_CURSOR));
link.addMouseListener(new MouseListener()
{
public void mouseExited(MouseEvent arg0)
{
link.setText("<HTML><FONT color=\"#000099\">"+text+"</FONT></HTML>");
}
public void mouseEntered(MouseEvent arg0)
{
link.setText("<HTML><FONT color=\"#000099\"><U>"+text+"</U></FONT></HTML>");
}
public void mouseClicked(MouseEvent arg0)
{
if (Desktop.isDesktopSupported())
{
try
{
Desktop.getDesktop().browse(uri);
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
JOptionPane pane = new JOptionPane("Could not open link.");
JDialog dialog = pane.createDialog(new JFrame(), "");
dialog.setVisible(true);
}
}
public void mousePressed(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
});
return link;
}
It'll give you a JLabel that acts like a proper link.
In action:
public static void main(String[] args)
{
JFrame frame = new JFrame("Linkify Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 100);
frame.setLocationRelativeTo(null);
Container container = frame.getContentPane();
container.setLayout(new GridBagLayout());
container.add(new JLabel("Click "));
container.add(linkify("this", "http://facebook.com", "Facebook"));
container.add(new JLabel(" link to open Facebook."));
frame.setVisible(true);
}
If you'd like no tooltip just send a null.
Hope someone finds this useful! (If you do, be sure to let me know, I'd be happy to hear.)
SELECT A.ABC_ID, A.VAL FROM A WHERE NOT EXISTS
(SELECT * FROM B WHERE B.ABC_ID = A.ABC_ID AND B.VAL = A.VAL)
or
SELECT A.ABC_ID, A.VAL FROM A WHERE VAL NOT IN
(SELECT VAL FROM B WHERE B.ABC_ID = A.ABC_ID)
or
SELECT A.ABC_ID, A.VAL LEFT OUTER JOIN B
ON A.ABC_ID = B.ABC_ID AND A.VAL = B.VAL FROM A WHERE B.VAL IS NULL
Please note that these queries do not require that ABC_ID be in table B at all. I think that does what you want.
For all those who came here and did indeed use Date typed Variables, here is the solution I found. It does also apply to TypeScript.
I was facing this error because I tried to compare two dates using the following Method
var res = dat1.getTime() > dat2.getTime(); // or any other comparison operator
However Im sure I used a Date object, because Im using angularjs with typescript, and I got the data from a typed API call.
Im not sure why the error is raised, but I assume that because my Object was created by JSON deserialisation, possibly the getTime()
method was simply not added to the prototype.
In this case, recreating a date-Object based on your dates will fix the issue.
var res = new Date(dat1).getTime() > new Date(dat2).getTime()
I was right about this. Types will be cast to the according type but they wont be instanciated. Hence there will be a string cast to a date, which will obviously result in a runtime exception.
The trick is, if you use interfaces with non primitive only data such as dates or functions, you will need to perform a mapping after your http request.
class Details {
description: string;
date: Date;
score: number;
approved: boolean;
constructor(data: any) {
Object.assign(this, data);
}
}
and to perform the mapping:
public getDetails(id: number): Promise<Details> {
return this.http
.get<Details>(`${this.baseUrl}/api/details/${id}`)
.map(response => new Details(response.json()))
.toPromise();
}
for arrays use:
public getDetails(): Promise<Details[]> {
return this.http
.get<Details>(`${this.baseUrl}/api/details`)
.map(response => {
const array = JSON.parse(response.json()) as any[];
const details = array.map(data => new Details(data));
return details;
})
.toPromise();
}
For credits and further information about this topic follow the link.
I think you can normalize the row elements sum to 1 by this:
new_matrix = a / a.sum(axis=1, keepdims=1)
.
And the column normalization can be done with new_matrix = a / a.sum(axis=0, keepdims=1)
. Hope this can hep.
IN SIMPLE WORDS
USING Exclamation mark indicates that variable must consists non nil value (it never be nil)
string.Join(" ,", myArrayList.ToArray());
This will work with .net framework 4.5
Short answer is that you don't 'decrypt' the password (because it's not encrypted - it's hashed).
The long answer is that you shouldn't send the user their password by email, or any other way. If the user has forgotten their password, you should send them a password reset email, and allow them to change their password on your website.
Laravel has most of this functionality built in (see the Laravel documentation - I'm not going to replicate it all here. Also available for versions 4.2 and 5.0 of Laravel).
For further reading, check out this 'blogoverflow' post: Why passwords should be hashed.
While Migrating Android application package file (APK) to Android App Bundle (AAB), publishing app into Play Store i faced this issue and got resolved like this below...
When building .aab
file you get prompted for the location to store key export path as below:
In second image you find Encrypted key export path Location where our .pepk will store in the specific folder while generating .aab file.
Once you log in to the Google Play Console with play store credential: select your project from left side choose App Signing option Release Management>>App Signing
you will find the Google App Signing Certification window ACCEPT it.
After that you will find three radio button select **
Upload a key exported from Android Studio radio button
**, it will expand you APP SIGNING PRIVATE KEY button as below
click on the button and choose the .pepk
file (We Stored while generating .aab
file as above)
Read the all other option and submit.
Once Successfully you can go back to app release and browse the .aab file and complete RollOut...
@Ambilpura
Here was an answer baked into the default ASP.NET MVC 5 project I believe that accomplishes my styling goals nicely in the UI. Form submit using pure javascript to some containing form.
@using (Html.BeginForm("Logout", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
<a href="javascript:document.getElementById('logoutForm').submit()">
<span>Sign out</span>
</a>
}
The fully shown use case is a logout dropdown in the navigation bar of a web app.
@using (Html.BeginForm("Logout", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
@Html.AntiForgeryToken()
<div class="dropdown">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<span class="ma-nav-text ma-account-name">@User.Identity.Name</span>
<i class="material-icons md-36 text-inverse">person</i>
</button>
<ul class="dropdown-menu dropdown-menu-right ma-dropdown-tray">
<li>
<a href="javascript:document.getElementById('logoutForm').submit()">
<i class="material-icons">system_update_alt</i>
<span>Sign out</span>
</a>
</li>
</ul>
</div>
}
I'm using db2 7.1 and SQuirrel. This is the only query that worked for me.
select * from SYSIBM.tables where table_schema = 'my_schema' and table_type = 'BASE TABLE';
You can use Explicit wait or Fluent Wait
Example of Explicit Wait -
WebDriverWait wait = new WebDriverWait(WebDriverRefrence,20);
WebElement aboutMe;
aboutMe= wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("about_me")));
Example of Fluent Wait -
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(20, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement aboutMe= wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("about_me"));
}
});
Check this TUTORIAL for more details.
Swift 3 | UIDeviceOrientationDidChange Notification Observed Too Often
The following code prints "deviceDidRotate" every time your device changes orientation in 3D space - regardless of a change from portrait to landscape orientation. For example, if you hold your phone in portrait orientation and tilt it forward and backward - deviceDidRotate() is called repeatedly.
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(
self,
selector: #selector(deviceDidRotate),
name: .UIDeviceOrientationDidChange,
object: nil
)
}
func deviceDidRotate() {
print("deviceDidRotate")
}
To work around this you could hold the previous device orientation and check for a change in deviceDidRotate().
var previousDeviceOrientation: UIDeviceOrientation = UIDevice.current.orientation
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(
self,
selector: #selector(deviceDidRotate),
name: .UIDeviceOrientationDidChange,
object: nil
)
}
func deviceDidRotate() {
if UIDevice.current.orientation == previousDeviceOrientation { return }
previousDeviceOrientation = UIDevice.current.orientation
print("deviceDidRotate")
}
Or you can use a different notification that only gets called when the device changes from landscape to portrait. In this case you'd want to use the UIApplicationDidChangeStatusBarOrientation
notification.
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(
self,
selector: #selector(deviceDidRotate),
name: .UIApplicationDidChangeStatusBarOrientation,
object: nil
)
}
func deviceDidRotate() {
print("deviceDidRotate")
}
There are several answers here but none of them satisfied my below requirements:
I don't want to wait for command to finish or pollute my terminal with subprocess outputs.
I want to run bash script with redirects.
I want to support piping within my bash script (for example find ... | tar ...
).
The only combination that satiesfies above requirements is:
subprocess.Popen(['./my_script.sh "arg1" > "redirect/path/to"'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
Another solution :
create the SSH keys, type ssh-keygen -t rsa -C "[email protected]"
. This will create both id_rsa and id_rsa.pub files.
Add the id_rsa to ssh list on local computer: ssh-add ~/.ssh/id_rsa.
After generating the keys get the pubkey using :
cat ~/.ssh/id_rsa.pub
you will get something like :
cat ~/.ssh/id_rsa.pub
ssh-rsa AAAB3NzaC1yc2EAAAADAQABAAACAQCvMzmFEUPvaA1AFEBH6zGIF3N6pVE2SJv9V1MHgEwk4C7xovdk7Lr4LDoqEcqxgeJftwWQWWVrWWf7q9qCdHTAanH2Q5vx5nZjLB+B7saksehVOPWDR/MOSpVcr5bwIjf8dc8u5S8h24uBlguGkX+4lFJ+zwhiuwJlhykMvs5py1gD2hy+hvOs1Y17JPWhVVesGV3tlmtbfVolEiv9KShgkk3Hq56fyl+QmPzX1jya4TIC3k55FTzwRWBd+IpblbrGlrIBS6hvpHQpgUs47nSHLEHTn0Xmn6Q== [email protected]
copy this key (value) and go to github.com and under the setting (ssh and pgp key) add your public key.
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'TableName'
When you open a file, the system points to the beginning of the file. Any read or write you do will happen from the beginning. A seek()
operation moves that pointer to some other part of the file so you can read or write at that place.
So, if you want to read the whole file but skip the first 20 bytes, open the file, seek(20)
to move to where you want to start reading, then continue with reading the file.
Or say you want to read every 10th byte, you could write a loop that does seek(9, 1)
(moves 9 bytes forward relative to the current positions), read(1)
(reads one byte), repeat.
The most efficient and easy way:
list(data_set.to_records())
You can filter the columns you need before this call.
Use a foreach loop instead of a for loop - it solved my problem.
int j = 0;
foreach (Microsoft.Office.Interop.Word.Page p in pane.Pages)
{
var bits = p.EnhMetaFileBits;
var target = path1 +j.ToString()+ "_image.doc";
try
{
using (var ms = new MemoryStream((byte[])(bits)))
{
var image = System.Drawing.Image.FromStream(ms);
var pngTarget = Path.ChangeExtension(target, "png");
image.Save(pngTarget, System.Drawing.Imaging.ImageFormat.Png);
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
j++;
}
Here is a modification of a program that worked for me. It uses Word 2007 with the Save As PDF add-in installed. It searches a directory for .doc files, opens them in Word and then saves them as a PDF. Note that you'll need to add a reference to Microsoft.Office.Interop.Word to the solution.
using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
...
// Create a new Microsoft Word application object
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
// C# doesn't have optional arguments so we'll need a dummy value
object oMissing = System.Reflection.Missing.Value;
// Get list of Word files in specified directory
DirectoryInfo dirInfo = new DirectoryInfo(@"\\server\folder");
FileInfo[] wordFiles = dirInfo.GetFiles("*.doc");
word.Visible = false;
word.ScreenUpdating = false;
foreach (FileInfo wordFile in wordFiles)
{
// Cast as Object for word Open method
Object filename = (Object)wordFile.FullName;
// Use the dummy value as a placeholder for optional arguments
Document doc = word.Documents.Open(ref filename, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing);
doc.Activate();
object outputFileName = wordFile.FullName.Replace(".doc", ".pdf");
object fileFormat = WdSaveFormat.wdFormatPDF;
// Save document into PDF Format
doc.SaveAs(ref outputFileName,
ref fileFormat, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing);
// Close the Word document, but leave the Word application open.
// doc has to be cast to type _Document so that it will find the
// correct Close method.
object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing);
doc = null;
}
// word has to be cast to type _Application so that it will find
// the correct Quit method.
((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing);
word = null;
The 'Enter some junk value' answer didn't do the trick for me, my site was continuing to load despite the entered junk.
Instead I added the following line to the top of the .htaccess file:
deny from all
This will quickly let you know if .htaccess is being picked up or not. If the .htaccess is being used, the files in that folder won't load at all.
In case you want to add the URL parameter in JavaScript, see this answer. As suggested there, you can use the URLSeachParams
API in modern browsers as follows:
<script>
function addUrlParameter(name, value) {
var searchParams = new URLSearchParams(window.location.search)
searchParams.set(name, value)
window.location.search = searchParams.toString()
}
</script>
<body>
...
<a onclick="addUrlParameter('like', 'like')">Like this page</a>
...
</body>
In MacOS Catalina 10.15.5 the .npmrc
file path can be found at
/Users/<user-name>/.npmrc
Open in it in (for first time users, create a new file) any editor and copy-paste your token. Save it.
You are ready to go.
Note:
As mentioned by @oligofren, the command npm config ls -l
will npm configurations. You will get the .npmrc file from config parameter userconfig
I'd use inheritance. Especially if there are going to be more differences than number of holes. Especially if Gouda will need to have different set of members then Parmesan.
class Gouda(Cheese):
def __init__(self):
super(Gouda).__init__(num_holes=10)
class Parmesan(Cheese):
def __init__(self):
super(Parmesan).__init__(num_holes=15)
Use
label.setOpaque(true);
Otherwise the background is not painted, since the default of opaque
is false
for JLabel
.
From the JavaDocs:
If true the component paints every pixel within its bounds. Otherwise, the component may not paint some or all of its pixels, allowing the underlying pixels to show through.
For more information, read the Java Tutorial How to Use Labels.
Make sure you read SilverlightFox's answer. It highlights a more important reason.
The reason is mostly that if you know the source of a request you may want to customize it a little bit.
For instance lets say you have a website which has many recipes. And you use a custom jQuery framework to slide recipes into a container based on a link they click.
The link may be www.example.com/recipe/apple_pie
Now normally that returns a full page, header, footer, recipe content and ads. But if someone is browsing your website some of those parts are already loaded. So you can use an AJAX to get the recipe the user has selected but to save time and bandwidth don't load the header/footer/ads.
Now you can just write a secondary endpoint for the data like www.example.com/recipe_only/apple_pie
but that's harder to maintain and share to other people.
But it's easier to just detect that it is an ajax request making the request and then returning only a part of the data. That way the user wastes less bandwidth and the site appears more responsive.
The frameworks just add the header because some may find it useful to keep track of which requests are ajax and which are not. But it's entirely dependent on the developer to use such techniques.
It's actually kind of similar to the Accept-Language
header. A browser can request a website please show me a Russian version of this website without having to insert /ru/ or similar in the URL.
In all of the above, the EditText still needs the focusable="false"
attribute in the xml in order to prevent the keyboard from popping up.
Web API works very nicely if you accept the fact that you are using HTTP. It's when you start trying to pretend that you are sending objects over the wire that it starts to get messy.
public class TextController : ApiController
{
public HttpResponseMessage Post(HttpRequestMessage request) {
var someText = request.Content.ReadAsStringAsync().Result;
return new HttpResponseMessage() {Content = new StringContent(someText)};
}
}
This controller will handle a HTTP request, read a string out of the payload and return that string back.
You can use HttpClient to call it by passing an instance of StringContent. StringContent will be default use text/plain as the media type. Which is exactly what you are trying to pass.
[Fact]
public void PostAString()
{
var client = new HttpClient();
var content = new StringContent("Some text");
var response = client.PostAsync("http://oak:9999/api/text", content).Result;
Assert.Equal("Some text",response.Content.ReadAsStringAsync().Result);
}
If you want a command-line solution, I suggest to just go with MBO's answer.
If you're a newbie, you might like the graphical approach:
gitk
(from the command line, or right click in file browser if you have that)It's simple please follow the below step.
Right side panel you can see Theme: and drop down with following option
just select which ever you want and click on apply and Ok.
I hope this may work for you..
I misunderstood question. Sorry. for editor - File->Settings->Editor->Colors &Fonts and choose your scheme.... :)
dfsq's answer is very nice. I modified it a bit to fit my needs: I actually needed a modal for the case that, after clicking, the user would also be navigated to the corresponding page. Executing the query asynchronously is not always what one needs.
Using Blade
I created the file resources/views/includes/confirmation_modal.blade.php
:
<div class="modal fade" id="confirmation-modal" tabindex="-1" role="dialog" aria-labelledby="confirmation-modal-label" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4>{{ $headerText }}</h4>
</div>
<div class="modal-body">
{{ $bodyText }}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<form action="" method="POST" style="display:inline">
{{ method_field($verb) }}
{{ csrf_field() }}
<input type="submit" class="btn btn-danger btn-ok" value="{{ $confirmButtonText }}" />
</form>
</div>
</div>
</div>
</div>
<script>
$('#confirmation-modal').on('show.bs.modal', function(e) {
href = $(e.relatedTarget).data('href');
// change href of button to corresponding target
$(this).find('form').attr('action', href);
});
</script>
Now, using it is straight-forward:
<a data-href="{{ route('data.destroy', ['id' => $data->id]) }}" data-toggle="modal" data-target="#confirmation-modal" class="btn btn-sm btn-danger">Remove</a>
Not much changed here and the modal can be included like this:
@include('includes.confirmation_modal', ['headerText' => 'Delete Data?', 'bodyText' => 'Do you really want to delete these data? This operation is irreversible.',
'confirmButtonText' => 'Remove Data', 'verb' => 'DELETE'])
Just by putting the verb in there, it uses it. This way, CSRF is also utilized.
Helped me, maybe it helps someone else.
It is a <p>
element that creates the top margin. You removed all top margins except of that element.
For this particular purpose, $("span").show()
should be good enough.
this.$router.go()
does exactly this; if no arguments are specified, the router navigates to current location, refreshing the page.
note: current implementation of router and its history components don't mark the param as optional, but IMVHO it's either a bug or an omission on Evan You's part, since the spec explicitly allows it. I've filed an issue report about it. If you're really concerned with current TS annotations, just use the equivalent this.$router.go(0)
As to 'why is it so': go
internally passes its arguments to window.history.go
, so its equal to windows.history.go()
- which, in turn, reloads the page, as per MDN doc.
note: since this executes a "soft" reload on regular desktop (non-portable) Firefox, a bunch of strange quirks may appear if you use it but in fact you require a true reload; using the window.location.reload(true);
(https://developer.mozilla.org/en-US/docs/Web/API/Location/reload) mentioned by OP instead may help - it certainly did solve my problems on FF.
Sometimes this error also appears when you have a var or a let that hasn't been intialized.
For example
class ViewController: UIViewController {
var x: Double
// or
var y: String
// or
let z: Int
}
Depending on what your variable is supposed to do you might either set that var type as an optional or initialize it with a value like the following
class ViewController: UIViewCOntroller {
// Set an initial value for the variable
var x: Double = 0
// or an optional String
var y: String?
// or
let z: Int = 2
}
$data['title'] = $this->layout->title = 'The Home Page';
$this->layout->content = View::make('home', $data);
I've done this so far because I needed in both the view and master file. It seems if you don't use $this->layout->title it won't be available in the master layout. Improvements welcome!
The easiest way would be to delete the plugins folder. Run this command:
cordova prepare
But, before you run it, you can check each plugin's version that you think would work for your build on Cordova's plugin repository website, and then you should modify the config.xml file, manually. Use upper carrots, "^" in the version field of the universal modeling language file, "config," to indicate that you want the specified plugin to update to the latest version in the future (the next time you run the command.)
So Far, pydub
worked best for me. Modules like playsound
will also do the job, But It has only one single feature. pydub
has many features like slicing the song(file), Adjusting the volume etc...
It is as simple as slicing the lists in python.
So, When it comes to just playing, It is as shown as below.
from pydub import AudioSegment
from pydub.playback import play
path_to_file = r"Music/Harry Potter Theme Song.mp3"
song = AudioSegment.from_mp3(path_to_file)
play(song)
I think this one is a better solution:
[class*=“button-“] {
/* base button properties */
}
.button-primary { ... }
.button-plain { ... }
If you don't want to change preferences, you can optimize imports by pressing Ctrl+Option+o on Mac or Ctrl+Alt+o on Windows/Linux and this will replace all imports with single imports in current file.
I solved this issue for myself, I found there's was two files of http-client with different version of other dependent jar files. So there may version were collapsing between libraries files so remove all old/previous libraries files and re-add are jar files from lib folder of this zip file:
It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.
Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:
SQL> select * from dba_directories;
... and if not, create one
SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
SQL> grant all on directory DATA_PUMP_DIR to myuser; -- DBAs dont need this grant
Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:
$ expdp system/manager schemas=user1 dumpfile=user1.dpdmp
Or specifying a specific directory, add directory=<directory name>
:
C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR
With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:
$ exp system/manager owner=user1 file=user1.dmp
Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.
Example for American UTF8 (UNIX):
$ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8
Windows uses SET, example using Japanese UTF8:
C:\> set NLS_LANG=Japanese_Japan.AL32UTF8
More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624
import MySQLdb
class Database:
host = 'localhost'
user = 'root'
password = '123'
db = 'test'
def __init__(self):
self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db)
self.cursor = self.connection.cursor()
def insert(self, query):
try:
self.cursor.execute(query)
self.connection.commit()
except:
self.connection.rollback()
def query(self, query):
cursor = self.connection.cursor( MySQLdb.cursors.DictCursor )
cursor.execute(query)
return cursor.fetchall()
def __del__(self):
self.connection.close()
if __name__ == "__main__":
db = Database()
#CleanUp Operation
del_query = "DELETE FROM basic_python_database"
db.insert(del_query)
# Data Insert into the table
query = """
INSERT INTO basic_python_database
(`name`, `age`)
VALUES
('Mike', 21),
('Michael', 21),
('Imran', 21)
"""
# db.query(query)
db.insert(query)
# Data retrieved from the table
select_query = """
SELECT * FROM basic_python_database
WHERE age = 21
"""
people = db.query(select_query)
for person in people:
print "Found %s " % person['name']
The problem is probably that you haven't resumed from the first error. You can't throw an error from within an error handler. You should add in a resume statement, something like the following, so VBA no longer thinks you are inside the error handler:
For Each oSheet In ActiveWorkbook.Sheets
On Error GoTo NextSheet:
Set qry = oSheet.ListObjects(1).QueryTable
oCmbBox.AddItem oSheet.Name
NextSheet:
Resume NextSheet2
NextSheet2:
Next oSheet
I don't know if this already been answered correctly or not. Well. Downloading the file from the source is not the resolution. How to grab *.svg from URL.
I installed 'svg-grabber' add-on to Google Chrome. That only partially resolve my problem, as Google Chrome does not have the shortcut to 'Back' one page.
I was trying to download the files from URL, but I kept getting an error, that there are no svg files on this page when I can see 40 of them. You can click on them, so they will open, but you cannot save it.
The folder within WordPress: .../static/img/icons/
I added 'Go Back With Backspace' add-on to Chrome, as I had to click on each file separately, as if they are white icons (that I am currently looking for), you will not see them. You have to click on the file. Then back. It was taking too long. Now is fine. There is a soft to download specific folder, but I do not want to download half of the internet, to just have get a white .
When you click on a white icon, a new tab opens, but it is all white. Then you click on svg-grabber icon in Chrome and it will open it in a new window on a black background with a button download all svg.
The solution that worked for me. Delete this folder:
workspace/.metadata/.plugins/org.eclipse.e4.workbench
Just a slight addition to the above solution if you are having problem with downloaded file's name...
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");
This will return the exact file name even if it contains spaces or other characters.
I had the same issue and I found this.
On the url, it requires the server key in the end and not the api key for the app.
So Basically, you just add the server key in the end of the URL like this:
Now, to obtain the server key, just follow these steps:
1) Go to Developer Console https://code.google.com/apis/console/
2) In the Credentials, under Public API Access, Create New key
3) Select the server key from the option.
4) Enter your IP Address on the field and if you have more ip addresses, you can just add on every single line.NOTE: Enter the IP Address only when you want to use it for your testing purpose. Else leave the IP Address section blank.
5) Once you are done, click create and your new Server Key will be generated and you can then add that server key to your URL.
Last thing is that, instead of putting the sensor=true in the middle of the URL, you can add it in the end like this:
This will definitely solve the issue and just remember to use the server key for Places API
.
EDIT
I believe the web URL has changed in the past years. You can access developers console from here now - https://console.developers.google.com/apis/dashboard
Hope this answer will help you and other viewers. Good Luck .. :)
Java has 5 different boolean compare operators: &, &&, |, ||, ^
& and && are "and" operators, | and || "or" operators, ^ is "xor"
The single ones will check every parameter, regardless of the values, before checking the values of the parameters.
The double ones will first check the left parameter and its value and if true
(||
) or false
(&&
) leave the second one untouched.
Sound compilcated? An easy example should make it clear:
Given for all examples:
String aString = null;
AND:
if (aString != null & aString.equals("lala"))
Both parameters are checked before the evaluation is done and a NullPointerException will be thrown for the second parameter.
if (aString != null && aString.equals("lala"))
The first parameter is checked and it returns false
, so the second paramter won't be checked, because the result is false
anyway.
The same for OR:
if (aString == null | !aString.equals("lala"))
Will raise NullPointerException, too.
if (aString == null || !aString.equals("lala"))
The first parameter is checked and it returns true
, so the second paramter won't be checked, because the result is true
anyway.
XOR can't be optimized, because it depends on both parameters.
If HEAD isn't set (i.e., you have no commits yet, but you don't want to just blow away .git
because you've already set up other repo config you want to keep), you can also do
git rm -rf --cached .
to unstage everything. This is effectively the same as sehe's solution, but avoids mucking with Git internals.
What is the difference between abstract class and interface in Python?
An interface, for an object, is a set of methods and attributes on that object.
In Python, we can use an abstract base class to define and enforce an interface.
For example, say we want to use one of the abstract base classes from the collections
module:
import collections
class MySet(collections.Set):
pass
If we try to use it, we get an TypeError
because the class we created does not support the expected behavior of sets:
>>> MySet()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class MySet with abstract methods
__contains__, __iter__, __len__
So we are required to implement at least __contains__
, __iter__
, and __len__
. Let's use this implementation example from the documentation:
class ListBasedSet(collections.Set):
"""Alternate set implementation favoring space over speed
and not requiring the set elements to be hashable.
"""
def __init__(self, iterable):
self.elements = lst = []
for value in iterable:
if value not in lst:
lst.append(value)
def __iter__(self):
return iter(self.elements)
def __contains__(self, value):
return value in self.elements
def __len__(self):
return len(self.elements)
s1 = ListBasedSet('abcdef')
s2 = ListBasedSet('defghi')
overlap = s1 & s2
We can create our own Abstract Base Class by setting the metaclass to abc.ABCMeta
and using the abc.abstractmethod
decorator on relevant methods. The metaclass will be add the decorated functions to the __abstractmethods__
attribute, preventing instantiation until those are defined.
import abc
For example, "effable" is defined as something that can be expressed in words. Say we wanted to define an abstract base class that is effable, in Python 2:
class Effable(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def __str__(self):
raise NotImplementedError('users must define __str__ to use this base class')
Or in Python 3, with the slight change in metaclass declaration:
class Effable(object, metaclass=abc.ABCMeta):
@abc.abstractmethod
def __str__(self):
raise NotImplementedError('users must define __str__ to use this base class')
Now if we try to create an effable object without implementing the interface:
class MyEffable(Effable):
pass
and attempt to instantiate it:
>>> MyEffable()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class MyEffable with abstract methods __str__
We are told that we haven't finished the job.
Now if we comply by providing the expected interface:
class MyEffable(Effable):
def __str__(self):
return 'expressable!'
we are then able to use the concrete version of the class derived from the abstract one:
>>> me = MyEffable()
>>> print(me)
expressable!
There are other things we could do with this, like register virtual subclasses that already implement these interfaces, but I think that is beyond the scope of this question. The other methods demonstrated here would have to adapt this method using the abc
module to do so, however.
We have demonstrated that the creation of an Abstract Base Class defines interfaces for custom objects in Python.
The best method would be using some JSON library, e.g. Jackson ( http://jackson.codehaus.org ).
But if this is not an option simply escape msget before adding it to your string:
The wrong way to do this is
String msgetEscaped = msget.replaceAll("\"", "\\\"");
Either use (as recommended in the comments)
String msgetEscaped = msget.replace("\"", "\\\"");
or
String msgetEscaped = msget.replaceAll("\"", "\\\\\"");
A sample with all three variants can be found here: http://ideone.com/Nt1XzO
You can turn on your PHP errors with error_reporting
:
error_reporting(E_ALL);
ini_set('display_errors', 'on');
Edit: It's possible that even after putting this, errors still don't show up. This can be caused if there is a fatal error in the script. From PHP Runtime Configuration:
Although display_errors may be set at runtime (with ini_set()), it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.
You should set display_errors = 1
in your php.ini
file and restart the server.
this is the code for set method
public void setAge(int age){
this.age = age;
}
Using the PHPExcel library to read an Excel file and transfer the data into a database
// Include PHPExcel_IOFactory
include 'PHPExcel/IOFactory.php';
$inputFileName = './sampleData/example1.xls';
// Read your Excel workbook
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
// Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++){
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
// Insert row data array into your database of choice here
}
Anything more becomes very dependent on your database, and how you want the data structured in it
You can still use the Screen class from a WPF app. You just need to reference the System.Windows.Forms assembly from your application. Once you've done that, (and referenced System.Drawing for the example below):
Rectangle workingArea = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;
...works just fine.
Have you considered setting your main window property WindowStartupLocation to CenterScreen?
I'd suggest that the -i
means it does match "ABC", but the difference is in the output. -i
doesn't manipulate the input, so it won't change "ABC" to "abc" because you specified "abc" as the pattern. -o
says it only shows the part of the output that matches the pattern specified, it doesn't say about matching input.
The output of echo "ABC" | grep -i abc
is ABC
, the -o
shows output matching "abc" so nothing shows:
Naos:~ mattlacey$ echo "ABC" | grep -i abc | grep -o abc
Naos:~ mattlacey$ echo "ABC" | grep -i abc | grep -o ABC
ABC
you can remove any package just by typing follwing command in terminal, and just remove the providers and alias you provided at the time of installing the package, if any and update the composer,
composer remove vendor/your_package_name
composer update
The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.
The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.
For pushing a single tag: git push <reponame> <tagname>
For instance, git push production 1.0.0
. Tags are not bound to branches, they are bound to commits.
When you want to have the tag's content in the master branch, do that locally on your machine. I would assume that you continued developing in your local master branch. Then just a git push origin master
should suffice.
The code below does the same thing as centering in the Interface Builder.
override func viewDidLoad() {
super.viewDidLoad()
// set up the view
let myView = UIView()
myView.backgroundColor = UIColor.blue
myView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(myView)
// Add code for one of the constraint methods below
// ...
}
Method 1: Anchor Style
myView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
myView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
Method 2: NSLayoutConstraint Style
NSLayoutConstraint(item: myView, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint
Style, however it is only available from iOS 9, so if you are supporting iOS 8 then you should still use NSLayoutConstraint
Style.To automate the answer of @Jordan S. Jones at WIN/DOS command-line,
Put this in a batch file named: getmns.bat (get mail name server):
@echo off
if @%1==@ goto USAGE
echo set type=MX>mnscmd.txt
echo %1>>mnscmd.txt
echo exit>>mnscmd.txt
nslookup<mnscmd.txt>mnsresult.txt
type mnsresult.txt
del mnsresult.txt
goto END
:USAGE
echo usage:
echo %0 domainname.ext
:END
echo.
For example:
getmns google.com
output:
google.com MX preference = 20, mail exchanger = alt1.aspmx.l.google.com
google.com MX preference = 10, mail exchanger = aspmx.l.google.com
google.com MX preference = 50, mail exchanger = alt4.aspmx.l.google.com
google.com MX preference = 40, mail exchanger = alt3.aspmx.l.google.com
google.com MX preference = 30, mail exchanger = alt2.aspmx.l.google.com
alt4.aspmx.l.google.com internet address = 74.125.25.27
alt3.aspmx.l.google.com internet address = 173.194.72.27
aspmx.l.google.com internet address = 173.194.65.27
alt1.aspmx.l.google.com internet address = 74.125.200.27
alt2.aspmx.l.google.com internet address = 64.233.187.27
For example to pipe the result again into a file do:
getmns google.com > google.mns.txt
:-D
LastOrDefault()
is usually not working but with the Tolist()
it will work. There is no need to use OrderByDescending
use Tolist()
like this.
GroupBy(p => p.Nws_ID).ToList().LastOrDefault();
Please Follow this process
First of all install git bash and create a repository on git
1) Go to working directory where the file exist which you want to push on remote and create .git folder by
$ git init
2) Add the files in your new local repository.
$ git add .
Note: while you are in same folder make sure you have placed dot after command if you putting path or not putting dot that will create ambiguity
3) Commit the files that you've staged in your local repository.
$ git commit -m "First commit"**
4) after this go to git repository and copy remote URL
$ git remote add origin *remote repository URL
5)
$ git remote -v
Note: this will ask for user.email and user.name just put it as per config
6)
$ git push origin master
this will push whole committed code to FILE.git on repository
And I think we done
Answering my own question after 5 years as i feel it still need more details
Abstraction:
Technical Definition :- Abstraction is a concept to hide unnecessary details(complex or simple) and only show the essential features of the object. There is no implementaion here its just an concept
What it means practically:- When i say my company needs some medium/device so that employees can connect to customer . This is the purest form of abstaction(like interface in java) as that device/medium can be phone or internet or skype or in person or email etc. I am not going into nitty gritty of device/medium
Even when i say my company needs some medium/device so that employees can connect to customer through voice call. Then also i am talking abstract but at bit lower level as device/medium can be phone or skype or something else etc
Now when i say my company needs some phone so that employees can connect to customer through voice call. Then also i am talking abstract but at bit lower level as phone can be of any company like iphone or samsung or nokia etc
Encapsulation:- Its basically about hiding the state(information) of object with the help of modifiers like private,public,protected etc. we expose the state thru public methods only if require.
What it means practically:- Now when i say my company needs some iphone so that employees can connect to customer through voice call.Now i am talking about some concrete object(like iphone). Even though i am not going into nitty gritty of iphone here too but iphone has some state/concrecrete info/implementation associated with it where device/medium does not have. When i say concrete object, actually it means any object which has some(not complete like java abstract class) implementation/info associated with it.
So iphone actually used here encapsulation as strategy to hide its state/information and expose only the ones which it think should be exposed. So both abstraction and encapsulation hides some unnecessary details but abstraction at the concept level and encapsulation actually at implementation level
This is the gist based on answers in this post and below ones
How can I push my tag to the remote repository so that all client computers can see it?
Run this to push mytag
to your git origin (eg: GitHub or GitLab)
git push origin refs/tags/mytag
It's better to use the full "refspec" as shown above (literally refs/tags/mytag
) just in-case mytag
is actually v1.0.0
and is ambiguous (eg: because there's a branch also named v1.0.0
).
when you make it Gone every time of compilation of program the component gets initialized that means you are removing the component from layout and when you make it invisible the component it will take the same space in the layout but every time you dont need to initialize it.
if you set Visibility=Gone then you have to initialize the component..like
eg Button _mButton = new Button(this);
_mButton = (Button)findViewByid(R.id.mButton);
so it will take more time as compared to Visibility = invisible.
In XML there can be only one root element - you have two - heading
and song
.
If you restructure to something like:
<?xml version="1.0" encoding="UTF-8"?>
<song>
<heading>
The Twelve Days of Christmas
</heading>
....
</song>
The error about well-formed XML on the root level should disappear (though there may be other issues).
Use ver
it will list all the installed toolboxes and versions of the toolbox.
A standard prolog predicate will do this.
isfive(5).
will evaluate to true if you call it with 5 and fail(return false) if you run it with anything else. For not equal you use \=
isNotEqual(A,B):- A\=B.
Technically it is does not unify, but it is similar to not equal.
Learn Prolog Now is a good website for learning prolog.
Edit: To add another example.
isEqual(A,A).
My SQL teacher said that if you specify both a DEFAULT
value and NOT NULL
or NULL
, DEFAULT
should always be expressed before NOT NULL
or NULL
.
Like this:
ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT "MyDefault" NOT NULL
ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT "MyDefault" NULL
If you are using Anaconda you should add the Anaconda path.
new_path = 'C:/Users/.../Anaconda/Library/etc/haarcascades/'
face_cascade = cv2.CascadeClassifier(new_path + 'haarcascade_frontalface_default.xml')
Use array_unshift() to insert the first element in an array.
User array_shift() to removes the first element of an array.
jsdom is too strict to do any real screen scraping sort of things, but beautifulsoup doesn't choke on bad markup.
node-soupselect is a port of python's beautifulsoup into nodejs, and it works beautifully
Please forgive me if I'm wrong. And I have to admit upfront that I haven't done any research on these 2 terms. Anyway...
Emulation is to mimic something with detailed known results, whatever the internal behaviors actually are. We only try to get things done and don't care much about what goes on inside.
Simulation, on the other hand, is to mimic something with some known behaviors to study something not being known yet.
my 2cents
One alternative would be to parse with yq (https://github.com/kislyuk/yq) like so:
cat pom.xml | xq -r '.project.version'
Notice the executable is xq not yq
To get xq, install yq like so pip install yq
To use border radius I have a border radius of 20px in the table, and then put the border radius on the first child of the table header (th) and the last child of the table header.
table {
border-collapse: collapse;
border-radius:20px;
padding: 10px;
}
table th:first-child {
/* border-radius = top left, top right, bottom right, bottom left */
border-radius: 20px 0 0 0; /* curves the top left */
padding-left: 15px;
}
table th:last-child {
border-radius: 0 20px 0 0; /* curves the top right */
}
This however will not work if this is done with table data (td) because it will add a curve onto each table row. This is not a problem if you only have 2 rows in your table but any additional ones will add curves onto the inner rows too. You only want these curves on the outside of the table. So for this, add an id to your last row. Then you can apply the curves to them.
/* curves the first tableData in the last row */
#lastRow td:first-child {
border-radius: 0 0 0 20px; /* bottom left curve */
}
/* curves the last tableData in the last row */
#lastRow td:last-child {
border-radius: 0 0 20px 0; /* bottom right curve */
}
The good news is if you have installed python3.4, pyvenv is already been installed. So, Just
pyvenv project_dir
source project_dir/bin/activate
python --version
python 3.4.*
Now in this virtual env, you can use pip to install modules for this project.
Leave this virtual env , just
deactivate
RemoteSigned: all scripts you created yourself will be run, and all scripts downloaded from the Internet will need to be signed by a trusted publisher.
OK, change the policy by simply typing:
Set-ExecutionPolicy RemoteSigned
Note the output while doing the merge - it is saying Fast Forward
In such situations, you want to do:
git merge v1.0 --no-commit --no-ff
import os, sys, re, glob
pattern = re.compile(r"\<\[\d\>")
replacementStringMatchesPattern = "<[1>"
for infile in glob.glob(os.path.join(os.getcwd(), '*.txt')):
for line in reader:
retline = pattern.sub(replacementStringMatchesPattern, "", line)
sys.stdout.write(retline)
print (retline)
Answer by @Ben proved to be useful for me. But I needed to check the product version as it was the main increment happening in my software and followed semantic versioning.
myFileVersionInfo.ProductVersion
This method met my expectations
Update: Instead of explicitly mentioning dll path in program (as needed in production version), we can get product version using Assembly.
Assembly assembly = Assembly.GetExecutingAssembly();
FileVersionInfo fileVersionInfo =FileVersionInfo.GetVersionInfo(assembly.Location);
string ProdVersion= fileVersionInfo.ProductVersion;
Based on your comment it looks like your'e only adding the new column if: mysql_query("SELECT * FROM assessment");
returns false. That's probably not what you wanted. Try removing the '!' on front of $sql in the first 'if' statement. So your code will look like:
$sql=mysql_query("SELECT * FROM assessment");
if ($sql) {
mysql_query("ALTER TABLE assessment ADD q6 INT(1) NOT NULL AFTER q5");
echo 'Q6 created';
}else...
.help will show you all the options. Do .exit in this case
File one:
angular.module('myApp.controllers', []);
File two:
angular.module('myApp.controllers').controller('Ctrl1', ['$scope', '$http', function($scope, $http){
}]);
File three:
angular.module('myApp.controllers').controller('Ctrl2', ['$scope', '$http', function($scope, $http){
}]);
Include in that order. I recommend 3 files so the module declaration is on its own.
As for folder structure there are many many many opinions on the subject, but these two are pretty good
I see 2 easy options:
gradient option:
html {
min-height:100%;
background:linear-gradient(0deg, rgba(255, 0, 150, 0.3), rgba(255, 0, 150, 0.3)), url(http://lorempixel.com/800/600/nature/2);
background-size:cover;
}
shadow option:
html {
min-height:100%;
background:url(http://lorempixel.com/800/600/nature/2);
background-size:cover;
box-shadow:inset 0 0 0 2000px rgba(255, 0, 150, 0.3);
}
an old codepen of mine with few examples
a third option
The
background-blend-mode
CSS property sets how an element's background images should blend with each other and with the element's background color.
html {
min-height:100%;
background:url(http://lorempixel.com/800/600/nature/2) rgba(255, 0, 150, 0.3);
background-size:cover;
background-blend-mode: multiply;
}
@FunctionalInterface
annotation is useful for compilation time checking of your code. You cannot have more than one method besides static
, default
and abstract methods that override methods in Object
in your @FunctionalInterface
or any other interface used as a functional interface.
But you can use lambdas without this annotation as well as you can override methods without @Override
annotation.
From docs
a functional interface has exactly one abstract method. Since default methods have an implementation, they are not abstract. If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere
This can be used in lambda expression:
public interface Foo {
public void doSomething();
}
This cannot be used in lambda expression:
public interface Foo {
public void doSomething();
public void doSomethingElse();
}
But this will give compilation error:
@FunctionalInterface
public interface Foo {
public void doSomething();
public void doSomethingElse();
}
Invalid '@FunctionalInterface' annotation; Foo is not a functional interface
I solved this problem using the JPA JAR from Maven repository, adding it on the build path of project.
How to launch a process (such as a bat file, perl script, console program) and have its standard output displayed on a windows form:
processCaller = new ProcessCaller(this);
//processCaller.FileName = @"..\..\hello.bat";
processCaller.FileName = @"commandline.exe";
processCaller.Arguments = "";
processCaller.StdErrReceived += new DataReceivedHandler(writeStreamInfo);
processCaller.StdOutReceived += new DataReceivedHandler(writeStreamInfo);
processCaller.Completed += new EventHandler(processCompletedOrCanceled);
processCaller.Cancelled += new EventHandler(processCompletedOrCanceled);
// processCaller.Failed += no event handler for this one, yet.
this.richTextBox1.Text = "Started function. Please stand by.." + Environment.NewLine;
// the following function starts a process and returns immediately,
// thus allowing the form to stay responsive.
processCaller.Start();
You can find ProcessCaller
on this link: Launching a process and displaying its standard output
SELECT * FROM Table_name Where Month(date)='10' && YEAR(date)='2016';
Either make an account on the Nuget.org website, then log in, browse to the package you want and click on the Download link on the left menu.
Or guess the URL. They have the following format:
https://www.nuget.org/api/v2/package/{packageID}/{packageVersion}
Then simply unzip the .nupkg file and extract the contents you need.
You can do this with a single call, like so:
scanf( "%i %i %i %i", &minx, &maxx, &miny, &maxy);
You can do this with git rebase -i
, passing in the revision that you want to use as the 'root':
git rebase -i origin/master
will open an editor window showing all of the commits you have made after the last commit in origin/master
. You can reject commits, squash commits into a single commit, or edit previous commits.
There are a few resources that can probably explain this in a better way, and show some other examples:
http://book.git-scm.com/4_interactive_rebasing.html
and
http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html
are the first two good pages I could find.
Use the following
SELECT timestamp, value, card
FROM my_table
ORDER BY timestamp DESC
LIMIT 1
Never ever choose a fixed pivot - this can be attacked to exploit your algorithm's worst case O(n2) runtime, which is just asking for trouble. Quicksort's worst case runtime occurs when partitioning results in one array of 1 element, and one array of n-1 elements. Suppose you choose the first element as your partition. If someone feeds an array to your algorithm that is in decreasing order, your first pivot will be the biggest, so everything else in the array will move to the left of it. Then when you recurse, the first element will be the biggest again, so once more you put everything to the left of it, and so on.
A better technique is the median-of-3 method, where you pick three elements at random, and choose the middle. You know that the element that you choose won't be the the first or the last, but also, by the central limit theorem, the distribution of the middle element will be normal, which means that you will tend towards the middle (and hence, nlog(n) time).
If you absolutely want to guarantee O(nlog(n)) runtime for the algorithm, the columns-of-5 method for finding the median of an array runs in O(n) time, which means that the recurrence equation for quicksort in the worst case will be:
T(n) = O(n) (find the median) + O(n) (partition) + 2T(n/2) (recurse left and right)
By the Master Theorem, this is O(nlog(n)). However, the constant factor will be huge, and if worst case performance is your primary concern, use a merge sort instead, which is only a little bit slower than quicksort on average, and guarantees O(nlog(n)) time (and will be much faster than this lame median quicksort).
Import datetime and timedelta:
>>> from datetime import datetime, timedelta
>>> str(datetime.now() + timedelta(hours=9))[11:19]
'01:41:44'
But the better way is:
>>> (datetime.now() + timedelta(hours=9)).strftime('%H:%M:%S')
'01:42:05'
You can refer strptime
and strftime
behavior to better understand how python processes dates and time field
echo [string] | sed "s/[original]/[target]/g"
For subsections it's as easy as leveraging strings in ng-include:
<ul id="subNav">
<li><a ng-click="subPage='section1/subpage1.htm'">Sub Page 1</a></li>
<li><a ng-click="subPage='section1/subpage2.htm'">Sub Page 2</a></li>
<li><a ng-click="subPage='section1/subpage3.htm'">Sub Page 3</a></li>
</ul>
<ng-include src="subPage"></ng-include>
Or you can create an object in case you have links to sub pages all over the place:
$scope.pages = { page1: 'section1/subpage1.htm', ... };
<ul id="subNav">
<li><a ng-click="subPage='page1'">Sub Page 1</a></li>
<li><a ng-click="subPage='page2'">Sub Page 2</a></li>
<li><a ng-click="subPage='page3'">Sub Page 3</a></li>
</ul>
<ng-include src="pages[subPage]"></ng-include>
Or you can even use $routeParams
$routeProvider.when('/home', ...);
$routeProvider.when('/home/:tab', ...);
$scope.params = $routeParams;
<ul id="subNav">
<li><a href="#/home/tab1">Sub Page 1</a></li>
<li><a href="#/home/tab2">Sub Page 2</a></li>
<li><a href="#/home/tab3">Sub Page 3</a></li>
</ul>
<ng-include src=" '/home/' + tab + '.html' "></ng-include>
You can also put an ng-controller at the top-most level of each partial
I would recommend keeping the object you have, and just utilizing the properties that you want, rather than removing the resolution you already have.
If you want to print it in a certain format you may want to look at this...That way you can preserve your resolution further down the line.
That being said you can create a new DateTime
object using only the properties you want as @romkyns has in his answer.
With Javascript you can get full size profile images like this
pass your accessToken
to the getface()
function from your FB.init
call
function getface(accessToken){
FB.api('/me/friends', function (response) {
for (id in response.data) {
var homie=response.data[id].id
FB.api(homie+'/albums?access_token='+accessToken, function (aresponse) {
for (album in aresponse.data) {
if (aresponse.data[album].name == "Profile Pictures") {
FB.api(aresponse.data[album].id + "/photos", function(aresponse) {
console.log(aresponse.data[0].images[0].source);
});
}
}
});
}
});
}
Using the latest 7.x Tomcat (currently 7.0.69) solved the problem for me.
We did also try a workaround in a old eclipse bug, maybe that did it's part to solve the problem, too?
https://bugs.eclipse.org/bugs/show_bug.cgi?id=67414
Workaround:
There is a minimal amount of "default" buffer when you startup a 'screen' session within your 'putty session'. I use screens a lot in my work, so I can tell you that you will not have a combination of 'screen' buffer & 'putty' buffer within your 'screen' session.
Setting the default number of scrollback lines by adding defscrollback 10000
to your ~/.screenrc
file is the correct solution.
By the way, I use "defscrollback 200000" in my ./screenrc
file.
You can't declare multiple types in the initialization, but you can assign to multiple types E.G.
{
int i;
char x;
for(i = 0, x = 'p'; ...){
...
}
}
Just declare them in their own scope.
In the "creative but confusing category" I offer:
int isOdd(int n) { return n ^ n * n ? isOdd(n * n) : n; }
A variant on this theme that is specific to Microsoft C++:
__declspec(naked) bool __fastcall isOdd(const int x)
{
__asm
{
mov eax,ecx
mul eax
mul eax
mul eax
mul eax
mul eax
mul eax
ret
}
}
As always, read Bootstrap's great documentation:
3.x Docs: https://getbootstrap.com/docs/3.3/css/#grid-nesting
Make sure the parent level row is inside of a .container
element. Whenever you'd like to nest rows, just open up a new .row
inside of your column.
Here's a simple layout to work from:
<div class="container">
<div class="row">
<div class="col-xs-6">
<div class="big-box">image</div>
</div>
<div class="col-xs-6">
<div class="row">
<div class="col-xs-6"><div class="mini-box">1</div></div>
<div class="col-xs-6"><div class="mini-box">2</div></div>
<div class="col-xs-6"><div class="mini-box">3</div></div>
<div class="col-xs-6"><div class="mini-box">4</div></div>
</div>
</div>
</div>
</div>
4.0 Docs: http://getbootstrap.com/docs/4.0/layout/grid/#nesting
Here's an updated version for 4.0, but you should really read the entire docs section on the grid so you understand how to leverage this powerful feature
<div class="container">
<div class="row">
<div class="col big-box">
image
</div>
<div class="col">
<div class="row">
<div class="col mini-box">1</div>
<div class="col mini-box">2</div>
</div>
<div class="row">
<div class="col mini-box">3</div>
<div class="col mini-box">4</div>
</div>
</div>
</div>
</div>
Which will look like this (with a little bit of added styling):
If anyone wants AutoClosingMessageBox in c++ I have implemented the equivalent code here is the link to gists
static intptr_t MessageBoxHookProc(int nCode, intptr_t wParam, intptr_t lParam)
{
if (nCode < 0)
return CallNextHookEx(hHook, nCode, wParam, lParam);
auto msg = reinterpret_cast<CWPRETSTRUCT*>(lParam);
auto hook = hHook;
//Hook Messagebox on Initialization.
if (!hookCaption.empty() && msg->message == WM_INITDIALOG)
{
int nLength = GetWindowTextLength(msg->hwnd);
char* text = new char[captionLen + 1];
GetWindowText(msg->hwnd, text, captionLen + 1);
//If Caption window found Unhook it.
if (hookCaption == text)
{
hookCaption = string("");
SetTimer(msg->hwnd, (uintptr_t)timerID, hookTimeout, (TIMERPROC)hookTimer);
UnhookWindowsHookEx(hHook);
hHook = 0;
}
}
return CallNextHookEx(hook, nCode, wParam, lParam);
}
To be sure, you need to not only replace the single quotes, but as well the already escaped ones:
"first ' and \' second".replace(/'|\\'/g, "\\'")
For hints, look closer at the class name name that throws an error and the line number, example: Compilation failure [ERROR] \applications\xxxxx.java:[44,30] error: cannot find symbol
One other cause is unsupported method of for java version say jdk7 vs 8. Check your %JAVA_HOME%
For future readers who need this answer quickly:
2^31-1 = 2.147.483.647 characters
As this has already been properly answered, I'd just add the following site as a reference:
You can search for "check", for example.
For example, like this:
const querystring = require('querystring');
const https = require('https');
var postData = querystring.stringify({
'msg' : 'Hello World!'
});
var options = {
hostname: 'posttestserver.com',
port: 443,
path: '/post.php',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
var req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (e) => {
console.error(e);
});
req.write(postData);
req.end();
:(){ :|:& };:
This fork bomb will cause havoc to the CPU and will likely crash your computer.
I was facing same issue. I tried everything possible for a day, but nothing worked. The dependency which was causing problem was using lower compile sdk, target sdk and min sdk. I created library module for the project, copied all the sources and matched the sdk versions with application sdk versions. And finally it worked like a charm.
One solution is like, If you know the specific lat/lng.
google.maps.event.addListener(map, 'idle', function() {
map.setCenter(new google.maps.LatLng(latitude, longitude));
map.setZoom(8);
});
If don't have specific lat/lng
google.maps.event.addListener(map, 'idle', function() {
map.setCenter(map.getCenter());
map.setZoom(8);
});
or
google.maps.event.addListener(map, 'idle', function() {
var bounds = new google.maps.LatLngBounds();
map.setCenter(bounds.getCenter());
map.setZoom(8);
});
We can expand this solution using LiveData
:
class AppForegroundStateLiveData : LiveData<AppForegroundStateLiveData.State>() {
private var lifecycleListener: LifecycleObserver? = null
override fun onActive() {
super.onActive()
lifecycleListener = AppLifecycleListener().also {
ProcessLifecycleOwner.get().lifecycle.addObserver(it)
}
}
override fun onInactive() {
super.onInactive()
lifecycleListener?.let {
this.lifecycleListener = null
ProcessLifecycleOwner.get().lifecycle.removeObserver(it)
}
}
internal inner class AppLifecycleListener : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onMoveToForeground() {
value = State.FOREGROUND
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onMoveToBackground() {
value = State.BACKGROUND
}
}
enum class State {
FOREGROUND, BACKGROUND
}
}
Now we can subscribe to this LiveData and catch the needed events. For example:
appForegroundStateLiveData.observeForever { state ->
when(state) {
AppForegroundStateLiveData.State.FOREGROUND -> { /* app move to foreground */ }
AppForegroundStateLiveData.State.BACKGROUND -> { /* app move to background */ }
}
}
you could also use display: table
insted of tables. Divs are way more flexible than tables.
Example:
.table {_x000D_
display: table;_x000D_
border-collapse: collapse;_x000D_
}_x000D_
_x000D_
.table .table-row {_x000D_
display: table-row;_x000D_
}_x000D_
_x000D_
.table .table-cell {_x000D_
display: table-cell;_x000D_
text-align: left;_x000D_
vertical-align: top;_x000D_
border: 1px solid black;_x000D_
}
_x000D_
<div class="table">_x000D_
<div class="table-row">_x000D_
<div class="table-cell">test</div>_x000D_
<div class="table-cell">test1123</div>_x000D_
</div>_x000D_
<div class="table-row">_x000D_
<div class="table-cell">test</div>_x000D_
<div class="table-cell">test123</div>_x000D_
</div>_x000D_
</div>
_x000D_
With Groovy, you don't need the includes, and can just do:
String oldDate = '04-DEC-2012'
Date date = Date.parse( 'dd-MMM-yyyy', oldDate )
String newDate = date.format( 'M-d-yyyy' )
println newDate
To print:
12-4-2012
We can pass multiple parameters with var_dump like:
var_dump("array1",$array1,"array2",$array2);
Perhaps the console is clearing. Try:
Console.WriteLine("Test");
Console.ReadLine();
And it will hopefully stay there until you press enter.
You can do str.replace(str[0], str[0].toUpperCase())
.
Check this example:
let str = "hello, WORLD!"
let newStr = str.replace(str[0], str[0].toUpperCase())
console.log("str: ", str)
console.log("newStr: ", newStr)
_x000D_
For the problem you're having about the batch file asking the user if the destination is a folder or file, if you know the answer in advance, you can do as such:
If destination is a file: echo f | [batch file path]
If folder: echo d | [batch file path]
It will essentially just pipe the letter after "echo" to the input of the batch file.
From Laravel 5.5 on you can use an artisan command to create a new Rule which you can code regarding your requirements to decide whether it passes or fail.
Ej:
php artisan make:rule PhoneNumber
Then edit app/Rules/PhoneNumber.php
, on method passes
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
return preg_match('%^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$%i', $value) && strlen($value) >= 10;
}
Then, use this Rule as you usually would do with the validation:
use App\Rules\PhoneNumber;
$request->validate([
'name' => ['required', new PhoneNumber],
]);
If you mean what ports are listening, you can open a command prompt and write:
netstat
You can write:
netstat /?
for an explanation of all options.
You should be able to create a customize UI button programmatically by accessing the titleLabel property of UIButton.
Per Class Reference in Swift: Regarding the titleLabel property, it says that "although this property is read-only, its own properties are read/write. Use these properties primarily to configure the text of the button."
In Swift, you can directly modify the properties of titleLabel like such:
let myFirstButton = UIButton()
myFirstButton.titleLabel!.text = "I made a label on the screen #toogood4you"
myFirstButton.titleLabel!.font = UIFont(name: "MarkerFelt-Thin", size: 45)
myFirstButton.titleLabel!.textColor = UIColor.red
myFirstButton.titleLabel!.textAlignment = .center
myFirstButton.titleLabel!.numberOfLines = 5
myFirstButton.titleLabel!.frame = CGRect(x: 15, y: 54, width: 300, height: 500)
Edit
Swift 3.1 Syntax