Things are about to change on the "eol conversion" front, with the upcoming Git 1.7.2:
A new config setting core.eol
is being added/evolved:
This is a replacement for the 'Add "
core.eol
" config variable' commit that's currently inpu
(the last one in my series).
Instead of implying that "core.autocrlf=true
" is a replacement for "* text=auto
", it makes explicit the fact thatautocrlf
is only for users who want to work with CRLFs in their working directory on a repository that doesn't have text file normalization.
When it is enabled, "core.eol" is ignored.Introduce a new configuration variable, "
core.eol
", that allows the user to set which line endings to use for end-of-line-normalized files in the working directory.
It defaults to "native
", which means CRLF on Windows and LF everywhere else. Note that "core.autocrlf
" overridescore.eol
.
This means that:[core] autocrlf = true
puts CRLFs in the working directory even if
core.eol
is set to "lf
".core.eol:
Sets the line ending type to use in the working directory for files that have the
text
property set.
Alternatives are 'lf', 'crlf' and 'native', which uses the platform's native line ending.
The default value isnative
.
Other evolutions are being considered:
For 1.8, I would consider making
core.autocrlf
just turn on normalization and leave the working directory line ending decision to core.eol, but that will break people's setups.
git 2.8 (March 2016) improves the way core.autocrlf
influences the eol:
See commit 817a0c7 (23 Feb 2016), commit 6e336a5, commit df747b8, commit df747b8 (10 Feb 2016), commit df747b8, commit df747b8 (10 Feb 2016), and commit 4b4024f, commit bb211b4, commit 92cce13, commit 320d39c, commit 4b4024f, commit bb211b4, commit 92cce13, commit 320d39c (05 Feb 2016) by Torsten Bögershausen (tboegi
).
(Merged by Junio C Hamano -- gitster
-- in commit c6b94eb, 26 Feb 2016)
convert.c
: refactorcrlf_action
Refactor the determination and usage of
crlf_action
.
Today, when no "crlf
" attribute are set on a file,crlf_action
is set toCRLF_GUESS
. UseCRLF_UNDEFINED
instead, and search for "text
" or "eol
" as before.Replace the old
CRLF_GUESS
usage:
CRLF_GUESS && core.autocrlf=true -> CRLF_AUTO_CRLF
CRLF_GUESS && core.autocrlf=false -> CRLF_BINARY
CRLF_GUESS && core.autocrlf=input -> CRLF_AUTO_INPUT
Make more clear, what is what, by defining:
- CRLF_UNDEFINED : No attributes set. Temparally used, until core.autocrlf
and core.eol is evaluated and one of CRLF_BINARY,
CRLF_AUTO_INPUT or CRLF_AUTO_CRLF is selected
- CRLF_BINARY : No processing of line endings.
- CRLF_TEXT : attribute "text" is set, line endings are processed.
- CRLF_TEXT_INPUT: attribute "input" or "eol=lf" is set. This implies text.
- CRLF_TEXT_CRLF : attribute "eol=crlf" is set. This implies text.
- CRLF_AUTO : attribute "auto" is set.
- CRLF_AUTO_INPUT: core.autocrlf=input (no attributes)
- CRLF_AUTO_CRLF : core.autocrlf=true (no attributes)
As torek adds in the comments:
all these translations (any EOL conversion from
eol=
orautocrlf
settings, and "clean
" filters) are run when files move from work-tree to index, i.e., duringgit add
rather than atgit commit
time.
(Note thatgit commit -a
or--only
or--include
do add files to the index at that time, though.)
For more on that, see "What is difference between autocrlf and eol".
Ahah! Checkout the previous commit, then checkout the master.
git checkout HEAD^
git checkout -f master
Let n be non-prime. Therefore, it has at least two integer factors greater than 1. Let f be the smallest of n's such factors. Suppose f > sqrt n. Then n/f is an integer LTE sqrt n, thus smaller than f. Therefore, f cannot be n's smallest factor. Reductio ad absurdum; n's smallest factor must be LTE sqrt n.
Another way to do this is to add the new characters to the string as follows:
Dim str As String
str = ""
To append text to your string this way:
str = str & "and this is more text"
The top voted answers here are correct but will not work if you are performing cross-domain requests because the session will not be available unless you explicitly tell jQuery to pass the session cookie. Here's how to do that:
$.ajax({
url: url,
type: 'POST',
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))
},
xhrFields: {
withCredentials: true
}
});
Use preventDefault()
to stop the event of submit button and in ajax call success submit the form using submit()
:
$('#btnSave').click(function (e) {
e.preventDefault(); // <------------------ stop default behaviour of button
var element = this;
$.ajax({
url: "/Home/SaveDetailedInfo",
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "Success") {
alert("Done");
$(element).closest("form").submit(); //<------------ submit form
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
});
except Exception:
pass
Use the Value
property.
MyDateTimePicker.Value = DateTime.Today.AddDays(-1);
DateTime.Today
holds today's date, from which you can subtract 1 day (add -1 days) to become yesterday.
DateTime.Now
, on the other hand, contains time information as well. DateTime.Now.AddDays(-1)
will return this time one day ago.
I would use the following if statement because it is easier to read (and modify in the future)
if(!isset($_GET) || !is_array($_GET) || count($_GET)==0) {
// empty, let's make sure it's an empty array for further reference
$_GET=array();
// or unset it
// or set it to null
// etc...
}
It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.
Edit: This is what the forums say:
By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.
To disable:
/system/bin/bugmailer.sh must be deleted/renamed.
There should be a folder on your SD card called "bug reports".
Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948
And this one: http://forum.xda-developers.com/showthread.php?t=1405639
var specialChars = "<>@!#$%^&*()_+[]{}?:;|'\"\\,./~`-="
var check = function(string){
for(i = 0; i < specialChars.length;i++){
if(string.indexOf(specialChars[i]) > -1){
return true
}
}
return false;
}
if(check($('#Search').val()) == false){
// Code that needs to execute when none of the above is in the string
}else{
alert('Your search string contains illegal characters.');
}
Do this instead:
values = [[1,2,3],[4,5]]
for x in values:
if len(x) == 3:
print(x)
Using plain old JavaScript:
var val = "Fish";_x000D_
var sel = document.getElementById('sel');_x000D_
document.getElementById('btn').onclick = function() {_x000D_
var opts = sel.options;_x000D_
for (var opt, j = 0; opt = opts[j]; j++) {_x000D_
if (opt.value == val) {_x000D_
sel.selectedIndex = j;_x000D_
break;_x000D_
}_x000D_
}_x000D_
}
_x000D_
<select id="sel">_x000D_
<option>Cat</option>_x000D_
<option>Dog</option>_x000D_
<option>Fish</option>_x000D_
</select>_x000D_
<button id="btn">Select Fish</button>
_x000D_
But if you really want to use jQuery:
var val = 'Fish';
$('#btn').on('click', function() {
$('#sel').val(val);
});
var val = 'Fish';_x000D_
$('#btn').on('click', function() {_x000D_
$('#sel').val(val);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<select id="sel">_x000D_
<option>Cat</option>_x000D_
<option>Dog</option>_x000D_
<option>Fish</option>_x000D_
</select>_x000D_
<button id="btn">Select Fish</button>
_x000D_
In case your options have value attributes which differ from their text content and you want to select via text content:
<select id="sel">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
<script>
var val = 'Fish';
$('#sel option:contains(' + val + ')').prop({selected: true});
</script>
But if you do have the above set up and want to select by value using jQuery, you can do as before:
var val = 3;
$('#sel').val(val);
For the browsers that support document.querySelector
and the HTMLOptionElement::selected
property, this is a more succinct way of accomplishing this task:
var val = 3;
document.querySelector('#sel [value="' + val + '"]').selected = true;
<select data-bind="value: val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
<script>
var viewModel = {
val: ko.observable()
};
ko.applyBindings(viewModel);
viewModel.val(3);
</script>
<template id="template" is="dom-bind">
<select value="{{ val }}">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</template>
<script>
template.val = 3;
</script>
Note: this has not been updated for the final stable release.
<app id="app">
<select [value]="val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</app>
<script>
var App = ng.Component({selector: 'app'})
.View({template: app.innerHTML})
.Class({constructor: function() {}});
ng.bootstrap(App).then(function(app) {
app._hostComponent.instance.val = 3;
});
</script>
<div id="app">
<select v-model="val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
val: null,
},
mounted: function() {
this.val = 3;
}
});
</script>
Explanation:
Step 1: int fun(int);
Here we declare the prototype of the function fun()
.
Step 2: int i = fun(10);
The variable i is declared as an integer type and the result of the fun(10)
will be stored in the variable i
.
Step 3: int fun(int i){ return (i++); }
Inside the fun()
we are returning a value return(i++)
. It returns 10
. because i++
is the post-increement operator.
Step 4: Then the control back to the main function and the value 10
is assigned to variable i
.
Step 5: printf("%d\n", --i);
Here --i
denoted pre-increement. Hence it prints the value 9
.
JLS§14.14.1, The basic for Statement, makes it clear that the ForUpdate expression(s) are evaluated and the value(s) are discarded. The effect is to make the two forms identical in the context of a for
statement.
You can add a div
to the td
, then style that. It should work as you expected.
<td><div>AAAAAAAAAAAAAAAAAAA</div></td>
Then the css.
td div { width: 50px; overflow: hidden; }
This may be an old post but I realized there is nothing to be returned from the php and your success function does not have input like as follows, success:function(e){}
. I hope that helps you.
Let's test 3 methods:
1)
public static double round1(double value, int scale) {
return Math.round(value * Math.pow(10, scale)) / Math.pow(10, scale);
}
2)
public static float round2(float number, int scale) {
int pow = 10;
for (int i = 1; i < scale; i++)
pow *= 10;
float tmp = number * pow;
return ( (float) ( (int) ((tmp - (int) tmp) >= 0.5f ? tmp + 1 : tmp) ) ) / pow;
}
3)
public static float round3(float d, int decimalPlace) {
return BigDecimal.valueOf(d).setScale(decimalPlace, BigDecimal.ROUND_HALF_UP).floatValue();
}
Number is 0.23453f
We'll test 100,000 iterations each method.
Results:
Time 1 - 18 ms
Time 2 - 1 ms
Time 3 - 378 ms
Tested on laptop
Intel i3-3310M CPU 2.4GHz
In order to use <Aux>
in your JSX, it needs to be a function that returns ReactElement<any> | null
. That's the definition of a function component.
However, it's currently defined as a function that returns React.ReactNode
, which is a much wider type. As React typings say:
type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;
Make sure the unwanted types are neutralized by wrapping the returned value into React Fragment (<></>
):
const aux: React.FC<AuxProps> = props =>
<>{props.children}</>;
I had to use a wildcard route at the end of my routes array.
{ path: '**', redirectTo: 'home' }
And the error was resolved.
This is my solution for the problem. This is controller with 2 action methods
public class FeedbackController : Controller
{
public ActionResult Index()
{
var feedbacks =dataFromSomeSource.getData;
return View(feedbacks);
}
[System.Web.Mvc.HttpDelete]
[System.Web.Mvc.Authorize(Roles = "admin")]
public ActionResult Delete([FromBody]int id)
{
return RedirectToAction("Index");
}
}
In View I render construct following structure.
<html>
..
<script src="~/Scripts/bootbox.min.js"></script>
<script>
function confirmDelete(id) {
bootbox.confirm('@Resources.Resource.AreYouSure', function(result) {
if (result) {
document.getElementById('idField').value = id;
document.getElementById('myForm').submit();
}
}.bind(this));
}
</script>
@using (Html.BeginForm("Delete", "Feedback", FormMethod.Post, new { id = "myForm" }))
{
@Html.HttpMethodOverride(HttpVerbs.Delete)
@Html.Hidden("id",null,new{id="idField"})
foreach (var feedback in @Model)
{
if (User.Identity.IsAuthenticated && User.IsInRole("admin"))
{
@Html.ActionLink("Delete Item", "", new { id = @feedback.Id }, new { onClick = "confirmDelete("+feedback.Id+");return false;" })
}
}
...
</html>
Point of interest in Razor View:
JavaScript function confirmDelete(id)
which is called when the link generated with @Html.ActionLink
is clicked;
confirmDelete()
function required id of item being clicked. This item is passed from onClick
handler confirmDelete("+feedback.Id+");return false;
Pay attention handler returns false to prevent default action - which is get request to target. OnClick
event for buttons could be attached with jQuery for all buttons in the list as alternative (probably it will be even better, as it will be less text in the HTML page and data could be passed via data-
attribute).
Form has id=myForm
, in order to find it in confirmDelete()
.
Form includes @Html.HttpMethodOverride(HttpVerbs.Delete)
in order to use the HttpDelete
verb, as action marked with the HttpDeleteAttribute
.
In the JS function I do use action confirmation (with help of external plugin, but standard confirm works fine too. Don't forget to use bind()
in call back or var that=this
(whatever you prefer).
Form has a hidden element with id='idField'
and name='id'
. So before the form is submitted after confirmation (result==true
), the value of the hidden element is set to value passed argument and browser will submit data to controller like this:
Request URL:http://localhost:38874/Feedback/Delete
Request Method:POST Status Code:302 Found
Response Headers
Location:/Feedback Host:localhost:38874 Form Data X-HTTP-Method-Override:DELETE id:5
As you see it is POST request with X-HTTP-Method-Override:DELETE and data in body set to "id:5". Response has 302 code which redirect to Index action, by this you refresh your screen after delete.
Yes - this is possible. In order to do it, you need to assign a tabindex...
<div tabindex="0">Hello World</div>
A tabindex of 0 will put the tag "in the natural tab order of the page". A higher number will give it a specific order of priority, where 1 will be the first, 2 second and so on.
You can also give a tabindex of -1, which will make the div only focus-able by script, not the user.
document.getElementById('test').onclick = function () {_x000D_
document.getElementById('scripted').focus();_x000D_
};
_x000D_
div:focus {_x000D_
background-color: Aqua;_x000D_
}
_x000D_
<div>Element X (not focusable)</div>_x000D_
<div tabindex="0">Element Y (user or script focusable)</div>_x000D_
<div tabindex="-1" id="scripted">Element Z (script-only focusable)</div>_x000D_
<div id="test">Set Focus To Element Z</div>
_x000D_
Obviously, it is a shame to have an element you can focus by script that you can't focus by other input method (especially if a user is keyboard only or similarly constrained). There are also a whole bunch of standard elements that are focusable by default and have semantic information baked in to assist users. Use this knowledge wisely.
Thanks to many of the answers above and elsewhere, this was my solution to a similar problem to the OP. The problem for me was creating a button in Word that asks the user for a network address, and pulls up the LAN resources in an Explorer window.
Untouched, the code would take you to \\10.1.1.1\Test,
so edit as you see fit. I'm just a monkey on a keyboard, here, so all comments and suggestions are welcome.
Private Sub CommandButton1_Click()
Dim ipAddress As Variant
On Error GoTo ErrorHandler
ipAddress = InputBox("Please enter the IP address of the network resource:", "Explore a network resource", "\\10.1.1.1")
If ipAddress <> "" Then
ThisDocument.FollowHyperlink ipAddress & "\Test"
End If
ExitPoint:
Exit Sub
ErrorHandler:
If Err.Number = "4120" Then
GoTo ExitPoint
ElseIf Err.Number = "4198" Then
MsgBox "Destination unavailable"
GoTo ExitPoint
End If
MsgBox "Error " & Err.Number & vbCrLf & Err.Description
Resume ExitPoint
End Sub
Use the exp1 if cond else exp2
syntax.
rate = lambda T: 200*exp(-T) if T>200 else 400*exp(-T)
Note you don't use return
in lambda expressions.
PHP 7: Null Coalesce Operator
//$http = 'SCRIPT_NAME';
$http = 'X_REQUESTED_WITH';
$http = strtoupper($http);
$header = $_SERVER['HTTP_'.$http] ?? $_SERVER[$http] ?? NULL;
if(is_null($header)){
die($http. ' Not Found');
}
echo $header;
///UPDATED DEMO 2 WATCH SOLUTION////
I hope that is the solution you're looking for! DEMO1 DEMO2
With that solution the only scrollbar in the page is on your contents section in the middle! In that section build your structure with a sidebar or whatever you want!
You can do that with that code here:
<div class="navTop">
<h1>Title</h1>
<nav>Dynamic menu</nav>
</div>
<div class="container">
<section>THE CONTENTS GOES HERE</section>
</div>
<footer class="bottomFooter">
Footer
</footer>
With that css:
.navTop{
width:100%;
border:1px solid black;
float:left;
}
.container{
width:100%;
float:left;
overflow:scroll;
}
.bottomFooter{
float:left;
border:1px solid black;
width:100%;
}
And a bit of jquery:
$(document).ready(function() {
function setHeight() {
var top = $('.navTop').outerHeight();
var bottom = $('footer').outerHeight();
var totHeight = $(window).height();
$('section').css({
'height': totHeight - top - bottom + 'px'
});
}
$(window).on('resize', function() { setHeight(); });
setHeight();
});
DEMO 1
If you don't want jquery
<div class="row">
<h1>Title</h1>
<nav>NAV</nav>
</div>
<div class="row container">
<div class="content">
<div class="sidebar">
SIDEBAR
</div>
<div class="contents">
CONTENTS
</div>
</div>
<footer>Footer</footer>
</div>
CSS
*{
margin:0;padding:0;
}
html,body{
height:100%;
width:100%;
}
body{
display:table;
}
.row{
width: 100%;
background: yellow;
display:table-row;
}
.container{
background: pink;
height:100%;
}
.content {
display: block;
overflow:auto;
height:100%;
padding-bottom: 40px;
box-sizing: border-box;
}
footer{
position: fixed;
bottom: 0;
left: 0;
background: yellow;
height: 40px;
line-height: 40px;
width: 100%;
text-align: center;
}
.sidebar{
float:left;
background:green;
height:100%;
width:10%;
}
.contents{
float:left;
background:red;
height:100%;
width:90%;
overflow:auto;
}
DEMO 2
I had to read subtitles files and split them into sentences. After pre-processing (like removing time information etc in the .srt files), the variable fullFile contained the full text of the subtitle file. The below crude way neatly split them into sentences. Probably I was lucky that the sentences always ended (correctly) with a space. Try this first and if it has any exceptions, add more checks and balances.
# Very approximate way to split the text into sentences - Break after ? . and !
fullFile = re.sub("(\!|\?|\.) ","\\1<BRK>",fullFile)
sentences = fullFile.split("<BRK>");
sentFile = open("./sentences.out", "w+");
for line in sentences:
sentFile.write (line);
sentFile.write ("\n");
sentFile.close;
Oh! well. I now realize that since my content was Spanish, I did not have the issues of dealing with "Mr. Smith" etc. Still, if someone wants a quick and dirty parser...
Be very careful when cloning ArrayLists. Cloning in java is shallow. This means that it will only clone the Arraylist itself and not its members. So if you have an ArrayList X1 and clone it into X2 any change in X2 will also manifest in X1 and vice-versa. When you clone you will only generate a new ArrayList with pointers to the same elements in the original.
You could use a std::stringstream. You can stream anything into it:
std::stringstream stream;
stream << 5.7;
stream << foo.bar;
std::string s = stream.str();
That should be a quite general approach. (Works only for C++, but you asked the question for this language too.)
this is my first code on this site try this
import java.util.Scanner;
public class BATM {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String username;
String password;
System.out.println("Log in:");
System.out.println("username: ");
username = input.next();
System.out.println("password: ");
password = input.next();
//users check = new users(username, password);
if(username.equals(username) && password.equals(password))
System.out.println("You are logged in");
}
}
:find
is another option.
I open vim from the root of my project and have the path
set to there.
Then, I can open files located anywhere in the tree using:
:find **/filena< tab >
Tab will autocomplete through various matches. (**
tells it to search recursively through the path).
Check out this issue. I think the bug will be resolved when new template precompilation logic will be implemented. For now I think the best you can do is to wrap your template into <div class="root">
and style this div
:
@Component({ ... })
@View({
template: `
<div class="root">
<h2>Hello Angular2!</h2>
<p>here is your template</p>
</div>
`,
styles: [`
.root {
background: blue;
}
`],
...
})
class SomeComponent {}
See this plunker
The diff / (24 * etc) does not take Timezone into account, so if your default timezone has a DST in it, it can throw the calculation off.
This link has a nice little implementation.
Here is the source of the above link in case the link goes down:
/** Using Calendar - THE CORRECT WAY**/
public static long daysBetween(Calendar startDate, Calendar endDate) {
//assert: startDate must be before endDate
Calendar date = (Calendar) startDate.clone();
long daysBetween = 0;
while (date.before(endDate)) {
date.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
return daysBetween;
}
and
/** Using Calendar - THE CORRECT (& Faster) WAY**/
public static long daysBetween(final Calendar startDate, final Calendar endDate)
{
//assert: startDate must be before endDate
int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
long endInstant = endDate.getTimeInMillis();
int presumedDays =
(int) ((endInstant - startDate.getTimeInMillis()) / MILLIS_IN_DAY);
Calendar cursor = (Calendar) startDate.clone();
cursor.add(Calendar.DAY_OF_YEAR, presumedDays);
long instant = cursor.getTimeInMillis();
if (instant == endInstant)
return presumedDays;
final int step = instant < endInstant ? 1 : -1;
do {
cursor.add(Calendar.DAY_OF_MONTH, step);
presumedDays += step;
} while (cursor.getTimeInMillis() != endInstant);
return presumedDays;
}
In Windows 7 and later, this will do the trick for you
The menu item Copy as Path is not available in Windows XP.
To point out what I had to dig out of Chris Johansen's chat with OP (linked from a reply to an answer):
git add vendor/plugins/open_flash_chart_2
# will add gitlink, content will stay untracked
git add vendor/plugins/open_flash_chart_2/
# NOTICE THE SLASH!!!!
The second form will add it without gitlink, and the contents are trackable. The .git dir is conveniently & automatically ignored. Thank you Chris!
use
statusCode: {
404: function() {
alert('page not found');
}
}
-
$.ajax({
type: 'POST',
url: '/controller/action',
data: $form.serialize(),
success: function(data){
alert('horray! 200 status code!');
},
statusCode: {
404: function() {
alert('page not found');
},
400: function() {
alert('bad request');
}
}
});
To make your function more portable, use it as such:
os.path.join(os.sep, 'home', 'build', 'test', 'sandboxes', todaystr, 'new_sandbox')
or
os.path.join(os.environ.get("HOME"), 'test', 'sandboxes', todaystr, 'new_sandbox')
You can get the protocol, host, and port using this:
window.location.origin
Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
---|---|---|---|---|---|
(Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
30.0.1599.101 (possibly earlier) | ? | 21.0 (21.0) | 11 | ? | 7 (possibly earlier, see webkit bug 46558) |
Android | Edge | Firefox Mobile (Gecko) | IE Phone | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
(Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
30.0.1599.101 (possibly earlier) | ? | 21.0 (21.0) | ? | ? | 7 (possibly earlier, see webkit bug 46558) |
All browser compatibility is from Mozilla Developer Network
I tried the above solutions in Python3 but this one seems to be the only one working for me when storing objects in a dict. Basically you make a copy of your dict() and iterate over that while deleting the entries in your original dictionary.
tmpDict = realDict.copy()
for key, value in tmpDict.items():
if value:
del(realDict[key])
If you have to sort object based on its id in the ArrayList , then use java8 stream.
List<Person> personList = new ArrayList<>();
List<Person> personListSorted =
personList.stream()
.sorted(Comparator.comparing(Person::getPersonId))
.collect(Collectors.toList());
Force a method to get the struct (the constructor way).
From this post:
A good design is to make your type unexported, but provide an exported constructor function like
NewMyType()
in which you can properly initialize your struct / type. Also return an interface type and not a concrete type, and the interface should contain everything others want to do with your value. And your concrete type must implement that interface of course.
This can be done by simply making the type itself unexported. You can export the function NewSomething and even the fields Text and DefaultText, but just don't export the struct type something.
Another way to customize it for you own module is by using a Config struct to set default values (Option 5 in the link). Not a good way though.
You should use a Set
. A Set
is a Collection that contains no duplicates.
If you have a List
that contains duplicates, you can get the unique entries like this:
List<String> gasList = // create list with duplicates...
Set<String> uniqueGas = new HashSet<String>(gasList);
System.out.println("Unique gas count: " + uniqueGas.size());
NOTE: This HashSet
constructor identifies duplicates by invoking the elements' equals() methods.
void transfer(double x) {
unsigned long long* p = (unsigned long long*)&x;
for (int i = sizeof(unsigned long long) * 8 - 1; i >= 0; i--) {cout<< ((*p) >>i & 1);}}
You're passing link=$a
and link=$b
in the hrefs for A and B, respectively. They are treated as strings, not variables. The following should fix that for you:
echo '<a href="pass.php?link=' . $a . '">Link 1</a>';
// and
echo '<a href="pass.php?link=' . $b . '">Link 2</a>';
The value of $a
also isn't included on pass.php
. I would suggest making a common variable file and include it on all necessary pages.
It appears that pip did a refactor and moved main to internal. There is a comprehensive discussion about it here: https://github.com/pypa/pip/issues/5240
A workaround for me was to change
import pip
pip.main(...)
to
from pip._internal import main
main(...)
I recommend reading through the discussion, I'm not sure this is the best approach, but it worked for my purposes.
I'd recommend that you take a look at jQuery.
jQuery way:
$("html").addClass("myClass");
Assuming your categories are in cells A1:A6 and the corresponding values are in B1:B6, you might try typing the formula =MEDIAN(IF($A$1:$A$6="Airline",$B$1:$B$6,""))
in another cell and then pressing CTRL+SHIFT+ENTER
.
Using CTRL+SHIFT+ENTER
tells Excel to treat the formula as an "array formula". In this example, that means that the IF
statement returns an array of 6 values (one of each of the cells in the range $A$1:$A$6
) instead of a single value. The MEDIAN
function then returns the median of these values. See http://www.cpearson.com/excel/arrayformulas.aspx for a similar example using AVERAGE
instead of MEDIAN
.
I guess there is a simple solution which I recently used after going through so many answers here.
with open(file_name) as f_in:
for line in f_in:
if len(line.split()) == 0:
continue
This just does the same work, ignoring all empty line.
If you wish to use 2 subdomains to other ports, you can use Minecraft's proxy server (it means BungeeCord, Waterfall, Travertine...), and bind subdomain to specifiend in config.yml server. To do that you have to setup your servers in BungeeCord's config:
servers:
pvp:
motd: 'A Minecraft Server PVP'
address: localhost:25566
restricted: false
skyblock:
motd: 'A Minecraft Server SkyBlock'
address: localhost:25567
restricted: false
Remember! Ports must be diffrent than default Minecraft's port (it means 25565), because we will use this port to our proxy. sub1.domain.com and sub2.domain.com we have to bind to server where you have these servers. Now, we have to bind subdomains in your Bungee server:
listeners:
forced_hosts:
sub1.domain.com: pvp
sub2.domain.com: skyblock
domain.com: pvp // You can bind other domains to same servers.
Remember to change force_default_server to true, and change host to 0.0.0.0:25565 Example of BungeeCord's config.yml with some servers: https://pastebin.com/tA9ktZ6f Now you can connect to your pvp server on sub1.domain.com and connect to skyblock on sub2.domain.com. Don't worry, BungeeCord takes only 0,5GB of RAM for 500 players.
"SELECT * FROM tablename WHERE field1 = 'value' && field2 = 'value2'";
becomes
"SELECT * FROM tablename WHERE field1 = ? && field2 = ?";
which is passed to the $mysqli::prepare
:
$stmt = $mysqli->prepare(
"SELECT * FROM tablename WHERE field1 = ? && field2 = ?");
$stmt->bind_param( "ss", $value, $value2);
// "ss' is a format string, each "s" means string
$stmt->execute();
$stmt->bind_result($col1, $col2);
// then fetch and close the statement
OP comments:
so if i have 5 parameters, i could potentially have "sssis" or something (depending on the types of inputs?)
Right, one type specifier per ?
parameter in the prepared statement, all of them positional (first specifier applies to first ?
which is replaced by first actual parameter (which is the second parameter to bind_param
)).
mysqli will take care of escaping and quoting (I think).
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live(). Refer: http://api.jquery.com/on/
$('#imageFile').on("change", function(){ uploadFile(); });
Slightly faster version of the implementation (If you know that most couples lists will have different lengths):
def checkEqual(L1, L2):
return len(L1) == len(L2) and sorted(L1) == sorted(L2)
Comparing:
>>> timeit(lambda: sorting([1,2,3], [3,2,1]))
2.42745304107666
>>> timeit(lambda: lensorting([1,2,3], [3,2,1]))
2.5644469261169434 # speed down not much (for large lists the difference tends to 0)
>>> timeit(lambda: sorting([1,2,3], [3,2,1,0]))
2.4570400714874268
>>> timeit(lambda: lensorting([1,2,3], [3,2,1,0]))
0.9596951007843018 # speed up
I am also using this approach for csv files (Python 3.6.9):
import csv
import io
import requests
r = requests.get(url)
buff = io.StringIO(r.text)
dr = csv.DictReader(buff)
for row in dr:
print(row)
Use stat(), if it is cross-platform enough for your needs. It is not C++ standard though, but POSIX.
On MS Windows there is _stat, _stat64, _stati64, _wstat, _wstat64, _wstati64.
Implemented in JavaScript (ES6):
/**
* Calculate x and y in circle's circumference
* @param {Object} input - The input parameters
* @param {number} input.radius - The circle's radius
* @param {number} input.angle - The angle in degrees
* @param {number} input.cx - The circle's origin x
* @param {number} input.cy - The circle's origin y
* @returns {Array[number,number]} The calculated x and y
*/
function pointsOnCircle({ radius, angle, cx, cy }){
angle = angle * ( Math.PI / 180 ); // Convert from Degrees to Radians
const x = cx + radius * Math.sin(angle);
const y = cy + radius * Math.cos(angle);
return [ x, y ];
}
Usage:
const [ x, y ] = pointsOnCircle({ radius: 100, angle: 180, cx: 150, cy: 150 });
console.log( x, y );
/**
* Calculate x and y in circle's circumference
* @param {Object} input - The input parameters
* @param {number} input.radius - The circle's radius
* @param {number} input.angle - The angle in degrees
* @param {number} input.cx - The circle's origin x
* @param {number} input.cy - The circle's origin y
* @returns {Array[number,number]} The calculated x and y
*/
function pointsOnCircle({ radius, angle, cx, cy }){
angle = angle * ( Math.PI / 180 ); // Convert from Degrees to Radians
const x = cx + radius * Math.sin(angle);
const y = cy + radius * Math.cos(angle);
return [ x, y ];
}
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
function draw( x, y ){
ctx.clearRect( 0, 0, canvas.width, canvas.height );
ctx.beginPath();
ctx.strokeStyle = "orange";
ctx.arc( 100, 100, 80, 0, 2 * Math.PI);
ctx.lineWidth = 3;
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.fillStyle = "indigo";
ctx.arc( x, y, 6, 0, 2 * Math.PI);
ctx.fill();
ctx.closePath();
}
let angle = 0; // In degrees
setInterval(function(){
const [ x, y ] = pointsOnCircle({ radius: 80, angle: angle++, cx: 100, cy: 100 });
console.log( x, y );
draw( x, y );
document.querySelector("#degrees").innerHTML = angle + "°";
document.querySelector("#points").textContent = x.toFixed() + "," + y.toFixed();
}, 100 );
_x000D_
<p>Degrees: <span id="degrees">0</span></p>
<p>Points on Circle (x,y): <span id="points">0,0</span></p>
<canvas width="200" height="200" style="border: 1px solid"></canvas>
_x000D_
Quoting from the SQLite documentation:
Any other character matches itself or its lower/upper case equivalent (i.e. case-insensitive matching)
...which I didn't know.But it works:
sqlite> create table products (name string);
sqlite> insert into products values ("Blue jeans");
sqlite> select * from products where name = 'Blue Jeans';
sqlite> select * from products where name like 'Blue Jeans';
Blue jeans
So you could do something like this:
name = 'Blue jeans'
if prod = Product.find(:conditions => ['name LIKE ?', name])
# update product or whatever
else
prod = Product.create(:name => name)
end
Not #find_or_create
, I know, and it may not be very cross-database friendly, but worth looking at?
ProductionWorker
extends Employee
, thus it is said that it has all the capabilities of an Employee. In order to accomplish that, Java automatically puts a super();
call in each constructor's first line, you can put it manually but usually it is not necessary. In your case, it is necessary because the call to super();
cannot be placed automatically due to the fact that Employee's constructor has parameters.
You either need to define a default constructor in your Employee
class, or call super('Erkan', 21, new Date());
in the first line of the constructor in ProductionWorker.
Another interessant possibility of format date. This screenshot belongs to Apple's App "News".
Here is the code:
let dateFormat1 = DateFormatter()
dateFormat1.dateFormat = "EEEE"
let stringDay = dateFormat1.string(from: Date())
let dateFormat2 = DateFormatter()
dateFormat2.dateFormat = "MMMM"
let stringMonth = dateFormat2.string(from: Date())
let dateFormat3 = DateFormatter()
dateFormat3.dateFormat = "dd"
let numDay = dateFormat3.string(from: Date())
let stringDate = String(format: "%@\n%@ %@", stringDay.uppercased(), stringMonth.uppercased(), numDay)
Nothing to add to alternative proposed by lorenzoliveto. It's just perfect.
let dateFormat = DateFormatter()
dateFormat.dateFormat = "EEEE\nMMMM dd"
let stringDate = dateFormat.string(from: Date()).uppercased()
Given the proliferation of different ways to read an Excel file in R
and the plethora of answers here, I thought I'd try to shed some light on which of the options mentioned here perform the best (in a few simple situations).
I myself have been using xlsx
since I started using R
, for inertia if nothing else, and I recently noticed there doesn't seem to be any objective information about which package works better.
Any benchmarking exercise is fraught with difficulties as some packages are sure to handle certain situations better than others, and a waterfall of other caveats.
That said, I'm using a (reproducible) data set that I think is in a pretty common format (8 string fields, 3 numeric, 1 integer, 3 dates):
set.seed(51423)
data.frame(
str1 = sample(sprintf("%010d", 1:NN)), #ID field 1
str2 = sample(sprintf("%09d", 1:NN)), #ID field 2
#varying length string field--think names/addresses, etc.
str3 =
replicate(NN, paste0(sample(LETTERS, sample(10:30, 1L), TRUE),
collapse = "")),
#factor-like string field with 50 "levels"
str4 = sprintf("%05d", sample(sample(1e5, 50L), NN, TRUE)),
#factor-like string field with 17 levels, varying length
str5 =
sample(replicate(17L, paste0(sample(LETTERS, sample(15:25, 1L), TRUE),
collapse = "")), NN, TRUE),
#lognormally distributed numeric
num1 = round(exp(rnorm(NN, mean = 6.5, sd = 1.5)), 2L),
#3 binary strings
str6 = sample(c("Y","N"), NN, TRUE),
str7 = sample(c("M","F"), NN, TRUE),
str8 = sample(c("B","W"), NN, TRUE),
#right-skewed integer
int1 = ceiling(rexp(NN)),
#dates by month
dat1 =
sample(seq(from = as.Date("2005-12-31"),
to = as.Date("2015-12-31"), by = "month"),
NN, TRUE),
dat2 =
sample(seq(from = as.Date("2005-12-31"),
to = as.Date("2015-12-31"), by = "month"),
NN, TRUE),
num2 = round(exp(rnorm(NN, mean = 6, sd = 1.5)), 2L),
#date by day
dat3 =
sample(seq(from = as.Date("2015-06-01"),
to = as.Date("2015-07-15"), by = "day"),
NN, TRUE),
#lognormal numeric that can be positive or negative
num3 =
(-1) ^ sample(2, NN, TRUE) * round(exp(rnorm(NN, mean = 6, sd = 1.5)), 2L)
)
I then wrote this to csv and opened in LibreOffice and saved it as an .xlsx file, then benchmarked 4 of the packages mentioned in this thread: xlsx
, openxlsx
, readxl
, and gdata
, using the default options (I also tried a version of whether or not I specify column types, but this didn't change the rankings).
I'm excluding RODBC
because I'm on Linux; XLConnect
because it seems its primary purpose is not reading in single Excel sheets but importing entire Excel workbooks, so to put its horse in the race on only its reading capabilities seems unfair; and xlsReadWrite
because it is no longer compatible with my version of R
(seems to have been phased out).
I then ran benchmarks with NN=1000L
and NN=25000L
(resetting the seed before each declaration of the data.frame
above) to allow for differences with respect to Excel file size. gc
is primarily for xlsx
, which I've found at times can create memory clogs. Without further ado, here are the results I found:
benchmark1k <-
microbenchmark(times = 100L,
xlsx = {xlsx::read.xlsx2(fl, sheetIndex=1); invisible(gc())},
openxlsx = {openxlsx::read.xlsx(fl); invisible(gc())},
readxl = {readxl::read_excel(fl); invisible(gc())},
gdata = {gdata::read.xls(fl); invisible(gc())})
# Unit: milliseconds
# expr min lq mean median uq max neval
# xlsx 194.1958 199.2662 214.1512 201.9063 212.7563 354.0327 100
# openxlsx 142.2074 142.9028 151.9127 143.7239 148.0940 255.0124 100
# readxl 122.0238 122.8448 132.4021 123.6964 130.2881 214.5138 100
# gdata 2004.4745 2042.0732 2087.8724 2062.5259 2116.7795 2425.6345 100
So readxl
is the winner, with openxlsx
competitive and gdata
a clear loser. Taking each measure relative to the column minimum:
# expr min lq mean median uq max
# 1 xlsx 1.59 1.62 1.62 1.63 1.63 1.65
# 2 openxlsx 1.17 1.16 1.15 1.16 1.14 1.19
# 3 readxl 1.00 1.00 1.00 1.00 1.00 1.00
# 4 gdata 16.43 16.62 15.77 16.67 16.25 11.31
We see my own favorite, xlsx
is 60% slower than readxl
.
Due to the amount of time it takes, I only did 20 repetitions on the larger file, otherwise the commands were identical. Here's the raw data:
# Unit: milliseconds
# expr min lq mean median uq max neval
# xlsx 4451.9553 4539.4599 4738.6366 4762.1768 4941.2331 5091.0057 20
# openxlsx 962.1579 981.0613 988.5006 986.1091 992.6017 1040.4158 20
# readxl 341.0006 344.8904 347.0779 346.4518 348.9273 360.1808 20
# gdata 43860.4013 44375.6340 44848.7797 44991.2208 45251.4441 45652.0826 20
Here's the relative data:
# expr min lq mean median uq max
# 1 xlsx 13.06 13.16 13.65 13.75 14.16 14.13
# 2 openxlsx 2.82 2.84 2.85 2.85 2.84 2.89
# 3 readxl 1.00 1.00 1.00 1.00 1.00 1.00
# 4 gdata 128.62 128.67 129.22 129.86 129.69 126.75
So readxl
is the clear winner when it comes to speed. gdata
better have something else going for it, as it's painfully slow in reading Excel files, and this problem is only exacerbated for larger tables.
Two draws of openxlsx
are 1) its extensive other methods (readxl
is designed to do only one thing, which is probably part of why it's so fast), especially its write.xlsx
function, and 2) (more of a drawback for readxl
) the col_types
argument in readxl
only (as of this writing) accepts some nonstandard R
: "text"
instead of "character"
and "date"
instead of "Date"
.
The problem is that you haven't got any element with the id u
so that you are calling something that doesn't exist.
To fix that you have to add an id to the element.
<input id="u" type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />
And I've seen too you have added a value for the input, so it means the input is not empty and it will contain text. As result placeholder
won't be displayed.
Finally there is a warning that W3Validator will say because of the "/" in the end. :
For the current document, the validator interprets strings like according to legacy rules that break the expectations of most authors and thus cause confusing warnings and error messages from the validator. This interpretation is triggered by HTML 4 documents or other SGML-based HTML documents. To avoid the messages, simply remove the "/" character in such contexts. NB: If you expect <FOO /> to be interpreted as an XML-compatible "self-closing" tag, then you need to use XHTML or HTML5.
In conclusion it says you have to remove the slash. Simply write this:
<input id="u" type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item...">
The put method in HashMap is defined like this:
Object put(Object key, Object value)
key is the first parameter, so in your put, "one" is the key. You can't easily look up by value in a HashMap, if you really want to do that, it would be a linear search done by calling entrySet()
, like this:
for (Map.Entry<Object, Object> e : hashmap.entrySet()) {
Object key = e.getKey();
Object value = e.getValue();
}
However, that's O(n) and kind of defeats the purpose of using a HashMap unless you only need to do it rarely. If you really want to be able to look up by key or value frequently, core Java doesn't have anything for you, but something like BiMap from the Google Collections is what you want.
Try this, to call your code in ngOnInit()
someMethod() // emitted method call from output
{
// Your code
}
ngOnInit(){
someMethod(); // call here your error will be gone
}
This issue can also happen due to the following
1.In the Web.Config
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
2.Make sure the following are available in the bin folder on the server where the Web API is deployed
•System.Net.Http
•System.Net.Http.Formatting
•System.Web.Http.WebHost
•System.Web.Http
These assemblies won't be copied in the bin folder by default if the publish is through Visual Studio because the Web API packages are installed through Nuget in the development machine. Still if you want to achieve these files to be available as part of Visual Studio publish then you need to set CopyLocal to True for these Assemblies
Try formatting the link like this (looks hellish, but it works in Firefox 3 under Vista for me) :
<a href="file://///SERVER/directory/file.ext">file.ext</a>
I did this in my project and it works like a charm
Date now = new Date();
System.out.println(now);
TimeZone.setDefault(TimeZone.getTimeZone("UTC")); // The magic is here
System.out.println(now);
I encountered this issue, but in my case the password for the 'phpmyadmin' user did not match the contents of /etc/phpmyadmin/config-db.php
Once I updated the password for the 'phpmyadmin' user the error went away.
These are the steps I took:
mysql -uroot -pYOUR_ROOT_PASS
use mysql;
UPDATE mysql.user SET Password=PASSWORD('YOUR_PASS_HERE') WHERE User='phpmyadmin' AND Host='localhost';
FLUSH PRIVILEGES;
DONE!! It worked for me.
Create a class that implements webviewclient and add the following code that allows ovveriding the url string as shown below. You can see these [example][1]
public class myWebClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
On your constructor, create a webview object as shown below.
web = new WebView(this); web.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
Then add the following code to perform loading of urls inside your app
WebSettings settings=web.getSettings();
settings.setJavaScriptEnabled(true);
web.loadUrl("http://www.facebook.com");
web.setWebViewClient(new myWebClient());
web.setWebChromeClient(new WebChromeClient() {
//
//
}
Try format
function:
> xx = 100000000000
> xx
[1] 1e+11
> format(xx, scientific=F)
[1] "100000000000"
The following should work:
ABC: *\([a-zA-Z]+\) *(.+)
Explanation:
ABC: # match literal characters 'ABC:'
* # zero or more spaces
\([a-zA-Z]+\) # one or more letters inside of parentheses
* # zero or more spaces
(.+) # capture one or more of any character (except newlines)
To get your desired grouping based on the comments below, you can use the following:
(ABC:) *(\([a-zA-Z]+\).+)
I had a similar problem, and it turned out that the simple solution was to have my configuration class extend WebMvcAutoConfiguration
:
@Configuration
@EnableWebMvc
@ComponentScan
public class ServerConfiguration extends WebMvcAutoConfiguration{
}
I didn't need any other code to allow my static content to be served, however, I did put a directory called public
under src/main/webapp
and configured maven to point to src/main/webapp
as a resource directory. This means that public
is copied into target/classes
, and is therefore on the classpath at runtime for spring-boot/tomcat to find.
I use this little PowerShell snippet:
function Get-SystemUptime {
$operatingSystem = Get-WmiObject Win32_OperatingSystem
"$((Get-Date) - ([Management.ManagementDateTimeConverter]::ToDateTime($operatingSystem.LastBootUpTime)))"
}
which then yields something like the following:
PS> Get-SystemUptime
6.20:40:40.2625526
try this:
<div ng-if="$scope.length == 0" ? true : false></div>
and show or hide
<div ng-show="$scope.length == 0"></div>
else it will be hide
-----------------or--------------------------
if you are using $ctrl than code will be like this:
try this:
<div ng-if="$ctrl.length == 0" ? true : false></div>
and show or hide
<div ng-show="$ctrl.length == 0"></div>
else it will be hide
You need to multiply your Model matrix. Because that is where model position, scaling and rotation should be (that's why it's called the model matrix).
All you need to do is (see here)
Model = glm::rotate(Model, angle_in_radians, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)
Note that to convert from degrees to radians, use
glm::radians(degrees)
That takes the Model matrix and applies rotation on top of all the operations that are already in there. The other functions translate and scale do the same. That way it's possible to combine many transformations in a single matrix.
note: earlier versions accepted angles in degrees. This is deprecated since 0.9.6
Model = glm::rotate(Model, angle_in_degrees, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)
Can be done on the same line using date.replace
:
from datetime import datetime
datetime.today().replace(day=1)
select case when IsNull(CONVERT(DATE, StartDate),'')='' then 'NA' else Convert(varchar(10),StartDate,121) end from table1
I was a little bit worried about using only touchmove for my project, since it only seems to fire when your touch moves from one location to another (and not on the initial touch). So I combined it with touchstart, and this seems to work very well for the initial touch and any movements.
<script>
function doTouch(e) {
e.preventDefault();
var touch = e.touches[0];
document.getElementById("xtext").innerHTML = touch.pageX;
document.getElementById("ytext").innerHTML = touch.pageY;
}
document.addEventListener('touchstart', function(e) {doTouch(e);}, false);
document.addEventListener('touchmove', function(e) {doTouch(e);}, false);
</script>
X: <div id="xtext">0</div>
Y: <div id="ytext">0</div>
This solution provides a strict FixedLengthArray (ak.a. SealedArray) type signature based in Tuples.
Syntax example :
// Array containing 3 strings
let foo : FixedLengthArray<[string, string, string]>
This is the safest approach, considering it prevents accessing indexes out of the boundaries.
Implementation :
type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift' | number
type ArrayItems<T extends Array<any>> = T extends Array<infer TItems> ? TItems : never
type FixedLengthArray<T extends any[]> =
Pick<T, Exclude<keyof T, ArrayLengthMutationKeys>>
& { [Symbol.iterator]: () => IterableIterator< ArrayItems<T> > }
Tests :
var myFixedLengthArray: FixedLengthArray< [string, string, string]>
// Array declaration tests
myFixedLengthArray = [ 'a', 'b', 'c' ] // ? OK
myFixedLengthArray = [ 'a', 'b', 123 ] // ? TYPE ERROR
myFixedLengthArray = [ 'a' ] // ? LENGTH ERROR
myFixedLengthArray = [ 'a', 'b' ] // ? LENGTH ERROR
// Index assignment tests
myFixedLengthArray[1] = 'foo' // ? OK
myFixedLengthArray[1000] = 'foo' // ? INVALID INDEX ERROR
// Methods that mutate array length
myFixedLengthArray.push('foo') // ? MISSING METHOD ERROR
myFixedLengthArray.pop() // ? MISSING METHOD ERROR
// Direct length manipulation
myFixedLengthArray.length = 123 // ? READ-ONLY ERROR
// Destructuring
var [ a ] = myFixedLengthArray // ? OK
var [ a, b ] = myFixedLengthArray // ? OK
var [ a, b, c ] = myFixedLengthArray // ? OK
var [ a, b, c, d ] = myFixedLengthArray // ? INVALID INDEX ERROR
(*) This solution requires the noImplicitAny
typescript configuration directive to be enabled in order to work (commonly recommended practice)
This solution behaves as an augmentation of the Array
type, accepting an additional second parameter(Array length). Is not as strict and safe as the Tuple based solution.
Syntax example :
let foo: FixedLengthArray<string, 3>
Keep in mind that this approach will not prevent you from accessing an index out of the declared boundaries and set a value on it.
Implementation :
type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift'
type FixedLengthArray<T, L extends number, TObj = [T, ...Array<T>]> =
Pick<TObj, Exclude<keyof TObj, ArrayLengthMutationKeys>>
& {
readonly length: L
[ I : number ] : T
[Symbol.iterator]: () => IterableIterator<T>
}
Tests :
var myFixedLengthArray: FixedLengthArray<string,3>
// Array declaration tests
myFixedLengthArray = [ 'a', 'b', 'c' ] // ? OK
myFixedLengthArray = [ 'a', 'b', 123 ] // ? TYPE ERROR
myFixedLengthArray = [ 'a' ] // ? LENGTH ERROR
myFixedLengthArray = [ 'a', 'b' ] // ? LENGTH ERROR
// Index assignment tests
myFixedLengthArray[1] = 'foo' // ? OK
myFixedLengthArray[1000] = 'foo' // ? SHOULD FAIL
// Methods that mutate array length
myFixedLengthArray.push('foo') // ? MISSING METHOD ERROR
myFixedLengthArray.pop() // ? MISSING METHOD ERROR
// Direct length manipulation
myFixedLengthArray.length = 123 // ? READ-ONLY ERROR
// Destructuring
var [ a ] = myFixedLengthArray // ? OK
var [ a, b ] = myFixedLengthArray // ? OK
var [ a, b, c ] = myFixedLengthArray // ? OK
var [ a, b, c, d ] = myFixedLengthArray // ? SHOULD FAIL
{{ word|striptags('<b>,<a>,<pre>')|raw }}
if you want to allow multiple tags
Isn't this the normal way to free the memory associated with an object?
Yes, it is.
I realized that it automatically invokes the destructor... is this normal?
Make sure that you did not double delete your object.
It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==
, the following should work:
byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);
This will output: YWJjZGVmPT0=
which is abcdef==
encoded in Base64.
Edit:
To decode a Base64 string, simply use Convert.FromBase64String()
. E.g.
string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);
At this point, bytes
will be a byte[]
(not a string
). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:
string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);
This will output the original input string, abcdef==
in this case.
For newbies
Python automatically compiles your script to compiled code, so called byte code, before running it.
Running a script is not considered an import and no .pyc will be created.
For example, if you have a script file abc.py that imports another module xyz.py, when you run abc.py, xyz.pyc will be created since xyz is imported, but no abc.pyc file will be created since abc.py isn’t being imported.
You need to do this via an extension as of the version 1.8.1.
Go to View ? Extensions. This will open Extensions Panel.
Type bookmark
to list all related extensions.
Install
I personally like "Numbered Bookmarks" - it is pretty simple and powerful.
Go to the line you need to create a bookmark.
Click Ctrl + Shift + [some number]
Ex: Ctrl + Shift + 2
Now you can jump to this line from anywhere by pressing Ctrl + number
Ex: Ctrl + 2
I have tried different methods to print a subplot title, look how they work. It's different when i use Latex.
It works with '%%' and 'string'+'%' in a typical case.
If you use Latex it worked using 'string'+'\%'
So in a typical case:
import matplotlib.pyplot as plt
fig,ax = plt.subplots(4,1)
float_number = 4.17
ax[0].set_title('Total: (%1.2f' %float_number + '\%)')
ax[1].set_title('Total: (%1.2f%%)' %float_number)
ax[2].set_title('Total: (%1.2f' %float_number + '%%)')
ax[3].set_title('Total: (%1.2f' %float_number + '%)')
If we use latex:
import matplotlib.pyplot as plt
import matplotlib
font = {'family' : 'normal',
'weight' : 'bold',
'size' : 12}
matplotlib.rc('font', **font)
matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['text.latex.unicode'] = True
fig,ax = plt.subplots(4,1)
float_number = 4.17
#ax[0].set_title('Total: (%1.2f\%)' %float_number) This makes python crash
ax[1].set_title('Total: (%1.2f%%)' %float_number)
ax[2].set_title('Total: (%1.2f' %float_number + '%%)')
ax[3].set_title('Total: (%1.2f' %float_number + '\%)')
We get this: Title example with % and latex
Vim was always faster to start up than Emacs. I'm saying that on any machine, out-of-the-box installs of Vim will start up faster than out-of-the-box installs of Emacs. And I tend to think that after a moderate amount of customisation of either one, Vim will still start up faster than Emacs.
After that, the other practical difference was Emacs' modes. They make your life tremendously easier when editing XML, C/C++/Java/whatever, LaTeX, and most popular languages you can think of. They make you want to keep the editor open for long sessions and work.
All in all, I'll say that Vim pulls you to it for short, fast editing tasks; while Emacs encourages you to dive in for long sessions.
My solution, to only hide the navigation bar, is:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final View decorView = getWindow().getDecorView();
decorView.setOnSystemUiVisibilityChangeListener (new View.OnSystemUiVisibilityChangeListener() {
@Override
public void onSystemUiVisibilityChange(int visibility) {
if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
});
}
@Override
protected void onResume() {
super.onResume();
final int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
final View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(uiOptions);
}
I had the same issue. I resolved it doing the following:
Add the this line to the dispatcher-servlet
file:
<tx:annotation-driven/>
Check above <beans>
section in the same file. These two lines must be present:
xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation= "http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
Also make sure you added @Repository
and @Transactional
where you are using sessionFactory
.
@Repository @Transactional public class ItemDaoImpl implements ItemDao { @Autowired private SessionFactory sessionFactory;
A lot of the answers given so far are pretty good, but you must clearly define what it is exactly that you want.
If you would like a alphabetical character followed by any number of non-white-space characters (note that it would also include numbers!) then you should use this:
^[A-Za-z]\S*$
If you would like to include only alpha-numeric characters and certain symbols, then use this:
^[A-Za-z][A-Za-z0-9!@#$%^&*]*$
Your original question looks like you are trying to include the space character as well, so you probably want something like this:
^[A-Za-z ][A-Za-z0-9!@#$%^&* ]*$
And that is my final answer!
I suggest taking some time to learn more about regular expressions. They are the greatest thing since sliced bread!
Try this syntax reference page (that site in general is very good).
That's odd. Does your program compile and run successfully and only fail on 'Publish' or does it fail on every compile now?
Also, have you perhaps changed the file's properties' Build Action
to something other than Compile
?
from TypeScript you can use native JS array filter() method:
let filteredElements=array.filter(element => element.field == filterValue);
it returns an array with only matching elements from the original array (0, 1 or more)
Reference: https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
The persistence.xml has a jar-file
that you can use. From the Java EE 5 tutorial:
<persistence> <persistence-unit name="OrderManagement"> <description>This unit manages orders and customers. It does not rely on any vendor-specific features and can therefore be deployed to any persistence provider. </description> <jta-data-source>jdbc/MyOrderDB</jta-data-source> <jar-file>MyOrderApp.jar</jar-file> <class>com.widgets.Order</class> <class>com.widgets.Customer</class> </persistence-unit> </persistence>
This file defines a persistence unit
named OrderManagement
, which uses a
JTA-aware data source jdbc/MyOrderDB
. The jar-file
and class
elements specify managed persistence classes: entity classes, embeddable classes, and mapped superclasses. The jar-file
element specifies JAR files that are visible to the packaged persistence unit that contain managed persistence classes, while the class
element explicitly names managed persistence classes.
In the case of Hibernate, have a look at the Chapter2. Setup and configuration too for more details.
EDIT: Actually, If you don't mind not being spec compliant, Hibernate supports auto-detection even in Java SE. To do so, add the hibernate.archive.autodetection
property:
<persistence-unit name="eventractor" transaction-type="RESOURCE_LOCAL">
<!-- This is required to be spec compliant, Hibernate however supports
auto-detection even in JSE.
<class>pl.michalmech.eventractor.domain.User</class>
<class>pl.michalmech.eventractor.domain.Address</class>
<class>pl.michalmech.eventractor.domain.City</class>
<class>pl.michalmech.eventractor.domain.Country</class>
-->
<properties>
<!-- Scan for annotated classes and Hibernate mapping XML files -->
<property name="hibernate.archive.autodetection" value="class, hbm"/>
<property name="hibernate.hbm2ddl.auto" value="validate" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
Laravel Server Requirements mention that BCMath
, Ctype
, JSON
, Mbstring
, OpenSSL
, PDO
, Tokenizer
, and XML
extensions are required. Most of the extensions are installed and enabled by default.
You can run the following command in Ubuntu to make sure the extensions are installed.
sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip
PHP version specific installation (if PHP 7.4 installed)
sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring
You may need other PHP extensions for your composer packages. Find from links below.
PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)
PHP extensions for Ubuntu 18.04 LTS (Bionic)
PHP extensions for Ubuntu 16.04 LTS (Xenial)
For Oracle use:
Select * from v$version;
For SQL server use:
Select @@VERSION as Version
and for MySQL use:
Show variables LIKE "%version%";
I tried changing year
to a different term, and it worked.
public_methods : {
get: function() {
return this._year;
},
set: function(newValue) {
if(newValue > this.originYear) {
this._year = newValue;
this.edition += newValue - this.originYear;
}
}
}
I only know a way around this. The idea is to export that list of pdf files you have into a file. Then split that file into several parts. Then remove pdf files listed in each part.
ls | grep .pdf > list.txt
wc -l list.txt
wc -l is to count how many line the list.txt contains. When you have the idea of how long it is, you can decide to split it in half, forth or something. Using split -l command For example, split it in 600 lines each.
split -l 600 list.txt
this will create a few file named xaa,xab,xac and so on depends on how you split it. Now to "import" each list in those file into command rm, use this:
rm $(<xaa)
rm $(<xab)
rm $(<xac)
Sorry for my bad english.
You could easily write such a function in about ten lines of code:
String combine(String[] s, String glue)
{
int k = s.length;
if ( k == 0 )
{
return null;
}
StringBuilder out = new StringBuilder();
out.append( s[0] );
for ( int x=1; x < k; ++x )
{
out.append(glue).append(s[x]);
}
return out.toString();
}
Determine if string is a date, even if string is a non-standard format
(strtotime doesn't accept any custom format)
<?php
function validateDateTime($dateStr, $format)
{
date_default_timezone_set('UTC');
$date = DateTime::createFromFormat($format, $dateStr);
return $date && ($date->format($format) === $dateStr);
}
// These return true
validateDateTime('2001-03-10 17:16:18', 'Y-m-d H:i:s');
validateDateTime('2001-03-10', 'Y-m-d');
validateDateTime('2001', 'Y');
validateDateTime('Mon', 'D');
validateDateTime('March 10, 2001, 5:16 pm', 'F j, Y, g:i a');
validateDateTime('March 10, 2001, 5:16 pm', 'F j, Y, g:i a');
validateDateTime('03.10.01', 'm.d.y');
validateDateTime('10, 3, 2001', 'j, n, Y');
validateDateTime('20010310', 'Ymd');
validateDateTime('05-16-18, 10-03-01', 'h-i-s, j-m-y');
validateDateTime('Monday 8th of August 2005 03:12:46 PM', 'l jS \of F Y h:i:s A');
validateDateTime('Wed, 25 Sep 2013 15:28:57', 'D, d M Y H:i:s');
validateDateTime('17:03:18 is the time', 'H:m:s \i\s \t\h\e \t\i\m\e');
validateDateTime('17:16:18', 'H:i:s');
// These return false
validateDateTime('2001-03-10 17:16:18', 'Y-m-D H:i:s');
validateDateTime('2001', 'm');
validateDateTime('Mon', 'D-m-y');
validateDateTime('Mon', 'D-m-y');
validateDateTime('2001-13-04', 'Y-m-d');
With reference to man ssh-keygen
, the length of a DSA key is restricted to exactly 1024 bit to remain compliant with NIST's FIPS 186-2. Nonetheless, longer DSA keys are theoretically possible; FIPS 186-3 explicitly allows them. Furthermore, security is no longer guaranteed with 1024 bit long RSA or DSA keys.
In conclusion, a 2048 bit RSA key is currently the best choice.
Establishing a secure SSH connection entails more than selecting safe encryption key pair technology. In view of Edward Snowden's NSA revelations, one has to be even more vigilant than what previously was deemed sufficient.
To name just one example, using a safe key exchange algorithm is equally important. Here is a nice overview of current best SSH hardening practices.
To read one byte:
file.read(1)
8 bits is one byte.
You could use Colker, which is built for this, but you'll have to remove the search box, and search feature code, because searching isn't compatible with the type of content you intend to use.
Page contents are stored in a java-script array
, and the "page
" (eg: ?page=pagename
) URL parameter determines which page content to serve.
byte[] result = new byte[a.length + b.length];
// copy a to result
System.arraycopy(a, 0, result, 0, a.length);
// copy b to result
System.arraycopy(b, 0, result, a.length, b.length);
Based on comment of @alessandro-pezzato.
Run multiples commands by using &
between the commands.
Example:
$ sleep 3 & sleep 5 & sleep 2 &
It's will execute the commands in background.
Beginning PowerShell 5.0 New-Item
, Remove-Item
, and Get-ChildItem
have been enhanced to support creating and managing symbolic links. The ItemType parameter for New-Item
accepts a new value, SymbolicLink. Now you can create symbolic links in a single line by running the New-Item cmdlet.
New-Item -ItemType SymbolicLink -Path "C:\temp" -Name "calc.lnk" -Value "c:\windows\system32\calc.exe"
Be Carefull a SymbolicLink is different from a Shortcut, shortcuts are just a file. They have a size (A small one, that just references where they point) and they require an application to support that filetype in order to be used. A symbolic link is filesystem level, and everything sees it as the original file. An application needs no special support to use a symbolic link.
Anyway if you want to create a Run As Administrator shortcut using Powershell you can use
$file="c:\temp\calc.lnk"
$bytes = [System.IO.File]::ReadAllBytes($file)
$bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON (Use –bor to set RunAsAdministrator option and –bxor to unset)
[System.IO.File]::WriteAllBytes($file, $bytes)
If anybody want to change something else in a .LNK file you can refer to official Microsoft documentation.
Sort of solution using metatable...
local function preparetable(t)
setmetatable(t,{__newindex=function(self,k,v) rawset(self,v,true) end})
end
local workingtable={}
preparetable(workingtable)
table.insert(workingtable,123)
table.insert(workingtable,456)
if workingtable[456] then
...
end
The example in Liam's answer saves the file as string in a single line. I prefer to add formatting. Someone in the future may want to change some value manually in the file. If you add formatting it's easier to do so.
The following adds basic JSON indentation:
string json = JsonConvert.SerializeObject(_data.ToArray(), Formatting.Indented);
create or replace procedure point_triangle
AS
BEGIN
FOR thisteam in (select FIRSTNAME,LASTNAME,SUM(PTS) from PLAYERREGULARSEASON where TEAM = 'IND' group by FIRSTNAME, LASTNAME order by SUM(PTS) DESC)
LOOP
dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.PTS);
END LOOP;
END;
/
To use the default system proxies (e.g. from the http_support environment variable), the following works for the current request (without installing it into urllib2 globally):
url = 'http://www.example.com/'
proxy = urllib2.ProxyHandler()
opener = urllib2.build_opener(proxy)
in_ = opener.open(url)
in_.read()
I'll provide an objective answer based on my experience with both, I'll also skip the theory behind them, assuming you already know it and/or other answers has already provided enough.
RabbitMQ: I'd pick this one if my requirements are simple enough to deal with system communication through channels/queues, retention and streaming is not a requirement. For e.g. When the manufacture system built the asset it does notify the agreement system to configure the contracts and so on.
Kafka: Event sourcing requirement mainly, when you may need to deal with streams (sometimes infinite), huge amount of data at once properly balanced, replay offsets in order to ensure a given state and so on. Keep in mind that this architecture brings more complexity as well, since it does include concepts such as topics/partitions/brokers/tombstone messages, etc. as a first class importance.
I'm assuming you're talking about com.google.common.base.Predicate<T>
from Guava.
From the API:
Determines a
true
orfalse
value for a given input. For example, aRegexPredicate
might implementPredicate<String>
, and return true for any string that matches its given regular expression.
This is essentially an OOP abstraction for a boolean
test.
For example, you may have a helper method like this:
static boolean isEven(int num) {
return (num % 2) == 0; // simple
}
Now, given a List<Integer>
, you can process only the even numbers like this:
List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
for (int number : numbers) {
if (isEven(number)) {
process(number);
}
}
With Predicate
, the if
test is abstracted out as a type. This allows it to interoperate with the rest of the API, such as Iterables
, which have many utility methods that takes Predicate
.
Thus, you can now write something like this:
Predicate<Integer> isEven = new Predicate<Integer>() {
@Override public boolean apply(Integer number) {
return (number % 2) == 0;
}
};
Iterable<Integer> evenNumbers = Iterables.filter(numbers, isEven);
for (int number : evenNumbers) {
process(number);
}
Note that now the for-each loop is much simpler without the if
test. We've reached a higher level of abtraction by defining Iterable<Integer> evenNumbers
, by filter
-ing using a Predicate
.
Iterables.filter
Predicate
allows Iterables.filter
to serve as what is called a higher-order function. On its own, this offers many advantages. Take the List<Integer> numbers
example above. Suppose we want to test if all numbers are positive. We can write something like this:
static boolean isAllPositive(Iterable<Integer> numbers) {
for (Integer number : numbers) {
if (number < 0) {
return false;
}
}
return true;
}
//...
if (isAllPositive(numbers)) {
System.out.println("Yep!");
}
With a Predicate
, and interoperating with the rest of the libraries, we can instead write this:
Predicate<Integer> isPositive = new Predicate<Integer>() {
@Override public boolean apply(Integer number) {
return number > 0;
}
};
//...
if (Iterables.all(numbers, isPositive)) {
System.out.println("Yep!");
}
Hopefully you can now see the value in higher abstractions for routines like "filter all elements by the given predicate", "check if all elements satisfy the given predicate", etc make for better code.
Unfortunately Java doesn't have first-class methods: you can't pass methods around to Iterables.filter
and Iterables.all
. You can, of course, pass around objects in Java. Thus, the Predicate
type is defined, and you pass objects implementing this interface instead.
According to Reserved IP addresses there are 588,514,304 reserved addresses and since there are 4,294,967,296 (2^32) IPv4 addressess in total, there are 3,706,452,992 public addresses.
And too many addresses in this post.
You should add the g
modifier so that sed performs a global substitution of the contents of the pattern buffer:
echo dog dog dos | sed -e 's:dog:log:g'
For a fantastic documentation on sed, check http://www.grymoire.com/Unix/Sed.html. This global flag is explained here: http://www.grymoire.com/Unix/Sed.html#uh-6
The official documentation for GNU sed
is available at http://www.gnu.org/software/sed/manual/
You had several issues with your code.
1) Missing a closing brace, }
, within your rules
.
2) In this case, there is no reason to use a function for the required
rule. By default, the plugin can handle checkbox
and radio
inputs just fine, so using true
is enough. However, this will simply do the same logic as in your original function and verify that at least one is checked.
3) If you also want only a maximum of two to be checked, then you'll need to apply the maxlength
rule.
4) The messages
option was missing the rule specification. It will work, but the one custom message would apply to all rules on the same field.
5) If a name
attribute contains brackets, you must enclose it within quotes.
DEMO: http://jsfiddle.net/K6Wvk/
$(document).ready(function () {
$('#formid').validate({ // initialize the plugin
rules: {
'test[]': {
required: true,
maxlength: 2
}
},
messages: {
'test[]': {
required: "You must check at least 1 box",
maxlength: "Check no more than {0} boxes"
}
}
});
});
Use moment.js library, for example:
var time = date_future - date_now;
var seconds = moment.duration(time).seconds();
var minutes = moment.duration(time).minutes();
var hours = moment.duration(time).hours();
var days = moment.duration(time).days();
Mark F's solution is awesome but it's not supported by old browsers. Kennebec's solution is awesome and supported by old browsers but doesn't support regex.
So, if you're looking for a solution that splits your string only once, that is supported by old browsers and supports regex, here's my solution:
String.prototype.splitOnce = function(regex)_x000D_
{_x000D_
var match = this.match(regex);_x000D_
if(match)_x000D_
{_x000D_
var match_i = this.indexOf(match[0]);_x000D_
_x000D_
return [this.substring(0, match_i),_x000D_
this.substring(match_i + match[0].length)];_x000D_
}_x000D_
else_x000D_
{ return [this, ""]; }_x000D_
}_x000D_
_x000D_
var str = "something/////another thing///again";_x000D_
_x000D_
alert(str.splitOnce(/\/+/)[1]);
_x000D_
Nobody has mentioned the Ion or Glide library. they work very well.
It's easier to handle compared to a WebView.
Superkey
A superkey is a combination of attributes that can be uniquely used to identify a
database record. A table might have many superkeys.Candidate keys are a special subset
of superkeys that do not have any extraneous information in them.
Examples: Imagine a table with the fields <Name>, <Age>, <SSN> and <Phone Extension>.
This table has many possible superkeys. Three of these are <SSN>, <Phone Extension, Name>
and <SSN, Name>.Of those listed, only <SSN> is a **candidate key**, as the others
contain information not necessary to uniquely identify records.
This happened to me, and once I removed this: enctype="multipart/form-data" It started working without the warning
You can access the namespace's dictionary with vars():
>>> import argparse
>>> args = argparse.Namespace()
>>> args.foo = 1
>>> args.bar = [1,2,3]
>>> d = vars(args)
>>> d
{'foo': 1, 'bar': [1, 2, 3]}
You can modify the dictionary directly if you wish:
>>> d['baz'] = 'store me'
>>> args.baz
'store me'
Yes, it is okay to access the __dict__ attribute. It is a well-defined, tested, and guaranteed behavior.
Code updated 2015/04/22.
// Get real path for our folder
$rootPath = realpath('folder-to-zip');
// Initialize archive object
$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
// Get real path for our folder
$rootPath = realpath('folder-to-zip');
// Initialize archive object
$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Initialize empty "delete list"
$filesToDelete = array();
// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
// Add current file to "delete list"
// delete it later cause ZipArchive create archive only after calling close function and ZipArchive lock files until archive created)
if ($file->getFilename() != 'important.txt')
{
$filesToDelete[] = $filePath;
}
}
}
// Zip archive will be created only after closing object
$zip->close();
// Delete all files from "delete list"
foreach ($filesToDelete as $file)
{
unlink($file);
}
My simple solution, it doesn't need any external plugin and for common cases should be enough:
/**
* Trigger a callback when the selected images are loaded:
* @param {String} selector
* @param {Function} callback
*/
var onImgLoad = function(selector, callback){
$(selector).each(function(){
if (this.complete || /*for IE 10-*/ $(this).height() > 0) {
callback.apply(this);
}
else {
$(this).on('load', function(){
callback.apply(this);
});
}
});
};
use it like this:
onImgLoad('img', function(){
// do stuff
});
for example, to fade in your images on load you can do:
$('img').hide();
onImgLoad('img', function(){
$(this).fadeIn(700);
});
Or as alternative, if you prefer a jquery plugin-like approach:
/**
* Trigger a callback when 'this' image is loaded:
* @param {Function} callback
*/
(function($){
$.fn.imgLoad = function(callback) {
return this.each(function() {
if (callback) {
if (this.complete || /*for IE 10-*/ $(this).height() > 0) {
callback.apply(this);
}
else {
$(this).on('load', function(){
callback.apply(this);
});
}
}
});
};
})(jQuery);
and use it in this way:
$('img').imgLoad(function(){
// do stuff
});
for example:
$('img').hide().imgLoad(function(){
$(this).fadeIn(700);
});
In my case an additional file not belonging to the database was inside the database folder. Mysql found the folder not empty after dropping all tables which triggered the error. I remove the file and the drop database worked fine.
Since OS X Lion, the scrollbar on websites are hidden by default and only visible once you start scrolling. Personally, I prefer the hidden scrollbar, but in case you really need it, you can overwrite the default and force the scrollbar in WebKit browsers back like this:
::-webkit-scrollbar {
-webkit-appearance: none;
width: 7px;
}
::-webkit-scrollbar-thumb {
border-radius: 4px;
background-color: rgba(0,0,0,.5);
-webkit-box-shadow: 0 0 1px rgba(255,255,255,.5);
}
_x000D_
You could also get this error when JRE is not set. If so, try adding JRE System Library to your project.
Under Eclipse IDE:
For the OP's command:
select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0, Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from #tmp_CTF**
I get this error:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.
when debugging something like this split the long line up so you'll get a better row number:
select compid
,2
, convert(datetime
, '01/01/'
+ CONVERT(char(4)
,cal_yr)
,101)
,0
, Update_dt
, th1
, th2
, th3_pc
, Update_id
, Update_dt
,1
from #tmp_CTF**
this now results in:
Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.
which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:
from [#tmp_CTF**]
if that is the table name.
will the height attribute stretch the image beyond its native resolution? If I have a image with a height of say 420 pixels, I can't get css to stretch the image beyond the native resolution to fill the height of the viewport.
I am getting pretty close results with:
.rightdiv img {
max-width: 25vw;
min-height: 100vh;
}
the 100vh is getting pretty close, with just a few pixels left over at the bottom for some reason.
You could always use Replace()
since you're performing this on the workbook's Name, which will almost certainly end with .xlsm
by virtue of using VBA.
Using ActiveWorkbook per your example:
Replace(Application.ActiveWorkbook.Name, ".xlsm", "")
Using ThisWorkbook:
Replace(Application.ThisWorkbook.Name, ".xlsm", "")
It means that there have been other commits pushed to the remote repository that differ from your commits. You can usually solve this with a
git pull
before you push
Ultimately, "fast-forward" means that the commits can be applied directly on top of the working tree without requiring a merge.
You need to use the -F
option:
-F/--form <name=content> Specify HTTP multipart POST data (H)
Try this:
curl \
-F "userid=1" \
-F "filecomment=This is an image file" \
-F "image=@/home/user1/Desktop/test.jpg" \
localhost/uploader.php
Use --format
option to get only the IP address instead whole container info:
sudo docker inspect --format '{{ .NetworkSettings.IPAddress }}' <CONTAINER ID>
What's the first part of your Subversion repository URL?
I can't guarantee the first four since it's possible to reconfigure everything to use different ports, of if you go through a proxy of some sort.
If you're using a VPN, you may have to configure your VPN client to reroute these to their correct ports. A lot of places don't configure their correctly VPNs to do this type of proxying. It's either because they have some sort of anal-retentive IT person who's being overly security conscious, or because they simply don't know any better. Even worse, they'll give you a client where this stuff can't be reconfigured.
The only way around that is to log into a local machine over the VPN, and then do everything from that system.
Use var
instead of int
for your clicks
variable generation and onClick
instead of click
as your function name:
var clicks = 0;
function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
_x000D_
<button type="button" onClick="onClick()">Click me</button>
<p>Clicks: <a id="clicks">0</a></p>
_x000D_
In JavaScript variables are declared with the var
keyword. There are no tags like int
, bool
, string
... to declare variables. You can get the type of a variable with 'typeof(yourvariable)', more support about this you find on Google.
And the name 'click' is reserved by JavaScript for function names so you have to use something else.
This is a sample I used for my unit test. I created a list of class object. Then I used forloop to add 'X' number of objects that I am expecting from the service. This way you can add/initialize a List for any given size.
public void TestMethod1()
{
var expected = new List<DotaViewer.Interface.DotaHero>();
for (int i = 0; i < 22; i++)//You add empty initialization here
{
var temp = new DotaViewer.Interface.DotaHero();
expected.Add(temp);
}
var nw = new DotaHeroCsvService();
var items = nw.GetHero();
CollectionAssert.AreEqual(expected,items);
}
Hope I was of help to you guys.
You can also create a batch file like the following if you need finer granularity between calls:
:loop
CallYour.Exe
timeout /t timeToWaitBetweenCallsInSeconds /nobreak
goto :loop
Example: Read json from file
/* test.json */
{
"appDesc": {
"description": "SomeDescription",
"message": "SomeMessage"
},
"appName": {
"description": "Home",
"message": "Welcome",
"imp":["awesome","best","good"]
}
}
void readJson()
{
QString val;
QFile file;
file.setFileName("test.json");
file.open(QIODevice::ReadOnly | QIODevice::Text);
val = file.readAll();
file.close();
qWarning() << val;
QJsonDocument d = QJsonDocument::fromJson(val.toUtf8());
QJsonObject sett2 = d.object();
QJsonValue value = sett2.value(QString("appName"));
qWarning() << value;
QJsonObject item = value.toObject();
qWarning() << tr("QJsonObject of description: ") << item;
/* in case of string value get value and convert into string*/
qWarning() << tr("QJsonObject[appName] of description: ") << item["description"];
QJsonValue subobj = item["description"];
qWarning() << subobj.toString();
/* in case of array get array and convert into string*/
qWarning() << tr("QJsonObject[appName] of value: ") << item["imp"];
QJsonArray test = item["imp"].toArray();
qWarning() << test[1].toString();
}
OUTPUT
QJsonValue(object, QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) )
"QJsonObject of description: " QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"})
"QJsonObject[appName] of description: " QJsonValue(string, "Home")
"Home"
"QJsonObject[appName] of value: " QJsonValue(array, QJsonArray(["awesome","best","good"]) )
"best"
Example: Read json from string
Assign json to string as below and use the readJson()
function shown before:
val =
' {
"appDesc": {
"description": "SomeDescription",
"message": "SomeMessage"
},
"appName": {
"description": "Home",
"message": "Welcome",
"imp":["awesome","best","good"]
}
}';
OUTPUT
QJsonValue(object, QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) )
"QJsonObject of description: " QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"})
"QJsonObject[appName] of description: " QJsonValue(string, "Home")
"Home"
"QJsonObject[appName] of value: " QJsonValue(array, QJsonArray(["awesome","best","good"]) )
"best"
Hopefully someone else is saved by reading this.
We encountered an issue with webkit based browsers doing:
window.open("webpage.htm", "_self");
The browser would lockup and die if we had too many DOM nodes. When we switched our code to following the accepted answer of:
location.href = "webpage.html";
all was good. It took us awhile to figure out what was causing the issue, since it wasn't obvious what made our page periodically fail to load.
tableColumns
null
for all columns as in SELECT * FROM ...
new String[] { "column1", "column2", ... }
for specific columns as in SELECT column1, column2 FROM ...
- you can also put complex expressions here:new String[] { "(SELECT max(column1) FROM table1) AS max" }
would give you a column named max
holding the max value of column1
whereClause
WHERE
without that keyword, e.g. "column1 > 5"
?
for things that are dynamic, e.g. "column1=?"
-> see whereArgs
whereArgs
?
in whereClause
in the order they appearthe others
whereClause
the statement after the keyword or null
if you don't use it.Example
String[] tableColumns = new String[] {
"column1",
"(SELECT max(column1) FROM table2) AS max"
};
String whereClause = "column1 = ? OR column1 = ?";
String[] whereArgs = new String[] {
"value1",
"value2"
};
String orderBy = "column1";
Cursor c = sqLiteDatabase.query("table1", tableColumns, whereClause, whereArgs,
null, null, orderBy);
// since we have a named column we can do
int idx = c.getColumnIndex("max");
is equivalent to the following raw query
String queryString =
"SELECT column1, (SELECT max(column1) FROM table1) AS max FROM table1 " +
"WHERE column1 = ? OR column1 = ? ORDER BY column1";
sqLiteDatabase.rawQuery(queryString, whereArgs);
By using the Where/Bind -Args version you get automatically escaped values and you don't have to worry if input-data contains '
.
Unsafe: String whereClause = "column1='" + value + "'";
Safe: String whereClause = "column1=?";
because if value contains a '
your statement either breaks and you get exceptions or does unintended things, for example value = "XYZ'; DROP TABLE table1;--"
might even drop your table since the statement would become two statements and a comment:
SELECT * FROM table1 where column1='XYZ'; DROP TABLE table1;--'
using the args version XYZ'; DROP TABLE table1;--
would be escaped to 'XYZ''; DROP TABLE table1;--'
and would only be treated as a value. Even if the '
is not intended to do bad things it is still quite common that people have it in their names or use it in texts, filenames, passwords etc. So always use the args version. (It is okay to build int
and other primitives directly into whereClause
though)
here is the one working fine:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
app = QApplication(sys.argv)
web = QWebView()
web.load(QUrl("http://www.yahoo.com"))
printer = QPrinter()
printer.setPageSize(QPrinter.A4)
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName("fileOK.pdf")
def convertIt():
web.print_(printer)
print("Pdf generated")
QApplication.exit()
QObject.connect(web, SIGNAL("loadFinished(bool)"), convertIt)
sys.exit(app.exec_())
For UNIX:
As Stephen C has suggested, changing the maximum file descriptor value to a higher value avoids this problem.
Try looking at your present file descriptor capacity:
$ ulimit -n
Then change the limit according to your requirements.
$ ulimit -n <value>
Note that this just changes the limits in the current shell and any child / descendant process. To make the change "stick" you need to put it into the relevant shell script or initialization file.
No. I don't see any advantage. Second one is more straitforward.
btw: Second style is found in every corners of JDK source.
By my side, using Chrome navigator, I had to use DataView() to read an arrayBuffer
function _arrayBufferToBase64( tabU8A ) {
var binary = '';
let lecteur_de_donnees = new DataView(tabU8A);
var len = lecteur_de_donnees.byteLength;
var chaine = '';
var pos1;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode( lecteur_de_donnees.getUint8( i ) );
}
chaine = window.btoa( binary )
return chaine;}
You can use this to fix error:
zcat {address_sql_database(.tar.gz)} | mysql -u root -p {database_name} --binary-mode
Here's a simple little function that will rbind two datasets together after auto-detecting what columns are missing from each and adding them with all NA
s.
For whatever reason this returns MUCH faster on larger datasets than using the merge
function.
fastmerge <- function(d1, d2) {
d1.names <- names(d1)
d2.names <- names(d2)
# columns in d1 but not in d2
d2.add <- setdiff(d1.names, d2.names)
# columns in d2 but not in d1
d1.add <- setdiff(d2.names, d1.names)
# add blank columns to d2
if(length(d2.add) > 0) {
for(i in 1:length(d2.add)) {
d2[d2.add[i]] <- NA
}
}
# add blank columns to d1
if(length(d1.add) > 0) {
for(i in 1:length(d1.add)) {
d1[d1.add[i]] <- NA
}
}
return(rbind(d1, d2))
}
You can also use an express framework
app.get("/:id",function(req,res)
{
var id = req.params.id;
res.render("home.ejs",{identity : id});
});
Express file, which receives a JS variable identity from node.js
<a href = "/any_route/<%=identity%>
includes identity JS variable into your href
without a trouble enter
$("#date").datepicker('getDate').getMonth() + 1;
The month on the datepicker is 0 based (0-11), so add 1 to get the month as it appears in the date.
One reason: the literal 0
has a bad tendency to acquire the type int
, e.g. in perfect argument forwarding or more in general as argument with templated type.
Another reason: readability and clarity of code.
I see that you tagged bash, but Perl would also be a good way to do this:
perl -p -e '`chmod 755 $_`' file.txt
You could also apply a regex to make sure you're getting the right files, e.g. to only process .txt files:
perl -p -e 'if(/\.txt$/) `chmod 755 $_`' file.txt
To "preview" what's happening, just replace the backticks with double quotes and prepend print
:
perl -p -e 'if(/\.txt$/) print "chmod 755 $_"' file.txt
Assuming you have access to them (the properties you've declared are protected
), you use them like this:
Person tom = new Person();
tom.Title = "A title";
string hisTitle = tom.Title;
These are properties. They're basically pairs of getter/setter methods (although you can have just a getter, or just a setter) with appropriate metadata. The example you've given is of automatically implemented properties where the compiler is adding a backing field. You can write the code yourself though. For example, the Title
property you've declared is like this:
private string title; // Backing field
protected string Title
{
get { return title; } // Getter
set { title = value; } // Setter
}
... except that the backing field is given an "unspeakable name" - one you can't refer to in your C# code. You're forced to go through the property itself.
You can make one part of a property more restricted than another. For example, this is quite common:
private string foo;
public string Foo
{
get { return foo; }
private set { foo = value; }
}
or as an automatically implemented property:
public string Foo { get; private set; }
Here the "getter" is public but the "setter" is private.
This seems weird, but you can try setting vertical-align: top
in the CSS
for the inputs. That fixes it in IE8, at least.
To solve this with homebrew
, you can temporarily backdate homebrew-core
and set the HOMEBREW_NO_AUTO_UPDATE
variable to hold it in place:
cd `brew --repo homebrew/core`
git checkout f2a764ef944b1080be64bd88dca9a1d80130c558
export HOMEBREW_NO_AUTO_UPDATE=1
brew install python
I don't recommend permanently backdating homebrew-core, as you will miss out on security patches, but it is useful for testing purposes.
You can also extract old versions of homebrew formulae into your own tap (tap_owner/tap_name) using the brew extract
command:
brew extract python tap_owner/tap_name --version=3.6.5
Give the name to both of the buttons and Get the check the value from form.
<div>
<input name="submitButton" type="submit" value="Register" />
</div>
<div>
<input name="cancelButton" type="submit" value="Cancel" />
</div>
On controller side :
public ActionResult Save(FormCollection form)
{
if (this.httpContext.Request.Form["cancelButton"] !=null)
{
// return to the action;
}
else if(this.httpContext.Request.Form["submitButton"] !=null)
{
// save the oprtation and retrun to the action;
}
}
This is just the syntax of the case statement, it looks like this.
SELECT
CASE
WHEN FRUIT = 'A' THEN 'APPLE'
WHEN FRUIT = 'B' THEN 'BANANA'
END AS FRUIT
FROM FRUIT_TABLE;
As a reminder remember; no assignment is performed the value becomes the column contents. (If you wanted to assign that to a variable you would put it before the CASE statement).
Public Protected Default and private are access modifiers.
They are meant for encapsulation, or hiding and showing contents of the class.
Private is not accessible outside the class Default is accessible only in the package. Protected in package as well as any class which extends it. Public is open for all.
Normally, member variables are defined private, but member methods are public.
AFAIK the values are:
700 for the hidden directory ".ssh" where key file is located
600 for the keyfile "id_rsa"
Had issues using the code in the answer provided by @haynar above (wouldn't play on Chrome), and it seems that one of the more modern ways to ensure it plays is to use the video tag
Example:
<video controls="controls" width="800" height="600"
name="Video Name" src="http://www.myserver.com/myvideo.mov"></video>
This worked like a champ for my .mov file (generated from Keynote) in both Safari and Chrome, and is listed as supported in most modern browsers (The video tag is supported in Internet Explorer 9+, Firefox, Opera, Chrome, and Safari.)
Note: Will work in IE / etc.. if you use MP4 (Mov is not officially supported by those guys)
Make variables are not exported into the environment of processes make invokes... by default. However you can use make's export
to force them to do so. Change:
test: NODE_ENV = test
to this:
test: export NODE_ENV = test
(assuming you have a sufficiently modern version of GNU make >= 3.77 ).
I think this uses more native capabilities
//printing the links to a file
$ echo "https://stackoverflow.com/questions/3110444/
https://stackoverflow.com/questions/8445445/
https://stackoverflow.com/questions/4875446/" > links_file.txt
$ xargs curl < links_file.txt
Enjoy!
Try this:
MERGE INTO table1 t1
USING
(
-- For more complicated queries you can use WITH clause here
SELECT * FROM table2
)t2
ON(t1.id = t2.id)
WHEN MATCHED THEN UPDATE SET
t1.name = t2.name,
t1.desc = t2.desc;
you can as well try:
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
if scanner.Err() != nil {
// handle error.
}
Try
var e = document.getElementById("mySelect");
var selectedOp = e.options[e.selectedIndex].text;
location.origin+location.pathname+location.search+location.hash;
and
location.href
does the same.
You're looking for the cunningly named Registry.GetValue
method.
@joe : Many thanks, this was a good heads up!
I had a slightly harder problem: 1. sending an AJAX request with POST data, for the server to produce a ZIP file 2. getting a response back 3. download the ZIP file
So that's how I did it (using JQuery to handle the AJAX request):
Initial post request:
var parameters = {
pid : "mypid",
"files[]": ["file1.jpg","file2.jpg","file3.jpg"]
}
var options = {
url: "request/url",//replace with your request url
type: "POST",//replace with your request type
data: parameters,//see above
context: document.body,//replace with your contex
success: function(data){
if (data) {
if (data.path) {
//Create an hidden iframe, with the 'src' attribute set to the created ZIP file.
var dlif = $('<iframe/>
',{'src':data.path}).hide();
//Append the iFrame to the context
this.append(dlif);
} else if (data.error) {
alert(data.error);
} else {
alert('Something went wrong');
}
}
}
};
$.ajax(options);
The "request/url" handles the zip creation (off topic, so I wont post the full code) and returns the following JSON object. Something like:
//Code to create the zip file
//......
//Id of the file
$zipid = "myzipfile.zip"
//Download Link - it can be prettier
$dlink = 'http://'.$_SERVER["SERVER_NAME"].'/request/download&file='.$zipid;
//JSON response to be handled on the client side
$result = '{"success":1,"path":"'.$dlink.'","error":null}';
header('Content-type: application/json;');
echo $result;
The "request/download" can perform some security checks, if needed, and generate the file transfer:
$fn = $_GET['file'];
if ($fn) {
//Perform security checks
//.....check user session/role/whatever
$result = $_SERVER['DOCUMENT_ROOT'].'/path/to/file/'.$fn;
if (file_exists($result)) {
header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename='.basename($result));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($result));
ob_clean();
flush();
readfile($result);
@unlink($result);
}
}
Which class ? Do you mean the Joda DateTime class ? If so, you can simply call getMillis()
on each, and perform the appropriate subtraction/scaling.
I would recommend Joda for date/time work, btw, due to it's useful and intuitive API, and its thread-safety for formatting/parsing options.
You need to change ||
to &&
so that both conditions must be true to enter the loop.
while(myChar != 'n' && myChar != 'N')
As said, JsonMappingException: out of START_ARRAY token
exception is thrown by Jackson object mapper as it's expecting an Object {}
whereas it found an Array [{}]
in response.
A simpler solution could be replacing the method getLocations
with:
public static List<Location> getLocations(InputStream inputStream) {
ObjectMapper objectMapper = new ObjectMapper();
try {
TypeReference<List<Location>> typeReference = new TypeReference<>() {};
return objectMapper.readValue(inputStream, typeReference);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
On the other hand, if you don't have a pojo like Location
, you could use:
TypeReference<List<Map<String, Object>>> typeReference = new TypeReference<>() {};
return objectMapper.readValue(inputStream, typeReference);
You could do this:
String json = new ObjectMapper().writeValueAsString(yourObjectHere);
Your two examples are the only things I have ever used the Rows
and Columns
properties for, but in theory you could do anything with them that can be done with a Range
object.
The return type of those properties is itself a Range
, so you can do things like:
Dim myRange as Range
Set myRange = Sheet1.Range(Cells(2,2),Cells(8,8))
myRange.Rows(3).Select
Which will select the third row in myRange
(Cells B4:H4 in Sheet1).
update: To do what you want to do, you could use:
Dim interestingRows as Range
Set interestingRows = Sheet1.Range(startRow & ":" & endRow)
update #2: Or, to get a subset of rows from within a another range:
Dim someRange As Range
Dim interestingRows As Range
Set myRange = Sheet1.Range(Cells(2, 2), Cells(8, 8))
startRow = 3
endRow = 6
Set interestingRows = Range(myRange.Rows(startRow), myRange.Rows(endRow))
suppose ROM is string variable which equals "strval" you can simply do
String value= " \" "+ROM+" \" ";
it will be stored as
value= " "strval" ";
Below code will remove all punctuation marks as well as non alphabetic characters. Copied from their book.
http://www.nltk.org/book/ch01.html
import nltk
s = "I can't do this now, because I'm so tired. Please give me some time. @ sd 4 232"
words = nltk.word_tokenize(s)
words=[word.lower() for word in words if word.isalpha()]
print(words)
output
['i', 'ca', 'do', 'this', 'now', 'because', 'i', 'so', 'tired', 'please', 'give', 'me', 'some', 'time', 'sd']
keySet() only returns a set of keys from your hashmap, you should iterate this key set and the get the value from the hashmap using these keys.
In your example, the type of the hashmap's key is TypeKey
, but you specified TypeValue
in your generic for-loop, so it cannot be compiled. You should change it to :
for (TypeKey name: example.keySet()){
String key = name.toString();
String value = example.get(name).toString();
System.out.println(key + " " + value);
}
Update for Java8:
example.entrySet().forEach(entry->{
System.out.println(entry.getKey() + " " + entry.getValue());
});
If you don't require to print key value and just need the hashmap value, you can use others' suggestions.
Another question: Is this collection is zero base? I mean if it has 1 key and value will it size be 0 or 1?
The collection returned from keySet()
is a Set.You cannot get the value from a Set using an index, so it is not a question of whether it is zero-based or one-based. If your hashmap has one key, the keySet() returned will have one entry inside, and its size will be 1.
u just used attribute
android:background="#ColorCode" for colors
if your image save in drawable folder then used :-
android:background="@drawable/ImageName" for image setting
I was a great fan of submit()
but not anymore.
In the web page that I test, I enter username and password and click Login. When I invoked usernametextbox.submit()
, password textbox is cleared (becomes empty) and login keeps failing.
After breaking my head for sometime, when I replaced usernametextbox.submit()
with loginbutton.click()
, it worked like a magic.
<?php
function plusTimetoOldtime($Old_Time,$getFormat,$Plus_Time) {
return date($getFormat,strtotime(date($getFormat,$Old_Time).$Plus_Time));
}
$Old_Time = strtotime("now");
$Plus_Time = '+1 day';
$getFormat = 'Y-m-d H:i:s';
echo plusTimetoOldtime($Old_Time,$getFormat,$Plus_Time);
?>
An update to @Aliostads answer using the more moden IHttpActionResult
introduced in Web API 2.
public class TryController : ApiController
{
public IHttpActionResult GetUser(int userId, DateTime lastModifiedAtClient)
{
var user = new DataEntities().Users.First(p => p.Id == userId);
if (user.LastModified <= lastModifiedAtClient)
{
return StatusCode(HttpStatusCode.NotModified);
// If you would like to return a Http Status code with any object instead:
// return Content(HttpStatusCode.InternalServerError, "My Message");
}
return Ok(user);
}
}
For me, I got this error by not setting USE_X_FORWARDED_HOST
to true. From the docs:
This should only be enabled if a proxy which sets this header is in use.
My hosting service wrote explicitly in their documentation that this setting must be used, and I get this 400 error if I forget it.
The file msrdo20.dll is missing from the installation.
According to the Support Statement for Visual Basic 6.0 on Windows Vista, Windows Server 2008 and Windows 7 this file should be distributed with the application.
I'm not sure why it isn't, but my solution is to place the file somewhere on the machine, and register it using regsvr32 in the command line, eg:
regsvr32 c:\windows\system32\msrdo20.dll
In an ideal world you would package this up with the redistributable.
Instead of using 2 separate queries, you can use aggregate()
in a single query:
Aggregate "$facet" can be fetch more quickly, the Total Count and the Data with skip & limit
db.collection.aggregate([
//{$sort: {...}}
//{$match:{...}}
{$facet:{
"stage1" : [ {"$group": {_id:null, count:{$sum:1}}} ],
"stage2" : [ { "$skip": 0}, {"$limit": 2} ]
}},
{$unwind: "$stage1"},
//output projection
{$project:{
count: "$stage1.count",
data: "$stage2"
}}
]);
output as follows:-
[{
count: 50,
data: [
{...},
{...}
]
}]
Also, have a look at https://docs.mongodb.com/manual/reference/operator/aggregation/facet/
The reader acts like a generator. On a file with some fake data:
>>> import sys, csv
>>> data = csv.reader(open('data.csv'),delimiter=';')
>>> data
<_csv.reader object at 0x1004a11a0>
>>> data.next()
['a', ' b', ' c']
>>> data.next()
['x', ' y', ' z']
>>> data.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
Using operator.itemgetter as Ignacio suggests:
>>> data = csv.reader(open('data.csv'),delimiter=';')
>>> import operator
>>> sortedlist = sorted(data, key=operator.itemgetter(2), reverse=True)
>>> sortedlist
[['x', ' y', ' z'], ['a', ' b', ' c']]
The X-Frame-Options is defined in the Http Header and not in the <head>
section of the page you want to use in the iframe.
Accepted values are: DENY, SAMEORIGIN and ALLOW-FROM "url"
One solution is to use a list/array:
var first_json = {"name":"joe", "age":27};
var second_json = {"name":"james", "age":32};
var jsons = new Array();
jsons.push(first_json);
jsons.push(second_json);
Result
jsons = [
{"name":"joe", "age":27},
{"name":"james", "age":32}
]
I would go with unset because it might give the garbage collector a better hint so that the memory can be available again sooner. Be careful that any things the object points to either have other references or get unset first or you really will have to wait on the garbage collector since there would then be no handles to them.
As per the javadoc for get(), it is the synonym for Navigate.to()
View javadoc screenshot below:
Javadoc for get() says it all -
Load a new web page in the current browser window. This is done using an HTTP GET operation, and the method will block until the load is complete. This will follow redirects issued either by the server or as a meta-redirect from within the returned HTML. Should a meta-redirect "rest" for any duration of time, it is best to wait until this timeout is over, since should the underlying page change whilst your test is executing the results of future calls against this interface will be against the freshly loaded page. Synonym for org.openqa.selenium.WebDriver.Navigation.to(String).
The Trace messages can occur in the output window as well, even if you're not in debug mode. You just have to make sure the the TRACE compiler constant is defined.
Even after this my code is working fine , so i just removed all warning messages with this statement at line 1 .
<?php error_reporting(E_ERROR); ?>
Regarding the question,
” can someone explain why the
compare()
function exists if a comparison can be made using simple operands?
Relative to <
and ==
, the compare
function is conceptually simpler and in practice it can be more efficient since it avoids two comparisons per item for ordinary ordering of items.
As an example of simplicity, for small integer values you can write a compare function like this:
auto compare( int a, int b ) -> int { return a - b; }
which is highly efficient.
Now for a structure
struct Foo
{
int a;
int b;
int c;
};
auto compare( Foo const& x, Foo const& y )
-> int
{
if( int const r = compare( x.a, y.a ) ) { return r; }
if( int const r = compare( x.b, y.b ) ) { return r; }
return compare( x.c, y.c );
}
Trying to express this lexicographic compare directly in terms of <
you wind up with horrendous complexity and inefficiency, relatively speaking.
With C++11, for the simplicity alone ordinary less-than comparison based lexicographic compare can be very simply implemented in terms of tuple comparison.
Do as this:
Windows -> Show View -> Servers
Then in the Servers view, right-click and add new. It will show a pop up containing many server vendors. Under Apache select Tomcat v7.0 (Depending upon your downloaded server version). And in the run time configuration point it to the Tomcat folder you have downloaded.
You can try this article. It has the info you want !!
In that example, e
is just a parameter for that function, but it's the event
object that gets passed in through it.
Hi problem is here remove it
compile 'com.google.android.gms:play-services:11.8.0'
why?
Note: Don't use the combined play-services target. It brings in dozens of libraries, bloating your application. Instead, specify only the specific Google Play services APIs your app uses.
And use what you need.https://developers.google.com/android/guides/setup
Like for location service
com.google.android.gms:play-services-location:11.8.0
For Cloud Messaging
com.google.android.gms:play-services-gcm:11.8.0
Virtual memory is, among other things, an abstraction to give the programmer the illusion of having infinite memory available on their system.
Virtual memory mappings are made to correspond to actual physical addresses. The operating system creates and deals with these mappings - utilizing the page table, among other data structures to maintain the mappings. Virtual memory mappings are always found in the page table or some similar data structure (in case of other implementations of virtual memory, we maybe shouldn't call it the "page table"). The page table is in physical memory as well - often in kernel-reserved spaces that user programs cannot write over.
Virtual memory is typically larger than physical memory - there wouldn't be much reason for virtual memory mappings if virtual memory and physical memory were the same size.
Only the needed part of a program is resident in memory, typically - this is a topic called "paging". Virtual memory and paging are tightly related, but not the same topic. There are other implementations of virtual memory, such as segmentation.
I could be assuming wrong here, but I'd bet the things you are finding hard to wrap your head around have to do with specific implementations of virtual memory, most likely paging. There is no one way to do paging - there are many implementations and the one your textbook describes is likely not the same as the one that appears in real OSes like Linux/Windows - there are probably subtle differences.
I could blab a thousand paragraphs about paging... but I think that is better left to a different question targeting specifically that topic.
Have a look at this
Appending the #value into the address is default behaviour that browsers such as IE use to identify named anchor positions on the page, seeing this comes from Netscape.
You can intercept it and remove it, read this article.
From my own experience , there are two way:
use ipdb,which is a enhanced debugger likes pdb.
import ipdb;ipdb.set_trace()
or breakpoint()
(from python3.7)
use django shell ,just use the command below. This is very helpfull when you are developing a new view.
python manage.py shell
Using DateTime
class in PHP7+:
function getMysqlDatetimeFromDate(int $day, int $month, int $year): string
{
$dt = new DateTime();
$dt->setDate($year, $month, $day);
$dt->setTime(0, 0, 0, 0); // set time to midnight
return $dt->format('Y-m-d H:i:s');
}
to fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the
deserialized type so that it is a normal .NET type (e.g. not a primitive type like
integer, not a collection type like an array or List) that can be deserialized from a
JSON object.`
The whole message indicates that it is possible to serialize to a List object, but the input must be a JSON list. This means that your JSON must contain
"accounts" : [{<AccountObjectData}, {<AccountObjectData>}...],
Where AccountObject data is JSON representing your Account object or your Badge object
What it seems to be getting currently is
"accounts":{"github":"sergiotapia"}
Where accounts is a JSON object (denoted by curly braces), not an array of JSON objects (arrays are denoted by brackets), which is what you want. Try
"accounts" : [{"github":"sergiotapia"}]
Take offline takes a while and sometimes I experience some problems with that..
Most solid way in my opinion:
Detach Right click DB -> Tasks -> Detach... check "Drop Connections" Ok
Reattach Right click Databases -> Attach.. Add... -> select your database, and change the Attach As column to your desired database name. Ok
More portable to use ed; some systems don't support \n in sed
printf "/^lorem ipsum dolor sit amet/a\nconsectetur adipiscing elit\n.\nw\nq\n" |\
/bin/ed $filename
If you are using Bootstrap 3.3.x then use this code (you need to add class name carousel-fade to your carousel).
.carousel-fade .carousel-inner .item {
-webkit-transition-property: opacity;
transition-property: opacity;
}
.carousel-fade .carousel-inner .item,
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
opacity: 0;
}
.carousel-fade .carousel-inner .active,
.carousel-fade .carousel-inner .next.left,
.carousel-fade .carousel-inner .prev.right {
opacity: 1;
}
.carousel-fade .carousel-inner .next,
.carousel-fade .carousel-inner .prev,
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
left: 0;
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
.carousel-fade .carousel-control {
z-index: 2;
}
The way via unlist
and matrix
seems a bit convoluted, and requires you to hard-code the number of elements (this is actually a pretty big no-go. Of course you could circumvent hard-coding that number and determine it at run-time)
I would go a different route, and construct a data frame directly from the list that strsplit
returns. For me, this is conceptually simpler. There are essentially two ways of doing this:
as.data.frame
– but since the list is exactly the wrong way round (we have a list of rows rather than a list of columns) we have to transpose the result. We also clear the rownames
since they are ugly by default (but that’s strictly unnecessary!):
`rownames<-`(t(as.data.frame(strsplit(text, '\\.'))), NULL)
Alternatively, use rbind
to construct a data frame from the list of rows. We use do.call
to call rbind
with all the rows as separate arguments:
do.call(rbind, strsplit(text, '\\.'))
Both ways yield the same result:
[,1] [,2] [,3] [,4]
[1,] "F" "US" "CLE" "V13"
[2,] "F" "US" "CA6" "U13"
[3,] "F" "US" "CA6" "U13"
[4,] "F" "US" "CA6" "U13"
[5,] "F" "US" "CA6" "U13"
[6,] "F" "US" "CA6" "U13"
…
Clearly, the second way is much simpler than the first.
ALTER SCHEMA TargetSchema
TRANSFER SourceSchema.TableName;
If you want to move all tables into a new schema, you can use the undocumented (and to be deprecated at some point, but unlikely!) sp_MSforeachtable
stored procedure:
exec sp_MSforeachtable "ALTER SCHEMA TargetSchema TRANSFER ?"
Ref.: ALTER SCHEMA