window.location.hash = '#tries';
This will scroll to the element in question, essentially "focus"ing it.
FWIW, I had what I think is a related problem and came up with a workaround: I wrote a Chrome Extension that did an document.execCommand('paste') into a textarea with focus on window unload in order to populate the element with the system clipboard contents. This worked 100% of the time manually, but the execCommand returned false almost all the time when run under Selenium.
I added a driver.refresh() after the initial driver.get( myChromeExtensionURL ), and now it works 100% of the time. This was with Selenium driver version 2.16.333243 and Chrome version 43 on Mac OS 10.9.
When I was researching the problem, I didn't see any mentions of this workaround, so I thought I'd document my discovery for those following in my Selenium/focus/execCommand('paste') footsteps.
I have toyed with this for forever, and finally found something that seems to always work!
textField = new JTextField() {
public void addNotify() {
super.addNotify();
requestFocus();
}
};
You need to either put the code below the HTML or load if using the document load event:
<input type="text" id="goal-input" name="goal" />
<script type="text/javascript">
$(function(){
$("#goal-input").focus();
});
</script>
Update:
Switching divs doesn't trigger the document load event since everything already have been loaded. You need to focus it when you switch div:
if (goal) {
step1.fadeOut('fast', function() {
step1.hide();
step2.fadeIn('fast', function() {
$("#name").focus();
});
});
}
Dynamically added items have to be added to the DOM... clone().append()
adds it to the DOM... which allows it to be selected via jquery.
Here is how a kotlin extension for showing and hiding the soft keyboard can be made:
fun View.showKeyboard() {
this.requestFocus()
val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
fun View.hideKeyboard() {
val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}
Then you can just do this:
editText.showKeyboard()
// OR
editText.hideKeyboard()
For me, what worked on all devices is this:
<!-- fake first focusable view, to allow stealing the focus to itself when clearing the focus from others -->
<View
android:layout_width="0px"
android:layout_height="0px"
android:focusable="true"
android:focusableInTouchMode="true" />
Just put this as a view before the problematic focused view, and that's it.
You can add the following code:
this.ActiveControl = null; //this = form
About this solution, we could just create a directive and attach it to the DOM element that has to get the focus when a given condition is satisfied. By following this approach we avoid coupling controller to DOM element ID's.
Sample code directive:
gbndirectives.directive('focusOnCondition', ['$timeout',
function ($timeout) {
var checkDirectivePrerequisites = function (attrs) {
if (!attrs.focusOnCondition && attrs.focusOnCondition != "") {
throw "FocusOnCondition missing attribute to evaluate";
}
}
return {
restrict: "A",
link: function (scope, element, attrs, ctrls) {
checkDirectivePrerequisites(attrs);
scope.$watch(attrs.focusOnCondition, function (currentValue, lastValue) {
if(currentValue == true) {
$timeout(function () {
element.focus();
});
}
});
}
};
}
]);
A possible usage
.controller('Ctrl', function($scope) {
$scope.myCondition = false;
// you can just add this to a radiobutton click value
// or just watch for a value to change...
$scope.doSomething = function(newMyConditionValue) {
// do something awesome
$scope.myCondition = newMyConditionValue;
};
});
HTML
<input focus-on-condition="myCondition">
This is what worked for me, sets focus and shows keyboard also
EditText userNameText = (EditText) findViewById(R.id.textViewUserNameText);
userNameText.setFocusable(true);
userNameText.setFocusableInTouchMode(true);
userNameText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(userNameText, InputMethodManager.SHOW_IMPLICIT);
With jQuery its just: $(this).blur();
Chris Coyier has a mini jQuery plugin for this which works perfectly well: http://css-tricks.com/snippets/jquery/move-cursor-to-end-of-textarea-or-input/
It uses setSelectionRange if supported, else has a solid fallback.
jQuery.fn.putCursorAtEnd = function() {
return this.each(function() {
$(this).focus()
// If this function exists...
if (this.setSelectionRange) {
// ... then use it (Doesn't work in IE)
// Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
var len = $(this).val().length * 2;
this.setSelectionRange(len, len);
} else {
// ... otherwise replace the contents with itself
// (Doesn't work in Google Chrome)
$(this).val($(this).val());
}
// Scroll to the bottom, in case we're in a tall textarea
// (Necessary for Firefox and Google Chrome)
this.scrollTop = 999999;
});
};
Then you can just do:
input.putCursorAtEnd();
you can set pointer on last position of textbox as per following.
temp=$("#txtName").val();
$("#txtName").val('');
$("#txtName").val(temp);
$("#txtName").focus();
txtCompanyID.Focusable = true;
Keyboard.Focus(txtCompanyID);
msdn:
There can be only one element on the whole desktop that has keyboard focus. In WPF, the element that has keyboard focus will have IsKeyboardFocused set to true.
You could break after the setting line and check the value of IsKeyboardFocused
property. Also check if you really reach that line or maybe you set some other element to get focus after that.
This will definitely work. Orange outline will not show anymore.. Common for all tags:
*:focus {
outline: none;
}
Specific to some tag, ex: input tag
input:focus {
outline:none;
}
border:0;
outline:none;
box-shadow:none;
This should do the trick.
There are 3 typical methods used to determine if the user can see the HTML page, however none of them work perfectly:
The W3C Page Visibility API is supposed to do this (supported since: Firefox 10, MSIE 10, Chrome 13). However, this API only raises events when the browser tab is fully overriden (e.g. when the user changes from one tab to another one). The API does not raise events when the visibility cannot be determined with 100% accuracy (e.g. Alt+Tab to switch to another application).
Using focus/blur based methods gives you a lot of false positive. For example, if the user displays a smaller window on top of the browser window, the browser window will lose the focus (onblur
raised) but the user is still able to see it (so it still need to be refreshed). See also http://javascript.info/tutorial/focus
In order to improve the imperfect behaviors described above, I use a combination of the 3 methods: W3C Visibility API, then focus/blur and user activity methods in order to reduce the false positive rate. This allows to manage the following events:
This is how it works: when the document lose the focus, the user activity (such as mouse move) on the document is monitored in order to determine if the window is visible or not. The page visibility probability is inversely proportional to the time of the last user activity on the page: if the user makes no activity on the document for a long time, the page is most probably not visible. The code below mimics the W3C Page Visibility API: it behaves the same way but has a small false positive rate. It has the advantage to be multibrowser (tested on Firefox 5, Firefox 10, MSIE 9, MSIE 7, Safari 5, Chrome 9).
<div id="x"></div> <script> /** Registers the handler to the event for the given object. @param obj the object which will raise the event @param evType the event type: click, keypress, mouseover, ... @param fn the event handler function @param isCapturing set the event mode (true = capturing event, false = bubbling event) @return true if the event handler has been attached correctly */ function addEvent(obj, evType, fn, isCapturing){ if (isCapturing==null) isCapturing=false; if (obj.addEventListener){ // Firefox obj.addEventListener(evType, fn, isCapturing); return true; } else if (obj.attachEvent){ // MSIE var r = obj.attachEvent('on'+evType, fn); return r; } else { return false; } } // register to the potential page visibility change addEvent(document, "potentialvisilitychange", function(event) { document.getElementById("x").innerHTML+="potentialVisilityChange: potentialHidden="+document.potentialHidden+", document.potentiallyHiddenSince="+document.potentiallyHiddenSince+" s<br>"; }); // register to the W3C Page Visibility API var hidden=null; var visibilityChange=null; if (typeof document.mozHidden !== "undefined") { hidden="mozHidden"; visibilityChange="mozvisibilitychange"; } else if (typeof document.msHidden !== "undefined") { hidden="msHidden"; visibilityChange="msvisibilitychange"; } else if (typeof document.webkitHidden!=="undefined") { hidden="webkitHidden"; visibilityChange="webkitvisibilitychange"; } else if (typeof document.hidden !=="hidden") { hidden="hidden"; visibilityChange="visibilitychange"; } if (hidden!=null && visibilityChange!=null) { addEvent(document, visibilityChange, function(event) { document.getElementById("x").innerHTML+=visibilityChange+": "+hidden+"="+document[hidden]+"<br>"; }); } var potentialPageVisibility = { pageVisibilityChangeThreshold:3*3600, // in seconds init:function() { function setAsNotHidden() { var dispatchEventRequired=document.potentialHidden; document.potentialHidden=false; document.potentiallyHiddenSince=0; if (dispatchEventRequired) dispatchPageVisibilityChangeEvent(); } function initPotentiallyHiddenDetection() { if (!hasFocusLocal) { // the window does not has the focus => check for user activity in the window lastActionDate=new Date(); if (timeoutHandler!=null) { clearTimeout(timeoutHandler); } timeoutHandler = setTimeout(checkPageVisibility, potentialPageVisibility.pageVisibilityChangeThreshold*1000+100); // +100 ms to avoid rounding issues under Firefox } } function dispatchPageVisibilityChangeEvent() { unifiedVisilityChangeEventDispatchAllowed=false; var evt = document.createEvent("Event"); evt.initEvent("potentialvisilitychange", true, true); document.dispatchEvent(evt); } function checkPageVisibility() { var potentialHiddenDuration=(hasFocusLocal || lastActionDate==null?0:Math.floor((new Date().getTime()-lastActionDate.getTime())/1000)); document.potentiallyHiddenSince=potentialHiddenDuration; if (potentialHiddenDuration>=potentialPageVisibility.pageVisibilityChangeThreshold && !document.potentialHidden) { // page visibility change threshold raiched => raise the even document.potentialHidden=true; dispatchPageVisibilityChangeEvent(); } } var lastActionDate=null; var hasFocusLocal=true; var hasMouseOver=true; document.potentialHidden=false; document.potentiallyHiddenSince=0; var timeoutHandler = null; addEvent(document, "pageshow", function(event) { document.getElementById("x").innerHTML+="pageshow/doc:<br>"; }); addEvent(document, "pagehide", function(event) { document.getElementById("x").innerHTML+="pagehide/doc:<br>"; }); addEvent(window, "pageshow", function(event) { document.getElementById("x").innerHTML+="pageshow/win:<br>"; // raised when the page first shows }); addEvent(window, "pagehide", function(event) { document.getElementById("x").innerHTML+="pagehide/win:<br>"; // not raised }); addEvent(document, "mousemove", function(event) { lastActionDate=new Date(); }); addEvent(document, "mouseover", function(event) { hasMouseOver=true; setAsNotHidden(); }); addEvent(document, "mouseout", function(event) { hasMouseOver=false; initPotentiallyHiddenDetection(); }); addEvent(window, "blur", function(event) { hasFocusLocal=false; initPotentiallyHiddenDetection(); }); addEvent(window, "focus", function(event) { hasFocusLocal=true; setAsNotHidden(); }); setAsNotHidden(); } } potentialPageVisibility.pageVisibilityChangeThreshold=4; // 4 seconds for testing potentialPageVisibility.init(); </script>
Since there is currently no working cross-browser solution without false positive, you should better think twice about disabling periodical activity on your web site.
Think about your user interface before you do this. I assume (though none of the answers has said so) that you'll be doing this when the document loads using jQuery's ready()
function. If a user has already focussed on a different element before the document has loaded (which is perfectly possible) then it's extremely irritating for them to have the focus stolen away.
You could check for this by adding onfocus
attributes in each of your <input>
elements to record whether the user has already focussed on a form field and then not stealing the focus if they have:
var anyFieldReceivedFocus = false;
function fieldReceivedFocus() {
anyFieldReceivedFocus = true;
}
function focusFirstField() {
if (!anyFieldReceivedFocus) {
// Do jQuery focus stuff
}
}
<input type="text" onfocus="fieldReceivedFocus()" name="one">
<input type="text" onfocus="fieldReceivedFocus()" name="two">
You could also use:
<body onload="focusOnInput()">
<form name="passwordForm" action="verify.php" method="post">
<input name="passwordInput" type="password" />
</form>
</body>
And then in your JavaScript:
function focusOnInput() {
document.forms["passwordForm"]["passwordInput"].focus();
}
For my problem this code worked, I had to navigate to an anchor tag on page load :
$(window).scrollTop($('a#captchaAnchor').position().top);
For that matter you can use this on any element, not just an anchor tag.
If EditText is inside Recycler or ListView and/or this have disable state use below code.
public static void showKeyboardByFocus(final View view)
{
view.requestFocus();
InputMethodManager keyboard = SystemMaster.getInputMethodManager();
keyboard.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
Runnable re = new Runnable()
{
@Override
public void run()
{
view.setEnabled(true);
view.requestFocus();
}
};
Handler h = new Handler(Looper.getMainLooper());
h.postDelayed(re, 360);
}
For what it's worth, you can use the autofocus
attribute on HTML5 compatible browsers. Works even on IE as of version 10.
<input name="myinput" value="whatever" autofocus />
Search and replace
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;
Replace to
outline: 0;
@Someone Somewhere I used this to clear focus:
editText.clearFocus();
and it helps
Maybe this one can help:
function focus(el){_x000D_
el.focus();_x000D_
return el==document.activeElement;_x000D_
}
_x000D_
return value: true = success, false = failed
Reff: https://developer.mozilla.org/en-US/docs/Web/API/DocumentOrShadowRoot/activeElement https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus
To add color to an input, Use the following css code:
input{
color: black;
}
None of the answers above works for me. The only (let's say) solution has been to change the first TextView in a disabled EditText that receives focus and then add
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
in the onCreate callback to prevent keyboard to be shown. Now my first EditText looks like a TextView but can get the initial focus, finally.
To lose the focus when other view is touched , both views should be set as view.focusableInTouchMode(true).
But it seems that use focuses in touch mode are not recommended. Please take a look here: http://android-developers.blogspot.com/2008/12/touch-mode.html
There's a write-up here that may be of use: Set Focus to First Input on Web Page
holder.checkbox.setTag(row_id);
and
holder.checkbox.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
CheckBox c = (CheckBox) v;
int row_id = (Integer) v.getTag();
checkboxes.put(row_id, c.isChecked());
}
});
it's worked for me set tabindex to 0 this.yourtextbox.TabIndex = 0;
Try this:
input.focus();
input.scrollIntoView()
just add this on your Activity:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (getCurrentFocus() != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
return super.dispatchTouchEvent(ev);
}
Add to your parent layout where did you put your EditText
this android:focusableInTouchMode="true"
In the shell, you can't execute more than one statement at a time:
>>> x = 5
y = 6
SyntaxError: multiple statements found while compiling a single statement
You need to execute them one by one:
>>> x = 5
>>> y = 6
>>>
When you see multiple statements are being declared, that means you're seeing a script, which will be executed later. But in the interactive interpreter, you can't do more than one statement at a time.
if your exe happens to be a console app, you might be interested in reading the stdout and stderr -- for that, I'll humbly refer you to this example:
http://support.microsoft.com/default.aspx?scid=kb;EN-US;q190351
It's a bit of a mouthful of code, but I've used variations of this code to spawn and read.
I try this with jquery; use this and have fun :D
jQuery.printInExcel = function (DivID)
{
var ExcelApp = new ActiveXObject("Excel.Application");
ExcelApp.Workbooks.Add;
ExcelApp.visible = true;
var str = "";
var tblcount = 0;
var trcount = 0;
$("#" + DivID + " table").each(function ()
{ $(this).find("tr").each(function ()
{ var tdcount = 0; $(this).find("td").each(function ()
{ str = str + $(this).text(); ExcelApp.Cells(trcount + 1, tdcount + 1).Value = str;
str = ""; tdcount++
});
trcount++
}); tblcount++
});
};
use this in your class and call it with $.printInExcel(your var);
To convert tuples to list
(Commas were missing between the tuples in the given question, it was added to prevent error message)
Method 1:
level1 = (
(1,1,1,1,1,1),
(1,0,0,0,0,1),
(1,0,0,0,0,1),
(1,0,0,0,0,1),
(1,0,0,0,0,1),
(1,1,1,1,1,1))
level1 = [list(row) for row in level1]
print(level1)
Method 2:
level1 = map(list,level1)
print(list(level1))
Method 1 took --- 0.0019991397857666016 seconds ---
Method 2 took --- 0.0010001659393310547 seconds ---
Actually, the problem is now solved. I added the 'pause' argument to the method 'carousel' like below:
$(document).ready(function() {
$('.carousel').carousel('pause');
});
Anyway, thanks so much @Yohn for your tips toward this solution.
Use the validators package:
>>> import validators
>>> validators.url("http://google.com")
True
>>> validators.url("http://google")
ValidationFailure(func=url, args={'value': 'http://google', 'require_tld': True})
>>> if not validators.url("http://google"):
... print "not valid"
...
not valid
>>>
Install it from PyPI with pip (pip install validators
).
Try VAVR Tuples.
Not only does vavr have a good set of tuple types, it has great support for functional programming, too.
Here is a very easy way of doing that
$(function () {
$(".glyphicon").unbind('click');
$(".glyphicon").click(function (e) {
$(this).toggleClass("glyphicon glyphicon-chevron-up glyphicon glyphicon-chevron-down");
});
Hope this helps :D
I'm not an expert but it sounds to me that this is something you could only do if you built the browser yourself - ie, not something done in a web page. I'm not sure that the sources for Chrome are publicly available (I think they are though), but the sources are what you'd probably need to change for this.
To get the lines that contain the texts 8768
, 9875
or 2353
, use:
^.*(8768|9875|2353).*$
What it means:
^ from the beginning of the line
.* get any character except \n (0 or more times)
(8768|9875|2353) if the line contains the string '8768' OR '9875' OR '2353'
.* and get any character except \n (0 or more times)
$ until the end of the line
If you do want the literal *
char, you'd have to escape it:
^.*(\*8768|\*9875|\*2353).*$
None of the above worked for me for some reason :/, so I added an element ref to a top element in app.component.html
, and (activate)=onNavigate($event)
to the router-outlet
.
<!--app.component.html-->
<div #topScrollAnchor></div>
<app-navbar></app-navbar>
<router-outlet (activate)="onNavigate($event)"></router-outlet>
Then I added the child to the app.component.ts file to the type of ElementRef
, and had it scroll to it on activation of the router-outlet.
export class AppComponent {
@ViewChild('topScrollAnchor') topScroll: ElementRef;
onNavigate(event): any {
this.topScroll.nativeElement.scrollIntoView({ behavior: 'smooth' });
}
}
Here's the code in stackblitz
Reflection and dynamic value access are correct solutions to this question but are quite slow. If your want something faster then you can create dynamic method using expressions:
object value = GetValue();
string propertyName = "MyProperty";
var parameter = Expression.Parameter(typeof(object));
var cast = Expression.Convert(parameter, value.GetType());
var propertyGetter = Expression.Property(cast, propertyName);
var castResult = Expression.Convert(propertyGetter, typeof(object));//for boxing
var propertyRetriver = Expression.Lambda<Func<object, object>>(castResult, parameter).Compile();
var retrivedPropertyValue = propertyRetriver(value);
This way is faster if you cache created functions. For instance in dictionary where key would be the actual type of object assuming that property name is not changing or some combination of type and property name.
The line would be as shown below:
Dim x As Integer
x = dgvName.Rows(yourRowIndex).Cells(yourColumnIndex).Value
you can also do this query...!
sqlContext.sql("""
select from_unixtime(unix_timestamp('08/26/2016', 'MM/dd/yyyy'), 'yyyy:MM:dd') as new_format
""").show()
You create __main__.py
in yourpackage
to make it executable as:
$ python -m yourpackage
Make sure you didn't add the properties files in the wrong resources folder as there is one under 'Web Pages' and one under 'Other Sources/...'. They needed to be under 'Other Sources/...'.
The DataView object itself is used to loop through DataView rows.
DataView rows are represented by the DataRowView object. The DataRowView.Row property provides access to the original DataTable row.
C#
foreach (DataRowView rowView in dataView)
{
DataRow row = rowView.Row;
// Do something //
}
VB.NET
For Each rowView As DataRowView in dataView
Dim row As DataRow = rowView.Row
' Do something '
Next
Try either
sudo apt-get install php-zip
orsudo apt-get install php5.6-zip
Then, you might have to restart your web server.
sudo service apache2 restart
orsudo service nginx restart
If you are installing on centos or fedora OS then use yum in place of apt-get. example:-
sudo yum install php-zip
or
sudo yum install php5.6-zip
and
sudo service httpd restart
Look at Jersey. Again, REST is all about the data. And a tutorial here
With ANY operator you can search for only one value.
For example,
select * from mytable where 'Book' = ANY(pub_types);
If you want to search multiple values, you can use @> operator.
For example,
select * from mytable where pub_types @> '{"Journal", "Book"}';
You can specify in which ever order you like.
<create-report-card-form [currentReportCardCount]="providerData.reportCards.length" ...
^^^^^^^^^^^^^^^^^^^^^^^^
In your HomeComponent template, you are trying to bind to an input on the CreateReportCardForm component that doesn't exist.
In CreateReportCardForm, these are your only three inputs:
@Input() public reportCardDataSourcesItems: SelectItem[];
@Input() public reportCardYearItems: SelectItem[];
@Input() errorMessages: Message[];
Add one for currentReportCardCount and you should be good to go.
0x7ffffff's answer is ok and definitely exhaustive.
As a plus, I suggest you to make an UIView extension, in this way:
public extension UIView {
/**
Fade in a view with a duration
- parameter duration: custom animation duration
*/
func fadeIn(duration duration: NSTimeInterval = 1.0) {
UIView.animateWithDuration(duration, animations: {
self.alpha = 1.0
})
}
/**
Fade out a view with a duration
- parameter duration: custom animation duration
*/
func fadeOut(duration duration: NSTimeInterval = 1.0) {
UIView.animateWithDuration(duration, animations: {
self.alpha = 0.0
})
}
}
Swift-3
/// Fade in a view with a duration
///
/// Parameter duration: custom animation duration
func fadeIn(withDuration duration: TimeInterval = 1.0) {
UIView.animate(withDuration: duration, animations: {
self.alpha = 1.0
})
}
/// Fade out a view with a duration
///
/// - Parameter duration: custom animation duration
func fadeOut(withDuration duration: TimeInterval = 1.0) {
UIView.animate(withDuration: duration, animations: {
self.alpha = 0.0
})
}
In this way you can do this wherever in your code:
let newImage = UIImage(named: "")
newImage.alpha = 0 // or newImage.fadeOut(duration: 0.0)
self.view.addSubview(newImage)
...
newImage.fadeIn()
Code reuse is important!
The interpretation of the backspace and carriage return characters is left to the software you use for display. A terminal emulator, when displaying \b would move the cursor one step back, and when displaying \r to the beginning of the line. If you print these characters somewhere else, like a text file, the software may choose. to do something else.
CMake can generate really nice Visual Studio .projs
/.slns
, but there is always the problem with the need to modify the .cmake
files rather than .proj
/.sln
. As it is now, we are dealing with it as follows:
/src
and files visible in Visual Studio are just "links" to them defined in .filter
./src
directory, not the default project's one..cmake
files.At first we were a little afraid of how it will turn out, but the workflow works really well and with nice diff visible before each commit, everyone can easily see if his changes were correctly mapped in .cmake
files.
One more important thing to know about is the lack of support (afaik) for "Solution Configurations" in CMake. As it stands, you have to generate two directories with projects/solutions - one for each build type (debug, release, etc.). There is no direct support for more sophisticated features - in other words: switching between configurations won't give you what you might expect.
I think you can do this with the hyperref
package, although I've not tried it myself. From the relevant LaTeX Wikibook section:
The
hyperref
package introduces another useful command;\autoref{}
. This command creates a reference with additional text corresponding to the targets type, all of which will be a hyperlink. For example, the command\autoref{sec:intro}
would create a hyperlink to the\label{sec:intro}
command, wherever it is. Assuming that this label is pointing to a section, the hyperlink would contain the text "section 3.4", or similar (capitalization rules will be followed, which makes this very convenient). You can customize the prefixed text by redefining\typeautorefname
to the prefix you want, as in:
\def\subsectionautorefname{section}
I was using python3.4 on Windows10. I installed python3.5. I couldn't find PYTHONPATH, PYTHONHOME env variable. If I command python in CMD console, It kept using python3.4. I deleted python3.4. Whenever I command python in CMD console, it starts showing an error like below.
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'
I searched to figure out my problem. Solution was simple. When you install python3.5, you can custom install and check Add Python to environment variables in Advanced Options.
I just leave here for case that someone have similar issues visit here so that they don't waste their precious time much to figure out.
In Kotlin:
AlertDialog.Builder(this)
.setTitle(R.string.question_title)
.setMessage(R.string.question_message)
.setPositiveButton(android.R.string.yes) { _, _ -> yesClicked() }
.setNegativeButton(android.R.string.no) { _, _ -> noClicked() }
.show()
It's not suitable for every situation, because not all items can have a non-proportional maximum, but slapping a good ol' max-width
on the offending element/container can put it back in line.
MSDN details it here very nicely on how to check it from registry:
To find .NET Framework versions by viewing the registry (.NET Framework 1-4)
- On the Start menu, choose Run.
- In the Open box, enter regedit.exe.You must have administrative credentials to run regedit.exe.
In the Registry Editor, open the following subkey:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP
The installed versions are listed under the NDP subkey. The version number is stored in the Version entry. For the .NET Framework 4 the Version entry is under the Client or Full subkey (under NDP), or under both subkeys.
To find .NET Framework versions by viewing the registry (.NET Framework 4.5 and later)
- On the Start menu, choose Run.
- In the Open box, enter regedit.exe. You must have administrative credentials to run regedit.exe.
In the Registry Editor, open the following subkey:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full
Note that the path to the Full subkey includes the subkey Net Framework rather than .NET Framework
Check for a DWORD value named
Release
. The existence of the Release DWORD indicates that the .NET Framework 4.5 or newer has been installed on that computer.
Note: The last row in the above snapshot which got clipped reads On all other OS versions: 461310
. I tried my level best to avoid the information getting clipped while taking the screenshot but the table was way too big.
By using pandas we can read excel easily.
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
DataF=pd.read_excel("Test.xlsx",sheet_name='Sheet1')
print("Column headings:")
print(DataF.columns)
Test at :https://repl.it Reference: https://pythonspot.com/read-excel-with-pandas/
If you've got the Java EE JDK with Glassfish, it's in glassfish3/glassfish/modules/javax.servlet-api.jar.
Try this
@RequestMapping(value = "proffessional", method = RequestMethod.POST)
public @ResponseBody
String forgotPassword(@ModelAttribute("PROFESSIONAL") UserProfessionalForm professionalForm,
BindingResult result, Model model) {
UserProfileVO userProfileVO = new UserProfileVO();
userProfileVO.setUser(sessionData.getUser());
userService.saveUserProfile(userProfileVO);
model.addAttribute("professional", professionalForm);
return "Your Professional Details Updated";
}
That work sharp for me
SELECT *
FROM [dbo].[table1] t1
LEFT JOIN [dbo].[table2] t2 ON t1.[t1_ID] = t2.[t2_ID]
WHERE t2.[t2_ID] IS NULL
Easiest way to get it by using date pattern - h:mm a
, where
Code snippet :
DateFormat dateFormat = new SimpleDateFormat("hh:mm a");
Not sure if this is the best way, but it works.
if (cartDiv == null) {
cartDiv = "<div id='unique_id'></div>"; // document.createElement('div');
document.body.appendChild(cartDiv);
}
You see the behavior when your target element contains child elements:
Each time your mouse enters or leaves a child element, mouseover
is triggered, but not mouseenter
.
$('#my_div').bind("mouseover mouseenter", function(e) {_x000D_
var el = $("#" + e.type);_x000D_
var n = +el.text();_x000D_
el.text(++n);_x000D_
});
_x000D_
#my_div {_x000D_
padding: 0 20px 20px 0;_x000D_
background-color: #eee;_x000D_
margin-bottom: 10px;_x000D_
width: 90px;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
#my_div>div {_x000D_
float: left;_x000D_
margin: 20px 0 0 20px;_x000D_
height: 25px;_x000D_
width: 25px;_x000D_
background-color: #aaa;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>_x000D_
_x000D_
<div>MouseEnter: <span id="mouseenter">0</span></div>_x000D_
<div>MouseOver: <span id="mouseover">0</span></div>_x000D_
_x000D_
<div id="my_div">_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
</div>
_x000D_
Not saying this is better, just another way:
$("#elem")[0].style.fontSize="20px";
With Java 8, you can do this:
int[] haystack = {1, 2, 3};
int needle = 3;
boolean found = Arrays.stream(haystack).anyMatch(x -> x == needle);
You'd need to do
boolean found = Arrays.stream(haystack).anyMatch(x -> needle.equals(x));
if you're working with objects.
From ScottGu's blog:
Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:
The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:
Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).
Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.
This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.
Also see this.
In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".
Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.
Wikipedia
There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.
Check out this article and this simple example. Quick translation of same to your classes ...
var d1 = typeof(Task<>);
Type[] typeArgs = { typeof(Item) };
var makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);
Per your edit: For that case, you can do this ...
var d1 = Type.GetType("GenericTest.TaskA`1"); // GenericTest was my namespace, add yours
Type[] typeArgs = { typeof(Item) };
var makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);
To see where I came up with backtick1 for the name of the generic class, see this article.
Note: if your generic class accepts multiple types, you must include the commas when you omit the type names, for example:
Type type = typeof(IReadOnlyDictionary<,>);
As a workaround, you can use a code block to render the code literally. Just surround your text with triple backticks ```. It will look like this:
2018-07-20 Wrote this answer
Can format it without
Also don't need <br /> for new line
Note that using <pre>
and <code>
you get slightly different behaviour:  
and <br />
will be parsed rather than inserted literally.
<pre>:
2018-07-20 Wrote this answer Can format it without Also don't need
for new line
<code>:
2018-07-20 Wrote this answer
Can format it without
Also don't need
for new line
If you want to be sure the (single commit) patch will be applied on top of a specific commit, you can use the new git 2.9 (June 2016) option git format-patch --base
git format-patch --base=COMMIT_VALUE~ -M -C COMMIT_VALUE~..COMMIT_VALUE
# or
git format-patch --base=auto -M -C COMMIT_VALUE~..COMMIT_VALUE
# or
git config format.useAutoBase true
git format-patch -M -C COMMIT_VALUE~..COMMIT_VALUE
See commit bb52995, commit 3de6651, commit fa2ab86, commit ded2c09 (26 Apr 2016) by Xiaolong Ye (``).
(Merged by Junio C Hamano -- gitster
-- in commit 72ce3ff, 23 May 2016)
format-patch
: add '--base
' option to record base tree info
Maintainers or third party testers may want to know the exact base tree the patch series applies to. Teach git format-patch a '
--base
' option to record the base tree info and append it at the end of the first message (either the cover letter or the first patch in the series).The base tree info consists of the "base commit", which is a well-known commit that is part of the stable part of the project history everybody else works off of, and zero or more "prerequisite patches", which are well-known patches in flight that is not yet part of the "base commit" that need to be applied on top of "base commit" in topological order before the patches can be applied.
The "base commit" is shown as "
base-commit:
" followed by the 40-hex of the commit object name.
A "prerequisite patch" is shown as "prerequisite-patch-id:
" followed by the 40-hex "patch id", which can be obtained by passing the patch through the "git patch-id --stable
" command.
Git 2.23 (Q3 2019) will improve that, because the "--base
" option of "format-patch
" computed the patch-ids
for prerequisite patches in an unstable way, which has been updated to compute in a way that is compatible with "git patch-id --stable
".
See commit a8f6855, commit 6f93d26 (26 Apr 2019) by Stephen Boyd (akshayka
).
(Merged by Junio C Hamano -- gitster
-- in commit 8202d12, 13 Jun 2019)
format-patch
: make--base patch-id
output stable
We weren't flushing the context each time we processed a hunk in the
patch-id
generation code indiff.c
, but we were doing that when we generated "stable" patch-ids with the 'patch-id
' tool.Let's port that similar logic over from
patch-id.c
intodiff.c
so we can get the same hash when we're generating patch-ids for 'format-patch --base=
' types of command invocations.
Before Git 2.24 (Q4 2019), "git format-patch -o <outdir>
" did an equivalent of "mkdir <outdir>
" not "mkdir -p <outdir>
", which is being corrected.
See commit edefc31 (11 Oct 2019) by Bert Wesarg (bertwesarg
).
(Merged by Junio C Hamano -- gitster
-- in commit f1afbb0, 18 Oct 2019)
format-patch
: create leading components of output directorySigned-off-by: Bert Wesarg
'git format-patch -o ' did an equivalent of '
mkdir <outdir>
' not 'mkdir -p <outdir>
', which is being corrected.
Avoid the usage of '
adjust_shared_perm
' on the leading directories which may have security implications. Achieved by temporarily disabling of 'config.sharedRepository
' like 'git init
' does.
With Git 2.25 (Q1 2020), "git rebase
" did not work well when format.useAutoBase
configuration variable is set, which has been corrected.
See commit cae0bc0, commit 945dc55, commit 700e006, commit a749d01, commit 0c47e06 (04 Dec 2019) by Denton Liu (Denton-L
).
(Merged by Junio C Hamano -- gitster
-- in commit 71a7de7, 16 Dec 2019)
rebase
: fixformat.useAutoBase
breakageReported-by: Christian Biesinger
Signed-off-by: Denton LiuWith
format.useAutoBase = true
, running rebase resulted in an error:fatal: failed to get upstream, if you want to record base commit automatically, please use git branch --set-upstream-to to track a remote branch. Or you could specify base commit by --base=<base-commit-id> manually error: git encountered an error while preparing the patches to replay these revisions: ede2467cdedc63784887b587a61c36b7850ebfac..d8f581194799ae29bf5fa72a98cbae98a1198b12 As a result, git cannot rebase them.
Fix this by always passing
--no-base
to format-patch from rebase so that the effect offormat.useAutoBase
is negated.
With Git 2.29 (Q4 2020), "git format-patch
"(man) learns to take "whenAble
" as a possible value for the format.useAutoBase
configuration variable to become no-op when the automatically computed base does not make sense.
See commit 7efba5f (01 Oct 2020) by Jacob Keller (jacob-keller
).
(Merged by Junio C Hamano -- gitster
-- in commit 5f8c70a, 05 Oct 2020)
format-patch
: teachformat.useAutoBase
"whenAble
" optionSigned-off-by: Jacob Keller
The
format.useAutoBase
configuration option exists to allow users to enable '--base=auto
' for format-patch by default.This can sometimes lead to poor workflow, due to unexpected failures when attempting to format an ancient patch:
$ git format-patch -1 <an old commit> fatal: base commit shouldn't be in revision list
This can be very confusing, as it is not necessarily immediately obvious that the user requested a
--base
(since this was in the configuration, not on the command line).We do want
--base=auto
to fail when it cannot provide a suitable base, as it would be equally confusing if a formatted patch did not include the base information when it was requested.Teach
format.useAutoBase
a new mode, "whenAble
".This mode will cause format-patch to attempt to include a base commit when it can. However, if no valid base commit can be found, then format-patch will continue formatting the patch without a base commit.
In order to avoid making yet another branch name unusable with
--base
, do not teach--base=whenAble
or--base=whenable
.Instead, refactor the
base_commit
option to use a callback, and rely on the global configuration variableauto_base
.This does mean that a user cannot request this optional base commit generation from the command line. However, this is likely not too valuable. If the user requests base information manually, they will be immediately informed of the failure to acquire a suitable base commit. This allows the user to make an informed choice about whether to continue the format.
Add tests to cover the new mode of operation for
--base
.
git config
now includes in its man page:
format-patch
by default.
Can also be set to "whenAble
" to allow enabling--base=auto
if a suitable base is available, but to skip adding base info otherwise without the format dying.
With Git 2.30 (Q1 2021), "git format-patch --output=there
"(man) did not work as expected and instead crashed.
The option is now supported.
See commit dc1672d, commit 1e1693b, commit 4c6f781 (04 Nov 2020) by Jeff King (peff
).
(Merged by Junio C Hamano -- gitster
-- in commit 5edc8bd, 18 Nov 2020)
format-patch
: support --output optionReported-by: Johannes Postler
Signed-off-by: Jeff King
We've never intended to support diff's
--output
option in format-patch. And until baa4adc66a (parse-options: disable option abbreviation withPARSE_OPT_KEEP_UNKNOWN,
2019-01-27, Git v2.22.0-rc0), it was impossible to trigger. We first parse the format-patch options before handing the remainder off tosetup_revisions()
.
Before that commit, we'd accept "--output=foo
" as an abbreviation for "--output-directory=foo". But afterwards, we don't check abbreviations, and --output gets passed to the diff code.This results in nonsense behavior and bugs. The diff code will have opened a filehandle at rev.diffopt.file, but we'll overwrite that with our own handles that we open for each individual patch file. So the --output file will always just be empty. But worse, the diff code also sets rev.diffopt.close_file, so
log_tree_commit()
will close the filehandle itself. And then the main loop incmd_format_patch()
will try to close it again, resulting in a double-free.The simplest solution would be to just disallow --output with format-patch, as nobody ever intended it to work. However, we have accidentally documented it (because format-patch includes diff-options). And it does work with "
git log
"(man) , which writes the whole output to the specified file. It's easy enough to make that work for format-patch, too: it's really the same as --stdout, but pointed at a specific file.We can detect the use of the --output option by the
"close_file"
flag (note that we can't use rev.diffopt.file, since the diff setup will otherwise set it to stdout). So we just need to unset that flag, but don't have to do anything else. Our situation is otherwise exactly like --stdout (note that we don't fclose() the file, but nor does the stdout case; exiting the program takes care of that for us).
for MS excel 2000 office version, click on the pivot table you will find a tab above the ribon, called Pivottable tool - click on that You can change data source from Data tab
You might need to set permissions at the database level that allows your schema owner to restore the dump.
You can use like this(Though the random number generator logic is not upto the mark)
public class WorkSheet {
HashMap<String,ArrayList<Integer>> map = new HashMap<String,ArrayList<Integer>>();
public static void main(String args[]) {
WorkSheet test = new WorkSheet();
test.inputData("mango", 5);
test.inputData("apple", 2);
test.inputData("grapes", 2);
test.inputData("peach", 3);
test.displayData();
}
public void displayData(){
for (Entry<String, ArrayList<Integer>> entry : map.entrySet()) {
System.out.print(entry.getKey()+" | ");
for(int fruitNo : entry.getValue()){
System.out.print(fruitNo+" ");
}
System.out.println();
}
}
public void inputData(String name ,int number) {
Random rndData = new Random();
ArrayList<Integer> fruit = new ArrayList<Integer>();
for(int i=0 ; i<number ; i++){
fruit.add(rndData.nextInt(10));
}
map.put(name, fruit);
}
}
grapes | 7 5
apple | 9 5
peach | 5 5 8
mango | 4 7 1 5 5
you can
float Lasttime;
public float Sec = 3f;
public int Num;
void Start(){
ExampleStart();
}
public void ExampleStart(){
Lasttime = Time.time;
}
void Update{
if(Time.time - Lasttime > sec){
// if(Num == step){
// Yourcode
//You Can Change Sec with => sec = YOURTIME(Float)
// Num++;
// ExampleStart();
}
if(Num == 0){
TextUI.text = "Welcome to Number Wizard!";
Num++;
ExampleStart();
}
if(Num == 1){
TextUI.text = ("The highest number you can pick is " + max);
Num++;
ExampleStart();
}
if(Num == 2){
TextUI.text = ("The lowest number you can pick is " + min);
Num++;
ExampleStart();
}
}
}
Khaled Developer
Easy For Gaming
The hint is, the output file is created even if you get this error. The automatic deconstruction of vector starts after your code executed. Elements in the vector are deconstructed as well. This is most probably where the error occurs. The way you access the vector is through vector::operator[]
with an index read from stream. Try vector::at()
instead of vector::operator[]
. This won't solve your problem, but will show which assignment to the vector causes error.
SELECT COALESCE(prereq, '') FROM test
Coalesce will return the first non-null argument passed to it from left to right. If all arguemnts are null, it'll return null, but we're forcing an empty string there, so no null values will be returned.
Also note that the COALESCE operator is supported in standard SQL. This is not the case of IFNULL. So it is a good practice to get use the former. Additionally, bear in mind that COALESCE supports more than 2 parameters and it will iterate over them until a non-null coincidence is found.
One possible solution is using nine patch image like this http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch
OR
I have done this in the following way. This is my main layout in which round_corner.xml and drop_shadow.xml used as background resource. round_corner_two is same like round_corner.xml only the color attribute is different. copy the round_corner.xml,drop_shadow.xml and round_conere_two.xml into drawable folder.
<RelativeLayout
android:id="@+id/facebook_id"
android:layout_width="250dp"
android:layout_height="52dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="28dp"
android:background="@drawable/round_corner" >
<LinearLayout
android:id="@+id/shadow_id"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_margin="1dp"
android:background="@drawable/drop_shadow" >
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginBottom="2dp"
android:background="@drawable/round_corner_two"
android:gravity="center"
android:text="@string/fb_butn_text"
android:textColor="@color/white" >
</TextView>
</LinearLayout>
</RelativeLayout>
round_corner.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!-- view background color -->
<solid
android:color="#ffffff" >
</solid>
<!-- view border color and width -->
<stroke
android:width="0dp"
android:color="#3b5998" >
</stroke>
<!-- If you want to add some padding -->
<padding
android:left="1dp"
android:top="1dp"
android:right="1dp"
android:bottom="1dp" >
</padding>
<!-- Here is the corner radius -->
<corners
android:radius="10dp" >
</corners>
</shape>
drop_shadow.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item >
<shape
android:shape="rectangle">
<solid android:color="@android:color/darker_gray" />
<corners android:radius="12dp"/>
</shape>
</item>
<item android:right="1dp" android:left="1dp" android:bottom="5dp">
<shape
android:shape="rectangle">
<solid android:color="@android:color/white"/>
<corners android:radius="5dp"/>
</shape>
</item>
</layer-list>
Obj-C way =):
NSString *inStr = [@(month) stringValue];
GCC supports #pragma once
since 3.4, see http://en.wikipedia.org/wiki/Pragma_once for further compiler support.
The big upside I see on using #pragma once
as opposed to include guards is to avoid copy/paste errors.
Let's face it: most of us hardly start a new header file from scratch, but rather just copy an existing one and modify it to our needs. It is much easier to create a working template using #pragma once
instead of include guards. The less I have to modify the template, the less I am likely to run into errors. Having the same include guard in different files leads to strange compiler errors and it takes some time to figure out what went wrong.
TL;DR: #pragma once
is easier to use.
As it says, it is ambiguous. Your array comparison returns a boolean array. Methods any() and all() reduce values over the array (either logical_or or logical_and). Moreover, you probably don't want to check for equality. You should replace your condition with:
np.allclose(A.dot(eig_vec[:,col]), eig_val[col] * eig_vec[:,col])
It's not built in, but if you want unusual length numbers then you could use the bitstring module.
>>> from bitstring import Bits
>>> a = Bits(bin='111111111111')
>>> a.int
-1
The same object can equivalently be created in several ways, including
>>> b = Bits(int=-1, length=12)
It just behaves like a string of bits of arbitrary length, and uses properties to get different interpretations:
>>> print a.int, a.uint, a.bin, a.hex, a.oct
-1 4095 111111111111 fff 7777
The $.getJSON()
method is shorthand that does not let you specify advanced options like that. To do that, you need to use the full $.ajax()
method.
Notice in the documentation at http://api.jquery.com/jQuery.getJSON/:
This is a shorthand Ajax function, which is equivalent to:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
So just use $.ajax()
and provide all the extra parameters you need.
You could make use of the Javascript DOM API. In particular, look at the createElement() method.
You could create a re-usable function that will create an image like so...
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
// This next line will just add it to the <body> tag
document.body.appendChild(img);
}
Then you could use it like this...
<button onclick=
"show_image('http://google.com/images/logo.gif',
276,
110,
'Google Logo');">Add Google Logo</button>
You should do this using jQuery.ajaxStart
and jQuery.ajaxStop
.
jQuery.ajaxStart
jQuery.ajaxStop
<div id="loading" style="display:none">Your Image</div>
<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script>
$(function () {
var loading = $("#loading");
$(document).ajaxStart(function () {
loading.show();
});
$(document).ajaxStop(function () {
loading.hide();
});
$("#startAjaxRequest").click(function () {
$.ajax({
url: "http://www.google.com",
// ...
});
});
});
</script>
<button id="startAjaxRequest">Start</button>
echo Yii::$app->request->url;
Logical OR :- returns true if at least one of the operands evaluate to true. Both operands are evaluated before apply the OR operator.
Short Circuit OR :- if left hand side operand returns true, it returns true without evaluating the right hand side operand.
Use a wild card selector *
for this purpose.
#div * { /* Narrowing, to specific elements, like input, textarea is PREFFERED */
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
Now, every element inside a div with id div
will have no selection.
As of AngularJS 1.2 there's a directive called ng-repeat-start
that does exactly what you ask for. See my answer in this question for a description of how to use it.
if you are using .bind(this), try this:
let index = Array.from(evt.target.parentElement.children).indexOf(evt.target);
$(this.pagination).find("a").on('click', function(evt) {
let index = Array.from(evt.target.parentElement.children).indexOf(evt.target);
this.goTo(index);
}.bind(this))
If it's conciseness you're after, you might like:
prop.table(table(tips$smoker))
and then scale by 100 and round if you like. Or more like your exact output:
tbl <- table(tips$smoker)
cbind(tbl,prop.table(tbl))
If you wanted to do this for multiple columns, there are lots of different directions you could go depending on what your tastes tell you is clean looking output, but here's one option:
tblFun <- function(x){
tbl <- table(x)
res <- cbind(tbl,round(prop.table(tbl)*100,2))
colnames(res) <- c('Count','Percentage')
res
}
do.call(rbind,lapply(tips[3:6],tblFun))
Count Percentage
Female 87 35.66
Male 157 64.34
No 151 61.89
Yes 93 38.11
Fri 19 7.79
Sat 87 35.66
Sun 76 31.15
Thur 62 25.41
Dinner 176 72.13
Lunch 68 27.87
If you don't like stack the different tables on top of each other, you can ditch the do.call
and leave them in a list.
IMO the nicest way is to use the next()
function:
router.get('/', function(req, res, next) {
var err = new Error('Not found');
err.status = 404;
return next(err);
}
Then the error is handled by your error handler and you can style the error nicely using HTML.
tableView?.allowsSelection = true
It's False by default in Xcode 11.7
You need to save your PHP script file in UTF-8 encoding, and leave the <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
in the HTML.
For text editor, I recommend Notepad++, because it can detect and display the actual encoding of the file (in the lower right corner of the editor), and you can convert it as well.
Keep the labels from your original file like this:
df = read.table('data.txt', header = T)
If you have columns named x and y, you can address them like this:
df$x
df$y
If you'd like to actually delete the first row from a data.frame, you can use negative indices like this:
df = df[-1,]
If you'd like to delete a column from a data.frame, you can assign NULL to it:
df$x = NULL
Here are some simple examples of how to create and manipulate a data.frame in R:
# create a data.frame with 10 rows
> x = rnorm(10)
> y = runif(10)
> df = data.frame( x, y )
# write it to a file
> write.table( df, 'test.txt', row.names = F, quote = F )
# read a data.frame from a file:
> read.table( df, 'test.txt', header = T )
> df$x
[1] -0.95343778 -0.63098637 -1.30646529 1.38906143 0.51703237 -0.02246754
[7] 0.20583548 0.21530721 0.69087460 2.30610998
> df$y
[1] 0.66658148 0.15355851 0.60098886 0.14284576 0.20408723 0.58271061
[7] 0.05170994 0.83627336 0.76713317 0.95052671
> df$x = x
> df
y x
1 0.66658148 -0.95343778
2 0.15355851 -0.63098637
3 0.60098886 -1.30646529
4 0.14284576 1.38906143
5 0.20408723 0.51703237
6 0.58271061 -0.02246754
7 0.05170994 0.20583548
8 0.83627336 0.21530721
9 0.76713317 0.69087460
10 0.95052671 2.30610998
> df[-1,]
y x
2 0.15355851 -0.63098637
3 0.60098886 -1.30646529
4 0.14284576 1.38906143
5 0.20408723 0.51703237
6 0.58271061 -0.02246754
7 0.05170994 0.20583548
8 0.83627336 0.21530721
9 0.76713317 0.69087460
10 0.95052671 2.30610998
> df$x = NULL
> df
y
1 0.66658148
2 0.15355851
3 0.60098886
4 0.14284576
5 0.20408723
6 0.58271061
7 0.05170994
8 0.83627336
9 0.76713317
10 0.95052671
Something I didn't see mentioned is PCMag Radio. That's a more consumer tech-oriented show, but they do geek out fairly often, and the chatter is always interesting.
Thanks to @Yiling. That was a hint.
<bean id="propertyConfigurer"
class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="searchSystemEnvironment" value="true" />
<property name="locations">
<list>
<value>file:#{systemEnvironment['FILE_PATH']}/first.properties</value>
<value>file:#{systemEnvironment['FILE_PATH']}/second.properties</value>
<value>file:#{systemEnvironment['FILE_PATH']}/third.properties</value>
</list>
</property>
</bean>
After this, you should have one environment variable named 'FILE_PATH'. Make sure you restart your terminal/IDE after creating that environment variable.
I adapted a script originally written by Narayana Vyas Kondreddi in 2002. I changed the where clause to check text/ntext fields as well, by using patindex rather than like. I also changed the results table slightly. Unreasonably, I changed variable names, and aligned as I prefer (no disrespect to Mr. Kondretti). The user may want to change the data types searched. I used a global table to allow querying mid-processing, but a permanent table might be a smarter way to go.
/* original script by Narayana Vyas Kondreddi, 2002 */
/* adapted by Oliver Holloway, 2009 */
/* these lines can be replaced by use of input parameter for a proc */
declare @search_string varchar(1000);
set @search_string = 'what.you.are.searching.for';
/* create results table */
create table ##string_locations (
table_name varchar(1000),
field_name varchar(1000),
field_value varchar(8000)
)
;
/* special settings */
set nocount on
;
/* declare variables */
declare
@table_name varchar(1000),
@field_name varchar(1000)
;
/* variable settings */
set @table_name = ''
;
set @search_string = QUOTENAME('%' + @search_string + '%','''')
;
/* for each table */
while @table_name is not null
begin
set @field_name = ''
set @table_name = (
select MIN(QUOTENAME(table_schema) + '.' + QUOTENAME(table_name))
from INFORMATION_SCHEMA.TABLES
where
table_type = 'BASE TABLE' and
QUOTENAME(table_schema) + '.' + QUOTENAME(table_name) > @table_name and
OBJECTPROPERTY(OBJECT_ID(QUOTENAME(table_schema) + '.' + QUOTENAME(table_name)), 'IsMSShipped') = 0
)
/* for each string-ish field */
while (@table_name is not null) and (@field_name is not null)
begin
set @field_name = (
select MIN(QUOTENAME(column_name))
from INFORMATION_SCHEMA.COLUMNS
where
table_schema = PARSENAME(@table_name, 2) and
table_name = PARSENAME(@table_name, 1) and
data_type in ('char', 'varchar', 'nchar', 'nvarchar', 'text', 'ntext') and
QUOTENAME(column_name) > @field_name
)
/* search that field for the string supplied */
if @field_name is not null
begin
insert into ##string_locations
exec(
'select ''' + @table_name + ''',''' + @field_name + ''',' + @field_name +
'from ' + @table_name + ' (nolock) ' +
'where patindex(' + @search_string + ',' + @field_name + ') > 0' /* patindex works with char & text */
)
end
;
end
;
end
;
/* return results */
select table_name, field_name, field_value from ##string_locations (nolock)
;
/* drop temp table */
--drop table ##string_locations
;
On Windows 2003, to call another script without waiting, I used this:
$commandString = "start /b c:\\php\\php.EXE C:\\Inetpub\\wwwroot\\mysite.com\\phpforktest.php --passmsg=$testmsg";
pclose(popen($commandString, 'r'));
This only works AFTER giving changing permissions on cmd.exe
- add Read and Execute for IUSR_YOURMACHINE
(I also set write to Deny).
sed
(and its ilk) are contained within several packages of Unix commands.
sed
, grep
etc. out of the box, though.-z
option unlike listed upper portsIf you don't want to install anything and your system ain't a Windows Server one, then you could use a scripting language (VBScript e.g.) for that. Below is a gross, off-the-cuff stab at it. Your command line would look like
cscript //NoLogo sed.vbs s/(oldpat)/(newpat)/ < inpfile.txt > outfile.txt
where oldpat and newpat are Microsoft vbscript regex patterns. Obviously I've only implemented the substitute command and assumed some things, but you could flesh it out to be smarter and understand more of the sed
command-line.
Dim pat, patparts, rxp, inp
pat = WScript.Arguments(0)
patparts = Split(pat,"/")
Set rxp = new RegExp
rxp.Global = True
rxp.Multiline = False
rxp.Pattern = patparts(1)
Do While Not WScript.StdIn.AtEndOfStream
inp = WScript.StdIn.ReadLine()
WScript.Echo rxp.Replace(inp, patparts(2))
Loop
You need to do something like this:
// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");
// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");
// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
// grab the "id" attribute
XmlAttribute idAttribute = aNode.Attributes["id"];
// check if that attribute even exists...
if (idAttribute != null)
{
// if yes - read its current value
string currentValue = idAttribute.Value;
// here, you can now decide what to do - for demo purposes,
// I just set the ID value to a fixed value if it was empty before
if (string.IsNullOrEmpty(currentValue))
{
idAttribute.Value = "515";
}
}
}
// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");
For url safe encode, like base64.urlsafe_b64encode(...)
in Python the code below, works to me for 100%
function base64UrlSafeEncode(string $input)
{
return str_replace(['+', '/'], ['-', '_'], base64_encode($input));
}
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
if (!$result) {
trigger_error('Invalid query: ' . $conn->error);
}
check the error with mysqli_error() function
probably your query has some faults.
The code:
$qrystr = "SELECT * FROM mytablename WHERE id= " . $rowid;
$qryresult = $this->connection->query($qrystr);
$result = $qryresult->fetchAll(PDO::FETCH_ASSOC);
unset($result[0]['id']); //Remove ID from array
$qrystr = " INSERT INTO mytablename";
$qrystr .= " ( " .implode(", ",array_keys($result[0])).") ";
$qrystr .= " VALUES ('".implode("', '",array_values($result[0])). "')";
$result = $this->connection->query($qrystr);
return $result;
Of course you should use PDO:bindparam and check your variables against attack, etc but gives the example
additional info
If you have a problem with handling NULL
values, you can use following codes so that imploding
names and values only for whose value is not NULL
.
foreach ($result[0] as $index => $value) {
if ($value === null) unset($result[0][$index]);
}
We created entity beans and used getter annotations. The problem we ran into is this: some entities have complex rules for some properties regarding when they can be updated. The solution was to have some business logic in each setter that determines whether or not the actual value changed and, if so, whether the change should be allowed. Of course, Hibernate can always set the properties, so we ended up with two groups of setters. Pretty ugly.
Reading previous posts, I also see that referencing the properties from inside the entity could lead to issues with collections not loading.
Bottom line, I would lean toward annotating the fields in the future.
The syntax error is just due to a missing alias for the subquery:
select COUNT(*) from
(
select m.Company_id
from Monitor as m
inner join Monitor_Request as mr on mr.Company_ID=m.Company_id
group by m.Company_id
having COUNT(m.Monitor_id)>=5) mySubQuery /* Alias */
Even better: use the inspect.isclass
function.
>>> import inspect
>>> class X(object):
... pass
...
>>> inspect.isclass(X)
True
>>> x = X()
>>> isinstance(x, X)
True
>>> y = 25
>>> isinstance(y, X)
False
try this
new Handler().postDelayed(
new Runnable(){
@Override
public void run() {
if (i == 1){
tabLayout.getTabAt(0).select();
} else if (i == 2){
tabLayout.getTabAt(1).select();
}
}
}, 100);
You could also do something like this :
function isPalindrome(str) {
var newStr = '';
for(var i = str.length - 1; i >=0; i--) {
newStr += str[i];
}
if(newStr == str) {
return true;
return newStr;
} else {
return false;
return newStr;
}
}
Those do both mean non-breaking space, yes.  
is another synonym, in hex.
leftclickben answer worked for me, but I wanted a path from a given node back up the tree to the root, and these seemed to be going the other way, down the tree. So, I had to flip some of the fields around and renamed for clarity, and this works for me, in case this is what anyone else wants too--
item | parent
-------------
1 | null
2 | 1
3 | 1
4 | 2
5 | 4
6 | 3
and
select t.item_id as item, @pv:=t.parent as parent
from (select * from item_tree order by item_id desc) t
join
(select @pv:=6)tmp
where t.item_id=@pv;
gives:
item | parent
-------------
6 | 3
3 | 1
1 | null
If the string is 1 character long, just take that character. If the string is not 1 character long, it cannot be parsed into a character.
I would suggest using absolute positioning within the element.
I've created this to help you visualize it a bit.
#parent {_x000D_
width:400px;_x000D_
height:400px;_x000D_
background-color:white;_x000D_
border:2px solid blue;_x000D_
position:relative;_x000D_
}_x000D_
#div1 {position:absolute;bottom:0;right:0;background:green;width:100px;height:100px;}_x000D_
#div2 {width:100px;height:100px;position:absolute;bottom:0;left:0;background:red;}_x000D_
#div3 {width:100px;height:100px;position:absolute;top:0;right:0;background:yellow;}_x000D_
#div4 {width:100px;height:100px;position:absolute;top:0;left:0;background:gray;}
_x000D_
<div id="parent">_x000D_
<div id="div1"></div>_x000D_
<div id="div2"></div>_x000D_
<div id="div3"></div>_x000D_
<div id="div4"></div>_x000D_
_x000D_
</div>
_x000D_
Try this:
(Get-ChildItem -Path c:\pstbak\*.* -Filter *.pst | ? {
$_.LastWriteTime -gt (Get-Date).AddDays(-3)
}).Count
Perhaps you can check it here for the LATEST version always
http://bootstrap-datepicker.readthedocs.org/en/latest/
$('.datepicker').datepicker({
format: 'mm/dd/yyyy',
startDate: '-3d'
})
or
$.fn.datepicker.defaults.format = "mm/dd/yyyy";
$('.datepicker').datepicker({
startDate: '-3d'
})
As you have noticed, xscale
and yscale
does not support a simple linear re-scaling (unfortunately). As an alternative to Hooked's answer, instead of messing with the data, you can trick the labels like so:
ticks = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x*scale))
ax.xaxis.set_major_formatter(ticks)
A complete example showing both x and y scaling:
import numpy as np
import pylab as plt
import matplotlib.ticker as ticker
# Generate data
x = np.linspace(0, 1e-9)
y = 1e3*np.sin(2*np.pi*x/1e-9) # one period, 1k amplitude
# setup figures
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
# plot two identical plots
ax1.plot(x, y)
ax2.plot(x, y)
# Change only ax2
scale_x = 1e-9
scale_y = 1e3
ticks_x = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_x))
ax2.xaxis.set_major_formatter(ticks_x)
ticks_y = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_y))
ax2.yaxis.set_major_formatter(ticks_y)
ax1.set_xlabel("meters")
ax1.set_ylabel('volt')
ax2.set_xlabel("nanometers")
ax2.set_ylabel('kilovolt')
plt.show()
And finally I have the credits for a picture:
Note that, if you have text.usetex: true
as I have, you may want to enclose the labels in $
, like so: '${0:g}$'
.
You can use some thing like this
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div ng-app="" ng-init="btn1=false" ng-init="btn2=false">_x000D_
<p>_x000D_
<input type="submit" ng-disabled="btn1||btn2" ng-click="btn1=true" ng-model="btn1" />_x000D_
</p>_x000D_
<p>_x000D_
<button ng-disabled="btn1||btn2" ng-model="btn2" ng-click="btn2=true">Click Me!</button>_x000D_
</p>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
folder = "ABC"
tries to run a command named folder
with arguments =
and "ABC"
. The format of command in bash is:
command arguments separated with space
while assignment is done with:
variable=something
[ -f $newfoldername/Primetime.eyetv]
, [
is a command (test
)
and -f
and $newfoldername/Primetime.eyetv]
are two arguments. It
expects a third argument (]
) which it can't find (arguments must be
separated with space) and thus will show error.[-f $newfoldername/Primetime.eyetv]
tries to run a command [-f
with argument $newfoldername/Primetime.eyetv]
Generally for cases like this, paste your code in shellcheck and see the feedback.
I got tired of manually checking for plugin updates so created a tool to do it for me: https://github.com/dpa99c/cordova-check-plugins
Install it globally:
$ npm install -g cordova-check-plugins
Then run from the root of your Cordova project. You can optionally update outdated plugins interactively or automatically, e.g.
$ cordova-check-plugins --update=auto
The parentheses are poorly placed.
You need to use:
doThrow(new Exception()).when(mockedObject).methodReturningVoid(...);
^
and NOT use:
doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));
^
This is explained in the documentation
Use ??
instead or {{ $usersType ?? '' }}
A different approach that I found ugly compared to the classic dict+append, but that works:
df = df.T
df[0] = ['1/1/2013', 'Smith','test',123]
df = df.T
df
Out[6]:
Date Name Action ID
0 1/1/2013 Smith test 123
For SpreadSheetGear users (a C# framework for interacting easier with spreadsheets) try this:
workbook.Worksheets[0].Cells["B1:B4"].HorizontalAlignment = HAlign.Center;
.
This will align all the cells in your sheet from B1 to B4 (column 2- row 1 through 4).
There is a library available through nuget for dealing with pretty much any well formed CSV (.net) - CsvHelper
Example to map to a class:
var csv = new CsvReader( textReader );
var records = csv.GetRecords<MyClass>();
Example to read individual fields:
var csv = new CsvReader( textReader );
while( csv.Read() )
{
var intField = csv.GetField<int>( 0 );
var stringField = csv.GetField<string>( 1 );
var boolField = csv.GetField<bool>( "HeaderName" );
}
Letting the client drive the file format:
,
is the standard field delimiter, "
is the standard value used to escape fields that contain a delimiter, quote, or line ending.
To use (for example) #
for fields and '
for escaping:
var csv = new CsvReader( textReader );
csv.Configuration.Delimiter = "#";
csv.Configuration.Quote = ''';
// read the file however meets your needs
For VB.lovers the VB.NET equivalent of Luke Quinane's code (thanks Luke!)
Imports System
Imports System.Net
Imports System.Runtime.InteropServices
Imports System.ComponentModel
Public Class NetworkConnection
Implements IDisposable
Private _networkName As String
Public Sub New(networkName As String, credentials As NetworkCredential)
_networkName = networkName
Dim netResource = New NetResource() With {
.Scope = ResourceScope.GlobalNetwork,
.ResourceType = ResourceType.Disk,
.DisplayType = ResourceDisplaytype.Share,
.RemoteName = networkName
}
Dim userName = If(String.IsNullOrEmpty(credentials.Domain), credentials.UserName, String.Format("{0}\{1}", credentials.Domain, credentials.UserName))
Dim result = WNetAddConnection2(NetResource, credentials.Password, userName, 0)
If result <> 0 Then
Throw New Win32Exception(result, "Error connecting to remote share")
End If
End Sub
Protected Overrides Sub Finalize()
Try
Dispose (False)
Finally
MyBase.Finalize()
End Try
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Dispose (True)
GC.SuppressFinalize (Me)
End Sub
Protected Overridable Sub Dispose(disposing As Boolean)
WNetCancelConnection2(_networkName, 0, True)
End Sub
<DllImport("mpr.dll")> _
Private Shared Function WNetAddConnection2(netResource As NetResource, password As String, username As String, flags As Integer) As Integer
End Function
<DllImport("mpr.dll")> _
Private Shared Function WNetCancelConnection2(name As String, flags As Integer, force As Boolean) As Integer
End Function
End Class
<StructLayout(LayoutKind.Sequential)> _
Public Class NetResource
Public Scope As ResourceScope
Public ResourceType As ResourceType
Public DisplayType As ResourceDisplaytype
Public Usage As Integer
Public LocalName As String
Public RemoteName As String
Public Comment As String
Public Provider As String
End Class
Public Enum ResourceScope As Integer
Connected = 1
GlobalNetwork
Remembered
Recent
Context
End Enum
Public Enum ResourceType As Integer
Any = 0
Disk = 1
Print = 2
Reserved = 8
End Enum
Public Enum ResourceDisplaytype As Integer
Generic = &H0
Domain = &H1
Server = &H2
Share = &H3
File = &H4
Group = &H5
Network = &H6
Root = &H7
Shareadmin = &H8
Directory = &H9
Tree = &HA
Ndscontainer = &HB
End Enum
It's definitely conceivable but I am not sure we're there yet. In the meantime, I'd recommend using something like Silverlight with IIS Smooth Streaming. Silverlight is plugin-based, but it works on Windows/OSX/Linux. Some day the HTML5 <video>
element will be the way to go, but that will lack support for a little while.
For me the problem turned out to be minHeight and minWidth on some of the Android themes.
On the Button element, add:
<Button android:minHeight="0dp" android:minWidth="0dp" ...
Or in your button's style:
<item name="android:minHeight">0dp</item>
<item name="android:minWidth">0dp</item>
Try this:
$(function() {
$("#location").change(function(){
var element = $(this).find('option:selected');
var myTag = element.attr("myTag");
$('#setMyTag').val(myTag);
});
});
.img-responsive {
margin: 0 auto;
}
you can write like above code in your document so no need to add one another class in image tag.
Association is generalized concept of relations. It includes both Composition and Aggregation.
Composition(mixture) is a way to wrap simple objects or data types into a single unit. Compositions are a critical building block of many basic data structures
Aggregation(collection) differs from ordinary composition in that it does not imply ownership. In composition, when the owning object is destroyed, so are the contained objects. In aggregation, this is not necessarily true.
Both denotes relationship between object and only differ in their strength.
Trick to remember the difference : has A -Aggregation and Own - cOmpositoin
Now let observe the following image
Analogy:
Composition: The following picture is image composition i.e. using individual images making one image.
Aggregation : collection of image in single location
For example, A university owns various departments, and each department has a number of professors. If the university closes, the departments will no longer exist, but the professors in those departments will continue to exist. Therefore, a University can be seen as a composition of departments, whereas departments have an aggregation of professors. In addition, a Professor could work in more than one department, but a department could not be part of more than one university.
The center of rectangle is the midpoint of the diagonal end points of rectangle.
Here the midpoint is ( (x1 + x2) / 2, (y1 + y2) / 2 )
.
That means:
xCenter = (x1 + x2) / 2
yCenter = (y1 + y2) / 2
Let me know your code.
This answer is specific to MAC users.
The default VIM available with MAC does not come with clipboard option enabled. You need that option to access the system clipboard.
To check if your vim has that option enabled use the below command
vim --version
In the result, you should have +clipboard
. If it is -clipboard
, then your VIM does NOT have the option to access the system clipboard.
You need to MAKE and install your VIM with the option you need. Following are the commands.
# Create the directories you need
$ sudo mkdir -p /opt/local/bin
# Download, compile, and install the latest Vim
$ cd ~
$ git clone https://github.com/vim/vim.git
$ cd vim
$ ./configure --prefix=/opt/local
$ make
$ sudo make install
# Add the binary to your path, ahead of /usr/bin
$ echo 'PATH=/opt/local/bin:$PATH' >> ~/.bash_profile
# Reload bash_profile so the changes take effect in this window
$ source ~/.bash_profile"
The above will install the latest VIM with the option +clipboard
enabled.
Now you need to set the system clipboard. Append the following line to ~/.vimrc
set clipboard=unnamed
Now you can yank text to system clipboard. Below steps explains how to yank.
press v
, this will switch you to VISUAL mode.Press y
, this will copy the selected text to clipboard.CMD + v
to paste.I use MACBook Pro with macOS Mojave and the above works in it.
If you have a Decimal or similar numeric type, you can use:
Math.Round(myNumber, 2)
EDIT: So, in your case, it would be:
Public Class Form1
Private Sub btncalc_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles btncalc.Click
txtA.Text = Math.Round((Val(txtD.Text) / Val(txtC.Text) * Val(txtF.Text) / Val(txtE.Text)), 2)
txtB.Text = Math.Round((Val(txtA.Text) * 1000 / Val(txtG.Text)), 2)
End Sub
End Class
The code that is written in the question has a bug in it
Your arraylist contains strings of " 1" " 3" " 4" " 9" and " 2" (note the spaces)
So IndexOf(4) will find nothing because 4 is an int, and even "tostring" would convert it to of "4" and not " 4", and nothing will get removed.
An arraylist is the correct way to go to do what you want.
The easiest way is to use the replace
method on the column. The arguments are a list of the things you want to replace (here ['ABC', 'AB']
) and what you want to replace them with (the string 'A'
in this case):
>>> df['BrandName'].replace(['ABC', 'AB'], 'A')
0 A
1 B
2 A
3 D
4 A
This creates a new Series of values so you need to assign this new column to the correct column name:
df['BrandName'] = df['BrandName'].replace(['ABC', 'AB'], 'A')
Any line starting with a "REM" is treated as a comment, nothing is executed including the redirection.
Also, the %date% variable may contain "/" characters which are treated as path separator characters, leading to the system being unable to create the desired log file.
You can continue to use getApplicationContext()
, but before use, you should add this flag: dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT)
, and the error will not show.
And don't forget to add permission:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
Additional tip for ASP NET CORE:
Interface:
public interface IViewRenderer
{
Task<string> RenderAsync<TModel>(Controller controller, string name, TModel model);
}
Implementation:
public class ViewRenderer : IViewRenderer
{
private readonly IRazorViewEngine viewEngine;
public ViewRenderer(IRazorViewEngine viewEngine) => this.viewEngine = viewEngine;
public async Task<string> RenderAsync<TModel>(Controller controller, string name, TModel model)
{
ViewEngineResult viewEngineResult = this.viewEngine.FindView(controller.ControllerContext, name, false);
if (!viewEngineResult.Success)
{
throw new InvalidOperationException(string.Format("Could not find view: {0}", name));
}
IView view = viewEngineResult.View;
controller.ViewData.Model = model;
await using var writer = new StringWriter();
var viewContext = new ViewContext(
controller.ControllerContext,
view,
controller.ViewData,
controller.TempData,
writer,
new HtmlHelperOptions());
await view.RenderAsync(viewContext);
return writer.ToString();
}
}
Registration in Startup.cs
...
services.AddSingleton<IViewRenderer, ViewRenderer>();
...
And usage in controller:
public MyController: Controller
{
private readonly IViewRenderer renderer;
public MyController(IViewRendere renderer) => this.renderer = renderer;
public async Task<IActionResult> MyViewTest
{
var view = await this.renderer.RenderAsync(this, "MyView", model);
return new OkObjectResult(view);
}
}
fun TextView.addImage(atText: String, @DrawableRes imgSrc: Int, imgWidth: Int, imgHeight: Int) {
val ssb = SpannableStringBuilder(this.text)
val drawable = ContextCompat.getDrawable(this.context, imgSrc) ?: return
drawable.mutate()
drawable.setBounds(0, 0,
imgWidth,
imgHeight)
val start = text.indexOf(atText)
ssb.setSpan(VerticalImageSpan(drawable), start, start + atText.length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
this.setText(ssb, TextView.BufferType.SPANNABLE)
}
VerticalImageSpan
class from great answer
https://stackoverflow.com/a/38788432/5381331
Using
val textView = findViewById<TextView>(R.id.textview)
textView.setText("Send an [email-icon] to [email protected].")
textView.addImage("[email-icon]", R.drawable.ic_email,
resources.getDimensionPixelOffset(R.dimen.dp_30),
resources.getDimensionPixelOffset(R.dimen.dp_30))
Result
Note
Why VerticalImageSpan
class?
ImageSpan.ALIGN_CENTER
attribute requires API 29.
Also, after the test, I see that ImageSpan.ALIGN_CENTER
only work if the image smaller than the text, if the image bigger than the text then only image is in center, text not center, it align on bottom of image
If you're doing this to several fields, or doing it quite often, then perhaps a plugin is the answer.
Here's the beginnings of a jQuery plugin that formats the value of a field to two decimal places.
It is triggered by the onchange event of the field. You may want something different.
<script type="text/javascript">
// mini jQuery plugin that formats to two decimal places
(function($) {
$.fn.currencyFormat = function() {
this.each( function( i ) {
$(this).change( function( e ){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(2);
});
});
return this; //for chaining
}
})( jQuery );
// apply the currencyFormat behaviour to elements with 'currency' as their class
$( function() {
$('.currency').currencyFormat();
});
</script>
<input type="text" name="one" class="currency"><br>
<input type="text" name="two" class="currency">
As explained in the documentation, by using an @RequestParam
annotation:
public @ResponseBody String byParameter(@RequestParam("foo") String foo) {
return "Mapped by path + method + presence of query parameter! (MappingController) - foo = "
+ foo;
}
the correct syntax is -
with t1
as
(select * from tab1
where conditions...
),
t2
as
(select * from tab2
where conditions...
(you can access columns of t1 here as well)
)
select * from t1, t2
where t1.col1=t2.col2;
I used below function to compare two strings and It is working good.
function CompareUserId (first, second)
{
var regex = new RegExp('^' + first+ '$', 'i');
if (regex.test(second))
{
return true;
}
else
{
return false;
}
return false;
}
For Sublime Text users.
Set following properly in you Setting-User configuration.
"trim_trailing_white_space_on_save": true
As @Agam said,
You need this statement in your driver file:
from AthleteList import AtheleteList
If this happens in visual studio then clean your project and run it again.
Build --> Clean Solution
Run (or F5)
curl is an extension that needs to be installed, it's got nothing to do with the PHP version.
I agree with Icarus (would have commented if I could), but instead of using a CustomObject class, I would use a Dictionary (in case Facebook adds something).
private class MyFacebookClass
{
public IList<IDictionary<string, string>> data { get; set; }
}
or
private class MyFacebookClass
{
public IList<IDictionary<string, object>> data { get; set; }
}
There are only two options:
Find out by reading all rows (and then you might as well store them)
run a specialized SELECT COUNT(*) query beforehand.
Going twice through the DataReader loop is really expensive, you would have to re-execute the query.
And (thanks to Pete OHanlon) the second option is only concurrency-safe when you use a transaction with a Snapshot isolation level.
Since you want to end up storing all rows in memory anyway the only sensible option is to read all rows in a flexible storage (List<>
or DataTable
) and then copy the data to any format you want. The in-memory operation will always be much more efficient.
you write the command on terminal/cmd adb install FileName.apk.
Try: Console.WriteLine
(type out
for a Visual Studio snippet)
Console.WriteLine(stuff);
Another way is to use System.Diagnostics.Debug.WriteLine
:
System.Diagnostics.Debug.WriteLine(stuff);
Debug.WriteLine
may suit better for Output window in IDE because it will be rendered for both Console and Windows applications. Whereas Console.WriteLine
won't be rendered in Output window but only in the Console itself in case of Console Application type.
Another difference is that Debug.WriteLine
will not print anything in Release configuration.
Just type in the following command: taskkill /f /im (program name) To find out the im of your program open task manager and look at the process while your program is running. After the program has run a process will disappear from the task manager; that is your program.
Here is a trick that some may find useful:
For Select queries (only), you can create Views, especially where you find yourself running the same select queries over and over e.g. in production support scenarios.
The main advantages of creating Views are:
You can create a view easily by simply clicking the "Create view" link at the bottom of the results table display.
The easiest way to create an object in JavaScript is to use the following syntax :
var test = {_x000D_
a : 5,_x000D_
b : 10,_x000D_
f : function(c) {_x000D_
return this.a + this.b + c;_x000D_
}_x000D_
}_x000D_
_x000D_
console.log(test);_x000D_
console.log(test.f(3));
_x000D_
This works great for storing data in a structured way.
For more complex use cases, however, it's often better to create instances of functions :
function Test(a, b) {_x000D_
this.a = a;_x000D_
this.b = b;_x000D_
this.f = function(c) {_x000D_
return this.a + this.b + c;_x000D_
};_x000D_
}_x000D_
_x000D_
var test = new Test(5, 10);_x000D_
console.log(test);_x000D_
console.log(test.f(3));
_x000D_
This allows you to create multiple objects that share the same "blueprint", similar to how you use classes in eg. Java.
This can still be done more efficiently, however, by using a prototype.
Whenever different instances of a function share the same methods or properties, you can move them to that object's prototype. That way, every instance of a function has access to that method or property, but it doesn't need to be duplicated for every instance.
In our case, it makes sense to move the method f
to the prototype :
function Test(a, b) {_x000D_
this.a = a;_x000D_
this.b = b;_x000D_
}_x000D_
_x000D_
Test.prototype.f = function(c) {_x000D_
return this.a + this.b + c;_x000D_
};_x000D_
_x000D_
var test = new Test(5, 10);_x000D_
console.log(test);_x000D_
console.log(test.f(3));
_x000D_
A simple but effective way to do inheritance in JavaScript, is to use the following two-liner :
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
That is similar to doing this :
B.prototype = new A();
The main difference between both is that the constructor of A
is not run when using Object.create
, which is more intuitive and more similar to class based inheritance.
You can always choose to optionally run the constructor of A
when creating a new instance of B
by adding adding it to the constructor of B
:
function B(arg1, arg2) {
A(arg1, arg2); // This is optional
}
If you want to pass all arguments of B
to A
, you can also use Function.prototype.apply()
:
function B() {
A.apply(this, arguments); // This is optional
}
If you want to mixin another object into the constructor chain of B
, you can combine Object.create
with Object.assign
:
B.prototype = Object.assign(Object.create(A.prototype), mixin.prototype);
B.prototype.constructor = B;
function A(name) {_x000D_
this.name = name;_x000D_
}_x000D_
_x000D_
A.prototype = Object.create(Object.prototype);_x000D_
A.prototype.constructor = A;_x000D_
_x000D_
function B() {_x000D_
A.apply(this, arguments);_x000D_
this.street = "Downing Street 10";_x000D_
}_x000D_
_x000D_
B.prototype = Object.create(A.prototype);_x000D_
B.prototype.constructor = B;_x000D_
_x000D_
function mixin() {_x000D_
_x000D_
}_x000D_
_x000D_
mixin.prototype = Object.create(Object.prototype);_x000D_
mixin.prototype.constructor = mixin;_x000D_
_x000D_
mixin.prototype.getProperties = function() {_x000D_
return {_x000D_
name: this.name,_x000D_
address: this.street,_x000D_
year: this.year_x000D_
};_x000D_
};_x000D_
_x000D_
function C() {_x000D_
B.apply(this, arguments);_x000D_
this.year = "2018"_x000D_
}_x000D_
_x000D_
C.prototype = Object.assign(Object.create(B.prototype), mixin.prototype);_x000D_
C.prototype.constructor = C;_x000D_
_x000D_
var instance = new C("Frank");_x000D_
console.log(instance);_x000D_
console.log(instance.getProperties());
_x000D_
Object.create
can be safely used in every modern browser, including IE9+. Object.assign
does not work in any version of IE nor some mobile browsers. It is recommended to polyfill Object.create
and/or Object.assign
if you want to use them and support browsers that do not implement them.
You can find a polyfill for Object.create
here
and one for Object.assign
here.
Maybe you can think about removing the attribute to a function. I mean something like this:
var obj = {_x000D_
key1: "it ",_x000D_
key2: function() {_x000D_
return this.key1 + " works!";_x000D_
}_x000D_
};_x000D_
_x000D_
alert(obj.key2());
_x000D_
You can use the decompose method in bs4:
soup = bs4.BeautifulSoup('<body><a href="http://example.com/">I linked to <i>example.com</i></a></body>')
for a in soup.find('a').children:
if isinstance(a,bs4.element.Tag):
a.decompose()
print soup
Out: <html><body><a href="http://example.com/">I linked to </a></body></html>
As per the Django Project Skeleton, the proper directory structure that could be followed is :
[projectname]/ <- project root
+-- [projectname]/ <- Django root
¦ +-- __init__.py
¦ +-- settings/
¦ ¦ +-- common.py
¦ ¦ +-- development.py
¦ ¦ +-- i18n.py
¦ ¦ +-- __init__.py
¦ ¦ +-- production.py
¦ +-- urls.py
¦ +-- wsgi.py
+-- apps/
¦ +-- __init__.py
+-- configs/
¦ +-- apache2_vhost.sample
¦ +-- README
+-- doc/
¦ +-- Makefile
¦ +-- source/
¦ +-- *snap*
+-- manage.py
+-- README.rst
+-- run/
¦ +-- media/
¦ ¦ +-- README
¦ +-- README
¦ +-- static/
¦ +-- README
+-- static/
¦ +-- README
+-- templates/
+-- base.html
+-- core
¦ +-- login.html
+-- README
Refer https://django-project-skeleton.readthedocs.io/en/latest/structure.html for the latest directory structure.
All those who can't install perldoc, or other modules, and want to know what modules are available (CPAN or otherwise), the following works for linux and Mingw32/64:
grep -RhIP '^package [A-Z][\w:]+;' `perl -e 'print join " ",@INC'` | sed 's/package //' | sort | uniq
Yes, it's messy. Yes, it probably reports more than you want. But if you pipe it into a file, you can easily check for, say, which dbm interfaces are present:
grep -RhIP '^package [A-Z][\w:]+;' `perl -e 'print join " ",@INC'` | sed 's/package //' | sort | uniq > modules-installed
cat modules-installed | grep -i dbm
AnyDBM_File;
Memoize::AnyDBM_File;
Memoize::NDBM_File;
Memoize::SDBM_File;
WWW::RobotRules::AnyDBM_File;
Which is why I ended up on this page (disappointed)
(I realise this doesn't answer the OP's question exactly, but I'm posting it for anybody who ended up here for the same reason I did. That's the problem with stack*** it's almost imposisble to find the question you're asking, even when it exists, yet stack*** is nearly always google's top hit!)
Instead of "w"
use "a"
(append) mode with open
function:
with open("games.txt", "a") as text_file:
\r
is the ASCII Carriage Return (CR) character.
There are different newline conventions used by different operating systems. The most common ones are:
\r\n
);\n
);\r
).The \n\r
(LF+CR) looks unconventional.
edit: My reading of the Telnet RFC suggests that:
The sequence "CR LF", as defined, will cause the NVT to be positioned at the left margin of the next print line (as would, for example, the sequence "LF CR").
Yes its possible to pass JSON object in URL
queryString = "{\"left\":\"" + params.get("left") + "}";
httpRestTemplate.exchange(
Endpoint + "/A/B?query={queryString}",
HttpMethod.GET, entity, z.class, queryString);
Assuming you can use integrated security, you can remove the user id and pass:
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True;"
I found code which converts the json string to NSDictionary or NSArray. Just add the extension.
SWIFT 3.0
HOW TO USE
let jsonData = (convertedJsonString as! String).parseJSONString
EXTENSION
extension String
{
var parseJSONString: AnyObject?
{
let data = self.data(using: String.Encoding.utf8, allowLossyConversion: false)
if let jsonData = data
{
// Will return an object or nil if JSON decoding fails
do
{
let message = try JSONSerialization.jsonObject(with: jsonData, options:.mutableContainers)
if let jsonResult = message as? NSMutableArray {
return jsonResult //Will return the json array output
} else if let jsonResult = message as? NSMutableDictionary {
return jsonResult //Will return the json dictionary output
} else {
return nil
}
}
catch let error as NSError
{
print("An error occurred: \(error)")
return nil
}
}
else
{
// Lossless conversion of the string was not possible
return nil
}
}
}
I strongly suspect that's because of the network connection or the web server you're talking to - it's not BufferedReader
's fault. Try measuring this:
InputStream stream = conn.getInputStream();
byte[] buffer = new byte[1000];
// Start timing
while (stream.read(buffer) > 0)
{
}
// End timing
I think you'll find it's almost exactly the same time as when you're parsing the text.
Note that you should also give InputStreamReader
an appropriate encoding - the platform default encoding is almost certainly not what you should be using.
git tag --sort=committerdate | tail -1
public void testDB() {
TextView tv = (TextView) this.findViewById(R.id.tv_data);
try {
Class.forName("com.mysql.jdbc.Driver");
// perfect
// localhost
/*
* Connection con = DriverManager .getConnection(
* "jdbc:mysql://192.168.1.5:3306/databasename?user=root&password=123"
* );
*/
// online testing
Connection con = DriverManager
.getConnection("jdbc:mysql://173.5.128.104:3306/vokyak_heyou?user=viowryk_hiweser&password=123");
String result = "Database connection success\n";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from tablename ");
ResultSetMetaData rsmd = rs.getMetaData();
while (rs.next()) {
result += rsmd.getColumnName(1) + ": " + rs.getString(1) + "\n";
}
tv.setText(result);
} catch (Exception e) {
e.printStackTrace();
tv.setText(e.toString());
}
}
Your tomcat-users.xml
looks good.
Make sure you have the manager/
application inside your $CATALINA_BASE/webapps/
You have to install tomcat-admin package: sudo apt-get install tomcat8-admin
(for version 8)
I am using Eclipse. I had to copy the manager/
folder from C:\Program Files\apache-tomcat-8.5.20\webapps
to my Eclipse workspace (~\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\webapps\
).
In case of Request to a REST Service:
You need to allow the CORS (cross origin sharing of resources) on the endpoint of your REST Service with Spring annotation:
@CrossOrigin(origins = "http://localhost:8080")
Very good tutorial: https://spring.io/guides/gs/rest-service-cors/
public void Empty(System.IO.DirectoryInfo directory)
{
try
{
logger.DebugFormat("Empty directory {0}", directory.FullName);
foreach (System.IO.FileInfo file in directory.GetFiles()) file.Delete();
foreach (System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
}
catch (Exception ex)
{
ex.Data.Add("directory", Convert.ToString(directory.FullName, CultureInfo.InvariantCulture));
throw new Exception(string.Format(CultureInfo.InvariantCulture,"Method:{0}", ex.TargetSite), ex);
}
}
I got this problem because it could not find the Android SDK path. I was missing a local.properties
file with it or an ANDROID_HOME
environment variable with it.
As an alternative to some of the answers suggested above, if you have powershell installed, you can invoke that directly as your terminal. That is edit the corresponding setting.json
value as follows:
"terminal.integrated.shell.windows": "C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
I find this works well as the environment is correctly configured.
I had the same issue. I just closed and reopened the terminal, and it worked. That was because I installed anaconda with the terminal open.
I just had this happen to a developer on the team I administer.
It turned out his developer certificate expired and after renewal, I neglected to add his certificate to the provisioning profile his app used.
That's because itoa
isn't a standard function. Try snprintf
instead.
char str[LEN];
snprintf(str, LEN, "%d", 42);
I think it has to do with your second element in storbinary
. You are trying to open file
, but it is already a pointer to the file you opened in line file = open(local_path,'rb')
. So, try to use ftp.storbinary("STOR " + i, file)
.
Right-Click on your project -> Properties -> Deployment Assembly.
On the Left-hand panel Click 'Add' and add the 'Project and External Dependencies'.
'Project and External Dependencies' will have all the spring related jars deployed along with your application
<script>
function validate() {
var phone=document.getElementById("phone").value;
if(isNaN(phone))
{
alert("please enter digits only");
}
else if(phone.length!=10)
{
alert("invalid mobile number");
}
else
{
confirm("hello your mobile number is" +" "+phone);
}
</script>
Please try the following code snippet,
IIF(Round(Avg(Fields!Vision_Score.Value)) = Avg(Fields!Vision_Score.Value),
Format(Avg(Fields!Vision_Score.Value)),
FORMAT(Avg(Fields!Vision_Score.Value),"##.##"))
hope it will help, Thank-you.
I think you can use db.collection.distinct(fields,query)
You will be able to get the distinct values in your case for NetworkID.
It should be something like this :
Db.collection.distinct('NetworkID')
Use empty
(it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:
styleClass="#{empty obj.validationErrorMap ? ' ' :
(obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"
If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:
styleClass="#{empty obj.validationErrorMap ? ' ' :
(obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"
Update: as per the comments, the Map
turns out to actually be a List
(please work on your naming conventions). To check if a List
contains an item the "normal" EL way, use JSTL fn:contains
(although not explicitly documented, it works for List
as well).
styleClass="#{empty obj.validationErrorMap ? ' ' :
(fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"
Even easier: via the requests module.
import requests
get_response = requests.get(url='http://google.com')
post_data = {'username':'joeb', 'password':'foobar'}
# POST some form-encoded data:
post_response = requests.post(url='http://httpbin.org/post', data=post_data)
To send data that is not form-encoded, send it serialised as a string (example taken from the documentation):
import json
post_response = requests.post(url='http://httpbin.org/post', data=json.dumps(post_data))
# If using requests v2.4.2 or later, pass the dict via the json parameter and it will be encoded directly:
post_response = requests.post(url='http://httpbin.org/post', json=post_data)
The above query will not work.
After the where
clause, if we can not CAST
the column value, then it will not work. You should cast
the column value.
e.g.:
SELECT.....
WHERE CAST( yourDateColumn AS DATE ) > DATEADD( DAY, -7, CAST( GETDATE() AS DATE )
public class HcfLcm {
public static void main(String[] args) {
System.out.println("HCF: "+ getHcf(20, 15)); //5
System.out.println("LCM: "+ getLcm2(20, 15)); //60
}
private static Integer getLcm2(int n1, int n2) {
int lcm = Math.max(n1, n2);
// Always true
while (true) {
if (lcm % n1 == 0 && lcm % n2 == 0) {
break;
}
++lcm;
}
return lcm;
}
private static Integer getLcm(int i, int j) {
int hcf = getHcf(i, j);
return hcf * i/hcf * j/hcf; // i*j*hcf
}
private static Integer getHcf(int i, int j) {
while(i%j != 0) {
int temp = i%j;
i = j;
j = temp;
}
return j;
}
}
According to phpbench:
Is it worth the effort to calculate the length of the loop in advance?
//pre-calculate the size of array
$size = count($x); //or $size = sizeOf($x);
for ($i=0; $i<$size; $i++) {
//...
}
//don't pre-calculate
for ($i=0; $i<count($x); $i++) { //or $i<sizeOf($x);
//...
}
A loop with 1000 keys with 1 byte values are given.
+---------+----------+
| count() | sizeof() |
+-----------------+---------+----------+
| With precalc | 152 | 212 |
| Without precalc | 70401 | 50644 |
+-----------------+---------+----------+ (time in µs)
So I personally prefer to use count() instead of sizeof() with pre calc.
Save your workbook. If this code doesn't do what you want, the only way to go back is to close without saving and reopen.
Select the data you want to list in one column. Must be contiguous columns. May contain blank cells.
Press Alt+F11 to open the VBE
Press Control+R to view the Project Explorer
Navigate to the project for your workbook and choose Insert - Module
Paste this code in the code pane
Sub MakeOneColumn()
Dim vaCells As Variant
Dim vOutput() As Variant
Dim i As Long, j As Long
Dim lRow As Long
If TypeName(Selection) = "Range" Then
If Selection.Count > 1 Then
If Selection.Count <= Selection.Parent.Rows.Count Then
vaCells = Selection.Value
ReDim vOutput(1 To UBound(vaCells, 1) * UBound(vaCells, 2), 1 To 1)
For j = LBound(vaCells, 2) To UBound(vaCells, 2)
For i = LBound(vaCells, 1) To UBound(vaCells, 1)
If Len(vaCells(i, j)) > 0 Then
lRow = lRow + 1
vOutput(lRow, 1) = vaCells(i, j)
End If
Next i
Next j
Selection.ClearContents
Selection.Cells(1).Resize(lRow).Value = vOutput
End If
End If
End If
End Sub
Press F5 to run the code
Read Google-gson
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.
Add the following line to your MODULE LEVEL build.gradle
configuration:
dependencies {
implementation 'com.google.code.gson:gson:2.8.5' // Old 2.8.2
}
You can try this:
input[type='text'] {
background-image: url(images/comment-author.gif);
background-position: 7px 7px;
background-repeat: no-repeat;
}
I usually use the second one of these:
from matplotlib.pyplot import cm
import numpy as np
#variable n below should be number of curves to plot
#version 1:
color=cm.rainbow(np.linspace(0,1,n))
for i,c in zip(range(n),color):
plt.plot(x, y,c=c)
#or version 2:
color=iter(cm.rainbow(np.linspace(0,1,n)))
for i in range(n):
c=next(color)
plt.plot(x, y,c=c)
Example of 2:
If you want to create one and specific table. You can use this code. It works for laravel(5.x) versions.
php artisan migrate:refresh --path=/database/migrations/fileName.php
$(window).height();
$(window).width();
More info
Using jQuery is not essential for getting those values, however. Use
document.documentElement.clientHeight;
document.documentElement.clientWidth;
to get sizes excluding scrollbars, or
window.innerHeight;
window.innerWidth;
to get the whole viewport, including scrollbars.
document.documentElement.clientHeight <= window.innerHeight; // is always true
It seems to depend on the details of the version of od
. On OSX, use this:
od -t x1 -An file |tr -d '\n '
(That's print as type hex bytes, with no address. And whitespace deleted afterwards, of course.)
Java 8 added a new way of making Comparators that reduces the amount of code you have to write, Comparator.comparing. Also check out Comparator.reversed
Here's a sample
import org.junit.Test;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import static org.junit.Assert.assertTrue;
public class ComparatorTest {
@Test
public void test() {
List<Person> peopleList = new ArrayList<>();
peopleList.add(new Person("A", 1000));
peopleList.add(new Person("B", 1));
peopleList.add(new Person("C", 50));
peopleList.add(new Person("Z", 500));
//sort by name, ascending
peopleList.sort(Comparator.comparing(Person::getName));
assertTrue(peopleList.get(0).getName().equals("A"));
assertTrue(peopleList.get(peopleList.size() - 1).getName().equals("Z"));
//sort by name, descending
peopleList.sort(Comparator.comparing(Person::getName).reversed());
assertTrue(peopleList.get(0).getName().equals("Z"));
assertTrue(peopleList.get(peopleList.size() - 1).getName().equals("A"));
//sort by age, ascending
peopleList.sort(Comparator.comparing(Person::getAge));
assertTrue(peopleList.get(0).getAge() == 1);
assertTrue(peopleList.get(peopleList.size() - 1).getAge() == 1000);
//sort by age, descending
peopleList.sort(Comparator.comparing(Person::getAge).reversed());
assertTrue(peopleList.get(0).getAge() == 1000);
assertTrue(peopleList.get(peopleList.size() - 1).getAge() == 1);
}
class Person {
String name;
int age;
Person(String n, int a) {
name = n;
age = a;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
}
In addition to what the other replies said, if you have to parse very large files with hundreds of thousands of timestamps, date_parser
can prove to be a huge performance bottleneck, as it's a Python function called once per row. You can get a sizeable performance improvements by instead keeping the dates as text while parsing the CSV file and then converting the entire column into dates in one go:
# For a data column
df = pd.read_csv(infile, parse_dates={'mydatetime': ['date', 'time']})
df['mydatetime'] = pd.to_datetime(df['mydatetime'], exact=True, cache=True, format='%Y-%m-%d %H:%M:%S')
# For a DateTimeIndex
df = pd.read_csv(infile, parse_dates={'mydatetime': ['date', 'time']}, index_col='mydatetime')
df.index = pd.to_datetime(df.index, exact=True, cache=True, format='%Y-%m-%d %H:%M:%S')
# For a MultiIndex
df = pd.read_csv(infile, parse_dates={'mydatetime': ['date', 'time']}, index_col=['mydatetime', 'num'])
idx_mydatetime = df.index.get_level_values(0)
idx_num = df.index.get_level_values(1)
idx_mydatetime = pd.to_datetime(idx_mydatetime, exact=True, cache=True, format='%Y-%m-%d %H:%M:%S')
df.index = pd.MultiIndex.from_arrays([idx_mydatetime, idx_num])
For my use case on a file with 200k rows (one timestamp per row), that cut down processing time from about a minute to less than a second.
The formula for French Excel:
=CONCATENER(
DECHEX(ALEA.ENTRE.BORNES(0;4294967295);8);"-";
DECHEX(ALEA.ENTRE.BORNES(0;42949);4);"-";
DECHEX(ALEA.ENTRE.BORNES(0;42949);4);"-";
DECHEX(ALEA.ENTRE.BORNES(0;42949);4);"-";
DECHEX(ALEA.ENTRE.BORNES(0;4294967295);8);
DECHEX(ALEA.ENTRE.BORNES(0;42949);4))
As noted by Josh M, this does not provide a compliant GUID however, but this works well for my current need.
INSERT INTO Table2 SELECT DISTINCT ID,Data = STUFF((SELECT ', ' + AA.Data FROM Table1 AS AA WHERE AA.ID = BB.ID FOR XML PATH(''), TYPE).value('.','nvarchar(max)'), 1, 2, '') FROM Table1 AS BB
GROUP BY ID,Data
ORDER BY ID;
<?php
$myArray = new array('1', '2');
$seralizedArray = serialize($myArray);
?>
the module.exports property or the exports object allows a module to select what should be shared with the application
I have a video on module_export available here
For some time, the following should work:
Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true;
Try this:
while True:
# main program
while True:
answer = str(input('Run again? (y/n): '))
if answer in ('y', 'n'):
break
print("invalid input.")
if answer == 'y':
continue
else:
print("Goodbye")
break
The inner while loop loops until the input is either 'y'
or 'n'
. If the input is 'y'
, the while loop starts again (continue
keyword skips the remaining code and goes straight to the next iteration). If the input is 'n'
, the program ends.
You can create a a method and pass paramters to it and get the json as a response.
private JSONObject jsonResult(String Name,int id, String curriculum) throws JSONException {
JSONObject json = null;
json = new JSONObject("{\"" + "Name" + "\":" + "\"" + Name+ "\""
+ "," + "\"" + "Id" + "\":" + id + "," + "\"" + "Curriculum"
+ "\":" + "\"" + curriculum+ "\"" + "}");
return json;
}
I hope this will help you.
As an alternate you can use reactive forms. Here is an example: https://stackblitz.com/edit/angular-pqb2xx
Template
<form [formGroup]="mainForm" ng-submit="submitForm()">
Global Price: <input type="number" formControlName="globalPrice">
<button type="button" [disabled]="mainForm.get('globalPrice').value === null" (click)="applyPriceToAll()">Apply to all</button>
<table border formArrayName="orderLines">
<ng-container *ngFor="let orderLine of orderLines let i=index" [formGroupName]="i">
<tr>
<td>{{orderLine.time | date}}</td>
<td>{{orderLine.quantity}}</td>
<td><input formControlName="price" type="number"></td>
</tr>
</ng-container>
</table>
</form>
Component
import { Component } from '@angular/core';
import { FormGroup, FormControl, FormArray } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular 6';
mainForm: FormGroup;
orderLines = [
{price: 10, time: new Date(), quantity: 2},
{price: 20, time: new Date(), quantity: 3},
{price: 30, time: new Date(), quantity: 3},
{price: 40, time: new Date(), quantity: 5}
]
constructor() {
this.mainForm = this.getForm();
}
getForm(): FormGroup {
return new FormGroup({
globalPrice: new FormControl(),
orderLines: new FormArray(this.orderLines.map(this.getFormGroupForLine))
})
}
getFormGroupForLine(orderLine: any): FormGroup {
return new FormGroup({
price: new FormControl(orderLine.price)
})
}
applyPriceToAll() {
const formLines = this.mainForm.get('orderLines') as FormArray;
const globalPrice = this.mainForm.get('globalPrice').value;
formLines.controls.forEach(control => control.get('price').setValue(globalPrice));
// optionally recheck value and validity without emit event.
}
submitForm() {
}
}
You are reading the file right but the problem seems to be with the default encoding of System.out
. Try this to print the UTF-8
string-
PrintStream out = new PrintStream(System.out, true, "UTF-8");
out.println(str);
You need the Microsoft.AspNet.WebApi.Core package.
You can see it in the .csproj file:
<Reference Include="System.Web.Http, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Microsoft.AspNet.WebApi.Core.5.0.0\lib\net45\System.Web.Http.dll</HintPath>
</Reference>
If you are on windows and using mingw, gcc uses the win32 runtime, where printf needs %I64d
for a 64 bit integer. (and %I64u
for an unsinged 64 bit integer)
For most other platforms you'd use %lld
for printing a long long. (and %llu
if it's unsigned). This is standarized in C99.
gcc doesn't come with a full C runtime, it defers to the platform it's running on - so the general case is that you need to consult the documentation for your particular platform - independent of gcc.
In Swift 5:
extension Int{
func expo(_ power: Int) -> Int {
var result = 1
var powerNum = power
var tempExpo = self
while (powerNum != 0){
if (powerNum%2 == 1){
result *= tempExpo
}
powerNum /= 2
tempExpo *= tempExpo
}
return result
}
}
Use like this
2.expo(5) // pow(2, 5)
Thanks to @Paul Buis's answer.
Instead of creating the PowerPoint presentation in a MemoryStream write it directly to the Response.OutputStream
. This way you don't need to be wasting any memory on the sever as the component will be directly streaming the output to the network socket stream. So instead of passing a MemoryStream to the function that is generating this presentation simply pass the Response.OutputStream.
To take an export to your local system from sql developer.
Path : C:\Source_Table_Extract\des_loan_due_dtls_src_boaf.csv
SPOOL "Path where you want to save the file"
SELECT /*csv*/ * FROM TABLE_NAME;
I didn't find any of the previous solutions to be adequate enough due to bad performance, so I made my own that uses simple math instead of looping. Should work fine in all browsers as well.
According to this performance test case it is much faster then the other solutions found here.
(function($) {
$.fn.textfill = function(maxFontSize) {
maxFontSize = parseInt(maxFontSize, 10);
return this.each(function(){
var ourText = $("span", this),
parent = ourText.parent(),
maxHeight = parent.height(),
maxWidth = parent.width(),
fontSize = parseInt(ourText.css("fontSize"), 10),
multiplier = maxWidth/ourText.width(),
newSize = (fontSize*(multiplier-0.1));
ourText.css(
"fontSize",
(maxFontSize > 0 && newSize > maxFontSize) ?
maxFontSize :
newSize
);
});
};
})(jQuery);
If you want to contribute I've added this to Gist.
The term you should be googling is "authoritative," not "definitive".
On Linux or Mac you can use the commands whois
, dig
, host
, nslookup
or several others. nslookup
might also work on Windows.
An example:
$ whois stackoverflow.com
[...]
Domain servers in listed order:
NS51.DOMAINCONTROL.COM
NS52.DOMAINCONTROL.COM
As for the extra credit: Yes, it is possible.
aryeh is definitely wrong, as his suggestion usually will only give you the IP address for the hostname. If you use dig
, you have to look for NS records, like so:
dig ns stackoverflow.com
Keep in mind that this may ask your local DNS server and thus may give wrong or out-of-date answers that it has in its cache.
Chris answer is working for me...
My values-v11/styles.xml file:
<resources>
<style name="LightThemeSelector" parent="android:Theme.Holo.Light.DarkActionBar">
<item name="android:actionBarStyle">@style/ActionBar</item>
<item name="android:editTextBackground">@drawable/edit_text_holo_light</item>
<item name="android:actionMenuTextAppearance">@style/MyActionBar.MenuTextStyle</item>
</style>
<!--sets the point size to the menu item(s) in the upper right of action bar-->
<style name="MyActionBar.MenuTextStyle" parent="android:style/TextAppearance.Holo.Widget.ActionBar.Title">
<item name="android:textSize">25sp</item>
</style>
<!-- sets the background of the actionbar to a PNG file in my drawable folder.
displayOptions unset allow me to NOT SHOW the application icon and application name in the upper left of the action bar-->
<style name="ActionBar" parent="@android:style/Widget.Holo.ActionBar">
<item name="android:background">@drawable/actionbar_background</item>
<item name="android:displayOptions"></item>
</style>
<style name="inputfield" parent="android:Theme.Holo.Light">
<item name="android:textColor">@color/red2</item>
</style>
</resources>
just a point,
numbers = [int(x) for x in numbers]
the list comprehension is more natural, while
numbers = map(int, numbers)
is faster.
Probably this will not matter in most cases
Useful read: LP vs map
I finally found out how to do this! Basically you need to run adb shell
first and then while you're in the shell run su
, which will switch the shell to run as root!
$: adb shell
$: su
The one problem I still have is that sqlite3 is not installed so the command is not recognized.
You can do it with plain JavaScript:
alert('123-4-'.substr(0, 4)); // outputs "123-"
This returns the first four characters of your string (adjust 4
to suit your needs).
Found Promise.prototype.catch()
examples on MDN below very helpful.
(The accepted answer mentions then(null, onErrorHandler)
which is basically the same as catch(onErrorHandler)
.)
Using and chaining the catch method
var p1 = new Promise(function(resolve, reject) { resolve('Success'); }); p1.then(function(value) { console.log(value); // "Success!" throw 'oh, no!'; }).catch(function(e) { console.log(e); // "oh, no!" }).then(function(){ console.log('after a catch the chain is restored'); }, function () { console.log('Not fired due to the catch'); }); // The following behaves the same as above p1.then(function(value) { console.log(value); // "Success!" return Promise.reject('oh, no!'); }).catch(function(e) { console.log(e); // "oh, no!" }).then(function(){ console.log('after a catch the chain is restored'); }, function () { console.log('Not fired due to the catch'); });
Gotchas when throwing errors
// Throwing an error will call the catch method most of the time var p1 = new Promise(function(resolve, reject) { throw 'Uh-oh!'; }); p1.catch(function(e) { console.log(e); // "Uh-oh!" }); // Errors thrown inside asynchronous functions will act like uncaught errors var p2 = new Promise(function(resolve, reject) { setTimeout(function() { throw 'Uncaught Exception!'; }, 1000); }); p2.catch(function(e) { console.log(e); // This is never called }); // Errors thrown after resolve is called will be silenced var p3 = new Promise(function(resolve, reject) { resolve(); throw 'Silenced Exception!'; }); p3.catch(function(e) { console.log(e); // This is never called });
If it is resolved
//Create a promise which would not call onReject var p1 = Promise.resolve("calling next"); var p2 = p1.catch(function (reason) { //This is never called console.log("catch p1!"); console.log(reason); }); p2.then(function (value) { console.log("next promise's onFulfilled"); /* next promise's onFulfilled */ console.log(value); /* calling next */ }, function (reason) { console.log("next promise's onRejected"); console.log(reason); });
Is there any disadvantages/consequences of pushing empty commits?
Aside from the extreme confusion someone might get as to why there's a bunch of commits with no content in them on master, not really.
You can change the commit that you pushed to remote, but the sha1 of the commit (basically it's id number) will change permanently, which alters the source tree -- You'd then have to do a git push -f
back to remote.
You need to do two things:
The code:
dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))
library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha = 0.35, linetype=0)+
geom_line(aes(linetype=model), size = 1) +
geom_point(aes(shape=model), size=4) +
theme(legend.position=c(.6,0.8)) +
theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
scale_linetype_discrete("Model 1") +
scale_shape_discrete("Model 1") +
scale_colour_discrete("Model 1")
However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha=0.2, colour=NA)+
geom_line() +
geom_point() +
facet_wrap(~model)
Try running below command (Works on both windows and linux)
isql -v
byte[] b = IOUtils.toByteArray((new URL( )).openStream()); //idiom
Note however, that stream is not closed in the above example.
if you want a (76-character) chunk (using commons codec)...
byte[] b = Base64.encodeBase64(IOUtils.toByteArray((new URL( )).openStream()), true);
@RequestMapping
has a String[]
value parameter, so you should be able to specify multiple values like this:
@RequestMapping(value={"", "/", "welcome"})
The standard requires the array length to be a value that is computable at compile time so that the compiler is able to allocate enough space on the stack. In your case, you are trying to set the array length to a value that is unknown at compile time. Yes, i know that it seems obvious that it should be known to the compiler, but this is not the case here. The compiler cannot make any assumptions about the contents of non-constant variables. So go with:
const int row = 8;
const int col= 8;
int a[row][col];
UPD: some compilers will actually allow you to pull this off. IIRC, g++ has this feature. However, never use it because your code will become un-portable across compilers.
See this. Your code would be something like the following:
from django.db.models import Max
# Generates a "SELECT MAX..." query
Argument.objects.aggregate(Max('rating')) # {'rating__max': 5}
You can also use this on existing querysets:
from django.db.models import Max
args = Argument.objects.filter(name='foo') # or whatever arbitrary queryset
args.aggregate(Max('rating')) # {'rating__max': 5}
If you need the model instance that contains this max value, then the code you posted is probably the best way to do it:
arg = args.order_by('-rating')[0]
Note that this will error if the queryset is empty, i.e. if no arguments match the query (because the [0]
part will raise an IndexError
). If you want to avoid that behavior and instead simply return None
in that case, use .first()
:
arg = args.order_by('-rating').first() # may return None
I tried your code:
CheckedListBox cb = new CheckedListBox();
for (var i = 1; i < 11; i++)
cb.Items.Add("Item " + i, i % 3 == 0);
string fmt = RHelper.FormatQuery(cb);
Console.WriteLine(fmt);
Console.ReadLine();
It threw an exception at this line:
foreach (DataRowView item in chekedListBox.CheckedItems)
// Unable to cast object of type 'System.String' to type 'System.Data.DataRowView'.
Maybe you are also facing the same kind of problem. Instead of casting to DataRowView, try making the following changes:
foreach (var item in chekedListBox.CheckedItems)
{
ID = ID + item.ToString(); // item["" + FieldName + ""];
Because items in CheckedListBox are of object type.
I figured out below would work:
my_df.dropna().quantile([0.0, .9])
I find this to be the best way:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime())); // 2014/08/06 16:00:22
You're looking for the @content
directive:
@mixin placeholder {
::-webkit-input-placeholder {@content}
:-moz-placeholder {@content}
::-moz-placeholder {@content}
:-ms-input-placeholder {@content}
}
@include placeholder {
font-style:italic;
color: white;
font-weight:100;
}
SASS Reference has more information, which can be found here: http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#mixin-content
As of Sass 3.4, this mixin can be written like so to work both nested and unnested:
@mixin optional-at-root($sel) {
@at-root #{if(not &, $sel, selector-append(&, $sel))} {
@content;
}
}
@mixin placeholder {
@include optional-at-root('::-webkit-input-placeholder') {
@content;
}
@include optional-at-root(':-moz-placeholder') {
@content;
}
@include optional-at-root('::-moz-placeholder') {
@content;
}
@include optional-at-root(':-ms-input-placeholder') {
@content;
}
}
Usage:
.foo {
@include placeholder {
color: green;
}
}
@include placeholder {
color: red;
}
Output:
.foo::-webkit-input-placeholder {
color: green;
}
.foo:-moz-placeholder {
color: green;
}
.foo::-moz-placeholder {
color: green;
}
.foo:-ms-input-placeholder {
color: green;
}
::-webkit-input-placeholder {
color: red;
}
:-moz-placeholder {
color: red;
}
::-moz-placeholder {
color: red;
}
:-ms-input-placeholder {
color: red;
}