To get the value from the servlet from POST
command, you can follow the approach as explained on this post by using request.getParameter(key)
format which will return the value you want.
I prefer to use WebClient, it seems to handle SSL transparently:
http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx
Some troubleshooting help here:
Here is a late answer, just for simplistic approach using Int()
and If
in case of 1-3 character columns:
Function outColLetterFromNumber(i As Integer) As String
If i < 27 Then 'one-letter
col = Chr(64 + i)
ElseIf i < 677 Then 'two-letter
col = Chr(64 + Int(i / 26)) & Chr(64 + i - (Int(i / 26) * 26))
Else 'three-letter
col = Chr(64 + Int(i / 676)) & Chr(64 + Int(i - Int(i / 676) * 676) / 26)) & Chr(64 + i - (Int(i - Int(i / 676) * 676) / 26) * 26))
End If
outColLetterFromNumber = col
End Function
Try wrapping your entire select in brackets, then running a count(*) on that
select count(*)
from
(
select m.id
from Monitor as m
inner join Monitor_Request as mr
on mr.Company_ID=m.Company_id group by m.Company_id
having COUNT(m.Monitor_id)>=5
) myNewTable
Retrieve profile information for a signed-in user Use the GoogleSignInResult.getSignInAccount method to request profile information for the currently signed in user. You can call the getSignInAccount method after the sign-in intent succeeds.
GoogleSignInResult result =
Auth.GoogleSignInApi.getSignInResultFromIntent(data);
GoogleSignInAccount acct = result.getSignInAccount();
String personName = acct.getDisplayName();
String personGivenName = acct.getGivenName();
String personFamilyName = acct.getFamilyName();
String personEmail = acct.getEmail();
String personId = acct.getId();
Uri personPhoto = acct.getPhotoUrl();
You have to convert the type of your return value of the method to the Generic type which you pass to the method during calling.
public static T values<T>()
{
Random random = new Random();
int number = random.Next(1, 4);
return (T)Convert.ChangeType(number, typeof(T));
}
You need pass a type that is type casteable for the value you return through that method.
If you would want to return a value which is not type casteable to the generic type you pass, you might have to alter the code or make sure you pass a type that is casteable for the return value of method. So, this approach is not reccomended.
A predicate in T is a delegate that takes in a T and returns a bool. List<T>.RemoveAll will remove all elements in a list where calling the predicate returns true. The easiest way to supply a simple predicate is usually a lambda expression, but you can also use anonymous methods or actual methods.
{
List<Vehicle> vehicles;
// Using a lambda
vehicles.RemoveAll(vehicle => vehicle.EnquiryID == 123);
// Using an equivalent anonymous method
vehicles.RemoveAll(delegate(Vehicle vehicle)
{
return vehicle.EnquiryID == 123;
});
// Using an equivalent actual method
vehicles.RemoveAll(VehiclePredicate);
}
private static bool VehiclePredicate(Vehicle vehicle)
{
return vehicle.EnquiryID == 123;
}
If I remember correctly, you'll need to set the netbeans_jdkhome
property in your netbeans config file. Should be in your etc/netbeans.conf
file.
In android studio version 4.0 (WINDOWS), I could find the solution by just checking android studio welcome screen and clicking on the "Events" dropdown AFTER trying to launch the emulator (hence after getting the error):
the events section clearly shows that ANDROID_SDK_ROOT was not set in my system.
In a nutshell, whenever you see such error when starting the emulator, just check the "events" section in the welcome to android studio screen to find the real problem.
Beware that if ANDROID_HOME is not set properly, it will still tell you that ANDROID_SDK_ROOT is broken.
This error occurs when the syntax of connection string is not valid.
You can use the connection string as
'jdbc:derby:MyDbTest;create=true'
or
you can use the following command in the command prompt, the command below creates a new database called MyDbTest
succesfully:
connect 'jdbc:derby:MyDbTest;create=true';
If you need to clear the values of $_SESSION
, set the array equal to an empty array:
$_SESSION = array();
Of course, you can't access the values of $_SESSION
on another page once you call session_destroy
, so it doesn't matter that much.
Try the following:
session_destroy();
$_SESSION = array(); // Clears the $_SESSION variable
In order to unit test code that relies on your database you need to setup a database or mock for each and every test.
I am working in an application that has a lot of tables with a lot of connections and some massive Linq blocks. These need testing. A simple grouping missed, or a join that results in more than 1 row will affect results.
To deal with this I have setup a heavy Unit Test Helper that is a lot of work to setup, but enables us to reliably mock the database in any state, and running 48 tests against 55 interconnected tables, with the entire database setup 48 times takes 4.7 seconds.
Here's how:
In the Db context class ensure each table class is set to virtual
public virtual DbSet<Branch> Branches { get; set; }
public virtual DbSet<Warehouse> Warehouses { get; set; }
In a UnitTestHelper class create a method to setup your database. Each table class is an optional parameter. If not supplied, it will be created through a Make method
internal static Db Bootstrap(bool onlyMockPassedTables = false, List<Branch> branches = null, List<Products> products = null, List<Warehouses> warehouses = null)
{
if (onlyMockPassedTables == false) {
branches ??= new List<Branch> { MakeBranch() };
warehouses ??= new List<Warehouse>{ MakeWarehouse() };
}
For each table class, each object in it is mapped to the other lists
branches?.ForEach(b => {
b.Warehouse = warehouses.FirstOrDefault(w => w.ID == b.WarehouseID);
});
warehouses?.ForEach(w => {
w.Branches = branches.Where(b => b.WarehouseID == w.ID);
});
And add it to the DbContext
var context = new Db(new DbContextOptionsBuilder<Db>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
context.Branches.AddRange(branches);
context.Warehouses.AddRange(warehouses);
context.SaveChanges();
return context;
}
Define a list of IDs to make is easier to reuse them and make sure joins are valid
internal const int BranchID = 1;
internal const int WarehouseID = 2;
Create a Make for each table to setup the most basic, but connected version it can be
internal static Branch MakeBranch(int id = BranchID, string code = "The branch", int warehouseId = WarehouseID) => new Branch { ID = id, Code = code, WarehouseID = warehouseId };
internal static Warehouse MakeWarehouse(int id = WarehouseID, string code = "B", string name = "My Big Warehouse") => new Warehouse { ID = id, Code = code, Name = name };
It's a lot of work, but it only needs doing once, and then your tests can be very focused because the rest of the database will be setup for it.
[Test]
[TestCase(new string [] {"ABC", "DEF"}, "ABC", ExpectedResult = 1)]
[TestCase(new string [] {"ABC", "BCD"}, "BC", ExpectedResult = 2)]
[TestCase(new string [] {"ABC"}, "EF", ExpectedResult = 0)]
[TestCase(new string[] { "ABC", "DEF" }, "abc", ExpectedResult = 1)]
public int Given_SearchingForBranchByName_Then_ReturnCount(string[] codesInDatabase, string searchString)
{
// Arrange
var branches = codesInDatabase.Select(x => UnitTestHelpers.MakeBranch(code: $"qqqq{x}qqq")).ToList();
var db = UnitTestHelpers.Bootstrap(branches: branches);
var service = new BranchService(db);
// Act
var result = service.SearchByName(searchString);
// Assert
return result.Count();
}
DBQuery.shellBatchSize = 300
will do.
MongoDB Docs - Configure the mongo Shell - Change the mongo Shell Batch Size
Here is an option at the bottom of the Custom Search Control Panel: "Sites to search", you can choose "Search the entire web but emphasize included sites"
The ~
selector is in fact the General sibling combinator (renamed to Subsequent-sibling combinator in selectors Level 4):
The general sibling combinator is made of the "tilde" (U+007E, ~) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence precedes (not necessarily immediately) the element represented by the second one.
Consider the following example:
.a ~ .b {_x000D_
background-color: powderblue;_x000D_
}
_x000D_
<ul>_x000D_
<li class="b">1st</li>_x000D_
<li class="a">2nd</li>_x000D_
<li>3rd</li>_x000D_
<li class="b">4th</li>_x000D_
<li class="b">5th</li>_x000D_
</ul>
_x000D_
.a ~ .b
matches the 4th and 5th list item because they:
.b
elements .a
.a
in HTML source order.Likewise, .check:checked ~ .content
matches all .content
elements that are siblings of .check:checked
and appear after it.
Another solution (which is a hack) is to set the alpha on the tabBarController to 0.01 so that it is virtually invisible yet still clickable. Then set a an ImageView control on the bottom of the MainWindow nib with your custom tabbar image underneath the alpha'ed tabBarCOntroller. Then swap the images, change colors or hightlight when the tabbarcontroller switches views.
However, you lose the '...more' and customize functionality.
if your models table column is not equie mysql column.
such as :
class People:
id: int = Column(name='id', type_=Integer, primary_key=True)
createdTime: datetime = Column(name='create_time', type_=TIMESTAMP,
nullable=False,
server_default=text("CURRENT_TIMESTAMP"),
default=func.now())
modifiedTime: datetime = Column(name='modify_time', type_=TIMESTAMP,
server_default=text("CURRENT_TIMESTAMP"),
default=func.now())
Need to use:
from sqlalchemy.orm import class_mapper
def asDict(self):
return {x.key: getattr(self, x.key, None) for x in
class_mapper(Application).iterate_properties}
if you use this way you can get modify_time and create_time both are None
{'id': 1, 'create_time': None, 'modify_time': None}
def to_dict(self):
return {c.name: getattr(self, c.name, None)
for c in self.__table__.columns}
Because Class Attributes name not equal with column store in mysql
In your case, what you can do is:
z = dict(list(x.items()) + list(y.items()))
This will, as you want it, put the final dict in z
, and make the value for key b
be properly overridden by the second (y
) dict's value:
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = dict(list(x.items()) + list(y.items()))
>>> z
{'a': 1, 'c': 11, 'b': 10}
If you use Python 2, you can even remove the list()
calls. To create z:
>>> z = dict(x.items() + y.items())
>>> z
{'a': 1, 'c': 11, 'b': 10}
If you use Python version 3.9.0a4 or greater, then you can directly use:
x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11}
z = x | y
print(z)
{'a': 1, 'c': 11, 'b': 10}
OK so I think i know the issue you're having.
Basically, because Composer can't see the migration files you are creating, you are having to run the dump-autoload command which won't download anything new, but looks for all of the classes it needs to include again. It just regenerates the list of all classes that need to be included in the project (autoload_classmap.php), and this is why your migration is working after you run that command.
How to fix it (possibly) You need to add some extra information to your composer.json file.
"autoload": {
"classmap": [
"PATH TO YOUR MIGRATIONS FOLDER"
],
}
You need to add the path to your migrations folder to the classmap array. Then run the following three commands...
php artisan clear-compiled
composer dump-autoload
php artisan optimize
This will clear the current compiled files, update the classes it needs and then write them back out so you don't have to do it again.
Ideally, you execute composer dump-autoload -o
, for a faster load of your webpages. The only reason it is not default, is because it takes a bit longer to generate (but is only slightly noticable).
Hope you can manage to get this sorted, as its very annoying indeed :(
Today I needed to get the page's request parameters into a associative array so I put together the following, with a little help from my friends. It also handles parameters without an =
as true
.
With an example:
// URL: http://www.example.com/test.php?abc=123&def&xyz=&something%20else
var _GET = (function() {
var _get = {};
var re = /[?&]([^=&]+)(=?)([^&]*)/g;
while (m = re.exec(location.search))
_get[decodeURIComponent(m[1])] = (m[2] == '=' ? decodeURIComponent(m[3]) : true);
return _get;
})();
console.log(_GET);
> Object {abc: "123", def: true, xyz: "", something else: true}
console.log(_GET['something else']);
> true
console.log(_GET.abc);
> 123
The above answers require you to malloc a new stream object.
public <T>
boolean containsByLambda(Collection<? extends T> c, Predicate<? super T> p) {
for (final T z : c) {
if (p.test(z)) {
return true;
}
}
return false;
}
public boolean containsTabById(TabPane tabPane, String id) {
return containsByLambda(tabPane.getTabs(), z -> z.getId().equals(id));
}
...
if (containsTabById(tabPane, idToCheck))) {
...
}
Hello I was searching for a solution to reverse sorting a two dimensional numpy array, and I couldn't find anything that worked, but I think I have stumbled on a solution which I am uploading just in case anyone is in the same boat.
x=np.sort(array)
y=np.fliplr(x)
np.sort sorts ascending which is not what you want, but the command fliplr flips the rows left to right! Seems to work!
Hope it helps you out!
I guess it's similar to the suggest about -np.sort(-a) above but I was put off going for that by comment that it doesn't always work. Perhaps my solution won't always work either however I have tested it with a few arrays and seems to be OK.
It depends which style from the div you need. Is this a background style which was defined in CSS
or background style which was added through javascript(inline)
to the current node?
In case of CSS
style, you should use computed style. Like you do in getStyle()
.
With inline style you should use node.style
reference: x.style.backgroundColor
;
Also notice, that you pick the style by using camelCase/non hyphen reference, so not background-color
, but backgroundColor
;
For swift 5, you can simple do like that:
yourString.firstUppercased
Sample: "abc" -> "Abc"
As Daniel Howard points out, Rob Spencer describes what you want at http://scaledinnovation.com/analytics/splines/aboutSplines.html.
Here's an interactive demo: http://jsbin.com/ApitIxo/2/
Here it is as a snippet in case jsbin is down.
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset=utf-8 />_x000D_
<title>Demo smooth connection</title>_x000D_
</head>_x000D_
<body>_x000D_
<div id="display">_x000D_
Click to build a smooth path. _x000D_
(See Rob Spencer's <a href="http://scaledinnovation.com/analytics/splines/aboutSplines.html">article</a>)_x000D_
<br><label><input type="checkbox" id="showPoints" checked> Show points</label>_x000D_
<br><label><input type="checkbox" id="showControlLines" checked> Show control lines</label>_x000D_
<br>_x000D_
<label>_x000D_
<input type="range" id="tension" min="-1" max="2" step=".1" value=".5" > Tension <span id="tensionvalue">(0.5)</span>_x000D_
</label>_x000D_
<div id="mouse"></div>_x000D_
</div>_x000D_
<canvas id="canvas"></canvas>_x000D_
<style>_x000D_
html { position: relative; height: 100%; width: 100%; }_x000D_
body { position: absolute; left: 0; right: 0; top: 0; bottom: 0; } _x000D_
canvas { outline: 1px solid red; }_x000D_
#display { position: fixed; margin: 8px; background: white; z-index: 1; }_x000D_
</style>_x000D_
<script>_x000D_
function update() {_x000D_
$("tensionvalue").innerHTML="("+$("tension").value+")";_x000D_
drawSplines();_x000D_
}_x000D_
$("showPoints").onchange = $("showControlLines").onchange = $("tension").onchange = update;_x000D_
_x000D_
// utility function_x000D_
function $(id){ return document.getElementById(id); }_x000D_
var canvas=$("canvas"), ctx=canvas.getContext("2d");_x000D_
_x000D_
function setCanvasSize() {_x000D_
canvas.width = parseInt(window.getComputedStyle(document.body).width);_x000D_
canvas.height = parseInt(window.getComputedStyle(document.body).height);_x000D_
}_x000D_
window.onload = window.onresize = setCanvasSize();_x000D_
_x000D_
function mousePositionOnCanvas(e) {_x000D_
var el=e.target, c=el;_x000D_
var scaleX = c.width/c.offsetWidth || 1;_x000D_
var scaleY = c.height/c.offsetHeight || 1;_x000D_
_x000D_
if (!isNaN(e.offsetX)) _x000D_
return { x:e.offsetX*scaleX, y:e.offsetY*scaleY };_x000D_
_x000D_
var x=e.pageX, y=e.pageY;_x000D_
do {_x000D_
x -= el.offsetLeft;_x000D_
y -= el.offsetTop;_x000D_
el = el.offsetParent;_x000D_
} while (el);_x000D_
return { x: x*scaleX, y: y*scaleY };_x000D_
}_x000D_
_x000D_
canvas.onclick = function(e){_x000D_
var p = mousePositionOnCanvas(e);_x000D_
addSplinePoint(p.x, p.y);_x000D_
};_x000D_
_x000D_
function drawPoint(x,y,color){_x000D_
ctx.save();_x000D_
ctx.fillStyle=color;_x000D_
ctx.beginPath();_x000D_
ctx.arc(x,y,3,0,2*Math.PI);_x000D_
ctx.fill()_x000D_
ctx.restore();_x000D_
}_x000D_
canvas.onmousemove = function(e) {_x000D_
var p = mousePositionOnCanvas(e);_x000D_
$("mouse").innerHTML = p.x+","+p.y;_x000D_
};_x000D_
_x000D_
var pts=[]; // a list of x and ys_x000D_
_x000D_
// given an array of x,y's, return distance between any two,_x000D_
// note that i and j are indexes to the points, not directly into the array._x000D_
function dista(arr, i, j) {_x000D_
return Math.sqrt(Math.pow(arr[2*i]-arr[2*j], 2) + Math.pow(arr[2*i+1]-arr[2*j+1], 2));_x000D_
}_x000D_
_x000D_
// return vector from i to j where i and j are indexes pointing into an array of points._x000D_
function va(arr, i, j){_x000D_
return [arr[2*j]-arr[2*i], arr[2*j+1]-arr[2*i+1]]_x000D_
}_x000D_
_x000D_
function ctlpts(x1,y1,x2,y2,x3,y3) {_x000D_
var t = $("tension").value;_x000D_
var v = va(arguments, 0, 2);_x000D_
var d01 = dista(arguments, 0, 1);_x000D_
var d12 = dista(arguments, 1, 2);_x000D_
var d012 = d01 + d12;_x000D_
return [x2 - v[0] * t * d01 / d012, y2 - v[1] * t * d01 / d012,_x000D_
x2 + v[0] * t * d12 / d012, y2 + v[1] * t * d12 / d012 ];_x000D_
}_x000D_
_x000D_
function addSplinePoint(x, y){_x000D_
pts.push(x); pts.push(y);_x000D_
drawSplines();_x000D_
}_x000D_
function drawSplines() {_x000D_
clear();_x000D_
cps = []; // There will be two control points for each "middle" point, 1 ... len-2e_x000D_
for (var i = 0; i < pts.length - 2; i += 1) {_x000D_
cps = cps.concat(ctlpts(pts[2*i], pts[2*i+1], _x000D_
pts[2*i+2], pts[2*i+3], _x000D_
pts[2*i+4], pts[2*i+5]));_x000D_
}_x000D_
if ($("showControlLines").checked) drawControlPoints(cps);_x000D_
if ($("showPoints").checked) drawPoints(pts);_x000D_
_x000D_
drawCurvedPath(cps, pts);_x000D_
_x000D_
}_x000D_
function drawControlPoints(cps) {_x000D_
for (var i = 0; i < cps.length; i += 4) {_x000D_
showPt(cps[i], cps[i+1], "pink");_x000D_
showPt(cps[i+2], cps[i+3], "pink");_x000D_
drawLine(cps[i], cps[i+1], cps[i+2], cps[i+3], "pink");_x000D_
} _x000D_
}_x000D_
_x000D_
function drawPoints(pts) {_x000D_
for (var i = 0; i < pts.length; i += 2) {_x000D_
showPt(pts[i], pts[i+1], "black");_x000D_
} _x000D_
}_x000D_
_x000D_
function drawCurvedPath(cps, pts){_x000D_
var len = pts.length / 2; // number of points_x000D_
if (len < 2) return;_x000D_
if (len == 2) {_x000D_
ctx.beginPath();_x000D_
ctx.moveTo(pts[0], pts[1]);_x000D_
ctx.lineTo(pts[2], pts[3]);_x000D_
ctx.stroke();_x000D_
}_x000D_
else {_x000D_
ctx.beginPath();_x000D_
ctx.moveTo(pts[0], pts[1]);_x000D_
// from point 0 to point 1 is a quadratic_x000D_
ctx.quadraticCurveTo(cps[0], cps[1], pts[2], pts[3]);_x000D_
// for all middle points, connect with bezier_x000D_
for (var i = 2; i < len-1; i += 1) {_x000D_
// console.log("to", pts[2*i], pts[2*i+1]);_x000D_
ctx.bezierCurveTo(_x000D_
cps[(2*(i-1)-1)*2], cps[(2*(i-1)-1)*2+1],_x000D_
cps[(2*(i-1))*2], cps[(2*(i-1))*2+1],_x000D_
pts[i*2], pts[i*2+1]);_x000D_
}_x000D_
ctx.quadraticCurveTo(_x000D_
cps[(2*(i-1)-1)*2], cps[(2*(i-1)-1)*2+1],_x000D_
pts[i*2], pts[i*2+1]);_x000D_
ctx.stroke();_x000D_
}_x000D_
}_x000D_
function clear() {_x000D_
ctx.save();_x000D_
// use alpha to fade out_x000D_
ctx.fillStyle = "rgba(255,255,255,.7)"; // clear screen_x000D_
ctx.fillRect(0,0,canvas.width,canvas.height);_x000D_
ctx.restore();_x000D_
}_x000D_
_x000D_
function showPt(x,y,fillStyle) {_x000D_
ctx.save();_x000D_
ctx.beginPath();_x000D_
if (fillStyle) {_x000D_
ctx.fillStyle = fillStyle;_x000D_
}_x000D_
ctx.arc(x, y, 5, 0, 2*Math.PI);_x000D_
ctx.fill();_x000D_
ctx.restore();_x000D_
}_x000D_
_x000D_
function drawLine(x1, y1, x2, y2, strokeStyle){_x000D_
ctx.beginPath();_x000D_
ctx.moveTo(x1, y1);_x000D_
ctx.lineTo(x2, y2);_x000D_
if (strokeStyle) {_x000D_
ctx.save();_x000D_
ctx.strokeStyle = strokeStyle;_x000D_
ctx.stroke();_x000D_
ctx.restore();_x000D_
}_x000D_
else {_x000D_
ctx.save();_x000D_
ctx.strokeStyle = "pink";_x000D_
ctx.stroke();_x000D_
ctx.restore();_x000D_
}_x000D_
}_x000D_
_x000D_
</script>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
If you are using JavaScript to render then use escape_JavaScript("<%=render partial: partial_name, locals=>{@newval=>@oldval}%>");
Another option that I recently stumbled on is this:
{
echo "First error line"
echo "Second error line"
echo "Third error line"
} >&2
This uses only Bash built-ins while making multi-line error output less error prone (since you don't have to remember to add &>2
to every line).
Removes trailing returns when importing from Excel. When you execute this, you may receive an error that there is no WHERE; ignore and execute.
UPDATE table_name SET col_name = TRIM(TRAILING '\r' FROM col_name)
In C, the type of a character constant like 'a'
is actually an int
, with size of 4 (or some other implementation-dependent value). In C++, the type is char
, with size of 1. This is one of many small differences between the two languages.
You are giving colour to the background and then expecting it to be transparent?
Remove background-color: #D8F0DA
,
If you want #D8F0DA to be the colour of text, use color: #D8F0DA
jQuery Library must be in the head section then.
<button onclick="var less = parseInt($('#qty').val()) - 1; $('#qty').val(less);"></button>
<input type="text" id="qty" value="2">
<button onclick="var add = parseInt($('#qty').val()) + 1; $('#qty').val(add);">+</button>
All answers were just a suggested solutions or workarounds. But still don't get answer to the question: why margin:auto works with position:relative but does not with position:absolute.
Following explanation was helpful for me:
"Margins make little sense on absolutely positioned elements since such elements are removed from the normal flow, thus they cannot push away any other elements on the page. Using margins like this can only affect the placement of the element to which the margin is applied, not any other element." http://www.justskins.com/forums/css-margins-and-absolute-82168.html
Maybe use atribute disabled:
<input disabled="disabled" id="fieldName" name="fieldName" type="text" class="text_box" />
Or just use label tag: ;)
<label>
Your Fundamentals are wrong, the program won't work, so go through the basics and rewrite the program.
Some of the corrections you must make are:
1) You must make a variable of semaphore type
sem_t semvar;
2) The functions sem_wait()
, sem_post()
require the semaphore variable but you are passing the semaphore id, which makes no sense.
sem_wait(&semvar);
//your critical section code
sem_post(&semvar);
3) You are passing the semaphore to sem_wait()
and sem_post()
without initializing it. You must initialize it to 1 (in your case) before using it, or you will have a deadlock.
ret = semctl( semid, 1, SETVAL, sem);
if (ret == 1)
perror("Semaphore failed to initialize");
Study the semaphore API's from the man page and go through this example.
You can make nginx ignore client aborts using:
location / {
proxy_ignore_client_abort on;
}
Recommended solution is to install and trust a self-signed certificate (root). Assuming you created your own CA and the hierarchy of the certificated is correct you don't need to change the server trust evaluation. This is recommended because it doesn't require any changes in the code.
If it is not possible then you need to change server trust evaluation.
More info in this document: Technical Q&A QA1948 HTTPS and Test Servers
Based on Lucio's code, I made a module. It will return an away with all the files with specific extensions under the one. Just post it here in case anybody needs it.
var path = require('path'),
fs = require('fs');
/**
* Find all files recursively in specific folder with specific extension, e.g:
* findFilesInDir('./project/src', '.html') ==> ['./project/src/a.html','./project/src/build/index.html']
* @param {String} startPath Path relative to this file or other file which requires this files
* @param {String} filter Extension name, e.g: '.html'
* @return {Array} Result files with path string in an array
*/
function findFilesInDir(startPath,filter){
var results = [];
if (!fs.existsSync(startPath)){
console.log("no dir ",startPath);
return;
}
var files=fs.readdirSync(startPath);
for(var i=0;i<files.length;i++){
var filename=path.join(startPath,files[i]);
var stat = fs.lstatSync(filename);
if (stat.isDirectory()){
results = results.concat(findFilesInDir(filename,filter)); //recurse
}
else if (filename.indexOf(filter)>=0) {
console.log('-- found: ',filename);
results.push(filename);
}
}
return results;
}
module.exports = findFilesInDir;
This happened to me when i am using ProgressDialog
in AsyncTask
. Actually i am using hide()
method in onPostExecute
. Based on the answer of @Alex Volovoy i need to use dismiss()
with ProgressDialog
to remove it in onPostExecute and its done.
progressDialog.hide(); // Don't use it, it gives error
progressDialog.dismiss(); // Use it
You need to use .change()
event as well as using #
to target element by id
:
$('#EventStartTimeMin').change(function() {
if($(this).val()===""){
console.log('empty');
}
});
This should work:
grep(pattern = 'A1|A9|A6', x = myfile$Letter)
Or even more simply:
library(data.table)
myfile$Letter %like% 'A1|A9|A6'
This is a guess :)
Is it because the ID is a string? What happens if you change it to int?
I mean:
public int Id { get; set; }
A way to do this would be to set the color of the element to black, and then fade to the color of the background like this:
<style>
p {
animation-name: example;
animation-duration: 2s;
}
@keyframes example {
from {color:black;}
to {color:white;}
}
</style>
<p>I am FADING!</p>
I hope this is what you needed!
For anyone who looks at this today after 2 years, Visual Studio 2019 (Community edition as well) shows the references
wget -O yourfilename.zip remote-storage.url/theirfilename.zip
will do the trick for you.
Note:
a) its a capital O.
b) wget -O filename url
will only work. Putting -O
last will not.
I have added some modification to the code from this answer (https://stackoverflow.com/a/24588210/4489664) because for nullable Types it will return exception
public static List<T> DataTableToList<T>(this DataTable table) where T: new()
{
List<T> list = new List<T>();
var typeProperties = typeof(T).GetProperties().Select(propertyInfo => new
{
PropertyInfo = propertyInfo,
Type = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType
}).ToList();
foreach (var row in table.Rows.Cast<DataRow>())
{
T obj = new T();
foreach (var typeProperty in typeProperties)
{
object value = row[typeProperty.PropertyInfo.Name];
object safeValue = value == null || DBNull.Value.Equals(value)
? null
: Convert.ChangeType(value, typeProperty.Type);
typeProperty.PropertyInfo.SetValue(obj, safeValue, null);
}
list.Add(obj);
}
return list;
}
length
and dbms_lob.getlength
return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength
will return the number of bytes, which may differ from the number of characters in a multi-byte character set.
As the documentation doesn't specify what happens when you apply length
on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength
.
My use case is that I'm on a metered account. Data transfer is limited on weekdays, Mon - Fri, from 6am - 6pm. I am using bandwidth limiting, but somehow, data still slips through, about 1GB per day!
I strongly suspected it's sickrage or sickbeard, doing a high amount of searches. My download machine is called "download." The following was my solution, using the above,for starting, and stopping the download VM, using KVM:
# Stop download Mon-Fri, 6am
0 6 * * 1,2,3,4,5 root virsh shutdown download
# Start download Mon-Fri, 6pm
0 18 * * 1,2,3,4,5 root virsh start download
I think this is correct, and hope it helps someone else too.
I was also facing the same issue.
I was using the code below in .aspx page without writing authentication configuration in web.config file. After writing the settings in Web.config, I am able to run my code.
<% If Request.IsAuthenticated Then%>
<table></table>
<%end if%>
Usually, a Python dictionary throws a KeyError
if you try to get an item with a key that is not currently in the dictionary. The defaultdict
in contrast will simply create any items that you try to access (provided of course they do not exist yet). To create such a "default" item, it calls the function object that you pass to the constructor (more precisely, it's an arbitrary "callable" object, which includes function and type objects). For the first example, default items are created using int()
, which will return the integer object 0
. For the second example, default items are created using list()
, which returns a new empty list object.
In my case one of parents of my modal was animated and had this
.animated {
-webkit-animation-duration: 1s;
animation-duration: 1s;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
z-index: 100;
}
The blocker here is animation-fill-mode: both;
. I could not just move modal outside, so the solution was to override 'animation-fill-mode' to animation-fill-mode: none;
. Animation still worked fine.
Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
public class ReadDocFile
{
public static void main(String[] args)
{
File file = null;
WordExtractor extractor = null;
try
{
file = new File("c:\\New.doc");
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
HWPFDocument document = new HWPFDocument(fis);
extractor = new WordExtractor(document);
String[] fileData = extractor.getParagraphText();
for (int i = 0; i < fileData.length; i++)
{
if (fileData[i] != null)
System.out.println(fileData[i]);
}
}
catch (Exception exep)
{
exep.printStackTrace();
}
}
}
You can use jQuery
to achieve this
Example:
$(function () {
$('.map').maphilight();
});
Go through this LINK to know more.
If the above one doesnt work then go through this link.
EDIT :
Give same class to each area
tag like class="mapping"
and try this below code
$('.mapping').mouseover(function() {
alert($(this).attr('id'));
}).mouseout(function(){
alert('Mouseout....');
});
If you are using ES5 -
backgroundImage: "url(" + Background + ")"
If you are using ES6 -
backgroundImage: `url(${Background})`
Basically removing unnecessary curly braces while adding value to backgroundImage property works will work.
Here's a simple way
for (i in 1:10) {
skip_to_next <- FALSE
# Note that print(b) fails since b doesn't exist
tryCatch(print(b), error = function(e) { skip_to_next <<- TRUE})
if(skip_to_next) { next }
}
Note that the loop completes all 10 iterations, despite errors. You can obviously replace print(b)
with any code you want. You can also wrap many lines of code in {
and }
if you have more than one line of code inside the tryCatch
I had only below properties in /resources/application.properties. After running spring boot, using this URL(http://localhost:8080/h2-console/), the table in H2 console was visible and read to view the table data, also you can run simple SQL commands. One thing, in your java code, while fetching data, the column names are upper-case, even though schema.sql is using lower-case names :)
spring.datasource.initialize=true
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=- 1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true
It could be even caused by your ad blocker.
Try to disable it or adding an exception for the domain from which the images come from.
Essentially console.log("Put a message here.")
if the browser has a supporting console.
Another typical debugging method is using alerts, alert("Put a message here.")
RE: Update II
This seems to make sense, you are trying to automate QUnit tests, from what I have read on QUnit this is an in-browser unit testing suite/library. QUnit expects to run in a browser and therefore expects the browser to recognize all of the JavaScript functions you are calling.
Based on your Maven configuration it appears you are using Rhino to execute your Javascript at the command line/terminal. This is not going to work for testing browser specifics, you would likely need to look into Selenium for this. If you do not care about testing your JavaScript in a browser but are only testing JavaScript at a command line level (for reason I would not be familiar with) it appears that Rhino recognizes a print()
method for evaluating expressions and printing them out. Checkout this documentation.
These links might be of interest to you.
write the code that you want to be executed inside this. When your document is ready, this will be executed.
$(document).ready(function() {
});
Nested JSON
object
var data = {
view:{
type: 'success', note:'Updated successfully',
},
};
You can parse this data.view.type
and data.view.note
JSON
Object and inside Array
var data = {
view: [
{type: 'success', note:'updated successfully'}
],
};
You can parse this data.view[0].type
and data.view[0].note
You need to pass your components as children, like this:
var App = require('./App.js');
var SampleComponent = require('./SampleComponent.js');
ReactDOM.render(
<App>
<SampleComponent name="SomeName"/>
<App>,
document.body
);
And then append them in the component's body:
var App = React.createClass({
render: function() {
return (
<div>
<h1>App main component! </h1>
{
this.props.children
}
</div>
);
}
});
You don't need to manually manipulate HTML code, React will do that for you. If you want to add some child components, you just need to change props or state it depends. For example:
var App = React.createClass({
getInitialState: function(){
return [
{id:1,name:"Some Name"}
]
},
addChild: function() {
// State change will cause component re-render
this.setState(this.state.concat([
{id:2,name:"Another Name"}
]))
}
render: function() {
return (
<div>
<h1>App main component! </h1>
<button onClick={this.addChild}>Add component</button>
{
this.state.map((item) => (
<SampleComponent key={item.id} name={item.name}/>
))
}
</div>
);
}
});
In my case, one of my closing parenthesis for "onChanges()" were missed on the input element and thus the input element was apparently not being rendered at all:
<input mat-menu-item
matInput type="text"
[formControl]="myFormControl"
(ngModelChange)="onChanged()>
From Dianne Hackborn:
Things That Cannot Change:
The most obvious and visible of these is the “manifest package name,” the unique name you give to your application in its AndroidManifest.xml. The name uses a Java-language-style naming convention, with Internet domain ownership helping to avoid name collisions. For example, since Google owns the domain “google.com”, the manifest package names of all of our applications should start with “com.google.” It’s important for developers to follow this convention in order to avoid conflicts with other developers.
Once you publish your application under its manifest package name, this is the unique identity of the application forever more. Switching to a different name results in an entirely new application, one that can’t be installed as an update to the existing application.
More on things you cannot change here
Regarding your question on the URL from Google Play, the package defined there is linked to the app's fully qualified package you have in your AndroidManifest.xml file. More on Google Play's link formats here.
You can use _.omit()
for emitting the key from a JSON array if you have fewer objects:
_.forEach(data, (d) => {
_.omit(d, ['keyToEmit1', 'keyToEmit2'])
});
If you have more objects, you can use the reverse of it which is _.pick()
:
_.forEach(data, (d) => {
_.pick(d, ['keyToPick1', 'keyToPick2'])
});
As posted in my update above, a potential solution would be to use Declaration Merging as suggested by @Tyler-sebastion. I was able to define two additional interfaces and add the index property on the EventTarget
in this way.
interface KonvaTextEventTarget extends EventTarget {
index: number
}
interface KonvaMouseEvent extends React.MouseEvent<HTMLElement> {
target: KonvaTextEventTarget
}
I then can declare the event as KonvaMouseEvent
in my onclick MouseEventHandler function.
onClick={(event: KonvaMouseEvent) => {
makeMove(ownMark, event.target.index)
}}
I'm still not 100% if this is the best approach as it feels a bit Kludgy and overly verbose just to get past the tslint error.
Time Complexity : O(n) : Without Set
private static void removeDup(ArrayList<String> listWithDuplicateElements) {
System.out.println(" Original Duplicate List :" + listWithDuplicateElements);
List<String> listWithoutDuplicateElements = new ArrayList<>(listWithDuplicateElements.size());
listWithDuplicateElements.stream().forEach(str -> {
if (listWithoutDuplicateElements.indexOf(str) == -1) {
listWithoutDuplicateElements.add(str);
}
});
System.out.println(" Without Duplicate List :" + listWithoutDuplicateElements);
}
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollView01"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:scrollbars="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="666dp"
android:background="#1500FFe5"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" >
<TextView
android:id="@+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editGrWt"
android:layout_marginTop="14dp"
android:layout_toLeftOf="@+id/textView3"
android:ems="6"
android:text=" Diamond :"
android:textColor="@color/background_material_dark"
android:textSize="15sp" />
<EditText
android:id="@+id/editDWt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/TextView02"
android:layout_alignLeft="@+id/editGrWt"
android:background="@color/bright_foreground_inverse_material_light"
android:ems="4"
android:hint="Weight"
android:inputType="numberDecimal"
android:nextFocusLeft="@+id/editDRate"
android:selectAllOnFocus="true"
android:imeOptions="actionNext"
/>
<requestFocus />
<TextView
android:id="@+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/TextView02"
android:layout_below="@+id/TextView02"
android:layout_marginTop="14dp"
android:ems="6"
android:text=" Diamond :"
android:textColor="@color/background_material_dark"
android:textSize="15sp" />
<EditText
android:id="@+id/editDWt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/TextView03"
android:layout_alignBottom="@+id/TextView03"
android:layout_alignLeft="@+id/editDWt"
android:background="@color/bright_foreground_inverse_material_light"
android:ems="4"
android:hint="Weight"
android:inputType="numberDecimal"
android:text="0"
android:selectAllOnFocus="true"
android:imeOptions="actionNext"/>
<requestFocus />
<TextView
android:id="@+id/TextView04"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editDWt1"
android:layout_marginTop="14dp"
android:layout_toLeftOf="@+id/textView3"
android:ems="6"
android:text=" Stone :"
android:textColor="@color/background_material_dark"
android:textSize="15sp" />
<EditText
android:id="@+id/editStWt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/TextView04"
android:layout_alignBottom="@+id/TextView04"
android:layout_alignLeft="@+id/editDWt1"
android:background="@color/bright_foreground_inverse_material_light"
android:ems="4"
android:hint="Weight"
android:inputType="numberDecimal"
android:nextFocusForward="@+id/editStRate1"
android:imeOptions="actionNext" />
<requestFocus />
<TextView
android:id="@+id/TextView05"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/TextView04"
android:layout_below="@+id/editStRate1"
android:layout_marginTop="14dp"
android:ems="6"
android:text=" Stone :"
android:textColor="@color/background_material_dark"
android:textSize="15sp" />
</RelativeLayout>
</ScrollView>
for those having problems after adding active and focus give a class or id name to your button and add this to css
for example
//html code
<button id="aboutus">ABOUT US</button>
//css code
#aboutus{background-color: white;border:none;outline-style: none;}
Using basic math and simple javascript this can be done in just a few lines of code.
EXAMPLE - Convert 7735 seconds
to HH:MM:SS
.
Calculations use:
Math.floor()
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor The
Math.floor()
function returns the largest integer less than or equal to a given number.
%
arithmetic operator (Remainder) - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#RemainderThe remainder operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.
Check out code below. Seconds are divided by 3600
to get number of hours and a remainder, which is used to calculate number of minutes and seconds.
HOURS => 7735 / 3600 = 2 remainder 535
MINUTES => 535 / 60 = 8 remainder 55
SECONDS => 55
Many answers here use complicated methods to show number of hours, minutes and seconds in a proper way with leading zero - 45
, 04
etc. This can be done using padStart()
. This works for strings so the number must be converted to string using toString()
.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
The
padStart()
method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string.
function secondsToTime(e){_x000D_
var h = Math.floor(e / 3600).toString().padStart(2,'0'),_x000D_
m = Math.floor(e % 3600 / 60).toString().padStart(2,'0'),_x000D_
s = Math.floor(e % 60).toString().padStart(2,'0');_x000D_
_x000D_
return h + ':' + m + ':' + s;_x000D_
}_x000D_
_x000D_
console.log(secondsToTime(7735)); //02:08:55_x000D_
_x000D_
/*_x000D_
secondsToTime(SECONDS) => HH:MM:SS _x000D_
_x000D_
secondsToTime(8) => 00:00:08 _x000D_
secondsToTime(68) => 00:01:08_x000D_
secondsToTime(1768) => 00:29:28_x000D_
secondsToTime(3600) => 01:00:00_x000D_
secondsToTime(5296) => 01:28:16_x000D_
secondsToTime(7735) => 02:08:55_x000D_
secondsToTime(45296) => 12:34:56_x000D_
secondsToTime(145296) => 40:21:36_x000D_
secondsToTime(1145296) => 318:08:16_x000D_
*/
_x000D_
//
is unconditionally "flooring division", e.g:
>>> 4.0//1.5
2.0
As you see, even though both operands are float
s, //
still floors -- so you always know securely what it's going to do.
Single /
may or may not floor depending on Python release, future imports, and even flags on which Python's run, e.g.:
$ python2.6 -Qold -c 'print 2/3'
0
$ python2.6 -Qnew -c 'print 2/3'
0.666666666667
As you see, single /
may floor, or it may return a float, based on completely non-local issues, up to and including the value of the -Q
flag...;-).
So, if and when you know you want flooring, always use //
, which guarantees it. If and when you know you don't want flooring, slap a float()
around other operand and use /
. Any other combination, and you're at the mercy of version, imports, and flags!-)
You need to do next in command line:
wsimport -keep -s (name of folder where you want to store generated code) urlToWsdl
for example:
wsimport -keep -s C://NewFolder https://www.blablabla.com
If you are detecting for presence, here's the easiest solution:
SET STRING=F00BAH
SET SUBSTRING=F00
ECHO %STRING% | FINDSTR /C:"%SUBSTRING%" >nul & IF ERRORLEVEL 1 (ECHO CASE TRUE) else (ECHO CASE FALSE)
This works great for dropping the output of windows commands into a boolean variable. Just replace the echo with the command you want to run. You can also string Findstr's together to further qualify a statement using pipes. E.G. for Service Control (SC.exe)
SC QUERY WUAUSERV | findstr /C:"STATE" | FINDSTR /C:"RUNNING" & IF ERRORLEVEL 1 (ECHO case True) else (ECHO CASE FALSE)
That one evaluates the output of SC Query for windows update services which comes out as a multiline text, finds the line containing "state" then finds if the word "running" occurs on that line, and sets the errorlevel accordingly.
Here's a great scripted solution for logging people out remotely or locally. I'm using qwinsta to get session information and building an array out of the given output. This makes it really easy to iterate through each entry and log out only the actual users, and not the system or RDP listener itself which usually just throws an access denied error anyway.
$serverName = "Name of server here OR localhost"
$sessions = qwinsta /server $serverName| ?{ $_ -notmatch '^ SESSIONNAME' } | %{
$item = "" | Select "Active", "SessionName", "Username", "Id", "State", "Type", "Device"
$item.Active = $_.Substring(0,1) -match '>'
$item.SessionName = $_.Substring(1,18).Trim()
$item.Username = $_.Substring(19,20).Trim()
$item.Id = $_.Substring(39,9).Trim()
$item.State = $_.Substring(48,8).Trim()
$item.Type = $_.Substring(56,12).Trim()
$item.Device = $_.Substring(68).Trim()
$item
}
foreach ($session in $sessions){
if ($session.Username -ne "" -or $session.Username.Length -gt 1){
logoff /server $serverName $session.Id
}
}
In the first line of this script give $serverName the appropriate value or localhost if running locally. I use this script to kick users before an automated process attempts to move some folders around. Prevents "file in use" errors for me. Another note, this script will have to be ran as an administrator user otherwise you can get accessed denied trying to log someone out. Hope this helps!
In my case, it wasn't working until I also installed the following package : libatlas-base-dev, gfortran
sudo apt-get install libatlas-base-dev gfortran
Then run pip install scipy
In my case, same as in this question, it happened becayse I had my project in a symbolic link directory. After reopening the project in the real directory and reconfiguring gradle (File -> Sync with Gradle files
) the problem went away. Shame on you, Android Studio!
In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size
like this:
#include <vector>
int main () {
std::vector<int> v;
auto size = v.size();
}
Your third call
int size = v.size();
triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.
int size = static_cast<int>(v.size());
would always compile cleanly and also explicitly states that your conversion from std::vector::size_type
to int
was intended.
Note that if the size of the vector
is greater than the biggest number an int
can represent, size
will contain an implementation defined (de facto garbage) value.
String s = "ASCII Text";
byte[] bytes = s.getBytes("US-ASCII");
Just subtract the string address from what strchr returns:
char *string = "qwerty";
char *e;
int index;
e = strchr(string, 'e');
index = (int)(e - string);
Note that the result is zero based, so in above example it will be 2.
If this is your detail.html
I don't see where do you load detail.js
?
Maybe this
<script src="js/index.js"></script>
should be this
<script src="js/detail.js"></script>
?
Simple excel file create in mvc 4
public ActionResult results() { return File(new System.Text.UTF8Encoding().GetBytes("string data"), "application/csv", "filename.csv"); }
Here is my solution using jQuery
<script type="text/javascript">
$('#mtoogle').toggle(
function () {
document.getElementById('playTune').pause();
},
function () {
document.getElementById('playTune').play();
}
);
</script>
And the working demo
Angular 2+
I found this while searching for Angular 2+, so here is the way:
$window.location.reload();
Example:
2.032 MB (2,131,022 bytes)
$u=($mbox.TotalItemSize.value).tostring()
$u=$u.trimend(" bytes)") #yields 2.032 MB (2,131,022
$u=$u.Split("(") #yields `$u[1]` as 2,131,022
$uI=[int]$u[1]
The result is 2131022 in integer form.
Set the auto increment field to NULL or 0 if you want it to be auto magically assigned...
Yes, you can. Go to File -> Settings -> Editor -> Show quick documentation on mouse move
Or, in Mac OS X, go to Android Studio - > Preferences -> Editor - > General > Show quick documentation on mouse move
.
Try excluding height from the style element.
i.e. neither give height:100% nor to any other value.
You can use the Feed Dialog via URL to emulate the behavior of Sharer.php, but it's a little more complicated. You need a Facebook App setup with the Base URL of the URL you plan to share configured. Then you can do the following:
1) Create a link like:
http://www.facebook.com/dialog/feed?app_id=[FACEBOOK_APP_ID]' +
'&link=[FULLY_QUALIFIED_LINK_TO_SHARE_CONTENT]' +
'&picture=[LINK_TO_IMAGE]' +
'&name=' + encodeURIComponent('[CONTENT_TITLE]') +
'&caption=' + encodeURIComponent('[CONTENT_CAPTION]) +
'&description=' + encodeURIComponent('[CONTENT_DESCRIPTION]') +
'&redirect_uri=' + FBVars.baseURL + '[URL_TO_REDIRECT_TO_AFTER_SHARE]' +
'&display=popup';
(obviously replace the [CONTENT] with the appropriate content. Documentation here: https://developers.facebook.com/docs/reference/dialogs/feed)
2) Open that link in a popup window with JavaScript on click of the share link
3) I like to create file (i.e. popupclose.html) to redirect users back to when they finish sharing, this file will contain <script>window.close();</script>
to close the popup window
The only downside of using the Feed Dialog (besides setup) is that, if you manage Pages as well, you don't have the ability to choose to share via a Page, only a regular user account can share. And it can give you some really cryptic error messages, most of them are related to the setup of your Facebook app or problems with either the content or URL you are sharing.
Keep in mind that international users may be using a decimal separator other than .
in which case values can get mixed up or just become nil when using intValue
on a string.
For example, in the UK 1.23
is written 1,23
, so the number 1.777
would be input by user as 1,777
, which, as .intValue
, will be 1777
not 1
(truncated).
I've made a macro that will convert input text to an NSNumber based on a locale argument which can be nil (if nil it uses device current locale).
#define stringToNumber(__string, __nullable_locale) (\
(^NSNumber *(void){\
NSLocale *__locale = __nullable_locale;\
if (!__locale) {\
__locale = [NSLocale currentLocale];\
}\
NSString *__string_copy = [__string stringByReplacingOccurrencesOfString:__locale.groupingSeparator withString:@""];\
__string_copy = [__string_copy stringByReplacingOccurrencesOfString:__locale.decimalSeparator withString:@"."];\
return @([__string_copy doubleValue]);\
})()\
)
If you're doing programatic customisation, don't hard code the system font. Use UIFont systemFontOfSize:
, UIFont boldSystemFontOfSize:
and UIFont italicSystemFontOfSize
(Apple documentation).
This has become especially relevant since iOS 7, which changed the system font to Helvetica Neue.
This has become super especially relevant since iOS 9, which changed the system font again to San Francisco.
#include <math.h>
double round(double x);
float roundf(float x);
Don't forget to link with -lm. See also ceil(), floor() and trunc().
If you want to launch VM by sending arguments, you should send VM arguments and not Program arguments.
Program arguments are arguments that are passed to your application, which are accessible via the "args" String array parameter of your main method. VM arguments are arguments such as System properties that are passed to the JavaSW interpreter. The Debug configuration above is essentially equivalent to:
java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3
The VM arguments go after the call to your Java interpreter (ie, 'java') and before the Java class. Program arguments go after your Java class.
Consider a program ArgsTest.java:
package test;
import java.io.IOException;
public class ArgsTest {
public static void main(String[] args) throws IOException {
System.out.println("Program Arguments:");
for (String arg : args) {
System.out.println("\t" + arg);
}
System.out.println("System Properties from VM Arguments");
String sysProp1 = "sysProp1";
System.out.println("\tName:" + sysProp1 + ", Value:" + System.getProperty(sysProp1));
String sysProp2 = "sysProp2";
System.out.println("\tName:" + sysProp2 + ", Value:" + System.getProperty(sysProp2));
}
}
If given input as,
java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3
in the commandline, in project bin folder would give the following result:
Program Arguments: pro1 pro2 pro3 System Properties from VM Arguments Name:sysProp1, Value:sp1 Name:sysProp2, Value:sp2
I didn't understand your question ... what do you mean by "when i set every one of my colour"? try this (edit: "#fffff" in original answer changed to "#ffffff"
yourView.setBackgroundColor(Color.parseColor("#ffffff"));
When using git rm, the removal will part of your next commit. So if you want to push the change you should use git rm
Im using a custom image instead of the default title text to the right of my apps logo. This is set up programatically like
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setCustomView(R.layout.include_ab_txt_logo);
actionBar.setDisplayShowCustomEnabled(true);
The issues with the above answers for me are @Cliffus's suggestion does not work for me due to the issues others have outlined in the comments and while @dushyanth programatic padding setting may have worked in the past I would think that the fact that the spacing is now set using android:layout_marginEnd="8dip"
since API 17 manually setting the padding should have no effect. See the link he posted to git to verify its current state.
A simple solution for me is to set a negative margin on my custom view in the actionBar, like so android:layout_marginLeft="-14dp"
. A quick test shows it works for me on 2.3.3 and 4.3 using ActionBarCompat
Hope this helps someone!
Yes you can very easily downloads Files from the remote Url Using this code. This Code is working Fine for Me.
func DownlondFromUrl(){
// Create destination URL
let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
let destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.jpg")
//Create URL to the source file you want to download
let fileURL = URL(string: "https://s3.amazonaws.com/learn-swift/IMG_0001.JPG")
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = URLRequest(url:fileURL!)
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
}
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
} else {
print("Error took place while downloading a file. Error description: %@", error?.localizedDescription);
}
}
task.resume()
}
HttpClient is deprecated in sdk 23.
You have to move on URLConnection or down sdk to 22
Still you need HttpClient with update gradle sdk 23
You have to add the dependencies of HttpClient in app/gradle as
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
...
}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>teste4</groupId>
<artifactId>teste4</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<repositories>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>org.primefaces.themes</groupId>
<artifactId>bootstrap</artifactId>
<version>1.0.9</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.27</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.7.Final</version>
</dependency>
</dependencies>
</project>
Specify a 'display-image' and 'full-size-image' as described here: http://www.informit.com/articles/article.aspx?p=1829415&seqNum=16
iOS8 requires these images
Another program that can do this is axel
.
axel -n <NUMBER_OF_CONNECTIONS> URL
For baisic HTTP Auth,
axel -n <NUMBER_OF_CONNECTIONS> "user:password@https://domain.tld/path/file.ext"
/\d+\.?\d*/
One or more digits (\d+
), optional period (\.?
), zero or more digits (\d*
).
Depending on your usage or regex engine you may need to add start/end line anchors:
/^\d+\.?\d*$/
If you wanted to learn some GUI, may be tic tac toe is good. Even for console, I still find that is a fun problem. Not challenging but a little bit fun. Later you can advance some other games or port that game to GUI, client server or java applet for the web. I think if you want to learn something and get fun as well, game is a good choice:)
You can't "open" a directory using the open
function. This function is meant to be used to open files.
Here, what you want to do is open the file that's in the directory. The first thing you must do is compute this file's path. The os.path.join
function will let you do that by joining parts of the path (the directory and the file name):
fpath = os.path.join(direct, "5_1.txt")
You can then open the file:
f = open(fpath)
And read its content:
content = f.read()
Additionally, I believe that on Windows, using open
on a directory does return a PermissionDenied
exception, although that's not really the case.
In my case, this error popped up not because of duplicate values, but because I attempted to join a shorter Series to a Dataframe: both had the same index, but the Series had fewer rows (missing the top few). The following worked for my purposes:
df.head()
SensA
date
2018-04-03 13:54:47.274 -0.45
2018-04-03 13:55:46.484 -0.42
2018-04-03 13:56:56.235 -0.37
2018-04-03 13:57:57.207 -0.34
2018-04-03 13:59:34.636 -0.33
series.head()
date
2018-04-03 14:09:36.577 62.2
2018-04-03 14:10:28.138 63.5
2018-04-03 14:11:27.400 63.1
2018-04-03 14:12:39.623 62.6
2018-04-03 14:13:27.310 62.5
Name: SensA_rrT, dtype: float64
df = series.to_frame().combine_first(df)
df.head(10)
SensA SensA_rrT
date
2018-04-03 13:54:47.274 -0.45 NaN
2018-04-03 13:55:46.484 -0.42 NaN
2018-04-03 13:56:56.235 -0.37 NaN
2018-04-03 13:57:57.207 -0.34 NaN
2018-04-03 13:59:34.636 -0.33 NaN
2018-04-03 14:00:34.565 -0.33 NaN
2018-04-03 14:01:19.994 -0.37 NaN
2018-04-03 14:02:29.636 -0.34 NaN
2018-04-03 14:03:31.599 -0.32 NaN
2018-04-03 14:04:30.779 -0.33 NaN
2018-04-03 14:05:31.733 -0.35 NaN
2018-04-03 14:06:33.290 -0.38 NaN
2018-04-03 14:07:37.459 -0.39 NaN
2018-04-03 14:08:36.361 -0.36 NaN
2018-04-03 14:09:36.577 -0.37 62.2
Javascript provides more than one method to check the viewport width. As you noticed, innerWidth doesn't include the toolbar width, and toolbar widths will differ across systems. There is also the outerWidth option, which will include the toolbar width. The Mozilla Javascript API states:
Window.outerWidth gets the width of the outside of the browser window. It represents the width of the whole browser window including sidebar (if expanded), window chrome and window resizing borders/handles.
The state of javascript is such that one cannot rely on a specific meaning for outerWidth in every browser on every platform.
outerWidth
is not well supported on older mobile browsers, though it enjoys support across major desktop browsers and most newer smart phone browsers.
As ausi pointed out, matchMedia
would be a great choice as CSS is better standardised (matchMedia uses JS to read the viewport values detected by CSS). But even with accepted standards, retarded browsers still exist that ignore them (IE < 10 in this case, which makes matchMedia not very useful at least until XP dies).
In summary, if you are only developing for desktop browsers and newer mobile browsers, outerWidth should give you what you are looking for, with some caveats.
What about 1.1E10, +1, -0, etc? Parsing all possible numbers is trickier than many people think. If you want to include as many numbers are possible you should use the to_number function in a PL/SQL function. From http://www.oracle-developer.net/content/utilities/is_number.sql:
CREATE OR REPLACE FUNCTION is_number (str_in IN VARCHAR2) RETURN NUMBER IS
n NUMBER;
BEGIN
n := TO_NUMBER(str_in);
RETURN 1;
EXCEPTION
WHEN VALUE_ERROR THEN
RETURN 0;
END;
/
DECLARE @isAvailable BIT = 0;
IF EXISTS(SELECT 1 FROM [User] WHERE (UserID = 20070022))
BEGIN
SET @isAvailable = 1
END
initially isAvailable boolean value is set to 0
Defining a new directive to work around a bug is not really ideal.
Because the datepicker displays later dates correctly, one simple workaround could be just setting the model variable to null first, and then to the current date after a while:
$scope.dt = null;
$timeout( function(){
$scope.dt = new Date();
},100);
fyi The code I ended up with:
IF UPDATE (QtyToRepair)
begin
INSERT INTO tmpQtyToRepairChanges (OrderNo, PartNumber, ModifiedDate, ModifiedUser, ModifiedHost, QtyToRepairOld, QtyToRepairNew)
SELECT S.OrderNo, S.PartNumber, GETDATE(), SUSER_NAME(), HOST_NAME(), D.QtyToRepair, I.QtyToRepair FROM SCHEDULE S
INNER JOIN Inserted I ON S.OrderNo = I.OrderNo and S.PartNumber = I.PartNumber
INNER JOIN Deleted D ON S.OrderNo = D.OrderNo and S.PartNumber = D.PartNumber
WHERE I.QtyToRepair <> D.QtyToRepair
end
You can get the channel ID with the username (in your case "klauskkpm") using the filter "forUsername", like this:
https://www.googleapis.com/youtube/v3/channels?key={YOUR_API_KEY}&forUsername=klauskkpm&part=id
More info here: https://developers.google.com/youtube/v3/docs/channels/list
You can add/remove Appender programmatically to Log4j:
ConsoleAppender console = new ConsoleAppender(); //create appender
//configure the appender
String PATTERN = "%d [%p|%c|%C{1}] %m%n";
console.setLayout(new PatternLayout(PATTERN));
console.setThreshold(Level.FATAL);
console.activateOptions();
//add appender to any Logger (here is root)
Logger.getRootLogger().addAppender(console);
FileAppender fa = new FileAppender();
fa.setName("FileLogger");
fa.setFile("mylog.log");
fa.setLayout(new PatternLayout("%d %-5p [%c{1}] %m%n"));
fa.setThreshold(Level.DEBUG);
fa.setAppend(true);
fa.activateOptions();
//add appender to any Logger (here is root)
Logger.getRootLogger().addAppender(fa);
//repeat with all other desired appenders
I'd suggest you put it into an init() somewhere, where you are sure, that this will be executed before anything else. You can then remove all existing appenders on the root logger with
Logger.getRootLogger().getLoggerRepository().resetConfiguration();
and start with adding your own. You need log4j in the classpath of course for this to work.
Remark:
You can take any Logger.getLogger(...)
you like to add appenders. I just took the root logger because it is at the bottom of all things and will handle everything that is passed through other appenders in other categories (unless configured otherwise by setting the additivity flag).
If you need to know how logging works and how is decided where logs are written read this manual for more infos about that.
In Short:
Logger fizz = LoggerFactory.getLogger("com.fizz")
will give you a logger for the category "com.fizz".
For the above example this means that everything logged with it will be referred to the console and file appender on the root logger.
If you add an appender to
Logger.getLogger("com.fizz").addAppender(newAppender)
then logging from fizz
will be handled by alle the appenders from the root logger and the newAppender
.
You don't create Loggers with the configuration, you just provide handlers for all possible categories in your system.
As part of your jvm arguments you can set -Dlog4j.configuration=file:"<FILE_PATH>"
. Where FILE_PATH is the path of your log4j.properties file.
Please note that as of log4j2, the new system variable to use is log4j.configurationFile
and you put in the actual path to the file (i.e. without the file:
prefix) and it will automatically load the factory based on the extension of the configuration file:
-Dlog4j.configurationFile=/path/to/log4jconfig.{ext}
You can redirect forward or mask your domain name in godaddy but I don't know about other hosting sites.Have a look on this link
There's a easy way to paginate a table using breedjs (jQuery plugin), see the example:
HTML
<table>
<thead>
<tr>
<th>Name</th>
<th>Gender</th>
<th>Age</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr b-scope="people" b-loop="person in people" b-paginate="5">
<td>{{person.name}}</td>
<td>{{person.gender}}</td>
<td>{{person.age}}</td>
<td>{{person.email}}</td>
</tr>
</tbody>
</table>
<ul></ul>
JS
var data={ people: [ {...}, {...}, ...] };
$(function() {
breed.run({
scope: 'people',
input: data,
runEnd: function(){ //This runEnd is just to mount the page buttons
for(i=1 ; i<=breed.getPageCount('people') ; i++){
$('ul').append(
$('<li>',{
html: i,
onclick: "breed.paginate({scope: 'people', page: " + i + "});"
})
);
}
}
});
});
Every time you want to change pages, just call:
breed.paginate({scope: 'people', page: pageNumber);
For single example of spec file you need to add line number at the last , For Example
rspec spec/controllers/api/v1/card_list_controller_spec.rb:35
For single file you can specify your file path, For Example
rspec spec/controllers/api/v1/card_list_controller_spec.rb
For Whole Rspec Example in spec folder, you can try with this command
bundle exec rspec spec
The problem with editing JavaScript like you can CSS and HTML is that there is no clean way to propagate the changes. JavaScript can modify the DOM, send Ajax requests, and dynamically modify existing objects and functions at runtime. So, once you have loaded a page with JavaScript, it might be completely different after the JavaScript has run. The browser would have to keep track of every modification your JavaScript code performs so that when you edit the JS, it rolls back the changes to a clean page.
But, you can modify JavaScript dynamically a few other ways:
javascript: alert (1);
The first two options are great because you can modify any JavaScript variables and functions currently in scope. However, you won't be able to modify the code and run it with a "just-served" page like you can with the third option.
Other than that, as far as I know, there is no edit-and-run JavaScript editor in the browser. Hope this helps,
I just found this when googling to solve the same problem, and had to make a minor change to the solution to make it work in my situation, as I had 2 similar substrings, "Sun" and "Sunstruck" to search for. The offered solution was locating the wrong entry when searching for "Sun". Data in column B
I added another column C, formulaes C1=" "&B1&" " and changed the search to =COUNTIF(B1:B10,"* "&A1&" *")>0, the extra column to allow finding the first of last entry in the concatenated string.
SQL Server Authentication Modes
SQL Server 2008 offers two authentication mode options:
Windows authentication mode requires users to provide a valid Windows username and password to access the database server. In enterprise environments, these credentials are normally Active Directory domain credentials.
Mixed authentication mode allows the use of Windows credentials but supplements them with local SQL Server user accounts that the administrator may create and maintain within SQL Server.
I got this same error inside a stored procedure, in the where clause. i discovered that the problem ocurred with a local declared variable, previously loaded by the same table/column.
I resolved it casting the data to single char type.
It's a bit late, but I think your problem was your URL. If instead of
http://127.0.0.1:8080/test.html?target=bob
you had
http://127.0.0.1:8080/test.html#/?target=bob
I'm pretty sure it would have worked. Angular is really picky about its #/
Try using an empty collapse argument within the paste function:
paste(sdata, collapse = '')
It's nice that Go has a Duration
type -- having explicitly defined units can prevent real-world problems.
And because of Go's strict type rules, you can't multiply a Duration by an integer -- you must use a cast in order to multiply common types.
/*
MultiplyDuration Hide semantically invalid duration math behind a function
*/
func MultiplyDuration(factor int64, d time.Duration) time.Duration {
return time.Duration(factor) * d // method 1 -- multiply in 'Duration'
// return time.Duration(factor * int64(d)) // method 2 -- multiply in 'int64'
}
The official documentation demonstrates using method #1:
To convert an integer number of units to a Duration, multiply:
seconds := 10
fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
But, of course, multiplying a duration by a duration should not produce a duration -- that's nonsensical on the face of it. Case in point, 5 milliseconds times 5 milliseconds produces 6h56m40s
. Attempting to square 5 seconds results in an overflow (and won't even compile if done with constants).
By the way, the int64
representation of Duration
in nanoseconds "limits the largest representable duration to approximately 290 years", and this indicates that Duration
, like int64
, is treated as a signed value: (1<<(64-1))/(1e9*60*60*24*365.25) ~= 292
, and that's exactly how it is implemented:
// A Duration represents the elapsed time between two instants
// as an int64 nanosecond count. The representation limits the
// largest representable duration to approximately 290 years.
type Duration int64
So, because we know that the underlying representation of Duration
is an int64
, performing the cast between int64
and Duration
is a sensible NO-OP -- required only to satisfy language rules about mixing types, and it has no effect on the subsequent multiplication operation.
If you don't like the the casting for reasons of purity, bury it in a function call as I have shown above.
Don't forget to check if the conversion was successful!
bool ok;
auto str= tr("1337");
str.toDouble(&ok); // returns 1337.0, ok set to true
auto strr= tr("LEET");
strr.toDouble(&ok); // returns 0.0, ok set to false
The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.
If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.
Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.
In the sender you set:
byte [] IP= { (byte)192, (byte)168, 1, 106 };
InetAddress address = InetAddress.getByAddress(IP);
but might be simpler to use the address in string form:
InetAddress address = InetAddress.getByName("192.168.1.106");
In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.
Here's a simple UDP Receiver that works :
import java.io.IOException;
import java.net.*;
public class Receiver {
public static void main(String[] args) {
int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
new Receiver().run(port);
}
public void run(int port) {
try {
DatagramSocket serverSocket = new DatagramSocket(port);
byte[] receiveData = new byte[8];
String sendString = "polo";
byte[] sendData = sendString.getBytes("UTF-8");
System.out.printf("Listening on udp:%s:%d%n",
InetAddress.getLocalHost().getHostAddress(), port);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
while(true)
{
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData(), 0,
receivePacket.getLength() );
System.out.println("RECEIVED: " + sentence);
// now send acknowledgement packet back to sender
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
receivePacket.getAddress(), receivePacket.getPort());
serverSocket.send(sendPacket);
}
} catch (IOException e) {
System.out.println(e);
}
// should close serverSocket in finally block
}
}
You could use inline styles and define the width in the <th>
tag. Make it so that the sum of the widths = 100%.
<tr>
<th style="width:10%">Size</th>
<th style="width:30%">Bust</th>
<th style="width:50%">Waist</th>
<th style="width:10%">Hips</th>
</tr>
Typically using inline styles is not ideal, however this does provide flexibility because you can get very specific and granular with exact widths.
You can create a RegExp
object to make it a bit more readable
str.replace(new RegExp('/'), 'foobar');
If you want to replace all of them add the "g"
flag
str.replace(new RegExp('/', 'g'), 'foobar');
In Unix systems the end of a line is represented with a line feed (LF). In windows a line is represented with a carriage return (CR) and a line feed (LF) thus (CRLF). when you get code from git that was uploaded from a unix system they will only have an LF.
If you are a single developer working on a windows machine, and you don't care that git automatically replaces LFs to CRLFs, you can turn this warning off by typing the following in the git command line
git config core.autocrlf true
If you want to make an intelligent decision how git should handle this, read the documentation
Here is a snippet
Formatting and Whitespace
Formatting and whitespace issues are some of the more frustrating and subtle problems that many developers encounter when collaborating, especially cross-platform. It’s very easy for patches or other collaborated work to introduce subtle whitespace changes because editors silently introduce them, and if your files ever touch a Windows system, their line endings might be replaced. Git has a few configuration options to help with these issues.
core.autocrlf
If you’re programming on Windows and working with people who are not (or vice-versa), you’ll probably run into line-ending issues at some point. This is because Windows uses both a carriage-return character and a linefeed character for newlines in its files, whereas Mac and Linux systems use only the linefeed character. This is a subtle but incredibly annoying fact of cross-platform work; many editors on Windows silently replace existing LF-style line endings with CRLF, or insert both line-ending characters when the user hits the enter key.
Git can handle this by auto-converting CRLF line endings into LF when you add a file to the index, and vice versa when it checks out code onto your filesystem. You can turn on this functionality with the core.autocrlf setting. If you’re on a Windows machine, set it to true – this converts LF endings into CRLF when you check out code:
$ git config --global core.autocrlf true
If you’re on a Linux or Mac system that uses LF line endings, then you don’t want Git to automatically convert them when you check out files; however, if a file with CRLF endings accidentally gets introduced, then you may want Git to fix it. You can tell Git to convert CRLF to LF on commit but not the other way around by setting core.autocrlf to input:
$ git config --global core.autocrlf input
This setup should leave you with CRLF endings in Windows checkouts, but LF endings on Mac and Linux systems and in the repository.
If you’re a Windows programmer doing a Windows-only project, then you can turn off this functionality, recording the carriage returns in the repository by setting the config value to false:
$ git config --global core.autocrlf false
For lists, use enumerate
for field, possible_values in enumerate(fields):
print(field, possible_values)
iteritems
will not work for list objects
Public
- means that the class (program) is available for use by any other class.
Static
- creates a class. Can also be applied to variables and methods,making them class methods/variables instead of just local to a particular instance of the class.
Void
- this means that no product is returned when the class completes processing. Compare this with helper classes that provide a return value to the main class,these operate like functions; these do not have void in the declaration.
It's faster to avoid using regular expressions, if you're just trying to find the first substring match within an array of string values. You can add your own array searching function:
Code:
Array.prototype.findFirstSubstring = function(s) {
for(var i = 0; i < this.length;i++)
{
if(this[i].indexOf(s) !== -1)
return i;
}
return -1;
};
Usage:
i.findFirstSubstring('height');
Returns:
-1 if not found or the array index of the first substring occurrence if it is found (in your case would be 2
)
TextView tekst = (TextView) findViewById(R.id.editText1);
You cannot cast EditText
to TextView
.
I was facing the same problem when import projects into IntelliJ.
for in my case first, check SDK details and check you have configured JDK correctly or not.
Go to File-> Project Structure-> platform Settings-> SDKs
Check your JDK is correct or not.
Next, I Removed project from IntelliJ and delete all IntelliJ and IDE related files and folder from the project folder (.idea, .settings, .classpath, dependency-reduced-pom). Also, delete the target folder and re-import the project.
The above solution worked in my case.
function calc()
{
if (document.getElementById('xxx').checked)
{
document.getElementById('totalCost').value = 10;
} else {
calculate();
}
}
HTML
<input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>
Reference link: http://www.programering.com/a/MTNyUDMwATA.html
Steps I followed
1) Execute the command adb nodaemon server
in command prompt
Output at command prompt will be: The following error occurred cannot bind 'tcp:5037'
The original ADB server port binding failed
2) Enter the following command query which using port 5037
netstat -ano | findstr "5037"
The following information will be prompted on command prompt: TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 9288
3) View the task manager, close all adb.exe
4) Restart eclipse or other IDE
The above steps worked for me.
My mistake, the resource files WERE actually copied to target/test-classes
. The problem seemed to be due to spaces in my project name, e.g. Project%20Name
.
I'm now loading the file as follows and it works:
org.apache.commons.io.FileUtils.toFile(myClass().getResource("resourceFile.txt")??);
Or, (taken from Java: how to get a File from an escaped URL?) this may be better (no dependency on Apache Commons):
myClass().getResource("resourceFile.txt")??.toURI();
var rad_id = document.getElementById('<%=radio_btn_lst.ClientID %>');
var radio = rad_id.getElementsByTagName("input");
radio[0].checked = true;
//this for javascript in asp.net try this in .aspx page
// if you select other radiobutton increase [0] to [1] or [2] like this
I got some good hints from the answers on this page. I adapted it a bit for my use and thought I could share.
// lets say we have 2 ajax functions that needs to be "synchronized".
// In other words, we want to know when both are completed.
function foo1(callback) {
$.ajax({
url: '/echo/html/',
success: function(data) {
alert('foo1');
callback();
}
});
}
function foo2(callback) {
$.ajax({
url: '/echo/html/',
success: function(data) {
alert('foo2');
callback();
}
});
}
// here is my simplified solution
ajaxSynchronizer = function() {
var funcs = [];
var funcsCompleted = 0;
var callback;
this.add = function(f) {
funcs.push(f);
}
this.synchronizer = function() {
funcsCompleted++;
if (funcsCompleted == funcs.length) {
callback.call(this);
}
}
this.callWhenFinished = function(cb) {
callback = cb;
for (var i = 0; i < funcs.length; i++) {
funcs[i].call(this, this.synchronizer);
}
}
}
// this is the function that is called when both ajax calls are completed.
afterFunction = function() {
alert('All done!');
}
// this is how you set it up
var synchronizer = new ajaxSynchronizer();
synchronizer.add(foo1);
synchronizer.add(foo2);
synchronizer.callWhenFinished(afterFunction);
There are some limitations here, but for my case it was ok. I also found that for more advanced stuff it there is also a AOP plugin (for jQuery) that might be useful: http://code.google.com/p/jquery-aop/
In case you want jquery validate to auto pick validations on dynamically added items, you can simply remove and add validation on the whole form like below
//remove validations on entire form
$("#yourFormId")
.removeData("validator")
.removeData("unobtrusiveValidation");
//Simply add it again
$.validator
.unobtrusive
.parse("#yourFormId");
You could do something like this:
$("#txtArea").on("keypress",function(e) {_x000D_
var key = e.keyCode;_x000D_
_x000D_
// If the user has pressed enter_x000D_
if (key == 13) {_x000D_
document.getElementById("txtArea").value =document.getElementById("txtArea").value + "\n";_x000D_
return false;_x000D_
}_x000D_
else {_x000D_
return true;_x000D_
}_x000D_
});
_x000D_
<textarea id="txtArea"></textarea>
_x000D_
There is an other way to load jQuery dynamically (source). You could also use
document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"><\/script>');
It's considered bad practice to use document.write
, but for sake of completion it's good to mention it.
See Why is document.write considered a "bad practice"? for the reasons. The pro is that document.write
does block your page from loading other assests, so there is no need to create a callback function.
In your case, because of the constraint you need to delete the duplicated records.
created_at
date - in this case I'm keeping the oldestUSING
to filter the right rowsWITH duplicated AS (
SELECT id,
count(*)
FROM products
GROUP BY id
HAVING count(*) > 1),
ordered AS (
SELECT p.id,
created_at,
rank() OVER (partition BY p.id ORDER BY p.created_at) AS rnk
FROM products o
JOIN duplicated d ON d.id = p.id ),
products_to_delete AS (
SELECT id,
created_at
FROM ordered
WHERE rnk = 2
)
DELETE
FROM products
USING products_to_delete
WHERE products.id = products_to_delete.id
AND products.created_at = products_to_delete.created_at;
<a href="" onMouseOver="document.MyImage.src='http://icons.iconarchive.com/icons/uiconstock/round-edge-social/72/ask-icon.png';" onMouseOut="document.MyImage.src='http://icons.iconarchive.com/icons/uiconstock/round-edge-social/72/arto-icon.png';">
<img src="http://icons.iconarchive.com/icons/uiconstock/round-edge-social/72/arto-icon.png" name="MyImage">
The general idea behind creating "optional arguments" is to first define an intermediate command that scans ahead to detect what characters are coming up next in the token stream and then inserts the relevant macros to process the argument(s) coming up as appropriate. This can be quite tedious (although not difficult) using generic TeX programming. LaTeX's \@ifnextchar
is quite useful for such things.
The best answer for your question is to use the new xparse
package. It is part of the LaTeX3 programming suite and contains extensive features for defining commands with quite arbitrary optional arguments.
In your example you have a \sec
macro that either takes one or two braced arguments. This would be implemented using xparse
with the following:
\documentclass{article} \usepackage{xparse} \begin{document} \DeclareDocumentCommand\sec{ m g }{% {#1% \IfNoValueF {#2} { and #2}% }% } (\sec{Hello}) (\sec{Hello}{Hi}) \end{document}
The argument { m g }
defines the arguments of \sec
; m
means "mandatory argument" and g
is "optional braced argument". \IfNoValue(T)(F)
can then be used to check whether the second argument was indeed present or not. See the documentation for the other types of optional arguments that are allowed.
Yes, there are a number of ways that you can do this. The "fastest" way would be to add CSS to the div similar to the following
#term-defs {
height: 300px;
overflow: scroll; }
This will force the div to be scrollable, but this might not get the best effect. Another route would be to absolute fix the position of the items at the top, you can play with this by doing something like this.
#top {
position: fixed;
top: 0;
left: 0;
z-index: 999;
width: 100%;
height: 23px;
}
This will fix it to the top, on top of other content with a height of 23px.
The final implementation will depend on what effect you really want.
You can proceed in this way. It must work for you as well!
Step 1:
virtualenv venv
source venv/bin/activate
Step 2:
sudo python3 -m pip install opencv-python==3.4.2.16
sudo python3 -m pip install opencv-contrib-python==3.4.2.16
Step 3:
import cv2
sift = cv2.xfeatures2d.SIFT_create()
Don't use cv2.SIFT() . It will raise an exception.
You can, using CSS variables (more precisely called CSS custom properties).
style="--my-color-var: orange;"
background-color: var(--my-color-var);
div {
width: 100px;
height: 100px;
position: relative;
border: 1px solid black;
}
div:after {
background-color: var(--my-color-var);
content: '';
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
}
_x000D_
<div style="--my-color-var: orange;"></div>
_x000D_
.bubble {
position: relative;
width: 30px;
height: 15px;
padding: 0;
background: #FFF;
border: 1px solid #000;
border-radius: 5px;
text-align: center;
background-color: var(--bubble-color);
}
.bubble:after {
content: "";
position: absolute;
top: 4px;
left: -4px;
border-style: solid;
border-width: 3px 4px 3px 0;
border-color: transparent var(--bubble-color);
display: block;
width: 0;
z-index: 1;
}
.bubble:before {
content: "";
position: absolute;
top: 4px;
left: -5px;
border-style: solid;
border-width: 3px 4px 3px 0;
border-color: transparent #000;
display: block;
width: 0;
z-index: 0;
}
_x000D_
<div class='bubble' style="--bubble-color: rgb(100,255,255);"> 100 </div>
_x000D_
You should not attempt to parse HTML with regex. HTML is not a regular language, so any regex you come up with will likely fail on some esoteric edge case. Please refer to the seminal answer to this question for specifics. While mostly formatted as a joke, it makes a very good point.
The following examples are Java, but the regex will be similar -- if not identical -- for other languages.
String target = someString.replaceAll("<[^>]*>", "");
Assuming your non-html does not contain any < or > and that your input string is correctly structured.
If you know they're a specific tag -- for example you know the text contains only <td>
tags, you could do something like this:
String target = someString.replaceAll("(?i)<td[^>]*>", "");
Edit: Omega brought up a good point in a comment on another post that this would result in multiple results all being squished together if there were multiple tags.
For example, if the input string were <td>Something</td><td>Another Thing</td>
, then the above would result in SomethingAnother Thing
.
In a situation where multiple tags are expected, we could do something like:
String target = someString.replaceAll("(?i)<td[^>]*>", " ").replaceAll("\\s+", " ").trim();
This replaces the HTML with a single space, then collapses whitespace, and then trims any on the ends.
SWIFT 3. Example for the first element
let wordByLanguage = ["English": 5, "Spanish": 4, "Polish": 3, "Arabic": 2]
if let firstLang = wordByLanguage.first?.key {
print(firstLang) // English
}
Let's start by the following example:
Now we have 3 options to merge changes of feature branch into master branch:
Merge commits
Will keep all commits history of the feature branch and move them into the master branch
Will add extra dummy commit.
Rebase and merge
Will append all commits history of the feature branch in the front of the master branch
Will NOT add extra dummy commit.
Squash and merge
Will group all feature branch commits into one commit then append it in the front of the master branch
Will add extra dummy commit.
You can find below how the master branch will look after each one of them.
In all cases:
We can safely DELETE the feature branch.
After Xcode 6.1 Beta the code below works, slight edit on Tom S code that stopped working with the 6.1 beta (worked with previous beta):
if UIApplication.sharedApplication().respondsToSelector("registerUserNotificationSettings:") {
// It's iOS 8
var types = UIUserNotificationType.Badge | UIUserNotificationType.Sound | UIUserNotificationType.Alert
var settings = UIUserNotificationSettings(forTypes: types, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
} else {
// It's older
var types = UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound | UIRemoteNotificationType.Alert
UIApplication.sharedApplication().registerForRemoteNotificationTypes(types)
}
You can escape it by preceding it with a \
(making it \/
), or you could use new RegExp('/')
to avoid escaping the regex.
See example in JSFiddle.
'/'.match(/\//) // matches /
'/'.match(new RegExp('/') // matches /
When app is in background as shanegao you can use
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
if ( application.applicationState == UIApplicationStateInactive || application.applicationState == UIApplicationStateBackground )
{
//opened from a push notification when the app was on background
}
}
But if you want to launch the application and when app is closed and you want to debug your application you can go to Edit Scheme and in left menu select Run and then in launch select Wait for executable to be launched and then you application launch when you click on push notification
Edit Scheme > Run > Wait for executable to be launched
Javascript is base of jQuery.
jQuery is a wrapper of JavaScript, with much pre-written functionality and DOM traversing.
I think 2 update calls should do
update VersionedFields
set Value = replace(value,'<iframe','<a><iframe')
update VersionedFields
set Value = replace(value,'> </iframe>','</a>')
Because timedelta is defined like:
class datetime.timedelta([days,] [seconds,] [microseconds,] [milliseconds,] [minutes,] [hours,] [weeks])
All arguments are optional and default to 0.
You can easily say "Three days and four milliseconds" with optional arguments that way.
>>> datetime.timedelta(days=3, milliseconds=4)
datetime.timedelta(3, 0, 4000)
>>> datetime.timedelta(3, 0, 0, 4) #no need for that.
datetime.timedelta(3, 0, 4000)
And for str casting, it returns a nice formatted value instead of __repr__
to improve readability. From docs:
str(t) Returns a string in the form [D day[s], ][H]H:MM:SS[.UUUUUU], where D is negative for negative t. (5)
>>> datetime.timedelta(seconds = 42).__repr__()
'datetime.timedelta(0, 42)'
>>> datetime.timedelta(seconds = 42).__str__()
'0:00:42'
Checkout documentation:
http://docs.python.org/library/datetime.html#timedelta-objects
Needs to be:
if (document.forms[0].elements["checkAddress"].checked == true)
Assuming you have one form, otherwise use the form name.
As a side note, don't call the element and the function in the same name it can cause weird conflicts.
(1)This is the native javascript solution for this issue. It works on most of modern browsers.
function export2csv() {_x000D_
let data = "";_x000D_
const tableData = [];_x000D_
const rows = document.querySelectorAll("table tr");_x000D_
for (const row of rows) {_x000D_
const rowData = [];_x000D_
for (const [index, column] of row.querySelectorAll("th, td").entries()) {_x000D_
// To retain the commas in the "Description" column, we can enclose those fields in quotation marks._x000D_
if ((index + 1) % 3 === 0) {_x000D_
rowData.push('"' + column.innerText + '"');_x000D_
} else {_x000D_
rowData.push(column.innerText);_x000D_
}_x000D_
}_x000D_
tableData.push(rowData.join(","));_x000D_
}_x000D_
data += tableData.join("\n");_x000D_
const a = document.createElement("a");_x000D_
a.href = URL.createObjectURL(new Blob([data], { type: "text/csv" }));_x000D_
a.setAttribute("download", "data.csv");_x000D_
document.body.appendChild(a);_x000D_
a.click();_x000D_
document.body.removeChild(a);_x000D_
}
_x000D_
table {_x000D_
border-collapse: collapse;_x000D_
}_x000D_
_x000D_
td, th {_x000D_
border: 1px solid #aaa;_x000D_
padding: 0.5rem;_x000D_
text-align: left;_x000D_
}_x000D_
_x000D_
td {_x000D_
font-size: 0.875rem;_x000D_
}_x000D_
_x000D_
.btn-group {_x000D_
padding: 1rem 0;_x000D_
}_x000D_
_x000D_
button {_x000D_
background-color: #fff;_x000D_
border: 1px solid #000;_x000D_
margin-top: 0.5rem;_x000D_
border-radius: 3px;_x000D_
padding: 0.5rem 1rem;_x000D_
font-size: 1rem;_x000D_
}_x000D_
_x000D_
button:hover {_x000D_
cursor: pointer;_x000D_
background-color: #000;_x000D_
color: #fff;_x000D_
}
_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Name</th>_x000D_
<th>Author</th>_x000D_
<th>Description</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>jQuery</td>_x000D_
<td>John Resig</td>_x000D_
<td>The Write Less, Do More, JavaScript Library.</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>React</td>_x000D_
<td>Jordan Walke</td>_x000D_
<td>React makes it painless to create interactive UIs.</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Vue.js</td>_x000D_
<td>Yuxi You</td>_x000D_
<td>The Progressive JavaScript Framework.</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
_x000D_
<div class="btn-group">_x000D_
<button onclick="export2csv()">csv</button>_x000D_
</div>
_x000D_
(2) If you want a pure javascript library, FileSaver.js could help you save the code snippets for triggering file download. Besides, FileSaver.js will not be responsible for constructing content for exporting. You have to construct the content by yourself in the format you want.
Escape sequences must be interpreted by SOMETHING to be converted to color. The standard CMD.EXE used by java when started from the command line, doesn't support this so therefore Java does not.
I use this:
private void MainForm_Load(object sender, EventArgs e)
{
if (Settings.Instance.HideAtStartup)
{
BeginInvoke(new MethodInvoker(delegate
{
Hide();
}));
}
}
Obviously you have to change the if condition with yours.
For large files, what I did was read the file line by line and read each line into an array. Then, once the array reached a certain size, append it to a new file.
for line in open("file.txt", "r"):
list.append(line)
if len(list) == 1000000:
output.writelines(list)
del list[:]
JSON.stringify
takes more optional arguments.
Try:
JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab
From:
How can I beautify JSON programmatically?
Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre>
tag to get newlines to show.
GROUP BY meetingID
HAVING COUNT(caseID) < 4 AND COUNT(caseID) > 2
Just try to send a session variable when you press log in. And on the welcome page, first check whether that session is empty like this in the page load or in the Init Event:
if(Session["UserID"] == null || Session["UserID"] == "")
{
Response.Redirect("Login.aspx");
}
css :hover
kinda is like js onmouseover
row1 {
// your css
}
row1:hover {
color: red;
}
row1:hover #a, .b, .c:nth-child[3] {
border: 1px solid red;
}
not too sure how it works but css applies styles to echo'ed ids
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.
The Python Book © 2015 Imagine Publishing Ltd, simply distunguishes the difference by the following hint mentioned in page 10 as:
An interpreted language such as Python is one where the source code is converted to machine code and then executed each time the program runs. This is different from a compiled language such as C, where the source code is only converted to machine code once – the resulting machine code is then executed each time the program runs.
Here's a solution using jQuery:
<script type="text/javascript">
$('#container').css('opacity', 0);
$(window).load(function() {
$('#container').css('opacity', 1);
});
</script>
I put this script just after my </body>
tag. Just replace "#container" with a selector for the DOM element(s) you want to hide. I tried several variations of this (including .hide()
/.show()
, and .fadeOut()
/.fadeIn()
), and just setting the opacity seems to have the fewest ill effects (flicker, changing page height, etc.). You can also replace css('opacity', 0)
with fadeTo(100, 1)
for a smoother transition. (No, fadeIn()
won't work, at least not under jQuery 1.3.2.)
Now the caveats: I implemented the above because I'm using TypeKit and there's an annoying flicker when you refresh the page and the fonts take a few hundred milliseconds to load. So I don't want any text to appear on the screen until TypeKit has loaded. But obviously you're in big trouble if you use the code above and something on your page fails to load. There are two obvious ways that it could be improved:
I won't bother implementing the loading indicator here, but the time limit is easy. Just add this to the script above:
$(document).ready(function() {
setTimeout('$("#container").css("opacity", 1)', 1000);
});
So now, worst-case scenario, your page will take an extra second to appear.
long n = long.Parse(date.ToString("yyyyMMddHHmmss"));
For Retrofit1.9 with OkHttp3 users, here is the solution,
.setClient(new Ok3Client(new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).build()))
I've created config/initializers/secret_key.rb
file and I wrote only following line of code:
Rails.application.config.secret_key_base = ENV["SECRET_KEY_BASE"]
But I think that solution posted by @Erik Trautman is more elegant ;)
Edit: Oh, and finally I found this advice on Heroku: https://devcenter.heroku.com/changelog-items/426 :)
Enjoy!
- Method 1
select max(salary) from Employees
where salary< (select max(salary) from Employees)
- Method 2
select MAX(salary) from Employees
where salary not in(select MAX(salary) from Employees)
- Method 3
select MAX(salary) from Employees
where salary!= (select MAX(salary) from Employees )
Use this, two<anything any number of times><end of line>
's/two.*$/BLAH/g'
You have a version conflict, please verify whether compiled version and JVM of Tomcat version are same. you can do it by examining tomcat startup .bat , looking for JAVA_HOME
Guessing you probably just want to format the output date? then this is what you are after
SELECT *, DATE_FORMAT(date,'%d/%m/%Y') AS niceDate
FROM table
ORDER BY date DESC
LIMIT 0,14
Or do you actually want to sort by Day before Month before Year?
Curl does that by default without any parameters or flags, I would use it for your purposes:
curl $url > /dev/null 2>&1
Curl is more about streams and wget is more about copying sites based on this comparison.
mail -s "Your Subject" [email protected] < /file/with/mail/content
(/file/with/mail/content
should be a plaintext file, not a file attachment or an image, etc)
The setTimeout/setInterval solutions presented here will only work in specific circumstances.
The problem shows up especially in older Internet Explorer versions up to 8.
The variables affecting the success of these setTimeout/setInterval solutions are:
1) dynamic or static HTML
2) cached or non cached requests
3) size of the complete HTML document
4) chunked or non chunked transfer encoding
the original (native Javascript) code solving this specific issue is here:
https://github.com/dperini/ContentLoaded
http://javascript.nwbox.com/ContentLoaded (test)
this is the code from which the jQuery team have built their implementation.
try:
value = raw_input()
do_stuff(value) # next line was found
except (EOFError):
break #end of file reached
This seems to be proper usage of raw_input when dealing with the end of the stream of input from piped input. [Refer this post][1]
select substring(your_field, CHARINDEX(';',your_field)+1 ,CHARINDEX('[',your_field)-CHARINDEX(';',your_field)-1) from your_table
Can't get the others to work. I believe you just want what is in between ';' and '[' in all cases regardless of how long the string in between is. After specifying the field in the substring function, the second argument is the starting location of what you will extract. That is, where the ';' is + 1 (fourth position - the c), because you don't want to include ';'. The next argument takes the location of the '[' (position 14) and subtracts the location of the spot after the ';' (fourth position - this is why I now subtract 1 in the query). This basically says substring(field,location I want substring to begin, how long I want substring to be). I've used this same function in other cases. If some of the fields don't have ';' and '[', you'll want to filter those out in the "where" clause, but that's a little different than the question. If your ';' was say... ';;;', you would use 3 instead of 1 in the example. Hope this helps!
On POSIX, ultimately you want to be invoking the TIOCGWINSZ
(Get WINdow SiZe) ioctl()
call. Most languages ought to have some sort of wrapper for that. E.g in Perl you can use Term::Size:
use Term::Size qw( chars );
my ( $columns, $rows ) = chars \*STDOUT;
You could achieve that simply by wrapping the image by a <div>
and adding overflow: hidden
to that element:
<div class="img-wrapper">
<img src="..." />
</div>
.img-wrapper {
display: inline-block; /* change the default display type to inline-block */
overflow: hidden; /* hide the overflow */
}
Also it's worth noting that <img>
element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px
gap at the bottom of the image.
That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align
property to the image with a value other than baseline
.
Additionally for a better user experience, you could add transition
to the images.
Thus we'll end up with the following:
.img-wrapper img {
transition: all .2s ease;
vertical-align: middle;
}
Open Network and Sharing Center and go to the Change adapter settings in the sidebar.
Right-click on the host-only adapter in the list of adapters and then Configure button -> Driver tab -> Update driver button.
Select Browse my computer ... and in the next dialog select Let me pick .... You should see the list with just host-only driver in it.
Select it and click next. After the driver is updated, please try using host-only network in a VM again.
See http://php.net/manual/en/function.pathinfo.php
pathinfo(__FILE__, PATHINFO_FILENAME);
The best way to secure phpMyAdmin is the combination of all these 4:
1. Change phpMyAdmin URL
2. Restrict access to localhost only.
3. Connect through SSH and tunnel connection to a local port on your computer
4. Setup SSL to already encrypted SSH connection. (x2 security)
Here is how to do these all with: Ubuntu 16.4 + Apache 2 Setup Windows computer + PuTTY to connect and tunnel the SSH connection to a local port:
# Secure Web Serving of phpMyAdmin (change URL of phpMyAdmin):
sudo nano /etc/apache2/conf-available/phpmyadmin.conf
/etc/phpmyadmin/apache.conf
Change: phpmyadmin URL by this line:
Alias /newphpmyadminname /usr/share/phpmyadmin
Add: AllowOverride All
<Directory /usr/share/phpmyadmin>
Options FollowSymLinks
DirectoryIndex index.php
AllowOverride Limit
...
sudo systemctl restart apache2
sudo nano /usr/share/phpmyadmin/.htaccess
deny from all
allow from 127.0.0.1
alias phpmyadmin="sudo nano /usr/share/phpmyadmin/.htaccess"
alias myip="echo ${SSH_CONNECTION%% *}"
# Secure Web Access to phpMyAdmin:
Make sure pma.yourdomain.com is added to Let's Encrypt SSL configuration:
https://www.digitalocean.com/community/tutorials/how-to-secure-apache-with-let-s-encrypt-on-ubuntu-16-04
PuTTY => Source Port (local): <local_free_port> - Destination: 127.0.0.1:443 (OR localhost:443) - Local, Auto - Add
C:\Windows\System32\drivers\etc
Notepad - Run As Administrator - open: hosts
127.0.0.1 pma.yourdomain.com
https://pma.yourdomain.com:<local_free_port>/newphpmyadminname/ (HTTPS OK, SSL VPN OK)
https://localhost:<local_free_port>/newphpmyadminname/ (HTTPS ERROR, SSL VPN OK)
# Check to make sure you are on SSH Tunnel
1. Windows - CMD:
ping pma.yourdomain.com
ping www.yourdomain.com
# See PuTTY ports:
netstat -ano |find /i "listening"
2. Test live:
https://pma.yourdomain.com:<local_free_port>/newphpmyadminname/
If you are able to do these all successfully,
you now have your own url path for phpmyadmin,
you denied all access to phpmyadmin except localhost,
you connected to your server with SSH,
you tunneled that connection to a port locally,
you connected to phpmyadmin as if you are on your server,
you have additional SSL conenction (HTTPS) to phpmyadmin in case something leaks or breaks.
CSS3 introduces new units that are measured relative to the viewport, which is the window in this case. These are vh
and vw
, which measure viewport height and width, respectively. Here is a simple CSS only solution:
img {
max-width: 100%;
max-height: 100vh;
height: auto;
}
The one caveat to this is that it only works if there are no other elements contributing height on the page.
A simple way is to tell IIS to send your custom error file for HTTP requests. The file can then contain a meta redirect, a JavaScript redirect and instructions with link, etc... Importantly, you can still check "Require SSL" for the site (or folder) and this will work.
</configuration>
</system.webServer>
<httpErrors>
<clear/>
<!--redirect if connected without SSL-->
<error statusCode="403" subStatusCode="4" path="errors\403.4_requiressl.html" responseMode="File"/>
</httpErrors>
</system.webServer>
</configuration>
Here's the best practice (in my humble experience). Selecting these four packages will also update all other dependencies to the appropriate versions that will help you keep your environment consistent. The latter is a common problem others have expressed in earlier responses. This solution doesn't need the terminal.
Just in case anyone arrives here and was hoping for VB (I did, and I didn't enter c# as a search term), here's the basics of the first response..
Public Shared Function ConvertDataTableToHTML(dt As DataTable) As String
Dim html As String = "<table>"
html += "<tr>"
For i As Integer = 0 To dt.Columns.Count - 1
html += "<td>" + System.Web.HttpUtility.HtmlEncode(dt.Columns(i).ColumnName) + "</td>"
Next
html += "</tr>"
For i As Integer = 0 To dt.Rows.Count - 1
html += "<tr>"
For j As Integer = 0 To dt.Columns.Count - 1
html += "<td>" + System.Web.HttpUtility.HtmlEncode(dt.Rows(i)(j).ToString()) + "</td>"
Next
html += "</tr>"
Next
html += "</table>"
Return html
End Function
Looking at your classpath you exclude src/main/resources
and src/test/resources
:
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources"/>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources"/>
Is there a reason for it? Try not to exclude a classpath to spring-config.xml
:)
String source = "24/10/17";
String[] sourceSplit= source.split("/");
int anno= Integer.parseInt(sourceSplit[2]);
int mese= Integer.parseInt(sourceSplit[1]);
int giorno= Integer.parseInt(sourceSplit[0]);
GregorianCalendar calendar = new GregorianCalendar();
calendar.set(anno,mese-1,giorno);
Date data1= calendar.getTime();
SimpleDateFormat myFormat = new SimpleDateFormat("20yy-MM-dd");
String dayFormatted= myFormat.format(data1);
System.out.println("data formattata,-->"+dayFormatted);
Send canvas image to PHP:
var photo = canvas.toDataURL('image/jpeg');
$.ajax({
method: 'POST',
url: 'photo_upload.php',
data: {
photo: photo
}
});
Here's PHP script:
photo_upload.php
<?php
$data = $_POST['photo'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
mkdir($_SERVER['DOCUMENT_ROOT'] . "/photos");
file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/photos/".time().'.png', $data);
die;
?>
You could also use the php native funcion get_browser()
IMPORTANT NOTE: You should have a browscap.ini file.
You can use the call
command...
Type: call /?
Usage: call [drive:][path]filename [batch-parameters]
For example call "Example File/Input File/My Program.bat"
[This is also capable with calling files that have a .exe, .cmd, .txt, etc.
NOTE: THIS COMMAND DOES NOT ALWAYS WORK!!!
Not all computers are capable to run this command, but if it does work than it is very useful, and you won't have to open a brand new window...
I would suggest using closest
, which selects the closest matching parent element:
$('input[name="submitButton"]').closest("form");
Instead of filtering by the name, I would do this:
$('input[type=submit]').closest("form");
Go to C:\app\insolution\product\11.2.0\client_1\BIN and find oci.dll. Right click on it -->Properties -->Under Security tab, click on Edit -->Then Click on Add Button --> Here add two new users with names IUSR and IIS_IUSRS and give them full controls. That's it.
just to extend @GabLeRoux's answer:
[<img src="https://img.youtube.com/vi/<VIDEO ID>/maxresdefault.jpg" width="50%">](https://youtu.be/<VIDEO ID>)
this way you will be able to adjust the size of the thumbnail image in the README.md file on you Github repo.
Pythonic
X = X[:, :, None]
which is equivalent to
X = X[:, :, numpy.newaxis]
and
X = numpy.expand_dims(X, axis=-1)
But as you are explicitly asking about stacking images,
I would recommend going for stacking the list
of images np.stack([X1, X2, X3])
that you may have collected in a loop.
If you do not like the order of the dimensions you can rearrange with np.transpose()
If you want to delete all subdirectories under /path/to/base
, for example
/path/to/base/dir1
/path/to/base/dir2
/path/to/base/dir3
but you don't want to delete the root /path/to/base
, you have to add -mindepth 1
and -maxdepth 1
options, which will access only the subdirectories under /path/to/base
-mindepth 1
excludes the root /path/to/base
from the matches.
-maxdepth 1
will ONLY match subdirectories immediately under /path/to/base
such as /path/to/base/dir1
, /path/to/base/dir2
and /path/to/base/dir3
but it will not list subdirectories of these in a recursive manner. So these example subdirectories will not be listed:
/path/to/base/dir1/dir1
/path/to/base/dir2/dir1
/path/to/base/dir3/dir1
and so forth.
So , to delete all the sub-directories under /path/to/base
which are older than 10 days;
find /path/to/base -mindepth 1 -maxdepth 1 -type d -ctime +10 | xargs rm -rf
You can also use the Grid View its also Responsive its something like this:
#wrapper {
width: auto;
height: auto;
box-sizing: border-box;
display: grid;
grid-auto-flow: row;
grid-template-columns: repeat(6, 1fr);
}
#left{
text-align: left;
grid-column: 1/4;
}
#right {
text-align: right;
grid-column: 4/6;
}
and the HTML should look like this :
<div id="wrapper">
<div id="left" > ...some awesome stuff </div>
<div id="right" > ...some awesome stuff </div>
</div>
here is a link for more information:
https://www.w3schools.com/css/css_rwd_grid.asp
im quite new but i thougt i could share my little experience
I ran into the same problem, and was able to fix it by manually deleting all the files in the TFS cache, located here:
%LocalAppData%\Microsoft\Team Foundation\3.0\Cache
or 4.0
, 5.0
, etc.
After finding this StackOverflow question/answer
Complex type is getting null in a ApiController parameter
the [FromBody] attribute on the controller method needs to be [FromUri] since a GET does not have a body. After this change the "filter" complex object is passed correctly.