I know this is an old question, but I shall post my answer for posterity...
It depends on the system that you are building and the particular business rules in place.
I am building a moderate to large scale CRM in MongoDb, C# (Backend API), and Angular (Frontend web app) and found ObjectId utterly terrible for use in Angular Routing for selecting particular entities. Same with API Controller routing.
The suggestion above worked perfectly for my project.
db.contacts.insert({
"id":db.contacts.find().Count()+1,
"name":"John Doe",
"emails":[
"[email protected]",
"[email protected]"
],
"phone":"555111322",
"status":"Active"
});
The reason it is perfect for my case, but not all cases is that as the above comment states, if you delete 3 records from the collection, you will get collisions.
My business rules state that due to our in house SLA's, we are not allowed to delete correspondence data or clients records for longer than the potential lifespan of the application I'm writing, and therefor, I simply mark records with an enum "Status" which is either "Active" or "Deleted". You can delete something from the UI, and it will say "Contact has been deleted" but all the application has done is change the status of the contact to "Deleted" and when the app calls the respository for a list of contacts, I filter out deleted records before pushing the data to the client app.
Therefore, db.collection.find().count() + 1 is a perfect solution for me...
It won't work for everyone, but if you will not be deleting data, it works fine.
I'm going to throw out another solution because it's straightforward and not mathematically intensive - it just uses basic algebra. Calculate the signed area of the polygon. If it's negative the points are in clockwise order, if it's positive they are counterclockwise. (This is very similar to Beta's solution.)
Calculate the signed area: A = 1/2 * (x1*y2 - x2*y1 + x2*y3 - x3*y2 + ... + xn*y1 - x1*yn)
Or in pseudo-code:
signedArea = 0
for each point in points:
x1 = point[0]
y1 = point[1]
if point is last point
x2 = firstPoint[0]
y2 = firstPoint[1]
else
x2 = nextPoint[0]
y2 = nextPoint[1]
end if
signedArea += (x1 * y2 - x2 * y1)
end for
return signedArea / 2
Note that if you are only checking the ordering, you don't need to bother dividing by 2.
You can also accomplish this by breaking things up into separate logical statements by including &
to separate the statements.
subset(my.df, my.df$v1 != "b" & my.df$v1 != "d" & my.df$v1 != "e")
This is not elegant and takes more code but might be more readable to newer R users. As pointed out in a comment above, subset
is a "convenience" function that is best used when working interactively.
Click "view details" to find the inner exception.
Well Curl could be a better option for json representation but in that case it would be difficult to understand the structure of json because its in command line. if you want to get your json on browser you simply remove all the XML Annotations like -
@XmlRootElement(name="person")
@XmlAccessorType(XmlAccessType.NONE)
@XmlAttribute
@XmlElement
from your model class and than run the same url, you have used for xml representation.
Make sure that you have jacson-databind dependency in your pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1</version>
</dependency>
I found the approach given by cimmanon and Kurt Mueller almost worked, but that I needed a parent reference (i.e., I need to add the '&' prefix to each vendor prefix); like this:
@mixin placeholder {
&::-webkit-input-placeholder {@content}
&:-moz-placeholder {@content}
&::-moz-placeholder {@content}
&:-ms-input-placeholder {@content}
}
I use the mixin like this:
input {
@include placeholder {
font-family: $base-font-family;
color: red;
}
}
With the parent reference in place, then correct css gets generated, e.g.:
input::-webkit-input-placeholder {
font-family: Constantia, "Lucida Bright", Lucidabright, "Lucida Serif", Lucida, "DejaVu Serif", "Liberation Serif", Georgia, serif;
color: red;
}
Without the parent reference (&), then a space is inserted before the vendor prefix and the CSS processor ignores the declaration; that looks like this:
input::-webkit-input-placeholder {
font-family: Constantia, "Lucida Bright", Lucidabright, "Lucida Serif", Lucida, "DejaVu Serif", "Liberation Serif", Georgia, serif;
color: red;
}
GROUP BY DATEADD(day, DATEDIFF(day, 0, MyDateTimeColumn), 0)
Or in SQL Server 2008 onwards you could simply cast to Date
as @Oded suggested:
GROUP BY CAST(orderDate AS DATE)
The character set is part of the locale, which is determined by the value of NLS_LANG
. As the documentation makes clear this is an operating system variable:
NLS_LANG
is set as an environment variable on UNIX platforms.NLS_LANG
is set in the registry on Windows platforms.
Now we can use ALTER SESSION
to change the values for a couple of locale elements, NLS_LANGUAGE and NLS_TERRITORY. But not, alas, the character set. The reason for this discrepancy is - I think - that the language and territory simply effect how Oracle interprets the stored data, e.g. whether to display a comma or a period when displaying a large number. Wheareas the character set is concerned with how the client application renders the displayed data. This information is picked up by the client application at startup time, and cannot be changed from within.
You need to add an action
into your form like:
<form name='form1' method='post' action='<?php echo($_SERVER['PHP_SELF']);'>
<!-- All your input for the form here -->
</form>
Then put your snippet at the top of the document en send the mail. What echo($_SERVER['PHP_SELF']);
does is that it sends your information to the top of your script so you could use it.
Basically you have two options
scale_x_continuous(limits = c(-5000, 5000))
or
coord_cartesian(xlim = c(-5000, 5000))
Where the first removes all data points outside the given range and the second only adjusts the visible area. In most cases you would not see the difference, but if you fit anything to the data it would probably change the fitted values.
You can also use the shorthand function xlim
(or ylim
), which like the first option removes data points outside of the given range:
+ xlim(-5000, 5000)
For more information check the description of coord_cartesian
.
The RStudio cheatsheet for ggplot2
makes this quite clear visually. Here is a small section of that cheatsheet:
Distributed under CC BY.
This was too good of an answer not to post it here. It's from a Gilles, a fellow user from askubuntu:
The clipboard is provided by the X server. It doesn't matter whether the server is headless or not, what matters is that your local graphical session is available to programs running on the remote machine. Thanks to X's network-transparent design, this is possible.
I assume that you're connecting to the remote server with SSH from a machine running Linux. Make sure that X11 forwarding is enabled both in the client configuration and in the server configuration. In the client configuration, you need to have the line
ForwardX11 yes
in~/.ssh/config
to have it on by default, or pass the option-X
to thessh
command just for that session. In the server configuration, you need to have the lineX11Forwarding yes
in/etc/ssh/sshd_config
(it is present by default on Ubuntu).To check whether X11 forwarding is enabled, look at the value of the
DISPLAY
environment variable:echo $DISPLAY
. You should see a value likelocalhost:10
(applications running on the remote machine are told to connect to a display running on the same machine, but that display connection is in fact forwarded by SSH to your client-side display). Note that ifDISPLAY
isn't set, it's no use setting it manually: the environment variable is always set correctly if the forwarding is in place. If you need to diagnose SSH connection issues, pass the option-vvv
tossh
to get a detailed trace of what's happening.If you're connecting through some other means, you may or may not be able to achieve X11 forwarding. If your client is running Windows, PuTTY supports X11 forwarding; you'll have to run an X server on the Windows machine such as Xming.
By Gilles from askubuntu
Yes, it prints GARBAGE unless you are lucky.
VERY IMPORTANT.
The type of the printf/sprintf/fprintf argument MUST match the associated format type char.
If the types don't match and it compiles, the results are very undefined.
Many newer compilers know about printf and issue warnings if the types do not match. If you get these warnings, FIX them.
If you want to convert types for arguments for variable functions, you must supply the cast (ie, explicit conversion) because the compiler can't figure out that a conversion needs to be performed (as it can with a function prototype with typed arguments).
printf("%d\n", (int) ch)
In this example, printf is being TOLD that there is an "int" on the stack. The cast makes sure that whatever thing sizeof returns (some sort of long integer, usually), printf will get an int.
printf("%d", (int) sizeof('\n'))
You could try using AJAX calls with jQuery. Like how youtube adds your comment without refreshing. This would remove the problem with refreshing overal.
You'd need to send the info necessary trough the ajax call.
I'll use the youtube comment as example.
$.ajax({
type: 'POST',
url: 'ajax/comment-on-video.php',
data: {
comment: $('#idOfInputField').val();
},
success: function(obj) {
if(obj === 'true') {
//Some code that recreates the inserted comment on the page.
}
}
});
You can now create the file comment-on-video.php
and create something like this:
<?php
session_start();
if(isset($_POST['comment'])) {
$comment = mysqli_real_escape_string($db, $_POST['comment']);
//Given you are logged in and store the user id in the session.
$user = $_SESSION['user_id'];
$query = "INSERT INTO `comments` (`comment_text`, `user_id`) VALUES ($comment, $user);";
$result = mysqli_query($db, $query);
if($result) {
echo true;
exit();
}
}
echo false;
exit();
?>
Yes, the sorting is different.
Items in the ORDER BY
list are applied in order.
Later items only order peers left from the preceding step.
Why don't you just try?
! typically means that the method acts upon the object instead of returning a result. From the book Programming Ruby:
Methods that are "dangerous," or modify the receiver, might be named with a trailing "!".
This is an example using the Expr() Class - I needed this too some days ago and it took me some time to find out what is the exact syntax and way of usage:
/**
* fetches Products that are more expansive than the given price
*
* @param int $price
* @return array
*/
public function findProductsExpensiveThan($price)
{
$em = $this->getEntityManager();
$qb = $em->createQueryBuilder();
$q = $qb->select(array('p'))
->from('YourProductBundle:Product', 'p')
->where(
$qb->expr()->gt('p.price', $price)
)
->orderBy('p.price', 'DESC')
->getQuery();
return $q->getResult();
}
Assuming that by "string" you're talking about std::string in C++, you might have a look at the Tokenizer package in Boost.
So I had this exact same issue and lost about 6 hours of my life searching, I had the
withCredentials: true
But the browser still didn't save the cookie until for some weird reason I had the idea to shuffle the configuration setting:
Axios.post(GlobalVariables.API_URL + 'api/login', {
email,
password,
honeyPot
}, {
withCredentials: true,
headers: {'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'
}});
Seems like you should always send the 'withCredentials' Key first.
public static bool IsNegative<T>(T value)
where T : struct, IComparable<T>
{
return value.CompareTo(default(T)) < 0;
}
You can use also system table_types view
IF EXISTS (SELECT *
FROM [sys].[table_types]
WHERE user_type_id = Type_id(N'[dbo].[UdTableType]'))
BEGIN
PRINT 'EXISTS'
END
I needed to add this event to multiple elements that might have a scrollbar. For the cases where no scrollbar was present, the main scrollbar didn't work as it should. So i made a small change to @Šime code as follows:
$( '.scrollable' ).on( 'mousewheel DOMMouseScroll', function ( e ) {
if($(this).prop('scrollHeight') > $(this).height())
{
var e0 = e.originalEvent, delta = e0.wheelDelta || -e0.detail;
this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
e.preventDefault();
}
});
Now, only elements with a scrollbar will prevent the main scroll from begin stopped.
I'm resurrecting the dead here, but because a range can be defined as "A:A", using a for each loop ends up with a potential infinite loop. The solution, as far as I know, is to use the Do Until
loop.
Do Until Selection.Value = ""
Rem Do things here...
Loop
.NET is not very helpful, but you can try the following algorithm:
Here is the call:
var encoding = FileHelper.GetEncoding(filePath);
if (encoding == null)
throw new Exception("The file encoding is not supported. Please choose one of the following encodings: UTF8/UTF7/iso-8859-1");
Here is the code:
public class FileHelper
{
/// <summary>
/// Determines a text file's encoding by analyzing its byte order mark (BOM) and if not found try parsing into diferent encodings
/// Defaults to UTF8 when detection of the text file's endianness fails.
/// </summary>
/// <param name="filename">The text file to analyze.</param>
/// <returns>The detected encoding or null.</returns>
public static Encoding GetEncoding(string filename)
{
var encodingByBOM = GetEncodingByBOM(filename);
if (encodingByBOM != null)
return encodingByBOM;
// BOM not found :(, so try to parse characters into several encodings
var encodingByParsingUTF8 = GetEncodingByParsing(filename, Encoding.UTF8);
if (encodingByParsingUTF8 != null)
return encodingByParsingUTF8;
var encodingByParsingLatin1 = GetEncodingByParsing(filename, Encoding.GetEncoding("iso-8859-1"));
if (encodingByParsingLatin1 != null)
return encodingByParsingLatin1;
var encodingByParsingUTF7 = GetEncodingByParsing(filename, Encoding.UTF7);
if (encodingByParsingUTF7 != null)
return encodingByParsingUTF7;
return null; // no encoding found
}
/// <summary>
/// Determines a text file's encoding by analyzing its byte order mark (BOM)
/// </summary>
/// <param name="filename">The text file to analyze.</param>
/// <returns>The detected encoding.</returns>
private static Encoding GetEncodingByBOM(string filename)
{
// Read the BOM
var byteOrderMark = new byte[4];
using (var file = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
file.Read(byteOrderMark, 0, 4);
}
// Analyze the BOM
if (byteOrderMark[0] == 0x2b && byteOrderMark[1] == 0x2f && byteOrderMark[2] == 0x76) return Encoding.UTF7;
if (byteOrderMark[0] == 0xef && byteOrderMark[1] == 0xbb && byteOrderMark[2] == 0xbf) return Encoding.UTF8;
if (byteOrderMark[0] == 0xff && byteOrderMark[1] == 0xfe) return Encoding.Unicode; //UTF-16LE
if (byteOrderMark[0] == 0xfe && byteOrderMark[1] == 0xff) return Encoding.BigEndianUnicode; //UTF-16BE
if (byteOrderMark[0] == 0 && byteOrderMark[1] == 0 && byteOrderMark[2] == 0xfe && byteOrderMark[3] == 0xff) return Encoding.UTF32;
return null; // no BOM found
}
private static Encoding GetEncodingByParsing(string filename, Encoding encoding)
{
var encodingVerifier = Encoding.GetEncoding(encoding.BodyName, new EncoderExceptionFallback(), new DecoderExceptionFallback());
try
{
using (var textReader = new StreamReader(filename, encodingVerifier, detectEncodingFromByteOrderMarks: true))
{
while (!textReader.EndOfStream)
{
textReader.ReadLine(); // in order to increment the stream position
}
// all text parsed ok
return textReader.CurrentEncoding;
}
}
catch (Exception ex) { }
return null; //
}
}
With MySql 5.1 (Win7). To recreate DBs (InnoDbs) I've replaced all contents of following dirs (my.ini params):
datadir="C:/ProgramData/MySQL/MySQL Server 5.1/Data/"
innodb_data_home_dir="C:/MySQL Datafiles/"
After that I started MySql Service and all works fine.
You can also use another built-in template default_if_none
{{ profile.user.first_name|default_if_none:"--" }}
The traditional way to deal with asynchronous calls in JavaScript has been with callbacks. Say we had to make three calls to the server, one after the other, to set up our application. With callbacks, the code might look something like the following (assuming a xhrGET function to make the server call):
// Fetch some server configuration
xhrGET('/api/server-config', function(config) {
// Fetch the user information, if he's logged in
xhrGET('/api/' + config.USER_END_POINT, function(user) {
// Fetch the items for the user
xhrGET('/api/' + user.id + '/items', function(items) {
// Actually display the items here
});
});
});
In this example, we first fetch the server configuration. Then based on that, we fetch information about the current user, and then finally get the list of items for the current user. Each xhrGET call takes a callback function that is executed when the server responds.
Now of course the more levels of nesting we have, the harder the code is to read, debug, maintain, upgrade, and basically work with. This is generally known as callback hell. Also, if we needed to handle errors, we need to possibly pass in another function to each xhrGET call to tell it what it needs to do in case of an error. If we wanted to have just one common error handler, that is not possible.
The Promise API was designed to solve this nesting problem and the problem of error handling.
The Promise API proposes the following:
promise
object.promise
object will have a then
function that can take two arguments, a success
handler and an error
handler.then
function will be called only once, after
the asynchronous task finishes.then
function will also return a promise
, to allow chaining multiple calls.value
, which will be passed to the next
function as an argument
, in the chain of promise
s.promise
(makes another asynchronous request), then the next
handler (success or error) will be called only after that request is finished.So the previous example code might translate to something like the following, using
promises and the $http
service(in AngularJs):
$http.get('/api/server-config').then(
function(configResponse) {
return $http.get('/api/' + configResponse.data.USER_END_POINT);
}
).then(
function(userResponse) {
return $http.get('/api/' + userResponse.data.id + '/items');
}
).then(
function(itemResponse) {
// Display items here
},
function(error) {
// Common error handling
}
);
Propagating Success and Error
Chaining promises is a very powerful technique that allows us to accomplish a lot of
functionality, like having a service make a server call, do some postprocessing of the
data, and then return the processed data to the controller. But when we work with
promise
chains, there are a few things we need to keep in mind.
Consider the following hypothetical promise
chain with three promises, P1, P2, and P3.
Each promise
has a success handler and an error handler, so S1 and E1 for P1, S2 and
E2 for P2, and S3 and E3 for P3:
xhrCall()
.then(S1, E1) //P1
.then(S2, E2) //P2
.then(S3, E3) //P3
In the normal flow of things, where there are no errors, the application would flow through S1, S2, and finally, S3. But in real life, things are never that smooth. P1 might encounter an error, or P2 might encounter an error, triggering E1 or E2.
Consider the following cases:
• We receive a successful response from the server in P1, but the data returned is not correct, or there is no data available on the server (think empty array). In such a case, for the next promise P2, it should trigger the error handler E2.
• We receive an error for promise P2, triggering E2. But inside the handler, we have data from the cache, ensuring that the application can load as normal. In that case, we might want to ensure that after E2, S3 is called.
So each time we write a success or an error handler, we need to make a call—given our current function, is this promise a success or a failure for the next handler in the promise chain?
If we want to trigger the success handler for the next promise in the chain, we can just return a value from the success or the error handler
If, on the other hand, we want to trigger the error handler for the next promise in the
chain, we can do that using a deferred
object and calling its reject()
method
Now What is deferred object?
Deferred objects in jQuery represents a unit of work that will be completed later, typically asynchronously. Once the unit of work completes, the
deferred
object can be set to resolved or failed.A
deferred
object contains apromise
object. Via thepromise
object you can specify what is to happen when the unit of work completes. You do so by setting callback functions on thepromise
object.
Deferred objects in Jquery : https://api.jquery.com/jquery.deferred/
Deferred objects in AngularJs : https://docs.angularjs.org/api/ng/service/$q
Yes it works fine and is commonly used:
$ echo "hello world" | mail -s "a subject" [email protected]
Just another possibility: Spring initializes bean by type not by name if you don't define bean with a name, which is ok if you use it by its type:
Producer:
@Service
public void FooServiceImpl implements FooService{}
Consumer:
@Autowired
private FooService fooService;
or
@Autowired
private void setFooService(FooService fooService) {}
but not ok if you use it by name:
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
ctx.getBean("fooService");
It would complain: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'fooService' is defined
In this case, assigning name to @Service("fooService")
would make it work.
Just start your browser with superuser rights, and don't forget to set Java's JRE security to medium.
Do you have ROWS of data (horizontal) as you stated or COLUMNS (vertical)?
If it's the latter you can use "Text to columns" functionality to convert a whole column "in situ" - to do that:
Select column > Data > Text to columns > Next > Next > Choose "Date" under "column data format" and "YMD" from dropdown > Finish
....otherwise you can convert with a formula by using
=TEXT(A1,"0000-00-00")+0
and format in required date format
DateTime birthDate = new DateTime(1981, 8, 9);
Console.WriteLine ("I was born on the {0}. of {1}, {2}.", birthDate.Day, birthDate.ToString("MMMM"), birthDate.Year);
/* The above code will say:
"I was born on the 9. of august, 1981."
"dd" converts to the day (01 thru 31).
"ddd" converts to 3-letter name of day (e.g. mon).
"dddd" converts to full name of day (e.g. monday).
"MMM" converts to 3-letter name of month (e.g. aug).
"MMMM" converts to full name of month (e.g. august).
"yyyy" converts to year.
*/
You need to change
<activity
android:name=".YOUR ACTIVITY"
android:theme="@style/AppTheme.NoActionBar" />
</application>`
these lines in the manifest.It will perfectly work for me.
this will unhide all files and folders on your computer
attrib -r -s -h /S /D
do:
$("button").click(function() {
$('html,body').animate({
scrollTop: $(".second").offset().top},
'slow');
});
Updated Jsfiddle
Also worth noting that WinFlexBison has been packaged for the Chocolatey package manager. Install that and then go:
choco install winflexbison
...which at the time of writing contains Bison 2.7 & Flex 2.6.3.
There is also winflexbison3
which (at the time of writing) has Bison 3.0.4 & Flex 2.6.3.
Use ?? , 'or' not supported in updated version.
{{ $usersType or '' }} ?
{{ $usersType ?? '' }} ?
See the most recent stash:
git stash show -p
See an arbitrary stash:
git stash show -p stash@{1}
From the git stash
manpages:
By default, the command shows the diffstat, but it will accept any format known to git diff (e.g., git stash show -p stash@{1} to view the second most recent stash in patch form).
I know there are several iterations of answers but now this doesn't require jquery or any other external library and can be accomplished pretty easy just with the following.
document.querySelector("#gate option[value='Gateway 2']").setAttribute('selected',true);
_x000D_
<select id="gate">_x000D_
<option value='null'>- choose -</option>_x000D_
<option value='Gateway 1'>Gateway 1</option>_x000D_
<option value='Gateway 2'>Gateway 2</option>_x000D_
</select>
_x000D_
You can use Collections.list()
to convert an Enumeration
to a List
in one line:
List<T> list = Collections.list(enumeration);
There's no similar method to get a Set
, however you can still do it one line:
Set<T> set = new HashSet<T>(Collections.list(enumeration));
For anyone still reading this, indexOf() will probably perform better on most enterprise systems, as contains() is not compatible with IE!
To combine revision 3 and 4 into a single revision, you can use git rebase. If you want to remove the changes in revision 3, you need to use the edit command in the interactive rebase mode. If you want to combine the changes into a single revision, use squash.
I have successfully used this squash technique, but have never needed to remove a revision before. The git-rebase documentation under "Splitting commits" should hopefully give you enough of an idea to figure it out. (Or someone else might know).
From the git documentation:
Start it with the oldest commit you want to retain as-is:
git rebase -i <after-this-commit>
An editor will be fired up with all the commits in your current branch (ignoring merge commits), which come after the given commit. You can reorder the commits in this list to your heart's content, and you can remove them. The list looks more or less like this:
pick deadbee The oneline of this commit pick fa1afe1 The oneline of the next commit ...The oneline descriptions are purely for your pleasure; git-rebase will not look at them but at the commit names ("deadbee" and "fa1afe1" in this example), so do not delete or edit the names.
By replacing the command "pick" with the command "edit", you can tell git-rebase to stop after applying that commit, so that you can edit the files and/or the commit message, amend the commit, and continue rebasing.
If you want to fold two or more commits into one, replace the command "pick" with "squash" for the second and subsequent commit. If the commits had different authors, it will attribute the squashed commit to the author of the first commit.
This is very common error that we face while starting any Project Vue. I spent lot of time to search this error and finally found a Solution. Suppose i have component that is "table.vue",
i.e components/table.vue
In app.js
Vue.component('mytablecomp', require('./components/table.vue').default);
So in in your index.blade file call component as
<mytablecomp></mytablecomp>
Just you need to keep in mind that your component name is in small not in large or camel case. Then my above code will surely work for you.
Thanks
To delete trailing whitespace at end of line in a file portably, use ed
:
test -s file &&
printf '%s\n' H ',g/[[:space:]]*$/s///' 'wq' | ed -s file
Replace all require
statements with import
statements. Example:
// Before:
const Web3 = require('web3');
// After:
import Web3 from 'web3';
It worked for me.
I've found this code to detect if the device is in landscape orientation and in this case add a splash page saying "change orientation to see the site". It's working on iOS, android and windows phones. I think that this is very useful since it's quite elegant and avoid to set a landscape view for the mobile site. The code is working very well. The only thing not completely satisfying is that if someone load the page being in landscape view the splash page doesn't appears.
<script>
(function() {
'use strict';
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i);
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
if (isMobile.any()) {
doOnOrientationChange();
window.addEventListener('resize', doOnOrientationChange, 'false');
}
function doOnOrientationChange() {
var a = document.getElementById('alert');
var b = document.body;
var w = b.offsetWidth;
var h = b.offsetHeight;
(w / h > 1) ? (a.className = 'show', b.className = 'full-body') : (a.className = 'hide', b.className = '');
}
})();
</script>
And the HTML: <div id="alert" class="hide"> <div id="content">This site is not thought to be viewed in landscape mode, please turn your device </div> </div>
It is WiFi bug due to wifi disable or not properly connected.
Simply Reconnect the wifi will solve the issue.
It is important to understand that accessors restrict access to variable, but not their content. In ruby, like in some other OO languages, every variable is a pointer to an instance. So if you have an attribute to an Hash, for example, and you set it to be "read only" you always could change its content, but not the content of pointer. Look at this:
irb(main):024:0> class A
irb(main):025:1> attr_reader :a
irb(main):026:1> def initialize
irb(main):027:2> @a = {a:1, b:2}
irb(main):028:2> end
irb(main):029:1> end
=> :initialize
irb(main):030:0> a = A.new
=> #<A:0x007ffc5a10fe88 @a={:a=>1, :b=>2}>
irb(main):031:0> a.a
=> {:a=>1, :b=>2}
irb(main):032:0> a.a.delete(:b)
=> 2
irb(main):033:0> a.a
=> {:a=>1}
irb(main):034:0> a.a = {}
NoMethodError: undefined method `a=' for #<A:0x007ffc5a10fe88 @a={:a=>1}>
from (irb):34
from /usr/local/bin/irb:11:in `<main>'
As you can see is possible delete a key/value pair from the Hash @a, as add new keys, change values, eccetera. But you can't point to a new object because is a read only instance variable.
For python3.5.3, pip3 is also installed when you install python. When you install it you may not select the add to path. Then you can find where the pip3 located and add it to path manually.
Its absolutely possible only when you set layer.masksToBounds = true
and do you rest stuff.
The best bet with these types of questions is to see exactly what python does. The dis
module is incredibly informative:
>>> import dis
>>> dis.dis("val != None")
1 0 LOAD_NAME 0 (val)
2 LOAD_CONST 0 (None)
4 COMPARE_OP 3 (!=)
6 RETURN_VALUE
>>> dis.dis("not (val is None)")
1 0 LOAD_NAME 0 (val)
2 LOAD_CONST 0 (None)
4 COMPARE_OP 9 (is not)
6 RETURN_VALUE
>>> dis.dis("val is not None")
1 0 LOAD_NAME 0 (val)
2 LOAD_CONST 0 (None)
4 COMPARE_OP 9 (is not)
6 RETURN_VALUE
Notice that the last two cases reduce to the same sequence of operations, Python reads not (val is None)
and uses the is not
operator. The first uses the !=
operator when comparing with None
.
As pointed out by other answers, using !=
when comparing with None
is a bad idea.
To append entries to the table:
for row in data:
name = ??? # figure out the name of the drug
number = ??? # figure out the number you want to append
drug_dictionary[name].append(number)
To loop through the data:
for name, numbers in drug_dictionary.items():
print name, numbers
IMO, the provider is telling you to change the service endpoint (i.e. where to reach the web service), not the client endpoint (I don't understand what this could be). To change the service endpoint, you basically have two options.
The first option is to change the BindingProvider.ENDPOINT_ADDRESS_PROPERTY
property value of the BindingProvider
(every proxy implements javax.xml.ws.BindingProvider
interface):
...
EchoService service = new EchoService();
Echo port = service.getEchoPort();
/* Set NEW Endpoint Location */
String endpointURL = "http://NEW_ENDPOINT_URL";
BindingProvider bp = (BindingProvider)port;
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointURL);
System.out.println("Server said: " + echo.echo(args[0]));
...
The drawback is that this only works when the original WSDL is still accessible. Not recommended.
The second option is to get the endpoint URL from the WSDL.
...
URL newEndpoint = new URL("NEW_ENDPOINT_URL");
QName qname = new QName("http://ws.mycompany.tld","EchoService");
EchoService service = new EchoService(newEndpoint, qname);
Echo port = service.getEchoPort();
System.out.println("Server said: " + echo.echo(args[0]));
...
When I used CocoaPods to develop iOS projects, there is a .xcworkspace
file, you need to open the project with .xcworkspace
file related with CocoaPods.
But when you Show Package Contents
with .xcworkspace
file, you will find the contents.xcworkspacedata
file.
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:BluetoothColorLamp24G.xcodeproj">
</FileRef>
<FileRef
location = "group:Pods/Pods.xcodeproj">
</FileRef>
</Workspace>
pay attention to this line:
location = "group:BluetoothColorLamp24G.xcodeproj"
The .xcworkspace
file has reference with the .xcodeproj
file.
Development Environment:
macOS 10.14
Xcode 10.1
If you got node __dirname not defined
with node --experimental-modules
, you can do :
const __dirname = path.dirname(import.meta.url)
.replace(/^file:\/\/\//, '') // can be usefull
Because othe example, work only with current/pwd directory not other directory.
I only use rebase workflow, because it is visually clearer(not only in GitKraken, but also in Intellij and in gitk
, but I recommend the first one most): you have a branch, it originates from the master, and it goes back to master. When the diagram is clean and beautiful, you will know that nothing goes to hell, ever.
My workflow is almost the same from yours, but with only one small difference: I squash
commits into one in my local branch before rebase
my branch onto the latest changes on master
, because:
rebase
works on basis of each commit
which means, if you have 15 commits changing the same line as master
does, you have to check 15 times if you don't squash, but what matters is the final result, right?
So, the whole workflow is:
Checkout to master
and pull to ensure that you have the latest version
From there, create a new branch
Do your work there, you can freely commit several times, and push to remote, no worries, because it is your branch.
If someone tells you, "hey, my PR/MR is approved, now it is merged to master", you can fetch them/pull them. You can do it anytime, or in step 6.
After doing all your work, commit them, and if you have several commits, squash them(they are all your work, and how many times you change a line of code does not matter; the only important thing is the final version). Push it or not, it doesn't matter.
Checkout to master
, pull
again to ensure you have the latest master
in local. Your diagram should be similar to this:
As you can see, you are on your local branch, which originates from an outdated status on master
, while master
(both local and remote) has moved forward with changes of your colleague.
master
and choose "Rebase"; another reason why I like it.)
After that, you will be like:So now, you have all the changes on the latest master
, combined with changes on your branch. You can now push to your remote, and, if you have pushed before, you will have to force push; Git will tell you that you cannot simply fast forward. That's normal, because of the rebase, you have changed the start point of your branch. But you should not fear: wisely use the force, but without fear. In the end, the remote is also your branch so you do not affect master
even if you do something wrong.
Create PR/MR and wait until it is approved, so master
will have your contribution. Congrats! So you can now checkout to master
, pull your changes, and delete your local branch in order to clean up the diagram. The remote branch should be deleted too, if this is not done when you merge it into master.
The final diagram is clean and clear again:
(out of date) Spreadsheet of device metrics.
SEE ALSO:
Device Metrics - Material Design.
Screen Sizes.
--------------------------- ----- ------------ --------------- ------- ----------- ---------------- --- ----------
Device Inches ResolutionPX Density DPI ResolutionDP AspectRatios SysNavYorN ContentResolutionDP
--------------------------- ----- ------------ --------------- ------- ----------- ---------------- --- ----------
Galaxy Y 320 x 240 ldpi 0.75 120 427 x 320 4:3 1.3333 427 x 320
? 400 x 240 ldpi 0.75 120 533 x 320 5:3 1.6667 533 x 320
? 432 x 240 ldpi 0.75 120 576 x 320 9:5 1.8000 576 x 320
Galaxy Ace 480 x 320 mdpi 1 160 480 x 320 3:2 1.5000 480 x 320
Nexus S 800 x 480 hdpi 1.5 240 533 x 320 5:3 1.6667 533 x 320
"Galaxy SIII Mini" 800 x 480 hdpi 1.5 240 533 x 320 5:3 1.6667 533 x 320
? 854 x 480 hdpi 1.5 240 569 x 320 427:240 1.7792 569 x 320
Galaxy SIII 1280 x 720 xhdpi 2 320 640 x 360 16:9 1.7778 640 x 360
Galaxy Nexus 1280 x 720 xhdpi 2 320 640 x 360 16:9 1.7778 640 x 360
HTC One X 4.7" 1280 x 720 xhdpi 2 320 640 x 360 16:9 1.7778 640 x 360
Nexus 5 5" 1920 x 1080 xxhdpi 3 480 640 x 360 16:9 1.7778 YES 592 x 360
Galaxy S4 5" 1920 x 1080 xxhdpi 3 480 640 x 360 16:9 1.7778 640 x 360
HTC One 5" 1920 x 1080 xxhdpi 3 480 640 x 360 16:9 1.7778 640 x 360
Galaxy Note III 5.7" 1920 x 1080 xxhdpi 3 480 640 x 360 16:9 1.7778 640 x 360
HTC One Max 5.9" 1920 x 1080 xxhdpi 3 480 640 x 360 16:9 1.7778 640 x 360
Galaxy Note II 5.6" 1280 x 720 xhdpi 2 320 640 x 360 16:9 1.7778 640 x 360
Nexus 4 4.4" 1200 x 768 xhdpi 2 320 600 x 384 25:16 1.5625 YES 552 x 384
--------------------------- ----- ------------ --------------- ------- ----------- ---------------- --- ----------
Device Inches ResolutionPX Density DPI ResolutionDP AspectRatios SysNavYorN ContentResolutionDP
--------------------------- ----- ------------ --------------- ------- ----------- ---------------- --- ----------
? 800 x 480 mdpi 1 160 800 x 480 5:3 1.6667 800 x 480
? 854 x 480 mdpi 1 160 854 x 480 427:240 1.7792 854 x 480
Galaxy Mega 6.3" 1280 x 720 hdpi 1.5 240 853 x 480 16:9 1.7778 853 x 480
Kindle Fire HD 7" 1280 x 800 hdpi 1.5 240 853 x 533 8:5 1.6000 853 x 533
Galaxy Mega 5.8" 960 x 540 tvdpi 1.33333 213.333 720 x 405 16:9 1.7778 720 x 405
Sony Xperia Z Ultra 6.4" 1920 x 1080 xhdpi 2 320 960 x 540 16:9 1.7778 960 x 540
Blackberry Priv 5.43" 2560 x 1440 ? 540 ? 16:9 1.7778
Blackberry Passport 4.5" 1440 x 1440 ? 453 ? 1:1 1.0
Kindle Fire (1st & 2nd gen) 7" 1024 x 600 mdpi 1 160 1024 x 600 128:75 1.7067 1024 x 600
Tesco Hudl 7" 1400 x 900 hdpi 1.5 240 933 x 600 14:9 1.5556 933 x 600
Nexus 7 (1st gen/2012) 7" 1280 x 800 tvdpi 1.33333 213.333 960 x 600 8:5 1.6000 YES 912 x 600
Nexus 7 (2nd gen/2013) 7" 1824 x 1200 xhdpi 2 320 912 x 600 38:25 1.5200 YES 864 x 600
Kindle Fire HDX 7" 1920 x 1200 xhdpi 2 320 960 x 600 8:5 1.6000 960 x 600
? 800 x 480 ldpi 0.75 120 1067 x 640 5:3 1.6667 1067 x 640
? 854 x 480 ldpi 0.75 120 1139 x 640 427:240 1.7792 1139 x 640
Kindle Fire HD 8.9" 1920 x 1200 hdpi 1.5 240 1280 x 800 8:5 1.6000 1280 x 800
Kindle Fire HDX 8.9" 2560 x 1600 xhdpi 2 320 1280 x 800 8:5 1.6000 1280 x 800
Galaxy Tab 2 10" 1280 x 800 mdpi 1 160 1280 x 800 8:5 1.6000 1280 x 800
Galaxy Tab 3 10" 1280 x 800 mdpi 1 160 1280 x 800 8:5 1.6000 1280 x 800
ASUS Transformer 10" 1280 x 800 mdpi 1 160 1280 x 800 8:5 1.6000 1280 x 800
ASUS Transformer 2 10" 1920 x 1200 hdpi 1.5 240 1280 x 800 8:5 1.6000 1280 x 800
Nexus 10 10" 2560 x 1600 xhdpi 2 320 1280 x 800 8:5 1.6000 1280 x 800
Galaxy Note 10.1 10" 2560 x 1600 xhdpi 2 320 1280 x 800 8:5 1.6000 1280 x 800
--------------------------- ----- ------------ --------------- ------- ----------- ---------------- --- ----------
Device Inches ResolutionPX Density DPI ResolutionDP AspectRatios SysNavYorN ContentResolutionDP
--------------------------- ----- ------------ --------------- ------- ----------- ---------------- --- ----------
Coping with different aspect ratios
The different aspect ratios seen above are (from most square; h/w):
1:1 1.0 <- rare for phone; common for watch
4:3 1.3333 <- matches iPad (when portrait)
3:2 1.5000
38:25 1.5200
14:9 1.5556 <- rare
25:16 1.5625
8:5 1.6000 <- aka 16:10
5:3 1.6667
128:75 1.7067
16:9 1.7778 <- matches iPhone 5-7
427:240 1.7792 <- rare
37:18 2.0555 <- Galaxy S8
If you skip the extreme aspect ratios, that are rarely seen at phone size or larger, all the other devices fit a range from 1.3333 to 1.7778, which conveniently matches the current iPhone/iPad ratios (considering all devices in portrait mode). Note that there are quite a few variations within that range, so if you are creating a small number of fixed aspect-ratio layouts, you will need to decide how to handle the odd "in-between" screens.
Minimum "portrait mode" solution is to support 1.3333, which results in unused space at top and bottom, on all the resolutions with larger aspect ratio.
Most likely, you would instead design it to stretch over the 1.333 to 1.778 range. But sometimes part of your design looks too distorted then.
Advanced layout ideas:
For text, you can design for 1.3333, then increase line spacing for 1.666 - though that will look quite sparse. For graphics, design for an intermediate ratio, so that on some screens it is slightly squashed, on others it is slightly stretched. geometric mean of Sqrt(1333 x 1667) ~= 1491. So you design for 1491 x 1000, which will be stretched/squashed by +-12% when assigned to the extreme cases.
Next refinement is to design layout as a stack of different-height "bands" that each fill the width of the screen. Then determine where you can most pleasingly "stretch-or-squash" a band's height, to adjust for different ratios.
For example, consider imaginary phones with 1333 x 1000 pixels and 1666 x 1000 pixels. Suppose you have two "bands", and your main "band" is square, so it is 1000 x 1000. Second band is 333 x 1000 on one screen, 666 x 1000 on the other - quite a range to design for.
You might decide your main band looks okay altered 10% up-or-down, and squash it 900 x 1000 on the 1333 x 1000 screen, leaving 433 x 1000. Then stretch it to 1100 x 1000 on 1666 x 1000 screen, leaving 566 x 1000. So your second band now needs to adjust over only 433 to 566, which has geometric mean of Sqrt(433 x 566) ~= 495. So you design for 495 x 1000, which will be stretched/squashed by +-14% when assigned to the extreme cases.
My experience is that the new version of Filezilla has this problem, but not the old versions. I was using Filezilla and everything was OK. After I upgraded to version 3.10, I faced this problem and I couldn't solve it. I uninstalled version 3.10 and reinstalled version 3.8 and the problem was gone! Now I am using version 3.8 and everything is OK. I prefer to face no problems even if I have to use old versions. ;)
Try installing the old version and do not upgrade, however odd that may sound.
<ul style="color: red;">
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
Just set all the selected time unit's displayFormat
to MMM DD
options: {
scales: {
xAxes: [{
type: 'time',
time: {
displayFormats: {
'millisecond': 'MMM DD',
'second': 'MMM DD',
'minute': 'MMM DD',
'hour': 'MMM DD',
'day': 'MMM DD',
'week': 'MMM DD',
'month': 'MMM DD',
'quarter': 'MMM DD',
'year': 'MMM DD',
}
...
Notice that I've set all the unit's display format to MMM DD
. A better way, if you have control over the range of your data and the chart size, would be force a unit, like so
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day',
unitStepSize: 1,
displayFormats: {
'day': 'MMM DD'
}
...
Fiddle - http://jsfiddle.net/prfd1m8q/
It just means that either alter > ncol( reach_mat )
or i > nrow( reach_mat )
, in other words, your indices exceed the array boundary (i is greater than the number of rows, or alter is greater than the number of columns).
Just run the above tests to see what and when is happening.
If you are running IIS 8 with windows server 2012 you need to do the following:
from then on your application should start running
There is a blog post on MSDN about why an exponent operator does NOT exists from the C# team.
It would be possible to add a power operator to the language, but performing this operation is a fairly rare thing to do in most programs, and it doesn't seem justified to add an operator when calling Math.Pow() is simple.
You asked:
Do I have to write a loop or include another namespace to handle exponential operations? If so, how do I handle exponential operations using non-integers?
Math.Pow
supports double parameters so there is no need for you to write your own.
You can use online converter, developed by me at N'counter.
This is the easiest way to open SPSS file in Excel.
1) You just have to upload your file to SPSS coN'verter at https://secure.ncounter.de/SpssConverter
2) Select some options
3) And your converted Excel file will be downloaded
No information about your file contents is retained on our server. The file travels to our server, is converted in-memory, and is immediately discarded: We don't peer into your data at any time!
Although there are already few answers to this questions but I think some people still may have doubt in actually visualising the differece b/w throughput and bandwidth just like I had ;) until I read this analogy on quora(full credits to that) which proved really helpful
Consider
A highway which has a capacity of moving ,say, 200 vehicles at a time
but
at a random time someone notices only , say, 150 vehicles moving through it..
say due to some traffic-jam in between...
i.e.
capacity is 200 but not all the time it is fully utilised, actual traffic is only 150 out of a max of 200.
i.e. the bandwidth is 200 per unit time but still actual throughput is 150 ...
I thought it might help someone...
You can define a Multi-module project structure, then you can set the configuration for sonar in one properties file in the root folder of your project, (Way #1
)
Try this code:
<form id="myform">
<!-- form elements -->
<a href="#" onclick="document.getElementById('myform').submit()">Submit</a>
</form>
But users with disabled JavaScript won't be able to submit the form, so you could add the following code:
<noscript>
<input type="submit" value="Submit form!" />
</noscript>
You can simply pass more arguments to summarise
:
df %>% group_by(grp) %>% summarise(mean(a), mean(b), mean(c), mean(d))
Source: local data frame [3 x 5]
grp mean(a) mean(b) mean(c) mean(d)
1 1 2.500000 3.500000 2.000000 3.0
2 2 3.800000 3.200000 3.200000 2.8
3 3 3.666667 3.333333 2.333333 3.0
Assume time column is in timestamp integer msec format
1 day = 86400000 ms
Here you go:
day_divider = 86400000
df['time'] = df['time'].values.astype(dtype='datetime64[ms]') # for msec format
df['time'] = (df['time']/day_divider).values.astype(dtype='datetime64[D]') # for day format
It might be worth mentioning that you can also create a .dockerignore
file, to exclude the files that you don't want to copy:
https://docs.docker.com/engine/reference/builder/#dockerignore-file
Before the docker CLI sends the context to the docker daemon, it looks for a file named .dockerignore in the root directory of the context. If this file exists, the CLI modifies the context to exclude files and directories that match patterns in it. This helps to avoid unnecessarily sending large or sensitive files and directories to the daemon and potentially adding them to images using ADD or COPY.
classpath 'com.google.gms:google-services:4.1.0'
has a problem. instead use:
classpath 'com.google.gms:google-services:4.2.0'
as this example you can change ip and port this works with me
php artisan serve --host=0.0.0.0 --port=8000
I was able to list all untracked files reported by svn st
in bash by doing:
echo $(svn st | grep -P "^\?" | cut -c 9-)
If you are feeling lucky, you could replace echo
with rm
to delete untracked files. Or copy the files you want to delete by hand, if you are feeling a less lucky.
(I used @abe-voelker 's answer to revert the remaining files: https://stackoverflow.com/a/6204601/1695680)
From PEP 8 - Style Guide for Python Code:
The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately.
Example of implicit line continuation:
a = some_function(
'1' + '2' + '3' - '4')
On the topic of line-breaks around a binary operator, it goes on to say:-
For decades the recommended style was to break after binary operators. But this can hurt readability in two ways: the operators tend to get scattered across different columns on the screen, and each operator is moved away from its operand and onto the previous line.
In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth's style (line breaks before the operator) is suggested.
Example of explicit line continuation:
a = '1' \
+ '2' \
+ '3' \
- '4'
An uninitialized Boolean
member (actually a reference to an object of type Boolean
) will have the default value of null
.
An uninitialized boolean
(primitive) member will have the default value of false
.
A simple approach is to output as html, which pandas does out of the box:
df.to_html('temp.html')
SELECT 'ALTER TABLE '||substr(c.table_name,1,35)||
' DISABLE CONSTRAINT '||constraint_name||' ;'
FROM user_constraints c, user_tables u
WHERE c.table_name = u.table_name;
This statement returns the commands which turn off all the constraints including primary key, foreign keys, and another constraints.
You can also use WKWebsiteDataStore to get similar behaviour to HTTPCookieStorage from UIWebView.
let dataStore = WKWebsiteDataStore.default()
let cookies = HTTPCookieStorage.shared.cookies ?? [HTTPCookie]()
cookies.forEach({
dataStore.httpCookieStore.setCookie($0, completionHandler: nil)
})
var values = [];
var count = 0;
$("#tblName").on("click", "tbody tr", function (event) {
$(this).find("td").each(function () {
values[count] = $(this).text();
count++;
});
});
Now values array contain all the cell values of that row can be used like values[0] first cell value of clicked row
Regarding to @crabcrusherclamcollector answer there is issue when using that approach in EF queries (System.NotSupportedException: The LINQ expression node type 'Invoke' is not supported in LINQ to Entities). I modified implementation to that:
public static class SystemTime
{
private static Func<DateTime> UtcNowFunc = () => DateTime.UtcNow;
public static void SetDateTime(DateTime dateTimeNow)
{
UtcNowFunc = () => dateTimeNow;
}
public static void ResetDateTime()
{
UtcNowFunc = () => DateTime.UtcNow;
}
public static DateTime UtcNow
{
get
{
DateTime now = UtcNowFunc.Invoke();
return now;
}
}
}
I'm not sure that I fully understand the question, but from the title of your question, I'm guessing that what you're looking for is pager.setCurrentItem( num )
. That allows you to programatically switch to another page within the ViewPager
.
I'd need to see a stack trace from logcat to be more specific if this is not the problem.
And in PostgreSQL:
SELECT pg_size_pretty(pg_relation_size('tablename'));
For anyone that wants to download jdk 8 without an oracle account: https://download.oracle.com/otn-pub/java/jdk/8u271-b09/61ae65e088624f5aaa0b1d2d801acb16/jdk-8u271-windows-x64.exe
copy and paste the link. Jdk 15 didn't work for me so i tried using jdk 8 and it worked.
Two ways.
i. You can put it in ApplicationController and add the filters in the controller
class ApplicationController < ActionController::Base def filter_method end end class FirstController < ApplicationController before_filter :filter_method end class SecondController < ApplicationController before_filter :filter_method end
But the problem here is that this method will be added to all the controllers since all of them extend from application controller
ii. Create a parent controller and define it there
class ParentController < ApplicationController def filter_method end end class FirstController < ParentController before_filter :filter_method end class SecondController < ParentController before_filter :filter_method end
I have named it as parent controller but you can come up with a name that fits your situation properly.
You can also define the filter method in a module and include it in the controllers where you need the filter
Try installing the 32 bit version of Java 6. This works for version Install4J 4.0.5. Should fire right up, or allow you to re-run the installer.
Any newer version or the 64-bit version of 6 will fail, complaining that the java.exe is damaged.
Perhaps you could use something like this:
import urllib2
def internet_on():
try:
urllib2.urlopen('http://216.58.192.142', timeout=1)
return True
except urllib2.URLError as err:
return False
Currently, 216.58.192.142 is one of the IP addresses for google.com. Change http://216.58.192.142
to whatever site can be expected to respond quickly.
This fixed IP will not map to google.com forever. So this code is not robust -- it will need constant maintenance to keep it working.
The reason why the code above uses a fixed IP address instead of fully qualified domain name (FQDN) is because a FQDN would require a DNS lookup. When the machine does not have a working internet connection, the DNS lookup itself may block the call to urllib_request.urlopen
for more than a second. Thanks to @rzetterberg for pointing this out.
If the fixed IP address above is not working, you can find a current IP address for google.com (on unix) by running
% dig google.com +trace
...
google.com. 300 IN A 216.58.192.142
Maybe not the most efficient way. But you could convert the list into a vector.
#include <list>
#include <vector>
list<Object> myList;
vector<Object> myVector(myList.begin(), myList.end());
Then access the vector using the [x] operator.
auto x = MyVector[0];
You could put that in a helper function:
#include <memory>
#include <vector>
#include <list>
template<class T>
shared_ptr<vector<T>>
ListToVector(list<T> List) {
shared_ptr<vector<T>> Vector {
new vector<string>(List.begin(), List.end()) }
return Vector;
}
Then use the helper funciton like this:
auto MyVector = ListToVector(Object);
auto x = MyVector[0];
To remove all cookies you could write:
foreach ($_COOKIE as $key => $value) {
unset($value);
setcookie($key, '', time() - 3600);
}
You could attempt to load the the https page in an iframe and route all ajax requests in/out of the frame via some bridge, it's a hackaround but it might work (not sure if it will impose the same access restrictions given the secure context). Otherwise a local http proxy to reroute requests (like any cross domain calls) would be the accepted solution.
Python 2.6 and 3 specifically say to avoid using PIPE for stdout and stderr.
The correct way is
import subprocess
# must create a file object to store the output. Here we are getting
# the ssid we are connected to
outfile = open('/tmp/ssid', 'w');
status = subprocess.Popen(["iwgetid"], bufsize=0, stdout=outfile)
outfile.close()
# now operate on the file
Just another alternative using sp_executesql (tested only in SQL 2016). As previous posts noticed, atomicity must be handled elsewhere.
CREATE FUNCTION [dbo].[fn_get_service_version_checksum2]
(
@ServiceId INT
)
RETURNS INT
AS
BEGIN
DECLARE @Checksum INT;
SELECT @Checksum = dbo.fn_get_service_version(@ServiceId);
DECLARE @LatestVersion INT = (SELECT MAX(ServiceVersion) FROM [ServiceVersion] WHERE ServiceId = @ServiceId);
-- Check whether the current version already exists and that it's the latest version.
IF EXISTS(SELECT TOP 1 1 FROM [ServiceVersion] WHERE ServiceId = @ServiceId AND [Checksum] = @Checksum AND ServiceVersion = @LatestVersion)
RETURN @LatestVersion;
-- Insert the new version to the table.
EXEC sp_executesql N'
INSERT INTO [ServiceVersion] (ServiceId, ServiceVersion, [Checksum], [Timestamp])
VALUES (@ServiceId, @LatestVersion + 1, @Checksum, GETUTCDATE());',
N'@ServiceId INT = NULL, @LatestVersion INT = NULL, @Checksum INT = NULL',
@ServiceId = @ServiceId,
@LatestVersion = @LatestVersion,
@Checksum = @Checksum
;
RETURN @LatestVersion + 1;
END;
I just did it like this, including the authentication method:
s3_client = boto3.client(
's3',
aws_access_key_id='access_key',
aws_secret_access_key='access_key_secret',
config=boto3.session.Config(signature_version='s3v4'),
region_name='region'
)
response = s3_client.list_objects(Bucket='bucket_name', Prefix=key)
if ('Contents' in response):
# Object / key exists!
return True
else:
# Object / key DOES NOT exist!
return False
Necromancing, just in case all the links go dark:
Add a group to your report
Also, be advised to set the sort order of the group expression here, so the tabs will be alphabetically sorted (or however you want it sorted).
Set the page break in the group properties
Now you need to set the PageName
of the Tablix Member (group), NOT the PageName
of the Tablix itselfs.
If you got the right object, if will say "Tablix Member" (Tablix-Element in German) in the title box of the properties grid. If it's the wrong object, it will say only "table/tablix" (without member) in the property grid's title box.
Note: If you get the tablix instead of the tablix member, it will put the same tab name in every tab, followed by a (tabNum)
! If that happens, you now know what the problem is.
Yes we can do it. First convert the tuple into an list, then delete the element in the list after that again convert back into tuple.
Demo:
my_tuple = (10, 20, 30, 40, 50)
# converting the tuple to the list
my_list = list(my_tuple)
print my_list # output: [10, 20, 30, 40, 50]
# Here i wanna delete second element "20"
my_list.pop(1) # output: [10, 30, 40, 50]
# As you aware that pop(1) indicates second position
# Here i wanna remove the element "50"
my_list.remove(50) # output: [10, 30, 40]
# again converting the my_list back to my_tuple
my_tuple = tuple(my_list)
print my_tuple # output: (10, 30, 40)
Thanks
Step #1: Wrap whatever it is you want centered on the screen in a full-screen RelativeLayout
.
Step #2: Give that child view (the one, which you want centered inside the RelativeLayout
) the android:layout_centerInParent="true"
attribute.
Another library-based option: use d3-time-format
:
const formatter = d3.timeFormat('%U');
const weekNum = formatter(new Date());
If your <td>
is not empty, one popular trick is to insert a non breaking space
in it, such that:
<td id="td1"> </td>
Then you will be able to use:
document.getElementById('td1').firstChild.data = 'New Value';
Otherwise, if you do not fancy adding the meaningless  
you can use the solution that Jonathan Fingland described in the other answer.
from datetime import datetime
from pyspark.sql.functions import col, udf
from pyspark.sql.types import DateType
# Creation of a dummy dataframe:
df1 = sqlContext.createDataFrame([("11/25/1991","11/24/1991","11/30/1991"),
("11/25/1391","11/24/1992","11/30/1992")], schema=['first', 'second', 'third'])
# Setting an user define function:
# This function converts the string cell into a date:
func = udf (lambda x: datetime.strptime(x, '%m/%d/%Y'), DateType())
df = df1.withColumn('test', func(col('first')))
df.show()
df.printSchema()
Here is the output:
+----------+----------+----------+----------+
| first| second| third| test|
+----------+----------+----------+----------+
|11/25/1991|11/24/1991|11/30/1991|1991-01-25|
|11/25/1391|11/24/1992|11/30/1992|1391-01-17|
+----------+----------+----------+----------+
root
|-- first: string (nullable = true)
|-- second: string (nullable = true)
|-- third: string (nullable = true)
|-- test: date (nullable = true)
You'll have to use an HttpServletRequestWrapper:
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
final HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(httpRequest) {
@Override
public String getHeader(String name) {
final String value = request.getParameter(name);
if (value != null) {
return value;
}
return super.getHeader(name);
}
};
chain.doFilter(wrapper, response);
}
Depending on what you want to do you may need to implement other methods of the wrapper like getHeaderNames
for instance. Just be aware that this is trusting the client and allowing them to manipulate any HTTP header. You may want to sandbox it and only allow certain header values to be modified this way.
If you're going to v-model
a computed, it needs a setter. Whatever you want it to do with the updated value (probably write it to the $store
, considering that's what your getter pulls it from) you do in the setter.
If writing it back to the store happens via form submission, you don't want to v-model
, you just want to set :value
.
If you want to have an intermediate state, where it's saved somewhere but doesn't overwrite the source in the $store
until form submission, you'll need to create such a data item.
You can use unescapeJava
from org.apache.commons.text.StringEscapeUtils
like below
str = "hello\r\njava\r\nbook";
StringEscapeUtils.unescapeJava(str);
Two different options to add item to an array without mutation
case ADD_ITEM :
return {
...state,
arr: [...state.arr, action.newItem]
}
OR
case ADD_ITEM :
return {
...state,
arr: state.arr.concat(action.newItem)
}
You aren't building your formula right.
Worksheets("EmployeeCosts").Range("B" & var1a).Formula = "=SUM(H5:H" & var1a & ")"
This does the same as the following lines do:
Dim myFormula As String
myFormula = "=SUM(H5:H"
myFormula = myFormula & var1a
myformula = myformula & ")"
which is what you are trying to do.
Also, you want to have the =
at the beginning of the formala.
I am heavily tempted to close this as a duplicate; this question appears to be answered in many different ways all over the site:
not sure if this is what you wanted but
var arr = ["A", "B", "C"];
var arrString = arr.join(", ");
This results in the following output:
A, B, C
While you should definitely avoid circular dependencies, you can defer imports in python.
for example:
import SomeModule
def someFunction(arg):
from some.dependency import DependentClass
this ( at least in some instances ) will circumvent the error.
I'm currently fighting with dropdowns and I'd like to share my experiences:
There are specific situations where <select>
can't be used and must be 'emulated' with dropdown.
For example if you want to create bootstrap input groups, like Buttons with dropdowns (see http://getbootstrap.com/components/#input-groups-buttons-dropdowns). Unfortunately <select>
is not supported in input groups, it will not be rendered properly.
Or does anybody solved this already? I would be very interested on the solution.
And to make it even more complicated, you can't use so simply $(this).text()
to catch what user selected in dropdown if you're using glypicons or font awesome icons as content for dropdown. For example:
<li id="someId"><a href="#0"><i class="fa fa-minus"></i></a></li>
Because in this case there is no text and if you will add some then it will be also displayed in dropdown element and this is unwanted.
I found two possible solutions:
1)
Use $(this).html()
to get content of the selected <li>
element and then to examine it, but you will get something like <a href="#0"><i class="fa fa-minus"></i></a>
so you need to play with this to extract what you need.
2)
Use $(this).text()
and hide the text in element in hidden span:
<li id="someId"><a href="#0"><i class="fa fa-minus"><span class="hidden">text</span></i></a></li>
.
For me this is simple and elegant solution, you can put any text you need, text will be hidden, and you don't need to do any transformations of $(this).html()
result like in option 1) to get what you need.
I hope it's clear and can help somebody :-)
It looks like you can say
Convert.ToInt64(value, 16)
to get the decimal from hexdecimal.
The other way around is:
otherVar.ToString("X");
I was in the same situation, wanting to .NET instead of a third party library. As another poster mentioned above, simply using the ZipPackage class (introduced in .NET 3.5) is not quite enough. There is an additional file that MUST be included in the archive in order for the ZipPackage to work. If this file is added, then the resulting ZIP package can be opened directly from Windows Explorer - no problem.
All you have to do is add the [Content_Types].xml file to the root of the archive with a "Default" node for every file extension you wish to include. Once added, I could browse the package from Windows Explorer or programmatically decompress and read its contents.
More information on the [Content_Types].xml file can be found here: http://msdn.microsoft.com/en-us/magazine/cc163372.aspx
Here is a sample of the [Content_Types].xml (must be named exactly) file:
<?xml version="1.0" encoding="utf-8" ?>
<Types xmlns=
"http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="xml" ContentType="text/xml" />
<Default Extension="htm" ContentType="text/html" />
<Default Extension="html" ContentType="text/html" />
<Default Extension="rels" ContentType=
"application/vnd.openxmlformats-package.relationships+xml" />
<Default Extension="jpg" ContentType="image/jpeg" />
<Default Extension="png" ContentType="image/png" />
<Default Extension="css" ContentType="text/css" />
</Types>
And the C# for creating a ZIP file:
var zipFilePath = "c:\\myfile.zip";
var tempFolderPath = "c:\\unzipped";
using (Package package = ZipPackage.Open(zipFilePath, FileMode.Open, FileAccess.Read))
{
foreach (PackagePart part in package.GetParts())
{
var target = Path.GetFullPath(Path.Combine(tempFolderPath, part.Uri.OriginalString.TrimStart('/')));
var targetDir = target.Remove(target.LastIndexOf('\\'));
if (!Directory.Exists(targetDir))
Directory.CreateDirectory(targetDir);
using (Stream source = part.GetStream(FileMode.Open, FileAccess.Read))
{
source.CopyTo(File.OpenWrite(target));
}
}
}
Note:
Use the enumerate()
function to generate the index along with the elements of the sequence you are looping over:
for index, w in enumerate(loopme):
print "CURRENT WORD IS", w, "AT CHARACTER", index
querySelector
and querySelectorAll
are a relatively new APIs, whereas getElementById
and getElementsByClassName
have been with us for a lot longer. That means that what you use will mostly depend on which browsers you need to support.
As for the :
, it has a special meaning so you have to escape it if you have to use it as a part of a ID/class name.
I just now searched for this as I'm in a similar situation, and instead of kill -9 698
I tried sudo kill 428
where 428 was the pid of the process I'm trying to kill. It worked cleanly for me, in the absence of the hyphen '-' character. I hope it helps!
From angular's documentation,
ng-init SHOULD NOT be used for any initialization. It should be used only for aliasing. https://docs.angularjs.org/api/ng/directive/ngInit
onload should be used if any expression needs to be evaluated after a partial view is loaded (by ng-include). https://docs.angularjs.org/api/ng/directive/ngInclude
The major difference between them is when used with ng-include.
<div ng-include="partialViewUrl" onload="myFunction()"></div>
In this case, myFunction is called everytime the partial view is loaded.
<div ng-include="partialViewUrl" ng-init="myFunction()"></div>
Whereas, in this case, myFunction is called only once when the parent view is loaded.
There is one more way to achieve it:-
Private Sub UserForm_Initialize()
Dim list As Object
Set list = UserForm1.Controls.Add("Forms.ListBox.1", "hello", True)
With list
.Top = 30
.Left = 30
.Width = 200
.Height = 340
.ColumnHeads = True
.ColumnCount = 2
.ColumnWidths = "100;100"
.MultiSelect = fmMultiSelectExtended
.RowSource = "Sheet1!C4:D25"
End With End Sub
Here, I am using the range C4:D25 as source of data for the columns. It will result in both the columns populated with values.
The properties are self explanatory. You can explore other options by drawing ListBox in UserForm and using "Properties Window (F4)" to play with the option values.
b2 -j%cores% toolset=%msvcver% address-model=64 architecture=x86 link=static threading=multi runtime-link=shared --build-type=minimal stage --stagedir=stage/x64
Properties ? Linker ? General ? Additional Library Directories $(BOOST)\stage\x64\lib
md-icons aren't in the bower release of angular-material yet. I've been using Polymer's icons, they'll probably be the same anyway.
bower install polymer/core-icons
I know this is a very old question but I didn't see anybody talking about the main difference between process.stdout.write
and console.log
and I just want to mention it.
As Mauvis Leford and TK-421 pointed out, the console.log
adds a line-break
character at the end of the line (\n
) but that's not all what it does.
The code has not changed since at least 0.10.X
version and now we have a a 5.X
version.
Here is the code:
Console.prototype.log = function() {
this._stdout.write(util.format.apply(this, arguments) + '\n');
};
As you can see, there is a part that says .apply(this, arguments)
and that makes a big difference on functionality. It is easier to explain that with examples:
process.stdout.write
has a very basic functionality, you can just write something in there, like this:
process.stdout.write("Hello World\n");
If you don't put the break line at the end you will get a weird character after your string, something like this:
process.stdout.write("Hello World"); //Hello World%
(I think that means something like "the end of the program", so you will see it only if you process.stdout.write
was used at the end of your file and you didn't add the break line)
On the other hand, console.log
can do more.
You can use it in the same way
console.log("Hello World"); //You don't need the break line here because it was already formated
and also that weird character did disappear
You can write more than one string
console.log("Hello", "World");
You can make associations
console.log("Hello %s", "World") //Useful when "World" is inside a variable
An that's it, that added functionality is given thanks to the util.format.apply
part (I could talk a lot about what exactly this does but you get my point, you can read more here).
I hope somebody find this information useful.
Tested on iTunes 12.5.3.17
1.Open the iTunes select the “Apps” section with in that select the “Library”
2.Now drag and drop the file AppName.ipa in this Library section (Before connecting your iOS device to your computer machine)
3.Now connect your iOS device to your computer machine, we are able to see our device in iTunes…
4.Select your device go to “Apps” section of your device and search your App in the list of apps with "Install" button infront of it.
5.Now hit the “Install” button and then press the “Done” button in bottom right corner, The “Install” button will turn in to “Will Install” one alert will be shown to you with two options “Don’t Apply”, “Apply”, hit on option “Apply”.
6.The “App installation” will start on your device with progress….
7.Finally the app will be installed on your iOS device and you will be able to use it…
package lecture3;
import java.util.Scanner;
public class divisibleBy2and5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter an integer number:");
Scanner input = new Scanner(System.in);
int x;
x = input.nextInt();
if (x % 2==0){
System.out.println("The integer number you entered is divisible by 2");
}
else{
System.out.println("The integer number you entered is not divisible by 2");
if(x % 5==0){
System.out.println("The integer number you entered is divisible by 5");
}
else{
System.out.println("The interger number you entered is not divisible by 5");
}
}
}
}
One BIG difference to note is .Equals() will throw an exception if first string is null, Whereas == will not.
string s = null;
string a = "a";
//Throws {"Object reference not set to an instance of an object."}
if (s.Equals(a))
Console.WriteLine("s is equal to a");
//no Exception
if(s==a)
Console.WriteLine("s is equal to a");
Bourne shell (sh
) compliant way:
SCRIPT_HOME=`dirname $0 | while read a; do cd $a && pwd && break; done`
Definitively, for any PHP project, you may want to use GuzzleHTTP for sending requests. Guzzle has very nice documentation you can check here. I just want to say that, you probably want to centralize the usage of the Client class of Guzzle in any component of your Laravel project (for example a trait) instead of being creating Client instances on several controllers and components of Laravel (as many articles and replies suggest).
I created a trait you can try to use, which allows you to send requests from any component of your Laravel project, just using it and calling to makeRequest
.
namespace App\Traits;
use GuzzleHttp\Client;
trait ConsumesExternalServices
{
/**
* Send a request to any service
* @return string
*/
public function makeRequest($method, $requestUrl, $queryParams = [], $formParams = [], $headers = [], $hasFile = false)
{
$client = new Client([
'base_uri' => $this->baseUri,
]);
$bodyType = 'form_params';
if ($hasFile) {
$bodyType = 'multipart';
$multipart = [];
foreach ($formParams as $name => $contents) {
$multipart[] = [
'name' => $name,
'contents' => $contents
];
}
}
$response = $client->request($method, $requestUrl, [
'query' => $queryParams,
$bodyType => $hasFile ? $multipart : $formParams,
'headers' => $headers,
]);
$response = $response->getBody()->getContents();
return $response;
}
}
Notice this trait can even handle files sending.
If you want more details about this trait and some other stuff to integrate this trait to Laravel, check this article. Additionally, if interested in this topic or need major assistance, you can take my course which guides you in the whole process.
I hope it helps all of you.
Best wishes :)
I can also verify the above solution except I had to change in
**..\server\<server profile>\conf\props\jmx-console-users.properties**
Doing it in code is is IMO wrong and even more so if you put it into the onCreate. Do it in the manifest and the "system" knows the orientation from the startup of the app. And this type of meta or top level "guidance" SHOULD be in the manifest. If you want to prove it to yourself set a break in the Activity's onCreate. If you do it in code there it will be called twice : it starts up in Portrait mode then is switched to Landscape. This does not happen if you do it in the manifest.
You can easily do this by css. HTML :
<form id="aform" name="aform" method="POST">
<input name="chkBox_1" type="checkbox" checked value="1" readonly />
<br/>
<input name="chkBox_2" type="checkbox" value="1" readonly />
<br/>
<input id="submitBttn" type="button" value="Submit">
</form>
CSS :
input[type="checkbox"][readonly] {
pointer-events: none;
}
This error message is displayed if the path you pass to Bitmap.Save()
is invalid (folder doesn't exist etc).
It might be worth looking at a tutorial: MDN Canvas Tutorial
You can get the width and height of a canvas element simply by accessing those properties of the element. For example:
var canvas = document.getElementById('mycanvas');
var width = canvas.width;
var height = canvas.height;
If the width and height attributes are not present in the canvas element, the default 300x150 size will be returned. To dynamically get the correct width and height use the following code:
const canvasW = canvas.getBoundingClientRect().width;
const canvasH = canvas.getBoundingClientRect().height;
Or using the shorter object destructuring syntax:
const { width, height } = canvas.getBoundingClientRect();
The context
is an object you get from the canvas to allow you to draw into it. You can think of the context
as the API to the canvas, that provides you with the commands that enable you to draw on the canvas element.
in case u wanna do the validation for "some elements" (not all element) on your form.You can use this method:
$('input[name="element-one"], input[name="element-two"], input[name="element-three"]').valid();
Hope it help everybody :)
EDITED
This needs bash 4.1 if you use
{fd}
orlocal -n
.The rest should work in bash 3.x I hope. I am not completely sure due to
printf %q
- this might be a bash 4 feature.
Your example can be modified as follows to archive the desired effect:
# Add following 4 lines:
_passback() { while [ 1 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; return $1; }
passback() { _passback "$@" "$?"; }
_capture() { { out="$("${@:2}" 3<&-; "$2_" >&3)"; ret=$?; printf "%q=%q;" "$1" "$out"; } 3>&1; echo "(exit $ret)"; }
capture() { eval "$(_capture "$@")"; }
e=2
# Add following line, called "Annotation"
function test1_() { passback e; }
function test1() {
e=4
echo "hello"
}
# Change following line to:
capture ret test1
echo "$ret"
echo "$e"
prints as desired:
hello
4
Note that this solution:
e=1000
, too.$?
if you need $?
The only bad sideffects are:
bash
._
)_capture
just replace all occurances of 3
with another (higher) number.The following (which is quite long, sorry for that) hopefully explains, how to adpot this recipe to other scripts, too.
d() { let x++; date +%Y%m%d-%H%M%S; }
x=0
d1=$(d)
d2=$(d)
d3=$(d)
d4=$(d)
echo $x $d1 $d2 $d3 $d4
outputs
0 20171129-123521 20171129-123521 20171129-123521 20171129-123521
while the wanted output is
4 20171129-123521 20171129-123521 20171129-123521 20171129-123521
Shell variables (or generally speaking, the environment) is passed from parental processes to child processes, but not vice versa.
If you do output capturing, this usually is run in a subshell, so passing back variables is difficult.
Some even tell you, that it is impossible to fix. This is wrong, but it is a long known difficult to solve problem.
There are several ways on how to solve it best, this depends on your needs.
Here is a step by step guide on how to do it.
There is a way to pass back variables to a parental shell. However this is a dangerous path, because this uses eval
. If done improperly, you risk many evil things. But if done properly, this is perfectly safe, provided that there is no bug in bash
.
_passback() { while [ 0 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; }
d() { let x++; d=$(date +%Y%m%d-%H%M%S); _passback x d; }
x=0
eval `d`
d1=$d
eval `d`
d2=$d
eval `d`
d3=$d
eval `d`
d4=$d
echo $x $d1 $d2 $d3 $d4
prints
4 20171129-124945 20171129-124945 20171129-124945 20171129-124945
Note that this works for dangerous things, too:
danger() { danger="$*"; passback danger; }
eval `danger '; /bin/echo *'`
echo "$danger"
prints
; /bin/echo *
This is due to printf '%q'
, which quotes everything such, that you can re-use it in a shell context safely.
This does not only look ugly, it also is much to type, so it is error prone. Just one single mistake and you are doomed, right?
Well, we are at shell level, so you can improve it. Just think about an interface you want to see, and then you can implement it.
Let's go a step back and think about some API which allows us to easily express, what we want to do.
Well, what do we want do do with the d()
function?
We want to capture the output into a variable. OK, then let's implement an API for exactly this:
# This needs a modern bash 4.3 (see "help declare" if "-n" is present,
# we get rid of it below anyway).
: capture VARIABLE command args..
capture()
{
local -n output="$1"
shift
output="$("$@")"
}
Now, instead of writing
d1=$(d)
we can write
capture d1 d
Well, this looks like we haven't changed much, as, again, the variables are not passed back from d
into the parent shell, and we need to type a bit more.
However now we can throw the full power of the shell at it, as it is nicely wrapped in a function.
A second thing is, that we want to be DRY (Don't Repeat Yourself). So we definitively do not want to type something like
x=0
capture1 x d1 d
capture1 x d2 d
capture1 x d3 d
capture1 x d4 d
echo $x $d1 $d2 $d3 $d4
The x
here is not only redundant, it's error prone to always repeate in the correct context. What if you use it 1000 times in a script and then add a variable? You definitively do not want to alter all the 1000 locations where a call to d
is involved.
So leave the x
away, so we can write:
_passback() { while [ 0 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; }
d() { let x++; output=$(date +%Y%m%d-%H%M%S); _passback output x; }
xcapture() { local -n output="$1"; eval "$("${@:2}")"; }
x=0
xcapture d1 d
xcapture d2 d
xcapture d3 d
xcapture d4 d
echo $x $d1 $d2 $d3 $d4
outputs
4 20171129-132414 20171129-132414 20171129-132414 20171129-132414
This already looks very good. (But there still is the local -n
which does not work in oder common bash
3.x)
d()
The last solution has some big flaws:
d()
needs to be alteredxcapture
to pass the output.
output
,
so we can never pass this one back._passback
Can we get rid of this, too?
Of course, we can! We are in a shell, so there is everything we need to get this done.
If you look a bit closer to the call to eval
you can see, that we have 100% control at this location. "Inside" the eval
we are in a subshell,
so we can do everything we want without fear of doing something bad to the parental shell.
Yeah, nice, so let's add another wrapper, now directly inside the eval
:
_passback() { while [ 0 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; }
# !DO NOT USE!
_xcapture() { "${@:2}" > >(printf "%q=%q;" "$1" "$(cat)"); _passback x; } # !DO NOT USE!
# !DO NOT USE!
xcapture() { eval "$(_xcapture "$@")"; }
d() { let x++; date +%Y%m%d-%H%M%S; }
x=0
xcapture d1 d
xcapture d2 d
xcapture d3 d
xcapture d4 d
echo $x $d1 $d2 $d3 $d4
prints
4 20171129-132414 20171129-132414 20171129-132414 20171129-132414
However, this, again, has some major drawback:
!DO NOT USE!
markers are there,
because there is a very bad race condition in this,
which you cannot see easily:
>(printf ..)
is a background job. So it might still
execute while the _passback x
is running.sleep 1;
before printf
or _passback
.
_xcapture a d; echo
then outputs x
or a
first, respectively._passback x
should not be part of _xcapture
,
because this makes it difficult to reuse that recipe.$(cat)
),
but as this solution is !DO NOT USE!
I took the shortest route.However, this shows, that we can do it, without modification to d()
(and without local -n
)!
Please note that we not neccessarily need _xcapture
at all,
as we could have written everyting right in the eval
.
However doing this usually isn't very readable. And if you come back to your script in a few years, you probably want to be able to read it again without much trouble.
Now let's fix the race condition.
The trick could be to wait until printf
has closed it's STDOUT, and then output x
.
There are many ways to archive this:
Following the last path could look like (note that it does the printf
last because this works better here):
_passback() { while [ 0 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; }
_xcapture() { { printf "%q=%q;" "$1" "$("${@:2}" 3<&-; _passback x >&3)"; } 3>&1; }
xcapture() { eval "$(_xcapture "$@")"; }
d() { let x++; date +%Y%m%d-%H%M%S; }
x=0
xcapture d1 d
xcapture d2 d
xcapture d3 d
xcapture d4 d
echo $x $d1 $d2 $d3 $d4
outputs
4 20171129-144845 20171129-144845 20171129-144845 20171129-144845
Why is this correct?
_passback x
directly talks to STDOUT.>&3
.$("${@:2}" 3<&-; _passback x >&3)
finishes after the _passback
,
when the subshell closes STDOUT.printf
cannot happen before the _passback
,
regardless how long _passback
takes.printf
command is not executed before the complete
commandline is assembled, so we cannot see artefacts from printf
,
independently how printf
is implemented.Hence first _passback
executes, then the printf
.
This resolves the race, sacrificing one fixed file descriptor 3. You can, of course, choose another file descriptor in the case, that FD3 is not free in your shellscript.
Please also note the 3<&-
which protects FD3 to be passed to the function.
_capture
contains parts, which belong to d()
, which is bad,
from a reusability perspective. How to solve this?
Well, do it the desparate way by introducing one more thing,
an additional function, which must return the right things,
which is named after the original function with _
attached.
This function is called after the real function, and can augment things. This way, this can be read as some annotation, so it is very readable:
_passback() { while [ 0 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; }
_capture() { { printf "%q=%q;" "$1" "$("${@:2}" 3<&-; "$2_" >&3)"; } 3>&1; }
capture() { eval "$(_capture "$@")"; }
d_() { _passback x; }
d() { let x++; date +%Y%m%d-%H%M%S; }
x=0
capture d1 d
capture d2 d
capture d3 d
capture d4 d
echo $x $d1 $d2 $d3 $d4
still prints
4 20171129-151954 20171129-151954 20171129-151954 20171129-151954
There is only on bit missing:
v=$(fn)
sets $?
to what fn
returned. So you probably want this, too.
It needs some bigger tweaking, though:
# This is all the interface you need.
# Remember, that this burns FD=3!
_passback() { while [ 1 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; return $1; }
passback() { _passback "$@" "$?"; }
_capture() { { out="$("${@:2}" 3<&-; "$2_" >&3)"; ret=$?; printf "%q=%q;" "$1" "$out"; } 3>&1; echo "(exit $ret)"; }
capture() { eval "$(_capture "$@")"; }
# Here is your function, annotated with which sideffects it has.
fails_() { passback x y; }
fails() { x=$1; y=69; echo FAIL; return 23; }
# And now the code which uses it all
x=0
y=0
capture wtf fails 42
echo $? $x $y $wtf
prints
23 42 69 FAIL
_passback()
can be elmininated with passback() { set -- "$@" "$?"; while [ 1 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; return $1; }
_capture()
can be eliminated with capture() { eval "$({ out="$("${@:2}" 3<&-; "$2_" >&3)"; ret=$?; printf "%q=%q;" "$1" "$out"; } 3>&1; echo "(exit $ret)")"; }
The solution pollutes a file descriptor (here 3) by using it internally.
You need to keep that in mind if you happen to pass FDs.
Note thatbash
4.1 and above has {fd}
to use some unused FD.
(Perhaps I will add a solution here when I come around.)
Note that this is why I use to put it in separate functions like _capture
, because stuffing this all into one line is possible, but makes it increasingly harder to read and understand
Perhaps you want to capture STDERR of the called function, too.
Or you want to even pass in and out more than one filedescriptor
from and to variables.
I have no solution yet, however here is a way to catch more than one FD, so we can probably pass back the variables this way, too.
Also do not forget:
This must call a shell function, not an external command.
There is no easy way to pass environment variables out of external commands. (With
LD_PRELOAD=
it should be possible, though!) But this then is something completely different.
This is not the only possible solution. It is one example to a solution.
As always you have many ways to express things in the shell. So feel free to improve and find something better.
The solution presented here is quite far from being perfect:
bash
, so probably is hard to port to other shells.However I think it is quite easy to use:
This error indicates that the two tables have the 1 or more column names that have the same column name. The error message translates to: "I can see the same column in both tables but you haven't told me to rename either before bringing one of them in"
You either want to delete one of the columns before bringing it in from the other on using del df['column name'], or use lsuffix to re-write the original column, or rsuffix to rename the one that is being brought it.
df_a.join(df_b, on='mukey', how='left', lsuffix='_left', rsuffix='_right')
Depending on your development environment you may not even have the choice what encoding your string data type will use internally.
But for storing and exchanging data I would always use UTF-8, if you have the choice. If you have mostly ASCII data this will give you the smallest amount of data to transfer, while still being able to encode everything. Optimizing for the least I/O is the way to go on modern machines.
mysqld --help --verbose will find only location of default configuration file. What if you use 2 MySQL instances on the same server? It's not going to help.
Good article about figuring it out:
Look at the user and host column of your permission. Where you are coming from localhost or some other IPs do make a difference.
There are 3 location providers in Android.
They are:
gps –> (GPS, AGPS): Name of the GPS location provider. This provider determines location using satellites. Depending on conditions, this provider may take a while to return a location fix. Requires the permission android.permission.ACCESS_FINE_LOCATION.
network –> (AGPS, CellID, WiFi MACID): Name of the network location provider. This provider determines location based on availability of cell tower and WiFi access points. Results are retrieved by means of a network lookup. Requires either of the permissions android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION.
passive –> (CellID, WiFi MACID): A special location provider for receiving locations without actually initiating a location fix. This provider can be used to passively receive location updates when other applications or services request them without actually requesting the locations yourself. This provider will return locations generated by other providers. Requires the permission android.permission.ACCESS_FINE_LOCATION, although if the GPS is not enabled this provider might only return coarse fixes. This is what Android calls these location providers, however, the underlying technologies to make this stuff work is mapped to the specific set of hardware and telco provided capabilities (network service).
The best way is to use the “network” or “passive” provider first, and then fallback on “gps”, and depending on the task, switch between providers. This covers all cases, and provides a lowest common denominator service (in the worst case) and great service (in the best case).
Article Reference : Android Location Providers - gps, network, passive By Nazmul Idris
Code Reference : https://stackoverflow.com/a/3145655/28557
-----------------------Update-----------------------
Now Android have Fused location provider
The Fused Location Provider intelligently manages the underlying location technology and gives you the best location according to your needs. It simplifies ways for apps to get the user’s current location with improved accuracy and lower power usage
Fused location provider provide three ways to fetch location
References :
Official site : http://developer.android.com/google/play-services/location.html
Fused location provider example: GIT : https://github.com/kpbird/fused-location-provider-example
http://blog.lemberg.co.uk/fused-location-provider
--------------------------------------------------------
Here is a updated version of the code provided by @theprtk. It is a cleaned up a little to show the generalized version whilst having an example.
Note: I'd add this as a comment to his post but I don't have enough reputation yet
/**
* @see http://clojure.com/blog/2012/05/15/anatomy-of-reducer.html
* @description functions that transform reducing functions
*/
const transduce = {
/** a generic map() that can take a reducing() & return another reducing() */
map: changeInput => reducing => (acc, input) =>
reducing(acc, changeInput(input)),
/** a generic filter() that can take a reducing() & return */
filter: predicate => reducing => (acc, input) =>
predicate(input) ? reducing(acc, input) : acc,
/**
* a composing() that can take an infinite # transducers to operate on
* reducing functions to compose a computed accumulator without ever creating
* that intermediate array
*/
compose: (...args) => x => {
const fns = args;
var i = fns.length;
while (i--) x = fns[i].call(this, x);
return x;
},
};
const example = {
data: [{ src: 'file.html' }, { src: 'file.txt' }, { src: 'file.json' }],
/** note: `[1,2,3].reduce(concat, [])` -> `[1,2,3]` */
concat: (acc, input) => acc.concat([input]),
getSrc: x => x.src,
filterJson: x => x.src.split('.').pop() !== 'json',
};
/** step 1: create a reducing() that can be passed into `reduce` */
const reduceFn = example.concat;
/** step 2: transforming your reducing function by mapping */
const mapFn = transduce.map(example.getSrc);
/** step 3: create your filter() that operates on an input */
const filterFn = transduce.filter(example.filterJson);
/** step 4: aggregate your transformations */
const composeFn = transduce.compose(
filterFn,
mapFn,
transduce.map(x => x.toUpperCase() + '!'), // new mapping()
);
/**
* Expected example output
* Note: each is wrapped in `example.data.reduce(x, [])`
* 1: ['file.html', 'file.txt', 'file.json']
* 2: ['file.html', 'file.txt']
* 3: ['FILE.HTML!', 'FILE.TXT!']
*/
const exampleFns = {
transducers: [
mapFn(reduceFn),
filterFn(mapFn(reduceFn)),
composeFn(reduceFn),
],
raw: [
(acc, x) => acc.concat([x.src]),
(acc, x) => acc.concat(x.src.split('.').pop() !== 'json' ? [x.src] : []),
(acc, x) => acc.concat(x.src.split('.').pop() !== 'json' ? [x.src.toUpperCase() + '!'] : []),
],
};
const execExample = (currentValue, index) =>
console.log('Example ' + index, example.data.reduce(currentValue, []));
exampleFns.raw.forEach(execExample);
exampleFns.transducers.forEach(execExample);
Don't forget to weakify self if you are using self inside of the closure.
dispatch_async(dispatch_get_main_queue(),{ [weak self] () -> () in
if let strongSelf = self {
self?.doSomething()
}
})
You can search "slashdot effect analysis" for graphs of what you would see if some aspect of the site suddenly became popular in the news, e.g. this graph on wiki.
Web-applications that survive tend to be the ones which can generate static pages instead of putting every request through a processing language.
There was an excellent video (I think it might have been on ted.com? I think it might have been by flickr web team? Does someone know the link?) with ideas on how to scale websites beyond the single server, e.g. how to allocate connections amongst the mix of read-only and read-write servers to get best effect for various types of users.
No need to use .each
. click
already binds to all div
occurrences.
$('div').click(function(e) {
..
});
Note: use hard binding such as .click
to make sure dynamically loaded elements don't get bound.
Adding onKeyPress will work onChange in Text Field.
<TextField
onKeyPress={(ev) => {
console.log(`Pressed keyCode ${ev.key}`);
if (ev.key === 'Enter') {
// Do code here
ev.preventDefault();
}
}}
/>
The :query_string_normalizer
option is also available, which will override the default normalizer HashConversions.to_params(query)
query_string_normalizer: ->(query){query.to_json}
<link rel="icon" type="image/x-icon" href="http://example.com/favicon.ico" /> <link rel="icon" type="image/png" href="http://example.com/favicon.png" /> <link rel="icon" type="image/gif" href="http://example.com/favicon.gif" /> <link rel="icon" type="image/jpeg" href="http://example.com/favicon.jpeg" /> <link rel="icon" type="image/webp" href="http://example.com/favicon.webp" />
It all depends on which format of image you like to use!
if you have an icon of your website, it will be much better for UX!
show logo in the browser tab
I found this question as I was researching an error after I upgraded from 1.7.2 of jQuery to 1.8.2. I'm adding my answer because there has been a change in jQuery 1.8 and higher that changes how this question is answered now.
With jQuery 1.8 they have deprecated the pseudo-selectors like :radio, :checkbox, :text.
To do the above now just replace the :radio
with [type=radio]
.
So your answer now becomes for all versions of jQuery 1.8 and above:
$("input[type=radio][name=theme]").click(function() {
var value = $(this).val();
});
You can read about the change on the 1.8 readme and the ticket specific for this change as well as a understand why on the :radio selector page under the Additional Information section.
nil is an empty value bound/corresponding with an object (the id type in Objective-C). nil got no reference/address, just an empty value.
NSString *str = nil;
So nil should be used, if we are dealing with an object.
if(str==nil)
NSLog("str is empty");
Now NULL is used for non-object pointer (like a C pointer) in Objective-C. Like nil , NULL got no value nor address.
char *myChar = NULL;
struct MyStruct *dStruct = NULL;
So if there is a situation, when I need to check my struct (structure type variable) is empty or not then, I will use:
if (dStruct == NULL)
NSLog("The struct is empty");
Let’s have another example, the
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
Of key-value observing, the context should be a C pointer or an object reference. Here for the context we can not use nil; we have to use NULL.
Finally the NSNull class defines a singleton object used to represent null values in collection objects(NSArray, NSDictionary). The [NSNull null] will returns the singleton instance of NSNull. Basically [NSNull null] is a proper object.
There is no way to insert a nil object into a collection type object. Let's have an example:
NSMutableArray *check = [[NSMutableArray alloc] init];
[check addObject:[NSNull null]];
[check addObject:nil];
On the second line, we will not get any error, because it is perfectly fair to insert a NSNull object into a collection type object. On the third line, we will get "object cannot be nil" error. Because nil is not an object.
OK, imagine you have this object below and you want to clone it:
let obj = {a:1, b:2, c:3}; //ES6
or
var obj = {a:1, b:2, c:3}; //ES5
the answer is mainly depeneds on which ECMAscript you using, in ES6+
, you can simply use Object.assign
to do the clone:
let cloned = Object.assign({}, obj); //new {a:1, b:2, c:3};
or using spread operator like this:
let cloned = {...obj}; //new {a:1, b:2, c:3};
But if you using ES5
, you can use few methods, but the JSON.stringify
, just make sure you not using for a big chunk of data to copy, but it could be one line handy way in many cases, something like this:
let cloned = JSON.parse(JSON.stringify(obj));
//new {a:1, b:2, c:3};, can be handy, but avoid using on big chunk of data over and over
It's simple enough with the powerful urllib3
library.
Import it like this:
import urllib3
http = urllib3.PoolManager()
And make a request like this:
response = http.request('GET', 'https://example.com')
print(response.data) # Raw data.
print(response.data.decode('utf-8')) # Text.
print(response.status) # Status code.
print(response.headers['Content-Type']) # Content type.
You can add headers too:
response = http.request('GET', 'https://example.com', headers={
'key1': 'value1',
'key2': 'value2'
})
More info can be found on the urllib3 documentation.
urllib3
is much safer and easier to use than the builtin urllib.request
or http
modules and is stable.
This answer is a workaround for those who use "Theme.AppCompat.Dialog" or any other "Theme.AppCompat.Dialog" descendants like "Theme.AppCompat.Light.Dialog", "Theme.AppCompat.DayNight.Dialog", etc. I myself has to use AppCompat dialog because i use AppCompatActivity as extends for all my activities. There will be a problem that make the dialog has padding on every sides(top, right, bottom and left) if we use the accepted answer.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}
On your Activity's style, add these code
<style name="DialogActivityTheme" parent="Theme.AppCompat.Dialog">
<item name="windowNoTitle">true</item>
<item name="android:windowBackground">@null</item>
</style>
As you may notice, the problem that generate padding to our dialog is "android:windowBackground", so here i make the window background to null.
Sure. I suppose that you have already installed TensorFlow for GPU.
You need to add the following block after importing keras. I am working on a machine which have 56 core cpu, and a gpu.
import keras
import tensorflow as tf
config = tf.ConfigProto( device_count = {'GPU': 1 , 'CPU': 56} )
sess = tf.Session(config=config)
keras.backend.set_session(sess)
Of course, this usage enforces my machines maximum limits. You can decrease cpu and gpu consumption values.
Assuming there is nothing else alongside the image, the best way is to use text-align: center
in the img
parent:
.row .span4 {
text-align: center;
}
Edit
As mentioned in the other answers, you can add the bootstrap CSS class .text-center
to the parent element. This does exactly the same thing and is available in both v2.3.3 and v3
Also if you want selected field from table and aggregated then as array .
SELECT json_agg(json_build_object('data_a',a,
'data_b',b,
)) from t;
The result will come .
[{'data_a':1,'data_b':'value1'}
{'data_a':2,'data_b':'value2'}]
If you have this problem in Windows 10, and you know you have premisions on folder (You could write before but it just started to print exception PermissionError recently).. You will need to install Windows updates... I hope someone will help this info.
datediff(to_date(String timestamp), to_date(String timestamp))
For example:
SELECT datediff(to_date('2019-08-03'), to_date('2019-08-01')) <= 2;
You can also use the provided CLI tool mysqlcheck
to run the optimizations. It's got a ton of switches but at its most basic you just pass in the database, username, and password.
Adding this to cron or the Windows Scheduler can make this an automated process. (MariaDB but basically the same thing.)
Many good answers here, but I use a simple one using Exists, as below:
foreach (var setting in FullList)
{
if(cleanList.Exists(x => x.ProcedureName == setting.ProcedureName))
setting.IsActive = true; // do you business logic here
else
setting.IsActive = false;
updateList.Add(setting);
}
For UTF-8 textual information, you should use utf8_general_ci
because...
utf8_bin
: compare strings by the
binary value of each character in
the string
utf8_general_ci
: compare strings
using general language rules and
using case-insensitive comparisons
a.k.a. it will should making searching and indexing the data faster/more efficient/more useful.
I had to enable it in my BIOS as shown below (for Asus):
In case that needed here is how we solved insert of array
request is from postman (You will look at "guests" )
{
"author_id" : 3,
"name" : "World War II",
"date" : "01 09 1939",
"time" : "16 : 22",
"location" : "39.9333635/32.8597419",
"guests" : [2, 3, 1337, 1942, 1453]
}
And how we scripted
var express = require('express');
var utils = require('./custom_utils.js');
module.exports = function(database){
var router = express.Router();
router.post('/', function(req, res, next) {
database.query('INSERT INTO activity (author_id, name, date, time, location) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE name = VALUES(name), date = VALUES(date), time = VALUES(time), location = VALUES(location)',
[req.body.author_id, req.body.name, req.body.date, req.body.time, req.body.location], function(err, results, fields){
if(err){
console.log(err);
res.json({ status: utils.respondMSG.DB_ERROR });
}
else {
var act_id = results.insertId;
database.query('INSERT INTO act_guest (user_id, activity_id, status) VALUES ? ON DUPLICATE KEY UPDATE status = VALUES(status)',
[Array.from(req.body.guests).map(function(g){ return [g, act_id, 0]; })], function(err, results, fields){
if(err){
console.log(err);
res.json({ status: utils.respondMSG.DB_ERROR });
}
else {
res.json({
status: utils.respondMSG.SUCCEED,
data: {
activity_id : act_id
}
});
}
});
}
});
});
return router;
};
The easiest way to do this is to use jQuery : jQuery UI combobox/autocomplete
You can use dijkstra's algorithm with negative edges not including negative cycle, but you must allow a vertex can be visited multiple times and that version will lose it's fast time complexity.
In that case practically I've seen it's better to use SPFA algorithm which have normal queue and can handle negative edges.
Android path set in linux:
$export ANDROID_HOME=/usr/lib/android-sdk-linux
$export PATH=$PATH:$ANDROID_HOME/tools
$export PATH=$PATH:$ANDROID_HOME/platforms-tools
than
$cordova run android
The best way to do this is probably to use a third party library.
There's an implementation of what you're looking for in jQuery UI jQuery UI and in dojo dojo. jQuery is more popular, but dojo allows you to declaratively define widgets in HTML, which sounds more like what you're looking for.
Which one you use will depend on your style, but both are developed for cross browser work, and both will be updated more often than copy and paste code.
This might sound crazy to a lot of developers who like to take advantage of database functions,
But after exhaustive problems thinking, creating and bugfixing applications for mysql and postgrsql with php comparing date functions, I've come to the conclusion (for myself), that the easiest way, that is the simplest with less SQL headaches is not to take advantage of any of them.
Why? because if you are developing in a middleware language like PHP, PHP has all of these functions, and they are easier to implement in the application ode as comparing integers. PostgreSQL timestamp is NOT == UNIX TIMESTAMP and MySQL's UNIX TIMESTAMP is NOT PostgresQL's or Oracles timestamp.. it gets harder to port if you use database timestamps..
so just use an integer, not a timestamp, as the number of seconds since january 1st 1970 midnight. and never mind database timestamps. , and use gmdate() and store everything as gmt time to avoid timezone issues.
if you need to search, sort or compare the day from other data, or the month or the year or the day of the week, or anything, in your application, and INTEGER datatype for time_day, time_hour, time_seconds.. or whatever you wnat to index to be searched will make for smoother and more portable databases. you can just use one field, in most instances: INTEGER time_created NOT NULL
(more fields in your database row is the only drawback to this solution that i have found, and that doesnt cause as many headaches, or cups of coffee :)
php's date functions are outstanding to compare dates, but in mysql or postgresql, comparing dates ? nah.. use integer sql comparisons
i realize it may SEEM easier to use CURRENT_TIMESTAMP on an insert function. HA! don't be fooled.
You cant do DELETE FROM SESSION_TABLE WHERE time-initialized < '2 days'
if time-intitialized is a postgresql timestamp.
but you CAN do:
DELETE FROM SESSION_TABLE WHERE time_initialized < '$yesterday'
As long as you set $yesterday in php as the integer of seconds since 1970 that yesterday was.
This is easier housekeeping of session records than comparing timestamps in postgresql select statements.
SELECT age(), SELECT extract(), and asbtime are headaches in an of themselves. this is just my opinion.
you can do addition, substraction, <, >, all with php date objects
_peter_sysko U4EA Networks, Inc.
If your query consists only of the $where
operator, you can pass in just the JavaScript expression:
db.T.find("this.Grade1 > this.Grade2");
For greater performance, run an aggregate operation that has a $redact
pipeline to filter the documents which satisfy the given condition.
The $redact
pipeline incorporates the functionality of $project
and $match
to implement field level redaction where it will return all documents matching the condition using $$KEEP
and removes from the pipeline results those that don't match using the $$PRUNE
variable.
Running the following aggregate operation filter the documents more efficiently than using $where
for large collections as this uses a single pipeline and native MongoDB operators, rather than JavaScript evaluations with $where
, which can slow down the query:
db.T.aggregate([
{
"$redact": {
"$cond": [
{ "$gt": [ "$Grade1", "$Grade2" ] },
"$$KEEP",
"$$PRUNE"
]
}
}
])
which is a more simplified version of incorporating the two pipelines $project
and $match
:
db.T.aggregate([
{
"$project": {
"isGrade1Greater": { "$cmp": [ "$Grade1", "$Grade2" ] },
"Grade1": 1,
"Grade2": 1,
"OtherFields": 1,
...
}
},
{ "$match": { "isGrade1Greater": 1 } }
])
With MongoDB 3.4 and newer:
db.T.aggregate([
{
"$addFields": {
"isGrade1Greater": { "$cmp": [ "$Grade1", "$Grade2" ] }
}
},
{ "$match": { "isGrade1Greater": 1 } }
])
I would try to specify something like
var searchPattern = "as?x";
it should work.
[Speed consideration]
Lot of ppl here suggests ResultSet.last()
but for that you would need to open connection as a ResultSet.TYPE_SCROLL_INSENSITIVE
which for Derby embedded database is up to 10 times SLOWER than ResultSet.TYPE_FORWARD_ONLY
.
According to my micro-tests for embedded Derby and H2 databases it is significantly faster to call SELECT COUNT(*)
before your SELECT.
I have had this happen in my organization after all our users were bound to active directory (effectively changing the UID from 50x to ######).
Now it is simply a case of changing the ownership of all files where were owned by x to y.
Where 501 is my old numeric user id which is still associated with all the homebrew files.
The old user id can be found using ll /usr/local/Cellar
Now update the ownership
sudo find /usr/local -user 501 -exec chown -h $USER {} \;
This way we avoid changing the ownership on files which are not controlled by homebrew or belong to some other system user.
If the new branch contains edits that are different from the current branch for that particular changed file, then it will not allow you to switch branches until the change is committed or stashed. If the changed file is the same on both branches (that is, the committed version of that file), then you can switch freely.
Example:
$ echo 'hello world' > file.txt
$ git add file.txt
$ git commit -m "adding file.txt"
$ git checkout -b experiment
$ echo 'goodbye world' >> file.txt
$ git add file.txt
$ git commit -m "added text"
# experiment now contains changes that master doesn't have
# any future changes to this file will keep you from changing branches
# until the changes are stashed or committed
$ echo "and we're back" >> file.txt # making additional changes
$ git checkout master
error: Your local changes to the following files would be overwritten by checkout:
file.txt
Please, commit your changes or stash them before you can switch branches.
Aborting
This goes for untracked files as well as tracked files. Here's an example for an untracked file.
Example:
$ git checkout -b experimental # creates new branch 'experimental'
$ echo 'hello world' > file.txt
$ git add file.txt
$ git commit -m "added file.txt"
$ git checkout master # master does not have file.txt
$ echo 'goodbye world' > file.txt
$ git checkout experimental
error: The following untracked working tree files would be overwritten by checkout:
file.txt
Please move or remove them before you can switch branches.
Aborting
A good example of why you WOULD want to move between branches while making changes would be if you were performing some experiments on master, wanted to commit them, but not to master just yet...
$ echo 'experimental change' >> file.txt # change to existing tracked file
# I want to save these, but not on master
$ git checkout -b experiment
M file.txt
Switched to branch 'experiment'
$ git add file.txt
$ git commit -m "possible modification for file.txt"
If you want to load/process/display images I suggest you use an image processing framework. Using Marvin, for instance, you can do that easily with just a few lines of source code.
Source code:
public class Example extends JFrame{
MarvinImagePlugin prewitt = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.edge.prewitt");
MarvinImagePlugin errorDiffusion = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.halftone.errorDiffusion");
MarvinImagePlugin emboss = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.color.emboss");
public Example(){
super("Example");
// Layout
setLayout(new GridLayout(2,2));
// Load images
MarvinImage img1 = MarvinImageIO.loadImage("./res/car.jpg");
MarvinImage img2 = new MarvinImage(img1.getWidth(), img1.getHeight());
MarvinImage img3 = new MarvinImage(img1.getWidth(), img1.getHeight());
MarvinImage img4 = new MarvinImage(img1.getWidth(), img1.getHeight());
// Image Processing plug-ins
errorDiffusion.process(img1, img2);
prewitt.process(img1, img3);
emboss.process(img1, img4);
// Set panels
addPanel(img1);
addPanel(img2);
addPanel(img3);
addPanel(img4);
setSize(560,380);
setVisible(true);
}
public void addPanel(MarvinImage image){
MarvinImagePanel imagePanel = new MarvinImagePanel();
imagePanel.setImage(image);
add(imagePanel);
}
public static void main(String[] args) {
new Example().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Output:
I show fold contents and syntax groups on mouse-over:
function! SyntaxBallon()
let synID = synID(v:beval_lnum, v:beval_col, 0)
let groupID = synIDtrans(synID)
let name = synIDattr(synID, "name")
let group = synIDattr(groupID, "name")
return name . "\n" . group
endfunction
function! FoldBalloon()
let foldStart = foldclosed(v:beval_lnum)
let foldEnd = foldclosedend(v:beval_lnum)
let lines = []
if foldStart >= 0
" we are in a fold
let numLines = foldEnd - foldStart + 1
if (numLines > 17)
" show only the first 8 and the last 8 lines
let lines += getline(foldStart, foldStart + 8)
let lines += [ '-- Snipped ' . (numLines - 16) . ' lines --']
let lines += getline(foldEnd - 8, foldEnd)
else
" show all lines
let lines += getline(foldStart, foldEnd)
endif
endif
" return result
return join(lines, has("balloon_multiline") ? "\n" : " ")
endfunction
function! Balloon()
if foldclosed(v:beval_lnum) >= 0
return FoldBalloon()
else
return SyntaxBallon()
endfunction
set balloonexpr=Balloon()
set ballooneval
The easiest way is to do:
chmod -R u+rwX,go+rX,go-w /path/to/dir
which basically means:
to ch
ange file mod
es -R
ecursively by giving:
u
ser: r
ead, w
rite and eX
ecute permissions,g
roup and o
ther users: r
ead and eX
ecute permissions, but not -w
rite permission.Please note that X
will make a directory executable, but not a file, unless it's already searchable/executable.
+X
- make a directory or file searchable/executable by everyone if it is already searchable/executable by anyone.
Please check man chmod
for more details.
See also: How to chmod all directories except files (recursively)? at SU
This runs on page load.
<script type="text/javascript">
$(function () {
$("#header").focus();
});
</script>
import itertools
foos=[1.0, 2.0, 3.0, 4.0, 5.0]
bars=[1, 2, 3]
print zip(foos, itertools.cycle([bars]))
I think you might want:
String encodedFile = Base64.getEncoder().encodeToString(bytes);
git reset --hard @{u}
* deletes all your local changes on the current branch, including commits. I'm surprised no one has posted this yet considering you won't have to look up what commit to revert to or play with branches.
* That is, reset to the current branch at @{upstream}
—commonly origin/<branchname>
, but not always
The accepted answer makes a good point - there is not a single number that is going to make sense as a standard for every project. There are projects that just don't need such a standard. Where the accepted answer falls short, in my opinion, is in describing how one might make that decision for a given project.
I will take a shot at doing so. I am not an expert in test engineering and would be happy to see a more informed answer.
First, why would you want to impose such a standard in the first place? In general, when you want to introduce empirical confidence in your process. What do I mean by "empirical confidence"? Well, the real goal correctness. For most software, we can't possibly know this across all inputs, so we settle for saying that code is well-tested. This is more knowable, but is still a subjective standard: It will always be open to debate whether or not you have met it. Those debates are useful and should occur, but they also expose uncertainty.
Code coverage is an objective measurement: Once you see your coverage report, there is no ambiguity about whether standards have been met are useful. Does it prove correctness? Not at all, but it has a clear relationship to how well-tested the code is, which in turn is our best way to increase confidence in its correctness. Code coverage is a measurable approximation of immeasurable qualities we care about.
Some specific cases where having an empirical standard could add value:
Code coverage is not a single metric; there are several different ways of measuring coverage. Which one you might set a standard upon depends on what you're using that standard to satisfy.
I'll use two common metrics as examples of when you might use them to set standards:
if
), have both branches been evaluated? This gives a better sense of the logical coverage of your code: How many of the possible paths my code may take have I tested?
There are many other metrics (line coverage is similar to statement coverage, but yields different numeric results for multi-line statements, for instance; conditional coverage and path coverage is similar to branch coverage, but reflect a more detailed view of the possible permutations of program execution you might encounter.)
Finally, back to the original question: If you set code coverage standards, what should that number be?
Hopefully it's clear at this point that we're talking about an approximation to begin with, so any number we pick is going to be inherently approximate.
Some numbers that one might choose:
I haven't seen numbers below 80% in practice, and have a hard time imagining a case where one would set them. The role of these standards is to increase confidence in correctness, and numbers below 80% aren't particularly confidence-inspiring. (Yes, this is subjective, but again, the idea is to make the subjective choice once when you set the standard, and then use an objective measurement going forward.)
The above assumes that correctness is the goal. Code coverage is just information; it may be relevant to other goals. For instance, if you're concerned about maintainability, you probably care about loose coupling, which can be demonstrated by testability, which in turn can be measured (in certain fashions) by code coverage. So your code coverage standard provides an empirical basis for approximating the quality of "maintainability" as well.
I want to output a table where each column has the smallest possible width,
where columns are padded with white space (but this can be changed) and rows are separated by newlines (but this can be changed) and where each item is formatted using str
(but...).
def ftable(tbl, pad=' ', sep='\n', normalize=str):
# normalize the content to the most useful data type
strtbl = [[normalize(it) for it in row] for row in tbl]
# next, for each column we compute the maximum width needed
w = [0 for _ in tbl[0]]
for row in strtbl:
for ncol, it in enumerate(row):
w[ncol] = max(w[ncol], len(it))
# a string is built iterating on the rows and the items of `strtbl`:
# items are prepended white space to an uniform column width
# formatted items are `join`ed using `pad` (by default " ")
# eventually we join the rows using newlines and return
return sep.join(pad.join(' '*(wid-len(it))+it for wid, it in zip(w, row))
for row in strtbl)
The function signature, ftable(tbl, pad=' ', sep='\n', normalize=str)
, with its default arguments is intended to
provide for maximum flexibility.
You can customize
pad='&', sep='\\\\\n'
to have the bulk of a LaTeX table)str
but if
you know that all your data is floating point lambda item:
"%.4f"%item
could be a reasonable choice, etc.Superficial testing:
I need some test data, possibly involving columns of different width so that the algorithm needs to be a little more sophisticated (but just a little bit;)
In [1]: from random import randrange
In [2]: table = [[randrange(10**randrange(10)) for i in range(5)] for j in range(3)]
In [3]: table
Out[3]:
[[974413992, 510, 0, 3114, 1],
[863242961, 0, 94924, 782, 34],
[1060993, 62, 26076, 75832, 833174]]
In [4]: print(ftable(table))
974413992 510 0 3114 1
863242961 0 94924 782 34
1060993 62 26076 75832 833174
In [5]: print(ftable(table, pad='|'))
974413992|510| 0| 3114| 1
863242961| 0|94924| 782| 34
1060993| 62|26076|75832|833174
CodeIgniter Active Records do not currently support sub-queries, However I use the following approach:
#Create where clause
$this->db->select('id_cer');
$this->db->from('revokace');
$where_clause = $this->db->_compile_select();
$this->db->_reset_select();
#Create main query
$this->db->select('*');
$this->db->from('certs');
$this->db->where("`id` NOT IN ($where_clause)", NULL, FALSE);
_compile_select() and _reset_select() are two undocumented (AFAIK) methods which compile the query and return the sql (without running it) and reset the query.
On the main query the FALSE in the where clause tells codeigniter not to escape the query (or add backticks etc) which would mess up the query. (The NULL is simply because the where clause has an optional second parameter we are not using)
However you should be aware as _compile_select() and _reset_select() are not documented methods it is possible that there functionality (or existence) could change in future releases.
Following @thomas-jungblut implementation in python, i did the same for Octave. If you find something wrong please let me know and i will fix+update.
Data comes from a txt file with the following rows:
1 10 1000
2 20 2500
3 25 3500
4 40 5500
5 60 6200
think about it as a very rough sample for features [number of bedrooms] [mts2] and last column [rent price] which is what we want to predict.
Here is the Octave implementation:
%
% Linear Regression with multiple variables
%
% Alpha for learning curve
alphaNum = 0.0005;
% Number of features
n = 2;
% Number of iterations for Gradient Descent algorithm
iterations = 10000
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% No need to update after here
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
DATA = load('CHANGE_WITH_DATA_FILE_PATH');
% Initial theta values
theta = ones(n + 1, 1);
% Number of training samples
m = length(DATA(:, 1));
% X with one mor column (x0 filled with '1's)
X = ones(m, 1);
for i = 1:n
X = [X, DATA(:,i)];
endfor
% Expected data must go always in the last column
y = DATA(:, n + 1)
function gradientDescent(x, y, theta, alphaNum, iterations)
iterations = [];
costs = [];
m = length(y);
for iteration = 1:10000
hypothesis = x * theta;
loss = hypothesis - y;
% J(theta)
cost = sum(loss.^2) / (2 * m);
% Save for the graphic to see if the algorithm did work
iterations = [iterations, iteration];
costs = [costs, cost];
gradient = (x' * loss) / m; % /m is for the average
theta = theta - (alphaNum * gradient);
endfor
% Show final theta values
display(theta)
% Show J(theta) graphic evolution to check it worked, tendency must be zero
plot(iterations, costs);
endfunction
% Execute gradient descent
gradientDescent(X, y, theta, alphaNum, iterations);
I've been reading that hashing functions like SHA256 weren't really intended for use with storing passwords: https://patrickmn.com/security/storing-passwords-securely/#notpasswordhashes
Instead adaptive key derivation functions like PBKDF2, bcrypt or scrypt were. Here is a PBKDF2 based one that Microsoft wrote for PasswordHasher in their Microsoft.AspNet.Identity library:
/* =======================
* HASHED PASSWORD FORMATS
* =======================
*
* Version 3:
* PBKDF2 with HMAC-SHA256, 128-bit salt, 256-bit subkey, 10000 iterations.
* Format: { 0x01, prf (UInt32), iter count (UInt32), salt length (UInt32), salt, subkey }
* (All UInt32s are stored big-endian.)
*/
public string HashPassword(string password)
{
var prf = KeyDerivationPrf.HMACSHA256;
var rng = RandomNumberGenerator.Create();
const int iterCount = 10000;
const int saltSize = 128 / 8;
const int numBytesRequested = 256 / 8;
// Produce a version 3 (see comment above) text hash.
var salt = new byte[saltSize];
rng.GetBytes(salt);
var subkey = KeyDerivation.Pbkdf2(password, salt, prf, iterCount, numBytesRequested);
var outputBytes = new byte[13 + salt.Length + subkey.Length];
outputBytes[0] = 0x01; // format marker
WriteNetworkByteOrder(outputBytes, 1, (uint)prf);
WriteNetworkByteOrder(outputBytes, 5, iterCount);
WriteNetworkByteOrder(outputBytes, 9, saltSize);
Buffer.BlockCopy(salt, 0, outputBytes, 13, salt.Length);
Buffer.BlockCopy(subkey, 0, outputBytes, 13 + saltSize, subkey.Length);
return Convert.ToBase64String(outputBytes);
}
public bool VerifyHashedPassword(string hashedPassword, string providedPassword)
{
var decodedHashedPassword = Convert.FromBase64String(hashedPassword);
// Wrong version
if (decodedHashedPassword[0] != 0x01)
return false;
// Read header information
var prf = (KeyDerivationPrf)ReadNetworkByteOrder(decodedHashedPassword, 1);
var iterCount = (int)ReadNetworkByteOrder(decodedHashedPassword, 5);
var saltLength = (int)ReadNetworkByteOrder(decodedHashedPassword, 9);
// Read the salt: must be >= 128 bits
if (saltLength < 128 / 8)
{
return false;
}
var salt = new byte[saltLength];
Buffer.BlockCopy(decodedHashedPassword, 13, salt, 0, salt.Length);
// Read the subkey (the rest of the payload): must be >= 128 bits
var subkeyLength = decodedHashedPassword.Length - 13 - salt.Length;
if (subkeyLength < 128 / 8)
{
return false;
}
var expectedSubkey = new byte[subkeyLength];
Buffer.BlockCopy(decodedHashedPassword, 13 + salt.Length, expectedSubkey, 0, expectedSubkey.Length);
// Hash the incoming password and verify it
var actualSubkey = KeyDerivation.Pbkdf2(providedPassword, salt, prf, iterCount, subkeyLength);
return actualSubkey.SequenceEqual(expectedSubkey);
}
private static void WriteNetworkByteOrder(byte[] buffer, int offset, uint value)
{
buffer[offset + 0] = (byte)(value >> 24);
buffer[offset + 1] = (byte)(value >> 16);
buffer[offset + 2] = (byte)(value >> 8);
buffer[offset + 3] = (byte)(value >> 0);
}
private static uint ReadNetworkByteOrder(byte[] buffer, int offset)
{
return ((uint)(buffer[offset + 0]) << 24)
| ((uint)(buffer[offset + 1]) << 16)
| ((uint)(buffer[offset + 2]) << 8)
| ((uint)(buffer[offset + 3]));
}
Note this requires Microsoft.AspNetCore.Cryptography.KeyDerivation nuget package installed which requires .NET Standard 2.0 (.NET 4.6.1 or higher). For earlier versions of .NET see the Crypto class from Microsoft's System.Web.Helpers library.
Update Nov 2015
Updated answer to use an implementation from a different Microsoft library which uses PBKDF2-HMAC-SHA256 hashing instead of PBKDF2-HMAC-SHA1 (note PBKDF2-HMAC-SHA1 is still secure if iterCount is high enough). You can check out the source the simplified code was copied from as it actually handles validating and upgrading hashes implemented from previous answer, useful if you need to increase iterCount in the future.
I'm using Wand-py (an implementation of the Wand wrapper around ImageMagick) to import some pretty advanced SVGs and so far have seen great results! This is all the code it takes:
with wand.image.Image( blob=svg_file.read(), format="svg" ) as image:
png_image = image.make_blob("png")
I just discovered this today, and felt like it was worth sharing for anyone else who might straggle across this answer as it's been a while since most of these questions were answered.
NOTE: Technically in testing I discovered you don't even actually have to pass in the format parameter for ImageMagick, so with wand.image.Image( blob=svg_file.read() ) as image:
was all that was really needed.
EDIT: From an attempted edit by qris, here's some helpful code that lets you use ImageMagick with an SVG that has a transparent background:
from wand.api import library
import wand.color
import wand.image
with wand.image.Image() as image:
with wand.color.Color('transparent') as background_color:
library.MagickSetBackgroundColor(image.wand,
background_color.resource)
image.read(blob=svg_file.read(), format="svg")
png_image = image.make_blob("png32")
with open(output_filename, "wb") as out:
out.write(png_image)
I know it is an old question but there's two type of environment variables. The one owned with User and the one system wide. Depending how do you open git bash (with user privilege or with administrator privilege) the environment variable PATH used can be from you User variables or from System variables. See below:
as said in a previous answer, check with the command env|grep PATH
to see which one you are using and update your variable accordingly.
BTW, no need to reboot the system. Just close and reopen the git bash
The simple one I used to do is
str.contains(" ") ? str.split(" ")[0] : str
Where str
is your string or text bla bla :). So, if
str
is having empty value it returns as it is.str
is having one word, it returns as it is.str
is multiple words, it extract the first word and return.Hope this is helpful.
If you mean File.separator
and File.pathSeparator
then:
File.pathSeparator
is used to separate individual file paths in a list of file paths. Consider on windows, the PATH environment variable. You use a ;
to separate the file paths so on Windows File.pathSeparator
would be ;
.
File.separator
is either /
or \
that is used to split up the path to a specific file. For example on Windows it is \
or C:\Documents\Test
Noticed this is a 2-years old question, but still want to share my workaround for this particular question:
Firstly, run docker container ls -a
to list all the containers you have and pinpoint the want you want to delete.
Secondly, delete the one with command docker container rm <CONTAINER ID>
(If the container is currently running, you should stop it first, run docker container stop <CONTAINER ID>
to gracefully stop the specified container, if it does not stop it for whatever the reason is, alternatively you can run docker container kill <CONTAINER ID> to force shutdown of the specified container
).
Thirdly, remove the container by running docker container rm <CONTAINER ID>
.
Lastly you can run docker image ls -a
to view all the images and delete the one you want to by running docker image rm <hash>
.
Very simple. You just need to loop over the attributes element and push their nodeValues into an array:
let att = document.getElementById('id');
let arr = Array();
for (let i = 0; i < att.attributes.length; i++) {
arr.push(att.attributes[i].nodeValue);
}
If want the name of the attribute you can replace 'nodeValue' for 'nodeName'.
let att = document.getElementById('id');
let arr = Array();
for (let i = 0; i < att.attributes.length; i++) {
arr.push(att.attributes[i].nodeName);
}
Assuming Java (JDK + JRE) is installed in your system, do the following:
C:/>javap javax.servlet.http.HttpServletRequest
It should show a bunch of classes
As I observed in my code. If once the value is fetched of body from Response, its become blank.
String str = response.body().string(); // {response:[]}
String str1 = response.body().string(); // BLANK
So I believe after fetching once the value from body, it become empty.
Suggestion : Store it in String, that can be used many time.
To click the "ok" button in an alert box:
driver.switchTo().alert().accept();
var empty = $("#cartContent").html().trim().length == 0;
from math import ceil
num = 0.1111111111000
num = ceil(num * 100) / 100.0
See:
math.ceil
documentation
round
documentation - You'll probably want to check this out anyway for future reference
jQuery.preloadImage=function(src,onSuccess,onError)
{
var img = new Image()
img.src=src;
var error=false;
img.onerror=function(){
error=true;
if(onError)onError.call(img);
}
if(error==false)
setTimeout(function(){
if(img.height>0&&img.width>0){
if(onSuccess)onSuccess.call(img);
return img;
} else {
setTimeout(arguments.callee,5);
}
},0);
return img;
}
jQuery.preloadImages=function(arrayOfImages){
jQuery.each(arrayOfImages,function(){
jQuery.preloadImage(this);
})
}
// example
jQuery.preloadImage(
'img/someimage.jpg',
function(){
/*complete
this.width!=0 == true
*/
},
function(){
/*error*/
}
)
With Oracle 11g R2 (at least with 11.2.02) there is a view named datapump_dir_objs.
SELECT * FROM datapump_dir_objs;
The view shows the NAME
of the directory object, the PATH
as well as READ
and WRITE
permissions for the currently connected user. It does not show any directory objects which the current user has no permission to read from or write to, though.
Let's start with the uncomfortable truth: GWT compiler performance is really lousy. You can use some hacks here and there, but you're not going to get significantly better performance.
A nice performance hack you can do is to compile for only specific browsers, by inserting the following line in your gwt.xml
:
<define-property name="user.agent" values="ie6,gecko,gecko1_8"></define-property>
or in gwt 2.x syntax, and for one browser only:
<set-property name="user.agent" value="gecko1_8"/>
This, for example, will compile your application for IE and FF only. If you know you are using only a specific browser for testing, you can use this little hack.
Another option: if you are using several locales, and again using only one for testing, you can comment them all out so that GWT will use the default locale, this shaves off some additional overhead from compile time.
Bottom line: you're not going to get order-of-magnitude increase in compiler performance, but taking several relaxations, you can shave off a few minutes here and there.
The order of items in the PATH matters. If there are multiple entries for various java installations, the first one in your PATH will be used.
I have had similar issues after installing a product, like Oracle, that puts it's JRE at the beginning of the PATH.
Ensure that the JDK you want to be loaded is the first entry in your PATH (or at least that it appears before C:\Program Files\Java\jre6\bin
appears).
None of these solutions worked for me inside a Weebly "add your own html" box. Not sure what they are doing with their code. But I found this solution at https://benmarshall.me/responsive-iframes/ and it works perfectly.
CSS
.iframe-container {
overflow: hidden;
padding-top: 56.25%;
position: relative;
}
.iframe-container iframe {
border: 0;
height: 100%;
left: 0;
position: absolute;
top: 0;
width: 100%;
}
/* 4x3 Aspect Ratio */
.iframe-container-4x3 {
padding-top: 75%;
}
HTML
<div class="iframe-container">
<iframe src="https://player.vimeo.com/video/106466360" allowfullscreen></iframe>
</div>
I recommend web storage. Example:
// Storing the data:
localStorage.setItem("variableName","Text");
// Receiving the data:
localStorage.getItem("variableName");
Just replace variable
with your variable name and text
with what you want to store. According to W3Schools, it's better than cookies.
I like to do the following if running in a script where the function is defined:
POINTER= # used for function return values
my_function() {
# do stuff
POINTER="my_function_return"
}
my_other_function() {
# do stuff
POINTER="my_other_function_return"
}
my_function
RESULT="$POINTER"
my_other_function
RESULT="$POINTER"
I like this, becase I can then include echo statements in my functions if I want
my_function() {
echo "-> my_function()"
# do stuff
POINTER="my_function_return"
echo "<- my_function. $POINTER"
}
Conditional expressions are considered to be true if they are non-zero, but the C standard requires that logical operators themselves return either 0 or 1.
@Tom: #define TRUE !FALSE is bad and is completely pointless. If the header file makes its way into compiled C++ code, then it can lead to problems:
void foo(bool flag);
...
int flag = TRUE;
foo(flag);
Some compilers will generate a warning about the int => bool conversion. Sometimes people avoid this by doing:
foo(flag == TRUE);
to force the expression to be a C++ bool. But if you #define TRUE !FALSE, you end up with:
foo(flag == !0);
which ends up doing an int-to-bool comparison that can trigger the warning anyway.
if you need it in rails you can use first (source code)
'1234567890'.first(5) # => "12345"
there is also last (source code)
'1234567890'.last(2) # => "90"
alternatively check from/to (source code):
"hello".from(1).to(-2) # => "ell"
Modify the DataNode class so that it implements Comparable interface.
public int compareTo(DataNode o)
{
return(degree - o.degree);
}
then just use
Collections.sort(nodeList);
Instead of preventing users from pressing Enter, which may seem unnatural, you can leave the form as is and add some extra client-side validation: When the survey is not finished the result is not sent to the server and the user gets a nice message telling what needs to be finished to complete the form. If you are using jQuery, try the Validation plugin:
http://docs.jquery.com/Plugins/Validation
This will require more work than catching the Enter button, but surely it will provide a richer user experience.
When you use addEventListener
, this
will be bound automatically. So if you want a reference to the element on which the event handler is installed, just use this
from within your function:
productLineSelect.addEventListener('change',getSelection,false);
function getSelection(){
var value = sel.options[this.selectedIndex].value;
alert(value);
}
If you want to pass in some other argument from the context where you call addEventListener
, you can use a closure, like this:
productLineSelect.addEventListener('change', function(){
// pass in `this` (the element), and someOtherVar
getSelection(this, someOtherVar);
},false);
function getSelection(sel, someOtherVar){
var value = sel.options[sel.selectedIndex].value;
alert(value);
alert(someOtherVar);
}
Either serialize:
$postvalue=array("a","b","c");
<input type="hidden" name="result" value="<?php echo serialize($postvalue); ?>">
on receive: unserialize($_POST['result'])
Or implode:
$postvalue=array("a","b","c");
<input type="hidden" name="result" value="<?php echo implode(',', $postvalue); ?>">
On receive: explode(',', $_POST['result'])