Packages and stored procedures in Oracle execute by default using the rights of the package/procedure OWNER, not the currently logged on user.
So if you call a package that creates a user for example, its the package owner, not the calling user that needs create user privilege. The caller just needs to have execute permission on the package.
If you would prefer that the package should be run using the calling user's permissions, then when creating the package you need to specify AUTHID CURRENT_USER
Oracle documentation "Invoker Rights vs Definer Rights" has more information http://docs.oracle.com/cd/A97630_01/appdev.920/a96624/08_subs.htm#18575
Hope this helps.
First response - wanted to finally give back to a helpful community...
Wanted to add this to the responses for people still looking for simple a solution. I'm using a free product by Foxit Software - FoxItReader.
Here is the link to the version that works with the silent print - newer versions the silent print feature is still not working.
FoxitReader623.815_Setup
FOR %%f IN (*.pdf) DO ("C:\Program Files (x86)\Foxit Software\Foxit Reader\FoxitReader.exe" /t %%f "SPST-SMPICK" %%f & del %%f)
I simply created a command to loop through the directory and for each pdf file (FOR %%f IN *.pdf) open the reader silently (/t) get the next PDF (%%f) and send it to the print queue (SPST-SMPICK), then delete each PDF after I send it to the print queue (del%%f). Shashank showed an example of moving the files to another directory if that what you need to do
FOR %%X in ("%dir1%*.pdf") DO (move "%%~dpnX.pdf" p/)
Simple Way
if ($('#text-field > p.filled-text').length != 0)
git rm --cached remove_file
git add .gitignore
git commit -m "Excluding"
I had this error aswell.
I am working in mysql workbench. When giving the values they have to be inside "". That solved it for me.
I had this issue with a specific application and not the entire IIS site. In my case, access to the application directory was not the problem. Instead, I needed to give the application pool a recycle.
I think this was related to how the application was deployed and the IIS settings were set (done via scripts and a deployment agent).
For specific request one can set timeOut to 0 which is no timeout till we get reply from DB or other server
request.setTimeout(0)
You should check it against null
.
If you want to check if object x is null or not, you can do:
if(x != null)
But if it is not null, it can have properties which are null or empty. You will check those explicitly:
if(x.getProperty() != null)
For "empty" check, it depends on what type is involved. For a Java String
, you usually do:
if(str != null && !str.isEmpty())
As you haven't mentioned about any specific problem with this, difficult to tell.
Environment variables are kept in HKEY_LOCAL_MACHINE\SYSTEM\ControlSet\Control\Session Manager\Environment.
Many of the useful env vars, such as Path, are stored as REG_SZ. There are several ways to access the registry including REGEDIT:
REGEDIT /E <filename> "HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment"
The output starts with magic numbers. So to search it with the find command it needs to be typed and redirected: type <filename> | findstr -c:\"Path\"
So, if you just want to refresh the path variable in your current command session with what's in system properties the following batch script works fine:
RefreshPath.cmd:
@echo off REM This solution requests elevation in order to read from the registry. if exist %temp%\env.reg del %temp%\env.reg /q /f REGEDIT /E %temp%\env.reg "HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment" if not exist %temp%\env.reg ( echo "Unable to write registry to temp location" exit 1 ) SETLOCAL EnableDelayedExpansion for /f "tokens=1,2* delims==" %%i in ('type %temp%\env.reg ^| findstr -c:\"Path\"=') do ( set upath=%%~j echo !upath:\\=\! >%temp%\newpath ) ENDLOCAL for /f "tokens=*" %%i in (%temp%\newpath) do set path=%%i
If you are using the scafolded Identity and using Asp.net Core 2.2+ you can access the current user from a view like this:
@using Microsoft.AspNetCore.Identity
@inject SignInManager<IdentityUser> SignInManager
@inject UserManager<IdentityUser> UserManager
@if (SignInManager.IsSignedIn(User))
{
<p>Hello @User.Identity.Name!</p>
}
else
{
<p>You're not signed in!</p>
}
$(document).ready(function() {
$('#div2').hide(0);
$('#preview').on('click', function() {
$('#div1').hide(300, function() { // first hide div1
// then show div2
$('#div2').show(300);
});
});
});
You missed #
before div2
For windows: Best is to use pre-compiled package available from this site: http://www.lfd.uci.edu/%7Egohlke/pythonlibs/#scipy
The cleanest way is to test for it's existence, drop it if it exists, and then recreate it. You can't embed a "create proc" statement inside an IF statement. This should do nicely:
IF OBJECT_ID('MySproc', 'P') IS NOT NULL
DROP PROC MySproc
GO
CREATE PROC MySproc
AS
BEGIN
...
END
1 is substantially different from 2 and 3, since it leaves the array in tact, whereas the other two leave it empty.
I'd say #3 is pretty wacky and probably less efficient, so forget that.
Which leaves you with #1 and #2, and they do not do the same thing, so one cannot be "better" than the other. If the array is large and you don't need to keep it, generally scope will deal with it (but see NOTE), so generally, #1 is still the clearest and simplest method. Shifting each element off will not speed anything up. Even if there is a need to free the array from the reference, I'd just go:
undef @Array;
when done.
This won't work with subdomains.
domain.com correctly gets redirected to www.domain.com
but
images.domain.com gets redirected to www.images.domain.com
Instead of checking if the subdomain is "not www", check if there are two dots:
RewriteCond %{HTTP_HOST} ^(.*)$ [NC]
RewriteCond %{HTTP_HOST} !^(.*)\.(.*)\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ HTTP%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
You might be doing a PUT call for GET operation Please check once
Use PHPMailer instead: https://github.com/PHPMailer/PHPMailer
How to use it:
require('./PHPMailer/class.phpmailer.php');
$mail=new PHPMailer();
$mail->CharSet = 'UTF-8';
$body = 'This is the message';
$mail->IsSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = '123!@#';
$mail->SetFrom('[email protected]', $name);
$mail->AddReplyTo('[email protected]','no-reply');
$mail->Subject = 'subject';
$mail->MsgHTML($body);
$mail->AddAddress('[email protected]', 'title1');
$mail->AddAddress('[email protected]', 'title2'); /* ... */
$mail->AddAttachment($fileName);
$mail->send();
import subprocess
string="echo Hello world"
result=subprocess.getoutput(string)
print("result::: ",result)
If you want to measure CPU time, can use time.process_time()
for Python 3.3 and above:
import time
start = time.process_time()
# your code here
print(time.process_time() - start)
First call turns the timer on, and second call tells you how many seconds have elapsed.
There is also a function time.clock()
, but it is deprecated since Python 3.3 and will be removed in Python 3.8.
There are better profiling tools like timeit
and profile
, however time.process_time() will measure the CPU time and this is what you're are asking about.
If you want to measure wall clock time instead, use time.time()
.
td {
overflow: hidden;
max-width: 400px;
word-wrap: break-word;
}
Use the pointtype
and pointsize
options, e.g.
plot "./points.dat" using 1:2 pt 7 ps 10
where pt 7
gives you a filled circle and ps 10
is the size.
See: Plotting data.
The answer is no.
.class {
background-color: none; /* do not do this */
}
.class {
background-color: transparent;
}
background-color: transparent
accomplishes the same thing what you wanted to do with background-color: none
.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>
function showButtons () { $('#b1, #b2, #b3').show(); }
</script>
<style type="text/css">
#b1, #b2, #b3 {
display: none;
}
</style>
</head>
<body>
<a href="#" onclick="showButtons();">Show me the money!</a>
<input type="submit" id="b1" value="B1" />
<input type="submit" id="b2" value="B2"/>
<input type="submit" id="b3" value="B3" />
</body>
</html>
It should be pretty obvious from your question that you're actually just asking about the difference between git merge
and git rebase
.
So let's suppose you're in the common case - you've done some work on your master branch, and you pull from origin's, which also has done some work. After the fetch, things look like this:
- o - o - o - H - A - B - C (master)
\
P - Q - R (origin/master)
If you merge at this point (the default behavior of git pull), assuming there aren't any conflicts, you end up with this:
- o - o - o - H - A - B - C - X (master)
\ /
P - Q - R --- (origin/master)
If on the other hand you did the appropriate rebase, you'd end up with this:
- o - o - o - H - P - Q - R - A' - B' - C' (master)
|
(origin/master)
The content of your work tree should end up the same in both cases; you've just created a different history leading up to it. The rebase rewrites your history, making it look as if you had committed on top of origin's new master branch (R
), instead of where you originally committed (H
). You should never use the rebase approach if someone else has already pulled from your master branch.
Finally, note that you can actually set up git pull
for a given branch to use rebase instead of merge by setting the config parameter branch.<name>.rebase
to true. You can also do this for a single pull using git pull --rebase
.
'a' in x
and a quick search reveals some nice information about it: http://docs.python.org/3/tutorial/datastructures.html#dictionaries
You can use Object.keys(), "which returns an array of a given object's own enumerable property names, in the same order as we get with a normal loop."
You can use any object in place of stats
:
var stats = {_x000D_
a: 3,_x000D_
b: 6,_x000D_
d: 7,_x000D_
erijgolekngo: 35_x000D_
}_x000D_
/* this is the answer here */_x000D_
for (var key in Object.keys(stats)) {_x000D_
var t = Object.keys(stats)[key];_x000D_
console.log(t + " value =: " + stats[t]);_x000D_
}
_x000D_
List<String> arrayList = new ArrayList<String>();
Is generic where you want to hide implementation details while returning it to client, at later point of time you may change implementation from ArrayList
to LinkedList
transparently.
This mechanism is useful in cases where you design libraries etc., which may change their implementation details at some point of time with minimal changes on client side.
ArrayList<String> arrayList = new ArrayList<String>();
This mandates you always need to return ArrayList
. At some point of time if you would like to change implementation details to LinkedList
, there should be changes on client side also to use LinkedList
instead of ArrayList
.
Change ownership and permissions folder
sudo chown -R username.www-data /var/www
sudo chmod -R +rwx /var/www
Based on this forum post: https://groups.google.com/forum/#!topic/ggplot2/mK9DR3dKIBU
Sounds like the easiest thing to do is to add a line break (\n) before your x axis, and after your y axis labels. Seems a lot easier (although dumber) than the solutions posted above.
ggplot(mpg, aes(cty, hwy)) +
geom_point() +
xlab("\nYour_x_Label") + ylab("Your_y_Label\n")
Hope that helps!
You can also plot to a png file using gnuplot (which is free):
terminal commands
gnuplot> set title '<title>'
gnuplot> set ylabel '<yLabel>'
gnuplot> set xlabel '<xLabel>'
gnuplot> set grid
gnuplot> set term png
gnuplot> set output '<Output file name>.png'
gnuplot> plot '<fromfile.csv>'
note: you always need to give the right extension (.png here) at set output
Then it is also possible that the ouput is not lines, because your data is not continues. To fix this simply change the 'plot' line to:
plot '<Fromfile.csv>' with line lt -1 lw 2
More line editing options (dashes and line color ect.) at: http://gnuplot.sourceforge.net/demo_canvas/dashcolor.html
apt-get install gnuplot
)brew install gnuplot
)In most of the cases, if you are unable to export the certificate as a PFX (including the private key) is because MMC/IIS cannot find/don't have access to the private key (used to generate the CSR). These are the steps I followed to fix this issue:
Hope this helps!
You're missing a return
statement.
When the compiler looks at your code, it's sees a third path (the else
you didn't code for) that could occur but doesn't return a value. Hence not all code paths return a value
.
For my suggested fix, I put a return
after your loop ends. The other obvious spot - adding an else
that had a return
value to the if-else-if
- would break the for
loop.
public static bool isTwenty(int num)
{
for(int j = 1; j <= 20; j++)
{
if(num % j != 0)
{
return false;
}
else if(num % j == 0 && num == 20)
{
return true;
}
}
return false; //This is your missing statement
}
Although officially there is no limit specified by RFC 2616, many security protocols and recommendations state that maxQueryStrings on a server should be set to a maximum character limit of 1024. While the entire URL, including the querystring, should be set to a max of 2048 characters. This is to prevent the Slow HTTP Request DDOS vulnerability on a web server. This typically shows up as a vulnerability on the Qualys Web Application Scanner and other security scanners.
Please see the below example code for Windows IIS Servers with Web.config:
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxQueryString="1024" maxUrl="2048">
<headerLimits>
<add header="Content-type" sizeLimit="100" />
</headerLimits>
</requestLimits>
</requestFiltering>
</security>
</system.webServer>
This would also work on a server level using machine.config.
Note: Limiting query string and URL length may not completely prevent Slow HTTP Requests DDOS attack but it is one step you can take to prevent it.
I had to use COUNTIF() in my case as part of my SELECT columns AND to mimic a % of the number of times each item appeared in my results.
So I used this...
SELECT COL1, COL2, ... ETC
(1 / SELECT a.vcount
FROM (SELECT vm2.visit_id, count(*) AS vcount
FROM dbo.visitmanifests AS vm2
WHERE vm2.inactive = 0 AND vm2.visit_id = vm.Visit_ID
GROUP BY vm2.visit_id) AS a)) AS [No of Visits],
COL xyz
FROM etc etc
Of course you will need to format the result according to your display requirements.
You can get by this date:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
print(dateFormat.format(new Date());
A callback function is a function you provide to another piece of code, allowing it to be called by that code.
Why would you want to do this? Let's say there is a service you need to invoke. If the service returns immediately, you just:
For example, suppose the service were the factorial
function. When you want the value of 5!
, you would invoke factorial(5)
, and the following steps would occur:
Your current execution location is saved (on the stack, but that's not important)
Execution is handed over to factorial
When factorial
completes, it puts the result somewhere you can get to it
Execution comes back to where it was in [1]
Now suppose factorial
took a really long time, because you're giving it huge numbers and it needs to run on some supercomputing cluster somwhere. Let's say you expect it to take 5 minutes to return your result. You could:
Keep your design and run your program at night when you're asleep, so that you're not staring at the screen half the time
Design your program to do other things while factorial
is doing its thing
If you choose the second option, then callbacks might work for you.
In order to exploit a callback pattern, what you want is to be able to call factorial
in the following way:
factorial(really_big_number, what_to_do_with_the_result)
The second parameter, what_to_do_with_the_result
, is a function you send along to factorial
, in the hope that factorial
will call it on its result before returning.
Yes, this means that factorial
needs to have been written to support callbacks.
Now suppose that you want to be able to pass a parameter to your callback. Now you can't, because you're not going to be calling it, factorial
is. So factorial
needs to be written to allow you to pass your parameters in, and it will just hand them over to your callback when it invokes it. It might look like this:
factorial (number, callback, params)
{
result = number! // i can make up operators in my pseudocode
callback (result, params)
}
Now that factorial
allows this pattern, your callback might look like this:
logIt (number, logger)
{
logger.log(number)
}
and your call to factorial
would be
factorial(42, logIt, logger)
What if you want to return something from logIt
? Well, you can't, because factorial
isn't paying attention to it.
Well, why can't factorial
just return what your callback returns?
Since execution is meant to be handed over to the callback when factorial
is finished, it really shouldn't return anything to its caller. And ideally, it would somehow launch its work in another thread / process / machine and return immediately so that you can continue, maybe something like this:
factorial(param_1, param_2, ...)
{
new factorial_worker_task(param_1, param_2, ...);
return;
}
This is now an "asynchronous call", meaning that when you call it, it returns immediately but hasn't really done its job yet. So you do need mechanisms to check on it, and to obtain its result when its finished, and your program has gotten more complex in the process.
And by the way, using this pattern the factorial_worker_task
can launch your callback asynchronously and return immediately.
The answer is to stay within the callback pattern. Whenever you want to write
a = f()
g(a)
and f
is to be called asynchronously, you will instead write
f(g)
where g
is passed as a callback.
This fundamentally changes the flow-topology of your program, and takes some getting used to.
Your programming language could help you a lot by giving you a way to create functions on-the-fly. In the code immediately above, the function g
might be as small as print (2*a+1)
. If your language requires that you define this as a separate function, with an entirely unnecessary name and signature, then your life is going to get unpleasant if you use this pattern a lot.
If, on the other hand, you language allows you to create lambdas, then you are in much better shape. You will then end up writing something like
f( func(a) { print(2*a+1); })
which is so much nicer.
How would you pass the callback function to factorial
? Well, you could do it in a number of ways.
If the called function is running in the same process, you could pass a function pointer
Or maybe you want to maintain a dictionary of fn name --> fn ptr
in your program, in which case you could pass the name
Maybe your language allows you to define the function in-place, possible as a lambda! Internally it is creating some kind of object and passing a pointer, but you don't have to worry about that.
Perhaps the function you are calling is running on an entirely separate machine, and you are calling it using a network protocol like HTTP. You could expose your callback as an HTTP-callable function, and pass its URL.
You get the idea.
In this web era we have entered, the services we invoke are often over the network. We often do not have any control over those services i.e. we didn't write them, we don't maintain them, we can't ensure they're up or how they're performing.
But we can't expect our programs to block while we're waiting for these services to respond. Being aware of this, the service providers often design APIs using the callback pattern.
JavaScript supports callbacks very nicely e.g. with lambdas and closures. And there is a lot of activity in the JavaScript world, both on the browser as well as on the server. There are even JavaScript platforms being developed for mobile.
As we move forward, more and more of us will be writing asynchronous code, for which this understanding will be essential.
WITH cteRowNum AS (
SELECT DeptID, EmpName, Salary,
ROW_NUMBER() OVER(PARTITION BY DeptID ORDER BY Salary DESC) AS RowNum
FROM EmpDetails
)
SELECT DeptID, EmpName, Salary,Rownum
FROM cteRowNum
WHERE RowNum in(1,2);
I think we need to write more specific media query. Make sure if you write one media query it should be not effect to other view (Mob,Tab,Desk) otherwise it can be trouble. I would like suggest to write one basic media query for respective device which cover both view and one orientation media query that you can specific code more about orientation view its for good practice. we Don't need to write both media orientation query at same time. You can refer My below example. I am sorry if my English writing is not much good. Ex:
For Mobile
@media screen and (max-width:767px) {
..This is basic media query for respective device.In to this media query CSS code cover the both view landscape and portrait view.
}
@media screen and (min-width:320px) and (max-width:767px) and (orientation:landscape) {
..This orientation media query. In to this orientation media query you can specify more about CSS code for landscape view.
}
For Tablet
@media screen and (max-width:1024px){
..This is basic media query for respective device.In to this media query CSS code cover the both view landscape and portrait view.
}
@media screen and (min-width:768px) and (max-width:1024px) and (orientation:landscape){
..This orientation media query. In to this orientation media query you can specify more about CSS code for landscape view.
}
Desktop
make as per your design requirement enjoy...(:
Thanks, Jitu
Just in case someone makes the same error I did before stumbling on this page, that is, adding CSS
reset rules (like the very popular reset by Eric Meyer used on millions of websites) after including bootstrap.
Also, perhaps I should point out that such reset won't be necessary with bootstrap given bootsrap actually implements the normalize.css v3.0.2 reset.
I realize this is stale for a while and an answer had been selected, but how about the alternative to allow the foreign key to be NULL and then choose ON DELETE SET NULL.
Basically, your table should be changed like so:
ALTER TABLE 'bericht'
DROP FOREIGN KEY 'your_foreign_key';
ALTER TABLE 'bericht'
ADD CONSTRAINT 'your_foreign_key' FOREIGN KEY ('column_foreign_key') REFERENCES 'other_table' ('column_parent_key') ON UPDATE CASCADE ON DELETE SET NULL;
Personally I would recommend using both "ON UPDATE CASCADE" as well as "ON DELETE SET NULL" to avoid unnecessary complications, however your set up may dictate a different approach.
Hope this helps.
simplejson module is simply 1,5 times faster than json (On my computer, with simplejson 2.1.1 and Python 2.7 x86).
If you want, you can try the benchmark: http://abral.altervista.org/jsonpickle-bench.zip On my PC simplejson is faster than cPickle. I would like to know also your benchmarks!
Probably, as said Coady, the difference between simplejson and json is that simplejson includes _speedups.c. So, why don't python developers use simplejson?
If you are using Razor, you cannot access the field directly, but you can manage its value.
The idea is that the first Microsoft approach drive the developers away from Web Development and make it easy for Desktop programmers (for example) to make web applications.
Meanwhile, the web developers, did not understand this tricky strange way of ASP.NET.
Actually this hidden input is rendered on client-side, and the ASP has no access to it (it never had). However, in time you will see its a piratical way and you may rely on it, when you get use with it. The web development differs from the Desktop or Mobile.
The model is your logical unit, and the hidden field (and the whole view page) is just a representative view of the data. So you can dedicate your work on the application or domain logic and the view simply just serves it to the consumer - which means you need no detailed access and "brainstorming" functionality in the view.
The controller actually does work you need for manage the hidden or general setup. The model serves specific logical unit properties and functionality and the view just renders it to the end user, simply said. Read more about MVC.
Model
public class MyClassModel
{
public int Id { get; set; }
public string Name { get; set; }
public string MyPropertyForHidden { get; set; }
}
This is the controller aciton
public ActionResult MyPageView()
{
MyClassModel model = new MyClassModel(); // Single entity, strongly-typed
// IList model = new List<MyClassModel>(); // or List, strongly-typed
// ViewBag.MyHiddenInputValue = "Something to pass"; // ...or using ViewBag
return View(model);
}
The view is below
//This will make a Model property of the View to be of MyClassModel
@model MyNamespace.Models.MyClassModel // strongly-typed view
// @model IList<MyNamespace.Models.MyClassModel> // list, strongly-typed view
// ... Some Other Code ...
@using(Html.BeginForm()) // Creates <form>
{
// Renders hidden field for your model property (strongly-typed)
// The field rendered to server your model property (Address, Phone, etc.)
Html.HiddenFor(model => Model.MyPropertyForHidden);
// For list you may use foreach on Model
// foreach(var item in Model) or foreach(MyClassModel item in Model)
}
// ... Some Other Code ...
The view with ViewBag:
// ... Some Other Code ...
@using(Html.BeginForm()) // Creates <form>
{
Html.Hidden(
"HiddenName",
ViewBag.MyHiddenInputValue,
new { @class = "hiddencss", maxlength = 255 /*, etc... */ }
);
}
// ... Some Other Code ...
We are using Html Helper to render the Hidden field or we could write it by hand - <input name=".." id=".." value="ViewBag.MyHiddenInputValue">
also.
The ViewBag is some sort of data carrier to the view. It does not restrict you with model - you can place whatever you like.
.format('MM/DD/YYYY HH:mm:ss')
In the current component's module import RouterModule.
Like:-
import {RouterModule} from '@angular/router';
@NgModule({
declarations:[YourComponents],
imports:[RouterModule]
...
It helped me.
Fix: Unlock your device before running it.
Hi Guys: Think I may have a fix for this:
Sounds ridiculous but try unlocking your Virtual Device; i.e. use your mouse to swipe and open. Your app should then work!!
Update: This function only avoids copy if it can, hence this is not the correct answer for this question. unutbu's answer is the right one.
a = a.astype(numpy.float32, copy=False)
numpy astype has a copy flag. Why shouldn't we use it ?
This code is working for me:
var datetime = new DateTime(2017, 10, 27, 14, 45, 53, 175, DateTimeKind.Local);
var text = datetime.ToString("o");
Console.WriteLine(text);
-- 2017-10-27T14:45:53.1750000+03:00
// datetime from string
var newDate = DateTime.ParseExact(text, "o", null);
Define two dates using new Date(). Calculate the time difference of two dates using date2. getTime() – date1. getTime(); Calculate the no. of days between two dates, divide the time difference of both the dates by no. of milliseconds in a day (10006060*24)
$('input[type="submit"]').click(function(){
$(this).css('color','red');
});
Use class, Demo:- http://jsfiddle.net/BX6Df/
$('input[type="submit"]').click(function(){
$(this).addClass('red');
});
if you want to toggle the color each click, you can try this:- http://jsfiddle.net/SMNks/
$('input[type="submit"]').click(function(){
$(this).toggleClass('red');
});
.red
{
background-color:red;
}
Updated answer for your comment.
$('input[type="submit"]').click(function(){
$('input[type="submit"].red').removeClass('red')
$(this).addClass('red');
});
PDO offers an alternative designed to replace mysql_escape_string() with the PDO::quote() method.
Here is an excerpt from the PHP website:
<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');
/* Simple string */
$string = 'Nice';
print "Unquoted string: $string\n";
print "Quoted string: " . $conn->quote($string) . "\n";
?>
The above code will output:
Unquoted string: Nice
Quoted string: 'Nice'
If we want to retrieve or update these attributes using existing, native JavaScript, then we can do so using the getAttribute and setAttribute methods as shown below:
Through JavaScript
<div id='strawberry-plant' data-fruit='12'></div>
<script>
// 'Getting' data-attributes using getAttribute
var plant = document.getElementById('strawberry-plant');
var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'
// 'Setting' data-attributes using setAttribute
plant.setAttribute('data-fruit','7'); // Pesky birds
</script>
Through jQuery
// Fetching data
var fruitCount = $(this).data('fruit');
OR
// If you updated the value, you will need to use below code to fetch new value
// otherwise above gives the old value which is intially set.
// And also above does not work in ***Firefox***, so use below code to fetch value
var fruitCount = $(this).attr('data-fruit');
// Assigning data
$(this).attr('data-fruit','7');
just give the surrounding <tr>
a custom class like:
<tr class="custom_centered">
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
and have the css only select <td>
s that are inside an <tr>
with your custom class.
tr.custom_centered td {
text-align: center;
}
like this you don't risk to override other tables or even override a bootstrap base class (like some of my predecessors suggested).
I recently had this case where I needed to append to a list continuously in one thread, loop through the items and check if the item was ready, it was an AsyncResult in my case and remove it from the list only if it was ready. I could not find any examples that demonstrated my problem clearly Here is an example demonstrating adding to list in one thread continuously and removing from the same list in another thread continuously The flawed version runs easily on smaller numbers but keep the numbers big enough and run a few times and you will see the error
The FLAWED version
import threading
import time
# Change this number as you please, bigger numbers will get the error quickly
count = 1000
l = []
def add():
for i in range(count):
l.append(i)
time.sleep(0.0001)
def remove():
for i in range(count):
l.remove(i)
time.sleep(0.0001)
t1 = threading.Thread(target=add)
t2 = threading.Thread(target=remove)
t1.start()
t2.start()
t1.join()
t2.join()
print(l)
Output when ERROR
Exception in thread Thread-63:
Traceback (most recent call last):
File "/Users/zup/.pyenv/versions/3.6.8/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/Users/zup/.pyenv/versions/3.6.8/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "<ipython-input-30-ecfbac1c776f>", line 13, in remove
l.remove(i)
ValueError: list.remove(x): x not in list
Version that uses locks
import threading
import time
count = 1000
l = []
lock = threading.RLock()
def add():
with lock:
for i in range(count):
l.append(i)
time.sleep(0.0001)
def remove():
with lock:
for i in range(count):
l.remove(i)
time.sleep(0.0001)
t1 = threading.Thread(target=add)
t2 = threading.Thread(target=remove)
t1.start()
t2.start()
t1.join()
t2.join()
print(l)
Output
[] # Empty list
Conclusion
As mentioned in the earlier answers while the act of appending or popping elements from the list itself is thread safe, what is not thread safe is when you append in one thread and pop in another
GPRESULT
is the right command, but it cannot be run without parameters. /v
or verbose option is difficult to manage without also outputting to a text file. E.G. I recommend using
gpresult /user myAccount /v > C:\dev\me.txt
--Ensure C:\Dev\me.txt exists
Another option is to display summary information only which may be entirely visible in the command window:
gpresult /user myAccount /r
The accounts are listed under the heading:
The user is a part of the following security groups
---------------------------------------------------
My solution was to add a space between the $ and the {.
For example:
@Value("${project.ftp.adresse}")
becomes
@Value("$ {project.ftp.adresse}")
If the component is an EJB, then, there shouldn't be a problem injecting an EM.
But....In JBoss 5, the JAX-RS integration isn't great. If you have an EJB, you cannot use scanning and you must manually list in the context-param resteasy.jndi.resource. If you still have scanning on, Resteasy will scan for the resource class and register it as a vanilla JAX-RS service and handle the lifecycle.
This is probably the problem.
Move your map variable into a scope where the event listener can use it. You are creating the map inside your initialize() function and nothing else can use it when created that way.
var map; //<-- This is now available to both event listeners and the initialize() function
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(40.5472,12.282715),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
What I do when I wonder something like the question asked here is go to the source.
expect().toBe()
is defined as:
function toBe() {
return {
compare: function(actual, expected) {
return {
pass: actual === expected
};
}
};
}
It performs its test with ===
which means that when used as expect(foo).toBe(true)
, it will pass only if foo
actually has the value true
. Truthy values won't make the test pass.
expect().toBeTruthy()
is defined as:
function toBeTruthy() {
return {
compare: function(actual) {
return {
pass: !!actual
};
}
};
}
A value is truthy if the coercion of this value to a boolean yields the value true
. The operation !!
tests for truthiness by coercing the value passed to expect
to a boolean. Note that contrarily to what the currently accepted answer implies, == true
is not a correct test for truthiness. You'll get funny things like
> "hello" == true
false
> "" == true
false
> [] == true
false
> [1, 2, 3] == true
false
Whereas using !!
yields:
> !!"hello"
true
> !!""
false
> !![1, 2, 3]
true
> !![]
true
(Yes, empty or not, an array is truthy.)
expect().toBeTrue()
is part of Jasmine-Matchers (which is registered on npm as jasmine-expect
after a later project registered jasmine-matchers
first).
expect().toBeTrue()
is defined as:
function toBeTrue(actual) {
return actual === true ||
is(actual, 'Boolean') &&
actual.valueOf();
}
The difference with expect().toBeTrue()
and expect().toBe(true)
is that expect().toBeTrue()
tests whether it is dealing with a Boolean
object. expect(new Boolean(true)).toBe(true)
would fail whereas expect(new Boolean(true)).toBeTrue()
would pass. This is because of this funny thing:
> new Boolean(true) === true
false
> new Boolean(true) === false
false
At least it is truthy:
> !!new Boolean(true)
true
elem.isDisplayed()
?Ultimately Protractor hands off this request to Selenium. The documentation states that the value produced by .isDisplayed()
is a promise that resolves to a boolean
. I would take it at face value and use .toBeTrue()
or .toBe(true)
. If I found a case where the implementation returns truthy/falsy values, I would file a bug report.
Without jQuery-UI accordion, one can simply do this:
<div class="section">
<div class="section-title">
Section 1
</div>
<div class="section-content">
Section 1 Content: Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.
</div>
</div>
<div class="section">
<div class="section-title">
Section 2
</div>
<div class="section-content">
Section 2 Content: Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.
</div>
</div>
And js
$( ".section-title" ).click(function() {
$(this).parent().find( ".section-content" ).slideToggle();
});
We can just use Audio and an object together like:
var audio = {};
audio['ubuntu'] = new Audio();
audio['ubuntu'].src="start.ogg";
audio['ubuntu'].play();
and even adding addEventListener
for play
and ended
In another way you can use window.location.href="your URL"
e.g.:
res.send('<script>window.location.href="your URL";</script>');
or:
return res.redirect("your url");
You could hard code it.
<div class="col-md-6" style="background-color:blue;">
</div>
<div class="col-md-6" style="background-color:white;">
</div>
You can also install R from this page:
https://cran.r-project.org/bin/macosx/
It works out of the box
It is not possible to get the users computer name with Javascript. You can get all details about the browser and network. But not more than that.
Like some one answered in one of the previous question today.
I already did a favor of visiting your website, May be I will return or refer other friends.. I also told you where I am and what OS, Browser and screen resolution I use Why do you want to know the color of my underwear? ;-)
You cannot do it using asp.net as well.
Easiest way to check if they are authenticated is Request.User.IsAuthenticated
I think (from memory)
There is no separate chromedriver binary for Windows 64 bit. Chromedriver 32 bit binary works for both 32 as well as 64 bit versions of Windows. As of today, you can find the latest version of chromedriver Windows binary at https://chromedriver.storage.googleapis.com/2.25/chromedriver_win32.zip
A PendingIntent is a token that you give to another application (e.g. Notification Manager, Alarm Manager or other 3rd party applications), which allows this other application to use the permissions of your application to execute a predefined piece of code. To perform a broadcast via a pending intent so get a PendingIntent via PendingIntent.getBroadcast(). To perform an activity via an pending intent you receive the activity via PendingIntent.getActivity().
You can use either HttpClient
or RestSharp
. Since I do not know what your code is, here is an example using HttpClient
:
using (var client = new HttpClient())
{
// This would be the like http://www.uber.com
client.BaseAddress = new Uri("Base Address/URL Address");
// serialize your json using newtonsoft json serializer then add it to the StringContent
var content = new StringContent(YourJson, Encoding.UTF8, "application/json")
// method address would be like api/callUber:SomePort for example
var result = await client.PostAsync("Method Address", content);
string resultContent = await result.Content.ReadAsStringAsync();
}
I think no one has given the correct answer to the question. My working solution is : 1. Just declare another class along with container-fluid class example(.maxx):
<div class="container-fluid maxx">_x000D_
<div class="row">_x000D_
<div class="col-sm-12">_x000D_
<p>Hello</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
.container-fluid.maxx {_x000D_
padding-left: 0px;_x000D_
padding-right: 0px; }
_x000D_
This will work 100% and will remove the padding from left and right. I hope this helps.
Had this problem a number of times on our setup, so I've made a check list.
This assumes you want phpMyAdmin connecting locally to MySQL using a UNIX socket rather than TCP/IP.
UNIX sockets should be slightly faster as they have less overhead and can be more secure as they can only be accessed locally.
Service
service mysqld status
service mysqld start
service mysqld restart
MySQL Config (my.cnf)
protocol=tcp
PHP Config (php.ini)
If you can connect locally from the command line, but not from phpMyAdmin, and the socket file is not in the default location:
mysqli.default_socket = *location*
pdo_myql.default_socket
and mysql.default_socket
just to be sureservice httpd restart
phpMyAdmin Config (config.inc.php)
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['socket'] = '*location*';
N.B.
As pointed out by @chk; Setting the $cfg['Servers'][$i]['host']
from localhost
to 127.0.0.1
just causes the connection to use TCP/IP rather than using the socket and is more of a workaround than a solution.
The MySQL config setting bind-address=
also only affects TCP/IP connections.
If you don't need remote connections, it is recommended to turn off TCP/IP listening with skip-networking
.
Copy the cell. Paste special as link. Will update with original. No formula though.
Declare @DatePeriod datetime
Set @DatePeriod = '2011-05-30'
Select ProductName,
IsNull([1],0) as 'Week 1',
IsNull([2],0) as 'Week 2',
IsNull([3],0) as 'Week 3',
IsNull([4],0) as 'Week 4',
IsNull([5], 0) as 'Week 5'
From
(
Select ProductName,
DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH, 0, '2011-05-30'), 0), '2011-05-30') +1 as [Weeks],
Sale as 'Sale'
From dbo.WeekReport
-- Only get rows where the date is the same as the DatePeriod
-- i.e DatePeriod is 30th May 2011 then only the weeks of May will be calculated
Where DatePart(Month, '2011-05-30')= DatePart(Month, @DatePeriod)
)p
Pivot (Sum(Sale) for Weeks in ([1],[2],[3],[4],[5])) as pv
OUTPUT LOOK LIKE THIS
a 0 0 0 0 20
b 0 0 0 0 4
c 0 0 0 0 3
Create views on two first "selects" and "union" them.
I had issue with the solutions mentioned above as specifying the string key would give me javax.el.PropertyNotFoundException. The code shown below worked for me. In this I used status to count the index of for each loop and displayed the value of index I am interested on
<c:forEach items="${requestScope.key}" var="map" varStatus="status" >
<c:if test="${status.index eq 1}">
<option><c:out value=${map.value}/></option>
</c:if>
</c:forEach>
This will squash second commit into the first one:
A-B-C-... -> AB-C-...
git filter-branch --commit-filter '
if [ "$GIT_COMMIT" = <sha1ofA> ];
then
skip_commit "$@";
else
git commit-tree "$@";
fi
' HEAD
Commit message for AB will be taken from B (although I'd prefer from A).
Has the same effect as Uwe Kleine-König's answer, but works for non-initial A as well.
The %pdb
magic command is good to use as well. Just say %pdb on
and subsequently the pdb
debugger will run on all exceptions, no matter how deep in the call stack. Very handy.
If you have a particular line that you want to debug, just raise an exception there (often you already are!) or use the %debug
magic command that other folks have been suggesting.
This problem happened with me and sovled by just add
respond_to :html, :json
to ApplicationController file
You can Check Devise issues on Github: https://github.com/plataformatec/devise/issues/2667
setInterval(function()
{
$.ajax({
type:"post",
url:"myurl.html",
datatype:"html",
success:function(data)
{
//do something with response data
}
});
}, 10000);//time in milliseconds
You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.
Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String
'Assign data to first item in array
compArray(1) = "asdf"
'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"
'Prints "ErrorState"
Debug.Print Computers("Computer Name")
Collections cannot be sorted so if you need to sort data you will probably want to use an array.
Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx
Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx
Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!
Edit:
Sub ArrayExample()
Dim subject As String
Dim TestArray() As String
Dim counter As Long
subject = "Example"
counter = Len(subject)
ReDim TestArray(1 To counter) As String
For counter = 1 To Len(subject)
TestArray(counter) = Right(Left(subject, counter), 1)
Next
End Sub
In Visual Studio please click 'Folder.ico' file in the Solution Explorer pane. Then you will see Properties pane. Change 'Copy to Output Directory' behavior to 'Copy if newer'. This will make Visual Studio copy the file to the output bin directory.
Now to get the file path using relative path just type:
string pathToIcoFile = AppDomain.CurrentDomain.BaseDirectory + "//FolderIcon//Folder.ico";
Hope that helped.
move c:\Sourcefoldernam\*.* e:\destinationFolder
^ This did not work for me for some reason
But when I tried using quotation marks, it suddenly worked:
move "c:\Sourcefoldernam\*.*" "e:\destinationFolder"
I think its because my directory had spaces in one of the folders. So if it doesn't work for you, try with quotation marks!
but as for this method, I don't understand the purpose of Integer.MAX_VALUE and Integer.MIN_VALUE.
By starting out with smallest
set to Integer.MAX_VALUE
and largest
set to Integer.MIN_VALUE
, they don't have to worry later about the special case where smallest
and largest
don't have a value yet. If the data I'm looking through has a 10
as the first value, then numbers[i]<smallest
will be true (because 10
is <
Integer.MAX_VALUE
) and we'll update smallest
to be 10
. Similarly, numbers[i]>largest
will be true
because 10
is >
Integer.MIN_VALUE
and we'll update largest
. And so on.
Of course, when doing this, you must ensure that you have at least one value in the data you're looking at. Otherwise, you end up with apocryphal numbers in smallest
and largest
.
Note the point Onome Sotu makes in the comments:
...if the first item in the array is larger than the rest, then the largest item will always be Integer.MIN_VALUE because of the else-if statement.
Which is true; here's a simpler example demonstrating the problem (live copy):
public class Example
{
public static void main(String[] args) throws Exception {
int[] values = {5, 1, 2};
int smallest = Integer.MAX_VALUE;
int largest = Integer.MIN_VALUE;
for (int value : values) {
if (value < smallest) {
smallest = value;
} else if (value > largest) {
largest = value;
}
}
System.out.println(smallest + ", " + largest); // 1, 2 -- WRONG
}
}
To fix it, either:
Don't use else
, or
Start with smallest
and largest
equal to the first element, and then loop the remaining elements, keeping the else if
.
Here's an example of that second one (live copy):
public class Example
{
public static void main(String[] args) throws Exception {
int[] values = {5, 1, 2};
int smallest = values[0];
int largest = values[0];
for (int n = 1; n < values.length; ++n) {
int value = values[n];
if (value < smallest) {
smallest = value;
} else if (value > largest) {
largest = value;
}
}
System.out.println(smallest + ", " + largest); // 1, 5
}
}
With delay and fade :
setTimeout(function(){
$(".alert").each(function(index){
$(this).delay(200*index).fadeTo(1500,0).slideUp(500,function(){
$(this).remove();
});
});
},2000);
This is my edited version : you just need to add an extra argument "autoClose".
example :
$('input[name="fieldName"]').datepicker({ autoClose: true});
also you can specify a close callback if you want. :)
replace datepicker.js with this:
!function( $ ) {
// Picker object
var Datepicker = function(element, options , closeCallBack){
this.element = $(element);
this.format = DPGlobal.parseFormat(options.format||this.element.data('date-format')||'dd/mm/yyyy');
this.autoClose = options.autoClose||this.element.data('date-autoClose')|| true;
this.closeCallback = closeCallBack || function(){};
this.picker = $(DPGlobal.template)
.appendTo('body')
.on({
click: $.proxy(this.click, this)//,
//mousedown: $.proxy(this.mousedown, this)
});
this.isInput = this.element.is('input');
this.component = this.element.is('.date') ? this.element.find('.add-on') : false;
if (this.isInput) {
this.element.on({
focus: $.proxy(this.show, this),
//blur: $.proxy(this.hide, this),
keyup: $.proxy(this.update, this)
});
} else {
if (this.component){
this.component.on('click', $.proxy(this.show, this));
} else {
this.element.on('click', $.proxy(this.show, this));
}
}
this.minViewMode = options.minViewMode||this.element.data('date-minviewmode')||0;
if (typeof this.minViewMode === 'string') {
switch (this.minViewMode) {
case 'months':
this.minViewMode = 1;
break;
case 'years':
this.minViewMode = 2;
break;
default:
this.minViewMode = 0;
break;
}
}
this.viewMode = options.viewMode||this.element.data('date-viewmode')||0;
if (typeof this.viewMode === 'string') {
switch (this.viewMode) {
case 'months':
this.viewMode = 1;
break;
case 'years':
this.viewMode = 2;
break;
default:
this.viewMode = 0;
break;
}
}
this.startViewMode = this.viewMode;
this.weekStart = options.weekStart||this.element.data('date-weekstart')||0;
this.weekEnd = this.weekStart === 0 ? 6 : this.weekStart - 1;
this.onRender = options.onRender;
this.fillDow();
this.fillMonths();
this.update();
this.showMode();
};
Datepicker.prototype = {
constructor: Datepicker,
show: function(e) {
this.picker.show();
this.height = this.component ? this.component.outerHeight() : this.element.outerHeight();
this.place();
$(window).on('resize', $.proxy(this.place, this));
if (e ) {
e.stopPropagation();
e.preventDefault();
}
if (!this.isInput) {
}
var that = this;
$(document).on('mousedown', function(ev){
if ($(ev.target).closest('.datepicker').length == 0) {
that.hide();
}
});
this.element.trigger({
type: 'show',
date: this.date
});
},
hide: function(){
this.picker.hide();
$(window).off('resize', this.place);
this.viewMode = this.startViewMode;
this.showMode();
if (!this.isInput) {
$(document).off('mousedown', this.hide);
}
//this.set();
this.element.trigger({
type: 'hide',
date: this.date
});
},
set: function() {
var formated = DPGlobal.formatDate(this.date, this.format);
if (!this.isInput) {
if (this.component){
this.element.find('input').prop('value', formated);
}
this.element.data('date', formated);
} else {
this.element.prop('value', formated);
}
},
setValue: function(newDate) {
if (typeof newDate === 'string') {
this.date = DPGlobal.parseDate(newDate, this.format);
} else {
this.date = new Date(newDate);
}
this.set();
this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
this.fill();
},
place: function(){
var offset = this.component ? this.component.offset() : this.element.offset();
this.picker.css({
top: offset.top + this.height,
left: offset.left
});
},
update: function(newDate){
this.date = DPGlobal.parseDate(
typeof newDate === 'string' ? newDate : (this.isInput ? this.element.prop('value') : this.element.data('date')),
this.format
);
this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
this.fill();
},
fillDow: function(){
var dowCnt = this.weekStart;
var html = '<tr>';
while (dowCnt < this.weekStart + 7) {
html += '<th class="dow">'+DPGlobal.dates.daysMin[(dowCnt++)%7]+'</th>';
}
html += '</tr>';
this.picker.find('.datepicker-days thead').append(html);
},
fillMonths: function(){
var html = '';
var i = 0
while (i < 12) {
html += '<span class="month">'+DPGlobal.dates.monthsShort[i++]+'</span>';
}
this.picker.find('.datepicker-months td').append(html);
},
fill: function() {
var d = new Date(this.viewDate),
year = d.getFullYear(),
month = d.getMonth(),
currentDate = this.date.valueOf();
this.picker.find('.datepicker-days th:eq(1)')
.text(DPGlobal.dates.months[month]+' '+year);
var prevMonth = new Date(year, month-1, 28,0,0,0,0),
day = DPGlobal.getDaysInMonth(prevMonth.getFullYear(), prevMonth.getMonth());
prevMonth.setDate(day);
prevMonth.setDate(day - (prevMonth.getDay() - this.weekStart + 7)%7);
var nextMonth = new Date(prevMonth);
nextMonth.setDate(nextMonth.getDate() + 42);
nextMonth = nextMonth.valueOf();
var html = [];
var clsName,
prevY,
prevM;
while(prevMonth.valueOf() < nextMonth) {zs
if (prevMonth.getDay() === this.weekStart) {
html.push('<tr>');
}
clsName = this.onRender(prevMonth);
prevY = prevMonth.getFullYear();
prevM = prevMonth.getMonth();
if ((prevM < month && prevY === year) || prevY < year) {
clsName += ' old';
} else if ((prevM > month && prevY === year) || prevY > year) {
clsName += ' new';
}
if (prevMonth.valueOf() === currentDate) {
clsName += ' active';
}
html.push('<td class="day '+clsName+'">'+prevMonth.getDate() + '</td>');
if (prevMonth.getDay() === this.weekEnd) {
html.push('</tr>');
}
prevMonth.setDate(prevMonth.getDate()+1);
}
this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
var currentYear = this.date.getFullYear();
var months = this.picker.find('.datepicker-months')
.find('th:eq(1)')
.text(year)
.end()
.find('span').removeClass('active');
if (currentYear === year) {
months.eq(this.date.getMonth()).addClass('active');
}
html = '';
year = parseInt(year/10, 10) * 10;
var yearCont = this.picker.find('.datepicker-years')
.find('th:eq(1)')
.text(year + '-' + (year + 9))
.end()
.find('td');
year -= 1;
for (var i = -1; i < 11; i++) {
html += '<span class="year'+(i === -1 || i === 10 ? ' old' : '')+(currentYear === year ? ' active' : '')+'">'+year+'</span>';
year += 1;
}
yearCont.html(html);
},
click: function(e) {
e.stopPropagation();
e.preventDefault();
var target = $(e.target).closest('span, td, th');
if (target.length === 1) {
switch(target[0].nodeName.toLowerCase()) {
case 'th':
switch(target[0].className) {
case 'switch':
this.showMode(1);
break;
case 'prev':
case 'next':
this.viewDate['set'+DPGlobal.modes[this.viewMode].navFnc].call(
this.viewDate,
this.viewDate['get'+DPGlobal.modes[this.viewMode].navFnc].call(this.viewDate) +
DPGlobal.modes[this.viewMode].navStep * (target[0].className === 'prev' ? -1 : 1)
);
this.fill();
this.set();
break;
}
break;
case 'span':
if (target.is('.month')) {
var month = target.parent().find('span').index(target);
this.viewDate.setMonth(month);
} else {
var year = parseInt(target.text(), 10)||0;
this.viewDate.setFullYear(year);
}
if (this.viewMode !== 0) {
this.date = new Date(this.viewDate);
this.element.trigger({
type: 'changeDate',
date: this.date,
viewMode: DPGlobal.modes[this.viewMode].clsName
});
}
this.showMode(-1);
this.fill();
this.set();
break;
case 'td':
if (target.is('.day') && !target.is('.disabled')){
var day = parseInt(target.text(), 10)||1;
var month = this.viewDate.getMonth();
if (target.is('.old')) {
month -= 1;
} else if (target.is('.new')) {
month += 1;
}
var year = this.viewDate.getFullYear();
this.date = new Date(year, month, day,0,0,0,0);
this.viewDate = new Date(year, month, Math.min(28, day),0,0,0,0);
this.fill();
this.set();
this.element.trigger({
type: 'changeDate',
date: this.date,
viewMode: DPGlobal.modes[this.viewMode].clsName
});
if(this.autoClose === true){
this.hide();
this.closeCallback();
}
}
break;
}
}
},
mousedown: function(e){
e.stopPropagation();
e.preventDefault();
},
showMode: function(dir) {
if (dir) {
this.viewMode = Math.max(this.minViewMode, Math.min(2, this.viewMode + dir));
}
this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();
}
};
$.fn.datepicker = function ( option, val ) {
return this.each(function () {
var $this = $(this);
var datePicker = $this.data('datepicker');
var options = typeof option === 'object' && option;
if (!datePicker) {
if (typeof val === 'function')
$this.data('datepicker', (datePicker = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options),val)));
else{
$this.data('datepicker', (datePicker = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options))));
}
}
if (typeof option === 'string') datePicker[option](val);
});
};
$.fn.datepicker.defaults = {
onRender: function(date) {
return '';
}
};
$.fn.datepicker.Constructor = Datepicker;
var DPGlobal = {
modes: [
{
clsName: 'days',
navFnc: 'Month',
navStep: 1
},
{
clsName: 'months',
navFnc: 'FullYear',
navStep: 1
},
{
clsName: 'years',
navFnc: 'FullYear',
navStep: 10
}],
dates:{
days: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"],
daysShort: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"],
daysMin: ["D", "L", "Ma", "Me", "J", "V", "S", "D"],
months: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"],
monthsShort: ["Jan", "Fév", "Mar", "Avr", "Mai", "Jui", "Jul", "Aou", "Sep", "Oct", "Nov", "Déc"],
today: "Aujourd'hui",
clear: "Effacer",
weekStart: 1,
format: "dd/mm/yyyy"
},
isLeapYear: function (year) {
return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0))
},
getDaysInMonth: function (year, month) {
return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
},
parseFormat: function(format){
var separator = format.match(/[.\/\-\s].*?/),
parts = format.split(/\W+/);
if (!separator || !parts || parts.length === 0){
throw new Error("Invalid date format.");
}
return {separator: separator, parts: parts};
},
parseDate: function(date, format) {
var parts = date.split(format.separator),
date = new Date(),
val;
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
if (parts.length === format.parts.length) {
var year = date.getFullYear(), day = date.getDate(), month = date.getMonth();
for (var i=0, cnt = format.parts.length; i < cnt; i++) {
val = parseInt(parts[i], 10)||1;
switch(format.parts[i]) {
case 'dd':
case 'd':
day = val;
date.setDate(val);
break;
case 'mm':
case 'm':
month = val - 1;
date.setMonth(val - 1);
break;
case 'yy':
year = 2000 + val;
date.setFullYear(2000 + val);
break;
case 'yyyy':
year = val;
date.setFullYear(val);
break;
}
}
date = new Date(year, month, day, 0 ,0 ,0);
}
return date;
},
formatDate: function(date, format){
var val = {
d: date.getDate(),
m: date.getMonth() + 1,
yy: date.getFullYear().toString().substring(2),
yyyy: date.getFullYear()
};
val.dd = (val.d < 10 ? '0' : '') + val.d;
val.mm = (val.m < 10 ? '0' : '') + val.m;
var date = [];
for (var i=0, cnt = format.parts.length; i < cnt; i++) {
date.push(val[format.parts[i]]);
}
return date.join(format.separator);
},
headTemplate: '<thead>'+
'<tr>'+
'<th class="prev">‹</th>'+
'<th colspan="5" class="switch"></th>'+
'<th class="next">›</th>'+
'</tr>'+
'</thead>',
contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>'
};
DPGlobal.template = '<div class="datepicker dropdown-menu">'+
'<div class="datepicker-days">'+
'<table class=" table-condensed">'+
DPGlobal.headTemplate+
'<tbody></tbody>'+
'</table>'+
'</div>'+
'<div class="datepicker-months">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
'</table>'+
'</div>'+
'<div class="datepicker-years">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
'</table>'+
'</div>'+
'</div>';
}( window.jQuery );
From the man page:
-h, --no-filename
Suppress the prefixing of file names on output. This is the default when there
is only one file (or only standard input) to search.
The default date format depends on the language setting for the database server. You can also change it per session, like:
set language french
select cast(getdate() as varchar(50))
-->
févr 8 2013 9:45AM
The pointer-events property allows for control over how HTML elements respond to mouse/touch events – including CSS hover/active states, click/tap events in Javascript, and whether or not the cursor is visible.
That's not the only way you disable a Link, but a good CSS way which work in IE10+ and all new browsers:
.current-page {_x000D_
pointer-events: none;_x000D_
color: grey;_x000D_
}
_x000D_
<a href="#" class="current-page">This link is disabled</a>
_x000D_
For delays as large as one minute, sleep()
is a nice choice.
If someday, you want to pause on delays smaller than one second, you may want to consider poll()
with a timeout.
Both are POSIX.
As noted in the comments, there are some things to try: gc.collect
(@EdChum) may clear stuff, for example. At least from my experience, these things sometimes work and often don't.
There is one thing that always works, however, because it is done at the OS, not language, level.
Suppose you have a function that creates an intermediate huge DataFrame, and returns a smaller result (which might also be a DataFrame):
def huge_intermediate_calc(something):
...
huge_df = pd.DataFrame(...)
...
return some_aggregate
Then if you do something like
import multiprocessing
result = multiprocessing.Pool(1).map(huge_intermediate_calc, [something_])[0]
Then the function is executed at a different process. When that process completes, the OS retakes all the resources it used. There's really nothing Python, pandas, the garbage collector, could do to stop that.
First, ensure MySQL is running. Command: mysqld start
If you still cannot connect then: What does your /etc/my.cnf look like? (or /etc/msyql/my.cnf)
The other 2 posts are correct in that you need to check your socket because 2002 is a socket error.
A great tutorial on setting up LAMP is: http://library.linode.com/lamp-guides/centos-5.3/index-print
Sometimes you need to call the base class' implementation, when you aren't in the derived function...It still works:
struct Base
{
virtual int Foo()
{
return -1;
}
};
struct Derived : public Base
{
virtual int Foo()
{
return -2;
}
};
int main(int argc, char* argv[])
{
Base *x = new Derived;
ASSERT(-2 == x->Foo());
//syntax is trippy but it works
ASSERT(-1 == x->Base::Foo());
return 0;
}
Actually, that does not delete the variable/property. All it will do is set its value to None
, therefore the variable will still take up space in memory. If you want to completely wipe all existence of the variable from memory, you can just type:
del self.left
Above answers did not work for me.
Adding the attribute preserveAspectRatio="xMidYMin"
to the <svg>
tag did the trick though. The viewBox
attribute needs to be specified for this to work as well.
Source: Mozilla developer network
EXEC sp_helpuser
or
SELECT * FROM sysusers
Both of these select all the users of the current database (not the server).
Converting of a hash map to a string of query parameters:
Map<String, String> params = new HashMap<>();
params.put("msisdn", msisdn);
params.put("email", email);
params.put("clientVersion", clientVersion);
params.put("clientType", clientType);
params.put("issuerName", issuerName);
params.put("applicationName", applicationName);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.queryParam(entry.getKey(), entry.getValue());
}
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", "application/json");
HttpEntity<String> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, new HttpEntity(headers), String.class);
Here is a non-numpy solution:
>>> a = [[40, 10], [50, 11]]
>>> [float(sum(l))/len(l) for l in zip(*a)]
[45.0, 10.5]
From the official documentation regarding the Formatter class:
The constructor takes two optional arguments: a message format string and a date format string.
So change
# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s")
to
# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s",
"%Y-%m-%d %H:%M:%S")
If you want to kill the Sticky Service,the following command NOT WORKING:
adb shell am force-stop <PACKAGE>
adb shell kill <PID>
The following command is WORKING:
adb shell pm disable <PACKAGE>
If you want to restart the app,you must run command below first:
adb shell pm enable <PACKAGE>
To change into another directory use WORKDIR. All the RUN, CMD and ENTRYPOINT commands after WORKDIR will be executed from that directory.
RUN git clone XYZ
WORKDIR "/XYZ"
RUN make
You need ImageMagick
and GhostScript
<?php
$im = new imagick('file.pdf[0]');
$im->setImageFormat('jpg');
header('Content-Type: image/jpeg');
echo $im;
?>
The [0]
means page 1
.
I had similar issue. Earlier I was using Maven 3 to build the project. After switching to maven 2 , I had the above error.
Solved it by switching to Maven 3.
I am working on an angular js app, andhavecome across a similar issue. What i did was display the image from the db, then created a button to remove or keep the current image. If the user decided to keep the current image, i changed the ng-submit attribute to another function whihc doesnt require image validation, and updated the record in the db without touching the original image path name. The remove image function also changed the ng-submit attribute value back to a function that submits the form and includes image validation and upload. Also a bit of javascript to slide the into view to upload a new image.
You need to create WifiConfiguration
instance like this:
String networkSSID = "test";
String networkPass = "pass";
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + networkSSID + "\""; // Please note the quotes. String should contain ssid in quotes
Then, for WEP network you need to do this:
conf.wepKeys[0] = "\"" + networkPass + "\"";
conf.wepTxKeyIndex = 0;
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
For WPA network you need to add passphrase like this:
conf.preSharedKey = "\""+ networkPass +"\"";
For Open network you need to do this:
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
Then, you need to add it to Android wifi manager settings:
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetwork(conf);
And finally, you might need to enable it, so Android connects to it:
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
break;
}
}
UPD: In case of WEP, if your password is in hex, you do not need to surround it with quotes.
I think your only option here is a constant. With that said - don't use it - stick with nulls instead of bogus dates.
create table atable
(
atableID int IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
Modified datetime DEFAULT '1/1/1753'
)
Here is a small tool scanip that will help you to get all ip addresses and their corresponding mac addresses in the network (Works on Linux).
Even after adding @Autowire if your class is not a RestController or Configuration Class, the applicationContext object was coming as null. Tried Creating new class with below and it is working fine:
@Component
public class SpringContext implements ApplicationContextAware{
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws
BeansException {
this.applicationContext=applicationContext;
}
}
you can then implement a getter method in the same class as per your need to get the bean. Like:
applicationContext.getBean(String serviceName,Interface.Class)
Actually, it appears that urllib2 can do an HTTP HEAD request.
The question that @reto linked to, above, shows how to get urllib2 to do a HEAD request.
Here's my take on it:
import urllib2
# Derive from Request class and override get_method to allow a HEAD request.
class HeadRequest(urllib2.Request):
def get_method(self):
return "HEAD"
myurl = 'http://bit.ly/doFeT'
request = HeadRequest(myurl)
try:
response = urllib2.urlopen(request)
response_headers = response.info()
# This will just display all the dictionary key-value pairs. Replace this
# line with something useful.
response_headers.dict
except urllib2.HTTPError, e:
# Prints the HTTP Status code of the response but only if there was a
# problem.
print ("Error code: %s" % e.code)
If you check this with something like the Wireshark network protocol analazer, you can see that it is actually sending out a HEAD request, rather than a GET.
This is the HTTP request and response from the code above, as captured by Wireshark:
HEAD /doFeT HTTP/1.1
Accept-Encoding: identity
Host: bit.ly
Connection: close
User-Agent: Python-urllib/2.7HTTP/1.1 301 Moved
Server: nginx
Date: Sun, 19 Feb 2012 13:20:56 GMT
Content-Type: text/html; charset=utf-8
Cache-control: private; max-age=90
Location: http://www.kidsidebyside.org/?p=445
MIME-Version: 1.0
Content-Length: 127
Connection: close
Set-Cookie: _bit=4f40f738-00153-02ed0-421cf10a;domain=.bit.ly;expires=Fri Aug 17 13:20:56 2012;path=/; HttpOnly
However, as mentioned in one of the comments in the other question, if the URL in question includes a redirect then urllib2 will do a GET request to the destination, not a HEAD. This could be a major shortcoming, if you really wanted to only make HEAD requests.
The request above involves a redirect. Here is request to the destination, as captured by Wireshark:
GET /2009/05/come-and-draw-the-circle-of-unity-with-us/ HTTP/1.1
Accept-Encoding: identity
Host: www.kidsidebyside.org
Connection: close
User-Agent: Python-urllib/2.7
An alternative to using urllib2 is to use Joe Gregorio's httplib2 library:
import httplib2
url = "http://bit.ly/doFeT"
http_interface = httplib2.Http()
try:
response, content = http_interface.request(url, method="HEAD")
print ("Response status: %d - %s" % (response.status, response.reason))
# This will just display all the dictionary key-value pairs. Replace this
# line with something useful.
response.__dict__
except httplib2.ServerNotFoundError, e:
print (e.message)
This has the advantage of using HEAD requests for both the initial HTTP request and the redirected request to the destination URL.
Here's the first request:
HEAD /doFeT HTTP/1.1
Host: bit.ly
accept-encoding: gzip, deflate
user-agent: Python-httplib2/0.7.2 (gzip)
Here's the second request, to the destination:
HEAD /2009/05/come-and-draw-the-circle-of-unity-with-us/ HTTP/1.1
Host: www.kidsidebyside.org
accept-encoding: gzip, deflate
user-agent: Python-httplib2/0.7.2 (gzip)
You can use something like this:
for i in `cat foo.txt`
do
sudo $i
done
Though if the commands have arguments (i.e. there is whitespace in the lines) you may have to monkey around with that a bit to protect the whitepace so that the whole string is seen by sudo
as a command. But it gives you an idea on how to start.
MySQL is different from most DBMSs use of +
or ||
for concatenation. It uses the CONCAT
function:
SELECT CONCAT(first_name, " ", last_name) AS Name FROM test.student
As @eggyal pointed out in comments, you can enable string concatenation with the ||
operator in MySQL by setting the PIPES_AS_CONCAT
SQL mode.
The registry is the official way to detect if a specific version of the Framework is installed.
Which registry keys are needed change depending on the Framework version you are looking for:
Framework Version Registry Key ------------------------------------------------------------------------------------------ 1.0 HKLM\Software\Microsoft\.NETFramework\Policy\v1.0\3705 1.1 HKLM\Software\Microsoft\NET Framework Setup\NDP\v1.1.4322\Install 2.0 HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\Install 3.0 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.0\Setup\InstallSuccess 3.5 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Install 4.0 Client Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Client\Install 4.0 Full Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full\Install
Generally you are looking for:
"Install"=dword:00000001
except for .NET 1.0, where the value is a string (REG_SZ
) rather than a number (REG_DWORD
).
Determining the service pack level follows a similar pattern:
Framework Version Registry Key ------------------------------------------------------------------------------------------ 1.0 HKLM\Software\Microsoft\Active Setup\Installed Components\{78705f0d-e8db-4b2d-8193-982bdda15ecd}\Version 1.0[1] HKLM\Software\Microsoft\Active Setup\Installed Components\{FDC11A6F-17D1-48f9-9EA3-9051954BAA24}\Version 1.1 HKLM\Software\Microsoft\NET Framework Setup\NDP\v1.1.4322\SP 2.0 HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\SP 3.0 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.0\SP 3.5 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\SP 4.0 Client Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Client\Servicing 4.0 Full Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full\Servicing [1] Windows Media Center or Windows XP Tablet Edition
As you can see, determining the SP level for .NET 1.0 changes if you are running on Windows Media Center or Windows XP Tablet Edition. Again, .NET 1.0 uses a string value while all of the others use a DWORD.
For .NET 1.0 the string value at either of these keys has a format of #,#,####,#. The last # is the Service Pack level.
While I didn't explicitly ask for this, if you want to know the exact version number of the Framework you would use these registry keys:
Framework Version Registry Key ------------------------------------------------------------------------------------------ 1.0 HKLM\Software\Microsoft\Active Setup\Installed Components\{78705f0d-e8db-4b2d-8193-982bdda15ecd}\Version 1.0[1] HKLM\Software\Microsoft\Active Setup\Installed Components\{FDC11A6F-17D1-48f9-9EA3-9051954BAA24}\Version 1.1 HKLM\Software\Microsoft\NET Framework Setup\NDP\v1.1.4322 2.0[2] HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\Version 2.0[3] HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\Increment 3.0 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.0\Version 3.5 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Version 4.0 Client Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Version 4.0 Full Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Version [1] Windows Media Center or Windows XP Tablet Edition [2] .NET 2.0 SP1 [3] .NET 2.0 Original Release (RTM)
Again, .NET 1.0 uses a string value while all of the others use a DWORD.
for .NET 1.0 the string value at either of these keys has a format of #,#,####,#
. The #,#,####
portion of the string is the Framework version.
for .NET 1.1, we use the name of the registry key itself, which represents the version number.
Finally, if you look at dependencies, .NET 3.0 adds additional functionality to .NET 2.0 so both .NET 2.0 and .NET 3.0 must both evaulate as being installed to correctly say that .NET 3.0 is installed. Likewise, .NET 3.5 adds additional functionality to .NET 2.0 and .NET 3.0, so .NET 2.0, .NET 3.0, and .NET 3. should all evaluate to being installed to correctly say that .NET 3.5 is installed.
.NET 4.0 installs a new version of the CLR (CLR version 4.0) which can run side-by-side with CLR 2.0.
There won't be a v4.5
key in the registry if .NET 4.5 is installed. Instead you have to check if the HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full
key contains a value called Release
. If this value is present, .NET 4.5 is installed, otherwise it is not. More details can be found here and here.
Add the file to a formData
object, and set the Content-Type
header to multipart/form-data
.
var formData = new FormData();
var imagefile = document.querySelector('#file');
formData.append("image", imagefile.files[0]);
axios.post('upload_file', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
The fix for me was to put "log4j.properties" into the "src" folder. It did not work in my package folder it has to be one up at the very root of source. Adding it to the build path which then moves it to the "Reference Libraries" also did not work.
To repeat: put log4j.properties at the root of your src folder.
my log4j.properties files has the following content which works on the latest version of Spring Tool Suite which is based on Eclipse.
# Configure logging for testing: optionally with log file
#log4j.rootLogger=INFO, stdout
log4j.rootLogger=WARN, stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%
I'm having same problem. I try to install office 2010 64bit on windows 7 64 bit and then install 2007 Office System Driver : Data Connectivity Components.
after that, visual studio 2008 can opens a connection to an MS-Access 2007 database file.
If you want to generate the class with auto properties, convert the XSD to XML using this then convert the XML to JSON using this and copy to clipboard the result. Then in VS, inside the file where your class will be created, go to Edit>Paste Special>Paste JSON as classes.
There are multiple ways to do this, one way is mentioned below. Just assume you have .js file like this.
let add = function (a, b) {
console.log(a + b);
};
let sub = function (a, b) {
console.log(a - b);
};
You can export these functions using the following code snippet,
module.exports.add = add;
module.exports.sub = sub;
And you can use the exported functions using this code snippet,
var add = require('./counter').add;
var sub = require('./counter').sub;
add(1,2);
sub(1,2);
I know this is a late reply, but hope this helps!
myModal1 is the id of modal
$('#myModal1').modal({ show: true });
I met the same problem as you.
I push two tables
result
into t1
object and group t1
.
from p in Products
join bp in BaseProducts on p.BaseProductId equals bp.Id
select new {
p,
bp
} into t1
group t1 by t1.p.SomeId into g
select new ProductPriceMinMax {
SomeId = g.FirstOrDefault().p.SomeId,
CountryCode = g.FirstOrDefault().p.CountryCode,
MinPrice = g.Min(m => m.bp.Price),
MaxPrice = g.Max(m => m.bp.Price),
BaseProductName = g.FirstOrDefault().bp.Name
};
Close()
- It is used to close the browser or page currently which is having the focus.
Quit()
- It is used to shut down the web driver instance or destroy the web driver instance(Close all the windows).
Dispose()
- I am not aware of this method.
What it correct way of installing SmartGit on Ubuntu? Thus I can have normal icon
In smartgit/bin folder, there's a shell script waiting for you: add-menuitem.sh. It does just that.
Just like normal background-color: #f0f
You just need a way to target it, eg: <option id="myPinkOption">blah</option>
enum Orientations
{
None, North, East, South, West
}
private Orientations? _orientation { get; set; }
public Orientations? Orientation
{
get
{
return _orientation ?? Orientations.None;
}
set
{
_orientation = value;
}
}
If you set the property to null will return Orientations.None on get. The property _orientation is null by default.
Here is a nice widget/plugin library which has ellipsis built in: http://www.codeitbetter.co.uk/widgets/ellipsis/ All you need to do it reference the library and call the following:
<script type="text/javascript">
$(document).ready(function () {
$(".ellipsis_10").Ellipsis({
numberOfCharacters: 10,
showLessText: "less",
showMoreText: "more"
});
});
</script>
<div class="ellipsis_10">
Some text here that's longer than 10 characters.
</div>
If not opposed to or may already be using jQuery, you could do this without the approach of having to use obtrusive js. Hope it helps. https://en.wikipedia.org/wiki/Unobtrusive_JavaScript Also like to reference, https://stackoverflow.com/a/3910750/4812515 for a discussion on this.
HTML:
<input type="button" value="Open Curtain" id=myButton1"></input>
Javascript:
$('#myButton1').click(function() {
var self = this;
change(self);
});
function change( el ) {
if ( el.value === "Open Curtain" )
el.value = "Close Curtain";
else
el.value = "Open Curtain";
}
As others have pointed out, params
values can come from the query string of a GET request, or the form data of a POST request, but there's also a third place they can come from: The path of the URL.
As you might know, Rails uses something called routes to direct requests to their corresponding controller actions. These routes may contain segments that are extracted from the URL and put into params
. For example, if you have a route like this:
match 'products/:id', ...
Then a request to a URL like http://example.com/products/42
will set params[:id]
to 42
.
I think you should do it the other way round.
Define your Div
s and have your a href
within each Div
, pointing to different links
This will replace your existing mySelect with a new mySelect.
$('#mySelect').replaceWith('<Select id="mySelect" size="9">
<option value="whatever" selected="selected" >text</option>
</Select>');
Java has mainly three sub categories :
where core java is the first and basic step of all to start or learn java from beginning.
Install PIL(Python Image Library) :
then:
from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();
Try this:
String result = "34.1 -118.33\n<!--ABCDEFG-->";
result = result.substring(0, result.indexOf("\n"));
You could also put this on one line like so:
/path/to/jre/bin/keytool -genkey -alias [mypassword] -keyalg [RSA]
Wanted to include this as a comment on piet.t answer but I don't have enough rep to comment.
See the "signing" section of this article that describes how to access the keytool.exe without changing your working directory to the path: https://flutter.dev/docs/deployment/android#signing-the-app
Note that they say you can type in space separated folder names like /"Program Files"/ with quotes but I found in bash i had to separate with back slashes like /Program\ Files/.
Appears you are having 'y' default to 1: An arrow function would be useful in 2020:
let x = (y = 1) => //insert operation with y here
Let 'x' be a function where 'y' is a parameter which would be assigned a default to '1' if it is some null or undefined value, then return some operation with y.
you haven't loaded driver into memory.
use this following in init()
Class.forName("com.mysql.jdbc.Driver");
Also, you missed a colon (:) in url, use this
String mySqlUrl = "jdbc:mysql://localhost:3306/mysql";
I know that we are (n-1) * (n times), but why the division by 2?
It's only (n - 1) * n
if you use a naive bubblesort. You can get a significant savings if you notice the following:
After each compare-and-swap, the largest element you've encountered will be in the last spot you were at.
After the first pass, the largest element will be in the last position; after the kth pass, the kth largest element will be in the kth last position.
Thus you don't have to sort the whole thing every time: you only need to sort n - 2 elements the second time through, n - 3 elements the third time, and so on. That means that the total number of compare/swaps you have to do is (n - 1) + (n - 2) + ...
. This is an arithmetic series, and the equation for the total number of times is (n - 1)*n / 2.
Example: if the size of the list is N = 5, then you do 4 + 3 + 2 + 1 = 10 swaps -- and notice that 10 is the same as 4 * 5 / 2.
Here is my jQuery plugin:
(function($) {
'use strict';
$.fn.tooltipOnOverflow = function() {
$(this).on("mouseenter", function() {
if (this.offsetWidth < this.scrollWidth) {
$(this).attr('title', $(this).text());
} else {
$(this).removeAttr("title");
}
});
};
})(jQuery);
Usage:
$("td, th").tooltipOnOverflow();
Edit:
I have made a gist for this plugin. https://gist.github.com/UziTech/d45102cdffb1039d4415
Use Material Cardview instead, it extends Cardview and provides multiple new features including default clickable effect :
<com.google.android.material.card.MaterialCardView>
...
</com.google.android.material.card.MaterialCardView>
Dependency (It can be used up to API 14 to support older device):
implementation 'com.google.android.material:material:1.0.0'
You can pass params directly to $http.get()
The following works fine
$http.get(user.details_path, {
params: { user_id: user.id }
});
This works for me for aligning the image to center of div.
.yourclass {
background-image: url(image.png);
background-position: center;
background-size: cover;
background-repeat: no-repeat;
}
On Excel 2010 try this:
Yes, you may put comments in there. They however must start at the beginning of a line.
cf. http://git-scm.com/book/en/Git-Basics-Recording-Changes-to-the-Repository#Ignoring-Files
The rules for the patterns you can put in the .gitignore file are as follows:
- Blank lines or lines starting with # are ignored.
[…]
The comment character is #
, example:
# no .a files
*.a
you can use this http://www.md5decrypt.org/ or this http://md5.gromweb.com/ it will decrypt your md5 code
I'm not sure I quite understand the question but if you want to search objects on the database for a particular search string try:
SELECT owner, name, type, line, text
FROM dba_source
WHERE instr(UPPER(text), UPPER(:srch_str)) > 0;
From there if you need any more info you can just look up the object / line number.
This is just an example. You may like to customize it as per your requirement.
$.ajax({
url: 'ajax/test1.html',
success: function(data1) {
alert('Request 1 was performed.');
$.ajax({
type: 'POST',
url: url,
data: data1, //pass data1 to second request
success: successHandler, // handler if second request succeeds
dataType: dataType
});
}
});
For more details : see this
Three steps to implement your function:
Step#1 You can specify a string, including the chars A-Z and 0-9.
Like.
String candidateChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
Step#2 Then if you would like to generate a random char from this candidate string. You can use
candidateChars.charAt(random.nextInt(candidateChars.length()));
Step#3 At last, specify the length of random string to be generated (in your description, it is 17). Writer a for-loop and append the random chars generated in step#2 to StringBuilder object.
Based on this, here is an example public class RandomTest {
public static void main(String[] args) {
System.out.println(generateRandomChars(
"ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", 17));
}
/**
*
* @param candidateChars
* the candidate chars
* @param length
* the number of random chars to be generated
*
* @return
*/
public static String generateRandomChars(String candidateChars, int length) {
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(candidateChars.charAt(random.nextInt(candidateChars
.length())));
}
return sb.toString();
}
}
Sort of:
class some_class {
static std::vector<std::string> v; // declaration
};
const char *vinit[] = {"one", "two", "three"};
std::vector<std::string> some_class::v(vinit, end(vinit)); // definition
end
is just so I don't have to write vinit+3
and keep it up to date if the length changes later. Define it as:
template<typename T, size_t N>
T * end(T (&ra)[N]) {
return ra + N;
}
Declare in inner class. This solution is pretty solid and recommended.
class Test(object):
class Decorators(object):
@staticmethod
def decorator(foo):
def magic(self, *args, **kwargs) :
print("start magic")
foo(self, *args, **kwargs)
print("end magic")
return magic
@Decorators.decorator
def bar( self ) :
print("normal call")
test = Test()
test.bar()
The result:
>>> test = Test()
>>> test.bar()
start magic
normal call
end magic
>>>
An easy way to execute .jar files is to create a batch file.
Let's say you placed your jar file on your Desktop;
@echo OFF
java -jar C:\Users\YourName\Desktop\myjar.jar
Copy this code to a .txt file, modify "YourName" and save as "myjar.bat". Then whenever you double click, the jar file will be executed. Hope this helps.
*args
just means that the function takes a number of arguments, generally of the same type.
Check out this section in the Python tutorial for more info.
The main difference between struts & spring MVC is about the difference between Aspect Oriented Programming (AOP) & Object oriented programming (OOP).
Spring makes application loosely coupled by using Dependency Injection.The core of the Spring Framework is the IoC container.
OOP can do everything that AOP does but different approach. In other word, AOP complements OOP by providing another way of thinking about program structure.
Practically, when you want to apply same changes for many files. It should be exhausted work with Struts to add same code for tons of files. Instead Spring write new changes somewhere else and inject to the files.
Some related terminologies of AOP is cross-cutting concerns, Aspect, Dependency Injection...
We had this in many other cases, what we decided internally is to always have a wrapper for the controller/directive so that we don't need to think about it. Here is you example with our wrapper.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.min.js"></script>
<script>
function main($scope) {
$scope.thisScope = $scope;
$scope.testa = false;
$scope.testb = false;
$scope.testc = false;
$scope.testd = false;
}
</script>
<div ng-app >
<div ng-controller="main">
Test A: {{testa}}<br />
Test B: {{testb}}<br />
Test C: {{testc}}<br />
Test D: {{testd}}<br />
<div>
testa (without ng-if): <input type="checkbox" ng-model="thisScope.testa" />
</div>
<div ng-if="!testa">
testb (with ng-if): <input type="checkbox" ng-model="thisScope.testb" />
</div>
<div ng-show="!testa">
testc (with ng-show): <input type="checkbox" ng-model="thisScope.testc" />
</div>
<div ng-hide="testa">
testd (with ng-hide): <input type="checkbox" ng-model="thisScope.testd" />
</div>
</div>
</div>
Hopes this helps, Yishay
if (list.Count > desiredIndex && list[desiredIndex] != null)
{
// logic
}
How can I track down the large files in the git history?
Start by analyzing, validating and selecting the root cause. Use git-repo-analysis
to help.
You may also find some value in the detailed reports generated by BFG Repo-Cleaner, which can be run very quickly by cloning to a Digital Ocean droplet using their 10MiB/s network throughput.
It's a unicode character. In this case \u003C
and \u003E
mean :
U+003C < Less-than sign
U+003E > Greater-than sign
See a list here
Follow these steps then you can create custom styles for your file upload form:
1.) This is the simple HTML form(please read the HTML comments I have written here bellow)
<form action="#type your action here" method="POST" enctype="multipart/form-data">
<div id="yourBtn" style="height: 50px; width: 100px;border: 1px dashed #BBB; cursor:pointer;" onclick="getFile()">Click to upload!</div>
<!-- this is your file input tag, so i hide it!-->
<div style='height: 0px;width: 0px; overflow:hidden;'><input id="upfile" type="file" value="upload"/></div>
<!-- here you can have file submit button or you can write a simple script to upload the file automatically-->
<input type="submit" value='submit' >
</form>
2.) Then use this simple script to pass the click event to file input tag.
function getFile(){
document.getElementById("upfile").click();
}
Now you can use any type of a styling without worrying how to change default styles. I know this very well, because I have been trying to change the default styles for month and a half. believe me it's very hard because different browsers have different upload input tag. So use this one to build your custom file upload forms.Here is the full AUTOMATED UPLOAD code.
<html>
<style>
#yourBtn{
position: relative;
top: 150px;
font-family: calibri;
width: 150px;
padding: 10px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border: 1px dashed #BBB;
text-align: center;
background-color: #DDD;
cursor:pointer;
}
</style>
<script type="text/javascript">
function getFile(){
document.getElementById("upfile").click();
}
function sub(obj){
var file = obj.value;
var fileName = file.split("\\");
document.getElementById("yourBtn").innerHTML = fileName[fileName.length-1];
document.myForm.submit();
event.preventDefault();
}
</script>
<body>
<center>
<form action="#type your action here" method="POST" enctype="multipart/form-data" name="myForm">
<div id="yourBtn" onclick="getFile()">click to upload a file</div>
<!-- this is your file input tag, so i hide it!-->
<!-- i used the onchange event to fire the form submission-->
<div style='height: 0px; width: 0px;overflow:hidden;'><input id="upfile" type="file" value="upload" onchange="sub(this)"/></div>
<!-- here you can have file submit button or you can write a simple script to upload the file automatically-->
<!-- <input type="submit" value='submit' > -->
</form>
</center>
</body>
</html>
All kernels will use some assembly code as well.
Use this function in your script and put a span near textbox to show the error message
$(document).ready(function () {
$(".digit").keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$("#errormsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
@Html.TextBoxFor(x => x.company.ContactNumber, new { @class = "digit" })
<span id="errormsg"></span>
Another approach is keep that element, change the text, then append that element back
const star_icon = $(li).find('.stars svg')
$(li).find('.stars').text(repo.stargazers_count).append(star_icon)
Emacs takes many launch options. The one that you are looking for is
emacs -nw
. This will open Emacs inside the terminal disregarding the DISPLAY environment variable even if it is set.
The long form of this flag is emacs --no-window-system
.
More information about Emacs launch options can be found in the manual.
Unfortunatelly, today (September 2018) you can not find cross-browser solution for client side file writing.
For example: in some browser like a Chrome we have today this possibility and we can write with FileSystemFileEntry.createWriter() with client side call, but according to the docu:
This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.
For IE (but not MS Edge) we could use ActiveX too, but this is only for this client.
If you want update your JSON file cross-browser you have to use server and client side together.
On client side you can make a request to the server and then you have to read the response from server. Or you could read a file with FileReader too. For the cross-browser writing to the file you have to have some server (see below on server part).
var xhr = new XMLHttpRequest(),
jsonArr,
method = "GET",
jsonRequestURL = "SOME_PATH/jsonFile/";
xhr.open(method, jsonRequestURL, true);
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
// we convert your JSON into JavaScript object
jsonArr = JSON.parse(xhr.responseText);
// we add new value:
jsonArr.push({"nissan": "sentra", "color": "green"});
// we send with new request the updated JSON file to the server:
xhr.open("POST", jsonRequestURL, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// if you want to handle the POST response write (in this case you do not need it):
// xhr.onreadystatechange = function(){ /* handle POST response */ };
xhr.send("jsonTxt="+JSON.stringify(jsonArr));
// but on this place you have to have a server for write updated JSON to the file
}
};
xhr.send(null);
You can use a lot of different servers, but I would like to write about PHP and Node.js servers.
By using searching machine you could find "free PHP Web Hosting*" or "free Node.js Web Hosting". For PHP server I would recommend 000webhost.com and for Node.js I would recommend to see and to read this list.
PHP server side script solution
The PHP script for reading and writing from JSON file:
<?php
// This PHP script must be in "SOME_PATH/jsonFile/index.php"
$file = 'jsonFile.txt';
if($_SERVER['REQUEST_METHOD'] === 'POST')
// or if(!empty($_POST))
{
file_put_contents($file, $_POST["jsonTxt"]);
//may be some error handeling if you want
}
else if($_SERVER['REQUEST_METHOD'] === 'GET')
// or else if(!empty($_GET))
{
echo file_get_contents($file);
//may be some error handeling if you want
}
?>
Node.js server side script solution
I think that Node.js is a little bit complex for beginner. This is not normal JavaScript like in browser. Before you start with Node.js I would recommend to read one from two books:
The Node.js script for reading and writing from JSON file:
var http = require("http"),
fs = require("fs"),
port = 8080,
pathToJSONFile = '/SOME_PATH/jsonFile.txt';
http.createServer(function(request, response)
{
if(request.method == 'GET')
{
response.writeHead(200, {"Content-Type": "application/json"});
response.write(fs.readFile(pathToJSONFile, 'utf8'));
response.end();
}
else if(request.method == 'POST')
{
var body = [];
request.on('data', function(chunk)
{
body.push(chunk);
});
request.on('end', function()
{
body = Buffer.concat(body).toString();
var myJSONdata = body.split("=")[1];
fs.writeFileSync(pathToJSONFile, myJSONdata); //default: 'utf8'
});
}
}).listen(port);
Related links for Node.js:
I had to use Debug.print
instead of Print
, which works in the Immediate window.
Sub SendEmail()
'Dim objHTTP As New MSXML2.XMLHTTP
'Set objHTTP = New MSXML2.XMLHTTP60
'Dim objHTTP As New MSXML2.XMLHTTP60
Dim objHTTP As New WinHttp.WinHttpRequest
'Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
'Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
URL = "http://localhost:8888/rest/mail/send"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "Content-Type", "application/json"
objHTTP.send ("{""key"":null,""from"":""[email protected]"",""to"":null,""cc"":null,""bcc"":null,""date"":null,""subject"":""My Subject"",""body"":null,""attachments"":null}")
Debug.Print objHTTP.Status
Debug.Print objHTTP.ResponseText
End Sub
Using foreach
loop without key
foreach($array as $item) {
echo $item['filename'];
echo $item['filepath'];
// to know what's in $item
echo '<pre>'; var_dump($item);
}
Using foreach
loop with key
foreach($array as $i => $item) {
echo $item[$i]['filename'];
echo $item[$i]['filepath'];
// $array[$i] is same as $item
}
Using for
loop
for ($i = 0; $i < count($array); $i++) {
echo $array[$i]['filename'];
echo $array[$i]['filepath'];
}
var_dump
is a really useful function to get a snapshot of an array or object.
After half a day of fiddling with this, found out that PDO had a bug where...
--
//This would run as expected:
$pdo->exec("valid-stmt1; valid-stmt2;");
--
//This would error out, as expected:
$pdo->exec("non-sense; valid-stmt1;");
--
//Here is the bug:
$pdo->exec("valid-stmt1; non-sense; valid-stmt3;");
It would execute the "valid-stmt1;"
, stop on "non-sense;"
and never throw an error. Will not run the "valid-stmt3;"
, return true and lie that everything ran good.
I would expect it to error out on the "non-sense;"
but it doesn't.
Here is where I found this info: Invalid PDO query does not return an error
Here is the bug: https://bugs.php.net/bug.php?id=61613
So, I tried doing this with mysqli and haven't really found any solid answer on how it works so I thought I's just leave it here for those who want to use it..
try{
// db connection
$mysqli = new mysqli("host", "user" , "password", "database");
if($mysqli->connect_errno){
throw new Exception("Connection Failed: [".$mysqli->connect_errno. "] : ".$mysqli->connect_error );
exit();
}
// read file.
// This file has multiple sql statements.
$file_sql = file_get_contents("filename.sql");
if($file_sql == "null" || empty($file_sql) || strlen($file_sql) <= 0){
throw new Exception("File is empty. I wont run it..");
}
//run the sql file contents through the mysqli's multi_query function.
// here is where it gets complicated...
// if the first query has errors, here is where you get it.
$sqlFileResult = $mysqli->multi_query($file_sql);
// this returns false only if there are errros on first sql statement, it doesn't care about the rest of the sql statements.
$sqlCount = 1;
if( $sqlFileResult == false ){
throw new Exception("File: '".$fullpath."' , Query#[".$sqlCount."], [".$mysqli->errno."]: '".$mysqli->error."' }");
}
// so handle the errors on the subsequent statements like this.
// while I have more results. This will start from the second sql statement. The first statement errors are thrown above on the $mysqli->multi_query("SQL"); line
while($mysqli->more_results()){
$sqlCount++;
// load the next result set into mysqli's active buffer. if this fails the $mysqli->error, $mysqli->errno will have appropriate error info.
if($mysqli->next_result() == false){
throw new Exception("File: '".$fullpath."' , Query#[".$sqlCount."], Error No: [".$mysqli->errno."]: '".$mysqli->error."' }");
}
}
}
catch(Exception $e){
echo $e->getMessage(). " <pre>".$e->getTraceAsString()."</pre>";
}
The problem with opacity
is that it will also affect the content, when often you do not want this to happen.
If you just want your element to be transparent, it's really as easy as :
background-color: transparent;
But if you want it to be in colors, you can use:
background-color: rgba(255, 0, 0, 0.4);
Or define a background image (1px
by 1px
) saved with the right alpha
.
(To do so, use Gimp
, Paint.Net
or any other image software that allows you to do that.
Just create a new image, delete the background and put a semi-transparent color in it, then save it in png.)
As said by René, the best thing to do would be to mix both, with the rgba
first and the 1px
by 1px
image as a fallback if the browser doesn't support alpha :
background: url('img/red_transparent_background.png');
background: rgba(255, 0, 0, 0.4);
See also : http://www.w3schools.com/cssref/css_colors_legal.asp.
Demo : My JSFiddle
I have the same problem and I solved it and the explanation is as follow:
If the Seaborn package is not installed in anaconda, you will not be able to update it, namely, if in the Terminal we type: conda update seaborn
it will fail showing: "PackageNotFoundError: Package not found: 'seaborn' Package 'seaborn' is not installed in /Users/yifan/anaconda"
Thus we need to install seaborn in anaconda first by typing in Terminal: conda install -c https://conda.anaconda.org/anaconda seaborn
Then the seaborn will be fetched and installed in the environment of anaconda, namely in my case, /Users/yifan/anaconda
Once this installation is done, we will be able to import seaborn in python.
Side note, to check and list all discoverable environments where python is installed in anaconda, type in Terminal: conda info --envs
I got this after i copied the svc file and renamed it. Although the file name and the svc.cs file were correctly renamed, the markup still referenced the original file.
To fix this, right click on the copied svc file and choose View Markup and change the service reference.
To replace a fragment inside a ViewPager
you can move source codes of ViewPager
, PagerAdapter
and FragmentStatePagerAdapter
classes into your project and add following code.
into ViewPager
:
public void notifyItemChanged(Object oldItem, Object newItem) {
if (mItems != null) {
for (ItemInfo itemInfo : mItems) {
if (itemInfo.object.equals(oldItem)) {
itemInfo.object = newItem;
}
}
}
invalidate();
}
into FragmentStatePagerAdapter:
public void replaceFragmetns(ViewPager container, Fragment oldFragment, Fragment newFragment) {
startUpdate(container);
// remove old fragment
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
int position = getFragmentPosition(oldFragment);
while (mSavedState.size() <= position) {
mSavedState.add(null);
}
mSavedState.set(position, null);
mFragments.set(position, null);
mCurTransaction.remove(oldFragment);
// add new fragment
while (mFragments.size() <= position) {
mFragments.add(null);
}
mFragments.set(position, newFragment);
mCurTransaction.add(container.getId(), newFragment);
finishUpdate(container);
// ensure getItem returns newFragemtn after calling handleGetItemInbalidated()
handleGetItemInbalidated(container, oldFragment, newFragment);
container.notifyItemChanged(oldFragment, newFragment);
}
protected abstract void handleGetItemInbalidated(View container, Fragment oldFragment, Fragment newFragment);
protected abstract int getFragmentPosition(Fragment fragment);
handleGetItemInvalidated()
ensures that after next call of getItem()
it return newFragment
getFragmentPosition()
returns position of the fragment in your adapter.
Now, to replace fragments call
mAdapter.replaceFragmetns(mViewPager, oldFragment, newFragment);
If you interested in an example project ask me for the sources.
You can modify various VM properties by adding the following configuration (see the Vagrant docs for a bit more info):
# Configure VM Ram usage
config.vm.customize [
"modifyvm", :id,
"--name", "Test_Environment",
"--memory", "1024"
]
You can obtain the properties that you want to change from the documents for VirtualBox command-line options:
The vagrant documentation has the section on how to change IP address:
Vagrant::Config.run do |config|
config.vm.network :hostonly, "192.168.50.4"
end
Also you can restructure the configuration like this, ending is do with end without nesting it. This is simpler.
config.vm.define :web do |web_config|
web_config.vm.box = "lucid32"
web_config.vm.forward_port 80, 8080
end
web_config.vm.provision :puppet do |puppet|
puppet.manifests_path = "manifests"
puppet.manifest_file = "lucid32.pp"
end
a simple timestamp formatter in pure JS with custom patterns support and locale-aware, using Intl.RelativeTimeFormat
some formatting examples
/** delta: 1234567890, @locale: 'en-US', @style: 'long' */
/* D~ h~ m~ s~ */
14 days 6 hours 56 minutes 7 seconds
/* D~ h~ m~ s~ f~ */
14 days 6 hours 56 minutes 7 seconds 890
/* D#"d" h#"h" m#"m" s#"s" f#"ms" */
14d 6h 56m 7s 890ms
/* D,h:m:s.f */
14,06:56:07.890
/* D~, h:m:s.f */
14 days, 06:56:07.890
/* h~ m~ s~ */
342 hours 56 minutes 7 seconds
/* s~ m~ h~ D~ */
7 seconds 56 minutes 6 hours 14 days
/* up D~, h:m */
up 14 days, 06:56
the code & test
/**
Init locale formatter:
timespan.locale(@locale, @style)
Example:
timespan.locale('en-US', 'long');
timespan.locale('es', 'narrow');
Format time delta:
timespan.format(@pattern, @milliseconds)
@pattern tokens:
D: days, h: hours, m: minutes, s: seconds, f: millis
@pattern token extension:
h => '0'-padded value,
h# => raw value,
h~ => locale formatted value
Example:
timespan.format('D~ h~ m~ s~ f "millis"', 1234567890);
output: 14 days 6 hours 56 minutes 7 seconds 890 millis
NOTES:
* milliseconds unit have no locale translation
* may encounter declension issues for some locales
* use quoted text for raw inserts
*/
const timespan = (() => {
let rtf, tokensRtf;
const
tokens = /[Dhmsf][#~]?|"[^"]*"|'[^']*'/g,
map = [
{t: [['D', 1], ['D#'], ['D~', 'day']], u: 86400000},
{t: [['h', 2], ['h#'], ['h~', 'hour']], u: 3600000},
{t: [['m', 2], ['m#'], ['m~', 'minute']], u: 60000},
{t: [['s', 2], ['s#'], ['s~', 'second']], u: 1000},
{t: [['f', 3], ['f#'], ['f~']], u: 1}
],
locale = (value, style = 'long') => {
try {
rtf = new Intl.RelativeTimeFormat(value, {style});
} catch (e) {
if (rtf) throw e;
return;
}
const h = rtf.format(1, 'hour').split(' ');
tokensRtf = new Set(rtf.format(1, 'day').split(' ')
.filter(t => t != 1 && h.indexOf(t) > -1));
return true;
},
fallback = (t, u) => u + ' ' + t.fmt + (u == 1 ? '' : 's'),
mapper = {
number: (t, u) => (u + '').padStart(t.fmt, '0'),
string: (t, u) => rtf ? rtf.format(u, t.fmt).split(' ')
.filter(t => !tokensRtf.has(t)).join(' ')
.trim().replace(/[+-]/g, '') : fallback(t, u),
},
replace = (out, t) => out[t] || t.slice(1, t.length - 1),
format = (pattern, value) => {
if (typeof pattern !== 'string')
throw Error('invalid pattern');
if (!Number.isFinite(value))
throw Error('invalid value');
if (!pattern)
return '';
const out = {};
value = Math.abs(value);
pattern.match(tokens)?.forEach(t => out[t] = null);
map.forEach(m => {
let u = null;
m.t.forEach(t => {
if (out[t.token] !== null)
return;
if (u === null) {
u = Math.floor(value / m.u);
value %= m.u;
}
out[t.token] = '' + (t.fn ? t.fn(t, u) : u);
})
});
return pattern.replace(tokens, replace.bind(null, out));
};
map.forEach(m => m.t = m.t.map(t => ({
token: t[0], fmt: t[1], fn: mapper[typeof t[1]]
})));
locale('en');
return {format, locale};
})();
/************************** test below *************************/
const
cfg = {
locale: 'en,de,nl,fr,it,es,pt,ro,ru,ja,kor,zh,th,hi',
style: 'long,narrow'
},
el = id => document.getElementById(id),
locale = el('locale'), loc = el('loc'), style = el('style'),
fd = new Date(), td = el('td'), fmt = el('fmt'),
run = el('run'), out = el('out'),
test = () => {
try {
const tv = new Date(td.value);
if (isNaN(tv)) throw Error('invalid "datetime2" value');
timespan.locale(loc.value || locale.value, style.value);
const delta = fd.getTime() - tv.getTime();
out.innerHTML = timespan.format(fmt.value, delta);
} catch (e) { out.innerHTML = e.message; }
};
el('fd').innerText = el('td').value = fd.toISOString();
el('fmt').value = 'D~ h~ m~ s~ f~ "ms"';
for (const [id, value] of Object.entries(cfg)) {
const elm = el(id);
value.split(',').forEach(i => elm.innerHTML += `<option>${i}</option>`);
}
_x000D_
i {color:green}
_x000D_
locale: <select id="locale"></select>
custom: <input id="loc" style="width:8em"><br>
style: <select id="style"></select><br>
datetime1: <i id="fd"></i><br>
datetime2: <input id="td"><br>
pattern: <input id="fmt">
<button id="run" onclick="test()">test</button><br><br>
<i id="out"></i>
_x000D_
According to the official doc (https://nodejs.org/api/esm.html#esm_code_import_code_statements):
import statements are permitted only in ES modules. For similar functionality in CommonJS, see import().
To make Node treat your file as a ES module you need to (https://nodejs.org/api/esm.html#esm_enabling):
This error (or warning in later versions) occurs because you are compiling against a Java Execution Environment. This shows up as JRE System library [CDC-1.0/Foundation-1.0]
in the Build path of your Eclipse Java project. Such environments only expose the Java standard API instead of all the classes within the runtime. This means that the classes used to implement the Java standard API are not exposed.
You can allow access to these particular classes using access rules, you could configure Eclipse to use the JDK directly or you could disable the error. You would however be hiding a serious error as Sun internal classes shouldn't be used (see below for a short explanation).
Java contains a Base64
class in the standard API since Java 1.8. See below for an example how to use it:
Java 8 import statement:
import java.util.Base64;
Java 8 example code:
// create a byte array containing data (test)
byte[] binaryData = new byte[] { 0x64, 0x61, 0x74, 0x61 };
// create and configure encoder (using method chaining)
Base64.Encoder base64Encoder = Base64.getEncoder().withoutPadding();
// encode to string (instead of a byte array containing ASCII)
String base64EncodedData = base64Encoder.encodeToString(binaryData);
// decode using a single statement (no reuse of decoder)
// NOTE the decoder won't fail because the padding is missing
byte[] base64DecodedData = Base64.getDecoder().decode(base64EncodedData);
If Java 8 is not available a library such as Apache Commons Codec or Guava should be used.
Sun internal classes shouldn't be used. Those classes are used to implement Java. They have got public methods to allow instantiation from other packages. A good build environment however should protect you from using them.
Using internal classes may break compatibility with future Java SE runtimes; the implementation and location of these classes can change at any time. It should be strongly discouraged to disable the error or warning (but the disabling of the error is suggested in previous answers, including the two top voted ones).
Thanks for the help everyone, rejecting the promise in .catch()
solved my issue:
export function fetchVehicle(id) {
return dispatch => {
return dispatch({
type: 'FETCH_VEHICLE',
payload: fetch(`http://swapi.co/api/vehicles/${id}/`)
.then(status)
.then(res => res.json())
.catch(error => {
return Promise.reject()
})
});
};
}
function status(res) {
if (!res.ok) {
throw new Error(res.statusText);
}
return res;
}
you can add bellow code in appdelegate.m .if your app is navigation based
// for background color
[nav.navigationBar setBarTintColor:[UIColor blueColor]];
// for change navigation title and button color
[[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],
NSForegroundColorAttributeName,
[UIFont fontWithName:@"FontNAme" size:20],
NSFontAttributeName, nil]];
[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
you can also hide the gridline on yAxis as:
yAxis:{
gridLineWidth: 0,
minorGridLineWidth: 0
}
You can use <LinearLayout>
to group elements horizontaly. Also you should use style to set margins, background and other properties. This will allow you not to repeat code for every label you use.
Here is an example:
<LinearLayout
style="@style/FormItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
style="@style/FormLabel"
android:layout_width="wrap_content"
android:layout_height="@dimen/default_element_height"
android:text="@string/name_label"
/>
<EditText
style="@style/FormText.Editable"
android:id="@+id/cardholderName"
android:layout_width="wrap_content"
android:layout_height="@dimen/default_element_height"
android:layout_weight="1"
android:gravity="right|center_vertical"
android:hint="@string/card_name_hint"
android:imeOptions="actionNext"
android:singleLine="true"
/>
</LinearLayout>
Also you can create a custom view base on the layout above. Have you looked at Creating custom view ?
Are the classes imported? Try pressing CTRL
+ SHIFT
+ O
to resolve the imports. If this does not work you need to include the application servers runtime libraries.
In lieu of changing the port, I reclaimed port 80 as being used by IIS.
So I went to services, and stopped the following:
set them to manual so that it will not start on dev environment restart.
Based on official android docs, you can use this method in a Helper or Util class to get current battery percentage:
Java version:
public static int getBatteryPercentage(Context context) {
if (Build.VERSION.SDK_INT >= 21) {
BatteryManager bm = (BatteryManager) context.getSystemService(BATTERY_SERVICE);
return bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
} else {
IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, iFilter);
int level = batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) : -1;
int scale = batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1) : -1;
double batteryPct = level / (double) scale;
return (int) (batteryPct * 100);
}
}
Kotlin version:
fun getBatteryPercentage(context: Context): Int {
return if (Build.VERSION.SDK_INT >= 21) {
val bm = context.getSystemService(BATTERY_SERVICE) as BatteryManager
bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
} else {
val iFilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
val batteryStatus: Intent = context.registerReceiver(null, iFilter)
val level = batteryStatus?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
val scale = batteryStatus?.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
val batteryPct = level / scale.toDouble()
(batteryPct * 100).toInt()
}
}
I'm using Rails 4.2, and could not get the footable icons to show up. Little boxes were showing, instead of the (+) on collapsed rows and the little sorting arrows I expected. After studying the information here, I made one simple change to my code: remove the font directory in css. That is, change all the css entries like this:
src:url('fonts/footable.eot');
to look like this:
src:url('footable.eot');
It worked. I think Rails 4.2 already assumes the font directory, so specifying it again in the css code makes the font files not get found. Hope this helps.
in flask, with babel, I like to do this :
@app.template_filter('dt')
def _jinja2_filter_datetime(date, fmt=None):
if fmt:
return date.strftime(fmt)
else:
return date.strftime(gettext('%%m/%%d/%%Y'))
used in the template with {{mydatetimeobject|dt}}
so no with babel you can specify your various format in messages.po like this for instance :
#: app/views.py:36
#, python-format
msgid "%%m/%%d/%%Y"
msgstr "%%d/%%m/%%Y"
put export { Home };
at the end of the Home.js file
Static members need to be initialized in a .cpp translation unit at file scope or in the appropriate namespace:
const string foo::s( "my foo");
I have a single checkbox named chkDueDate
and an HTML object with a click event as follows:
$('#chkDueDate').attr('checked', !$('#chkDueDate').is(':checked'));
Clicking the HTML object (in this case a <span>
) toggles the checked property of the checkbox.
I would go like this (regex explained in comments):
import re
# If you need to use the regex more than once it is suggested to compile it.
pattern = re.compile(r"</{0,}\[\d+>")
# <\/{0,}\[\d+>
#
# Match the character “<” literally «<»
# Match the character “/” literally «\/{0,}»
# Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «{0,}»
# Match the character “[” literally «\[»
# Match a single digit 0..9 «\d+»
# Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
# Match the character “>” literally «>»
subject = """this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>.
and there are many other lines in the txt files
with<[3> such tags </[3>"""
result = pattern.sub("", subject)
print(result)
If you want to learn more about regex I recomend to read Regular Expressions Cookbook by Jan Goyvaerts and Steven Levithan.
Declare an instance of MyClass, and then call the member function on that instance:
MyClass m;
m.printInformation();
You can use ISNULL
:
ISNULL(field, VALUEINCASEOFNULL)
you can use preload="none" in the attribute of video tag so the video will be displayed only when user clicks on play button.
<video preload="none">
_x000D_
You can do either:
$("h1").css("background-color", "yellow");
Or:
$("h1").css({backgroundColor: "yellow"});
All the other answers in here are also valid, but if none of them solve the issue it is also worth checking that the actual headers are being passed to the server.
For example, in a load balanced environment behind nginx, the default configuration is to strip out the __RequestVerificationToken header before passing the request on to the server, see: simple nginx reverse proxy seems to strip some headers
Define your own utility for format your date required date format for eg.
NSString * stringFromDate(NSDate *date)
{ NSDateFormatter *formatter
[[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MM / dd / yyyy, hh?mm a"];
return [formatter stringFromDate:date];
}
Works in 2020
$response = Http::withHeaders([
'Content-Type' => 'application/json',
'Authorization'=> 'key='. $token,
])->post($url, [
'notification' => [
'body' => $request->summary,
'title' => $request->title,
'image' => 'http://'.request()->getHttpHost().$path,
],
'priority'=> 'high',
'data' => [
'click_action'=> 'FLUTTER_NOTIFICATION_CLICK',
'status'=> 'done',
],
'to' => '/topics/all'
]);
Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.
You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.
But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.
You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.
I tried to use onGlobalLayout()
to do some custom formatting of a TextView
, but as @George Bailey noticed, onGlobalLayout()
is indeed called twice: once on the initial layout path, and second time after modifying the text.
View.onSizeChanged()
works better for me because if I modify the text there, the method is called only once (during the layout pass). This required sub-classing of TextView
, but on API Level 11+ View. addOnLayoutChangeListener()
can be used to avoid sub-classing.
One more thing, in order to get correct width of the view in View.onSizeChanged()
, the layout_width
should be set to match_parent
, not wrap_content
.
Things are a lot better in modern Python.
Here's a simple child program, "hello.py":
#!/usr/bin/env python3
while True:
i = input()
if i == "quit":
break
print(f"hello {i}")
And a program to interact with it:
import asyncio
async def main():
proc = await asyncio.subprocess.create_subprocess_exec(
"./hello.py", stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE
)
proc.stdin.write(b"bob\n")
print(await proc.stdout.read(1024))
proc.stdin.write(b"alice\n")
print(await proc.stdout.read(1024))
proc.stdin.write(b"quit\n")
await proc.wait()
asyncio.run(main())
That prints out:
b'hello bob\n'
b'hello alice\n'
Note that the actual pattern, which is also by almost all of the previous answers, both here and in related questions, is to set the child's stdout file descriptor to non-blocking and then poll it in some sort of select loop. These days, of course, that loop is provided by asyncio.
//This is The easiest I can Imagine .
// You need to just change the order of Columns and rows , Yours is printing columns X rows and the solution is printing them rows X columns
for(int rows=0;rows<array.length;rows++){
for(int columns=0;columns <array[rows].length;columns++){
System.out.print(array[rows][columns] + "\t" );}
System.out.println();}
In short, a Service is a broader implementation for the developer to set up background operations, while an IntentService is useful for "fire and forget" operations, taking care of background Thread creation and cleanup.
From the docs:
Service A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.
IntentService
Service is a base class for IntentService Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent)
calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
Refer this doc - http://developer.android.com/reference/android/app/IntentService.html
This is very old, seems still many people having issues with the same thing. So I would like to share my experience that it might help someone.
I had the same issue in two places. In one project users 6.0.4.0 and in different project use 4.5.0.0.
1- This work for me. In bin folder I have 6.0.0.0 Newtonsoft.Json.dll and symbolic link to 4.5.0.0 dlls
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<probing privatePath="bin\4.5dlls-path;" />
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed"
culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
If you don't know how to create symbolic link here.
mklink /D "name of the folder" "Path to the dll"
2- In this case when I remove the secion from Web config file it worked. Remember I have reference to 6.0.0.0 and 4.5.0.0 in different projects. In symbolic link I had 12.0.1.0 dll and bin 6.0.0.0.
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<probing privatePath="bin\12.0.1dlls-path;" />
</dependentAssembly>
</assemblyBinding>
</runtime>
3- I have one more solution. If you have different versions of Newtonsoft.Json.dll in different projects try to upgrade all into one version or to the latest version, But in some case it might not work. Ex: System.Net.Http.Formatting.dll might need the version of Nettonsoft.Json.dll 6.0.0.0. In this case you need the vision 6.0.0.0, so try to make all into same version. Hope this might help some one.
What I was looking for was this:
git diff <ref1>..<ref2> <dirname>
An other solution is to use the response.status function. This will give you the http status wich is returned by the ajax call.
function checkHttpStatus(url) {
$.ajax({
type: "GET",
data: {},
url: url,
error: function(response) {
alert(url + " returns a " + response.status);
}, success() {
alert(url + " Good link");
}
});
}
<span class="label">My Label:</span>
<span class="text">My text</span>